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