1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Ludovic Courtès <ludo@gnu.org>
3 ;;; Copyright © 2013, 2018 Mark H Weaver <mhw@netris.org>
4 ;;; Copyright © 2013 Nikita Karetnikov <nikita@karetnikov.org>
5 ;;; Copyright © 2014 Cyril Roelandt <tipecaml@gmail.com>
6 ;;; Copyright © 2014 Cyrill Schenkel <cyrill.schenkel@gmail.com>
7 ;;; Copyright © 2014, 2015, 2017 Alex Kost <alezost@gmail.com>
8 ;;; Copyright © 2015 David Thompson <davet@gnu.org>
9 ;;; Copyright © 2015, 2016 Mathieu Lirzin <mthl@gnu.org>
10 ;;; Copyright © 2016 Roel Janssen <roel@gnu.org>
11 ;;; Copyright © 2016 Benz Schenk <benz.schenk@uzh.ch>
12 ;;; Copyright © 2018 Kyle Meyer <kyle@kyleam.com>
13 ;;; Copyright © 2018 Ricardo Wurmus <rekado@elephly.net>
14 ;;; Copyright © 2019 Chris Marusich <cmmarusich@gmail.com>
15 ;;; Copyright © 2019 Tobias Geerinckx-Rice <me@tobias.gr>
16 ;;; Copyright © 2019 Simon Tournier <zimon.toutoune@gmail.com>
17 ;;; Copyright © 2020 Arun Isaac <arunisaac@systemreboot.net>
18 ;;; Copyright © 2020 Maxim Cournoyer <maxim.cournoyer@gmail.com>
20 ;;; This file is part of GNU Guix.
22 ;;; GNU Guix is free software; you can redistribute it and/or modify it
23 ;;; under the terms of the GNU General Public License as published by
24 ;;; the Free Software Foundation; either version 3 of the License, or (at
25 ;;; your option) any later version.
27 ;;; GNU Guix is distributed in the hope that it will be useful, but
28 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
29 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
30 ;;; GNU General Public License for more details.
32 ;;; You should have received a copy of the GNU General Public License
33 ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
35 (define-module (guix ui)
36 #:use-module (guix i18n)
37 #:use-module (guix colors)
38 #:use-module (guix diagnostics)
39 #:use-module (guix gexp)
40 #:use-module (guix sets)
41 #:use-module (guix utils)
42 #:use-module (guix store)
43 #:use-module (guix config)
44 #:use-module (guix packages)
45 #:use-module (guix profiles)
46 #:use-module (guix derivations)
47 #:use-module (guix build-system)
48 #:use-module (guix serialization)
49 #:use-module ((guix licenses)
50 #:select (license? license-name license-uri))
51 #:use-module ((guix build syscalls)
52 #:select (free-disk-space terminal-columns terminal-rows
53 with-file-lock/no-wait))
54 #:use-module ((guix build utils)
55 ;; XXX: All we need are the bindings related to
56 ;; '&invoke-error'. However, to work around the bug described
57 ;; in 5d669883ecc104403c5d3ba7d172e9c02234577c, #:hide
58 ;; unwanted bindings instead of #:select'ing the needed
60 #:hide (package-name->name+version
61 ;; Avoid "overrides core binding" warning.
63 #:use-module (srfi srfi-1)
64 #:use-module (srfi srfi-9 gnu)
65 #:use-module (srfi srfi-11)
66 #:use-module (srfi srfi-19)
67 #:use-module (srfi srfi-26)
68 #:use-module (srfi srfi-31)
69 #:use-module (srfi srfi-34)
70 #:use-module (srfi srfi-35)
71 #:autoload (ice-9 ftw) (scandir)
72 #:use-module (ice-9 match)
73 #:use-module (ice-9 format)
74 #:use-module (ice-9 regex)
75 #:autoload (ice-9 popen) (open-pipe* close-pipe)
76 #:autoload (system base compile) (compile-file)
77 #:autoload (system repl repl) (start-repl)
78 #:autoload (system repl debug) (make-debug stack->vector)
79 #:autoload (web uri) (encode-and-join-uri-path)
80 #:use-module (texinfo)
81 #:use-module (texinfo plain-text)
82 #:use-module (texinfo string-utils)
84 ;; Re-exports for backward compatibility.
85 #:re-export (G_ N_ P_ ;now in (guix i18n)
87 warning info report-error leave ;now in (guix diagnostics)
89 guix-warning-port program-name)
90 #:export (display-hint
95 show-bug-report-information
99 show-derivation-outputs
103 show-manifest-transaction
104 call-with-error-handling
106 with-unbound-variable-handling
109 read/eval-package-expression
110 check-available-space
115 package-description-string
116 package-synopsis-string
119 package-specification->name+version+output
126 with-paginated-output-port
129 display-search-results
136 display-profile-content
137 display-profile-content-diff
139 switch-to-generation*
142 %default-message-language
143 current-message-language
151 ;;; User interface facilities for command-line tools.
155 (define (print-unbound-variable-error port key args default-printer)
156 ;; Print unbound variable errors more nicely, and in the right language.
158 ((proc message (variable) _ ...)
159 ;; We can always omit PROC because when it's useful (i.e., different from
160 ;; "module-lookup"), it gets displayed before.
161 (format port (G_ "error: ~a: unbound variable") variable))
165 (set-exception-printer! 'unbound-variable print-unbound-variable-error)
167 (define (make-user-module modules)
168 "Return a new user module with the additional MODULES loaded."
169 ;; Module in which the machine description file is loaded.
170 (let ((module (make-fresh-user-module)))
171 (for-each (lambda (iface)
172 (module-use! module (resolve-interface iface)))
176 (define (last-frame-with-source stack)
177 "Walk stack upwards and return the last frame that has source location
178 information, or #f if it could not be found."
179 (define (frame-with-source frame)
180 ;; Walk from FRAME upwards until source location information is found.
181 (let loop ((frame frame)
186 ;; On Guile 3, the latest frame with source may be that of
187 ;; 'raise-exception' in boot-9.scm. Skip it.
188 (if (and (frame-source frame)
189 (not (eq? 'raise-exception (frame-procedure-name frame))))
191 (loop (frame-previous frame) frame)))))
193 (let* ((depth (stack-length stack))
194 (last (and (> depth 0) (stack-ref stack 0))))
195 (frame-with-source (if (> depth 1)
196 (stack-ref stack 1) ;skip the 'throw' frame
199 (define* (load* file user-module
200 #:key (on-error 'nothing-special))
201 "Load the user provided Scheme source code FILE."
202 (define (error-string frame args)
203 (call-with-output-string
205 (apply display-error frame port (cdr args)))))
208 (make-prompt-tag "user-code"))
212 ;; XXX: Force a recompilation to avoid ABI issues.
214 ;; In 2.2.3, the bogus answer to <https://bugs.gnu.org/29226> was to
215 ;; ignore all available .go, not just those from ~/.cache, which in turn
216 ;; meant that we had to rebuild *everything*. Since this is too costly,
217 ;; we have to turn off '%fresh-auto-compile' with that version, so to
218 ;; avoid ABI breakage in the user's config file, we explicitly compile
219 ;; it (the problem remains if the user's config is spread on several
220 ;; modules.) See <https://bugs.gnu.org/29881>.
221 (unless (string=? (version) "2.2.3")
222 (set! %fresh-auto-compile #t))
224 (set! %load-should-auto-compile #t)
226 (save-module-excursion
228 (set-current-module user-module)
230 ;; Hide the "auto-compiling" messages.
231 (parameterize ((current-warning-port (%make-void-port "w")))
232 (call-with-prompt tag
234 (when (string=? (version) "2.2.3")
237 (compile-file file #:env user-module))
238 (const #f))) ;EACCES maybe, let's interpret it
240 ;; Give 'load' an absolute file name so that it doesn't try to
241 ;; search for FILE in %LOAD-PATH. Note: use 'load', not
242 ;; 'primitive-load', so that FILE is compiled, which then allows
243 ;; us to provide better error reporting with source line numbers.
244 (load (canonicalize-path file)))
247 ;; XXX: Errors are reported from the pre-unwind handler below, but
248 ;; calling 'exit' from there has no effect, so we call it here.
250 (rec (handle-error . args)
251 ;; Capture the stack up to this procedure call, excluded, and pass
252 ;; the faulty stack frame to 'report-load-error'.
253 (let* ((stack (make-stack #t handle-error tag))
254 (frame (last-frame-with-source stack)))
256 (report-load-error file args frame)
261 (display (G_ "entering debugger; type ',bt' for a backtrace\n"))
262 (start-repl #:debug (make-debug (stack->vector stack) 0
263 (error-string frame args)
266 (newline (current-error-port))
267 (display-backtrace stack (current-error-port)))
271 (define (known-variable-definition variable)
272 "Search among the currently loaded modules one that defines a variable named
273 VARIABLE and return it, or #f if none was found."
274 (define (module<? m1 m2)
275 (match (module-name m2)
278 (match (module-name m1)
283 (let loop ((modules (list (resolve-module '() #f #f #:ensure #f)))
288 ;; Pick the "best" suggestion.
289 (match (sort suggestions module<?)
291 ((first _ ...) first)))
293 (if (set-contains? visited head)
294 (loop tail suggestions visited)
295 (let ((visited (set-insert head visited))
297 (hash-map->list (lambda (name module)
299 (module-submodules head)))))
300 (match (module-local-variable head variable)
301 (#f (loop next suggestions visited))
303 (match (module-name head)
304 (('gnu _ ...) head) ;must be that one
305 (_ (loop next (cons head suggestions) visited)))))))))))
307 (define %hint-color (color BOLD CYAN))
309 (define* (display-hint message #:optional (port (current-error-port)))
310 "Display MESSAGE, a l10n message possibly containing Texinfo markup, to
313 (if (color-output? port)
315 (colorize-string str %hint-color))
318 (display (colorize (G_ "hint: ")) port)
320 ;; XXX: We should arrange so that the initial indent is wider.
321 (parameterize ((%text-width (max 15 (- (terminal-columns) 5))))
322 (texi->plain-text message))
325 (define* (report-unbound-variable-error args #:key frame)
326 "Return the given unbound-variable error, where ARGS is the list of 'throw'
330 (print-exception (current-error-port) frame key args)))
332 (('unbound-variable proc message (variable) _ ...)
333 (match (known-variable-definition variable)
335 (display-hint (G_ "Did you forget a @code{use-modules} form?")))
337 (display-hint (format #f (G_ "Did you forget @code{(use-modules ~a)}?")
338 (module-name module))))))))
340 (define (check-module-matches-file module file)
341 "Check whether FILE starts with 'define-module MODULE' and print a hint if
343 ;; This is a common mistake when people start writing their own package
344 ;; definitions and try loading them with 'guix build -L …', so help them
345 ;; diagnose the problem.
347 (display-hint (format #f (G_ "File @file{~a} should probably start with:
349 @example\n(define-module ~a)\n@end example")
354 (let* ((sexp (call-with-input-file file read))
355 (loc (and (pair? sexp)
356 (source-properties->location (source-properties sexp)))))
358 (('define-module (names ...) _ ...)
359 (unless (equal? module names)
361 (G_ "module name ~a does not match file name '~a'~%")
362 names (module->source-file-name module))
365 (warning (G_ "~a: file is empty~%") file))
370 (define* (report-load-error file args #:optional frame)
371 "Report the failure to load FILE, a user-provided Scheme file.
372 ARGS is the list of arguments received by the 'throw' handler."
374 (('system-error . rest)
375 (let ((err (system-error-errno args)))
376 (report-error (G_ "failed to load '~a': ~a~%") file (strerror err))))
377 (('read-error "scm_i_lreadparen" message _ ...)
378 ;; Guile's missing-paren messages are obscure so we make them more
379 ;; intelligible here.
380 (if (string-suffix? "end of file" message)
381 (let ((location (string-drop-right message
382 (string-length "end of file"))))
383 (format (current-error-port) (G_ "~amissing closing parenthesis~%")
386 (('syntax-error proc message properties form subform . rest)
387 (let ((loc (source-properties->location properties)))
388 (report-error loc (G_ "~s: ~a~%")
389 (or subform form) message)))
390 (('unbound-variable _ ...)
391 (report-unbound-variable-error args #:frame frame))
392 (((or 'srfi-34 '%exception) obj)
393 (cond ((message-condition? obj)
394 (report-error (and (error-location? obj)
395 (error-location obj))
397 (gettext (condition-message obj) %gettext-domain)))
398 ((formatted-message? obj)
400 (and (error-location? obj) (error-location obj))
401 (gettext (formatted-message-string obj) %gettext-domain)
402 (formatted-message-arguments obj)))
404 (report-error (G_ "exception thrown: ~s~%") obj)))
405 (when (fix-hint? obj)
406 (display-hint (condition-fix-hint obj))))
408 (report-error (G_ "failed to load '~a':~%") file)
410 (((? symbol? proc) (? string? message) (args ...) . rest)
411 (display-error frame (current-error-port) proc message
414 ;; Some exceptions like 'git-error' do not follow Guile's convention
415 ;; above and need to be printed with 'print-exception'.
416 (print-exception (current-error-port) frame key args))))))
418 (define (warn-about-load-error file module args) ;FIXME: factorize with ↑
419 "Report the failure to load FILE, a user-provided Scheme file, without
420 exiting. ARGS is the list of arguments received by the 'throw' handler."
422 (('system-error . rest)
423 (let ((err (system-error-errno args)))
424 (warning (G_ "failed to load '~a': ~a~%") module (strerror err))))
425 (('syntax-error proc message properties form . rest)
426 (let ((loc (source-properties->location properties)))
427 (warning loc (G_ "~a~%") message)))
428 (('unbound-variable _ ...)
429 (report-unbound-variable-error args))
430 (((or 'srfi-34 '%exception) obj)
431 (cond ((message-condition? obj)
432 (warning (G_ "failed to load '~a': ~a~%")
434 (gettext (condition-message obj) %gettext-domain)))
435 ((formatted-message? obj)
436 (warning (G_ "failed to load '~a': ~a~%")
438 (gettext (formatted-message-string obj)
440 (formatted-message-arguments obj))))
442 (warning (G_ "failed to load '~a': exception thrown: ~s~%")
445 (warning (G_ "failed to load '~a':~%") module)
446 (apply display-error #f (current-error-port) args)
447 (check-module-matches-file module file))))
449 (define (call-with-unbound-variable-handling thunk)
451 (make-prompt-tag "user-code"))
453 (catch 'unbound-variable
455 (call-with-prompt tag
459 (rec (handle-error . args)
460 (let* ((stack (make-stack #t handle-error tag))
461 (frame (and stack (last-frame-with-source stack))))
462 (report-unbound-variable-error args #:frame frame)
465 (define-syntax-rule (with-unbound-variable-handling exp ...)
466 "Capture 'unbound-variable' exceptions in the dynamic extent of EXP... and
467 report them in a user-friendly way."
468 (call-with-unbound-variable-handling (lambda () exp ...)))
470 (define %default-message-language
471 ;; Default language to use for messages.
472 (make-parameter "en"))
474 (define (current-message-language)
475 "Return the language used for messages according to the current locale.
476 Return %DEFAULT-MESSAGE-LANGUAGE if that information could not be obtained. The
477 result is an ISO-639-2 language code such as \"ar\", without the territory
479 (let ((locale (setlocale LC_MESSAGES)))
480 (match (string-index locale #\_)
482 (index (string-take locale index)))))
484 (define (install-locale)
485 "Install the current locale settings."
488 (setlocale LC_ALL ""))
490 (display-hint (G_ "Consider installing the @code{glibc-utf8-locales} or
491 @code{glibc-locales} package and defining @code{GUIX_LOCPATH}, along these
495 guix package -i glibc-utf8-locales
496 export GUIX_LOCPATH=\"$HOME/.guix-profile/lib/locale\"
499 See the \"Application Setup\" section in the manual, for more info.\n"))
500 ;; We're now running in the "C" locale. Try to install a UTF-8 locale
501 ;; instead. This one is guaranteed to be available in 'guix' from 'guix
503 (false-if-exception (setlocale LC_ALL "en_US.utf8")))))
505 (define (initialize-guix)
506 "Perform the usual initialization for stand-alone Guix commands."
507 ;; By default don't annoy users with deprecation warnings. In practice,
508 ;; 'define-deprecated' in (ice-9 deprecated) arranges so that those warnings
509 ;; are emitted at expansion-time only, but there are cases where they could
510 ;; slip through, for instance when interpreting code.
511 (unless (getenv "GUILE_WARN_DEPRECATED")
512 (debug-disable 'warn-deprecated))
515 (textdomain %gettext-domain)
517 ;; Ignore SIGPIPE. If the daemon closes the connection, we prefer to be
518 ;; notified via an EPIPE later.
519 (sigaction SIGPIPE SIG_IGN)
521 (setvbuf (current-output-port) 'line)
522 (setvbuf (current-error-port) 'line))
524 (define* (show-version-and-exit #:optional (command (car (command-line))))
525 "Display version information for COMMAND and `(exit 0)'."
526 (simple-format #t "~a (~a) ~a~%"
527 command %guix-package-name %guix-version)
528 (format #t "Copyright ~a 2020 ~a"
529 ;; TRANSLATORS: Translate "(C)" to the copyright symbol
530 ;; (C-in-a-circle), if this symbol is available in the user's
531 ;; locale. Otherwise, do not translate "(C)"; leave it as-is. */
533 (G_ "the Guix authors\n"))
535 License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
536 This is free software: you are free to change and redistribute it.
537 There is NO WARRANTY, to the extent permitted by law.
541 (define (show-bug-report-information)
542 ;; TRANSLATORS: The placeholder indicates the bug-reporting address for this
543 ;; package. Please add another line saying "Report translation bugs to
544 ;; ...\n" with the address for translation bugs (typically your translation
545 ;; team's web or email address).
547 Report bugs to: ~a.") %guix-bug-report-address)
549 ~a home page: <~a>") %guix-package-name %guix-home-page-url)
551 General help using Guix and GNU software: <~a>")
552 "https://guix.gnu.org/help/")
555 (define (augmented-system-error-handler file)
556 "Return a 'system-error' handler that mentions FILE in its message."
557 (lambda (key proc fmt args errno)
558 ;; Augment the FMT and ARGS with information about TARGET (this
559 ;; information is missing as of Guile 2.0.11, making the exception
561 (apply throw key proc "~A: ~S"
562 (list (strerror (car errno)) file)
565 (define-syntax apply-formals
567 ((_ proc (args ...)) (proc args ...))
568 ((_ proc (arg1 args ... . rest)) (apply proc arg1 args ... rest))))
570 (define-syntax-rule (error-reporting-wrapper proc formals file)
571 "Wrap PROC such that its 'system-error' exceptions are augmented to mention
573 (let ((real-proc (@ (guile) proc)))
577 (apply-formals real-proc formals))
578 (augmented-system-error-handler file)))))
581 ;; We 'set!' the global binding because (gnu build ...) modules and similar
582 ;; typically don't use (guix ui).
583 (error-reporting-wrapper symlink (source target) target))
586 ;; Note: here we use 'set!', not #:replace, because UIs typically use
587 ;; 'copy-recursively', which doesn't use (guix ui).
588 (error-reporting-wrapper copy-file (source target) target))
590 (set! canonicalize-path
591 (error-reporting-wrapper canonicalize-path (file) file))
594 (error-reporting-wrapper delete-file (file) file))
597 (error-reporting-wrapper execlp (filename . args) filename))
599 (define (make-regexp* regexp . flags)
600 "Like 'make-regexp' but error out if REGEXP is invalid, reporting the error
602 (catch 'regular-expression-syntax
604 (apply make-regexp regexp flags))
605 (lambda (key proc message . rest)
606 (leave (G_ "'~a' is not a valid regular expression: ~a~%")
609 (define (string->number* str)
610 "Like `string->number', but error out with an error message on failure."
611 (or (string->number str)
612 (leave (G_ "~a: invalid number~%") str)))
614 (define (size->number str)
615 "Convert STR, a storage measurement representation such as \"1024\" or
616 \"1MiB\", to a number of bytes. Raise an error if STR could not be
620 (char-set-union (char-set #\.) char-set:digit)))
623 (and unit-pos (substring str (+ 1 unit-pos))))
625 (let* ((numstr (if unit-pos
626 (substring str 0 (+ 1 unit-pos))
628 (num (string->number numstr)))
630 (leave (G_ "invalid number: ~a~%") numstr))
632 ((compose inexact->exact round)
635 ((or "KiB" "K" "k") (expt 2 10))
636 ((or "MiB" "M") (expt 2 20))
637 ((or "GiB" "G") (expt 2 30))
638 ((or "TiB" "T") (expt 2 40))
639 ((or "PiB" "P") (expt 2 50))
640 ((or "EiB" "E") (expt 2 60))
641 ((or "ZiB" "Z") (expt 2 70))
642 ((or "YiB" "Y") (expt 2 80))
653 (leave (G_ "unknown unit: ~a~%") unit)))))))
655 (define (display-collision-resolution-hint collision)
656 "Display hints on how to resolve COLLISION, a &profile-collistion-error."
657 (define (top-most-entry entry)
658 (let loop ((entry entry))
659 (match (force (manifest-entry-parent entry))
661 (parent (loop parent)))))
663 (let* ((first (profile-collision-error-entry collision))
664 (second (profile-collision-error-conflict collision))
665 (name1 (manifest-entry-name (top-most-entry first)))
666 (name2 (manifest-entry-name (top-most-entry second))))
667 (if (string=? name1 name2)
668 (display-hint (format #f (G_ "You cannot have two different versions
669 or variants of @code{~a} in the same profile.")
671 (display-hint (format #f (G_ "Try upgrading both @code{~a} and @code{~a},
672 or remove one of them from the profile.")
677 ;; On Guile 3.0, in 'call-with-error-handling' we need to re-raise. To
678 ;; preserve useful backtraces in case of unhandled errors, we want that to
679 ;; happen before the stack has been unwound, hence 'guard*'.
680 (define-syntax-rule (guard* (var clauses ...) exp ...)
681 "This variant of SRFI-34 'guard' does not unwind the stack before
682 evaluating the tests and bodies of CLAUSES."
683 (with-exception-handler
685 (cond clauses ... (else (raise var))))
689 (define-syntax-rule (guard* (var clauses ...) exp ...)
690 (guard (var clauses ...) exp ...))))
692 (define (call-with-error-handling thunk)
693 "Call THUNK within a user-friendly error handler."
694 (define (port-filename* port)
695 ;; 'port-filename' returns #f for non-file ports, but it raises an
696 ;; exception for file ports that are closed. Work around that.
697 (and (not (port-closed? port))
698 (port-filename port)))
700 (guard* (c ((package-input-error? c)
701 (let* ((package (package-error-package c))
702 (input (package-error-invalid-input c))
703 (location (package-location package))
704 (file (location-file location))
705 (line (location-line location))
706 (column (location-column location)))
707 (leave (G_ "~a:~a:~a: package `~a' has an invalid input: ~s~%")
709 (package-full-name package) input)))
710 ((package-cross-build-system-error? c)
711 (let* ((package (package-error-package c))
712 (loc (package-location package))
713 (system (package-build-system package)))
714 (leave (G_ "~a: ~a: build system `~a' does not support cross builds~%")
715 (location->string loc)
716 (package-full-name package)
717 (build-system-name system))))
718 ((gexp-input-error? c)
719 (let ((input (package-error-invalid-input c)))
720 (leave (G_ "~s: invalid G-expression input~%")
721 (gexp-error-invalid-input c))))
722 ((profile-not-found-error? c)
723 (leave (G_ "profile '~a' does not exist~%")
724 (profile-error-profile c)))
725 ((missing-generation-error? c)
726 (leave (G_ "generation ~a of profile '~a' does not exist~%")
727 (missing-generation-error-generation c)
728 (profile-error-profile c)))
729 ((unmatched-pattern-error? c)
730 (let ((pattern (unmatched-pattern-error-pattern c)))
731 (leave (G_ "package '~a~@[@~a~]~@[:~a~]' not found in profile~%")
732 (manifest-pattern-name pattern)
733 (manifest-pattern-version pattern)
734 (match (manifest-pattern-output pattern)
737 ((profile-collision-error? c)
738 (let ((entry (profile-collision-error-entry c))
739 (conflict (profile-collision-error-conflict c)))
740 (define (report-parent-entries entry)
741 (let ((parent (force (manifest-entry-parent entry))))
742 (when (manifest-entry? parent)
743 (report-error (G_ " ... propagated from ~a@~a~%")
744 (manifest-entry-name parent)
745 (manifest-entry-version parent))
746 (report-parent-entries parent))))
748 (define (manifest-entry-output* entry)
749 (match (manifest-entry-output entry)
751 (output (string-append ":" output))))
753 (report-error (G_ "profile contains conflicting entries for ~a~a~%")
754 (manifest-entry-name entry)
755 (manifest-entry-output* entry))
756 (report-error (G_ " first entry: ~a@~a~a ~a~%")
757 (manifest-entry-name entry)
758 (manifest-entry-version entry)
759 (manifest-entry-output* entry)
760 (manifest-entry-item entry))
761 (report-parent-entries entry)
762 (report-error (G_ " second entry: ~a@~a~a ~a~%")
763 (manifest-entry-name conflict)
764 (manifest-entry-version conflict)
765 (manifest-entry-output* conflict)
766 (manifest-entry-item conflict))
767 (report-parent-entries conflict)
768 (display-collision-resolution-hint c)
771 (let ((file (nar-error-file c))
772 (port (nar-error-port c)))
774 (leave (G_ "corrupt input while restoring '~a' from ~s~%")
775 file (or (port-filename* port) port))
776 (leave (G_ "corrupt input while restoring archive from ~s~%")
777 (or (port-filename* port) port)))))
778 ((store-connection-error? c)
779 (leave (G_ "failed to connect to `~a': ~a~%")
780 (store-connection-error-file c)
781 (strerror (store-connection-error-code c))))
782 ((store-protocol-error? c)
783 ;; FIXME: Server-provided error messages aren't i18n'd.
785 (store-protocol-error-message c)))
786 ((derivation-missing-output-error? c)
787 (leave (G_ "reference to invalid output '~a' of derivation '~a'~%")
788 (derivation-missing-output c)
789 (derivation-file-name (derivation-error-derivation c))))
790 ((file-search-error? c)
791 (leave (G_ "file '~a' could not be found in these \
792 directories:~{ ~a~}~%")
793 (file-search-error-file-name c)
794 (file-search-error-search-path c)))
796 (leave (G_ "program exited\
797 ~@[ with non-zero exit status ~a~]\
798 ~@[ terminated by signal ~a~]\
799 ~@[ stopped by signal ~a~]: ~s~%")
800 (invoke-error-exit-status c)
801 (invoke-error-term-signal c)
802 (invoke-error-stop-signal c)
803 (cons (invoke-error-program c)
804 (invoke-error-arguments c))))
806 ((formatted-message? c)
808 (and (error-location? c) (error-location c))
809 (gettext (formatted-message-string c) %gettext-domain)
810 (formatted-message-arguments c))
812 (display-hint (condition-fix-hint c)))
815 ;; On Guile 3.0.0, exceptions such as 'unbound-variable' are
816 ;; compound and include a '&message'. However, that message only
817 ;; contains the format string. Thus, special-case it here to
818 ;; avoid displaying a bare format string.
820 ;; Furthermore, use of 'guard*' ensures that the stack has not
821 ;; been unwound when we re-raise, since that would otherwise show
822 ;; useless backtraces.
825 ((exception-predicate &exception-with-kind-and-args) c))
829 ((message-condition? c)
830 ;; Normally '&message' error conditions have an i18n'd message.
831 (report-error (and (error-location? c) (error-location c))
833 (gettext (condition-message c) %gettext-domain))
835 (display-hint (condition-fix-hint c)))
837 ;; Catch EPIPE and the likes.
840 (lambda (key proc format-string format-args . rest)
841 (leave (G_ "~a: ~a~%") proc
842 (apply format #f format-string format-args))))))
844 (define-syntax-rule (leave-on-EPIPE exp ...)
845 "Run EXP... in a context where EPIPE errors are caught and lead to 'exit'
846 with successful exit code. This is useful when writing to the standard output
847 may lead to EPIPE, because the standard output is piped through 'head' or
853 ;; We really have to exit this brutally, otherwise Guile eventually
854 ;; attempts to flush all the ports, leading to an uncaught EPIPE down
856 (if (= EPIPE (system-error-errno args))
858 (apply throw args)))))
860 (define %guix-user-module
861 ;; Module in which user expressions are evaluated.
862 ;; Compute lazily to avoid circularity with (guix gexp).
864 (let ((module (make-module)))
865 (beautify-user-module! module)
866 ;; Use (guix gexp) so that one can use #~ & co.
867 (module-use! module (resolve-interface '(guix gexp)))
870 (define (read/eval str)
871 "Read and evaluate STR, raising an error if something goes wrong."
874 (call-with-input-string str read))
876 (leave (G_ "failed to read expression ~s: ~s~%")
880 (eval exp (force %guix-user-module)))
882 (report-error (G_ "failed to evaluate expression '~a':~%") exp)
884 (('syntax-error proc message properties form . rest)
885 (report-error (G_ "syntax error: ~a~%") message))
886 (((or 'srfi-34 '%exception) obj)
887 (cond ((message-condition? obj)
888 (report-error (G_ "~a~%")
889 (gettext (condition-message obj)
891 ((formatted-message? obj)
892 (apply report-error #f
893 (gettext (formatted-message-string obj)
895 (formatted-message-arguments obj)))
897 (report-error (G_ "exception thrown: ~s~%") obj))))
899 (apply display-error #f (current-error-port) args))
903 (define (read/eval-package-expression str)
904 "Read and evaluate STR and return the package it refers to, or exit an
906 (match (read/eval str)
909 (leave (G_ "expression ~s does not evaluate to a package~%")
912 (define (show-derivation-outputs derivation)
913 "Show the output file names of DERIVATION, which can be a derivation or a
915 (define (show-outputs derivation outputs)
916 (format #t "~{~a~%~}"
917 (map (cut derivation->output-path derivation <>)
922 (show-outputs derivation (derivation-output-names derivation)))
923 ((? derivation-input? input)
924 (show-outputs (derivation-input-derivation input)
925 (derivation-input-sub-derivations input)))))
927 (define* (check-available-space need
928 #:optional (directory (%store-prefix)))
929 "Make sure at least NEED bytes are available in DIRECTORY. Otherwise emit a
931 (let ((free (catch 'system-error
933 (free-disk-space directory))
935 (when (and free (>= need free))
936 (warning (G_ "at least ~,1h MB needed but only ~,1h MB available in ~a~%")
937 (/ need 1e6) (/ free 1e6) directory))))
939 (define (graft-derivation? drv)
940 "Return true if DRV is definitely a graft derivation, false otherwise."
941 (match (assq-ref (derivation-properties drv) 'type)
945 (define (profile-hook-derivation? drv)
946 "Return true if DRV is definitely a profile hook derivation, false otherwise."
947 (match (assq-ref (derivation-properties drv) 'type)
951 (define (colorize-store-file-name file)
952 "Colorize FILE, a store file name, such that the hash part is less prominent
954 (let ((len (string-length file))
955 (prefix (+ (string-length (%store-prefix)) 32 2)))
958 (string-append (colorize-string (string-take file prefix)
960 (string-drop file prefix)))))
962 (define %default-verbosity
963 ;; Default verbosity level for 'show-what-to-build'.
966 (define* (show-what-to-build store drv
967 #:key dry-run? (use-substitutes? #t)
968 (verbosity %default-verbosity)
969 (mode (build-mode normal)))
970 "Show what will or would (depending on DRY-RUN?) be built in realizing the
971 derivations listed in DRV using MODE, a 'build-mode' value. The elements of
972 DRV can be either derivations or derivation inputs.
974 Return two values: a Boolean indicating whether there's something to build,
975 and a Boolean indicating whether there's something to download.
977 When USE-SUBSTITUTES?, check and report what is prerequisites are available
978 for download. VERBOSITY is an integer indicating the level of details to be
979 shown: level 2 and higher provide all the details, level 1 shows a high-level
980 summary, and level 0 shows nothing."
983 ((? derivation? drv) (derivation-input drv))
984 ((? derivation-input? input) input))
987 (define substitutable-info
988 ;; Call 'substitution-oracle' upfront so we don't end up launching the
989 ;; substituter many times. This makes a big difference, especially when
990 ;; DRV is a long list as is the case with 'guix environment'.
992 (substitution-oracle store inputs #:mode mode)
995 (define colorized-store-item
996 (if (color-output? (current-error-port))
997 colorize-store-file-name
1000 (let*-values (((build/full download)
1001 (derivation-build-plan store inputs
1003 #:substitutable-info
1004 substitutable-info))
1006 (match (fold (lambda (drv acc)
1007 (let ((file (derivation-file-name drv)))
1009 ((#:graft graft #:hook hook #:build build)
1011 ((graft-derivation? drv)
1012 `(#:graft ,(cons file graft)
1015 ((profile-hook-derivation? drv)
1017 #:hook ,(cons file hook)
1022 #:build ,(cons file build))))))))
1023 '(#:graft () #:hook () #:build ())
1025 ((#:graft graft #:hook hook #:build build)
1026 (values graft hook build)))))
1027 (define installed-size
1028 (reduce + 0 (map substitutable-nar-size download)))
1030 (define download-size
1031 (/ (reduce + 0 (map substitutable-download-size download))
1034 (define display-download-size?
1035 ;; Sometimes narinfos lack information about the download size. Only
1036 ;; display when we have information for all of DOWNLOAD.
1037 (not (any (compose zero? substitutable-download-size) download)))
1039 ;; Combinatorial explosion ahead along two axes: DRY-RUN? and VERBOSITY.
1040 ;; Unfortunately, this is hardly avoidable for proper i18n.
1043 (unless (zero? verbosity)
1044 (format (current-error-port)
1045 (N_ "~:[The following derivation would be built:~%~{ ~a~%~}~;~]"
1046 "~:[The following derivations would be built:~%~{ ~a~%~}~;~]"
1048 (null? build) (map colorized-store-item build)))
1049 (cond ((>= verbosity 2)
1050 (if display-download-size?
1051 (format (current-error-port)
1052 ;; TRANSLATORS: "MB" is for "megabyte"; it should be
1053 ;; translated to the corresponding abbreviation.
1054 (G_ "~:[~,1h MB would be downloaded:~%~{ ~a~%~}~;~]")
1057 (map (compose colorized-store-item substitutable-path)
1059 (format (current-error-port)
1060 (N_ "~:[The following file would be downloaded:~%~{ ~a~%~}~;~]"
1061 "~:[The following files would be downloaded:~%~{ ~a~%~}~;~]"
1064 (map (compose colorized-store-item substitutable-path)
1066 (format (current-error-port)
1067 (N_ "~:[The following graft would be made:~%~{ ~a~%~}~;~]"
1068 "~:[The following grafts would be made:~%~{ ~a~%~}~;~]"
1070 (null? graft) (map colorized-store-item graft))
1071 (format (current-error-port)
1072 (N_ "~:[The following profile hook would be built:~%~{ ~a~%~}~;~]"
1073 "~:[The following profile hooks would be built:~%~{ ~a~%~}~;~]"
1075 (null? hook) (map colorized-store-item hook)))
1077 ;; Display the bare minimum; don't mention grafts and hooks.
1078 (unless (null? build)
1079 (newline (current-error-port)))
1080 (if display-download-size?
1081 (format (current-error-port)
1082 ;; TRANSLATORS: "MB" is for "megabyte"; it should be
1083 ;; translated to the corresponding abbreviation.
1084 (highlight (G_ "~:[~,1h MB would be downloaded~%~;~]"))
1085 (null? download) download-size)
1086 (format (current-error-port)
1088 (N_ "~:[~h item would be downloaded~%~;~]"
1089 "~:[~h items would be downloaded~%~;~]"
1091 (null? download) (length download))))))
1094 (unless (zero? verbosity)
1095 (format (current-error-port)
1096 (N_ "~:[The following derivation will be built:~%~{ ~a~%~}~;~]"
1097 "~:[The following derivations will be built:~%~{ ~a~%~}~;~]"
1099 (null? build) (map colorized-store-item build)))
1100 (cond ((>= verbosity 2)
1101 (if display-download-size?
1102 (format (current-error-port)
1103 ;; TRANSLATORS: "MB" is for "megabyte"; it should be
1104 ;; translated to the corresponding abbreviation.
1105 (G_ "~:[~,1h MB will be downloaded:~%~{ ~a~%~}~;~]")
1108 (map (compose colorized-store-item substitutable-path)
1110 (format (current-error-port)
1111 (N_ "~:[The following file will be downloaded:~%~{ ~a~%~}~;~]"
1112 "~:[The following files will be downloaded:~%~{ ~a~%~}~;~]"
1115 (map (compose colorized-store-item substitutable-path)
1117 (format (current-error-port)
1118 (N_ "~:[The following graft will be made:~%~{ ~a~%~}~;~]"
1119 "~:[The following grafts will be made:~%~{ ~a~%~}~;~]"
1121 (null? graft) (map colorized-store-item graft))
1122 (format (current-error-port)
1123 (N_ "~:[The following profile hook will be built:~%~{ ~a~%~}~;~]"
1124 "~:[The following profile hooks will be built:~%~{ ~a~%~}~;~]"
1126 (null? hook) (map colorized-store-item hook)))
1128 ;; Display the bare minimum; don't mention grafts and hooks.
1129 (unless (null? build)
1130 (newline (current-error-port)))
1131 (if display-download-size?
1132 (format (current-error-port)
1133 ;; TRANSLATORS: "MB" is for "megabyte"; it should be
1134 ;; translated to the corresponding abbreviation.
1135 (highlight (G_ "~:[~,1h MB will be downloaded~%~;~]"))
1136 (null? download) download-size)
1137 (format (current-error-port)
1139 (N_ "~:[~h item will be downloaded~%~;~]"
1140 "~:[~h items will be downloaded~%~;~]"
1142 (null? download) (length download)))))))
1144 (check-available-space installed-size)
1146 (values (pair? build/full) (pair? download))))
1148 (define show-what-to-build*
1149 (store-lift show-what-to-build))
1151 (define* (build-notifier #:key (dry-run? #f) (use-substitutes? #t)
1152 (verbosity %default-verbosity))
1153 "Return a procedure suitable for 'with-build-handler' that, when
1154 'build-things' is called, invokes 'show-what-to-build' to display the build
1155 plan. When DRY-RUN? is true, the 'with-build-handler' form returns without
1156 any build happening."
1158 (char-set-complement (char-set #\,)))
1160 (define (read-derivation-from-file* item)
1161 (catch 'system-error
1163 (read-derivation-from-file item))
1166 (lambda (continue store things mode)
1168 ;; List of derivation inputs to build. Filter out non-existent '.drv'
1169 ;; files because the daemon transparently tries to substitute them.
1170 (filter-map (match-lambda
1171 (((? derivation-path? drv) . output)
1172 (let ((drv (read-derivation-from-file* drv))
1173 (outputs (string-tokenize output not-comma)))
1174 (and drv (derivation-input drv outputs))))
1175 ((? derivation-path? drv)
1176 (and=> (read-derivation-from-file* drv)
1182 (let-values (((build? download?)
1183 (show-what-to-build store inputs
1185 #:use-substitutes? use-substitutes?
1186 #:verbosity verbosity
1189 (unless (and (or build? download?)
1193 (define (right-arrow port)
1194 "Return either a string containing the 'RIGHT ARROW' character, or an ASCII
1195 replacement if PORT is not Unicode-capable."
1196 (let ((encoding (port-encoding port))
1198 (catch 'encoding-error
1200 (call-with-output-string
1202 (set-port-encoding! port encoding)
1203 (set-port-conversion-strategy! port 'error)
1204 (display arrow port))))
1205 (lambda (key . args)
1208 (define* (tabulate rows #:key (initial-indent 0) (max-width 25)
1210 "Return a list of strings where each string is a tabulated representation of
1211 an element of ROWS. All the ROWS must be lists of the same number of cells.
1213 Add INITIAL-INDENT white space at the beginning of each row. Ensure that
1214 columns are at most MAX-WIDTH characters wide. Use INTER-COLUMN as a
1215 separator between subsequent columns."
1216 (define column-widths
1217 ;; List of column widths.
1218 (let loop ((rows rows)
1223 (((column rest ...) ...)
1225 (cons (min (apply max (map string-length column))
1230 (make-string initial-indent #\space))
1232 (define (string-pad-right* str len)
1233 (if (> (string-length str) len)
1235 (string-pad-right str len)))
1239 (string-append indent
1241 (map string-pad-right* row column-widths)
1245 (define* (show-manifest-transaction store manifest transaction
1247 "Display what will/would be installed/removed from MANIFEST by TRANSACTION."
1248 (define* (package-strings names versions outputs #:key old-versions)
1249 (tabulate (stable-sort
1250 (zip (map (lambda (name output)
1251 (if (string=? output "out")
1253 (string-append name ":" output)))
1256 (map (lambda (old new)
1257 (if (string=? old new)
1258 (G_ "(dependencies or package changed)")
1259 (string-append old " " → " " new)))
1260 old-versions versions)
1263 (string<? (first x) (first y))))
1264 #:initial-indent 3))
1266 (define → ;an arrow that can be represented on stderr
1267 (right-arrow (current-error-port)))
1269 (let-values (((remove install upgrade downgrade)
1270 (manifest-transaction-effects manifest transaction)))
1272 ((($ <manifest-entry> name version output item) ..1)
1273 (let ((len (length name))
1274 (remove (package-strings name version output)))
1276 (format (current-error-port)
1277 (N_ "The following package would be removed:~%~{~a~%~}~%"
1278 "The following packages would be removed:~%~{~a~%~}~%"
1281 (format (current-error-port)
1282 (N_ "The following package will be removed:~%~{~a~%~}~%"
1283 "The following packages will be removed:~%~{~a~%~}~%"
1288 (((($ <manifest-entry> name old-version)
1289 . ($ <manifest-entry> _ new-version output item)) ..1)
1290 (let ((len (length name))
1291 (downgrade (package-strings name new-version output
1292 #:old-versions old-version)))
1294 (format (current-error-port)
1295 (N_ "The following package would be downgraded:~%~{~a~%~}~%"
1296 "The following packages would be downgraded:~%~{~a~%~}~%"
1299 (format (current-error-port)
1300 (N_ "The following package will be downgraded:~%~{~a~%~}~%"
1301 "The following packages will be downgraded:~%~{~a~%~}~%"
1306 (((($ <manifest-entry> name old-version)
1307 . ($ <manifest-entry> _ new-version output item)) ..1)
1308 (let ((len (length name))
1309 (upgrade (package-strings name new-version output
1310 #:old-versions old-version)))
1312 (format (current-error-port)
1313 (N_ "The following package would be upgraded:~%~{~a~%~}~%"
1314 "The following packages would be upgraded:~%~{~a~%~}~%"
1317 (format (current-error-port)
1318 (N_ "The following package will be upgraded:~%~{~a~%~}~%"
1319 "The following packages will be upgraded:~%~{~a~%~}~%"
1324 ((($ <manifest-entry> name version output item _) ..1)
1325 (let ((len (length name))
1326 (install (package-strings name version output)))
1328 (format (current-error-port)
1329 (N_ "The following package would be installed:~%~{~a~%~}~%"
1330 "The following packages would be installed:~%~{~a~%~}~%"
1333 (format (current-error-port)
1334 (N_ "The following package will be installed:~%~{~a~%~}~%"
1335 "The following packages will be installed:~%~{~a~%~}~%"
1340 (define-syntax with-error-handling
1342 "Run BODY within a user-friendly error condition handler."
1344 (call-with-error-handling
1348 (define* (indented-string str indent
1349 #:key (initial-indent? #t))
1350 "Return STR with each newline preceded by INDENT spaces. When
1351 INITIAL-INDENT? is true, the first line is also indented."
1352 (define indent-string
1353 (make-list indent #\space))
1356 (string-fold-right (lambda (chr result)
1357 (if (eqv? chr #\newline)
1358 (cons chr (append indent-string result))
1362 (string-append (list->string indent-string) str)
1365 (define* (fill-paragraph str width #:optional (column 0))
1366 "Fill STR such that each line contains at most WIDTH characters, assuming
1367 that the first character is at COLUMN.
1369 When STR contains a single line break surrounded by other characters, it is
1370 converted to a space; sequences of more than one line break are preserved."
1371 (define (maybe-break chr result)
1373 ((column newlines chars)
1376 `(,column ,(+ 1 newlines) ,chars))
1378 (let* ((spaces (if (and (pair? chars) (eqv? (car chars) #\.)) 2 1))
1379 (chars (case newlines
1382 (append (make-list spaces #\space) chars))
1384 (append (make-list newlines #\newline) chars))))
1385 (column (case newlines
1387 ((1) (+ spaces column))
1389 (let ((chars (cons chr chars))
1390 (column (+ 1 column)))
1391 (if (> column width)
1392 (let*-values (((before after)
1393 (break (cut eqv? #\space <>) chars))
1403 (drop-while (cut eqv? #\space <>)
1405 `(,column 0 ,chars))) ; unbreakable
1406 `(,column 0 ,chars)))))))))
1408 (match (string-fold maybe-break
1411 ((column newlines chars)
1412 (list->string (reverse chars)))))
1420 ;; '*line-width*' was introduced in Guile 2.2.7/3.0.1. On older versions of
1421 ;; Guile, monkey-patch 'wrap*' below.
1422 (if (defined? '*line-width*)
1423 (let ((parameter (fluid->parameter *line-width*)))
1424 (parameter (terminal-columns))
1426 (make-parameter (terminal-columns))))
1428 (unless (defined? '*line-width*) ;Guile < 2.2.7
1429 (set! (@@ (texinfo plain-text) wrap*)
1430 ;; XXX: Monkey patch this private procedure to let 'package->recutils'
1431 ;; parameterize the fill of description field correctly.
1433 (let ((indent (fluid-ref (@@ (texinfo plain-text) *indent*))))
1434 (fill-string (string-concatenate strings)
1435 #:line-width (%text-width) #:initial-indent indent
1436 #:subsequent-indent indent)))))
1438 (define (texi->plain-text str)
1439 "Return a plain-text representation of texinfo fragment STR."
1440 ;; 'texi-fragment->stexi' uses a string port so make sure it's a
1441 ;; Unicode-capable one (see <http://bugs.gnu.org/11197>.)
1442 (with-fluids ((%default-port-encoding "UTF-8"))
1443 (stexi->plain-text (texi-fragment->stexi str))))
1445 (define (package-field-string package field-accessor)
1446 "Return a plain-text representation of PACKAGE field."
1447 (and=> (field-accessor package)
1448 (compose texi->plain-text P_)))
1450 (define (package-description-string package)
1451 "Return a plain-text representation of PACKAGE description field."
1452 (package-field-string package package-description))
1454 (define (package-synopsis-string package)
1455 "Return a plain-text representation of PACKAGE synopsis field."
1456 (package-field-string package package-synopsis))
1458 (define (string->recutils str)
1459 "Return a version of STR where newlines have been replaced by newlines
1460 followed by \"+ \", which makes for a valid multi-line field value in the
1463 (string-fold-right (lambda (chr result)
1464 (if (eqv? chr #\newline)
1465 (cons* chr #\+ #\space result)
1470 (define (hyperlink uri text)
1471 "Return a string that denotes a hyperlink using an OSC escape sequence as
1473 <https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda>."
1474 (string-append "\x1b]8;;" uri "\x1b\\"
1475 text "\x1b]8;;\x1b\\"))
1477 (define* (supports-hyperlinks? #:optional (port (current-output-port)))
1478 "Return true if PORT is a terminal that supports hyperlink escapes."
1479 ;; Note that terminals are supposed to ignore OSC escapes they don't
1480 ;; understand (this is the case of xterm as of version 349, for instance.)
1481 ;; However, Emacs comint as of 26.3 does not ignore it and instead lets it
1482 ;; through, hence the 'INSIDE_EMACS' special case below.
1483 (and (isatty?* port)
1484 (not (getenv "INSIDE_EMACS"))))
1486 (define* (file-hyperlink file #:optional (text file))
1487 "Return TEXT with escapes for a hyperlink to FILE."
1488 (hyperlink (string-append "file://" (gethostname)
1489 (encode-and-join-uri-path
1490 (string-split file #\/)))
1493 (define (location->hyperlink location)
1494 "Return a string corresponding to LOCATION, with escapes for a hyperlink."
1495 (let ((str (location->string location))
1496 (file (if (string-prefix? "/" (location-file location))
1497 (location-file location)
1498 (search-path %load-path (location-file location)))))
1500 (file-hyperlink file str)
1503 (define* (package->recutils p port #:optional (width (%text-width))
1505 (hyperlinks? (supports-hyperlinks? port))
1507 "Write to PORT a `recutils' record of package P, arranging to fit within
1508 WIDTH columns. EXTRA-FIELDS is a list of symbol/value pairs to emit. When
1509 HYPERLINKS? is true, emit hyperlink escape sequences when appropriate."
1511 ;; The available number of columns once we've taken into account space for
1512 ;; the initial "+ " prefix.
1513 (if (> width 2) (- width 2) width))
1515 (define (dependencies->recutils packages)
1516 (let ((list (string-join (delete-duplicates
1517 (map package-full-name
1518 (sort packages package<?))) " ")))
1520 (fill-paragraph list width*
1521 (string-length "dependencies: ")))))
1523 (define (package<? p1 p2)
1524 (string<? (package-full-name p1) (package-full-name p2)))
1526 ;; Note: Don't i18n field names so that people can post-process it.
1527 (format port "name: ~a~%" (package-name p))
1528 (format port "version: ~a~%" (package-version p))
1529 (format port "outputs: ~a~%" (string-join (package-outputs p)))
1530 (format port "systems: ~a~%"
1531 (string-join (package-transitive-supported-systems p)))
1532 (format port "dependencies: ~a~%"
1533 (match (package-direct-inputs p)
1534 (((labels inputs . _) ...)
1535 (dependencies->recutils (filter package? inputs)))))
1536 (format port "location: ~a~%"
1537 (or (and=> (package-location p)
1538 (if hyperlinks? location->hyperlink location->string))
1541 ;; Note: Starting from version 1.6 or recutils, hyphens are not allowed in
1542 ;; field identifiers.
1543 (format port "homepage: ~a~%" (package-home-page p))
1545 (format port "license: ~a~%"
1546 (match (package-license p)
1547 (((? license? licenses) ...)
1548 (string-join (map license-name licenses)
1550 ((? license? license)
1551 (let ((text (license-name license))
1552 (uri (license-uri license)))
1553 (if (and hyperlinks? uri (string-prefix? "http" uri))
1554 (hyperlink uri text)
1558 (format port "synopsis: ~a~%"
1559 (string-map (match-lambda
1562 (or (package-synopsis-string p) "")))
1566 (parameterize ((%text-width width*))
1567 ;; Call 'texi->plain-text' on the concatenated string to account
1568 ;; for the width of "description:" in paragraph filling.
1570 (string-append "description: "
1571 (or (and=> (package-description p) P_)
1574 (for-each (match-lambda
1576 (let ((field (symbol->string field)))
1577 (format port "~a: ~a~%"
1579 (fill-paragraph (object->string value) width*
1580 (string-length field))))))
1589 (define (relevance obj regexps metrics)
1590 "Compute a \"relevance score\" for OBJ as a function of its number of
1591 matches of REGEXPS and accordingly to METRICS. METRICS is list of
1592 field/weight pairs, where FIELD is a procedure that returns a string or list
1593 of strings describing OBJ, and WEIGHT is a positive integer denoting the
1594 weight of this field in the final score.
1596 A score of zero means that OBJ does not match any of REGEXPS. The higher the
1597 score, the more relevant OBJ is to REGEXPS."
1598 (define (score regexp str)
1599 (fold-matches regexp str 0
1602 (if (string=? (match:substring m) str)
1606 (define (regexp->score regexp)
1607 (let ((score-regexp (lambda (str) (score regexp str))))
1608 (fold (lambda (metric relevance)
1614 (+ relevance (* (score-regexp str) weight)))
1616 (+ relevance (* weight (apply + (map score-regexp lst)))))))))
1619 (let loop ((regexps regexps)
1623 (let ((score (regexp->score head)))
1624 ;; Return zero if one of PATTERNS doesn't match.
1627 (loop tail (+ total-score score)))))
1630 (define %package-metrics
1631 ;; Metrics used to compute the "relevance score" of a package against a set
1633 `((,package-name . 4)
1635 ;; Match against uncommon outputs.
1637 (filter (lambda (output)
1639 ;; Some common outputs shared by many packages.
1640 '("out" "doc" "debug" "lib" "include" "bin"))))
1641 (package-outputs package)))
1644 ;; Match regexps on the raw Texinfo since formatting it is quite expensive
1645 ;; and doesn't have much of an effect on search results.
1647 (and=> (package-synopsis package) P_)) . 3)
1649 (and=> (package-description package) P_)) . 2)
1652 (match (and=> (package-location type) location-file)
1653 ((? string? file) (basename file ".scm"))
1657 (define (package-relevance package regexps)
1658 "Return a score denoting the relevance of PACKAGE for REGEXPS. A score of
1659 zero means that PACKAGE does not match any of REGEXPS."
1660 (relevance package regexps %package-metrics))
1662 (define* (call-with-paginated-output-port proc
1663 #:key (less-options "FrX"))
1664 (if (isatty?* (current-output-port))
1665 ;; Set 'LESS' so that 'less' exits if everything fits on the screen (F),
1666 ;; lets ANSI escapes through (r), does not send the termcap
1667 ;; initialization string (X). Set it unconditionally because some
1668 ;; distros set it to something that doesn't work here.
1670 ;; For things that produce long lines, such as 'guix processes', use 'R'
1671 ;; instead of 'r': this strips hyperlinks but allows 'less' to make a
1672 ;; good estimate of the line length.
1673 (let ((pager (with-environment-variables `(("LESS" ,less-options))
1674 (open-pipe* OPEN_WRITE
1675 (or (getenv "GUIX_PAGER") (getenv "PAGER")
1679 (lambda () (proc pager))
1680 (lambda () (close-pipe pager))))
1681 (proc (current-output-port))))
1683 (define-syntax with-paginated-output-port
1685 "Evaluate EXP... with PORT bound to a port that talks to the pager if
1686 standard output is a tty, or with PORT set to the current output port."
1687 ((_ port exp ... #:less-options opts)
1688 (call-with-paginated-output-port (lambda (port) exp ...)
1689 #:less-options opts))
1691 (call-with-paginated-output-port (lambda (port) exp ...)))))
1693 (define* (display-search-results matches port
1695 (command "guix search")
1696 (print package->recutils))
1697 "Display MATCHES, a list of object/score pairs, by calling PRINT on each of
1698 them. If PORT is a terminal, print at most a full screen of results."
1703 (and first-line (isatty? port)
1704 (terminal-rows port)))
1706 (define (line-count str)
1707 (string-count str #\newline))
1709 (with-paginated-output-port paginated
1710 (let loop ((matches matches))
1712 (((package . score) rest ...)
1713 (let* ((links? (supports-hyperlinks? port)))
1714 (print package paginated
1715 #:hyperlinks? links?
1716 #:extra-fields `((relevance . ,score)))
1722 (define (string->generations str)
1723 "Return the list of generations matching a pattern in STR. This function
1724 accepts the following patterns: \"1\", \"1,2,3\", \"1..9\", \"1..\", \"..9\"."
1725 (define (maybe-integer)
1726 (let ((x (string->number str)))
1730 (define (maybe-comma-separated-integers)
1731 (let ((lst (delete-duplicates
1733 (string-split str #\,)))))
1734 (and (every integer? lst)
1737 (cond ((maybe-integer)
1740 ((maybe-comma-separated-integers)
1743 ((string-match "^([0-9]+)\\.\\.([0-9]+)$" str)
1746 (let ((s (string->number (match:substring match 1)))
1747 (e (string->number (match:substring match 2))))
1748 (and (every integer? (list s e))
1750 (iota (1+ (- e s)) s)))))
1751 ((string-match "^([0-9]+)\\.\\.$" str)
1754 (let ((s (string->number (match:substring match 1))))
1757 ((string-match "^\\.\\.([0-9]+)$" str)
1760 (let ((e (string->number (match:substring match 1))))
1765 (define (string->duration str)
1766 "Return the duration matching a pattern in STR. This function accepts the
1767 following patterns: \"1d\", \"1w\", \"1m\"."
1768 (define (hours->duration hours match)
1769 (make-time time-duration 0
1770 (* 3600 hours (string->number (match:substring match 1)))))
1772 (cond ((string-match "^([0-9]+)s$" str)
1775 (make-time time-duration 0
1776 (string->number (match:substring match 1)))))
1777 ((string-match "^([0-9]+)h$" str)
1780 (hours->duration 1 match)))
1781 ((string-match "^([0-9]+)d$" str)
1784 (hours->duration 24 match)))
1785 ((string-match "^([0-9]+)w$" str)
1788 (hours->duration (* 24 7) match)))
1789 ((string-match "^([0-9]+)m$" str)
1792 (hours->duration (* 24 30) match)))
1795 (define* (matching-generations str profile
1796 #:key (duration-relation <=))
1797 "Return the list of available generations matching a pattern in STR. See
1798 'string->generations' and 'string->duration' for the list of valid patterns.
1799 When STR is a duration pattern, return all the generations whose ctime has
1800 DURATION-RELATION with the current time."
1801 (define (valid-generations lst)
1802 (define (valid-generation? n)
1803 (any (cut = n <>) (generation-numbers profile)))
1805 (fold-right (lambda (x acc)
1806 (if (valid-generation? x)
1812 (define (filter-generations generations)
1816 (drop-while (cut > n <>)
1817 (generation-numbers profile)))
1819 (valid-generations (iota n 1)))
1821 (valid-generations lst))
1824 (define (filter-by-duration duration)
1825 (define (time-at-midnight time)
1826 ;; Return TIME at midnight by setting nanoseconds, seconds, minutes, and
1828 (let ((d (time-utc->date time)))
1831 (date-day d) (date-month d)
1832 (date-year d) (date-zone-offset d)))))
1834 (define generation-ctime-alist
1835 (map (lambda (number)
1839 (generation-time profile number)))))
1840 (generation-numbers profile)))
1845 (let ((s (time-second
1846 (subtract-duration (time-at-midnight (current-time))
1848 (delete #f (map (lambda (x)
1849 (and (duration-relation s (cdr x))
1851 generation-ctime-alist))))))
1853 (cond ((string->generations str)
1856 ((string->duration str)
1861 (formatted-message (G_ "invalid syntax: ~a~%") str)))))
1863 (define (display-generation profile number)
1864 "Display a one-line summary of generation NUMBER of PROFILE."
1865 (unless (zero? number)
1866 (let* ((file (generation-file-name profile number))
1867 (link (if (supports-hyperlinks?)
1868 (cut file-hyperlink file <>)
1870 (header (format #f (link (highlight (G_ "Generation ~a\t~a")))
1874 (generation-time profile number))
1875 ;; TRANSLATORS: This is a format-string for date->string.
1876 ;; Please choose a format that corresponds to the
1877 ;; usual way of presenting dates in your locale.
1878 ;; See https://www.gnu.org/software/guile/manual/html_node/SRFI_002d19-Date-to-string.html
1880 (G_ "~b ~d ~Y ~T"))))
1881 (current (generation-number profile)))
1882 (if (= number current)
1883 ;; TRANSLATORS: The word "current" here is an adjective for
1884 ;; "Generation", as in "current generation". Use the appropriate
1885 ;; gender where applicable.
1886 (format #t (G_ "~a\t(current)~%") header)
1887 (format #t "~a~%" header)))))
1889 (define (display-profile-content-diff profile gen1 gen2)
1890 "Display the changed packages in PROFILE GEN2 compared to generation GEN1."
1892 (define (equal-entry? first second)
1893 (string= (manifest-entry-item first) (manifest-entry-item second)))
1895 (define (display-entry entry prefix)
1897 (($ <manifest-entry> name version output location _)
1898 (format #t " ~a ~a\t~a\t~a\t~a~%" prefix name version output location))))
1900 (define (list-entries number)
1901 (manifest-entries (profile-manifest (generation-file-name profile number))))
1903 (define (display-diff profile old new)
1904 (display-generation profile new)
1905 (let ((added (lset-difference
1906 equal-entry? (list-entries new) (list-entries old)))
1907 (removed (lset-difference
1908 equal-entry? (list-entries old) (list-entries new))))
1909 (for-each (cut display-entry <> "+") added)
1910 (for-each (cut display-entry <> "-") removed)
1913 (display-diff profile gen1 gen2))
1915 (define (profile-lock-handler profile errno . _)
1916 "Handle failure to acquire PROFILE's lock."
1917 ;; NFS mounts can return ENOLCK. When that happens, there's not much that
1918 ;; can be done, so warn the user and keep going.
1919 (if (= errno ENOLCK)
1920 (warning (G_ "cannot lock profile ~a: ~a~%")
1921 profile (strerror errno))
1922 (leave (G_ "profile ~a is locked by another process~%")
1925 (define profile-lock-file
1926 (cut string-append <> ".lock"))
1928 (define-syntax-rule (with-profile-lock profile exp ...)
1929 "Grab PROFILE's lock and evaluate EXP... Call 'leave' if the lock is
1931 (with-file-lock/no-wait (profile-lock-file profile)
1932 (cut profile-lock-handler profile <...>)
1935 (define (display-profile-content profile number)
1936 "Display the packages in PROFILE, generation NUMBER, in a human-readable
1938 (for-each (match-lambda
1939 (($ <manifest-entry> name version output location _)
1940 (format #t " ~a\t~a\t~a\t~a~%"
1941 name version output location)))
1943 ;; Show most recently installed packages last.
1946 (profile-manifest (generation-file-name profile number))))))
1948 (define (display-generation-change previous current)
1949 (format #t (G_ "switched from generation ~a to ~a~%") previous current))
1951 (define (roll-back* store profile)
1952 "Like 'roll-back', but display what is happening."
1955 (roll-back store profile))
1956 display-generation-change))
1958 (define (switch-to-generation* profile number)
1959 "Like 'switch-generation', but display what is happening."
1960 (let ((previous (switch-to-generation profile number)))
1961 (display-generation-change previous number)))
1963 (define (delete-generation* store profile generation)
1964 "Like 'delete-generation', but display what is going on."
1965 (format #t (G_ "deleting ~a~%")
1966 (generation-file-name profile generation))
1967 (delete-generation store profile generation))
1969 (define* (package-specification->name+version+output spec
1970 #:optional (output "out"))
1971 "Parse package specification SPEC and return three value: the specified
1972 package name, version number (or #f), and output name (or OUTPUT). SPEC may
1973 optionally contain a version number and an output name, as in these examples:
1980 (let*-values (((name sub-drv)
1981 (match (string-rindex spec #\:)
1982 (#f (values spec output))
1983 (colon (values (substring spec 0 colon)
1984 (substring spec (+ 1 colon))))))
1986 (package-name->name+version name)))
1987 (values name version sub-drv)))
1991 ;;; Command-line option processing.
1994 (define (show-guix-usage)
1995 (format (current-error-port)
1996 (G_ "Try `guix --help' for more information.~%"))
1999 ;; Representation of a 'guix' command.
2000 (define-immutable-record-type <command>
2001 (command name synopsis category)
2004 (synopsis command-synopsis)
2005 (category command-category))
2007 (define (source-file-command file)
2008 "Read FILE, a Scheme source file, and return either a <command> object based
2009 on the 'define-command' top-level form found therein, or #f if FILE does not
2010 contain a 'define-command' form."
2011 (define command-name
2012 (match (string-split file #\/)
2013 ((_ ... "guix" "scripts" name)
2014 (list (file-sans-extension name)))
2015 ((_ ... "guix" "scripts" first second)
2016 (list first (file-sans-extension second)))))
2018 ;; The strategy here is to parse FILE. This is much cheaper than a
2019 ;; technique based on run-time introspection where we'd load FILE and all
2020 ;; the modules it depends on.
2021 (call-with-input-file file
2025 (('define-command _ ('synopsis synopsis)
2027 (command command-name synopsis 'main))
2029 ('category category) ('synopsis synopsis)
2031 (command command-name synopsis category))
2037 (define (command-files)
2038 "Return the list of source files that define Guix sub-commands."
2040 (and=> (search-path %load-path "guix.scm")
2041 (compose (cut string-append <> "/guix/scripts")
2045 (cut string-suffix? ".scm" <>))
2048 (map (cut string-append directory "/" <>)
2049 (scandir directory dot-scm?))
2053 "Return the list of commands, alphabetically sorted."
2054 (filter-map source-file-command (command-files)))
2056 (define (show-guix-help)
2057 (define (internal? command)
2058 (member command '("substitute" "authenticate" "offload"
2059 "perform-download")))
2061 (define (display-commands commands)
2062 (let* ((names (map (lambda (command)
2063 (string-join (command-name command)))
2065 (max-width (reduce max 0 (map string-length names))))
2066 (for-each (lambda (name command)
2067 (format #t " ~a ~a~%"
2068 (string-pad-right name max-width)
2069 (G_ (command-synopsis command))))
2073 (define (category-predicate category)
2075 (eq? category (command-category command))))
2077 (format #t (G_ "Usage: guix COMMAND ARGS...
2078 Run COMMAND with ARGS.\n"))
2080 (format #t (G_ "COMMAND must be one of the sub-commands listed below:\n"))
2082 (let ((commands (commands))
2083 (categories (module-ref (resolve-interface '(guix scripts))
2084 '%command-categories)))
2085 (for-each (match-lambda
2087 #t) ;hide internal commands
2088 ((category . synopsis)
2089 (format #t "~% ~a~%" (G_ synopsis))
2090 (display-commands (filter (category-predicate category)
2093 (show-bug-report-information))
2095 (define (run-guix-command command . args)
2096 "Run COMMAND with the given ARGS. Report an error when COMMAND is not
2101 (resolve-interface `(guix scripts ,command)))
2103 (format (current-error-port)
2104 (G_ "guix: ~a: command not found~%") command)
2105 (show-guix-usage))))
2107 (let ((command-main (module-ref module
2108 (symbol-append 'guix- command))))
2109 (parameterize ((program-name command))
2110 ;; Disable canonicalization so we don't don't stat unreasonably.
2111 (with-fluids ((%file-port-name-canonicalization #f))
2115 (apply command-main args))
2117 ;; Abuse 'exit-hook' (which is normally meant to be used by the
2118 ;; REPL) to run things like profiling hooks upon completion.
2119 (run-hook exit-hook)))))))
2121 (define (run-guix . args)
2122 "Run the 'guix' command defined by command line ARGS.
2123 Unlike 'guix-main', this procedure assumes that locale, i18n support,
2124 and signal handling have already been set up."
2125 (define option? (cut string-prefix? "-" <>))
2127 ;; The default %LOAD-EXTENSIONS includes the empty string, which doubles the
2128 ;; number of 'stat' calls per entry in %LOAD-PATH. Shamelessly remove it.
2129 (set! %load-extensions '(".scm"))
2133 (format (current-error-port)
2134 (G_ "guix: missing command name~%"))
2136 ((or ("-h") ("--help"))
2138 ((or ("-V") ("--version"))
2139 (show-version-and-exit "guix"))
2140 (((? option? o) args ...)
2141 (format (current-error-port)
2142 (G_ "guix: unrecognized option '~a'~%") o)
2145 (apply run-guix-command (string->symbol command)
2150 (apply run-guix-command
2151 (string->symbol command)
2154 (define (guix-main arg0 . args)
2156 (apply run-guix args))
2158 ;;; Local Variables:
2159 ;;; eval: (put 'guard* 'scheme-indent-function 2)
2162 ;;; ui.scm ends here