aboutsummaryrefslogtreecommitdiff
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2018 Oleg Pykhalov <go.wigust@gmail.com>
;;; Copyright © 2018 Clément Lassieur <clement@lassieur.org>
;;; Copyright © 2018 Christopher Baines <mail@cbaines.net>
;;; Copyright © 2019 Arun Isaac <arunisaac@systemreboot.net>
;;;
;;; This file is part of GNU Guix.
;;;
;;; GNU Guix is free software; you can redistribute it and/or modify it
;;; under the terms of the GNU General Public License as published by
;;; the Free Software Foundation; either version 3 of the License, or (at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with GNU Guix.  If not, see <http://www.gnu.org/licenses/>.

(define-module (gnu services cgit)
  #:use-module (gnu packages admin)
  #:use-module (gnu packages version-control)
  #:use-module (gnu services base)
  #:use-module (gnu services configuration)
  #:use-module (gnu services shepherd)
  #:use-module (gnu services web)
  #:use-module (gnu services)
  #:use-module (gnu system shadow)
  #:use-module (guix gexp)
  #:use-module (guix packages)
  #:use-module (guix records)
  #:use-module (guix store)
  #:use-module (ice-9 match)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-26)
  #:export (repository-cgit-configuration
            cgit-configuration
            %cgit-configuration-nginx
            cgit-configuration-nginx-config
            opaque-cgit-configuration
            serialize-cgit-configuration
            cgit-service-type))

;;; Commentary:
;;;
;;; This module provides a service definition for the Cgit a web frontend for
;;; Git repositories written in C.
;;;
;;; Note: fields of <cgit-configuration> and <repository-cgit-configuration>
;;; should be specified in the specific order.
;;;
;;; Code:

