gnu: linux-libre@4.14: Update to 4.14.91.
[guix.git] / guix / ui.scm
blob44336ee8fd6bbab731e62b8dcf4c882fe1eaa6f4
1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2012, 2013, 2014, 2015, 2016, 2017, 2018 Ludovic Courtès <ludo@gnu.org>
3 ;;; Copyright © 2013, 2018 Mark H Weaver <mhw@netris.org>
4 ;;; Copyright © 2013 Nikita Karetnikov <nikita@karetnikov.org>
5 ;;; Copyright © 2014 Cyril Roelandt <tipecaml@gmail.com>
6 ;;; Copyright © 2014 Cyrill Schenkel <cyrill.schenkel@gmail.com>
7 ;;; Copyright © 2014, 2015, 2017 Alex Kost <alezost@gmail.com>
8 ;;; Copyright © 2015 David Thompson <davet@gnu.org>
9 ;;; Copyright © 2015, 2016 Mathieu Lirzin <mthl@gnu.org>
10 ;;; Copyright © 2016 Roel Janssen <roel@gnu.org>
11 ;;; Copyright © 2016 Benz Schenk <benz.schenk@uzh.ch>
12 ;;; Copyright © 2018 Kyle Meyer <kyle@kyleam.com>
13 ;;; Copyright © 2013, 2014 Free Software Foundation, Inc.
14 ;;; Copyright © 2018 Sahithi Yarlagadda <sahi@swecha.net>
15 ;;; Copyright © 2018 Ricardo Wurmus <rekado@elephly.net>
16 ;;;
17 ;;; This file is part of GNU Guix.
18 ;;;
19 ;;; GNU Guix is free software; you can redistribute it and/or modify it
20 ;;; under the terms of the GNU General Public License as published by
21 ;;; the Free Software Foundation; either version 3 of the License, or (at
22 ;;; your option) any later version.
23 ;;;
24 ;;; GNU Guix is distributed in the hope that it will be useful, but
25 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
26 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
27 ;;; GNU General Public License for more details.
28 ;;;
29 ;;; You should have received a copy of the GNU General Public License
30 ;;; along with GNU Guix.  If not, see <http://www.gnu.org/licenses/>.
32 (define-module (guix ui)
33   #:use-module (guix i18n)
34   #:use-module (guix gexp)
35   #:use-module (guix sets)
36   #:use-module (guix utils)
37   #:use-module (guix store)
38   #:use-module (guix config)
39   #:use-module (guix packages)
40   #:use-module (guix profiles)
41   #:use-module (guix derivations)
42   #:use-module (guix combinators)
43   #:use-module (guix build-system)
44   #:use-module (guix serialization)
45   #:use-module ((guix licenses) #:select (license? license-name))
46   #:use-module ((guix build syscalls)
47                 #:select (free-disk-space terminal-columns))
48   #:use-module ((guix build utils)
49                 ;; XXX: All we need are the bindings related to
50                 ;; '&invoke-error'.  However, to work around the bug described
51                 ;; in 5d669883ecc104403c5d3ba7d172e9c02234577c, #:hide
52                 ;; unwanted bindings instead of #:select'ing the needed
53                 ;; bindings.
54                 #:hide (package-name->name+version))
55   #:use-module (srfi srfi-1)
56   #:use-module (srfi srfi-11)
57   #:use-module (srfi srfi-19)
58   #:use-module (srfi srfi-26)
59   #:use-module (srfi srfi-31)
60   #:use-module (srfi srfi-34)
61   #:use-module (srfi srfi-35)
62   #:autoload   (ice-9 ftw)  (scandir)
63   #:use-module (ice-9 match)
64   #:use-module (ice-9 format)
65   #:use-module (ice-9 regex)
66   #:autoload   (system base compile) (compile-file)
67   #:autoload   (system repl repl)  (start-repl)
68   #:autoload   (system repl debug) (make-debug stack->vector)
69   #:use-module (texinfo)
70   #:use-module (texinfo plain-text)
71   #:use-module (texinfo string-utils)
72   #:re-export (G_ N_ P_)                          ;backward compatibility
73   #:export (report-error
74             display-hint
75             leave
76             make-user-module
77             load*
78             warn-about-load-error
79             show-version-and-exit
80             show-bug-report-information
81             make-regexp*
82             string->number*
83             size->number
84             show-derivation-outputs
85             show-what-to-build
86             show-what-to-build*
87             show-manifest-transaction
88             call-with-error-handling
89             with-error-handling
90             with-unbound-variable-handling
91             leave-on-EPIPE
92             read/eval
93             read/eval-package-expression
94             check-available-space
95             location->string
96             fill-paragraph
97             %text-width
98             texi->plain-text
99             package-description-string
100             package-synopsis-string
101             string->recutils
102             package->recutils
103             package-specification->name+version+output
104             relevance
105             package-relevance
106             string->generations
107             string->duration
108             matching-generations
109             display-generation
110             display-profile-content
111             display-profile-content-diff
112             roll-back*
113             switch-to-generation*
114             delete-generation*
115             run-guix-command
116             run-guix
117             program-name
118             guix-warning-port
119             warning
120             info
121             guix-main
122             colorize-string))
124 ;;; Commentary:
126 ;;; User interface facilities for command-line tools.
128 ;;; Code:
130 (define-syntax-rule (define-diagnostic name prefix)
131   "Create a diagnostic macro (i.e., NAME), which will prepend PREFIX to all
132 messages."
133   (define-syntax name
134     (lambda (x)
135       (define (augmented-format-string fmt)
136         (string-append "~:[~*~;guix ~a: ~]~a" (syntax->datum fmt)))
138       (syntax-case x ()
139         ((name (underscore fmt) args (... ...))
140          (and (string? (syntax->datum #'fmt))
141               (free-identifier=? #'underscore #'G_))
142          (with-syntax ((fmt*   (augmented-format-string #'fmt))
143                        (prefix (datum->syntax x prefix)))
144            #'(format (guix-warning-port) (gettext fmt*)
145                      (program-name) (program-name) prefix
146                      args (... ...))))
147         ((name (N-underscore singular plural n) args (... ...))
148          (and (string? (syntax->datum #'singular))
149               (string? (syntax->datum #'plural))
150               (free-identifier=? #'N-underscore #'N_))
151          (with-syntax ((s      (augmented-format-string #'singular))
152                        (p      (augmented-format-string #'plural))
153                        (prefix (datum->syntax x prefix)))
154            #'(format (guix-warning-port)
155                      (ngettext s p n %gettext-domain)
156                      (program-name) (program-name) prefix
157                      args (... ...))))))))
159 (define-diagnostic warning "warning: ") ; emit a warning
160 (define-diagnostic info "")
162 (define-diagnostic report-error "error: ")
163 (define-syntax-rule (leave args ...)
164   "Emit an error message and exit."
165   (begin
166     (report-error args ...)
167     (exit 1)))
169 (define (print-unbound-variable-error port key args default-printer)
170   ;; Print unbound variable errors more nicely, and in the right language.
171   (match args
172     ((proc message (variable) _ ...)
173      ;; We can always omit PROC because when it's useful (i.e., different from
174      ;; "module-lookup"), it gets displayed before.
175      (format port (G_ "error: ~a: unbound variable") variable))
176     (_
177      (default-printer))))
179 (set-exception-printer! 'unbound-variable print-unbound-variable-error)
181 (define (make-user-module modules)
182   "Return a new user module with the additional MODULES loaded."
183   ;; Module in which the machine description file is loaded.
184   (let ((module (make-fresh-user-module)))
185     (for-each (lambda (iface)
186                 (module-use! module (resolve-interface iface)))
187               modules)
188     module))
190 (define (last-frame-with-source stack)
191   "Walk stack upwards and return the last frame that has source location
192 information, or #f if it could not be found."
193   (define (frame-with-source frame)
194     ;; Walk from FRAME upwards until source location information is found.
195     (let loop ((frame    frame)
196                (previous frame))
197       (if (not frame)
198           previous
199           (if (frame-source frame)
200               frame
201               (loop (frame-previous frame) frame)))))
203   (let* ((depth (stack-length stack))
204          (last  (and (> depth 0) (stack-ref stack 0))))
205     (frame-with-source (if (> depth 1)
206                            (stack-ref stack 1)    ;skip the 'throw' frame
207                            last))))
209 (define* (load* file user-module
210                 #:key (on-error 'nothing-special))
211   "Load the user provided Scheme source code FILE."
212   (define (error-string frame args)
213     (call-with-output-string
214       (lambda (port)
215         (apply display-error frame port (cdr args)))))
217   (define tag
218     (make-prompt-tag "user-code"))
220   (catch #t
221     (lambda ()
222       ;; XXX: Force a recompilation to avoid ABI issues.
223       ;;
224       ;; In 2.2.3, the bogus answer to <https://bugs.gnu.org/29226> was to
225       ;; ignore all available .go, not just those from ~/.cache, which in turn
226       ;; meant that we had to rebuild *everything*.  Since this is too costly,
227       ;; we have to turn off '%fresh-auto-compile' with that version, so to
228       ;; avoid ABI breakage in the user's config file, we explicitly compile
229       ;; it (the problem remains if the user's config is spread on several
230       ;; modules.)  See <https://bugs.gnu.org/29881>.
231       (unless (string=? (version) "2.2.3")
232         (set! %fresh-auto-compile #t))
234       (set! %load-should-auto-compile #t)
236       (save-module-excursion
237        (lambda ()
238          (set-current-module user-module)
240          ;; Hide the "auto-compiling" messages.
241          (parameterize ((current-warning-port (%make-void-port "w")))
242            (call-with-prompt tag
243              (lambda ()
244                (when (string=? (version) "2.2.3")
245                  (catch 'system-error
246                    (lambda ()
247                      (compile-file file #:env user-module))
248                    (const #f)))              ;EACCES maybe, let's interpret it
250                ;; Give 'load' an absolute file name so that it doesn't try to
251                ;; search for FILE in %LOAD-PATH.  Note: use 'load', not
252                ;; 'primitive-load', so that FILE is compiled, which then allows us
253                ;; to provide better error reporting with source line numbers.
254                (load (canonicalize-path file)))
255              (const #f))))))
256     (lambda _
257       ;; XXX: Errors are reported from the pre-unwind handler below, but
258       ;; calling 'exit' from there has no effect, so we call it here.
259       (exit 1))
260     (rec (handle-error . args)
261          ;; Capture the stack up to this procedure call, excluded, and pass
262          ;; the faulty stack frame to 'report-load-error'.
263          (let* ((stack (make-stack #t handle-error tag))
264                 (frame (last-frame-with-source stack)))
266            (report-load-error file args frame)
268            (case on-error
269              ((debug)
270               (newline)
271               (display (G_ "entering debugger; type ',bt' for a backtrace\n"))
272               (start-repl #:debug (make-debug (stack->vector stack) 0
273                                               (error-string frame args)
274                                               #f)))
275              ((backtrace)
276               (newline (current-error-port))
277               (display-backtrace stack (current-error-port)))
278              (else
279               #t))))))
281 (define (known-variable-definition variable)
282   "Search among the currently loaded modules one that defines a variable named
283 VARIABLE and return it, or #f if none was found."
284   (define (module<? m1 m2)
285     (match (module-name m2)
286       (('gnu _ ...) #t)
287       (('guix _ ...)
288        (match (module-name m1)
289          (('gnu _ ...) #f)
290          (_ #t)))
291       (_ #f)))
293   (let loop ((modules     (list (resolve-module '() #f #f #:ensure #f)))
294              (suggestions '())
295              (visited     (setq)))
296     (match modules
297       (()
298        ;; Pick the "best" suggestion.
299        (match (sort suggestions module<?)
300          (() #f)
301          ((first _ ...) first)))
302       ((head tail ...)
303        (if (set-contains? visited head)
304            (loop tail suggestions visited)
305            (let ((visited (set-insert head visited))
306                  (next    (append tail
307                                   (hash-map->list (lambda (name module)
308                                                     module)
309                                                   (module-submodules head)))))
310              (match (module-local-variable head variable)
311                (#f (loop next suggestions visited))
312                (_
313                 (match (module-name head)
314                   (('gnu _ ...) head)             ;must be that one
315                   (_ (loop next (cons head suggestions) visited)))))))))))
317 (define* (display-hint message #:optional (port (current-error-port)))
318   "Display MESSAGE, a l10n message possibly containing Texinfo markup, to
319 PORT."
320   (format port (G_ "hint: ~a~%")
321           ;; XXX: We should arrange so that the initial indent is wider.
322           (parameterize ((%text-width (max 15
323                                            (- (terminal-columns) 5))))
324             (texi->plain-text message))))
326 (define* (report-unbound-variable-error args #:key frame)
327   "Return the given unbound-variable error, where ARGS is the list of 'throw'
328 arguments."
329   (match args
330     ((key . args)
331      (print-exception (current-error-port) frame key args)))
332   (match args
333     (('unbound-variable proc message (variable) _ ...)
334      (match (known-variable-definition variable)
335        (#f
336         (display-hint (G_ "Did you forget a @code{use-modules} form?")))
337        ((? module? module)
338         (display-hint (format #f (G_ "Did you forget @code{(use-modules ~a)}?")
339                               (module-name module))))))))
341 (define* (report-load-error file args #:optional frame)
342   "Report the failure to load FILE, a user-provided Scheme file.
343 ARGS is the list of arguments received by the 'throw' handler."
344   (match args
345     (('system-error . rest)
346      (let ((err (system-error-errno args)))
347        (report-error (G_ "failed to load '~a': ~a~%") file (strerror err))))
348     (('read-error "scm_i_lreadparen" message _ ...)
349      ;; Guile's missing-paren messages are obscure so we make them more
350      ;; intelligible here.
351      (if (string-suffix? "end of file" message)
352          (let ((location (string-drop-right message
353                                             (string-length "end of file"))))
354            (format (current-error-port) (G_ "~amissing closing parenthesis~%")
355                    location))
356          (apply throw args)))
357     (('syntax-error proc message properties form . rest)
358      (let ((loc (source-properties->location properties)))
359        (format (current-error-port) (G_ "~a: error: ~a~%")
360                (location->string loc) message)))
361     (('unbound-variable _ ...)
362      (report-unbound-variable-error args #:frame frame))
363     (('srfi-34 obj)
364      (if (message-condition? obj)
365          (if (error-location? obj)
366              (format (current-error-port)
367                      (G_ "~a: error: ~a~%")
368                      (location->string (error-location obj))
369                      (gettext (condition-message obj)
370                               %gettext-domain))
371              (report-error (G_ "~a~%")
372                            (gettext (condition-message obj)
373                                     %gettext-domain)))
374          (report-error (G_ "exception thrown: ~s~%") obj))
375      (when (fix-hint? obj)
376        (display-hint (condition-fix-hint obj))))
377     ((error args ...)
378      (report-error (G_ "failed to load '~a':~%") file)
379      (apply display-error frame (current-error-port) args))))
381 (define (warn-about-load-error file args)         ;FIXME: factorize with ↑
382   "Report the failure to load FILE, a user-provided Scheme file, without
383 exiting.  ARGS is the list of arguments received by the 'throw' handler."
384   (match args
385     (('system-error . rest)
386      (let ((err (system-error-errno args)))
387        (warning (G_ "failed to load '~a': ~a~%") file (strerror err))))
388     (('syntax-error proc message properties form . rest)
389      (let ((loc (source-properties->location properties)))
390        (format (current-error-port) (G_ "~a: warning: ~a~%")
391                (location->string loc) message)))
392     (('srfi-34 obj)
393      (if (message-condition? obj)
394          (warning (G_ "failed to load '~a': ~a~%")
395                   file
396                   (gettext (condition-message obj) %gettext-domain))
397          (warning (G_ "failed to load '~a': exception thrown: ~s~%")
398                   file obj)))
399     ((error args ...)
400      (warning (G_ "failed to load '~a':~%") file)
401      (apply display-error #f (current-error-port) args))))
403 (define (call-with-unbound-variable-handling thunk)
404   (define tag
405     (make-prompt-tag "user-code"))
407   (catch 'unbound-variable
408     (lambda ()
409       (call-with-prompt tag
410         thunk
411         (const #f)))
412     (const #t)
413     (rec (handle-error . args)
414          (let* ((stack (make-stack #t handle-error tag))
415                 (frame (and stack (last-frame-with-source stack))))
416            (report-unbound-variable-error args #:frame frame)
417            (exit 1)))))
419 (define-syntax-rule (with-unbound-variable-handling exp ...)
420   "Capture 'unbound-variable' exceptions in the dynamic extent of EXP... and
421 report them in a user-friendly way."
422   (call-with-unbound-variable-handling (lambda () exp ...)))
424 (define (install-locale)
425   "Install the current locale settings."
426   (catch 'system-error
427     (lambda _
428       (setlocale LC_ALL ""))
429     (lambda args
430       (cond-expand
431         ;; Guile 2.2 already emits a warning, so let's not add a second one.
432         (guile-2.2 #t)
433         (else (warning (G_ "failed to install locale: ~a~%")
434                        (strerror (system-error-errno args)))))
435       (display-hint (G_ "Consider installing the @code{glibc-utf8-locales} or
436 @code{glibc-locales} package and defining @code{GUIX_LOCPATH}, along these
437 lines:
439 @example
440 guix package -i glibc-utf8-locales
441 export GUIX_LOCPATH=\"$HOME/.guix-profile/lib/locale\"
442 @end example
444 See the \"Application Setup\" section in the manual, for more info.\n")))))
446 (define (initialize-guix)
447   "Perform the usual initialization for stand-alone Guix commands."
448   ;; By default don't annoy users with deprecation warnings.  In practice,
449   ;; 'define-deprecated' in (ice-9 deprecated) arranges so that those warnings
450   ;; are emitted at expansion-time only, but there are cases where they could
451   ;; slip through, for instance when interpreting code.
452   (unless (getenv "GUILE_WARN_DEPRECATED")
453     (debug-disable 'warn-deprecated))
455   (install-locale)
456   (textdomain %gettext-domain)
458   ;; Ignore SIGPIPE.  If the daemon closes the connection, we prefer to be
459   ;; notified via an EPIPE later.
460   (sigaction SIGPIPE SIG_IGN)
462   (setvbuf (current-output-port) _IOLBF)
463   (setvbuf (current-error-port) _IOLBF))
465 (define* (show-version-and-exit #:optional (command (car (command-line))))
466   "Display version information for COMMAND and `(exit 0)'."
467   (simple-format #t "~a (~a) ~a~%"
468                  command %guix-package-name %guix-version)
469   (format #t "Copyright ~a 2018 ~a"
470           ;; TRANSLATORS: Translate "(C)" to the copyright symbol
471           ;; (C-in-a-circle), if this symbol is available in the user's
472           ;; locale.  Otherwise, do not translate "(C)"; leave it as-is.  */
473           (G_ "(C)")
474           (G_ "the Guix authors\n"))
475   (display (G_"\
476 License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
477 This is free software: you are free to change and redistribute it.
478 There is NO WARRANTY, to the extent permitted by law.
480   (exit 0))
482 (define (show-bug-report-information)
483   ;; TRANSLATORS: The placeholder indicates the bug-reporting address for this
484   ;; package.  Please add another line saying "Report translation bugs to
485   ;; ...\n" with the address for translation bugs (typically your translation
486   ;; team's web or email address).
487   (format #t (G_ "
488 Report bugs to: ~a.") %guix-bug-report-address)
489   (format #t (G_ "
490 ~a home page: <~a>") %guix-package-name %guix-home-page-url)
491   (display (G_ "
492 General help using GNU software: <http://www.gnu.org/gethelp/>"))
493   (newline))
495 (define (augmented-system-error-handler file)
496   "Return a 'system-error' handler that mentions FILE in its message."
497   (lambda (key proc fmt args errno)
498     ;; Augment the FMT and ARGS with information about TARGET (this
499     ;; information is missing as of Guile 2.0.11, making the exception
500     ;; uninformative.)
501     (apply throw key proc "~A: ~S"
502            (list (strerror (car errno)) file)
503            (list errno))))
505 (define-syntax apply-formals
506   (syntax-rules ()
507     ((_ proc (args ...)) (proc args ...))
508     ((_ proc (arg1 args ... . rest)) (apply proc arg1 args ... rest))))
510 (define-syntax-rule (error-reporting-wrapper proc formals file)
511   "Wrap PROC such that its 'system-error' exceptions are augmented to mention
512 FILE."
513   (let ((real-proc (@ (guile) proc)))
514     (lambda formals
515       (catch 'system-error
516         (lambda ()
517           (apply-formals real-proc formals))
518         (augmented-system-error-handler file)))))
520 (set! symlink
521   ;; We 'set!' the global binding because (gnu build ...) modules and similar
522   ;; typically don't use (guix ui).
523   (error-reporting-wrapper symlink (source target) target))
525 (set! copy-file
526   ;; Note: here we use 'set!', not #:replace, because UIs typically use
527   ;; 'copy-recursively', which doesn't use (guix ui).
528   (error-reporting-wrapper copy-file (source target) target))
530 (set! canonicalize-path
531   (error-reporting-wrapper canonicalize-path (file) file))
533 (set! delete-file
534   (error-reporting-wrapper delete-file (file) file))
536 (set! execlp
537   (error-reporting-wrapper execlp (filename . args) filename))
539 (define (make-regexp* regexp . flags)
540   "Like 'make-regexp' but error out if REGEXP is invalid, reporting the error
541 nicely."
542   (catch 'regular-expression-syntax
543     (lambda ()
544       (apply make-regexp regexp flags))
545     (lambda (key proc message . rest)
546       (leave (G_ "'~a' is not a valid regular expression: ~a~%")
547              regexp message))))
549 (define (string->number* str)
550   "Like `string->number', but error out with an error message on failure."
551   (or (string->number str)
552       (leave (G_ "~a: invalid number~%") str)))
554 (define (size->number str)
555   "Convert STR, a storage measurement representation such as \"1024\" or
556 \"1MiB\", to a number of bytes.  Raise an error if STR could not be
557 interpreted."
558   (define unit-pos
559     (string-rindex str char-set:digit))
561   (define unit
562     (and unit-pos (substring str (+ 1 unit-pos))))
564   (let* ((numstr (if unit-pos
565                      (substring str 0 (+ 1 unit-pos))
566                      str))
567          (num    (string->number numstr)))
568     (unless num
569       (leave (G_ "invalid number: ~a~%") numstr))
571     ((compose inexact->exact round)
572      (* num
573         (match unit
574           ((or "KiB" "K" "k") (expt 2 10))
575           ((or "MiB" "M")     (expt 2 20))
576           ((or "GiB" "G")     (expt 2 30))
577           ((or "TiB" "T")     (expt 2 40))
578           ((or "PiB" "P")     (expt 2 50))
579           ((or "EiB" "E")     (expt 2 60))
580           ((or "ZiB" "Z")     (expt 2 70))
581           ((or "YiB" "Y")     (expt 2 80))
582           ("kB"  (expt 10 3))
583           ("MB"  (expt 10 6))
584           ("GB"  (expt 10 9))
585           ("TB"  (expt 10 12))
586           ("PB"  (expt 10 15))
587           ("EB"  (expt 10 18))
588           ("ZB"  (expt 10 21))
589           ("YB"  (expt 10 24))
590           (""    1)
591           (x
592            (leave (G_ "unknown unit: ~a~%") unit)))))))
594 (define (display-collision-resolution-hint collision)
595   "Display hints on how to resolve COLLISION, a &profile-collistion-error."
596   (define (top-most-entry entry)
597     (let loop ((entry entry))
598       (match (force (manifest-entry-parent entry))
599         (#f entry)
600         (parent (loop parent)))))
602   (let* ((first  (profile-collision-error-entry collision))
603          (second (profile-collision-error-conflict collision))
604          (name1  (manifest-entry-name (top-most-entry first)))
605          (name2  (manifest-entry-name (top-most-entry second))))
606     (if (string=? name1 name2)
607         (display-hint (format #f (G_ "You cannot have two different versions
608 or variants of @code{~a} in the same profile.")
609                               name1))
610         (display-hint (format #f (G_ "Try upgrading both @code{~a} and @code{~a},
611 or remove one of them from the profile.")
612                               name1 name2)))))
614 (define (call-with-error-handling thunk)
615   "Call THUNK within a user-friendly error handler."
616   (define (port-filename* port)
617     ;; 'port-filename' returns #f for non-file ports, but it raises an
618     ;; exception for file ports that are closed.  Work around that.
619     (and (not (port-closed? port))
620          (port-filename port)))
622   (guard (c ((package-input-error? c)
623              (let* ((package  (package-error-package c))
624                     (input    (package-error-invalid-input c))
625                     (location (package-location package))
626                     (file     (location-file location))
627                     (line     (location-line location))
628                     (column   (location-column location)))
629                (leave (G_ "~a:~a:~a: package `~a' has an invalid input: ~s~%")
630                       file line column
631                       (package-full-name package) input)))
632             ((package-cross-build-system-error? c)
633              (let* ((package (package-error-package c))
634                     (loc     (package-location package))
635                     (system  (package-build-system package)))
636                (leave (G_ "~a: ~a: build system `~a' does not support cross builds~%")
637                       (location->string loc)
638                       (package-full-name package)
639                       (build-system-name system))))
640             ((gexp-input-error? c)
641              (let ((input (package-error-invalid-input c)))
642                (leave (G_ "~s: invalid G-expression input~%")
643                       (gexp-error-invalid-input c))))
644             ((profile-not-found-error? c)
645              (leave (G_ "profile '~a' does not exist~%")
646                     (profile-error-profile c)))
647             ((missing-generation-error? c)
648              (leave (G_ "generation ~a of profile '~a' does not exist~%")
649                     (missing-generation-error-generation c)
650                     (profile-error-profile c)))
651             ((profile-collision-error? c)
652              (let ((entry    (profile-collision-error-entry c))
653                    (conflict (profile-collision-error-conflict c)))
654                (define (report-parent-entries entry)
655                  (let ((parent (force (manifest-entry-parent entry))))
656                    (when (manifest-entry? parent)
657                      (report-error (G_ "   ... propagated from ~a@~a~%")
658                                    (manifest-entry-name parent)
659                                    (manifest-entry-version parent))
660                      (report-parent-entries parent))))
662                (define (manifest-entry-output* entry)
663                  (match (manifest-entry-output entry)
664                    ("out"   "")
665                    (output (string-append ":" output))))
667                (report-error (G_ "profile contains conflicting entries for ~a~a~%")
668                              (manifest-entry-name entry)
669                              (manifest-entry-output* entry))
670                (report-error (G_ "  first entry: ~a@~a~a ~a~%")
671                              (manifest-entry-name entry)
672                              (manifest-entry-version entry)
673                              (manifest-entry-output* entry)
674                              (manifest-entry-item entry))
675                (report-parent-entries entry)
676                (report-error (G_ "  second entry: ~a@~a~a ~a~%")
677                              (manifest-entry-name conflict)
678                              (manifest-entry-version conflict)
679                              (manifest-entry-output* conflict)
680                              (manifest-entry-item conflict))
681                (report-parent-entries conflict)
682                (display-collision-resolution-hint c)
683                (exit 1)))
684             ((nar-error? c)
685              (let ((file (nar-error-file c))
686                    (port (nar-error-port c)))
687                (if file
688                    (leave (G_ "corrupt input while restoring '~a' from ~s~%")
689                           file (or (port-filename* port) port))
690                    (leave (G_ "corrupt input while restoring archive from ~s~%")
691                           (or (port-filename* port) port)))))
692             ((nix-connection-error? c)
693              (leave (G_ "failed to connect to `~a': ~a~%")
694                     (nix-connection-error-file c)
695                     (strerror (nix-connection-error-code c))))
696             ((nix-protocol-error? c)
697              ;; FIXME: Server-provided error messages aren't i18n'd.
698              (leave (G_ "build failed: ~a~%")
699                     (nix-protocol-error-message c)))
700             ((derivation-missing-output-error? c)
701              (leave (G_ "reference to invalid output '~a' of derivation '~a'~%")
702                     (derivation-missing-output c)
703                     (derivation-file-name (derivation-error-derivation c))))
704             ((file-search-error? c)
705              (leave (G_ "file '~a' could not be found in these \
706 directories:~{ ~a~}~%")
707                     (file-search-error-file-name c)
708                     (file-search-error-search-path c)))
709             ((invoke-error? c)
710              (leave (G_ "program exited\
711 ~@[ with non-zero exit status ~a~]\
712 ~@[ terminated by signal ~a~]\
713 ~@[ stopped by signal ~a~]: ~s~%")
714                     (invoke-error-exit-status c)
715                     (invoke-error-term-signal c)
716                     (invoke-error-stop-signal c)
717                     (cons (invoke-error-program c)
718                           (invoke-error-arguments c))))
719             ((and (error-location? c) (message-condition? c))
720              (format (current-error-port)
721                      (G_ "~a: error: ~a~%")
722                      (location->string (error-location c))
723                      (gettext (condition-message c) %gettext-domain))
724              (when (fix-hint? c)
725                (display-hint (condition-fix-hint c)))
726              (exit 1))
727             ((and (message-condition? c) (fix-hint? c))
728              (format (current-error-port) "~a: error: ~a~%"
729                      (program-name)
730                      (gettext (condition-message c) %gettext-domain))
731              (display-hint (condition-fix-hint c))
732              (exit 1))
733             ((message-condition? c)
734              ;; Normally '&message' error conditions have an i18n'd message.
735              (leave (G_ "~a~%")
736                     (gettext (condition-message c) %gettext-domain))))
737     ;; Catch EPIPE and the likes.
738     (catch 'system-error
739       thunk
740       (lambda (key proc format-string format-args . rest)
741         (leave (G_ "~a: ~a~%") proc
742                (apply format #f format-string format-args))))))
744 (define-syntax-rule (leave-on-EPIPE exp ...)
745   "Run EXP... in a context when EPIPE errors are caught and lead to 'exit'
746 with successful exit code.  This is useful when writing to the standard output
747 may lead to EPIPE, because the standard output is piped through 'head' or
748 similar."
749   (catch 'system-error
750     (lambda ()
751       exp ...)
752     (lambda args
753       ;; We really have to exit this brutally, otherwise Guile eventually
754       ;; attempts to flush all the ports, leading to an uncaught EPIPE down
755       ;; the path.
756       (if (= EPIPE (system-error-errno args))
757           (primitive-_exit 0)
758           (apply throw args)))))
760 (define %guix-user-module
761   ;; Module in which user expressions are evaluated.
762   ;; Compute lazily to avoid circularity with (guix gexp).
763   (delay
764     (let ((module (make-module)))
765       (beautify-user-module! module)
766       ;; Use (guix gexp) so that one can use #~ & co.
767       (module-use! module (resolve-interface '(guix gexp)))
768       module)))
770 (define (read/eval str)
771   "Read and evaluate STR, raising an error if something goes wrong."
772   (let ((exp (catch #t
773                (lambda ()
774                  (call-with-input-string str read))
775                (lambda args
776                  (leave (G_ "failed to read expression ~s: ~s~%")
777                         str args)))))
778     (catch #t
779       (lambda ()
780         (eval exp (force %guix-user-module)))
781       (lambda args
782         (report-error (G_ "failed to evaluate expression '~a':~%") exp)
783         (match args
784           (('syntax-error proc message properties form . rest)
785            (report-error (G_ "syntax error: ~a~%") message))
786           (('srfi-34 obj)
787            (if (message-condition? obj)
788                (report-error (G_ "~a~%")
789                              (gettext (condition-message obj)
790                                       %gettext-domain))
791                (report-error (G_ "exception thrown: ~s~%") obj)))
792           ((error args ...)
793            (apply display-error #f (current-error-port) args))
794           (what? #f))
795         (exit 1)))))
797 (define (read/eval-package-expression str)
798   "Read and evaluate STR and return the package it refers to, or exit an
799 error."
800   (match (read/eval str)
801     ((? package? p) p)
802     (x
803      (leave (G_ "expression ~s does not evaluate to a package~%")
804             str))))
806 (define (show-derivation-outputs derivation)
807   "Show the output file names of DERIVATION."
808   (format #t "~{~a~%~}"
809           (map (match-lambda
810                  ((out-name . out)
811                   (derivation->output-path derivation out-name)))
812                (derivation-outputs derivation))))
814 (define* (check-available-space need
815                                 #:optional (directory (%store-prefix)))
816   "Make sure at least NEED bytes are available in DIRECTORY.  Otherwise emit a
817 warning."
818   (let ((free (catch 'system-error
819                 (lambda ()
820                   (free-disk-space directory))
821                 (const #f))))
822     (when (and free (>= need free))
823       (warning (G_ "at least ~,1h MB needed but only ~,1h MB available in ~a~%")
824                (/ need 1e6) (/ free 1e6) directory))))
826 (define (graft-derivation? drv)
827   "Return true if DRV is definitely a graft derivation, false otherwise."
828   (match (assq-ref (derivation-properties drv) 'type)
829     ('graft #t)
830     (_ #f)))
832 (define (profile-hook-derivation? drv)
833   "Return true if DRV is definitely a profile hook derivation, false otherwise."
834   (match (assq-ref (derivation-properties drv) 'type)
835     ('profile-hook #t)
836     (_ #f)))
838 (define* (show-what-to-build store drv
839                              #:key dry-run? (use-substitutes? #t)
840                              (mode (build-mode normal)))
841   "Show what will or would (depending on DRY-RUN?) be built in realizing the
842 derivations listed in DRV using MODE, a 'build-mode' value.  Return #t if
843 there's something to build, #f otherwise.  When USE-SUBSTITUTES?, check and
844 report what is prerequisites are available for download."
845   (define substitutable-info
846     ;; Call 'substitutation-oracle' upfront so we don't end up launching the
847     ;; substituter many times.  This makes a big difference, especially when
848     ;; DRV is a long list as is the case with 'guix environment'.
849     (if use-substitutes?
850         (substitution-oracle store drv #:mode mode)
851         (const #f)))
853   (define (built-or-substitutable? drv)
854     (or (null? (derivation-outputs drv))
855         (let ((out (derivation->output-path drv))) ;XXX: assume "out" exists
856           (or (valid-path? store out)
857               (substitutable-info out)))))
859   (let*-values (((build download)
860                  (fold2 (lambda (drv build download)
861                           (let-values (((b d)
862                                         (derivation-prerequisites-to-build
863                                          store drv
864                                          #:mode mode
865                                          #:substitutable-info
866                                          substitutable-info)))
867                             (values (append b build)
868                                     (append d download))))
869                         '() '()
870                         drv))
871                 ((build)                          ; add the DRV themselves
872                  (delete-duplicates
873                   (append (map derivation-file-name
874                                (remove built-or-substitutable? drv))
875                           (map derivation-input-path build))))
876                 ((download)                   ; add the references of DOWNLOAD
877                  (if use-substitutes?
878                      (delete-duplicates
879                       (append download
880                               (filter-map (lambda (item)
881                                             (if (valid-path? store item)
882                                                 #f
883                                                 (substitutable-info item)))
884                                           (append-map
885                                            substitutable-references
886                                            download))))
887                      download))
888                 ((graft hook build)
889                  (match (fold (lambda (file acc)
890                                 (let ((drv (read-derivation-from-file file)))
891                                   (match acc
892                                     ((#:graft graft #:hook hook #:build build)
893                                      (cond
894                                       ((graft-derivation? drv)
895                                        `(#:graft ,(cons file graft)
896                                          #:hook ,hook
897                                          #:build ,build))
898                                       ((profile-hook-derivation? drv)
899                                        `(#:graft ,graft
900                                          #:hook ,(cons file hook)
901                                          #:build ,build))
902                                       (else
903                                        `(#:graft ,graft
904                                          #:hook ,hook
905                                          #:build ,(cons file build))))))))
906                               '(#:graft () #:hook () #:build ())
907                               build)
908                    ((#:graft graft #:hook hook #:build build)
909                     (values graft hook build)))))
910     (define installed-size
911       (reduce + 0 (map substitutable-nar-size download)))
913     (define download-size
914       (/ (reduce + 0 (map substitutable-download-size download))
915          1e6))
917     (define display-download-size?
918       ;; Sometimes narinfos lack information about the download size.  Only
919       ;; display when we have information for all of DOWNLOAD.
920       (not (any (compose zero? substitutable-download-size) download)))
922     (if dry-run?
923         (begin
924           (format (current-error-port)
925                   (N_ "~:[The following derivation would be built:~%~{   ~a~%~}~;~]"
926                       "~:[The following derivations would be built:~%~{   ~a~%~}~;~]"
927                       (length build))
928                   (null? build) build)
929           (if display-download-size?
930               (format (current-error-port)
931                       ;; TRANSLATORS: "MB" is for "megabyte"; it should be
932                       ;; translated to the corresponding abbreviation.
933                       (G_ "~:[~,1h MB would be downloaded:~%~{   ~a~%~}~;~]")
934                       (null? download)
935                       download-size
936                       (map substitutable-path download))
937               (format (current-error-port)
938                       (N_ "~:[The following file would be downloaded:~%~{   ~a~%~}~;~]"
939                           "~:[The following files would be downloaded:~%~{   ~a~%~}~;~]"
940                           (length download))
941                       (null? download)
942                       (map substitutable-path download)))
943           (format (current-error-port)
944                   (N_ "~:[The following graft would be made:~%~{   ~a~%~}~;~]"
945                       "~:[The following grafts would be made:~%~{   ~a~%~}~;~]"
946                       (length graft))
947                   (null? graft) graft)
948           (format (current-error-port)
949                   (N_ "~:[The following profile hook would be built:~%~{   ~a~%~}~;~]"
950                       "~:[The following profile hooks would be built:~%~{   ~a~%~}~;~]"
951                       (length hook))
952                   (null? hook) hook))
953         (begin
954           (format (current-error-port)
955                   (N_ "~:[The following derivation will be built:~%~{   ~a~%~}~;~]"
956                       "~:[The following derivations will be built:~%~{   ~a~%~}~;~]"
957                       (length build))
958                   (null? build) build)
959           (if display-download-size?
960               (format (current-error-port)
961                       ;; TRANSLATORS: "MB" is for "megabyte"; it should be
962                       ;; translated to the corresponding abbreviation.
963                       (G_ "~:[~,1h MB will be downloaded:~%~{   ~a~%~}~;~]")
964                       (null? download)
965                       download-size
966                       (map substitutable-path download))
967               (format (current-error-port)
968                       (N_ "~:[The following file will be downloaded:~%~{   ~a~%~}~;~]"
969                           "~:[The following files will be downloaded:~%~{   ~a~%~}~;~]"
970                           (length download))
971                       (null? download)
972                       (map substitutable-path download)))
973           (format (current-error-port)
974                   (N_ "~:[The following graft will be made:~%~{   ~a~%~}~;~]"
975                       "~:[The following grafts will be made:~%~{   ~a~%~}~;~]"
976                       (length graft))
977                   (null? graft) graft)
978           (format (current-error-port)
979                   (N_ "~:[The following profile hook will be built:~%~{   ~a~%~}~;~]"
980                       "~:[The following profile hooks will be built:~%~{   ~a~%~}~;~]"
981                       (length hook))
982                   (null? hook) hook)))
984     (check-available-space installed-size)
986     (pair? build)))
988 (define show-what-to-build*
989   (store-lift show-what-to-build))
991 (define (right-arrow port)
992   "Return either a string containing the 'RIGHT ARROW' character, or an ASCII
993 replacement if PORT is not Unicode-capable."
994   (let ((encoding (port-encoding port))
995         (arrow "→"))
996     (catch 'encoding-error
997       (lambda ()
998         (call-with-output-string
999           (lambda (port)
1000             (set-port-encoding! port encoding)
1001             (set-port-conversion-strategy! port 'error)
1002             (display arrow port))))
1003       (lambda (key . args)
1004         "->"))))
1006 (define* (show-manifest-transaction store manifest transaction
1007                                     #:key dry-run?)
1008   "Display what will/would be installed/removed from MANIFEST by TRANSACTION."
1009   (define (package-strings name version output item)
1010     (map (lambda (name version output item)
1011            (format #f "   ~a~:[:~a~;~*~]\t~a\t~a"
1012                    name
1013                    (equal? output "out") output version
1014                    (if (package? item)
1015                        (package-output store item output)
1016                        item)))
1017          name version output item))
1019   (define →                        ;an arrow that can be represented on stderr
1020     (right-arrow (current-error-port)))
1022   (define (upgrade-string name old-version new-version output item)
1023     (format #f "   ~a~:[:~a~;~*~]\t~a ~a ~a\t~a"
1024             name (equal? output "out") output
1025             old-version → new-version
1026             (if (package? item)
1027                 (package-output store item output)
1028                 item)))
1030   (let-values (((remove install upgrade downgrade)
1031                 (manifest-transaction-effects manifest transaction)))
1032     (match remove
1033       ((($ <manifest-entry> name version output item) ..1)
1034        (let ((len    (length name))
1035              (remove (package-strings name version output item)))
1036          (if dry-run?
1037              (format (current-error-port)
1038                      (N_ "The following package would be removed:~%~{~a~%~}~%"
1039                          "The following packages would be removed:~%~{~a~%~}~%"
1040                          len)
1041                      remove)
1042              (format (current-error-port)
1043                      (N_ "The following package will be removed:~%~{~a~%~}~%"
1044                          "The following packages will be removed:~%~{~a~%~}~%"
1045                          len)
1046                      remove))))
1047       (x #f))
1048     (match downgrade
1049       (((($ <manifest-entry> name old-version)
1050          . ($ <manifest-entry> _ new-version output item)) ..1)
1051        (let ((len       (length name))
1052              (downgrade (map upgrade-string
1053                              name old-version new-version output item)))
1054          (if dry-run?
1055              (format (current-error-port)
1056                      (N_ "The following package would be downgraded:~%~{~a~%~}~%"
1057                          "The following packages would be downgraded:~%~{~a~%~}~%"
1058                          len)
1059                      downgrade)
1060              (format (current-error-port)
1061                      (N_ "The following package will be downgraded:~%~{~a~%~}~%"
1062                          "The following packages will be downgraded:~%~{~a~%~}~%"
1063                          len)
1064                      downgrade))))
1065       (x #f))
1066     (match upgrade
1067       (((($ <manifest-entry> name old-version)
1068          . ($ <manifest-entry> _ new-version output item)) ..1)
1069        (let ((len     (length name))
1070              (upgrade (map upgrade-string
1071                            name old-version new-version output item)))
1072          (if dry-run?
1073              (format (current-error-port)
1074                      (N_ "The following package would be upgraded:~%~{~a~%~}~%"
1075                          "The following packages would be upgraded:~%~{~a~%~}~%"
1076                          len)
1077                      upgrade)
1078              (format (current-error-port)
1079                      (N_ "The following package will be upgraded:~%~{~a~%~}~%"
1080                          "The following packages will be upgraded:~%~{~a~%~}~%"
1081                          len)
1082                      upgrade))))
1083       (x #f))
1084     (match install
1085       ((($ <manifest-entry> name version output item _) ..1)
1086        (let ((len     (length name))
1087              (install (package-strings name version output item)))
1088          (if dry-run?
1089              (format (current-error-port)
1090                      (N_ "The following package would be installed:~%~{~a~%~}~%"
1091                          "The following packages would be installed:~%~{~a~%~}~%"
1092                          len)
1093                      install)
1094              (format (current-error-port)
1095                      (N_ "The following package will be installed:~%~{~a~%~}~%"
1096                          "The following packages will be installed:~%~{~a~%~}~%"
1097                          len)
1098                      install))))
1099       (x #f))))
1101 (define-syntax with-error-handling
1102   (syntax-rules ()
1103     "Run BODY within a user-friendly error condition handler."
1104     ((_ body ...)
1105      (call-with-error-handling
1106       (lambda ()
1107         body ...)))))
1109 (define (location->string loc)
1110   "Return a human-friendly, GNU-standard representation of LOC."
1111   (match loc
1112     (#f (G_ "<unknown location>"))
1113     (($ <location> file line column)
1114      (format #f "~a:~a:~a" file line column))))
1116 (define* (fill-paragraph str width #:optional (column 0))
1117   "Fill STR such that each line contains at most WIDTH characters, assuming
1118 that the first character is at COLUMN.
1120 When STR contains a single line break surrounded by other characters, it is
1121 converted to a space; sequences of more than one line break are preserved."
1122   (define (maybe-break chr result)
1123     (match result
1124       ((column newlines chars)
1125        (case chr
1126          ((#\newline)
1127           `(,column ,(+ 1 newlines) ,chars))
1128          (else
1129           (let* ((spaces (if (and (pair? chars) (eqv? (car chars) #\.)) 2 1))
1130                  (chars  (case newlines
1131                            ((0) chars)
1132                            ((1)
1133                             (append (make-list spaces #\space) chars))
1134                            (else
1135                             (append (make-list newlines #\newline) chars))))
1136                  (column (case newlines
1137                            ((0) column)
1138                            ((1) (+ spaces column))
1139                            (else 0))))
1140             (let ((chars  (cons chr chars))
1141                   (column (+ 1 column)))
1142               (if (> column width)
1143                   (let*-values (((before after)
1144                                  (break (cut eqv? #\space <>) chars))
1145                                 ((len)
1146                                  (length before)))
1147                     (if (<= len width)
1148                         `(,len
1149                           0
1150                           ,(if (null? after)
1151                                before
1152                                (append before
1153                                        (cons #\newline
1154                                              (drop-while (cut eqv? #\space <>)
1155                                                          after)))))
1156                         `(,column 0 ,chars)))     ; unbreakable
1157                   `(,column 0 ,chars)))))))))
1159   (match (string-fold maybe-break
1160                       `(,column 0 ())
1161                       str)
1162     ((column newlines chars)
1163      (list->string (reverse chars)))))
1167 ;;; Packages.
1170 (define %text-width
1171   (make-parameter (terminal-columns)))
1173 (set! (@@ (texinfo plain-text) wrap*)
1174       ;; XXX: Monkey patch this private procedure to let 'package->recutils'
1175       ;; parameterize the fill of description field correctly.
1176       (lambda strings
1177         (let ((indent (fluid-ref (@@ (texinfo plain-text) *indent*))))
1178           (fill-string (string-concatenate strings)
1179                        #:line-width (%text-width) #:initial-indent indent
1180                        #:subsequent-indent indent))))
1182 (define (texi->plain-text str)
1183   "Return a plain-text representation of texinfo fragment STR."
1184   ;; 'texi-fragment->stexi' uses a string port so make sure it's a
1185   ;; Unicode-capable one (see <http://bugs.gnu.org/11197>.)
1186   (with-fluids ((%default-port-encoding "UTF-8"))
1187     (stexi->plain-text (texi-fragment->stexi str))))
1189 (define (package-field-string package field-accessor)
1190   "Return a plain-text representation of PACKAGE field."
1191   (and=> (field-accessor package)
1192          (compose texi->plain-text P_)))
1194 (define (package-description-string package)
1195   "Return a plain-text representation of PACKAGE description field."
1196   (package-field-string package package-description))
1198 (define (package-synopsis-string package)
1199   "Return a plain-text representation of PACKAGE synopsis field."
1200   (package-field-string package package-synopsis))
1202 (define (string->recutils str)
1203   "Return a version of STR where newlines have been replaced by newlines
1204 followed by \"+ \", which makes for a valid multi-line field value in the
1205 `recutils' syntax."
1206   (list->string
1207    (string-fold-right (lambda (chr result)
1208                         (if (eqv? chr #\newline)
1209                             (cons* chr #\+ #\space result)
1210                             (cons chr result)))
1211                       '()
1212                       str)))
1214 (define* (package->recutils p port #:optional (width (%text-width))
1215                             #:key (extra-fields '()))
1216   "Write to PORT a `recutils' record of package P, arranging to fit within
1217 WIDTH columns.  EXTRA-FIELDS is a list of symbol/value pairs to emit."
1218   (define width*
1219     ;; The available number of columns once we've taken into account space for
1220     ;; the initial "+ " prefix.
1221     (if (> width 2) (- width 2) width))
1223   (define (dependencies->recutils packages)
1224     (let ((list (string-join (delete-duplicates
1225                               (map package-full-name
1226                                    (sort packages package<?))) " ")))
1227       (string->recutils
1228        (fill-paragraph list width*
1229                        (string-length "dependencies: ")))))
1231   (define (package<? p1 p2)
1232     (string<? (package-full-name p1) (package-full-name p2)))
1234   ;; Note: Don't i18n field names so that people can post-process it.
1235   (format port "name: ~a~%" (package-name p))
1236   (format port "version: ~a~%" (package-version p))
1237   (format port "outputs: ~a~%" (string-join (package-outputs p)))
1238   (format port "systems: ~a~%"
1239           (string-join (package-transitive-supported-systems p)))
1240   (format port "dependencies: ~a~%"
1241           (match (package-direct-inputs p)
1242             (((labels inputs . _) ...)
1243              (dependencies->recutils (filter package? inputs)))))
1244   (format port "location: ~a~%"
1245           (or (and=> (package-location p) location->string)
1246               (G_ "unknown")))
1248   ;; Note: Starting from version 1.6 or recutils, hyphens are not allowed in
1249   ;; field identifiers.
1250   (format port "homepage: ~a~%" (package-home-page p))
1252   (format port "license: ~a~%"
1253           (match (package-license p)
1254             (((? license? licenses) ...)
1255              (string-join (map license-name licenses)
1256                           ", "))
1257             ((? license? license)
1258              (license-name license))
1259             (x
1260              (G_ "unknown"))))
1261   (format port "synopsis: ~a~%"
1262           (string-map (match-lambda
1263                         (#\newline #\space)
1264                         (chr       chr))
1265                       (or (and=> (package-synopsis-string p) P_)
1266                           "")))
1267   (format port "~a~%"
1268           (string->recutils
1269            (string-trim-right
1270             (parameterize ((%text-width width*))
1271               (texi->plain-text
1272                (string-append "description: "
1273                               (or (and=> (package-description p) P_)
1274                                   ""))))
1275             #\newline)))
1276   (for-each (match-lambda
1277               ((field . value)
1278                (let ((field (symbol->string field)))
1279                  (format port "~a: ~a~%"
1280                          field
1281                          (fill-paragraph (object->string value) width*
1282                                          (string-length field))))))
1283             extra-fields)
1284   (newline port))
1286 (define (relevance obj regexps metrics)
1287   "Compute a \"relevance score\" for OBJ as a function of its number of
1288 matches of REGEXPS and accordingly to METRICS.  METRICS is list of
1289 field/weight pairs, where FIELD is a procedure that returns a string
1290 describing OBJ, and WEIGHT is a positive integer denoting the weight of this
1291 field in the final score.
1293 A score of zero means that OBJ does not match any of REGEXPS.  The higher the
1294 score, the more relevant OBJ is to REGEXPS."
1295   (define (score str)
1296     (let ((counts (map (lambda (regexp)
1297                          (match (fold-matches regexp str '() cons)
1298                            (()  0)
1299                            ((m) (if (string=? (match:substring m) str)
1300                                     5              ;exact match
1301                                     1))
1302                            (lst (length lst))))
1303                        regexps)))
1304       ;; Compute a score that's proportional to the number of regexps matched
1305       ;; and to the number of matches for each regexp.
1306       (* (length counts) (reduce + 0 counts))))
1308   (fold (lambda (metric relevance)
1309           (match metric
1310             ((field . weight)
1311              (match (field obj)
1312                (#f  relevance)
1313                (str (+ relevance
1314                        (* (score str) weight)))))))
1315         0
1316         metrics))
1318 (define %package-metrics
1319   ;; Metrics used to compute the "relevance score" of a package against a set
1320   ;; of regexps.
1321   `((,package-name . 4)
1322     (,package-synopsis-string . 3)
1323     (,package-description-string . 2)
1324     (,(lambda (type)
1325         (match (and=> (package-location type) location-file)
1326           ((? string? file) (basename file ".scm"))
1327           (#f "")))
1328      . 1)))
1330 (define (package-relevance package regexps)
1331   "Return a score denoting the relevance of PACKAGE for REGEXPS.  A score of
1332 zero means that PACKAGE does not match any of REGEXPS."
1333   (relevance package regexps %package-metrics))
1335 (define (string->generations str)
1336   "Return the list of generations matching a pattern in STR.  This function
1337 accepts the following patterns: \"1\", \"1,2,3\", \"1..9\", \"1..\", \"..9\"."
1338   (define (maybe-integer)
1339     (let ((x (string->number str)))
1340       (and (integer? x)
1341            x)))
1343   (define (maybe-comma-separated-integers)
1344     (let ((lst (delete-duplicates
1345                 (map string->number
1346                      (string-split str #\,)))))
1347       (and (every integer? lst)
1348            lst)))
1350   (cond ((maybe-integer)
1351          =>
1352          list)
1353         ((maybe-comma-separated-integers)
1354          =>
1355          identity)
1356         ((string-match "^([0-9]+)\\.\\.([0-9]+)$" str)
1357          =>
1358          (lambda (match)
1359            (let ((s (string->number (match:substring match 1)))
1360                  (e (string->number (match:substring match 2))))
1361              (and (every integer? (list s e))
1362                   (<= s e)
1363                   (iota (1+ (- e s)) s)))))
1364         ((string-match "^([0-9]+)\\.\\.$" str)
1365          =>
1366          (lambda (match)
1367            (let ((s (string->number (match:substring match 1))))
1368              (and (integer? s)
1369                   `(>= ,s)))))
1370         ((string-match "^\\.\\.([0-9]+)$" str)
1371          =>
1372          (lambda (match)
1373            (let ((e (string->number (match:substring match 1))))
1374              (and (integer? e)
1375                   `(<= ,e)))))
1376         (else #f)))
1378 (define (string->duration str)
1379   "Return the duration matching a pattern in STR.  This function accepts the
1380 following patterns: \"1d\", \"1w\", \"1m\"."
1381   (define (hours->duration hours match)
1382     (make-time time-duration 0
1383                (* 3600 hours (string->number (match:substring match 1)))))
1385   (cond ((string-match "^([0-9]+)s$" str)
1386          =>
1387          (lambda (match)
1388            (make-time time-duration 0
1389                       (string->number (match:substring match 1)))))
1390         ((string-match "^([0-9]+)h$" str)
1391          =>
1392          (lambda (match)
1393            (hours->duration 1 match)))
1394         ((string-match "^([0-9]+)d$" str)
1395          =>
1396          (lambda (match)
1397            (hours->duration 24 match)))
1398         ((string-match "^([0-9]+)w$" str)
1399          =>
1400          (lambda (match)
1401            (hours->duration (* 24 7) match)))
1402         ((string-match "^([0-9]+)m$" str)
1403          =>
1404          (lambda (match)
1405            (hours->duration (* 24 30) match)))
1406         (else #f)))
1408 (define* (matching-generations str profile
1409                                #:key (duration-relation <=))
1410   "Return the list of available generations matching a pattern in STR.  See
1411 'string->generations' and 'string->duration' for the list of valid patterns.
1412 When STR is a duration pattern, return all the generations whose ctime has
1413 DURATION-RELATION with the current time."
1414   (define (valid-generations lst)
1415     (define (valid-generation? n)
1416       (any (cut = n <>) (generation-numbers profile)))
1418     (fold-right (lambda (x acc)
1419                   (if (valid-generation? x)
1420                       (cons x acc)
1421                       acc))
1422                 '()
1423                 lst))
1425   (define (filter-generations generations)
1426     (match generations
1427       (() '())
1428       (('>= n)
1429        (drop-while (cut > n <>)
1430                    (generation-numbers profile)))
1431       (('<= n)
1432        (valid-generations (iota n 1)))
1433       ((lst ..1)
1434        (valid-generations lst))
1435       (x #f)))
1437   (define (filter-by-duration duration)
1438     (define (time-at-midnight time)
1439       ;; Return TIME at midnight by setting nanoseconds, seconds, minutes, and
1440       ;; hours to zeros.
1441       (let ((d (time-utc->date time)))
1442          (date->time-utc
1443           (make-date 0 0 0 0
1444                      (date-day d) (date-month d)
1445                      (date-year d) (date-zone-offset d)))))
1447     (define generation-ctime-alist
1448       (map (lambda (number)
1449              (cons number
1450                    (time-second
1451                     (time-at-midnight
1452                      (generation-time profile number)))))
1453            (generation-numbers profile)))
1455     (match duration
1456       (#f #f)
1457       (res
1458        (let ((s (time-second
1459                  (subtract-duration (time-at-midnight (current-time))
1460                                     duration))))
1461          (delete #f (map (lambda (x)
1462                            (and (duration-relation s (cdr x))
1463                                 (first x)))
1464                          generation-ctime-alist))))))
1466   (cond ((string->generations str)
1467          =>
1468          filter-generations)
1469         ((string->duration str)
1470          =>
1471          filter-by-duration)
1472         (else #f)))
1474 (define (display-generation profile number)
1475   "Display a one-line summary of generation NUMBER of PROFILE."
1476   (unless (zero? number)
1477     (let ((header (format #f (G_ "Generation ~a\t~a") number
1478                           (date->string
1479                            (time-utc->date
1480                             (generation-time profile number))
1481                            ;; TRANSLATORS: This is a format-string for date->string.
1482                            ;; Please choose a format that corresponds to the
1483                            ;; usual way of presenting dates in your locale.
1484                            ;; See https://www.gnu.org/software/guile/manual/html_node/SRFI_002d19-Date-to-string.html
1485                            ;; for details.
1486                            (G_ "~b ~d ~Y ~T"))))
1487           (current (generation-number profile)))
1488       (if (= number current)
1489           ;; TRANSLATORS: The word "current" here is an adjective for
1490           ;; "Generation", as in "current generation".  Use the appropriate
1491           ;; gender where applicable.
1492           (format #t (G_ "~a\t(current)~%") header)
1493           (format #t "~a~%" header)))))
1495 (define (display-profile-content-diff profile gen1 gen2)
1496   "Display the changed packages in PROFILE GEN2 compared to generation GEN1."
1498   (define (equal-entry? first second)
1499     (string= (manifest-entry-item first) (manifest-entry-item second)))
1501   (define (display-entry entry prefix)
1502     (match entry
1503       (($ <manifest-entry> name version output location _)
1504        (format #t " ~a ~a\t~a\t~a\t~a~%" prefix name version output location))))
1506   (define (list-entries number)
1507     (manifest-entries (profile-manifest (generation-file-name profile number))))
1509   (define (display-diff profile old new)
1510     (display-generation profile new)
1511     (let ((added (lset-difference
1512                   equal-entry? (list-entries new) (list-entries old)))
1513           (removed (lset-difference
1514                     equal-entry? (list-entries old) (list-entries new))))
1515       (for-each (cut display-entry <> "+") added)
1516       (for-each (cut display-entry <> "-") removed)
1517       (newline)))
1519   (display-diff profile gen1 gen2))
1521 (define (display-profile-content profile number)
1522   "Display the packages in PROFILE, generation NUMBER, in a human-readable
1523 way."
1524   (for-each (match-lambda
1525               (($ <manifest-entry> name version output location _)
1526                (format #t "  ~a\t~a\t~a\t~a~%"
1527                        name version output location)))
1529             ;; Show most recently installed packages last.
1530             (reverse
1531              (manifest-entries
1532               (profile-manifest (generation-file-name profile number))))))
1534 (define (display-generation-change previous current)
1535   (format #t (G_ "switched from generation ~a to ~a~%") previous current))
1537 (define (roll-back* store profile)
1538   "Like 'roll-back', but display what is happening."
1539   (call-with-values
1540       (lambda ()
1541         (roll-back store profile))
1542     display-generation-change))
1544 (define (switch-to-generation* profile number)
1545   "Like 'switch-generation', but display what is happening."
1546   (let ((previous (switch-to-generation profile number)))
1547     (display-generation-change previous number)))
1549 (define (delete-generation* store profile generation)
1550   "Like 'delete-generation', but display what is going on."
1551   (format #t (G_ "deleting ~a~%")
1552           (generation-file-name profile generation))
1553   (delete-generation store profile generation))
1555 (define* (package-specification->name+version+output spec
1556                                                      #:optional (output "out"))
1557   "Parse package specification SPEC and return three value: the specified
1558 package name, version number (or #f), and output name (or OUTPUT).  SPEC may
1559 optionally contain a version number and an output name, as in these examples:
1561   guile
1562   guile@2.0.9
1563   guile:debug
1564   guile@2.0.9:debug
1566   (let*-values (((name sub-drv)
1567                  (match (string-rindex spec #\:)
1568                    (#f    (values spec output))
1569                    (colon (values (substring spec 0 colon)
1570                                   (substring spec (+ 1 colon))))))
1571                 ((name version)
1572                  (package-name->name+version name)))
1573     (values name version sub-drv)))
1577 ;;; Command-line option processing.
1580 (define (show-guix-usage)
1581   (format (current-error-port)
1582           (G_ "Try `guix --help' for more information.~%"))
1583   (exit 1))
1585 (define (command-files)
1586   "Return the list of source files that define Guix sub-commands."
1587   (define directory
1588     (and=> (search-path %load-path "guix.scm")
1589            (compose (cut string-append <> "/guix/scripts")
1590                     dirname)))
1592   (define dot-scm?
1593     (cut string-suffix? ".scm" <>))
1595   (if directory
1596       (scandir directory dot-scm?)
1597       '()))
1599 (define (commands)
1600   "Return the list of Guix command names."
1601   (map (compose (cut string-drop-right <> 4)
1602                 basename)
1603        (command-files)))
1605 (define (show-guix-help)
1606   (define (internal? command)
1607     (member command '("substitute" "authenticate" "offload"
1608                       "perform-download")))
1610   (format #t (G_ "Usage: guix COMMAND ARGS...
1611 Run COMMAND with ARGS.\n"))
1612   (newline)
1613   (format #t (G_ "COMMAND must be one of the sub-commands listed below:\n"))
1614   (newline)
1615   ;; TODO: Display a synopsis of each command.
1616   (format #t "~{   ~a~%~}" (sort (remove internal? (commands))
1617                                  string<?))
1618   (show-bug-report-information))
1620 (define program-name
1621   ;; Name of the command-line program currently executing, or #f.
1622   (make-parameter #f))
1624 (define (run-guix-command command . args)
1625   "Run COMMAND with the given ARGS.  Report an error when COMMAND is not
1626 found."
1627   (define module
1628     (catch 'misc-error
1629       (lambda ()
1630         (resolve-interface `(guix scripts ,command)))
1631       (lambda -
1632         (format (current-error-port)
1633                 (G_ "guix: ~a: command not found~%") command)
1634         (show-guix-usage))))
1636   (let ((command-main (module-ref module
1637                                   (symbol-append 'guix- command))))
1638     (parameterize ((program-name command))
1639       ;; Disable canonicalization so we don't don't stat unreasonably.
1640       (with-fluids ((%file-port-name-canonicalization #f))
1641         (dynamic-wind
1642           (const #f)
1643           (lambda ()
1644             (apply command-main args))
1645           (lambda ()
1646             ;; Abuse 'exit-hook' (which is normally meant to be used by the
1647             ;; REPL) to run things like profiling hooks upon completion.
1648             (run-hook exit-hook)))))))
1650 (define (run-guix . args)
1651   "Run the 'guix' command defined by command line ARGS.
1652 Unlike 'guix-main', this procedure assumes that locale, i18n support,
1653 and signal handling has already been set up."
1654   (define option? (cut string-prefix? "-" <>))
1656   ;; The default %LOAD-EXTENSIONS includes the empty string, which doubles the
1657   ;; number of 'stat' calls per entry in %LOAD-PATH.  Shamelessly remove it.
1658   (set! %load-extensions '(".scm"))
1660   (match args
1661     (()
1662      (format (current-error-port)
1663              (G_ "guix: missing command name~%"))
1664      (show-guix-usage))
1665     ((or ("-h") ("--help"))
1666      (show-guix-help))
1667     ((or ("-V") ("--version"))
1668      (show-version-and-exit "guix"))
1669     (((? option? o) args ...)
1670      (format (current-error-port)
1671              (G_ "guix: unrecognized option '~a'~%") o)
1672      (show-guix-usage))
1673     (("help" command)
1674      (apply run-guix-command (string->symbol command)
1675             '("--help")))
1676     (("help" args ...)
1677      (show-guix-help))
1678     ((command args ...)
1679      (apply run-guix-command
1680             (string->symbol command)
1681             args))))
1683 (define guix-warning-port
1684   (make-parameter (current-warning-port)))
1686 (define (guix-main arg0 . args)
1687   (initialize-guix)
1688   (apply run-guix args))
1690 (define color-table
1691   `((CLEAR       .   "0")
1692     (RESET       .   "0")
1693     (BOLD        .   "1")
1694     (DARK        .   "2")
1695     (UNDERLINE   .   "4")
1696     (UNDERSCORE  .   "4")
1697     (BLINK       .   "5")
1698     (REVERSE     .   "6")
1699     (CONCEALED   .   "8")
1700     (BLACK       .  "30")
1701     (RED         .  "31")
1702     (GREEN       .  "32")
1703     (YELLOW      .  "33")
1704     (BLUE        .  "34")
1705     (MAGENTA     .  "35")
1706     (CYAN        .  "36")
1707     (WHITE       .  "37")
1708     (ON-BLACK    .  "40")
1709     (ON-RED      .  "41")
1710     (ON-GREEN    .  "42")
1711     (ON-YELLOW   .  "43")
1712     (ON-BLUE     .  "44")
1713     (ON-MAGENTA  .  "45")
1714     (ON-CYAN     .  "46")
1715     (ON-WHITE    .  "47")))
1717 (define (color . lst)
1718   "Return a string containing the ANSI escape sequence for producing the
1719 requested set of attributes in LST.  Unknown attributes are ignored."
1720   (let ((color-list
1721          (remove not
1722                  (map (lambda (color) (assq-ref color-table color))
1723                       lst))))
1724     (if (null? color-list)
1725         ""
1726         (string-append
1727          (string #\esc #\[)
1728          (string-join color-list ";" 'infix)
1729          "m"))))
1731 (define (colorize-string str . color-list)
1732   "Return a copy of STR colorized using ANSI escape sequences according to the
1733 attributes STR.  At the end of the returned string, the color attributes will
1734 be reset such that subsequent output will not have any colors in effect."
1735   (string-append
1736    (apply color color-list)
1737    str
1738    (color 'RESET)))
1740 ;;; ui.scm ends here