1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2012, 2013, 2014, 2015, 2016, 2017, 2018 Ludovic Courtès <ludo@gnu.org>
3 ;;; Copyright © 2013, 2018 Mark H Weaver <mhw@netris.org>
4 ;;; Copyright © 2013 Nikita Karetnikov <nikita@karetnikov.org>
5 ;;; Copyright © 2014 Cyril Roelandt <tipecaml@gmail.com>
6 ;;; Copyright © 2014 Cyrill Schenkel <cyrill.schenkel@gmail.com>
7 ;;; Copyright © 2014, 2015, 2017 Alex Kost <alezost@gmail.com>
8 ;;; Copyright © 2015 David Thompson <davet@gnu.org>
9 ;;; Copyright © 2015, 2016 Mathieu Lirzin <mthl@gnu.org>
10 ;;; Copyright © 2016 Roel Janssen <roel@gnu.org>
11 ;;; Copyright © 2016 Benz Schenk <benz.schenk@uzh.ch>
13 ;;; This file is part of GNU Guix.
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.
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.
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 ((guix build utils)
45 #:select (invoke-error? invoke-error-program
46 invoke-error-arguments
47 invoke-error-exit-status
48 invoke-error-term-signal
49 invoke-error-stop-signal))
50 #:use-module (srfi srfi-1)
51 #:use-module (srfi srfi-11)
52 #:use-module (srfi srfi-19)
53 #:use-module (srfi srfi-26)
54 #:use-module (srfi srfi-31)
55 #:use-module (srfi srfi-34)
56 #:use-module (srfi srfi-35)
57 #:autoload (ice-9 ftw) (scandir)
58 #:use-module (ice-9 match)
59 #:use-module (ice-9 format)
60 #:use-module (ice-9 regex)
61 #:autoload (system base compile) (compile-file)
62 #:autoload (system repl repl) (start-repl)
63 #:autoload (system repl debug) (make-debug stack->vector)
64 #:use-module (texinfo)
65 #:use-module (texinfo plain-text)
66 #:use-module (texinfo string-utils)
67 #:re-export (G_ N_ P_) ;backward compatibility
68 #:export (report-error
75 show-bug-report-information
79 show-derivation-outputs
82 show-manifest-transaction
83 call-with-error-handling
87 read/eval-package-expression
92 package-description-string
93 package-synopsis-string
96 package-specification->name+version+output
103 display-profile-content
104 display-profile-content-diff
106 switch-to-generation*
118 ;;; User interface facilities for command-line tools.
122 (define-syntax-rule (define-diagnostic name prefix)
123 "Create a diagnostic macro (i.e., NAME), which will prepend PREFIX to all
127 (define (augmented-format-string fmt)
128 (string-append "~:[~*~;guix ~a: ~]~a" (syntax->datum fmt)))
131 ((name (underscore fmt) args (... ...))
132 (and (string? (syntax->datum #'fmt))
133 (free-identifier=? #'underscore #'G_))
134 (with-syntax ((fmt* (augmented-format-string #'fmt))
135 (prefix (datum->syntax x prefix)))
136 #'(format (guix-warning-port) (gettext fmt*)
137 (program-name) (program-name) prefix
139 ((name (N-underscore singular plural n) args (... ...))
140 (and (string? (syntax->datum #'singular))
141 (string? (syntax->datum #'plural))
142 (free-identifier=? #'N-underscore #'N_))
143 (with-syntax ((s (augmented-format-string #'singular))
144 (p (augmented-format-string #'plural))
145 (prefix (datum->syntax x prefix)))
146 #'(format (guix-warning-port)
147 (ngettext s p n %gettext-domain)
148 (program-name) (program-name) prefix
149 args (... ...))))))))
151 (define-diagnostic warning "warning: ") ; emit a warning
152 (define-diagnostic info "")
154 (define-diagnostic report-error "error: ")
155 (define-syntax-rule (leave args ...)
156 "Emit an error message and exit."
158 (report-error args ...)
161 (define (print-unbound-variable-error port key args default-printer)
162 ;; Print unbound variable errors more nicely, and in the right language.
164 ((proc message (variable) _ ...)
165 ;; We can always omit PROC because when it's useful (i.e., different from
166 ;; "module-lookup"), it gets displayed before.
167 (format port (G_ "~a: unbound variable") variable))
171 (set-exception-printer! 'unbound-variable print-unbound-variable-error)
173 (define (make-user-module modules)
174 "Return a new user module with the additional MODULES loaded."
175 ;; Module in which the machine description file is loaded.
176 (let ((module (make-fresh-user-module)))
177 (for-each (lambda (iface)
178 (module-use! module (resolve-interface iface)))
182 (define* (load* file user-module
183 #:key (on-error 'nothing-special))
184 "Load the user provided Scheme source code FILE."
185 (define (frame-with-source frame)
186 ;; Walk from FRAME upwards until source location information is found.
187 (let loop ((frame frame)
191 (if (frame-source frame)
193 (loop (frame-previous frame) frame)))))
195 (define (error-string frame args)
196 (call-with-output-string
198 (apply display-error frame port (cdr args)))))
201 (make-prompt-tag "user-code"))
205 ;; XXX: Force a recompilation to avoid ABI issues.
207 ;; In 2.2.3, the bogus answer to <https://bugs.gnu.org/29226> was to
208 ;; ignore all available .go, not just those from ~/.cache, which in turn
209 ;; meant that we had to rebuild *everything*. Since this is too costly,
210 ;; we have to turn off '%fresh-auto-compile' with that version, so to
211 ;; avoid ABI breakage in the user's config file, we explicitly compile
212 ;; it (the problem remains if the user's config is spread on several
213 ;; modules.) See <https://bugs.gnu.org/29881>.
214 (unless (string=? (version) "2.2.3")
215 (set! %fresh-auto-compile #t))
217 (set! %load-should-auto-compile #t)
219 (save-module-excursion
221 (set-current-module user-module)
223 ;; Hide the "auto-compiling" messages.
224 (parameterize ((current-warning-port (%make-void-port "w")))
225 (call-with-prompt tag
227 (when (string=? (version) "2.2.3")
230 (compile-file file #:env user-module))
231 (const #f))) ;EACCES maybe, let's interpret it
233 ;; Give 'load' an absolute file name so that it doesn't try to
234 ;; search for FILE in %LOAD-PATH. Note: use 'load', not
235 ;; 'primitive-load', so that FILE is compiled, which then allows us
236 ;; to provide better error reporting with source line numbers.
237 (load (canonicalize-path file)))
240 ;; XXX: Errors are reported from the pre-unwind handler below, but
241 ;; calling 'exit' from there has no effect, so we call it here.
243 (rec (handle-error . args)
244 ;; Capture the stack up to this procedure call, excluded, and pass
245 ;; the faulty stack frame to 'report-load-error'.
246 (let* ((stack (make-stack #t handle-error tag))
247 (depth (stack-length stack))
248 (last (and (> depth 0) (stack-ref stack 0)))
249 (frame (frame-with-source
251 (stack-ref stack 1) ;skip the 'throw' frame
254 (report-load-error file args frame)
259 (display (G_ "entering debugger; type ',bt' for a backtrace\n"))
260 (start-repl #:debug (make-debug (stack->vector stack) 0
261 (error-string frame args)
264 (newline (current-error-port))
265 (display-backtrace stack (current-error-port)))
269 (define (known-variable-definition variable)
270 "Search among the currently loaded modules one that defines a variable named
271 VARIABLE and return it, or #f if none was found."
272 (define (module<? m1 m2)
273 (match (module-name m2)
276 (match (module-name m1)
281 (let loop ((modules (list (resolve-module '() #f #f #:ensure #f)))
286 ;; Pick the "best" suggestion.
287 (match (sort suggestions module<?)
289 ((first _ ...) first)))
291 (if (set-contains? visited head)
292 (loop tail suggestions visited)
293 (let ((visited (set-insert head visited))
295 (hash-map->list (lambda (name module)
297 (module-submodules head)))))
298 (match (module-local-variable head variable)
299 (#f (loop next suggestions visited))
301 (match (module-name head)
302 (('gnu _ ...) head) ;must be that one
303 (_ (loop next (cons head suggestions) visited)))))))))))
305 (define* (display-hint message #:optional (port (current-error-port)))
306 "Display MESSAGE, a l10n message possibly containing Texinfo markup, to
308 (format port (G_ "hint: ~a~%")
309 ;; XXX: We should arrange so that the initial indent is wider.
310 (parameterize ((%text-width (max 15
311 (- (terminal-columns) 5))))
312 (texi->plain-text message))))
314 (define* (report-load-error file args #:optional frame)
315 "Report the failure to load FILE, a user-provided Scheme file.
316 ARGS is the list of arguments received by the 'throw' handler."
318 (('system-error . rest)
319 (let ((err (system-error-errno args)))
320 (report-error (G_ "failed to load '~a': ~a~%") file (strerror err))))
321 (('read-error "scm_i_lreadparen" message _ ...)
322 ;; Guile's missing-paren messages are obscure so we make them more
323 ;; intelligible here.
324 (if (string-suffix? "end of file" message)
325 (let ((location (string-drop-right message
326 (string-length "end of file"))))
327 (format (current-error-port) (G_ "~amissing closing parenthesis~%")
330 (('syntax-error proc message properties form . rest)
331 (let ((loc (source-properties->location properties)))
332 (format (current-error-port) (G_ "~a: error: ~a~%")
333 (location->string loc) message)))
334 (('unbound-variable proc message (variable) _ ...)
337 (print-exception (current-error-port) frame key args)))
338 (match (known-variable-definition variable)
340 (display-hint (G_ "Did you forget a @code{use-modules} form?")))
342 (display-hint (format #f (G_ "Did you forget @code{(use-modules ~a)}?")
343 (module-name module))))))
345 (if (message-condition? obj)
346 (if (error-location? obj)
347 (format (current-error-port)
348 (G_ "~a: error: ~a~%")
349 (location->string (error-location obj))
350 (gettext (condition-message obj)
352 (report-error (G_ "~a~%")
353 (gettext (condition-message obj)
355 (report-error (G_ "exception thrown: ~s~%") obj))
356 (when (fix-hint? obj)
357 (display-hint (condition-fix-hint obj))))
359 (report-error (G_ "failed to load '~a':~%") file)
360 (apply display-error frame (current-error-port) args))))
362 (define (warn-about-load-error file args) ;FIXME: factorize with ↑
363 "Report the failure to load FILE, a user-provided Scheme file, without
364 exiting. ARGS is the list of arguments received by the 'throw' handler."
366 (('system-error . rest)
367 (let ((err (system-error-errno args)))
368 (warning (G_ "failed to load '~a': ~a~%") file (strerror err))))
369 (('syntax-error proc message properties form . rest)
370 (let ((loc (source-properties->location properties)))
371 (format (current-error-port) (G_ "~a: warning: ~a~%")
372 (location->string loc) message)))
374 (if (message-condition? obj)
375 (warning (G_ "failed to load '~a': ~a~%")
377 (gettext (condition-message obj) %gettext-domain))
378 (warning (G_ "failed to load '~a': exception thrown: ~s~%")
381 (warning (G_ "failed to load '~a':~%") file)
382 (apply display-error #f (current-error-port) args))))
384 (define (install-locale)
385 "Install the current locale settings."
388 (setlocale LC_ALL ""))
390 (warning (G_ "failed to install locale: ~a~%")
391 (strerror (system-error-errno args))))))
393 (define (initialize-guix)
394 "Perform the usual initialization for stand-alone Guix commands."
395 ;; By default don't annoy users with deprecation warnings. In practice,
396 ;; 'define-deprecated' in (ice-9 deprecated) arranges so that those warnings
397 ;; are emitted at expansion-time only, but there are cases where they could
398 ;; slip through, for instance when interpreting code.
399 (unless (getenv "GUILE_WARN_DEPRECATED")
400 (debug-disable 'warn-deprecated))
403 (textdomain %gettext-domain)
405 ;; Ignore SIGPIPE. If the daemon closes the connection, we prefer to be
406 ;; notified via an EPIPE later.
407 (sigaction SIGPIPE SIG_IGN)
409 (setvbuf (current-output-port) _IOLBF)
410 (setvbuf (current-error-port) _IOLBF))
412 (define* (show-version-and-exit #:optional (command (car (command-line))))
413 "Display version information for COMMAND and `(exit 0)'."
414 (simple-format #t "~a (~a) ~a~%"
415 command %guix-package-name %guix-version)
416 (format #t "Copyright ~a 2018 ~a"
417 ;; TRANSLATORS: Translate "(C)" to the copyright symbol
418 ;; (C-in-a-circle), if this symbol is available in the user's
419 ;; locale. Otherwise, do not translate "(C)"; leave it as-is. */
421 (G_ "the Guix authors\n"))
423 License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
424 This is free software: you are free to change and redistribute it.
425 There is NO WARRANTY, to the extent permitted by law.
429 (define (show-bug-report-information)
430 ;; TRANSLATORS: The placeholder indicates the bug-reporting address for this
431 ;; package. Please add another line saying "Report translation bugs to
432 ;; ...\n" with the address for translation bugs (typically your translation
433 ;; team's web or email address).
435 Report bugs to: ~a.") %guix-bug-report-address)
437 ~a home page: <~a>") %guix-package-name %guix-home-page-url)
439 General help using GNU software: <http://www.gnu.org/gethelp/>"))
442 (define (augmented-system-error-handler file)
443 "Return a 'system-error' handler that mentions FILE in its message."
444 (lambda (key proc fmt args errno)
445 ;; Augment the FMT and ARGS with information about TARGET (this
446 ;; information is missing as of Guile 2.0.11, making the exception
448 (apply throw key proc "~A: ~S"
449 (list (strerror (car errno)) file)
452 (define-syntax-rule (error-reporting-wrapper proc (args ...) file)
453 "Wrap PROC such that its 'system-error' exceptions are augmented to mention
455 (let ((real-proc (@ (guile) proc)))
459 (real-proc args ...))
460 (augmented-system-error-handler file)))))
463 ;; We 'set!' the global binding because (gnu build ...) modules and similar
464 ;; typically don't use (guix ui).
465 (error-reporting-wrapper symlink (source target) target))
468 ;; Note: here we use 'set!', not #:replace, because UIs typically use
469 ;; 'copy-recursively', which doesn't use (guix ui).
470 (error-reporting-wrapper copy-file (source target) target))
472 (set! canonicalize-path
473 (error-reporting-wrapper canonicalize-path (file) file))
476 (define (make-regexp* regexp . flags)
477 "Like 'make-regexp' but error out if REGEXP is invalid, reporting the error
479 (catch 'regular-expression-syntax
481 (apply make-regexp regexp flags))
482 (lambda (key proc message . rest)
483 (leave (G_ "'~a' is not a valid regular expression: ~a~%")
486 (define (string->number* str)
487 "Like `string->number', but error out with an error message on failure."
488 (or (string->number str)
489 (leave (G_ "~a: invalid number~%") str)))
491 (define (size->number str)
492 "Convert STR, a storage measurement representation such as \"1024\" or
493 \"1MiB\", to a number of bytes. Raise an error if STR could not be
496 (string-rindex str char-set:digit))
499 (and unit-pos (substring str (+ 1 unit-pos))))
501 (let* ((numstr (if unit-pos
502 (substring str 0 (+ 1 unit-pos))
504 (num (string->number numstr)))
506 (leave (G_ "invalid number: ~a~%") numstr))
508 ((compose inexact->exact round)
511 ((or "KiB" "K" "k") (expt 2 10))
512 ((or "MiB" "M") (expt 2 20))
513 ((or "GiB" "G") (expt 2 30))
514 ((or "TiB" "T") (expt 2 40))
515 ((or "PiB" "P") (expt 2 50))
516 ((or "EiB" "E") (expt 2 60))
517 ((or "ZiB" "Z") (expt 2 70))
518 ((or "YiB" "Y") (expt 2 80))
529 (leave (G_ "unknown unit: ~a~%") unit)))))))
531 (define (display-collision-resolution-hint collision)
532 "Display hints on how to resolve COLLISION, a &profile-collistion-error."
533 (define (top-most-entry entry)
534 (let loop ((entry entry))
535 (match (force (manifest-entry-parent entry))
537 (parent (loop parent)))))
539 (let* ((first (profile-collision-error-entry collision))
540 (second (profile-collision-error-conflict collision))
541 (name1 (manifest-entry-name (top-most-entry first)))
542 (name2 (manifest-entry-name (top-most-entry second))))
543 (if (string=? name1 name2)
544 (display-hint (format #f (G_ "You cannot have two different versions
545 or variants of @code{~a} in the same profile.")
547 (display-hint (format #f (G_ "Try upgrading both @code{~a} and @code{~a},
548 or remove one of them from the profile.")
551 (define (call-with-error-handling thunk)
552 "Call THUNK within a user-friendly error handler."
553 (define (port-filename* port)
554 ;; 'port-filename' returns #f for non-file ports, but it raises an
555 ;; exception for file ports that are closed. Work around that.
556 (and (not (port-closed? port))
557 (port-filename port)))
559 (guard (c ((package-input-error? c)
560 (let* ((package (package-error-package c))
561 (input (package-error-invalid-input c))
562 (location (package-location package))
563 (file (location-file location))
564 (line (location-line location))
565 (column (location-column location)))
566 (leave (G_ "~a:~a:~a: package `~a' has an invalid input: ~s~%")
568 (package-full-name package) input)))
569 ((package-cross-build-system-error? c)
570 (let* ((package (package-error-package c))
571 (loc (package-location package))
572 (system (package-build-system package)))
573 (leave (G_ "~a: ~a: build system `~a' does not support cross builds~%")
574 (location->string loc)
575 (package-full-name package)
576 (build-system-name system))))
577 ((gexp-input-error? c)
578 (let ((input (package-error-invalid-input c)))
579 (leave (G_ "~s: invalid G-expression input~%")
580 (gexp-error-invalid-input c))))
581 ((profile-not-found-error? c)
582 (leave (G_ "profile '~a' does not exist~%")
583 (profile-error-profile c)))
584 ((missing-generation-error? c)
585 (leave (G_ "generation ~a of profile '~a' does not exist~%")
586 (missing-generation-error-generation c)
587 (profile-error-profile c)))
588 ((profile-collision-error? c)
589 (let ((entry (profile-collision-error-entry c))
590 (conflict (profile-collision-error-conflict c)))
591 (define (report-parent-entries entry)
592 (let ((parent (force (manifest-entry-parent entry))))
593 (when (manifest-entry? parent)
594 (report-error (G_ " ... propagated from ~a@~a~%")
595 (manifest-entry-name parent)
596 (manifest-entry-version parent))
597 (report-parent-entries parent))))
599 (define (manifest-entry-output* entry)
600 (match (manifest-entry-output entry)
602 (output (string-append ":" output))))
604 (report-error (G_ "profile contains conflicting entries for ~a~a~%")
605 (manifest-entry-name entry)
606 (manifest-entry-output* entry))
607 (report-error (G_ " first entry: ~a@~a~a ~a~%")
608 (manifest-entry-name entry)
609 (manifest-entry-version entry)
610 (manifest-entry-output* entry)
611 (manifest-entry-item entry))
612 (report-parent-entries entry)
613 (report-error (G_ " second entry: ~a@~a~a ~a~%")
614 (manifest-entry-name conflict)
615 (manifest-entry-version conflict)
616 (manifest-entry-output* conflict)
617 (manifest-entry-item conflict))
618 (report-parent-entries conflict)
619 (display-collision-resolution-hint c)
622 (let ((file (nar-error-file c))
623 (port (nar-error-port c)))
625 (leave (G_ "corrupt input while restoring '~a' from ~s~%")
626 file (or (port-filename* port) port))
627 (leave (G_ "corrupt input while restoring archive from ~s~%")
628 (or (port-filename* port) port)))))
629 ((nix-connection-error? c)
630 (leave (G_ "failed to connect to `~a': ~a~%")
631 (nix-connection-error-file c)
632 (strerror (nix-connection-error-code c))))
633 ((nix-protocol-error? c)
634 ;; FIXME: Server-provided error messages aren't i18n'd.
635 (leave (G_ "build failed: ~a~%")
636 (nix-protocol-error-message c)))
637 ((derivation-missing-output-error? c)
638 (leave (G_ "reference to invalid output '~a' of derivation '~a'~%")
639 (derivation-missing-output c)
640 (derivation-file-name (derivation-error-derivation c))))
641 ((file-search-error? c)
642 (leave (G_ "file '~a' could not be found in these \
643 directories:~{ ~a~}~%")
644 (file-search-error-file-name c)
645 (file-search-error-search-path c)))
647 (leave (G_ "program exited\
648 ~@[ with non-zero exit status ~a~]\
649 ~@[ terminated by signal ~a~]\
650 ~@[ stopped by signal ~a~]: ~s~%")
651 (invoke-error-exit-status c)
652 (invoke-error-term-signal c)
653 (invoke-error-stop-signal c)
654 (cons (invoke-error-program c)
655 (invoke-error-arguments c))))
656 ((and (error-location? c) (message-condition? c))
657 (format (current-error-port)
658 (G_ "~a: error: ~a~%")
659 (location->string (error-location c))
660 (gettext (condition-message c) %gettext-domain))
662 (display-hint (condition-fix-hint c)))
664 ((and (message-condition? c) (fix-hint? c))
665 (format (current-error-port) "~a: error: ~a~%"
667 (gettext (condition-message c) %gettext-domain))
668 (display-hint (condition-fix-hint c))
670 ((message-condition? c)
671 ;; Normally '&message' error conditions have an i18n'd message.
673 (gettext (condition-message c) %gettext-domain))))
674 ;; Catch EPIPE and the likes.
677 (lambda (key proc format-string format-args . rest)
678 (leave (G_ "~a: ~a~%") proc
679 (apply format #f format-string format-args))))))
681 (define-syntax-rule (leave-on-EPIPE exp ...)
682 "Run EXP... in a context when EPIPE errors are caught and lead to 'exit'
683 with successful exit code. This is useful when writing to the standard output
684 may lead to EPIPE, because the standard output is piped through 'head' or
690 ;; We really have to exit this brutally, otherwise Guile eventually
691 ;; attempts to flush all the ports, leading to an uncaught EPIPE down
693 (if (= EPIPE (system-error-errno args))
695 (apply throw args)))))
697 (define %guix-user-module
698 ;; Module in which user expressions are evaluated.
699 ;; Compute lazily to avoid circularity with (guix gexp).
701 (let ((module (make-module)))
702 (beautify-user-module! module)
703 ;; Use (guix gexp) so that one can use #~ & co.
704 (module-use! module (resolve-interface '(guix gexp)))
707 (define (read/eval str)
708 "Read and evaluate STR, raising an error if something goes wrong."
711 (call-with-input-string str read))
713 (leave (G_ "failed to read expression ~s: ~s~%")
717 (eval exp (force %guix-user-module)))
719 (report-error (G_ "failed to evaluate expression '~a':~%") exp)
721 (('syntax-error proc message properties form . rest)
722 (report-error (G_ "syntax error: ~a~%") message))
724 (if (message-condition? obj)
725 (report-error (G_ "~a~%")
726 (gettext (condition-message obj)
728 (report-error (G_ "exception thrown: ~s~%") obj)))
730 (apply display-error #f (current-error-port) args))
734 (define (read/eval-package-expression str)
735 "Read and evaluate STR and return the package it refers to, or exit an
737 (match (read/eval str)
740 (leave (G_ "expression ~s does not evaluate to a package~%")
743 (define (show-derivation-outputs derivation)
744 "Show the output file names of DERIVATION."
745 (format #t "~{~a~%~}"
748 (derivation->output-path derivation out-name)))
749 (derivation-outputs derivation))))
751 (define (check-available-space need)
752 "Make sure at least NEED bytes are available in the store. Otherwise emit a
754 (let ((free (catch 'system-error
756 (free-disk-space (%store-prefix)))
758 (when (and free (>= need free))
759 (warning (G_ "at least ~,1h MB needed but only ~,1h MB available in ~a~%")
760 (/ need 1e6) (/ free 1e6) (%store-prefix)))))
762 (define* (show-what-to-build store drv
763 #:key dry-run? (use-substitutes? #t)
764 (mode (build-mode normal)))
765 "Show what will or would (depending on DRY-RUN?) be built in realizing the
766 derivations listed in DRV using MODE, a 'build-mode' value. Return #t if
767 there's something to build, #f otherwise. When USE-SUBSTITUTES?, check and
768 report what is prerequisites are available for download."
769 (define substitutable-info
770 ;; Call 'substitutation-oracle' upfront so we don't end up launching the
771 ;; substituter many times. This makes a big difference, especially when
772 ;; DRV is a long list as is the case with 'guix environment'.
774 (substitution-oracle store drv #:mode mode)
777 (define (built-or-substitutable? drv)
778 (or (null? (derivation-outputs drv))
779 (let ((out (derivation->output-path drv))) ;XXX: assume "out" exists
780 (or (valid-path? store out)
781 (substitutable-info out)))))
783 (let*-values (((build download)
784 (fold2 (lambda (drv build download)
786 (derivation-prerequisites-to-build
790 substitutable-info)))
791 (values (append b build)
792 (append d download))))
795 ((build) ; add the DRV themselves
797 (append (map derivation-file-name
798 (remove built-or-substitutable? drv))
799 (map derivation-input-path build))))
800 ((download) ; add the references of DOWNLOAD
804 (filter-map (lambda (item)
805 (if (valid-path? store item)
807 (substitutable-info item)))
809 substitutable-references
812 (define installed-size
813 (reduce + 0 (map substitutable-nar-size download)))
815 (define download-size
816 (/ (reduce + 0 (map substitutable-download-size download))
819 (define display-download-size?
820 ;; Sometimes narinfos lack information about the download size. Only
821 ;; display when we have information for all of DOWNLOAD.
822 (not (any (compose zero? substitutable-download-size) download)))
826 (format (current-error-port)
827 (N_ "~:[The following derivation would be built:~%~{ ~a~%~}~;~]"
828 "~:[The following derivations would be built:~%~{ ~a~%~}~;~]"
831 (if display-download-size?
832 (format (current-error-port)
833 ;; TRANSLATORS: "MB" is for "megabyte"; it should be
834 ;; translated to the corresponding abbreviation.
835 (G_ "~:[~,1h MB would be downloaded:~%~{ ~a~%~}~;~]")
838 (map substitutable-path download))
839 (format (current-error-port)
840 (N_ "~:[The following file would be downloaded:~%~{ ~a~%~}~;~]"
841 "~:[The following files would be downloaded:~%~{ ~a~%~}~;~]"
844 (map substitutable-path download))))
846 (format (current-error-port)
847 (N_ "~:[The following derivation will be built:~%~{ ~a~%~}~;~]"
848 "~:[The following derivations will be built:~%~{ ~a~%~}~;~]"
851 (if display-download-size?
852 (format (current-error-port)
853 ;; TRANSLATORS: "MB" is for "megabyte"; it should be
854 ;; translated to the corresponding abbreviation.
855 (G_ "~:[~,1h MB will be downloaded:~%~{ ~a~%~}~;~]")
858 (map substitutable-path download))
859 (format (current-error-port)
860 (N_ "~:[The following file will be downloaded:~%~{ ~a~%~}~;~]"
861 "~:[The following files will be downloaded:~%~{ ~a~%~}~;~]"
864 (map substitutable-path download)))))
866 (check-available-space installed-size)
870 (define show-what-to-build*
871 (store-lift show-what-to-build))
873 (define (right-arrow port)
874 "Return either a string containing the 'RIGHT ARROW' character, or an ASCII
875 replacement if PORT is not Unicode-capable."
876 (let ((encoding (port-encoding port))
878 (catch 'encoding-error
880 (call-with-output-string
882 (set-port-encoding! port encoding)
883 (set-port-conversion-strategy! port 'error)
884 (display arrow port))))
888 (define* (show-manifest-transaction store manifest transaction
890 "Display what will/would be installed/removed from MANIFEST by TRANSACTION."
891 (define (package-strings name version output item)
892 (map (lambda (name version output item)
893 (format #f " ~a~:[:~a~;~*~]\t~a\t~a"
895 (equal? output "out") output version
897 (package-output store item output)
899 name version output item))
901 (define → ;an arrow that can be represented on stderr
902 (right-arrow (current-error-port)))
904 (define (upgrade-string name old-version new-version output item)
905 (format #f " ~a~:[:~a~;~*~]\t~a ~a ~a\t~a"
906 name (equal? output "out") output
907 old-version → new-version
909 (package-output store item output)
912 (let-values (((remove install upgrade downgrade)
913 (manifest-transaction-effects manifest transaction)))
915 ((($ <manifest-entry> name version output item) ..1)
916 (let ((len (length name))
917 (remove (package-strings name version output item)))
919 (format (current-error-port)
920 (N_ "The following package would be removed:~%~{~a~%~}~%"
921 "The following packages would be removed:~%~{~a~%~}~%"
924 (format (current-error-port)
925 (N_ "The following package will be removed:~%~{~a~%~}~%"
926 "The following packages will be removed:~%~{~a~%~}~%"
931 (((($ <manifest-entry> name old-version)
932 . ($ <manifest-entry> _ new-version output item)) ..1)
933 (let ((len (length name))
934 (downgrade (map upgrade-string
935 name old-version new-version output item)))
937 (format (current-error-port)
938 (N_ "The following package would be downgraded:~%~{~a~%~}~%"
939 "The following packages would be downgraded:~%~{~a~%~}~%"
942 (format (current-error-port)
943 (N_ "The following package will be downgraded:~%~{~a~%~}~%"
944 "The following packages will be downgraded:~%~{~a~%~}~%"
949 (((($ <manifest-entry> name old-version)
950 . ($ <manifest-entry> _ new-version output item)) ..1)
951 (let ((len (length name))
952 (upgrade (map upgrade-string
953 name old-version new-version output item)))
955 (format (current-error-port)
956 (N_ "The following package would be upgraded:~%~{~a~%~}~%"
957 "The following packages would be upgraded:~%~{~a~%~}~%"
960 (format (current-error-port)
961 (N_ "The following package will be upgraded:~%~{~a~%~}~%"
962 "The following packages will be upgraded:~%~{~a~%~}~%"
967 ((($ <manifest-entry> name version output item _) ..1)
968 (let ((len (length name))
969 (install (package-strings name version output item)))
971 (format (current-error-port)
972 (N_ "The following package would be installed:~%~{~a~%~}~%"
973 "The following packages would be installed:~%~{~a~%~}~%"
976 (format (current-error-port)
977 (N_ "The following package will be installed:~%~{~a~%~}~%"
978 "The following packages will be installed:~%~{~a~%~}~%"
983 (define-syntax with-error-handling
985 "Run BODY within a user-friendly error condition handler."
987 (call-with-error-handling
991 (define (location->string loc)
992 "Return a human-friendly, GNU-standard representation of LOC."
994 (#f (G_ "<unknown location>"))
995 (($ <location> file line column)
996 (format #f "~a:~a:~a" file line column))))
998 (define* (fill-paragraph str width #:optional (column 0))
999 "Fill STR such that each line contains at most WIDTH characters, assuming
1000 that the first character is at COLUMN.
1002 When STR contains a single line break surrounded by other characters, it is
1003 converted to a space; sequences of more than one line break are preserved."
1004 (define (maybe-break chr result)
1006 ((column newlines chars)
1009 `(,column ,(+ 1 newlines) ,chars))
1011 (let* ((spaces (if (and (pair? chars) (eqv? (car chars) #\.)) 2 1))
1012 (chars (case newlines
1015 (append (make-list spaces #\space) chars))
1017 (append (make-list newlines #\newline) chars))))
1018 (column (case newlines
1020 ((1) (+ spaces column))
1022 (let ((chars (cons chr chars))
1023 (column (+ 1 column)))
1024 (if (> column width)
1025 (let*-values (((before after)
1026 (break (cut eqv? #\space <>) chars))
1036 (drop-while (cut eqv? #\space <>)
1038 `(,column 0 ,chars))) ; unbreakable
1039 `(,column 0 ,chars)))))))))
1041 (match (string-fold maybe-break
1044 ((column newlines chars)
1045 (list->string (reverse chars)))))
1053 (make-parameter (terminal-columns)))
1055 (set! (@@ (texinfo plain-text) wrap*)
1056 ;; XXX: Monkey patch this private procedure to let 'package->recutils'
1057 ;; parameterize the fill of description field correctly.
1059 (let ((indent (fluid-ref (@@ (texinfo plain-text) *indent*))))
1060 (fill-string (string-concatenate strings)
1061 #:line-width (%text-width) #:initial-indent indent
1062 #:subsequent-indent indent))))
1064 (define (texi->plain-text str)
1065 "Return a plain-text representation of texinfo fragment STR."
1066 ;; 'texi-fragment->stexi' uses a string port so make sure it's a
1067 ;; Unicode-capable one (see <http://bugs.gnu.org/11197>.)
1068 (with-fluids ((%default-port-encoding "UTF-8"))
1069 (stexi->plain-text (texi-fragment->stexi str))))
1071 (define (package-field-string package field-accessor)
1072 "Return a plain-text representation of PACKAGE field."
1073 (and=> (field-accessor package)
1074 (compose texi->plain-text P_)))
1076 (define (package-description-string package)
1077 "Return a plain-text representation of PACKAGE description field."
1078 (package-field-string package package-description))
1080 (define (package-synopsis-string package)
1081 "Return a plain-text representation of PACKAGE synopsis field."
1082 (package-field-string package package-synopsis))
1084 (define (string->recutils str)
1085 "Return a version of STR where newlines have been replaced by newlines
1086 followed by \"+ \", which makes for a valid multi-line field value in the
1089 (string-fold-right (lambda (chr result)
1090 (if (eqv? chr #\newline)
1091 (cons* chr #\+ #\space result)
1096 (define* (package->recutils p port #:optional (width (%text-width))
1097 #:key (extra-fields '()))
1098 "Write to PORT a `recutils' record of package P, arranging to fit within
1099 WIDTH columns. EXTRA-FIELDS is a list of symbol/value pairs to emit."
1101 ;; The available number of columns once we've taken into account space for
1102 ;; the initial "+ " prefix.
1103 (if (> width 2) (- width 2) width))
1105 (define (dependencies->recutils packages)
1106 (let ((list (string-join (delete-duplicates
1107 (map package-full-name
1108 (sort packages package<?))) " ")))
1110 (fill-paragraph list width*
1111 (string-length "dependencies: ")))))
1113 (define (package<? p1 p2)
1114 (string<? (package-full-name p1) (package-full-name p2)))
1116 ;; Note: Don't i18n field names so that people can post-process it.
1117 (format port "name: ~a~%" (package-name p))
1118 (format port "version: ~a~%" (package-version p))
1119 (format port "outputs: ~a~%" (string-join (package-outputs p)))
1120 (format port "systems: ~a~%"
1121 (string-join (package-transitive-supported-systems p)))
1122 (format port "dependencies: ~a~%"
1123 (match (package-direct-inputs p)
1124 (((labels inputs . _) ...)
1125 (dependencies->recutils (filter package? inputs)))))
1126 (format port "location: ~a~%"
1127 (or (and=> (package-location p) location->string)
1130 ;; Note: Starting from version 1.6 or recutils, hyphens are not allowed in
1131 ;; field identifiers.
1132 (format port "homepage: ~a~%" (package-home-page p))
1134 (format port "license: ~a~%"
1135 (match (package-license p)
1136 (((? license? licenses) ...)
1137 (string-join (map license-name licenses)
1139 ((? license? license)
1140 (license-name license))
1143 (format port "synopsis: ~a~%"
1144 (string-map (match-lambda
1147 (or (and=> (package-synopsis-string p) P_)
1152 (parameterize ((%text-width width*))
1154 (string-append "description: "
1155 (or (and=> (package-description p) P_)
1158 (for-each (match-lambda
1160 (let ((field (symbol->string field)))
1161 (format port "~a: ~a~%"
1163 (fill-paragraph (object->string value) width*
1164 (string-length field))))))
1168 (define (relevance obj regexps metrics)
1169 "Compute a \"relevance score\" for OBJ as a function of its number of
1170 matches of REGEXPS and accordingly to METRICS. METRICS is list of
1171 field/weight pairs, where FIELD is a procedure that returns a string
1172 describing OBJ, and WEIGHT is a positive integer denoting the weight of this
1173 field in the final score.
1175 A score of zero means that OBJ does not match any of REGEXPS. The higher the
1176 score, the more relevant OBJ is to REGEXPS."
1178 (let ((counts (filter-map (lambda (regexp)
1179 (match (regexp-exec regexp str)
1181 (m (match:count m))))
1183 ;; Compute a score that's proportional to the number of regexps matched
1184 ;; and to the number of matches for each regexp.
1185 (* (length counts) (reduce + 0 counts))))
1187 (fold (lambda (metric relevance)
1193 (* (score str) weight)))))))
1197 (define %package-metrics
1198 ;; Metrics used to compute the "relevance score" of a package against a set
1200 `((,package-name . 4)
1201 (,package-synopsis-string . 3)
1202 (,package-description-string . 2)
1204 (match (and=> (package-location type) location-file)
1205 ((? string? file) (basename file ".scm"))
1209 (define (package-relevance package regexps)
1210 "Return a score denoting the relevance of PACKAGE for REGEXPS. A score of
1211 zero means that PACKAGE does not match any of REGEXPS."
1212 (relevance package regexps %package-metrics))
1214 (define (string->generations str)
1215 "Return the list of generations matching a pattern in STR. This function
1216 accepts the following patterns: \"1\", \"1,2,3\", \"1..9\", \"1..\", \"..9\"."
1217 (define (maybe-integer)
1218 (let ((x (string->number str)))
1222 (define (maybe-comma-separated-integers)
1223 (let ((lst (delete-duplicates
1225 (string-split str #\,)))))
1226 (and (every integer? lst)
1229 (cond ((maybe-integer)
1232 ((maybe-comma-separated-integers)
1235 ((string-match "^([0-9]+)\\.\\.([0-9]+)$" str)
1238 (let ((s (string->number (match:substring match 1)))
1239 (e (string->number (match:substring match 2))))
1240 (and (every integer? (list s e))
1242 (iota (1+ (- e s)) s)))))
1243 ((string-match "^([0-9]+)\\.\\.$" str)
1246 (let ((s (string->number (match:substring match 1))))
1249 ((string-match "^\\.\\.([0-9]+)$" str)
1252 (let ((e (string->number (match:substring match 1))))
1257 (define (string->duration str)
1258 "Return the duration matching a pattern in STR. This function accepts the
1259 following patterns: \"1d\", \"1w\", \"1m\"."
1260 (define (hours->duration hours match)
1261 (make-time time-duration 0
1262 (* 3600 hours (string->number (match:substring match 1)))))
1264 (cond ((string-match "^([0-9]+)s$" str)
1267 (make-time time-duration 0
1268 (string->number (match:substring match 1)))))
1269 ((string-match "^([0-9]+)h$" str)
1272 (hours->duration 1 match)))
1273 ((string-match "^([0-9]+)d$" str)
1276 (hours->duration 24 match)))
1277 ((string-match "^([0-9]+)w$" str)
1280 (hours->duration (* 24 7) match)))
1281 ((string-match "^([0-9]+)m$" str)
1284 (hours->duration (* 24 30) match)))
1287 (define* (matching-generations str profile
1288 #:key (duration-relation <=))
1289 "Return the list of available generations matching a pattern in STR. See
1290 'string->generations' and 'string->duration' for the list of valid patterns.
1291 When STR is a duration pattern, return all the generations whose ctime has
1292 DURATION-RELATION with the current time."
1293 (define (valid-generations lst)
1294 (define (valid-generation? n)
1295 (any (cut = n <>) (generation-numbers profile)))
1297 (fold-right (lambda (x acc)
1298 (if (valid-generation? x)
1304 (define (filter-generations generations)
1308 (drop-while (cut > n <>)
1309 (generation-numbers profile)))
1311 (valid-generations (iota n 1)))
1313 (valid-generations lst))
1316 (define (filter-by-duration duration)
1317 (define (time-at-midnight time)
1318 ;; Return TIME at midnight by setting nanoseconds, seconds, minutes, and
1320 (let ((d (time-utc->date time)))
1323 (date-day d) (date-month d)
1324 (date-year d) (date-zone-offset d)))))
1326 (define generation-ctime-alist
1327 (map (lambda (number)
1331 (generation-time profile number)))))
1332 (generation-numbers profile)))
1337 (let ((s (time-second
1338 (subtract-duration (time-at-midnight (current-time))
1340 (delete #f (map (lambda (x)
1341 (and (duration-relation s (cdr x))
1343 generation-ctime-alist))))))
1345 (cond ((string->generations str)
1348 ((string->duration str)
1353 (define (display-generation profile number)
1354 "Display a one-line summary of generation NUMBER of PROFILE."
1355 (unless (zero? number)
1356 (let ((header (format #f (G_ "Generation ~a\t~a") number
1359 (generation-time profile number))
1361 (current (generation-number profile)))
1362 (if (= number current)
1363 ;; TRANSLATORS: The word "current" here is an adjective for
1364 ;; "Generation", as in "current generation". Use the appropriate
1365 ;; gender where applicable.
1366 (format #t (G_ "~a\t(current)~%") header)
1367 (format #t "~a~%" header)))))
1369 (define (display-profile-content-diff profile gen1 gen2)
1370 "Display the changed packages in PROFILE GEN2 compared to generation GEN2."
1372 (define (equal-entry? first second)
1373 (string= (manifest-entry-item first) (manifest-entry-item second)))
1375 (define (display-entry entry prefix)
1377 (($ <manifest-entry> name version output location _)
1378 (format #t " ~a ~a\t~a\t~a\t~a~%" prefix name version output location))))
1380 (define (list-entries number)
1381 (manifest-entries (profile-manifest (generation-file-name profile number))))
1383 (define (display-diff profile old new)
1384 (display-generation profile new)
1385 (let ((added (lset-difference
1386 equal-entry? (list-entries new) (list-entries old)))
1387 (removed (lset-difference
1388 equal-entry? (list-entries old) (list-entries new))))
1389 (for-each (cut display-entry <> "+") added)
1390 (for-each (cut display-entry <> "-") removed)
1393 (display-diff profile gen1 gen2))
1395 (define (display-profile-content profile number)
1396 "Display the packages in PROFILE, generation NUMBER, in a human-readable
1398 (for-each (match-lambda
1399 (($ <manifest-entry> name version output location _)
1400 (format #t " ~a\t~a\t~a\t~a~%"
1401 name version output location)))
1403 ;; Show most recently installed packages last.
1406 (profile-manifest (generation-file-name profile number))))))
1408 (define (display-generation-change previous current)
1409 (format #t (G_ "switched from generation ~a to ~a~%") previous current))
1411 (define (roll-back* store profile)
1412 "Like 'roll-back', but display what is happening."
1415 (roll-back store profile))
1416 display-generation-change))
1418 (define (switch-to-generation* profile number)
1419 "Like 'switch-generation', but display what is happening."
1420 (let ((previous (switch-to-generation profile number)))
1421 (display-generation-change previous number)))
1423 (define (delete-generation* store profile generation)
1424 "Like 'delete-generation', but display what is going on."
1425 (format #t (G_ "deleting ~a~%")
1426 (generation-file-name profile generation))
1427 (delete-generation store profile generation))
1429 (define* (package-specification->name+version+output spec
1430 #:optional (output "out"))
1431 "Parse package specification SPEC and return three value: the specified
1432 package name, version number (or #f), and output name (or OUTPUT). SPEC may
1433 optionally contain a version number and an output name, as in these examples:
1440 (let*-values (((name sub-drv)
1441 (match (string-rindex spec #\:)
1442 (#f (values spec output))
1443 (colon (values (substring spec 0 colon)
1444 (substring spec (+ 1 colon))))))
1446 (package-name->name+version name)))
1447 (values name version sub-drv)))
1451 ;;; Command-line option processing.
1454 (define (show-guix-usage)
1455 (format (current-error-port)
1456 (G_ "Try `guix --help' for more information.~%"))
1459 (define (command-files)
1460 "Return the list of source files that define Guix sub-commands."
1462 (and=> (search-path %load-path "guix.scm")
1463 (compose (cut string-append <> "/guix/scripts")
1467 (cut string-suffix? ".scm" <>))
1470 (scandir directory dot-scm?)
1474 "Return the list of Guix command names."
1475 (map (compose (cut string-drop-right <> 4)
1479 (define (show-guix-help)
1480 (define (internal? command)
1481 (member command '("substitute" "authenticate" "offload"
1482 "perform-download")))
1484 (format #t (G_ "Usage: guix COMMAND ARGS...
1485 Run COMMAND with ARGS.\n"))
1487 (format #t (G_ "COMMAND must be one of the sub-commands listed below:\n"))
1489 ;; TODO: Display a synopsis of each command.
1490 (format #t "~{ ~a~%~}" (sort (remove internal? (commands))
1492 (show-bug-report-information))
1494 (define program-name
1495 ;; Name of the command-line program currently executing, or #f.
1496 (make-parameter #f))
1498 (define (run-guix-command command . args)
1499 "Run COMMAND with the given ARGS. Report an error when COMMAND is not
1504 (resolve-interface `(guix scripts ,command)))
1506 (format (current-error-port)
1507 (G_ "guix: ~a: command not found~%") command)
1508 (show-guix-usage))))
1510 (let ((command-main (module-ref module
1511 (symbol-append 'guix- command))))
1512 (parameterize ((program-name command))
1513 ;; Disable canonicalization so we don't don't stat unreasonably.
1514 (with-fluids ((%file-port-name-canonicalization #f))
1518 (apply command-main args))
1520 ;; Abuse 'exit-hook' (which is normally meant to be used by the
1521 ;; REPL) to run things like profiling hooks upon completion.
1522 (run-hook exit-hook)))))))
1524 (define (run-guix . args)
1525 "Run the 'guix' command defined by command line ARGS.
1526 Unlike 'guix-main', this procedure assumes that locale, i18n support,
1527 and signal handling has already been set up."
1528 (define option? (cut string-prefix? "-" <>))
1530 ;; The default %LOAD-EXTENSIONS includes the empty string, which doubles the
1531 ;; number of 'stat' calls per entry in %LOAD-PATH. Shamelessly remove it.
1532 (set! %load-extensions '(".scm"))
1536 (format (current-error-port)
1537 (G_ "guix: missing command name~%"))
1539 ((or ("-h") ("--help"))
1542 (show-version-and-exit "guix"))
1543 (((? option? o) args ...)
1544 (format (current-error-port)
1545 (G_ "guix: unrecognized option '~a'~%") o)
1548 (apply run-guix-command (string->symbol command)
1553 (apply run-guix-command
1554 (string->symbol command)
1557 (define guix-warning-port
1558 (make-parameter (current-warning-port)))
1560 (define (guix-main arg0 . args)
1562 (apply run-guix args))
1564 ;;; ui.scm ends here