ui: Tweak conflicting profile entry error message.
[guix.git] / guix / ui.scm
blobe40fe576ba08810111acef9c06cfba9a3ba526e8
1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2012, 2013, 2014, 2015, 2016, 2017 Ludovic Courtès <ludo@gnu.org>
3 ;;; Copyright © 2013 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 ;;;
13 ;;; This file is part of GNU Guix.
14 ;;;
15 ;;; GNU Guix is free software; you can redistribute it and/or modify it
16 ;;; under the terms of the GNU General Public License as published by
17 ;;; the Free Software Foundation; either version 3 of the License, or (at
18 ;;; your option) any later version.
19 ;;;
20 ;;; GNU Guix is distributed in the hope that it will be useful, but
21 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
22 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23 ;;; GNU General Public License for more details.
24 ;;;
25 ;;; You should have received a copy of the GNU General Public License
26 ;;; along with GNU Guix.  If not, see <http://www.gnu.org/licenses/>.
28 (define-module (guix ui)
29   #:use-module (guix i18n)
30   #:use-module (guix gexp)
31   #:use-module (guix sets)
32   #:use-module (guix utils)
33   #:use-module (guix store)
34   #:use-module (guix config)
35   #:use-module (guix packages)
36   #:use-module (guix profiles)
37   #:use-module (guix derivations)
38   #:use-module (guix combinators)
39   #:use-module (guix build-system)
40   #:use-module (guix serialization)
41   #:use-module ((guix licenses) #:select (license? license-name))
42   #:use-module ((guix build syscalls)
43                 #:select (free-disk-space terminal-columns))
44   #:use-module (srfi srfi-1)
45   #:use-module (srfi srfi-11)
46   #:use-module (srfi srfi-19)
47   #:use-module (srfi srfi-26)
48   #:use-module (srfi srfi-31)
49   #:use-module (srfi srfi-34)
50   #:use-module (srfi srfi-35)
51   #:autoload   (ice-9 ftw)  (scandir)
52   #:use-module (ice-9 match)
53   #:use-module (ice-9 format)
54   #:use-module (ice-9 regex)
55   #:autoload   (system repl repl)  (start-repl)
56   #:autoload   (system repl debug) (make-debug stack->vector)
57   #:use-module (texinfo)
58   #:use-module (texinfo plain-text)
59   #:use-module (texinfo string-utils)
60   #:re-export (G_ N_ P_)                          ;backward compatibility
61   #:export (report-error
62             leave
63             make-user-module
64             load*
65             warn-about-load-error
66             show-version-and-exit
67             show-bug-report-information
68             make-regexp*
69             string->number*
70             size->number
71             show-derivation-outputs
72             show-what-to-build
73             show-what-to-build*
74             show-manifest-transaction
75             call-with-error-handling
76             with-error-handling
77             leave-on-EPIPE
78             read/eval
79             read/eval-package-expression
80             location->string
81             fill-paragraph
82             %text-width
83             texi->plain-text
84             package-description-string
85             package-synopsis-string
86             string->recutils
87             package->recutils
88             package-specification->name+version+output
89             relevance
90             package-relevance
91             string->generations
92             string->duration
93             matching-generations
94             display-generation
95             display-profile-content
96             display-profile-content-diff
97             roll-back*
98             switch-to-generation*
99             delete-generation*
100             run-guix-command
101             run-guix
102             program-name
103             guix-warning-port
104             warning
105             info
106             guix-main))
108 ;;; Commentary:
110 ;;; User interface facilities for command-line tools.
112 ;;; Code:
114 (define-syntax-rule (define-diagnostic name prefix)
115   "Create a diagnostic macro (i.e., NAME), which will prepend PREFIX to all
116 messages."
117   (define-syntax name
118     (lambda (x)
119       (define (augmented-format-string fmt)
120         (string-append "~:[~*~;guix ~a: ~]~a" (syntax->datum fmt)))
122       (syntax-case x ()
123         ((name (underscore fmt) args (... ...))
124          (and (string? (syntax->datum #'fmt))
125               (free-identifier=? #'underscore #'G_))
126          (with-syntax ((fmt*   (augmented-format-string #'fmt))
127                        (prefix (datum->syntax x prefix)))
128            #'(format (guix-warning-port) (gettext fmt*)
129                      (program-name) (program-name) prefix
130                      args (... ...))))
131         ((name (N-underscore singular plural n) args (... ...))
132          (and (string? (syntax->datum #'singular))
133               (string? (syntax->datum #'plural))
134               (free-identifier=? #'N-underscore #'N_))
135          (with-syntax ((s      (augmented-format-string #'singular))
136                        (p      (augmented-format-string #'plural))
137                        (prefix (datum->syntax x prefix)))
138            #'(format (guix-warning-port)
139                      (ngettext s p n %gettext-domain)
140                      (program-name) (program-name) prefix
141                      args (... ...))))))))
143 (define-diagnostic warning "warning: ") ; emit a warning
144 (define-diagnostic info "")
146 (define-diagnostic report-error "error: ")
147 (define-syntax-rule (leave args ...)
148   "Emit an error message and exit."
149   (begin
150     (report-error args ...)
151     (exit 1)))
153 (define (print-unbound-variable-error port key args default-printer)
154   ;; Print unbound variable errors more nicely, and in the right language.
155   (match args
156     ((proc message (variable) _ ...)
157      ;; We can always omit PROC because when it's useful (i.e., different from
158      ;; "module-lookup"), it gets displayed before.
159      (format port (G_ "~a: unbound variable") variable))
160     (_
161      (default-printer))))
163 (set-exception-printer! 'unbound-variable print-unbound-variable-error)
165 (define (make-user-module modules)
166   "Return a new user module with the additional MODULES loaded."
167   ;; Module in which the machine description file is loaded.
168   (let ((module (make-fresh-user-module)))
169     (for-each (lambda (iface)
170                 (module-use! module (resolve-interface iface)))
171               modules)
172     module))
174 (define* (load* file user-module
175                 #:key (on-error 'nothing-special))
176   "Load the user provided Scheme source code FILE."
177   (define (frame-with-source frame)
178     ;; Walk from FRAME upwards until source location information is found.
179     (let loop ((frame    frame)
180                (previous frame))
181       (if (not frame)
182           previous
183           (if (frame-source frame)
184               frame
185               (loop (frame-previous frame) frame)))))
187   (define (error-string frame args)
188     (call-with-output-string
189      (lambda (port)
190        (apply display-error frame port (cdr args)))))
192   (define tag
193     (make-prompt-tag "user-code"))
195   (catch #t
196     (lambda ()
197       ;; XXX: Force a recompilation to avoid ABI issues.
198       ;; (set! %fresh-auto-compile #t)
199       (set! %load-should-auto-compile #t)
201       (save-module-excursion
202        (lambda ()
203          (set-current-module user-module)
205          ;; Hide the "auto-compiling" messages.
206          (parameterize ((current-warning-port (%make-void-port "w")))
207            (call-with-prompt tag
208              (lambda ()
209                ;; Give 'load' an absolute file name so that it doesn't try to
210                ;; search for FILE in %LOAD-PATH.  Note: use 'load', not
211                ;; 'primitive-load', so that FILE is compiled, which then allows us
212                ;; to provide better error reporting with source line numbers.
213                (load (canonicalize-path file)))
214              (const #f))))))
215     (lambda _
216       ;; XXX: Errors are reported from the pre-unwind handler below, but
217       ;; calling 'exit' from there has no effect, so we call it here.
218       (exit 1))
219     (rec (handle-error . args)
220          ;; Capture the stack up to this procedure call, excluded, and pass
221          ;; the faulty stack frame to 'report-load-error'.
222          (let* ((stack (make-stack #t handle-error tag))
223                 (depth (stack-length stack))
224                 (last  (and (> depth 0) (stack-ref stack 0)))
225                 (frame (frame-with-source
226                         (if (> depth 1)
227                             (stack-ref stack 1)   ;skip the 'throw' frame
228                             last))))
230            (report-load-error file args frame)
232            (case on-error
233              ((debug)
234               (newline)
235               (display (G_ "entering debugger; type ',bt' for a backtrace\n"))
236               (start-repl #:debug (make-debug (stack->vector stack) 0
237                                               (error-string frame args)
238                                               #f)))
239              ((backtrace)
240               (newline (current-error-port))
241               (display-backtrace stack (current-error-port)))
242              (else
243               #t))))))
245 (define (known-variable-definition variable)
246   "Search among the currently loaded modules one that defines a variable named
247 VARIABLE and return it, or #f if none was found."
248   (define (module<? m1 m2)
249     (match (module-name m2)
250       (('gnu _ ...) #t)
251       (('guix _ ...)
252        (match (module-name m1)
253          (('gnu _ ...) #f)
254          (_ #t)))
255       (_ #f)))
257   (let loop ((modules     (list (resolve-module '() #f #f #:ensure #f)))
258              (suggestions '())
259              (visited     (setq)))
260     (match modules
261       (()
262        ;; Pick the "best" suggestion.
263        (match (sort suggestions module<?)
264          (() #f)
265          ((first _ ...) first)))
266       ((head tail ...)
267        (if (set-contains? visited head)
268            (loop tail suggestions visited)
269            (let ((visited (set-insert head visited))
270                  (next    (append tail
271                                   (hash-map->list (lambda (name module)
272                                                     module)
273                                                   (module-submodules head)))))
274              (match (module-local-variable head variable)
275                (#f (loop next suggestions visited))
276                (_
277                 (match (module-name head)
278                   (('gnu _ ...) head)             ;must be that one
279                   (_ (loop next (cons head suggestions) visited)))))))))))
281 (define* (display-hint message #:optional (port (current-error-port)))
282   "Display MESSAGE, a l10n message possibly containing Texinfo markup, to
283 PORT."
284   (format port (G_ "hint: ~a~%")
285           (fill-paragraph (texi->plain-text message)
286                           (terminal-columns) 8)))
288 (define* (report-load-error file args #:optional frame)
289   "Report the failure to load FILE, a user-provided Scheme file.
290 ARGS is the list of arguments received by the 'throw' handler."
291   (match args
292     (('system-error . rest)
293      (let ((err (system-error-errno args)))
294        (report-error (G_ "failed to load '~a': ~a~%") file (strerror err))))
295     (('read-error "scm_i_lreadparen" message _ ...)
296      ;; Guile's missing-paren messages are obscure so we make them more
297      ;; intelligible here.
298      (if (string-suffix? "end of file" message)
299          (let ((location (string-drop-right message
300                                             (string-length "end of file"))))
301            (format (current-error-port) (G_ "~amissing closing parenthesis~%")
302                    location))
303          (apply throw args)))
304     (('syntax-error proc message properties form . rest)
305      (let ((loc (source-properties->location properties)))
306        (format (current-error-port) (G_ "~a: error: ~a~%")
307                (location->string loc) message)))
308     (('unbound-variable proc message (variable) _ ...)
309      (match args
310        ((key . args)
311         (print-exception (current-error-port) frame key args)))
312      (match (known-variable-definition variable)
313        (#f
314         (display-hint (G_ "Did you forget a @code{use-modules} form?")))
315        (module
316         (display-hint (format #f (G_ "Did you forget @code{(use-modules ~a)}?")
317                               (module-name module))))))
318     (('srfi-34 obj)
319      (if (message-condition? obj)
320          (if (error-location? obj)
321              (format (current-error-port)
322                      (G_ "~a: error: ~a~%")
323                      (location->string (error-location obj))
324                      (gettext (condition-message obj)
325                               %gettext-domain))
326              (report-error (G_ "~a~%")
327                            (gettext (condition-message obj)
328                                     %gettext-domain)))
329          (report-error (G_ "exception thrown: ~s~%") obj))
330      (when (fix-hint? obj)
331        (display-hint (condition-fix-hint obj))))
332     ((error args ...)
333      (report-error (G_ "failed to load '~a':~%") file)
334      (apply display-error frame (current-error-port) args))))
336 (define (warn-about-load-error file args)         ;FIXME: factorize with ↑
337   "Report the failure to load FILE, a user-provided Scheme file, without
338 exiting.  ARGS is the list of arguments received by the 'throw' handler."
339   (match args
340     (('system-error . rest)
341      (let ((err (system-error-errno args)))
342        (warning (G_ "failed to load '~a': ~a~%") file (strerror err))))
343     (('syntax-error proc message properties form . rest)
344      (let ((loc (source-properties->location properties)))
345        (format (current-error-port) (G_ "~a: warning: ~a~%")
346                (location->string loc) message)))
347     (('srfi-34 obj)
348      (if (message-condition? obj)
349          (warning (G_ "failed to load '~a': ~a~%")
350                   file
351                   (gettext (condition-message obj) %gettext-domain))
352          (warning (G_ "failed to load '~a': exception thrown: ~s~%")
353                   file obj)))
354     ((error args ...)
355      (warning (G_ "failed to load '~a':~%") file)
356      (apply display-error #f (current-error-port) args))))
358 (define (install-locale)
359   "Install the current locale settings."
360   (catch 'system-error
361     (lambda _
362       (setlocale LC_ALL ""))
363     (lambda args
364       (warning (G_ "failed to install locale: ~a~%")
365                (strerror (system-error-errno args))))))
367 (define (initialize-guix)
368   "Perform the usual initialization for stand-alone Guix commands."
369   ;; By default don't annoy users with deprecation warnings.  In practice,
370   ;; 'define-deprecated' in (ice-9 deprecated) arranges so that those warnings
371   ;; are emitted at expansion-time only, but there are cases where they could
372   ;; slip through, for instance when interpreting code.
373   (unless (getenv "GUILE_WARN_DEPRECATED")
374     (debug-disable 'warn-deprecated))
376   (install-locale)
377   (textdomain %gettext-domain)
379   ;; Ignore SIGPIPE.  If the daemon closes the connection, we prefer to be
380   ;; notified via an EPIPE later.
381   (sigaction SIGPIPE SIG_IGN)
383   (setvbuf (current-output-port) _IOLBF)
384   (setvbuf (current-error-port) _IOLBF))
386 (define* (show-version-and-exit #:optional (command (car (command-line))))
387   "Display version information for COMMAND and `(exit 0)'."
388   (simple-format #t "~a (~a) ~a~%"
389                  command %guix-package-name %guix-version)
390   (format #t "Copyright ~a 2017 ~a"
391           ;; TRANSLATORS: Translate "(C)" to the copyright symbol
392           ;; (C-in-a-circle), if this symbol is available in the user's
393           ;; locale.  Otherwise, do not translate "(C)"; leave it as-is.  */
394           (G_ "(C)")
395           (G_ "the Guix authors\n"))
396   (display (G_"\
397 License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
398 This is free software: you are free to change and redistribute it.
399 There is NO WARRANTY, to the extent permitted by law.
401   (exit 0))
403 (define (show-bug-report-information)
404   ;; TRANSLATORS: The placeholder indicates the bug-reporting address for this
405   ;; package.  Please add another line saying "Report translation bugs to
406   ;; ...\n" with the address for translation bugs (typically your translation
407   ;; team's web or email address).
408   (format #t (G_ "
409 Report bugs to: ~a.") %guix-bug-report-address)
410   (format #t (G_ "
411 ~a home page: <~a>") %guix-package-name %guix-home-page-url)
412   (display (G_ "
413 General help using GNU software: <http://www.gnu.org/gethelp/>"))
414   (newline))
416 (define (augmented-system-error-handler file)
417   "Return a 'system-error' handler that mentions FILE in its message."
418   (lambda (key proc fmt args errno)
419     ;; Augment the FMT and ARGS with information about TARGET (this
420     ;; information is missing as of Guile 2.0.11, making the exception
421     ;; uninformative.)
422     (apply throw key proc "~A: ~S"
423            (list (strerror (car errno)) file)
424            (list errno))))
426 (define-syntax-rule (error-reporting-wrapper proc (args ...) file)
427   "Wrap PROC such that its 'system-error' exceptions are augmented to mention
428 FILE."
429   (let ((real-proc (@ (guile) proc)))
430     (lambda (args ...)
431       (catch 'system-error
432         (lambda ()
433           (real-proc args ...))
434         (augmented-system-error-handler file)))))
436 (set! symlink
437   ;; We 'set!' the global binding because (gnu build ...) modules and similar
438   ;; typically don't use (guix ui).
439   (error-reporting-wrapper symlink (source target) target))
441 (set! copy-file
442   ;; Note: here we use 'set!', not #:replace, because UIs typically use
443   ;; 'copy-recursively', which doesn't use (guix ui).
444   (error-reporting-wrapper copy-file (source target) target))
446 (set! canonicalize-path
447   (error-reporting-wrapper canonicalize-path (file) file))
450 (define (make-regexp* regexp . flags)
451   "Like 'make-regexp' but error out if REGEXP is invalid, reporting the error
452 nicely."
453   (catch 'regular-expression-syntax
454     (lambda ()
455       (apply make-regexp regexp flags))
456     (lambda (key proc message . rest)
457       (leave (G_ "'~a' is not a valid regular expression: ~a~%")
458              regexp message))))
460 (define (string->number* str)
461   "Like `string->number', but error out with an error message on failure."
462   (or (string->number str)
463       (leave (G_ "~a: invalid number~%") str)))
465 (define (size->number str)
466   "Convert STR, a storage measurement representation such as \"1024\" or
467 \"1MiB\", to a number of bytes.  Raise an error if STR could not be
468 interpreted."
469   (define unit-pos
470     (string-rindex str char-set:digit))
472   (define unit
473     (and unit-pos (substring str (+ 1 unit-pos))))
475   (let* ((numstr (if unit-pos
476                      (substring str 0 (+ 1 unit-pos))
477                      str))
478          (num    (string->number numstr)))
479     (unless num
480       (leave (G_ "invalid number: ~a~%") numstr))
482     ((compose inexact->exact round)
483      (* num
484         (match unit
485           ((or "KiB" "K" "k") (expt 2 10))
486           ((or "MiB" "M")     (expt 2 20))
487           ((or "GiB" "G")     (expt 2 30))
488           ((or "TiB" "T")     (expt 2 40))
489           ((or "PiB" "P")     (expt 2 50))
490           ((or "EiB" "E")     (expt 2 60))
491           ((or "ZiB" "Z")     (expt 2 70))
492           ((or "YiB" "Y")     (expt 2 80))
493           ("kB"  (expt 10 3))
494           ("MB"  (expt 10 6))
495           ("GB"  (expt 10 9))
496           ("TB"  (expt 10 12))
497           ("PB"  (expt 10 15))
498           ("EB"  (expt 10 18))
499           ("ZB"  (expt 10 21))
500           ("YB"  (expt 10 24))
501           (""    1)
502           (x
503            (leave (G_ "unknown unit: ~a~%") unit)))))))
505 (define (call-with-error-handling thunk)
506   "Call THUNK within a user-friendly error handler."
507   (define (port-filename* port)
508     ;; 'port-filename' returns #f for non-file ports, but it raises an
509     ;; exception for file ports that are closed.  Work around that.
510     (and (not (port-closed? port))
511          (port-filename port)))
513   (guard (c ((package-input-error? c)
514              (let* ((package  (package-error-package c))
515                     (input    (package-error-invalid-input c))
516                     (location (package-location package))
517                     (file     (location-file location))
518                     (line     (location-line location))
519                     (column   (location-column location)))
520                (leave (G_ "~a:~a:~a: package `~a' has an invalid input: ~s~%")
521                       file line column
522                       (package-full-name package) input)))
523             ((package-cross-build-system-error? c)
524              (let* ((package (package-error-package c))
525                     (loc     (package-location package))
526                     (system  (package-build-system package)))
527                (leave (G_ "~a: ~a: build system `~a' does not support cross builds~%")
528                       (location->string loc)
529                       (package-full-name package)
530                       (build-system-name system))))
531             ((gexp-input-error? c)
532              (let ((input (package-error-invalid-input c)))
533                (leave (G_ "~s: invalid G-expression input~%")
534                       (gexp-error-invalid-input c))))
535             ((profile-not-found-error? c)
536              (leave (G_ "profile '~a' does not exist~%")
537                     (profile-error-profile c)))
538             ((missing-generation-error? c)
539              (leave (G_ "generation ~a of profile '~a' does not exist~%")
540                     (missing-generation-error-generation c)
541                     (profile-error-profile c)))
542             ((profile-collision-error? c)
543              (let ((entry    (profile-collision-error-entry c))
544                    (conflict (profile-collision-error-conflict c)))
545                (define (report-parent-entries entry)
546                  (let ((parent (force (manifest-entry-parent entry))))
547                    (when (manifest-entry? parent)
548                      (report-error (G_ "   ... propagated from ~a@~a~%")
549                                    (manifest-entry-name parent)
550                                    (manifest-entry-version parent))
551                      (report-parent-entries parent))))
553                (define (manifest-entry-output* entry)
554                  (match (manifest-entry-output entry)
555                    ("out"   "")
556                    (output (string-append ":" output))))
558                (report-error (G_ "profile contains conflicting entries for ~a~a~%")
559                              (manifest-entry-name entry)
560                              (manifest-entry-output* entry))
561                (report-error (G_ "  first entry: ~a@~a~a ~a~%")
562                              (manifest-entry-name entry)
563                              (manifest-entry-version entry)
564                              (manifest-entry-output* entry)
565                              (manifest-entry-item entry))
566                (report-parent-entries entry)
567                (report-error (G_ "  second entry: ~a@~a~a ~a~%")
568                              (manifest-entry-name conflict)
569                              (manifest-entry-version conflict)
570                              (manifest-entry-output* conflict)
571                              (manifest-entry-item conflict))
572                (report-parent-entries conflict)
573                (exit 1)))
574             ((nar-error? c)
575              (let ((file (nar-error-file c))
576                    (port (nar-error-port c)))
577                (if file
578                    (leave (G_ "corrupt input while restoring '~a' from ~s~%")
579                           file (or (port-filename* port) port))
580                    (leave (G_ "corrupt input while restoring archive from ~s~%")
581                           (or (port-filename* port) port)))))
582             ((nix-connection-error? c)
583              (leave (G_ "failed to connect to `~a': ~a~%")
584                     (nix-connection-error-file c)
585                     (strerror (nix-connection-error-code c))))
586             ((nix-protocol-error? c)
587              ;; FIXME: Server-provided error messages aren't i18n'd.
588              (leave (G_ "build failed: ~a~%")
589                     (nix-protocol-error-message c)))
590             ((derivation-missing-output-error? c)
591              (leave (G_ "reference to invalid output '~a' of derivation '~a'~%")
592                     (derivation-missing-output c)
593                     (derivation-file-name (derivation-error-derivation c))))
594             ((file-search-error? c)
595              (leave (G_ "file '~a' could not be found in these \
596 directories:~{ ~a~}~%")
597                     (file-search-error-file-name c)
598                     (file-search-error-search-path c)))
599             ((and (error-location? c) (message-condition? c))
600              (format (current-error-port)
601                      (G_ "~a: error: ~a~%")
602                      (location->string (error-location c))
603                      (gettext (condition-message c) %gettext-domain)))
604             ((message-condition? c)
605              ;; Normally '&message' error conditions have an i18n'd message.
606              (leave (G_ "~a~%")
607                     (gettext (condition-message c) %gettext-domain))))
608     ;; Catch EPIPE and the likes.
609     (catch 'system-error
610       thunk
611       (lambda (key proc format-string format-args . rest)
612         (leave (G_ "~a: ~a~%") proc
613                (apply format #f format-string format-args))))))
615 (define-syntax-rule (leave-on-EPIPE exp ...)
616   "Run EXP... in a context when EPIPE errors are caught and lead to 'exit'
617 with successful exit code.  This is useful when writing to the standard output
618 may lead to EPIPE, because the standard output is piped through 'head' or
619 similar."
620   (catch 'system-error
621     (lambda ()
622       exp ...)
623     (lambda args
624       ;; We really have to exit this brutally, otherwise Guile eventually
625       ;; attempts to flush all the ports, leading to an uncaught EPIPE down
626       ;; the path.
627       (if (= EPIPE (system-error-errno args))
628           (primitive-_exit 0)
629           (apply throw args)))))
631 (define %guix-user-module
632   ;; Module in which user expressions are evaluated.
633   ;; Compute lazily to avoid circularity with (guix gexp).
634   (delay
635     (let ((module (make-module)))
636       (beautify-user-module! module)
637       ;; Use (guix gexp) so that one can use #~ & co.
638       (module-use! module (resolve-interface '(guix gexp)))
639       module)))
641 (define (read/eval str)
642   "Read and evaluate STR, raising an error if something goes wrong."
643   (let ((exp (catch #t
644                (lambda ()
645                  (call-with-input-string str read))
646                (lambda args
647                  (leave (G_ "failed to read expression ~s: ~s~%")
648                         str args)))))
649     (catch #t
650       (lambda ()
651         (eval exp (force %guix-user-module)))
652       (lambda args
653         (report-error (G_ "failed to evaluate expression '~a':~%") exp)
654         (match args
655           (('syntax-error proc message properties form . rest)
656            (report-error (G_ "syntax error: ~a~%") message))
657           (('srfi-34 obj)
658            (if (message-condition? obj)
659                (report-error (G_ "~a~%")
660                              (gettext (condition-message obj)
661                                       %gettext-domain))
662                (report-error (G_ "exception thrown: ~s~%") obj)))
663           ((error args ...)
664            (apply display-error #f (current-error-port) args))
665           (what? #f))
666         (exit 1)))))
668 (define (read/eval-package-expression str)
669   "Read and evaluate STR and return the package it refers to, or exit an
670 error."
671   (match (read/eval str)
672     ((? package? p) p)
673     (x
674      (leave (G_ "expression ~s does not evaluate to a package~%")
675             str))))
677 (define (show-derivation-outputs derivation)
678   "Show the output file names of DERIVATION."
679   (format #t "~{~a~%~}"
680           (map (match-lambda
681                  ((out-name . out)
682                   (derivation->output-path derivation out-name)))
683                (derivation-outputs derivation))))
685 (define (check-available-space need)
686   "Make sure at least NEED bytes are available in the store.  Otherwise emit a
687 warning."
688   (let ((free (catch 'system-error
689                 (lambda ()
690                   (free-disk-space (%store-prefix)))
691                 (const #f))))
692     (when (and free (>= need free))
693       (warning (G_ "at least ~,1h MB needed but only ~,1h MB available in ~a~%")
694                (/ need 1e6) (/ free 1e6) (%store-prefix)))))
696 (define* (show-what-to-build store drv
697                              #:key dry-run? (use-substitutes? #t)
698                              (mode (build-mode normal)))
699   "Show what will or would (depending on DRY-RUN?) be built in realizing the
700 derivations listed in DRV using MODE, a 'build-mode' value.  Return #t if
701 there's something to build, #f otherwise.  When USE-SUBSTITUTES?, check and
702 report what is prerequisites are available for download."
703   (define substitutable-info
704     ;; Call 'substitutation-oracle' upfront so we don't end up launching the
705     ;; substituter many times.  This makes a big difference, especially when
706     ;; DRV is a long list as is the case with 'guix environment'.
707     (if use-substitutes?
708         (substitution-oracle store drv #:mode mode)
709         (const #f)))
711   (define (built-or-substitutable? drv)
712     (or (null? (derivation-outputs drv))
713         (let ((out (derivation->output-path drv))) ;XXX: assume "out" exists
714           (or (valid-path? store out)
715               (substitutable-info out)))))
717   (let*-values (((build download)
718                  (fold2 (lambda (drv build download)
719                           (let-values (((b d)
720                                         (derivation-prerequisites-to-build
721                                          store drv
722                                          #:mode mode
723                                          #:substitutable-info
724                                          substitutable-info)))
725                             (values (append b build)
726                                     (append d download))))
727                         '() '()
728                         drv))
729                 ((build)                          ; add the DRV themselves
730                  (delete-duplicates
731                   (append (map derivation-file-name
732                                (remove built-or-substitutable? drv))
733                           (map derivation-input-path build))))
734                 ((download)                   ; add the references of DOWNLOAD
735                  (if use-substitutes?
736                      (delete-duplicates
737                       (append download
738                               (filter-map (lambda (item)
739                                             (if (valid-path? store item)
740                                                 #f
741                                                 (substitutable-info item)))
742                                           (append-map
743                                            substitutable-references
744                                            download))))
745                      download)))
746     (define installed-size
747       (reduce + 0 (map substitutable-nar-size download)))
749     (define download-size
750       (/ (reduce + 0 (map substitutable-download-size download))
751          1e6))
753     (define display-download-size?
754       ;; Sometimes narinfos lack information about the download size.  Only
755       ;; display when we have information for all of DOWNLOAD.
756       (not (any (compose zero? substitutable-download-size) download)))
758     (if dry-run?
759         (begin
760           (format (current-error-port)
761                   (N_ "~:[The following derivation would be built:~%~{   ~a~%~}~;~]"
762                       "~:[The following derivations would be built:~%~{   ~a~%~}~;~]"
763                       (length build))
764                   (null? build) build)
765           (if display-download-size?
766               (format (current-error-port)
767                       ;; TRANSLATORS: "MB" is for "megabyte"; it should be
768                       ;; translated to the corresponding abbreviation.
769                       (G_ "~:[~,1h MB would be downloaded:~%~{   ~a~%~}~;~]")
770                       (null? download)
771                       download-size
772                       (map substitutable-path download))
773               (format (current-error-port)
774                       (N_ "~:[The following file would be downloaded:~%~{   ~a~%~}~;~]"
775                           "~:[The following files would be downloaded:~%~{   ~a~%~}~;~]"
776                           (length download))
777                       (null? download)
778                       (map substitutable-path download))))
779         (begin
780           (format (current-error-port)
781                   (N_ "~:[The following derivation will be built:~%~{   ~a~%~}~;~]"
782                       "~:[The following derivations will be built:~%~{   ~a~%~}~;~]"
783                       (length build))
784                   (null? build) build)
785           (if display-download-size?
786               (format (current-error-port)
787                       ;; TRANSLATORS: "MB" is for "megabyte"; it should be
788                       ;; translated to the corresponding abbreviation.
789                       (G_ "~:[~,1h MB will be downloaded:~%~{   ~a~%~}~;~]")
790                       (null? download)
791                       download-size
792                       (map substitutable-path download))
793               (format (current-error-port)
794                       (N_ "~:[The following file will be downloaded:~%~{   ~a~%~}~;~]"
795                           "~:[The following files will be downloaded:~%~{   ~a~%~}~;~]"
796                           (length download))
797                       (null? download)
798                       (map substitutable-path download)))))
800     (check-available-space installed-size)
802     (pair? build)))
804 (define show-what-to-build*
805   (store-lift show-what-to-build))
807 (define (right-arrow port)
808   "Return either a string containing the 'RIGHT ARROW' character, or an ASCII
809 replacement if PORT is not Unicode-capable."
810   (let ((encoding (port-encoding port))
811         (arrow "→"))
812     (catch 'encoding-error
813       (lambda ()
814         (call-with-output-string
815           (lambda (port)
816             (set-port-encoding! port encoding)
817             (set-port-conversion-strategy! port 'error)
818             (display arrow port))))
819       (lambda (key . args)
820         "->"))))
822 (define* (show-manifest-transaction store manifest transaction
823                                     #:key dry-run?)
824   "Display what will/would be installed/removed from MANIFEST by TRANSACTION."
825   (define (package-strings name version output item)
826     (map (lambda (name version output item)
827            (format #f "   ~a~:[:~a~;~*~]\t~a\t~a"
828                    name
829                    (equal? output "out") output version
830                    (if (package? item)
831                        (package-output store item output)
832                        item)))
833          name version output item))
835   (define →                        ;an arrow that can be represented on stderr
836     (right-arrow (current-error-port)))
838   (define (upgrade-string name old-version new-version output item)
839     (format #f "   ~a~:[:~a~;~*~]\t~a ~a ~a\t~a"
840             name (equal? output "out") output
841             old-version → new-version
842             (if (package? item)
843                 (package-output store item output)
844                 item)))
846   (let-values (((remove install upgrade downgrade)
847                 (manifest-transaction-effects manifest transaction)))
848     (match remove
849       ((($ <manifest-entry> name version output item) ..1)
850        (let ((len    (length name))
851              (remove (package-strings name version output item)))
852          (if dry-run?
853              (format (current-error-port)
854                      (N_ "The following package would be removed:~%~{~a~%~}~%"
855                          "The following packages would be removed:~%~{~a~%~}~%"
856                          len)
857                      remove)
858              (format (current-error-port)
859                      (N_ "The following package will be removed:~%~{~a~%~}~%"
860                          "The following packages will be removed:~%~{~a~%~}~%"
861                          len)
862                      remove))))
863       (x #f))
864     (match downgrade
865       (((($ <manifest-entry> name old-version)
866          . ($ <manifest-entry> _ new-version output item)) ..1)
867        (let ((len       (length name))
868              (downgrade (map upgrade-string
869                              name old-version new-version output item)))
870          (if dry-run?
871              (format (current-error-port)
872                      (N_ "The following package would be downgraded:~%~{~a~%~}~%"
873                          "The following packages would be downgraded:~%~{~a~%~}~%"
874                          len)
875                      downgrade)
876              (format (current-error-port)
877                      (N_ "The following package will be downgraded:~%~{~a~%~}~%"
878                          "The following packages will be downgraded:~%~{~a~%~}~%"
879                          len)
880                      downgrade))))
881       (x #f))
882     (match upgrade
883       (((($ <manifest-entry> name old-version)
884          . ($ <manifest-entry> _ new-version output item)) ..1)
885        (let ((len     (length name))
886              (upgrade (map upgrade-string
887                            name old-version new-version output item)))
888          (if dry-run?
889              (format (current-error-port)
890                      (N_ "The following package would be upgraded:~%~{~a~%~}~%"
891                          "The following packages would be upgraded:~%~{~a~%~}~%"
892                          len)
893                      upgrade)
894              (format (current-error-port)
895                      (N_ "The following package will be upgraded:~%~{~a~%~}~%"
896                          "The following packages will be upgraded:~%~{~a~%~}~%"
897                          len)
898                      upgrade))))
899       (x #f))
900     (match install
901       ((($ <manifest-entry> name version output item _) ..1)
902        (let ((len     (length name))
903              (install (package-strings name version output item)))
904          (if dry-run?
905              (format (current-error-port)
906                      (N_ "The following package would be installed:~%~{~a~%~}~%"
907                          "The following packages would be installed:~%~{~a~%~}~%"
908                          len)
909                      install)
910              (format (current-error-port)
911                      (N_ "The following package will be installed:~%~{~a~%~}~%"
912                          "The following packages will be installed:~%~{~a~%~}~%"
913                          len)
914                      install))))
915       (x #f))))
917 (define-syntax with-error-handling
918   (syntax-rules ()
919     "Run BODY within a user-friendly error condition handler."
920     ((_ body ...)
921      (call-with-error-handling
922       (lambda ()
923         body ...)))))
925 (define (location->string loc)
926   "Return a human-friendly, GNU-standard representation of LOC."
927   (match loc
928     (#f (G_ "<unknown location>"))
929     (($ <location> file line column)
930      (format #f "~a:~a:~a" file line column))))
932 (define* (fill-paragraph str width #:optional (column 0))
933   "Fill STR such that each line contains at most WIDTH characters, assuming
934 that the first character is at COLUMN.
936 When STR contains a single line break surrounded by other characters, it is
937 converted to a space; sequences of more than one line break are preserved."
938   (define (maybe-break chr result)
939     (match result
940       ((column newlines chars)
941        (case chr
942          ((#\newline)
943           `(,column ,(+ 1 newlines) ,chars))
944          (else
945           (let* ((spaces (if (and (pair? chars) (eqv? (car chars) #\.)) 2 1))
946                  (chars  (case newlines
947                            ((0) chars)
948                            ((1)
949                             (append (make-list spaces #\space) chars))
950                            (else
951                             (append (make-list newlines #\newline) chars))))
952                  (column (case newlines
953                            ((0) column)
954                            ((1) (+ spaces column))
955                            (else 0))))
956             (let ((chars  (cons chr chars))
957                   (column (+ 1 column)))
958               (if (> column width)
959                   (let*-values (((before after)
960                                  (break (cut eqv? #\space <>) chars))
961                                 ((len)
962                                  (length before)))
963                     (if (<= len width)
964                         `(,len
965                           0
966                           ,(if (null? after)
967                                before
968                                (append before
969                                        (cons #\newline
970                                              (drop-while (cut eqv? #\space <>)
971                                                          after)))))
972                         `(,column 0 ,chars)))     ; unbreakable
973                   `(,column 0 ,chars)))))))))
975   (match (string-fold maybe-break
976                       `(,column 0 ())
977                       str)
978     ((column newlines chars)
979      (list->string (reverse chars)))))
983 ;;; Packages.
986 (define %text-width
987   (make-parameter (terminal-columns)))
989 (set! (@@ (texinfo plain-text) wrap*)
990       ;; XXX: Monkey patch this private procedure to let 'package->recutils'
991       ;; parameterize the fill of description field correctly.
992       (lambda strings
993         (let ((indent (fluid-ref (@@ (texinfo plain-text) *indent*))))
994           (fill-string (string-concatenate strings)
995                        #:line-width (%text-width) #:initial-indent indent
996                        #:subsequent-indent indent))))
998 (define (texi->plain-text str)
999   "Return a plain-text representation of texinfo fragment STR."
1000   ;; 'texi-fragment->stexi' uses a string port so make sure it's a
1001   ;; Unicode-capable one (see <http://bugs.gnu.org/11197>.)
1002   (with-fluids ((%default-port-encoding "UTF-8"))
1003     (stexi->plain-text (texi-fragment->stexi str))))
1005 (define (package-field-string package field-accessor)
1006   "Return a plain-text representation of PACKAGE field."
1007   (and=> (field-accessor package)
1008          (compose texi->plain-text P_)))
1010 (define (package-description-string package)
1011   "Return a plain-text representation of PACKAGE description field."
1012   (package-field-string package package-description))
1014 (define (package-synopsis-string package)
1015   "Return a plain-text representation of PACKAGE synopsis field."
1016   (package-field-string package package-synopsis))
1018 (define (string->recutils str)
1019   "Return a version of STR where newlines have been replaced by newlines
1020 followed by \"+ \", which makes for a valid multi-line field value in the
1021 `recutils' syntax."
1022   (list->string
1023    (string-fold-right (lambda (chr result)
1024                         (if (eqv? chr #\newline)
1025                             (cons* chr #\+ #\space result)
1026                             (cons chr result)))
1027                       '()
1028                       str)))
1030 (define* (package->recutils p port #:optional (width (%text-width))
1031                             #:key (extra-fields '()))
1032   "Write to PORT a `recutils' record of package P, arranging to fit within
1033 WIDTH columns.  EXTRA-FIELDS is a list of symbol/value pairs to emit."
1034   (define width*
1035     ;; The available number of columns once we've taken into account space for
1036     ;; the initial "+ " prefix.
1037     (if (> width 2) (- width 2) width))
1039   (define (dependencies->recutils packages)
1040     (let ((list (string-join (delete-duplicates
1041                               (map package-full-name
1042                                    (sort packages package<?))) " ")))
1043       (string->recutils
1044        (fill-paragraph list width*
1045                        (string-length "dependencies: ")))))
1047   (define (package<? p1 p2)
1048     (string<? (package-full-name p1) (package-full-name p2)))
1050   ;; Note: Don't i18n field names so that people can post-process it.
1051   (format port "name: ~a~%" (package-name p))
1052   (format port "version: ~a~%" (package-version p))
1053   (format port "outputs: ~a~%" (string-join (package-outputs p)))
1054   (format port "systems: ~a~%"
1055           (string-join (package-transitive-supported-systems p)))
1056   (format port "dependencies: ~a~%"
1057           (match (package-direct-inputs p)
1058             (((labels inputs . _) ...)
1059              (dependencies->recutils (filter package? inputs)))))
1060   (format port "location: ~a~%"
1061           (or (and=> (package-location p) location->string)
1062               (G_ "unknown")))
1064   ;; Note: Starting from version 1.6 or recutils, hyphens are not allowed in
1065   ;; field identifiers.
1066   (format port "homepage: ~a~%" (package-home-page p))
1068   (format port "license: ~a~%"
1069           (match (package-license p)
1070             (((? license? licenses) ...)
1071              (string-join (map license-name licenses)
1072                           ", "))
1073             ((? license? license)
1074              (license-name license))
1075             (x
1076              (G_ "unknown"))))
1077   (format port "synopsis: ~a~%"
1078           (string-map (match-lambda
1079                         (#\newline #\space)
1080                         (chr       chr))
1081                       (or (and=> (package-synopsis-string p) P_)
1082                           "")))
1083   (format port "~a~%"
1084           (string->recutils
1085            (string-trim-right
1086             (parameterize ((%text-width width*))
1087               (texi->plain-text
1088                (string-append "description: "
1089                               (or (and=> (package-description p) P_)
1090                                   ""))))
1091             #\newline)))
1092   (for-each (match-lambda
1093               ((field . value)
1094                (let ((field (symbol->string field)))
1095                  (format port "~a: ~a~%"
1096                          field
1097                          (fill-paragraph (object->string value) width*
1098                                          (string-length field))))))
1099             extra-fields)
1100   (newline port))
1102 (define (relevance obj regexps metrics)
1103   "Compute a \"relevance score\" for OBJ as a function of its number of
1104 matches of REGEXPS and accordingly to METRICS.  METRICS is list of
1105 field/weight pairs, where FIELD is a procedure that returns a string
1106 describing OBJ, and WEIGHT is a positive integer denoting the weight of this
1107 field in the final score.
1109 A score of zero means that OBJ does not match any of REGEXPS.  The higher the
1110 score, the more relevant OBJ is to REGEXPS."
1111   (define (score str)
1112     (let ((counts (filter-map (lambda (regexp)
1113                                 (match (regexp-exec regexp str)
1114                                   (#f #f)
1115                                   (m  (match:count m))))
1116                               regexps)))
1117       ;; Compute a score that's proportional to the number of regexps matched
1118       ;; and to the number of matches for each regexp.
1119       (* (length counts) (reduce + 0 counts))))
1121   (fold (lambda (metric relevance)
1122           (match metric
1123             ((field . weight)
1124              (match (field obj)
1125                (#f  relevance)
1126                (str (+ relevance
1127                        (* (score str) weight)))))))
1128         0
1129         metrics))
1131 (define %package-metrics
1132   ;; Metrics used to compute the "relevance score" of a package against a set
1133   ;; of regexps.
1134   `((,package-name . 4)
1135     (,package-synopsis-string . 3)
1136     (,package-description-string . 2)
1137     (,(lambda (type)
1138         (match (and=> (package-location type) location-file)
1139           ((? string? file) (basename file ".scm"))
1140           (#f "")))
1141      . 1)))
1143 (define (package-relevance package regexps)
1144   "Return a score denoting the relevance of PACKAGE for REGEXPS.  A score of
1145 zero means that PACKAGE does not match any of REGEXPS."
1146   (relevance package regexps %package-metrics))
1148 (define (string->generations str)
1149   "Return the list of generations matching a pattern in STR.  This function
1150 accepts the following patterns: \"1\", \"1,2,3\", \"1..9\", \"1..\", \"..9\"."
1151   (define (maybe-integer)
1152     (let ((x (string->number str)))
1153       (and (integer? x)
1154            x)))
1156   (define (maybe-comma-separated-integers)
1157     (let ((lst (delete-duplicates
1158                 (map string->number
1159                      (string-split str #\,)))))
1160       (and (every integer? lst)
1161            lst)))
1163   (cond ((maybe-integer)
1164          =>
1165          list)
1166         ((maybe-comma-separated-integers)
1167          =>
1168          identity)
1169         ((string-match "^([0-9]+)\\.\\.([0-9]+)$" str)
1170          =>
1171          (lambda (match)
1172            (let ((s (string->number (match:substring match 1)))
1173                  (e (string->number (match:substring match 2))))
1174              (and (every integer? (list s e))
1175                   (<= s e)
1176                   (iota (1+ (- e s)) s)))))
1177         ((string-match "^([0-9]+)\\.\\.$" str)
1178          =>
1179          (lambda (match)
1180            (let ((s (string->number (match:substring match 1))))
1181              (and (integer? s)
1182                   `(>= ,s)))))
1183         ((string-match "^\\.\\.([0-9]+)$" str)
1184          =>
1185          (lambda (match)
1186            (let ((e (string->number (match:substring match 1))))
1187              (and (integer? e)
1188                   `(<= ,e)))))
1189         (else #f)))
1191 (define (string->duration str)
1192   "Return the duration matching a pattern in STR.  This function accepts the
1193 following patterns: \"1d\", \"1w\", \"1m\"."
1194   (define (hours->duration hours match)
1195     (make-time time-duration 0
1196                (* 3600 hours (string->number (match:substring match 1)))))
1198   (cond ((string-match "^([0-9]+)s$" str)
1199          =>
1200          (lambda (match)
1201            (make-time time-duration 0
1202                       (string->number (match:substring match 1)))))
1203         ((string-match "^([0-9]+)h$" str)
1204          =>
1205          (lambda (match)
1206            (hours->duration 1 match)))
1207         ((string-match "^([0-9]+)d$" str)
1208          =>
1209          (lambda (match)
1210            (hours->duration 24 match)))
1211         ((string-match "^([0-9]+)w$" str)
1212          =>
1213          (lambda (match)
1214            (hours->duration (* 24 7) match)))
1215         ((string-match "^([0-9]+)m$" str)
1216          =>
1217          (lambda (match)
1218            (hours->duration (* 24 30) match)))
1219         (else #f)))
1221 (define* (matching-generations str profile
1222                                #:key (duration-relation <=))
1223   "Return the list of available generations matching a pattern in STR.  See
1224 'string->generations' and 'string->duration' for the list of valid patterns.
1225 When STR is a duration pattern, return all the generations whose ctime has
1226 DURATION-RELATION with the current time."
1227   (define (valid-generations lst)
1228     (define (valid-generation? n)
1229       (any (cut = n <>) (generation-numbers profile)))
1231     (fold-right (lambda (x acc)
1232                   (if (valid-generation? x)
1233                       (cons x acc)
1234                       acc))
1235                 '()
1236                 lst))
1238   (define (filter-generations generations)
1239     (match generations
1240       (() '())
1241       (('>= n)
1242        (drop-while (cut > n <>)
1243                    (generation-numbers profile)))
1244       (('<= n)
1245        (valid-generations (iota n 1)))
1246       ((lst ..1)
1247        (valid-generations lst))
1248       (x #f)))
1250   (define (filter-by-duration duration)
1251     (define (time-at-midnight time)
1252       ;; Return TIME at midnight by setting nanoseconds, seconds, minutes, and
1253       ;; hours to zeros.
1254       (let ((d (time-utc->date time)))
1255          (date->time-utc
1256           (make-date 0 0 0 0
1257                      (date-day d) (date-month d)
1258                      (date-year d) (date-zone-offset d)))))
1260     (define generation-ctime-alist
1261       (map (lambda (number)
1262              (cons number
1263                    (time-second
1264                     (time-at-midnight
1265                      (generation-time profile number)))))
1266            (generation-numbers profile)))
1268     (match duration
1269       (#f #f)
1270       (res
1271        (let ((s (time-second
1272                  (subtract-duration (time-at-midnight (current-time))
1273                                     duration))))
1274          (delete #f (map (lambda (x)
1275                            (and (duration-relation s (cdr x))
1276                                 (first x)))
1277                          generation-ctime-alist))))))
1279   (cond ((string->generations str)
1280          =>
1281          filter-generations)
1282         ((string->duration str)
1283          =>
1284          filter-by-duration)
1285         (else #f)))
1287 (define (display-generation profile number)
1288   "Display a one-line summary of generation NUMBER of PROFILE."
1289   (unless (zero? number)
1290     (let ((header (format #f (G_ "Generation ~a\t~a") number
1291                           (date->string
1292                            (time-utc->date
1293                             (generation-time profile number))
1294                            "~b ~d ~Y ~T")))
1295           (current (generation-number profile)))
1296       (if (= number current)
1297           ;; TRANSLATORS: The word "current" here is an adjective for
1298           ;; "Generation", as in "current generation".  Use the appropriate
1299           ;; gender where applicable.
1300           (format #t (G_ "~a\t(current)~%") header)
1301           (format #t "~a~%" header)))))
1303 (define (display-profile-content-diff profile gen1 gen2)
1304   "Display the changed packages in PROFILE GEN2 compared to generation GEN2."
1306   (define (equal-entry? first second)
1307     (string= (manifest-entry-item first) (manifest-entry-item second)))
1309   (define (display-entry entry prefix)
1310     (match entry
1311       (($ <manifest-entry> name version output location _)
1312        (format #t " ~a ~a\t~a\t~a\t~a~%" prefix name version output location))))
1314   (define (list-entries number)
1315     (manifest-entries (profile-manifest (generation-file-name profile number))))
1317   (define (display-diff profile old new)
1318     (display-generation profile new)
1319     (let ((added (lset-difference
1320                   equal-entry? (list-entries new) (list-entries old)))
1321           (removed (lset-difference
1322                     equal-entry? (list-entries old) (list-entries new))))
1323       (for-each (cut display-entry <> "+") added)
1324       (for-each (cut display-entry <> "-") removed)
1325       (newline)))
1327   (display-diff profile gen1 gen2))
1329 (define (display-profile-content profile number)
1330   "Display the packages in PROFILE, generation NUMBER, in a human-readable
1331 way."
1332   (for-each (match-lambda
1333               (($ <manifest-entry> name version output location _)
1334                (format #t "  ~a\t~a\t~a\t~a~%"
1335                        name version output location)))
1337             ;; Show most recently installed packages last.
1338             (reverse
1339              (manifest-entries
1340               (profile-manifest (generation-file-name profile number))))))
1342 (define (display-generation-change previous current)
1343   (format #t (G_ "switched from generation ~a to ~a~%") previous current))
1345 (define (roll-back* store profile)
1346   "Like 'roll-back', but display what is happening."
1347   (call-with-values
1348       (lambda ()
1349         (roll-back store profile))
1350     display-generation-change))
1352 (define (switch-to-generation* profile number)
1353   "Like 'switch-generation', but display what is happening."
1354   (let ((previous (switch-to-generation profile number)))
1355     (display-generation-change previous number)))
1357 (define (delete-generation* store profile generation)
1358   "Like 'delete-generation', but display what is going on."
1359   (format #t (G_ "deleting ~a~%")
1360           (generation-file-name profile generation))
1361   (delete-generation store profile generation))
1363 (define* (package-specification->name+version+output spec
1364                                                      #:optional (output "out"))
1365   "Parse package specification SPEC and return three value: the specified
1366 package name, version number (or #f), and output name (or OUTPUT).  SPEC may
1367 optionally contain a version number and an output name, as in these examples:
1369   guile
1370   guile@2.0.9
1371   guile:debug
1372   guile@2.0.9:debug
1374   (let*-values (((name sub-drv)
1375                  (match (string-rindex spec #\:)
1376                    (#f    (values spec output))
1377                    (colon (values (substring spec 0 colon)
1378                                   (substring spec (+ 1 colon))))))
1379                 ((name version)
1380                  (package-name->name+version name)))
1381     (values name version sub-drv)))
1385 ;;; Command-line option processing.
1388 (define (show-guix-usage)
1389   (format (current-error-port)
1390           (G_ "Try `guix --help' for more information.~%"))
1391   (exit 1))
1393 (define (command-files)
1394   "Return the list of source files that define Guix sub-commands."
1395   (define directory
1396     (and=> (search-path %load-path "guix.scm")
1397            (compose (cut string-append <> "/guix/scripts")
1398                     dirname)))
1400   (define dot-scm?
1401     (cut string-suffix? ".scm" <>))
1403   (if directory
1404       (scandir directory dot-scm?)
1405       '()))
1407 (define (commands)
1408   "Return the list of Guix command names."
1409   (map (compose (cut string-drop-right <> 4)
1410                 basename)
1411        (command-files)))
1413 (define (show-guix-help)
1414   (define (internal? command)
1415     (member command '("substitute" "authenticate" "offload"
1416                       "perform-download")))
1418   (format #t (G_ "Usage: guix COMMAND ARGS...
1419 Run COMMAND with ARGS.\n"))
1420   (newline)
1421   (format #t (G_ "COMMAND must be one of the sub-commands listed below:\n"))
1422   (newline)
1423   ;; TODO: Display a synopsis of each command.
1424   (format #t "~{   ~a~%~}" (sort (remove internal? (commands))
1425                                  string<?))
1426   (show-bug-report-information))
1428 (define program-name
1429   ;; Name of the command-line program currently executing, or #f.
1430   (make-parameter #f))
1432 (define (run-guix-command command . args)
1433   "Run COMMAND with the given ARGS.  Report an error when COMMAND is not
1434 found."
1435   (define module
1436     (catch 'misc-error
1437       (lambda ()
1438         (resolve-interface `(guix scripts ,command)))
1439       (lambda -
1440         (format (current-error-port)
1441                 (G_ "guix: ~a: command not found~%") command)
1442         (show-guix-usage))))
1444   (let ((command-main (module-ref module
1445                                   (symbol-append 'guix- command))))
1446     (parameterize ((program-name command))
1447       ;; Disable canonicalization so we don't don't stat unreasonably.
1448       (with-fluids ((%file-port-name-canonicalization #f))
1449         (dynamic-wind
1450           (const #f)
1451           (lambda ()
1452             (apply command-main args))
1453           (lambda ()
1454             ;; Abuse 'exit-hook' (which is normally meant to be used by the
1455             ;; REPL) to run things like profiling hooks upon completion.
1456             (run-hook exit-hook)))))))
1458 (define (run-guix . args)
1459   "Run the 'guix' command defined by command line ARGS.
1460 Unlike 'guix-main', this procedure assumes that locale, i18n support,
1461 and signal handling has already been set up."
1462   (define option? (cut string-prefix? "-" <>))
1464   ;; The default %LOAD-EXTENSIONS includes the empty string, which doubles the
1465   ;; number of 'stat' calls per entry in %LOAD-PATH.  Shamelessly remove it.
1466   (set! %load-extensions '(".scm"))
1468   (match args
1469     (()
1470      (format (current-error-port)
1471              (G_ "guix: missing command name~%"))
1472      (show-guix-usage))
1473     ((or ("-h") ("--help"))
1474      (show-guix-help))
1475     (("--version")
1476      (show-version-and-exit "guix"))
1477     (((? option? o) args ...)
1478      (format (current-error-port)
1479              (G_ "guix: unrecognized option '~a'~%") o)
1480      (show-guix-usage))
1481     (("help" command)
1482      (apply run-guix-command (string->symbol command)
1483             '("--help")))
1484     (("help" args ...)
1485      (show-guix-help))
1486     ((command args ...)
1487      (apply run-guix-command
1488             (string->symbol command)
1489             args))))
1491 (define guix-warning-port
1492   (make-parameter (current-warning-port)))
1494 (define (guix-main arg0 . args)
1495   (initialize-guix)
1496   (apply run-guix args))
1498 ;;; ui.scm ends here