(define %cgit-configuration-nginx
  (nginx-server-configuration
   (root cgit)
   (locations
    (list
     (nginx-location-configuration
      (uri "@cgit")
      (body '("fastcgi_param SCRIPT_FILENAME $document_root/lib/cgit/cgit.cgi;"
              "fastcgi_param PATH_INFO $uri;"
              "fastcgi_param QUERY_STRING $args;"
              "fastcgi_param HTTP_HOST $server_name;"
              "fastcgi_pass 127.0.0.1:9000;")))))
   (try-files (list "$uri" "@cgit"))
   (listen '("80"))
   (ssl-certificate #f)
   (ssl-certificate-key #f)))


;;;
;;; Serialize <cgit-configuration>
;;;

(define (uglify-field-name field-name)
  (string-delete #\? (symbol->string field-name)))

(define (serialize-field field-name val)
  #~(format #f "~a=~a\n" #$(uglify-field-name field-name) #$val))

(define (serialize-string field-name val)
  (if (and (string? val) (string=? val ""))
      ""
      (serialize-field field-name val)))

(define (serialize-list field-name val)
  (if (null? val) "" (serialize-field field-name (string-join val))))

(define robots-list? list?)

(define (serialize-robots-list field-name val)
  (if (null? val) "" (serialize-field field-name (string-join val ", "))))

(define (integer? val)
  (exact-integer? val))

(define (serialize-integer field-name val)
  (serialize-field field-name (number->string val)))

(define (serialize-boolean field-name val)
  (serialize-integer field-name (if val 1 0)))

(define (serialize-repository-cgit-configuration x)
  (serialize-configuration x repository-cgit-configuration-fields))

(define (repository-cgit-configuration-list? val)
  (list? val))

(define (serialize-repository-cgit-configuration-list field-name val)
  #~(string-append
     #$@(map serialize-repository-cgit-configuration val)))

(define (file-object? val)
  (or (file-like? val) (string? val)))
(define (serialize-file-object field-name val)
  (serialize-string field-name val))

(define (project-list? val)
  (or (list? val)
      (file-object? val)))


;;;
;;; Serialize <nginx-server-configuration>
;;;

(define (nginx-server-configuration-list? val)
  (and (list? val) (and-map nginx-server-configuration? val)))

(define (serialize-nginx-server-configuration-list field-name val)
  "")


;;;
;;; Serialize <repository-cgit-configuration>
;;;

(define (serialize-repo-field field-name val)
  #~(format #f "repo.~a=~a\n" #$(uglify-field-name field-name) #$val))

(define (serialize-repo-list field-name val)
  (if (null? val) "" (serialize-repo-field field-name (string-join val))))

(define repo-boolean? boolean?)

(define (serialize-repo-integer field-name val)
  (serialize-repo-field field-name (number->string val)))

(define (serialize-repo-boolean field-name val)
  (serialize-repo-integer field-name (if val 1 0)))
(define-maybe repo-boolean)

(define repo-list? list?)

(define repo-string? string?)

(define (serialize-repo-string field-name val)
  (if (string=? val "") "" (serialize-repo-field field-name val)))

(define repo-file-object? file-object?)
(define serialize-repo-file-object serialize-repo-string)

(define module-link-path? list?)

(define (serialize-module-link-path field-name val)
  (if (null? val) ""
      (match val
        ((path text)
         (format #f "repo.module-link.~a=~a\n" path text)))))

(define (serialize-project-list _ val)
  (if (null? val) ""
      (serialize-field
       'project-list
       (if (file-object? val)
           val
           (plain-file "project-list" (string-join val "\n"))))))

(define (serialize-extra-options extra-options)
  (string-join extra-options "\n" 'suffix))

(define repository-directory? string?)

(define (serialize-repository-directory _ val)
  (if (string=? val "") "" (format #f "scan-path=~a\n" val)))

(define mimetype-alist? list?)

(define (serialize-mimetype-alist field-name val)
  (format #f "# Mimetypes\n~a"
          (string-join
           (map (match-lambda
                  ((extension mimetype)
                   (format #f "mimetype.~a=~a"
                           (symbol->string extension) mimetype)))
                val) "\n")))

(define-configuration repository-cgit-configuration
  (snapshots
   (repo-list '())
   "A mask of snapshot formats for this repo that cgit generates links for,
restricted by the global @code{snapshots} setting.")
  (source-filter
   (repo-file-object "")
   "Override the default @code{source-filter}.")
  (url
   (repo-string "")
   "The relative URL used to access the repository.")
  (about-filter
   (repo-file-object "")
   "Override the default @code{about-filter}.")
  (branch-sort
   (repo-string "")
   "Flag which, when set to @samp{age}, enables date ordering in the branch
ref list, and when set to @samp{name} enables ordering by branch name.")
  (clone-url
   (repo-list '())
   "A list of URLs which can be used to clone repo.")
  (commit-filter
   (repo-file-object "")
   "Override the default @code{commit-filter}.")
  (commit-sort
   (repo-string "")
   "Flag which, when set to @samp{date}, enables strict date ordering in the
commit log, and when set to @samp{topo} enables strict topological ordering.")
  (defbranch
   (repo-string "")
   "The name of the default branch for this repository.  If no such branch
exists in the repository, the first branch name (when sorted) is used as
default instead.  By default branch pointed to by HEAD, or \"master\" if there
is no suitable HEAD.")
  (desc
   (repo-string "")
   "The value to show as repository description.")
  (homepage
   (repo-string "")
   "The value to show as repository homepage.")
  (email-filter
   (repo-file-object "")
   "Override the default @code{email-filter}.")
  (enable-commit-graph?
   maybe-repo-boolean
   "A flag which can be used to disable the global setting
@code{enable-commit-graph?}.")
  (enable-log-filecount?
   maybe-repo-boolean
   "A flag which can be used to disable the global setting
@code{enable-log-filecount?}.")
  (enable-log-linecount?
   maybe-repo-boolean
   "A flag which can be used to disable the global setting
@code{enable-log-linecount?}.")
  (enable-remote-branches?
   maybe-repo-boolean
   "Flag which, when set to @code{#t}, will make cgit display remote
branches in the summary and refs views.")
  (enable-subject-links?
   maybe-repo-boolean
   "A flag which can be used to override the global setting
@code{enable-subject-links?}.")
  (enable-html-serving?
   maybe-repo-boolean
   "A flag which can be used to override the global setting
@code{enable-html-serving?}.")
  (hide?
   (repo-boolean #f)
   "Flag which, when set to @code{#t}, hides the repository from the
repository index.")
  (ignore?
   (repo-boolean #f)
   "Flag which, when set to @samp{#t}, ignores the repository.")
  (logo
   (repo-file-object "")
   "URL which specifies the source of an image which will be used as a
logo on this repo’s pages.")
  (logo-link
   (repo-string "")
   "URL loaded when clicking on the cgit logo image.")
  (owner-filter
   (repo-file-object "")
   "Override the default @code{owner-filter}.")
  (module-link
   (repo-string "")
   "Text which will be used as the formatstring for a hyperlink when a
submodule is printed in a directory listing.  The arguments for the
formatstring are the path and SHA1 of the submodule commit.")
  (module-link-path
   (module-link-path '())
   "Text which will be used as the formatstring for a hyperlink when a
submodule with the specified subdirectory path is printed in a directory
listing.")
  (max-stats
   (repo-string "")
   "Override the default maximum statistics period.")
  (name
   (repo-string "")
   "The value to show as repository name.")
  (owner
   (repo-string "")
   "A value used to identify the owner of the repository.")
  (path
   (repo-string "")
   "An absolute path to the repository directory.")
  (readme
   (repo-string "")
   "A path (relative to repo) which specifies a file to include verbatim
as the \"About\" page for this repo.")
  (section
   (repo-string "")
   "The name of the current repository section - all repositories defined
after this option will inherit the current section name.")
  (extra-options
   (repo-list '())
   "Extra options will be appended to cgitrc file."))

;; Generate a <cgit-configuration> record, which may include a list of
;; <repository-cgit-configuration>, <nginx-server-configuration>, <package>.
(define-configuration cgit-configuration
  (package
   (file-like cgit)
   "The CGIT package.")
  (nginx
   (nginx-server-configuration-list (list %cgit-configuration-nginx))
   "NGINX configuration.")
  (about-filter
   (file-object "")
   "Specifies a command which will be invoked to format the content of about
pages (both top-level and for each repository).")
  (agefile
   (string "")
   "Specifies a path, relative to each repository path, which can be used to
specify the date and time of the youngest commit in the repository.")
  (auth-filter
   (file-object "")
   "Specifies a command that will be invoked for authenticating repository
access.")
  (branch-sort
   (string "name")
   "Flag which, when set to @samp{age}, enables date ordering in the branch
ref list, and when set @samp{name} enables ordering by branch name.")
  (cache-root
   (string "/var/cache/cgit")
   "Path used to store the cgit cache entries.")
  (cache-static-ttl
   (integer -1)
   "Number which specifies the time-to-live, in minutes, for the cached
version of repository pages accessed with a fixed SHA1.")
  (cache-dynamic-ttl
   (integer 5)
   "Number which specifies the time-to-live, in minutes, for the cached
version of repository pages accessed without a fixed SHA1.")
  (cache-repo-ttl
   (integer 5)
   "Number which specifies the time-to-live, in minutes, for the cached
version of the repository summary page.")
  (cache-root-ttl
   (integer 5)
   "Number which specifies the time-to-live, in minutes, for the cached
version of the repository index page.")
  (cache-scanrc-ttl
   (integer 15)
   "Number which specifies the time-to-live, in minutes, for the result of
scanning a path for Git repositories.")
  (cache-about-ttl
   (integer 15)
   "Number which specifies the time-to-live, in minutes, for the cached
version of the repository about page.")
  (cache-snapshot-ttl
   (integer 5)
   "Number which specifies the time-to-live, in minutes, for the cached
version of snapshots.")
  (cache-size
   (integer 0)
   "The maximum number of entries in the cgit cache. When set to
@samp{0}, caching is disabled.")
  (case-sensitive-sort?
   (boolean #t)
   "Sort items in the repo list case sensitively.")
  (clone-prefix
   (list '())
   "List of common prefixes which, when combined with a repository URL,
generates valid clone URLs for the repository.")
  (clone-url
   (list '())
   "List of @code{clone-url} templates.")
  (commit-filter
   (file-object "")
   "Command which will be invoked to format commit messages.")
  (commit-sort
   (string "git log")
   "Flag which, when set to @samp{date}, enables strict date ordering in the
commit log, and when set to @samp{topo} enables strict topological
ordering.")
  (css
   (file-object "/share/cgit/cgit.css")
   "URL which specifies the css document to include in all cgit pages.")
  (email-filter
   (file-object "")
   "Specifies a command which will be invoked to format names and email
address of committers, authors, and taggers, as represented in various
places throughout the cgit interface.")
  (embedded?
   (boolean #f)
   "Flag which, when set to @samp{#t}, will make cgit generate a HTML
fragment suitable for embedding in other HTML pages.")
  (enable-commit-graph?
   (boolean #f)
   "Flag which, when set to @samp{#t}, will make cgit print an ASCII-art
commit history graph to the left of the commit messages in the
repository log page.")
  (enable-filter-overrides?
   (boolean #f)
   "Flag which, when set to @samp{#t}, allows all filter settings to be
overridden in repository-specific cgitrc files.")
  (enable-follow-links?
   (boolean #f)
   "Flag which, when set to @samp{#t}, allows users to follow a file in the
log view.")
  (enable-http-clone?
   (boolean #t)
   "If set to @samp{#t}, cgit will act as an dumb HTTP endpoint for Git
clones.")
  (enable-index-links?
   (boolean #f)
   "Flag which, when set to @samp{#t}, will make cgit generate extra links
\"summary\", \"commit\", \"tree\" for each repo in the repository index.")
  (enable-index-owner?
   (boolean #t)
   "Flag which, when set to @samp{#t}, will make cgit display the owner of
each repo in the repository index.")
  (enable-log-filecount?
   (boolean #f)
   "Flag which, when set to @samp{#t}, will make cgit print the number of
modified files for each commit on the repository log page.")
  (enable-log-linecount?
   (boolean #f)
   "Flag which, when set to @samp{#t}, will make cgit print the number of
added and removed lines for each commit on the repository log page.")
  (enable-remote-branches?
   (boolean #f)
   "Flag which, when set to @code{#t}, will make cgit display remote
branches in the summary and refs views.")
  (enable-subject-links?
   (boolean #f)
   "Flag which, when set to @code{1}, will make cgit use the subject of
the parent commit as link text when generating links to parent commits
in commit view.")
  (enable-html-serving?
   (boolean #f)
   "Flag which, when set to @samp{#t}, will make cgit use the subject of the
parent commit as link text when generating links to parent commits in
commit view.")
  (enable-tree-linenumbers?
   (boolean #t)
   "Flag which, when set to @samp{#t}, will make cgit generate linenumber
links for plaintext blobs printed in the tree view.")
  (enable-git-config?
   (boolean #f)
   "Flag which, when set to @samp{#f}, will allow cgit to use Git config to
set any repo specific settings.")
  (favicon
   (file-object "/favicon.ico")
   "URL used as link to a shortcut icon for cgit.")
  (footer
   (file-object "")
   "The content of the file specified with this option will be included
verbatim at the bottom of all pages (i.e. it replaces the standard
\"generated by...\" message).")
  (head-include
   (string "")
   "The content of the file specified with this option will be included
verbatim in the HTML HEAD section on all pages.")
  (header
   (string "")
   "The content of the file specified with this option will be included
verbatim at the top of all pages.")
  (include
   (file-object "")
   "Name of a configfile to include before the rest of the current config-
file is parsed.")
  (index-header
   (string "")
   "The content of the file specified with this option will be included
verbatim above the repository index.")
  (index-info
   (string "")
   "The content of the file specified with this option will be included
verbatim below the heading on the repository index page.")
  (local-time?
   (boolean #f)
   "Flag which, if set to @samp{#t}, makes cgit print commit and tag times
in the servers timezone.")
  (logo
   (file-object "/share/cgit/cgit.png")
   "URL which specifies the source of an image which will be used as a logo
on all cgit pages.")
  (logo-link
   (string "")
   "URL loaded when clicking on the cgit logo image.")
  (owner-filter
   (file-object "")
   "Command which will be invoked to format the Owner column of the main
page.")
  (max-atom-items
   (integer 10)
   "Number of items to display in atom feeds view.")
  (max-commit-count
   (integer 50)
   "Number of entries to list per page in \"log\" view.")
  (max-message-length
   (integer 80)
   "Number of commit message characters to display in \"log\" view.")
  (max-repo-count
   (integer 50)
   "Specifies the number of entries to list per page on the repository index
page.")
  (max-repodesc-length
   (integer 80)
   "Specifies the maximum number of repo description characters to display
on the repository index page.")
  (max-blob-size
   (integer 0)
   "Specifies the maximum size of a blob to display HTML for in KBytes.")
  (max-stats
   (string "")
   "Maximum statistics period.  Valid values are @samp{week},@samp{month},
@samp{quarter} and @samp{year}.")
  (mimetype
   (mimetype-alist '((gif "image/gif")
                     (html "text/html")
                     (jpg "image/jpeg")
                     (jpeg "image/jpeg")
                     (pdf "application/pdf")
                     (png "image/png")
                     (svg "image/svg+xml")))
   "Mimetype for the specified filename extension.")
  (mimetype-file
   (file-object "")
   "Specifies the file to use for automatic mimetype lookup.")
  (module-link
   (string "")
   "Text which will be used as the formatstring for a hyperlink when a
submodule is printed in a directory listing.")
  (nocache?
   (boolean #f)
   "If set to the value @samp{#t} caching will be disabled.")
  (noplainemail?
   (boolean #f)
   "If set to @samp{#t} showing full author email addresses will be
disabled.")
  (noheader?
   (boolean #f)
   "Flag which, when set to @samp{#t}, will make cgit omit the standard
header on all pages.")
  (project-list
   (project-list '())
   "A list of subdirectories inside of @code{repository-directory}, relative
to it, that should loaded as Git repositories.  An empty list means that all
subdirectories will be loaded.")
  (readme
   (file-object "")
   "Text which will be used as default @code{repository-cgit-configuration}
@code{readme}.")
  (remove-suffix?
   (boolean #f)
   "If set to @code{#t} and @code{repository-directory} is enabled, if any
repositories are found with a suffix of @code{.git}, this suffix will be
removed for the URL and name.")
  (renamelimit
   (integer -1)
   "Maximum number of files to consider when detecting renames.")
  (repository-sort
   (string "")
   "The way in which repositories in each section are sorted.")
  (robots
   (robots-list (list "noindex" "nofollow"))
   "Text used as content for the @code{robots} meta-tag.")
  (root-desc
   (string "a fast webinterface for the git dscm")
   "Text printed below the heading on the repository index page.")
  (root-readme
   (file-object "")
   "The content of the file specified with this option will be included
verbatim below the \"about\" link on the repository index page.")
  (root-title
   (string "")
   "Text printed as heading on the repository index page.")
  (scan-hidden-path
   (boolean #f)
   "If set to @samp{#t} and repository-directory is enabled,
repository-directory will recurse into directories whose name starts with a
period.  Otherwise, repository-directory will stay away from such directories,
considered as \"hidden\".  Note that this does not apply to the \".git\"
directory in non-bare repos.")
  (snapshots
   (list '())
   "Text which specifies the default set of snapshot formats that cgit
generates links for.")
  (repository-directory
   (repository-directory "/srv/git")
   "Name of the directory to scan for repositories (represents
@code{scan-path}).")
  (section
   (string "")
   "The name of the current repository section - all repositories defined
after this option will inherit the current section name.")
  (section-sort
   (string "")
   "Flag which, when set to @samp{1}, will sort the sections on the repository
listing by name.")
  (section-from-path
   (integer 0)
   "A number which, if defined prior to repository-directory, specifies how
many path elements from each repo path to use as a default section name.")
  (side-by-side-diffs?
   (boolean #f)
   "If set to @samp{#t} shows side-by-side diffs instead of unidiffs per
default.")
  (source-filter
   (file-object "")
   "Specifies a command which will be invoked to format plaintext blobs in the
tree view.")
  (summary-branches
   (integer 10)
   "Specifies the number of branches to display in the repository \"summary\"
view.")
  (summary-log
   (integer 10)
   "Specifies the number of log entries to display in the repository
\"summary\" view.")
  (summary-tags
   (integer 10)
   "Specifies the number of tags to display in the repository \"summary\"
view.")
  (strict-export
   (string "")
   "Filename which, if specified, needs to be present within the repository
for cgit to allow access to that repository.")
  (virtual-root
   (string "/")
   "URL which, if specified, will be used as root for all cgit links.")
  (repositories
   (repository-cgit-configuration-list '())
   "A list of @code{repository-cgit-configuration} records.")
  (extra-options
   (list '())
   "Extra options will be appended to cgitrc file."))

;; This distinguishes fields whose order matters, and makes sure further
;; changes won't inadvertently change the order.
(define (serialize-cgit-configuration config)
  (define (rest? field)
    (not (memq (configuration-field-name field)
               '(project-list
                 extra-options
                 repository-directory
                 repositories))))
  #~(string-append
     #$(let ((rest (filter rest? cgit-configuration-fields)))
         (serialize-configuration config rest))
     #$(serialize-project-list
        'project-list
        (cgit-configuration-project-list config))
     #$(serialize-extra-options
        (cgit-configuration-extra-options config))
     #$(serialize-repository-directory
        'repository-directory
        (cgit-configuration-repository-directory config))
     #$(serialize-repository-cgit-configuration-list
        'repositories
        (cgit-configuration-repositories config))))

(define-configuration opaque-cgit-configuration
  (cgit
   (file-like cgit)
   "The cgit package.")
  (cgitrc
   (string (configuration-missing-field 'opaque-cgit-configuration 'cgitrc))
   "The contents of the @code{cgitrc} to use.")
  (cache-root
   (string "/var/cache/cgit")
   "Path used to store the cgit cache entries.")
  (nginx
   (nginx-server-configuration-list (list %cgit-configuration-nginx))
   "NGINX configuration."))

(define (cgit-activation config)
  "Return the activation gexp for CONFIG."
  (let* ((opaque-config? (opaque-cgit-configuration? config))
         (config-str
          (if opaque-config?
              (opaque-cgit-configuration-cgitrc config)
              (serialize-cgit-configuration config))))
    #~(begin
        (use-modules (guix build utils))
        (mkdir-p #$(if opaque-config?
                       (opaque-cgit-configuration-cache-root config)
                       (cgit-configuration-cache-root config)))
        (copy-file #$(mixed-text-file "cgitrc" config-str)
                   "/etc/cgitrc"))))

(define (cgit-configuration-nginx-config config)
  (if (opaque-cgit-configuration? config)
      (opaque-cgit-configuration-nginx config)
      (cgit-configuration-nginx config)))

(define cgit-service-type
  (service-type
   (name 'cgit)
   (extensions
    (list (service-extension activation-service-type
                             cgit-activation)
          (service-extension nginx-service-type
                             cgit-configuration-nginx-config)

          ;; Make sure fcgiwrap is instantiated.
          (service-extension fcgiwrap-service-type
                             (const #t))))
   (default-value (cgit-configuration))
   (description
    "Run the cgit web interface, which allows users to browse Git
repositories.")))

(define (generate-cgit-documentation)
  (generate-documentation
   `((cgit-configuration
      ,cgit-configuration-fields
      (repositories repository-cgit-configuration))
     (repository-cgit-configuration
      ,repository-cgit-configuration-fields))
   'cgit-configuration))
ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; ;;; You should have received a copy of the GNU General Public License ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>. (define-module (gnu home services shells) #:use-module (gnu services configuration) #:autoload (gnu system shadow) (%default-bashrc %default-zprofile) #:use-module (gnu home services utils) #:use-module (gnu home services) #:use-module (gnu packages shells) #:use-module (gnu packages bash) #:use-module (guix gexp) #:use-module (guix packages) #:use-module (guix records) #:use-module (srfi srfi-1) #:use-module (srfi srfi-26) #:use-module (ice-9 match) #:export (home-shell-profile-service-type home-shell-profile-configuration home-bash-service-type home-bash-configuration home-bash-extension home-zsh-service-type home-zsh-configuration home-zsh-extension home-fish-service-type home-fish-configuration home-fish-extension home-inputrc-service-type home-inputrc-configuration)) ;;; Commentary: ;;; ;;; This module contains shell related services like Zsh. ;;; ;;; Code: ;;; ;;; Shell profile. ;;; (define path? string?) (define (serialize-path field-name val) val) (define-configuration home-shell-profile-configuration (profile (text-config '()) "\ @code{home-shell-profile} is instantiated automatically by @code{home-environment}, DO NOT create this service manually, it can only be extended. @code{profile} is a list of file-like objects, which will go to @file{~/.profile}. By default @file{~/.profile} contains the initialization code, which have to be evaluated by login shell to make home-environment's profile available to the user, but other commands can be added to the file if it is really necessary. In most cases shell's configuration files are preferred places for user's customizations. Extend home-shell-profile service only if you really know what you do.")) (define (add-shell-profile-file config) `((".profile" ,(mixed-text-file "shell-profile" "\ HOME_ENVIRONMENT=$HOME/.guix-home . $HOME_ENVIRONMENT/setup-environment $HOME_ENVIRONMENT/on-first-login\n" (serialize-configuration config (filter-configuration-fields home-shell-profile-configuration-fields '(profile))))))) (define (add-profile-extensions config extensions) (home-shell-profile-configuration (inherit config) (profile (append (home-shell-profile-configuration-profile config) extensions)))) (define home-shell-profile-service-type (service-type (name 'home-shell-profile) (extensions (list (service-extension home-files-service-type add-shell-profile-file))) (compose concatenate) (extend add-profile-extensions) (default-value (home-shell-profile-configuration)) (description "Create @file{~/.profile}, which is used for environment initialization of POSIX compliant login shells. This service type can be extended with a list of file-like objects."))) (define (serialize-boolean field-name val) "") (define (serialize-posix-env-vars field-name val) (environment-variable-shell-definitions val)) ;;; ;;; Zsh. ;;; (define-configuration home-zsh-configuration (package (package zsh) "The Zsh package to use.") (xdg-flavor? (boolean #t) "Place all the configs to @file{$XDG_CONFIG_HOME/zsh}. Makes @file{~/.zshenv} to set @env{ZDOTDIR} to @file{$XDG_CONFIG_HOME/zsh}. Shell startup process will continue with @file{$XDG_CONFIG_HOME/zsh/.zshenv}.") (environment-variables (alist '()) "Association list of environment variables to set for the Zsh session." (serializer serialize-posix-env-vars)) (zshenv (text-config '()) "List of file-like objects, which will be added to @file{.zshenv}. Used for setting user's shell environment variables. Must not contain commands assuming the presence of tty or producing output. Will be read always. Will be read before any other file in @env{ZDOTDIR}.") (zprofile (text-config '()) "List of file-like objects, which will be added to @file{.zprofile}. Used for executing user's commands at start of login shell (In most cases the shell started on tty just after login). Will be read before @file{.zlogin}.") (zshrc (text-config '()) "List of file-like objects, which will be added to @file{.zshrc}. Used for executing user's commands at start of interactive shell (The shell for interactive usage started by typing @code{zsh} or by terminal app or any other program).") (zlogin (text-config '()) "List of file-like objects, which will be added to @file{.zlogin}. Used for executing user's commands at the end of starting process of login shell.") (zlogout (text-config '()) "List of file-like objects, which will be added to @file{.zlogout}. Used for executing user's commands at the exit of login shell. It won't be read in some cases (if the shell terminates by exec'ing another process for example).")) (define (zsh-filter-fields field) (filter-configuration-fields home-zsh-configuration-fields (list field))) (define (zsh-serialize-field config field) (serialize-configuration config (zsh-filter-fields field))) (define* (zsh-field-not-empty? config field) (let ((file-name (symbol->string field)) (field-obj (car (zsh-filter-fields field)))) (not (null? ((configuration-field-getter field-obj) config))))) (define (zsh-file-zshenv config) (mixed-text-file "zshenv" (zsh-serialize-field config 'zshenv) (zsh-serialize-field config 'environment-variables) "[ -n \"$SSH_CLIENT\" ] && source /etc/profile")) (define (zsh-file-zprofile config) (mixed-text-file "zprofile" (plain-file-content %default-zprofile) "\ # It's only necessary if zsh is a login shell, otherwise profiles will # be already sourced by bash " (zsh-serialize-field config 'zprofile))) (define (zsh-file-by-field config field) (match field ('zshenv (zsh-file-zshenv config)) ('zprofile (zsh-file-zprofile config)) (e (mixed-text-file (symbol->string field) (zsh-serialize-field config field))))) (define (zsh-get-configuration-files config) `((".zprofile" ,(zsh-file-by-field config 'zprofile)) ;; Always non-empty (".zshenv" ,(zsh-file-by-field config 'zshenv)) ;; Always non-empty ,@(if (zsh-field-not-empty? config 'zshrc) `((".zshrc" ,(zsh-file-by-field config 'zshrc))) '()) ,@(if (zsh-field-not-empty? config 'zlogin) `((".zlogin" ,(zsh-file-by-field config 'zlogin))) '()) ,@(if (zsh-field-not-empty? config 'zlogout) `((".zlogout" ,(zsh-file-by-field config 'zlogout))) '()))) (define (add-zsh-dot-configuration config) (define zshenv-auxiliary-file (mixed-text-file "zshenv-auxiliary" "export ZDOTDIR=${XDG_CONFIG_HOME:-$HOME/.config}/zsh\n" "[[ -f $ZDOTDIR/.zshenv ]] && source $ZDOTDIR/.zshenv\n")) (if (home-zsh-configuration-xdg-flavor? config) `((".zshenv" ,zshenv-auxiliary-file)) (zsh-get-configuration-files config))) (define (add-zsh-xdg-configuration config) (if (home-zsh-configuration-xdg-flavor? config) (map (lambda (lst) (cons (string-append "zsh/" (car lst)) (cdr lst))) (zsh-get-configuration-files config)) '())) (define (add-zsh-packages config) (list (home-zsh-configuration-package config))) (define-configuration/no-serialization home-zsh-extension (environment-variables (alist '()) "Association list of environment variables to set.") (zshrc (text-config '()) "List of file-like objects.") (zshenv (text-config '()) "List of file-like objects.") (zprofile (text-config '()) "List of file-like objects.") (zlogin (text-config '()) "List of file-like objects.") (zlogout (text-config '()) "List of file-like objects.")) (define (home-zsh-extensions original-config extension-configs) (home-zsh-configuration (inherit original-config) (environment-variables (append (home-zsh-configuration-environment-variables original-config) (append-map home-zsh-extension-environment-variables extension-configs))) (zshrc (append (home-zsh-configuration-zshrc original-config) (append-map home-zsh-extension-zshrc extension-configs))) (zshenv (append (home-zsh-configuration-zshenv original-config) (append-map home-zsh-extension-zshenv extension-configs))) (zprofile (append (home-zsh-configuration-zprofile original-config) (append-map home-zsh-extension-zprofile extension-configs))) (zlogin (append (home-zsh-configuration-zlogin original-config) (append-map home-zsh-extension-zlogin extension-configs))) (zlogout (append (home-zsh-configuration-zlogout original-config) (append-map home-zsh-extension-zlogout extension-configs))))) (define home-zsh-service-type (service-type (name 'home-zsh) (extensions (list (service-extension home-files-service-type add-zsh-dot-configuration) (service-extension home-xdg-configuration-files-service-type add-zsh-xdg-configuration) (service-extension home-profile-service-type add-zsh-packages))) (compose identity) (extend home-zsh-extensions) (default-value (home-zsh-configuration)) (description "Install and configure Zsh."))) ;;; ;;; Bash. ;;; (define (bash-serialize-aliases field-name val) (with-shell-quotation-bindings #~(string-append #$@(map (match-lambda ((key . #f) "") ((key . #t) #~(string-append "alias " #$key "\n")) ((key . (? literal-string? value)) #~(string-append "alias " #$key "=" (shell-single-quote #$(literal-string-value value)) "\n")) ((key . value) #~(string-append "alias " #$key "=" (shell-double-quote #$value) "\n"))) val)))) (define-configuration home-bash-configuration (package (package bash) "The Bash package to use.") (guix-defaults? (boolean #t) "Add sane defaults like reading @file{/etc/bashrc} and coloring the output of @command{ls} to the top of the @file{.bashrc} file.") (environment-variables (alist '()) "Association list of environment variables to set for the Bash session. The rules for the @code{home-environment-variables-service-type} apply here (@pxref{Essential Home Services}). The contents of this field will be added after the contents of the @code{bash-profile} field." (serializer serialize-posix-env-vars)) (aliases (alist '()) "Association list of aliases to set for the Bash session. The aliases will be defined after the contents of the @code{bashrc} field has been put in the @file{.bashrc} file. The alias will automatically be quoted, so something line this: @lisp '((\"ls\" . \"ls -alF\")) @end lisp turns into @example alias ls=\"ls -alF\" @end example" (serializer bash-serialize-aliases)) (bash-profile (text-config '()) "List of file-like objects, which will be added to @file{.bash_profile}. Used for executing user's commands at start of login shell (In most cases the shell started on tty just after login). @file{.bash_login} won't be ever read, because @file{.bash_profile} always present.") (bashrc (text-config '()) "List of file-like objects, which will be added to @file{.bashrc}. Used for executing user's commands at start of interactive shell (The shell for interactive usage started by typing @code{bash} or by terminal app or any other program).") (bash-logout (text-config '()) "List of file-like objects, which will be added to @file{.bash_logout}. Used for executing user's commands at the exit of login shell. It won't be read in some cases (if the shell terminates by exec'ing another process for example).")) (define (add-bash-configuration config) (define (filter-fields field) (filter-configuration-fields home-bash-configuration-fields (list field))) (define (serialize-field field) (serialize-configuration config (filter-fields field))) (define* (file-if-not-empty field #:optional (extra-content #f)) (let ((file-name (symbol->string field)) (field-obj (car (filter-fields field)))) (if (or extra-content (not (null? ((configuration-field-getter field-obj) config)))) `(,(string-append "." (object->snake-case-string file-name)) ,(apply mixed-text-file (object->snake-case-string file-name) (append (or extra-content '()) (list (serialize-field field))))) '()))) (filter (compose not null?) `((".bash_profile" ,(mixed-text-file "bash_profile" "\ # Set up the system, user profile, and related variables. # /etc/profile will be sourced by bash automatically # Set up the home environment profile. if [ -f ~/.profile ]; then source ~/.profile; fi # Honor per-interactive-shell startup file if [ -f ~/.bashrc ]; then source ~/.bashrc; fi " (serialize-field 'bash-profile) (serialize-field 'environment-variables))) ,@(list (file-if-not-empty 'bashrc (if (home-bash-configuration-guix-defaults? config) (list (plain-file-content %default-bashrc) "\n" ;; The host distro might provide a bad 'PS1' ;; default--e.g., not taking $GUIX_ENVIRONMENT into ;; account. Provide a good default here when asked. "PS1='\\u@\\h \\w${GUIX_ENVIRONMENT:+ [env]}\\$ '\n" (serialize-field 'aliases)) (list (serialize-field 'aliases)))) (file-if-not-empty 'bash-logout))))) (define (add-bash-packages config) (list (home-bash-configuration-package config))) (define-configuration/no-serialization home-bash-extension (environment-variables (alist '()) "Additional environment variables to set. These will be combined with the environment variables from other extensions and the base service to form one coherent block of environment variables.") (aliases (alist '()) "Additional aliases to set. These will be combined with the aliases from other extensions and the base service.") (bash-profile (text-config '()) "Additional text blocks to add to @file{.bash_profile}, which will be combined with text blocks from other extensions and the base service.") (bashrc (text-config '()) "Additional text blocks to add to @file{.bashrc}, which will be combined with text blocks from other extensions and the base service.") (bash-logout (text-config '()) "Additional text blocks to add to @file{.bash_logout}, which will be combined with text blocks from other extensions and the base service.")) (define (home-bash-extensions original-config extension-configs) (match-record original-config <home-bash-configuration> (environment-variables aliases bash-profile bashrc bash-logout) (home-bash-configuration (inherit original-config) (environment-variables (append environment-variables (append-map home-bash-extension-environment-variables extension-configs))) (aliases (append aliases (append-map home-bash-extension-aliases extension-configs))) (bash-profile (append bash-profile (append-map home-bash-extension-bash-profile extension-configs))) (bashrc (append bashrc (append-map home-bash-extension-bashrc extension-configs))) (bash-logout (append bash-logout (append-map home-bash-extension-bash-logout extension-configs)))))) (define home-bash-service-type (service-type (name 'home-bash) (extensions (list (service-extension home-files-service-type add-bash-configuration) (service-extension home-profile-service-type add-bash-packages))) (compose identity) (extend home-bash-extensions) (default-value (home-bash-configuration)) (description "Install and configure GNU Bash."))) ;;; ;;; Fish. ;;; (define (serialize-fish-aliases field-name val) #~(string-append #$@(map (match-lambda ((key . value) #~(string-append "alias " #$key " \"" #$value "\"\n")) (_ "")) val))) (define (serialize-fish-abbreviations field-name val) #~(string-append #$@(map (match-lambda ((key . value) #~(string-append "abbr --add " #$key " " #$value "\n")) (_ "")) val))) (define (serialize-fish-env-vars field-name val) #~(string-append #$@(map (match-lambda ((key . #f) "") ((key . #t) #~(string-append "set -x " #$key "\n")) ((key . value) #~(string-append "set -x " #$key " " #$value "\n"))) val))) (define-configuration home-fish-configuration (package (package fish) "The Fish package to use.") (config (text-config '()) "List of file-like objects, which will be added to @file{$XDG_CONFIG_HOME/fish/config.fish}.") (environment-variables (alist '()) "Association list of environment variables to set in Fish." (serializer serialize-fish-env-vars)) (aliases (alist '()) "Association list of aliases for Fish, both the key and the value should be a string. An alias is just a simple function that wraps a command, If you want something more akin to @dfn{aliases} in POSIX shells, see the @code{abbreviations} field." (serializer serialize-fish-aliases)) (abbreviations (alist '()) "Association list of abbreviations for Fish. These are words that, when typed in the shell, will automatically expand to the full text." (serializer serialize-fish-abbreviations))) (define (fish-files-service config) `(("fish/config.fish" ,(mixed-text-file "fish-config.fish" #~(string-append "\ # if we haven't sourced the login config, do it status --is-login; and not set -q __fish_login_config_sourced and begin set --prepend fish_function_path " #$fish-foreign-env "/share/fish/functions fenv source $HOME/.profile set -e fish_function_path[1] set -g __fish_login_config_sourced 1 end\n\n") (serialize-configuration config home-fish-configuration-fields))))) (define (fish-profile-service config) (list (home-fish-configuration-package config))) (define-configuration/no-serialization home-fish-extension (config (text-config '()) "List of file-like objects for extending the Fish initialization file.") (environment-variables (alist '()) "Association list of environment variables to set.") (aliases (alist '()) "Association list of Fish aliases.") (abbreviations (alist '()) "Association list of Fish abbreviations.")) (define (home-fish-extensions original-config extension-configs) (home-fish-configuration (inherit original-config) (config (append (home-fish-configuration-config original-config) (append-map home-fish-extension-config extension-configs))) (environment-variables (append (home-fish-configuration-environment-variables original-config) (append-map home-fish-extension-environment-variables extension-configs))) (aliases (append (home-fish-configuration-aliases original-config) (append-map home-fish-extension-aliases extension-configs))) (abbreviations (append (home-fish-configuration-abbreviations original-config) (append-map home-fish-extension-abbreviations extension-configs))))) ;; TODO: Support for generating completion files ;; TODO: Support for installing plugins (define home-fish-service-type (service-type (name 'home-fish) (extensions (list (service-extension home-xdg-configuration-files-service-type fish-files-service) (service-extension home-profile-service-type fish-profile-service))) (compose identity) (extend home-fish-extensions) (default-value (home-fish-configuration)) (description "\ Install and configure Fish, the friendly interactive shell."))) ;;; ;;; Readline. ;;; (define (serialize-inputrc-key-bindings field-name val) #~(string-append #$@(map (match-lambda ((key . value) #~(string-append #$key ": " #$value "\n"))) val))) (define (serialize-inputrc-variables field-name val) #~(string-append #$@(map (match-lambda ((key . #f) #~(string-append "set " #$key " off\n")) ((key . #t) #~(string-append "set " #$key " on\n")) ((key . value) #~(string-append "set " #$key " " #$value "\n"))) val))) (define (serialize-inputrc-conditional-constructs field-name val) #~(string-append #$@(map (match-lambda (("$endif" . _) "$endif\n") (("$include" . value) #~(string-append "$include " #$value "\n")) ;; TODO: key can only be "$if" or "$else". ((key . value) #~(string-append #$key "\n" #$(serialize-configuration value home-inputrc-configuration-fields)))) val))) (define (serialize-inputrc-extra-content field-name value) #~(if (string=? #$value "") "" (string-append #$value "\n"))) (define-configuration home-inputrc-configuration (key-bindings (alist '()) "Association list of readline key bindings to be added to the @code{~/.inputrc} file. This is where code like this: @lisp '((\"Control-l\" . \"clear-screen\")) @end lisp turns into @example Control-l: clear-screen @end example" (serializer serialize-inputrc-key-bindings)) (variables (alist '()) "Association list of readline variables to set. This is where configuration options like this: @lisp '((\"bell-style\" . \"visible\") (\"colored-completion-prefix\" . #t)) @end lisp turns into @example set bell-style visible set colored-completion-prefix on @end example" (serializer serialize-inputrc-variables)) (conditional-constructs (alist '()) "Association list of conditionals to add to the initialization file. This includes @command{$if}, @command{else}, @command{endif} and @command{include} and they receive a value of another @command{home-inputrc-configuration}. @lisp (conditional-constructs `((\"$if mode=vi\" . ,(home-inputrc-configuration (variables `((\"show-mode-in-prompt\" . #t))))) (\"$else\" . ,(home-inputrc-configuration (key-bindings `((\"Control-l\" . \"clear-screen\"))))) (\"$endif\" . #t))) @end lisp turns into @example $if mode=vi set show-mode-in-prompt on $else Control-l: clear-screen $endif @end example" (serializer serialize-inputrc-conditional-constructs)) (extra-content (string "") "Extra content appended as-is to the configuration file. Run @command{man readline} for more information about all the configuration options." (serializer serialize-inputrc-extra-content))) (define (home-inputrc-files config) (list `(".inputrc" ,(mixed-text-file "inputrc" (serialize-configuration config home-inputrc-configuration-fields))))) (define home-inputrc-service-type (service-type (name 'inputrc) (extensions (list (service-extension home-files-service-type home-inputrc-files))) (default-value (home-inputrc-configuration)) (description "Configure readline in @code{.inputrc}."))) (define (generate-home-shell-profile-documentation) (generate-documentation `((home-shell-profile-configuration ,home-shell-profile-configuration-fields)) 'home-shell-profile-configuration)) (define (generate-home-bash-documentation) (string-append (generate-documentation `((home-bash-configuration ,home-bash-configuration-fields)) 'home-bash-configuration) "\n\n" (generate-documentation `((home-bash-extension ,home-bash-extension-fields)) 'home-bash-extension))) (define (generate-home-zsh-documentation) (generate-documentation `((home-zsh-configuration ,home-zsh-configuration-fields)) 'home-zsh-configuration)) (define (generate-home-fish-documentation) (string-append (generate-documentation `((home-fish-configuration ,home-fish-configuration-fields)) 'home-fish-configuration) "\n\n" (generate-documentation `((home-fish-extension ,home-fish-extension-fields)) 'home-fish-extension)))