gnu: lxqt.scm: Add prefix to licenses imports.
[guix.git] / guix / ui.scm
blob96f403acf51be082172e107128aba4581e495471
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-rule (error-reporting-wrapper proc (args ...) file)
506   "Wrap PROC such that its 'system-error' exceptions are augmented to mention
507 FILE."
508   (let ((real-proc (@ (guile) proc)))
509     (lambda (args ...)
510       (catch 'system-error
511         (lambda ()
512           (real-proc args ...))
513         (augmented-system-error-handler file)))))
515 (set! symlink
516   ;; We 'set!' the global binding because (gnu build ...) modules and similar
517   ;; typically don't use (guix ui).
518   (error-reporting-wrapper symlink (source target) target))
520 (set! copy-file
521   ;; Note: here we use 'set!', not #:replace, because UIs typically use
522   ;; 'copy-recursively', which doesn't use (guix ui).
523   (error-reporting-wrapper copy-file (source target) target))
525 (set! canonicalize-path
526   (error-reporting-wrapper canonicalize-path (file) file))
528 (set! delete-file
529   (error-reporting-wrapper delete-file (file) file))
532 (define (make-regexp* regexp . flags)
533   "Like 'make-regexp' but error out if REGEXP is invalid, reporting the error
534 nicely."
535   (catch 'regular-expression-syntax
536     (lambda ()
537       (apply make-regexp regexp flags))
538     (lambda (key proc message . rest)
539       (leave (G_ "'~a' is not a valid regular expression: ~a~%")
540              regexp message))))
542 (define (string->number* str)
543   "Like `string->number', but error out with an error message on failure."
544   (or (string->number str)
545       (leave (G_ "~a: invalid number~%") str)))
547 (define (size->number str)
548   "Convert STR, a storage measurement representation such as \"1024\" or
549 \"1MiB\", to a number of bytes.  Raise an error if STR could not be
550 interpreted."
551   (define unit-pos
552     (string-rindex str char-set:digit))
554   (define unit
555     (and unit-pos (substring str (+ 1 unit-pos))))
557   (let* ((numstr (if unit-pos
558                      (substring str 0 (+ 1 unit-pos))
559                      str))
560          (num    (string->number numstr)))
561     (unless num
562       (leave (G_ "invalid number: ~a~%") numstr))
564     ((compose inexact->exact round)
565      (* num
566         (match unit
567           ((or "KiB" "K" "k") (expt 2 10))
568           ((or "MiB" "M")     (expt 2 20))
569           ((or "GiB" "G")     (expt 2 30))
570           ((or "TiB" "T")     (expt 2 40))
571           ((or "PiB" "P")     (expt 2 50))
572           ((or "EiB" "E")     (expt 2 60))
573           ((or "ZiB" "Z")     (expt 2 70))
574           ((or "YiB" "Y")     (expt 2 80))
575           ("kB"  (expt 10 3))
576           ("MB"  (expt 10 6))
577           ("GB"  (expt 10 9))
578           ("TB"  (expt 10 12))
579           ("PB"  (expt 10 15))
580           ("EB"  (expt 10 18))
581           ("ZB"  (expt 10 21))
582           ("YB"  (expt 10 24))
583           (""    1)
584           (x
585            (leave (G_ "unknown unit: ~a~%") unit)))))))
587 (define (display-collision-resolution-hint collision)
588   "Display hints on how to resolve COLLISION, a &profile-collistion-error."
589   (define (top-most-entry entry)
590     (let loop ((entry entry))
591       (match (force (manifest-entry-parent entry))
592         (#f entry)
593         (parent (loop parent)))))
595   (let* ((first  (profile-collision-error-entry collision))
596          (second (profile-collision-error-conflict collision))
597          (name1  (manifest-entry-name (top-most-entry first)))
598          (name2  (manifest-entry-name (top-most-entry second))))
599     (if (string=? name1 name2)
600         (display-hint (format #f (G_ "You cannot have two different versions
601 or variants of @code{~a} in the same profile.")
602                               name1))
603         (display-hint (format #f (G_ "Try upgrading both @code{~a} and @code{~a},
604 or remove one of them from the profile.")
605                               name1 name2)))))
607 (define (call-with-error-handling thunk)
608   "Call THUNK within a user-friendly error handler."
609   (define (port-filename* port)
610     ;; 'port-filename' returns #f for non-file ports, but it raises an
611     ;; exception for file ports that are closed.  Work around that.
612     (and (not (port-closed? port))
613          (port-filename port)))
615   (guard (c ((package-input-error? c)
616              (let* ((package  (package-error-package c))
617                     (input    (package-error-invalid-input c))
618                     (location (package-location package))
619                     (file     (location-file location))
620                     (line     (location-line location))
621                     (column   (location-column location)))
622                (leave (G_ "~a:~a:~a: package `~a' has an invalid input: ~s~%")
623                       file line column
624                       (package-full-name package) input)))
625             ((package-cross-build-system-error? c)
626              (let* ((package (package-error-package c))
627                     (loc     (package-location package))
628                     (system  (package-build-system package)))
629                (leave (G_ "~a: ~a: build system `~a' does not support cross builds~%")
630                       (location->string loc)
631                       (package-full-name package)
632                       (build-system-name system))))
633             ((gexp-input-error? c)
634              (let ((input (package-error-invalid-input c)))
635                (leave (G_ "~s: invalid G-expression input~%")
636                       (gexp-error-invalid-input c))))
637             ((profile-not-found-error? c)
638              (leave (G_ "profile '~a' does not exist~%")
639                     (profile-error-profile c)))
640             ((missing-generation-error? c)
641              (leave (G_ "generation ~a of profile '~a' does not exist~%")
642                     (missing-generation-error-generation c)
643                     (profile-error-profile c)))
644             ((profile-collision-error? c)
645              (let ((entry    (profile-collision-error-entry c))
646                    (conflict (profile-collision-error-conflict c)))
647                (define (report-parent-entries entry)
648                  (let ((parent (force (manifest-entry-parent entry))))
649                    (when (manifest-entry? parent)
650                      (report-error (G_ "   ... propagated from ~a@~a~%")
651                                    (manifest-entry-name parent)
652                                    (manifest-entry-version parent))
653                      (report-parent-entries parent))))
655                (define (manifest-entry-output* entry)
656                  (match (manifest-entry-output entry)
657                    ("out"   "")
658                    (output (string-append ":" output))))
660                (report-error (G_ "profile contains conflicting entries for ~a~a~%")
661                              (manifest-entry-name entry)
662                              (manifest-entry-output* entry))
663                (report-error (G_ "  first entry: ~a@~a~a ~a~%")
664                              (manifest-entry-name entry)
665                              (manifest-entry-version entry)
666                              (manifest-entry-output* entry)
667                              (manifest-entry-item entry))
668                (report-parent-entries entry)
669                (report-error (G_ "  second entry: ~a@~a~a ~a~%")
670                              (manifest-entry-name conflict)
671                              (manifest-entry-version conflict)
672                              (manifest-entry-output* conflict)
673                              (manifest-entry-item conflict))
674                (report-parent-entries conflict)
675                (display-collision-resolution-hint c)
676                (exit 1)))
677             ((nar-error? c)
678              (let ((file (nar-error-file c))
679                    (port (nar-error-port c)))
680                (if file
681                    (leave (G_ "corrupt input while restoring '~a' from ~s~%")
682                           file (or (port-filename* port) port))
683                    (leave (G_ "corrupt input while restoring archive from ~s~%")
684                           (or (port-filename* port) port)))))
685             ((nix-connection-error? c)
686              (leave (G_ "failed to connect to `~a': ~a~%")
687                     (nix-connection-error-file c)
688                     (strerror (nix-connection-error-code c))))
689             ((nix-protocol-error? c)
690              ;; FIXME: Server-provided error messages aren't i18n'd.
691              (leave (G_ "build failed: ~a~%")
692                     (nix-protocol-error-message c)))
693             ((derivation-missing-output-error? c)
694              (leave (G_ "reference to invalid output '~a' of derivation '~a'~%")
695                     (derivation-missing-output c)
696                     (derivation-file-name (derivation-error-derivation c))))
697             ((file-search-error? c)
698              (leave (G_ "file '~a' could not be found in these \
699 directories:~{ ~a~}~%")
700                     (file-search-error-file-name c)
701                     (file-search-error-search-path c)))
702             ((invoke-error? c)
703              (leave (G_ "program exited\
704 ~@[ with non-zero exit status ~a~]\
705 ~@[ terminated by signal ~a~]\
706 ~@[ stopped by signal ~a~]: ~s~%")
707                     (invoke-error-exit-status c)
708                     (invoke-error-term-signal c)
709                     (invoke-error-stop-signal c)
710                     (cons (invoke-error-program c)
711                           (invoke-error-arguments c))))
712             ((and (error-location? c) (message-condition? c))
713              (format (current-error-port)
714                      (G_ "~a: error: ~a~%")
715                      (location->string (error-location c))
716                      (gettext (condition-message c) %gettext-domain))
717              (when (fix-hint? c)
718                (display-hint (condition-fix-hint c)))
719              (exit 1))
720             ((and (message-condition? c) (fix-hint? c))
721              (format (current-error-port) "~a: error: ~a~%"
722                      (program-name)
723                      (gettext (condition-message c) %gettext-domain))
724              (display-hint (condition-fix-hint c))
725              (exit 1))
726             ((message-condition? c)
727              ;; Normally '&message' error conditions have an i18n'd message.
728              (leave (G_ "~a~%")
729                     (gettext (condition-message c) %gettext-domain))))
730     ;; Catch EPIPE and the likes.
731     (catch 'system-error
732       thunk
733       (lambda (key proc format-string format-args . rest)
734         (leave (G_ "~a: ~a~%") proc
735                (apply format #f format-string format-args))))))
737 (define-syntax-rule (leave-on-EPIPE exp ...)
738   "Run EXP... in a context when EPIPE errors are caught and lead to 'exit'
739 with successful exit code.  This is useful when writing to the standard output
740 may lead to EPIPE, because the standard output is piped through 'head' or
741 similar."
742   (catch 'system-error
743     (lambda ()
744       exp ...)
745     (lambda args
746       ;; We really have to exit this brutally, otherwise Guile eventually
747       ;; attempts to flush all the ports, leading to an uncaught EPIPE down
748       ;; the path.
749       (if (= EPIPE (system-error-errno args))
750           (primitive-_exit 0)
751           (apply throw args)))))
753 (define %guix-user-module
754   ;; Module in which user expressions are evaluated.
755   ;; Compute lazily to avoid circularity with (guix gexp).
756   (delay
757     (let ((module (make-module)))
758       (beautify-user-module! module)
759       ;; Use (guix gexp) so that one can use #~ & co.
760       (module-use! module (resolve-interface '(guix gexp)))
761       module)))
763 (define (read/eval str)
764   "Read and evaluate STR, raising an error if something goes wrong."
765   (let ((exp (catch #t
766                (lambda ()
767                  (call-with-input-string str read))
768                (lambda args
769                  (leave (G_ "failed to read expression ~s: ~s~%")
770                         str args)))))
771     (catch #t
772       (lambda ()
773         (eval exp (force %guix-user-module)))
774       (lambda args
775         (report-error (G_ "failed to evaluate expression '~a':~%") exp)
776         (match args
777           (('syntax-error proc message properties form . rest)
778            (report-error (G_ "syntax error: ~a~%") message))
779           (('srfi-34 obj)
780            (if (message-condition? obj)
781                (report-error (G_ "~a~%")
782                              (gettext (condition-message obj)
783                                       %gettext-domain))
784                (report-error (G_ "exception thrown: ~s~%") obj)))
785           ((error args ...)
786            (apply display-error #f (current-error-port) args))
787           (what? #f))
788         (exit 1)))))
790 (define (read/eval-package-expression str)
791   "Read and evaluate STR and return the package it refers to, or exit an
792 error."
793   (match (read/eval str)
794     ((? package? p) p)
795     (x
796      (leave (G_ "expression ~s does not evaluate to a package~%")
797             str))))
799 (define (show-derivation-outputs derivation)
800   "Show the output file names of DERIVATION."
801   (format #t "~{~a~%~}"
802           (map (match-lambda
803                  ((out-name . out)
804                   (derivation->output-path derivation out-name)))
805                (derivation-outputs derivation))))
807 (define* (check-available-space need
808                                 #:optional (directory (%store-prefix)))
809   "Make sure at least NEED bytes are available in DIRECTORY.  Otherwise emit a
810 warning."
811   (let ((free (catch 'system-error
812                 (lambda ()
813                   (free-disk-space directory))
814                 (const #f))))
815     (when (and free (>= need free))
816       (warning (G_ "at least ~,1h MB needed but only ~,1h MB available in ~a~%")
817                (/ need 1e6) (/ free 1e6) directory))))
819 (define* (show-what-to-build store drv
820                              #:key dry-run? (use-substitutes? #t)
821                              (mode (build-mode normal)))
822   "Show what will or would (depending on DRY-RUN?) be built in realizing the
823 derivations listed in DRV using MODE, a 'build-mode' value.  Return #t if
824 there's something to build, #f otherwise.  When USE-SUBSTITUTES?, check and
825 report what is prerequisites are available for download."
826   (define substitutable-info
827     ;; Call 'substitutation-oracle' upfront so we don't end up launching the
828     ;; substituter many times.  This makes a big difference, especially when
829     ;; DRV is a long list as is the case with 'guix environment'.
830     (if use-substitutes?
831         (substitution-oracle store drv #:mode mode)
832         (const #f)))
834   (define (built-or-substitutable? drv)
835     (or (null? (derivation-outputs drv))
836         (let ((out (derivation->output-path drv))) ;XXX: assume "out" exists
837           (or (valid-path? store out)
838               (substitutable-info out)))))
840   (let*-values (((build download)
841                  (fold2 (lambda (drv build download)
842                           (let-values (((b d)
843                                         (derivation-prerequisites-to-build
844                                          store drv
845                                          #:mode mode
846                                          #:substitutable-info
847                                          substitutable-info)))
848                             (values (append b build)
849                                     (append d download))))
850                         '() '()
851                         drv))
852                 ((build)                          ; add the DRV themselves
853                  (delete-duplicates
854                   (append (map derivation-file-name
855                                (remove built-or-substitutable? drv))
856                           (map derivation-input-path build))))
857                 ((download)                   ; add the references of DOWNLOAD
858                  (if use-substitutes?
859                      (delete-duplicates
860                       (append download
861                               (filter-map (lambda (item)
862                                             (if (valid-path? store item)
863                                                 #f
864                                                 (substitutable-info item)))
865                                           (append-map
866                                            substitutable-references
867                                            download))))
868                      download)))
869     (define installed-size
870       (reduce + 0 (map substitutable-nar-size download)))
872     (define download-size
873       (/ (reduce + 0 (map substitutable-download-size download))
874          1e6))
876     (define display-download-size?
877       ;; Sometimes narinfos lack information about the download size.  Only
878       ;; display when we have information for all of DOWNLOAD.
879       (not (any (compose zero? substitutable-download-size) download)))
881     (if dry-run?
882         (begin
883           (format (current-error-port)
884                   (N_ "~:[The following derivation would be built:~%~{   ~a~%~}~;~]"
885                       "~:[The following derivations would be built:~%~{   ~a~%~}~;~]"
886                       (length build))
887                   (null? build) build)
888           (if display-download-size?
889               (format (current-error-port)
890                       ;; TRANSLATORS: "MB" is for "megabyte"; it should be
891                       ;; translated to the corresponding abbreviation.
892                       (G_ "~:[~,1h MB would be downloaded:~%~{   ~a~%~}~;~]")
893                       (null? download)
894                       download-size
895                       (map substitutable-path download))
896               (format (current-error-port)
897                       (N_ "~:[The following file would be downloaded:~%~{   ~a~%~}~;~]"
898                           "~:[The following files would be downloaded:~%~{   ~a~%~}~;~]"
899                           (length download))
900                       (null? download)
901                       (map substitutable-path download))))
902         (begin
903           (format (current-error-port)
904                   (N_ "~:[The following derivation will be built:~%~{   ~a~%~}~;~]"
905                       "~:[The following derivations will be built:~%~{   ~a~%~}~;~]"
906                       (length build))
907                   (null? build) build)
908           (if display-download-size?
909               (format (current-error-port)
910                       ;; TRANSLATORS: "MB" is for "megabyte"; it should be
911                       ;; translated to the corresponding abbreviation.
912                       (G_ "~:[~,1h MB will be downloaded:~%~{   ~a~%~}~;~]")
913                       (null? download)
914                       download-size
915                       (map substitutable-path download))
916               (format (current-error-port)
917                       (N_ "~:[The following file will be downloaded:~%~{   ~a~%~}~;~]"
918                           "~:[The following files will be downloaded:~%~{   ~a~%~}~;~]"
919                           (length download))
920                       (null? download)
921                       (map substitutable-path download)))))
923     (check-available-space installed-size)
925     (pair? build)))
927 (define show-what-to-build*
928   (store-lift show-what-to-build))
930 (define (right-arrow port)
931   "Return either a string containing the 'RIGHT ARROW' character, or an ASCII
932 replacement if PORT is not Unicode-capable."
933   (let ((encoding (port-encoding port))
934         (arrow "→"))
935     (catch 'encoding-error
936       (lambda ()
937         (call-with-output-string
938           (lambda (port)
939             (set-port-encoding! port encoding)
940             (set-port-conversion-strategy! port 'error)
941             (display arrow port))))
942       (lambda (key . args)
943         "->"))))
945 (define* (show-manifest-transaction store manifest transaction
946                                     #:key dry-run?)
947   "Display what will/would be installed/removed from MANIFEST by TRANSACTION."
948   (define (package-strings name version output item)
949     (map (lambda (name version output item)
950            (format #f "   ~a~:[:~a~;~*~]\t~a\t~a"
951                    name
952                    (equal? output "out") output version
953                    (if (package? item)
954                        (package-output store item output)
955                        item)))
956          name version output item))
958   (define →                        ;an arrow that can be represented on stderr
959     (right-arrow (current-error-port)))
961   (define (upgrade-string name old-version new-version output item)
962     (format #f "   ~a~:[:~a~;~*~]\t~a ~a ~a\t~a"
963             name (equal? output "out") output
964             old-version → new-version
965             (if (package? item)
966                 (package-output store item output)
967                 item)))
969   (let-values (((remove install upgrade downgrade)
970                 (manifest-transaction-effects manifest transaction)))
971     (match remove
972       ((($ <manifest-entry> name version output item) ..1)
973        (let ((len    (length name))
974              (remove (package-strings name version output item)))
975          (if dry-run?
976              (format (current-error-port)
977                      (N_ "The following package would be removed:~%~{~a~%~}~%"
978                          "The following packages would be removed:~%~{~a~%~}~%"
979                          len)
980                      remove)
981              (format (current-error-port)
982                      (N_ "The following package will be removed:~%~{~a~%~}~%"
983                          "The following packages will be removed:~%~{~a~%~}~%"
984                          len)
985                      remove))))
986       (x #f))
987     (match downgrade
988       (((($ <manifest-entry> name old-version)
989          . ($ <manifest-entry> _ new-version output item)) ..1)
990        (let ((len       (length name))
991              (downgrade (map upgrade-string
992                              name old-version new-version output item)))
993          (if dry-run?
994              (format (current-error-port)
995                      (N_ "The following package would be downgraded:~%~{~a~%~}~%"
996                          "The following packages would be downgraded:~%~{~a~%~}~%"
997                          len)
998                      downgrade)
999              (format (current-error-port)
1000                      (N_ "The following package will be downgraded:~%~{~a~%~}~%"
1001                          "The following packages will be downgraded:~%~{~a~%~}~%"
1002                          len)
1003                      downgrade))))
1004       (x #f))
1005     (match upgrade
1006       (((($ <manifest-entry> name old-version)
1007          . ($ <manifest-entry> _ new-version output item)) ..1)
1008        (let ((len     (length name))
1009              (upgrade (map upgrade-string
1010                            name old-version new-version output item)))
1011          (if dry-run?
1012              (format (current-error-port)
1013                      (N_ "The following package would be upgraded:~%~{~a~%~}~%"
1014                          "The following packages would be upgraded:~%~{~a~%~}~%"
1015                          len)
1016                      upgrade)
1017              (format (current-error-port)
1018                      (N_ "The following package will be upgraded:~%~{~a~%~}~%"
1019                          "The following packages will be upgraded:~%~{~a~%~}~%"
1020                          len)
1021                      upgrade))))
1022       (x #f))
1023     (match install
1024       ((($ <manifest-entry> name version output item _) ..1)
1025        (let ((len     (length name))
1026              (install (package-strings name version output item)))
1027          (if dry-run?
1028              (format (current-error-port)
1029                      (N_ "The following package would be installed:~%~{~a~%~}~%"
1030                          "The following packages would be installed:~%~{~a~%~}~%"
1031                          len)
1032                      install)
1033              (format (current-error-port)
1034                      (N_ "The following package will be installed:~%~{~a~%~}~%"
1035                          "The following packages will be installed:~%~{~a~%~}~%"
1036                          len)
1037                      install))))
1038       (x #f))))
1040 (define-syntax with-error-handling
1041   (syntax-rules ()
1042     "Run BODY within a user-friendly error condition handler."
1043     ((_ body ...)
1044      (call-with-error-handling
1045       (lambda ()
1046         body ...)))))
1048 (define (location->string loc)
1049   "Return a human-friendly, GNU-standard representation of LOC."
1050   (match loc
1051     (#f (G_ "<unknown location>"))
1052     (($ <location> file line column)
1053      (format #f "~a:~a:~a" file line column))))
1055 (define* (fill-paragraph str width #:optional (column 0))
1056   "Fill STR such that each line contains at most WIDTH characters, assuming
1057 that the first character is at COLUMN.
1059 When STR contains a single line break surrounded by other characters, it is
1060 converted to a space; sequences of more than one line break are preserved."
1061   (define (maybe-break chr result)
1062     (match result
1063       ((column newlines chars)
1064        (case chr
1065          ((#\newline)
1066           `(,column ,(+ 1 newlines) ,chars))
1067          (else
1068           (let* ((spaces (if (and (pair? chars) (eqv? (car chars) #\.)) 2 1))
1069                  (chars  (case newlines
1070                            ((0) chars)
1071                            ((1)
1072                             (append (make-list spaces #\space) chars))
1073                            (else
1074                             (append (make-list newlines #\newline) chars))))
1075                  (column (case newlines
1076                            ((0) column)
1077                            ((1) (+ spaces column))
1078                            (else 0))))
1079             (let ((chars  (cons chr chars))
1080                   (column (+ 1 column)))
1081               (if (> column width)
1082                   (let*-values (((before after)
1083                                  (break (cut eqv? #\space <>) chars))
1084                                 ((len)
1085                                  (length before)))
1086                     (if (<= len width)
1087                         `(,len
1088                           0
1089                           ,(if (null? after)
1090                                before
1091                                (append before
1092                                        (cons #\newline
1093                                              (drop-while (cut eqv? #\space <>)
1094                                                          after)))))
1095                         `(,column 0 ,chars)))     ; unbreakable
1096                   `(,column 0 ,chars)))))))))
1098   (match (string-fold maybe-break
1099                       `(,column 0 ())
1100                       str)
1101     ((column newlines chars)
1102      (list->string (reverse chars)))))
1106 ;;; Packages.
1109 (define %text-width
1110   (make-parameter (terminal-columns)))
1112 (set! (@@ (texinfo plain-text) wrap*)
1113       ;; XXX: Monkey patch this private procedure to let 'package->recutils'
1114       ;; parameterize the fill of description field correctly.
1115       (lambda strings
1116         (let ((indent (fluid-ref (@@ (texinfo plain-text) *indent*))))
1117           (fill-string (string-concatenate strings)
1118                        #:line-width (%text-width) #:initial-indent indent
1119                        #:subsequent-indent indent))))
1121 (define (texi->plain-text str)
1122   "Return a plain-text representation of texinfo fragment STR."
1123   ;; 'texi-fragment->stexi' uses a string port so make sure it's a
1124   ;; Unicode-capable one (see <http://bugs.gnu.org/11197>.)
1125   (with-fluids ((%default-port-encoding "UTF-8"))
1126     (stexi->plain-text (texi-fragment->stexi str))))
1128 (define (package-field-string package field-accessor)
1129   "Return a plain-text representation of PACKAGE field."
1130   (and=> (field-accessor package)
1131          (compose texi->plain-text P_)))
1133 (define (package-description-string package)
1134   "Return a plain-text representation of PACKAGE description field."
1135   (package-field-string package package-description))
1137 (define (package-synopsis-string package)
1138   "Return a plain-text representation of PACKAGE synopsis field."
1139   (package-field-string package package-synopsis))
1141 (define (string->recutils str)
1142   "Return a version of STR where newlines have been replaced by newlines
1143 followed by \"+ \", which makes for a valid multi-line field value in the
1144 `recutils' syntax."
1145   (list->string
1146    (string-fold-right (lambda (chr result)
1147                         (if (eqv? chr #\newline)
1148                             (cons* chr #\+ #\space result)
1149                             (cons chr result)))
1150                       '()
1151                       str)))
1153 (define* (package->recutils p port #:optional (width (%text-width))
1154                             #:key (extra-fields '()))
1155   "Write to PORT a `recutils' record of package P, arranging to fit within
1156 WIDTH columns.  EXTRA-FIELDS is a list of symbol/value pairs to emit."
1157   (define width*
1158     ;; The available number of columns once we've taken into account space for
1159     ;; the initial "+ " prefix.
1160     (if (> width 2) (- width 2) width))
1162   (define (dependencies->recutils packages)
1163     (let ((list (string-join (delete-duplicates
1164                               (map package-full-name
1165                                    (sort packages package<?))) " ")))
1166       (string->recutils
1167        (fill-paragraph list width*
1168                        (string-length "dependencies: ")))))
1170   (define (package<? p1 p2)
1171     (string<? (package-full-name p1) (package-full-name p2)))
1173   ;; Note: Don't i18n field names so that people can post-process it.
1174   (format port "name: ~a~%" (package-name p))
1175   (format port "version: ~a~%" (package-version p))
1176   (format port "outputs: ~a~%" (string-join (package-outputs p)))
1177   (format port "systems: ~a~%"
1178           (string-join (package-transitive-supported-systems p)))
1179   (format port "dependencies: ~a~%"
1180           (match (package-direct-inputs p)
1181             (((labels inputs . _) ...)
1182              (dependencies->recutils (filter package? inputs)))))
1183   (format port "location: ~a~%"
1184           (or (and=> (package-location p) location->string)
1185               (G_ "unknown")))
1187   ;; Note: Starting from version 1.6 or recutils, hyphens are not allowed in
1188   ;; field identifiers.
1189   (format port "homepage: ~a~%" (package-home-page p))
1191   (format port "license: ~a~%"
1192           (match (package-license p)
1193             (((? license? licenses) ...)
1194              (string-join (map license-name licenses)
1195                           ", "))
1196             ((? license? license)
1197              (license-name license))
1198             (x
1199              (G_ "unknown"))))
1200   (format port "synopsis: ~a~%"
1201           (string-map (match-lambda
1202                         (#\newline #\space)
1203                         (chr       chr))
1204                       (or (and=> (package-synopsis-string p) P_)
1205                           "")))
1206   (format port "~a~%"
1207           (string->recutils
1208            (string-trim-right
1209             (parameterize ((%text-width width*))
1210               (texi->plain-text
1211                (string-append "description: "
1212                               (or (and=> (package-description p) P_)
1213                                   ""))))
1214             #\newline)))
1215   (for-each (match-lambda
1216               ((field . value)
1217                (let ((field (symbol->string field)))
1218                  (format port "~a: ~a~%"
1219                          field
1220                          (fill-paragraph (object->string value) width*
1221                                          (string-length field))))))
1222             extra-fields)
1223   (newline port))
1225 (define (relevance obj regexps metrics)
1226   "Compute a \"relevance score\" for OBJ as a function of its number of
1227 matches of REGEXPS and accordingly to METRICS.  METRICS is list of
1228 field/weight pairs, where FIELD is a procedure that returns a string
1229 describing OBJ, and WEIGHT is a positive integer denoting the weight of this
1230 field in the final score.
1232 A score of zero means that OBJ does not match any of REGEXPS.  The higher the
1233 score, the more relevant OBJ is to REGEXPS."
1234   (define (score str)
1235     (let ((counts (map (lambda (regexp)
1236                          (match (fold-matches regexp str '() cons)
1237                            (()  0)
1238                            ((m) (if (string=? (match:substring m) str)
1239                                     5              ;exact match
1240                                     1))
1241                            (lst (length lst))))
1242                        regexps)))
1243       ;; Compute a score that's proportional to the number of regexps matched
1244       ;; and to the number of matches for each regexp.
1245       (* (length counts) (reduce + 0 counts))))
1247   (fold (lambda (metric relevance)
1248           (match metric
1249             ((field . weight)
1250              (match (field obj)
1251                (#f  relevance)
1252                (str (+ relevance
1253                        (* (score str) weight)))))))
1254         0
1255         metrics))
1257 (define %package-metrics
1258   ;; Metrics used to compute the "relevance score" of a package against a set
1259   ;; of regexps.
1260   `((,package-name . 4)
1261     (,package-synopsis-string . 3)
1262     (,package-description-string . 2)
1263     (,(lambda (type)
1264         (match (and=> (package-location type) location-file)
1265           ((? string? file) (basename file ".scm"))
1266           (#f "")))
1267      . 1)))
1269 (define (package-relevance package regexps)
1270   "Return a score denoting the relevance of PACKAGE for REGEXPS.  A score of
1271 zero means that PACKAGE does not match any of REGEXPS."
1272   (relevance package regexps %package-metrics))
1274 (define (string->generations str)
1275   "Return the list of generations matching a pattern in STR.  This function
1276 accepts the following patterns: \"1\", \"1,2,3\", \"1..9\", \"1..\", \"..9\"."
1277   (define (maybe-integer)
1278     (let ((x (string->number str)))
1279       (and (integer? x)
1280            x)))
1282   (define (maybe-comma-separated-integers)
1283     (let ((lst (delete-duplicates
1284                 (map string->number
1285                      (string-split str #\,)))))
1286       (and (every integer? lst)
1287            lst)))
1289   (cond ((maybe-integer)
1290          =>
1291          list)
1292         ((maybe-comma-separated-integers)
1293          =>
1294          identity)
1295         ((string-match "^([0-9]+)\\.\\.([0-9]+)$" str)
1296          =>
1297          (lambda (match)
1298            (let ((s (string->number (match:substring match 1)))
1299                  (e (string->number (match:substring match 2))))
1300              (and (every integer? (list s e))
1301                   (<= s e)
1302                   (iota (1+ (- e s)) s)))))
1303         ((string-match "^([0-9]+)\\.\\.$" str)
1304          =>
1305          (lambda (match)
1306            (let ((s (string->number (match:substring match 1))))
1307              (and (integer? s)
1308                   `(>= ,s)))))
1309         ((string-match "^\\.\\.([0-9]+)$" str)
1310          =>
1311          (lambda (match)
1312            (let ((e (string->number (match:substring match 1))))
1313              (and (integer? e)
1314                   `(<= ,e)))))
1315         (else #f)))
1317 (define (string->duration str)
1318   "Return the duration matching a pattern in STR.  This function accepts the
1319 following patterns: \"1d\", \"1w\", \"1m\"."
1320   (define (hours->duration hours match)
1321     (make-time time-duration 0
1322                (* 3600 hours (string->number (match:substring match 1)))))
1324   (cond ((string-match "^([0-9]+)s$" str)
1325          =>
1326          (lambda (match)
1327            (make-time time-duration 0
1328                       (string->number (match:substring match 1)))))
1329         ((string-match "^([0-9]+)h$" str)
1330          =>
1331          (lambda (match)
1332            (hours->duration 1 match)))
1333         ((string-match "^([0-9]+)d$" str)
1334          =>
1335          (lambda (match)
1336            (hours->duration 24 match)))
1337         ((string-match "^([0-9]+)w$" str)
1338          =>
1339          (lambda (match)
1340            (hours->duration (* 24 7) match)))
1341         ((string-match "^([0-9]+)m$" str)
1342          =>
1343          (lambda (match)
1344            (hours->duration (* 24 30) match)))
1345         (else #f)))
1347 (define* (matching-generations str profile
1348                                #:key (duration-relation <=))
1349   "Return the list of available generations matching a pattern in STR.  See
1350 'string->generations' and 'string->duration' for the list of valid patterns.
1351 When STR is a duration pattern, return all the generations whose ctime has
1352 DURATION-RELATION with the current time."
1353   (define (valid-generations lst)
1354     (define (valid-generation? n)
1355       (any (cut = n <>) (generation-numbers profile)))
1357     (fold-right (lambda (x acc)
1358                   (if (valid-generation? x)
1359                       (cons x acc)
1360                       acc))
1361                 '()
1362                 lst))
1364   (define (filter-generations generations)
1365     (match generations
1366       (() '())
1367       (('>= n)
1368        (drop-while (cut > n <>)
1369                    (generation-numbers profile)))
1370       (('<= n)
1371        (valid-generations (iota n 1)))
1372       ((lst ..1)
1373        (valid-generations lst))
1374       (x #f)))
1376   (define (filter-by-duration duration)
1377     (define (time-at-midnight time)
1378       ;; Return TIME at midnight by setting nanoseconds, seconds, minutes, and
1379       ;; hours to zeros.
1380       (let ((d (time-utc->date time)))
1381          (date->time-utc
1382           (make-date 0 0 0 0
1383                      (date-day d) (date-month d)
1384                      (date-year d) (date-zone-offset d)))))
1386     (define generation-ctime-alist
1387       (map (lambda (number)
1388              (cons number
1389                    (time-second
1390                     (time-at-midnight
1391                      (generation-time profile number)))))
1392            (generation-numbers profile)))
1394     (match duration
1395       (#f #f)
1396       (res
1397        (let ((s (time-second
1398                  (subtract-duration (time-at-midnight (current-time))
1399                                     duration))))
1400          (delete #f (map (lambda (x)
1401                            (and (duration-relation s (cdr x))
1402                                 (first x)))
1403                          generation-ctime-alist))))))
1405   (cond ((string->generations str)
1406          =>
1407          filter-generations)
1408         ((string->duration str)
1409          =>
1410          filter-by-duration)
1411         (else #f)))
1413 (define (display-generation profile number)
1414   "Display a one-line summary of generation NUMBER of PROFILE."
1415   (unless (zero? number)
1416     (let ((header (format #f (G_ "Generation ~a\t~a") number
1417                           (date->string
1418                            (time-utc->date
1419                             (generation-time profile number))
1420                            ;; TRANSLATORS: This is a format-string for date->string.
1421                            ;; Please choose a format that corresponds to the
1422                            ;; usual way of presenting dates in your locale.
1423                            ;; See https://www.gnu.org/software/guile/manual/html_node/SRFI_002d19-Date-to-string.html
1424                            ;; for details.
1425                            (G_ "~b ~d ~Y ~T"))))
1426           (current (generation-number profile)))
1427       (if (= number current)
1428           ;; TRANSLATORS: The word "current" here is an adjective for
1429           ;; "Generation", as in "current generation".  Use the appropriate
1430           ;; gender where applicable.
1431           (format #t (G_ "~a\t(current)~%") header)
1432           (format #t "~a~%" header)))))
1434 (define (display-profile-content-diff profile gen1 gen2)
1435   "Display the changed packages in PROFILE GEN2 compared to generation GEN1."
1437   (define (equal-entry? first second)
1438     (string= (manifest-entry-item first) (manifest-entry-item second)))
1440   (define (display-entry entry prefix)
1441     (match entry
1442       (($ <manifest-entry> name version output location _)
1443        (format #t " ~a ~a\t~a\t~a\t~a~%" prefix name version output location))))
1445   (define (list-entries number)
1446     (manifest-entries (profile-manifest (generation-file-name profile number))))
1448   (define (display-diff profile old new)
1449     (display-generation profile new)
1450     (let ((added (lset-difference
1451                   equal-entry? (list-entries new) (list-entries old)))
1452           (removed (lset-difference
1453                     equal-entry? (list-entries old) (list-entries new))))
1454       (for-each (cut display-entry <> "+") added)
1455       (for-each (cut display-entry <> "-") removed)
1456       (newline)))
1458   (display-diff profile gen1 gen2))
1460 (define (display-profile-content profile number)
1461   "Display the packages in PROFILE, generation NUMBER, in a human-readable
1462 way."
1463   (for-each (match-lambda
1464               (($ <manifest-entry> name version output location _)
1465                (format #t "  ~a\t~a\t~a\t~a~%"
1466                        name version output location)))
1468             ;; Show most recently installed packages last.
1469             (reverse
1470              (manifest-entries
1471               (profile-manifest (generation-file-name profile number))))))
1473 (define (display-generation-change previous current)
1474   (format #t (G_ "switched from generation ~a to ~a~%") previous current))
1476 (define (roll-back* store profile)
1477   "Like 'roll-back', but display what is happening."
1478   (call-with-values
1479       (lambda ()
1480         (roll-back store profile))
1481     display-generation-change))
1483 (define (switch-to-generation* profile number)
1484   "Like 'switch-generation', but display what is happening."
1485   (let ((previous (switch-to-generation profile number)))
1486     (display-generation-change previous number)))
1488 (define (delete-generation* store profile generation)
1489   "Like 'delete-generation', but display what is going on."
1490   (format #t (G_ "deleting ~a~%")
1491           (generation-file-name profile generation))
1492   (delete-generation store profile generation))
1494 (define* (package-specification->name+version+output spec
1495                                                      #:optional (output "out"))
1496   "Parse package specification SPEC and return three value: the specified
1497 package name, version number (or #f), and output name (or OUTPUT).  SPEC may
1498 optionally contain a version number and an output name, as in these examples:
1500   guile
1501   guile@2.0.9
1502   guile:debug
1503   guile@2.0.9:debug
1505   (let*-values (((name sub-drv)
1506                  (match (string-rindex spec #\:)
1507                    (#f    (values spec output))
1508                    (colon (values (substring spec 0 colon)
1509                                   (substring spec (+ 1 colon))))))
1510                 ((name version)
1511                  (package-name->name+version name)))
1512     (values name version sub-drv)))
1516 ;;; Command-line option processing.
1519 (define (show-guix-usage)
1520   (format (current-error-port)
1521           (G_ "Try `guix --help' for more information.~%"))
1522   (exit 1))
1524 (define (command-files)
1525   "Return the list of source files that define Guix sub-commands."
1526   (define directory
1527     (and=> (search-path %load-path "guix.scm")
1528            (compose (cut string-append <> "/guix/scripts")
1529                     dirname)))
1531   (define dot-scm?
1532     (cut string-suffix? ".scm" <>))
1534   (if directory
1535       (scandir directory dot-scm?)
1536       '()))
1538 (define (commands)
1539   "Return the list of Guix command names."
1540   (map (compose (cut string-drop-right <> 4)
1541                 basename)
1542        (command-files)))
1544 (define (show-guix-help)
1545   (define (internal? command)
1546     (member command '("substitute" "authenticate" "offload"
1547                       "perform-download")))
1549   (format #t (G_ "Usage: guix COMMAND ARGS...
1550 Run COMMAND with ARGS.\n"))
1551   (newline)
1552   (format #t (G_ "COMMAND must be one of the sub-commands listed below:\n"))
1553   (newline)
1554   ;; TODO: Display a synopsis of each command.
1555   (format #t "~{   ~a~%~}" (sort (remove internal? (commands))
1556                                  string<?))
1557   (show-bug-report-information))
1559 (define program-name
1560   ;; Name of the command-line program currently executing, or #f.
1561   (make-parameter #f))
1563 (define (run-guix-command command . args)
1564   "Run COMMAND with the given ARGS.  Report an error when COMMAND is not
1565 found."
1566   (define module
1567     (catch 'misc-error
1568       (lambda ()
1569         (resolve-interface `(guix scripts ,command)))
1570       (lambda -
1571         (format (current-error-port)
1572                 (G_ "guix: ~a: command not found~%") command)
1573         (show-guix-usage))))
1575   (let ((command-main (module-ref module
1576                                   (symbol-append 'guix- command))))
1577     (parameterize ((program-name command))
1578       ;; Disable canonicalization so we don't don't stat unreasonably.
1579       (with-fluids ((%file-port-name-canonicalization #f))
1580         (dynamic-wind
1581           (const #f)
1582           (lambda ()
1583             (apply command-main args))
1584           (lambda ()
1585             ;; Abuse 'exit-hook' (which is normally meant to be used by the
1586             ;; REPL) to run things like profiling hooks upon completion.
1587             (run-hook exit-hook)))))))
1589 (define (run-guix . args)
1590   "Run the 'guix' command defined by command line ARGS.
1591 Unlike 'guix-main', this procedure assumes that locale, i18n support,
1592 and signal handling has already been set up."
1593   (define option? (cut string-prefix? "-" <>))
1595   ;; The default %LOAD-EXTENSIONS includes the empty string, which doubles the
1596   ;; number of 'stat' calls per entry in %LOAD-PATH.  Shamelessly remove it.
1597   (set! %load-extensions '(".scm"))
1599   (match args
1600     (()
1601      (format (current-error-port)
1602              (G_ "guix: missing command name~%"))
1603      (show-guix-usage))
1604     ((or ("-h") ("--help"))
1605      (show-guix-help))
1606     ((or ("-V") ("--version"))
1607      (show-version-and-exit "guix"))
1608     (((? option? o) args ...)
1609      (format (current-error-port)
1610              (G_ "guix: unrecognized option '~a'~%") o)
1611      (show-guix-usage))
1612     (("help" command)
1613      (apply run-guix-command (string->symbol command)
1614             '("--help")))
1615     (("help" args ...)
1616      (show-guix-help))
1617     ((command args ...)
1618      (apply run-guix-command
1619             (string->symbol command)
1620             args))))
1622 (define guix-warning-port
1623   (make-parameter (current-warning-port)))
1625 (define (guix-main arg0 . args)
1626   (initialize-guix)
1627   (apply run-guix args))
1629 (define color-table
1630   `((CLEAR       .   "0")
1631     (RESET       .   "0")
1632     (BOLD        .   "1")
1633     (DARK        .   "2")
1634     (UNDERLINE   .   "4")
1635     (UNDERSCORE  .   "4")
1636     (BLINK       .   "5")
1637     (REVERSE     .   "6")
1638     (CONCEALED   .   "8")
1639     (BLACK       .  "30")
1640     (RED         .  "31")
1641     (GREEN       .  "32")
1642     (YELLOW      .  "33")
1643     (BLUE        .  "34")
1644     (MAGENTA     .  "35")
1645     (CYAN        .  "36")
1646     (WHITE       .  "37")
1647     (ON-BLACK    .  "40")
1648     (ON-RED      .  "41")
1649     (ON-GREEN    .  "42")
1650     (ON-YELLOW   .  "43")
1651     (ON-BLUE     .  "44")
1652     (ON-MAGENTA  .  "45")
1653     (ON-CYAN     .  "46")
1654     (ON-WHITE    .  "47")))
1656 (define (color . lst)
1657   "Return a string containing the ANSI escape sequence for producing the
1658 requested set of attributes in LST.  Unknown attributes are ignored."
1659   (let ((color-list
1660          (remove not
1661                  (map (lambda (color) (assq-ref color-table color))
1662                       lst))))
1663     (if (null? color-list)
1664         ""
1665         (string-append
1666          (string #\esc #\[)
1667          (string-join color-list ";" 'infix)
1668          "m"))))
1670 (define (colorize-string str . color-list)
1671   "Return a copy of STR colorized using ANSI escape sequences according to the
1672 attributes STR.  At the end of the returned string, the color attributes will
1673 be reset such that subsequent output will not have any colors in effect."
1674   (string-append
1675    (apply color color-list)
1676    str
1677    (color 'RESET)))
1679 ;;; ui.scm ends here