1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019 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>
18 ;;; This file is part of GNU Guix.
20 ;;; GNU Guix is free software; you can redistribute it and/or modify it
21 ;;; under the terms of the GNU General Public License as published by
22 ;;; the Free Software Foundation; either version 3 of the License, or (at
23 ;;; your option) any later version.
25 ;;; GNU Guix is distributed in the hope that it will be useful, but
26 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
27 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 ;;; GNU General Public License for more details.
30 ;;; You should have received a copy of the GNU General Public License
31 ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
33 (define-module (guix ui)
34 #:use-module (guix i18n)
35 #:use-module (guix colors)
36 #:use-module (guix diagnostics)
37 #:use-module (guix gexp)
38 #:use-module (guix sets)
39 #:use-module (guix utils)
40 #:use-module (guix store)
41 #:use-module (guix config)
42 #:use-module (guix packages)
43 #:use-module (guix profiles)
44 #:use-module (guix derivations)
45 #:use-module (guix build-system)
46 #:use-module (guix serialization)
47 #:use-module ((guix licenses)
48 #:select (license? license-name license-uri))
49 #:use-module ((guix build syscalls)
50 #:select (free-disk-space terminal-columns terminal-rows
51 with-file-lock/no-wait))
52 #:use-module ((guix build utils)
53 ;; XXX: All we need are the bindings related to
54 ;; '&invoke-error'. However, to work around the bug described
55 ;; in 5d669883ecc104403c5d3ba7d172e9c02234577c, #:hide
56 ;; unwanted bindings instead of #:select'ing the needed
58 #:hide (package-name->name+version))
59 #:use-module (srfi srfi-1)
60 #:use-module (srfi srfi-11)
61 #:use-module (srfi srfi-19)
62 #:use-module (srfi srfi-26)
63 #:use-module (srfi srfi-31)
64 #:use-module (srfi srfi-34)
65 #:use-module (srfi srfi-35)
66 #:autoload (ice-9 ftw) (scandir)
67 #:use-module (ice-9 match)
68 #:use-module (ice-9 format)
69 #:use-module (ice-9 regex)
70 #:autoload (system base compile) (compile-file)
71 #:autoload (system repl repl) (start-repl)
72 #:autoload (system repl debug) (make-debug stack->vector)
73 #:autoload (web uri) (encode-and-join-uri-path)
74 #:use-module (texinfo)
75 #:use-module (texinfo plain-text)
76 #:use-module (texinfo string-utils)
78 ;; Re-exports for backward compatibility.
79 #:re-export (G_ N_ P_ ;now in (guix i18n)
81 warning info report-error leave ;now in (guix diagnostics)
83 guix-warning-port program-name)
84 #:export (display-hint
89 show-bug-report-information
93 show-derivation-outputs
96 show-manifest-transaction
97 call-with-error-handling
99 with-unbound-variable-handling
102 read/eval-package-expression
103 check-available-space
107 package-description-string
108 package-synopsis-string
111 package-specification->name+version+output
120 display-search-results
127 display-profile-content
128 display-profile-content-diff
130 switch-to-generation*
133 %default-message-language
134 current-message-language
142 ;;; User interface facilities for command-line tools.
146 (define (print-unbound-variable-error port key args default-printer)
147 ;; Print unbound variable errors more nicely, and in the right language.
149 ((proc message (variable) _ ...)
150 ;; We can always omit PROC because when it's useful (i.e., different from
151 ;; "module-lookup"), it gets displayed before.
152 (format port (G_ "error: ~a: unbound variable") variable))
156 (set-exception-printer! 'unbound-variable print-unbound-variable-error)
158 (define (make-user-module modules)
159 "Return a new user module with the additional MODULES loaded."
160 ;; Module in which the machine description file is loaded.
161 (let ((module (make-fresh-user-module)))
162 (for-each (lambda (iface)
163 (module-use! module (resolve-interface iface)))
167 (define (last-frame-with-source stack)
168 "Walk stack upwards and return the last frame that has source location
169 information, or #f if it could not be found."
170 (define (frame-with-source frame)
171 ;; Walk from FRAME upwards until source location information is found.
172 (let loop ((frame frame)
176 (if (frame-source frame)
178 (loop (frame-previous frame) frame)))))
180 (let* ((depth (stack-length stack))
181 (last (and (> depth 0) (stack-ref stack 0))))
182 (frame-with-source (if (> depth 1)
183 (stack-ref stack 1) ;skip the 'throw' frame
186 (define* (load* file user-module
187 #:key (on-error 'nothing-special))
188 "Load the user provided Scheme source code FILE."
189 (define (error-string frame args)
190 (call-with-output-string
192 (apply display-error frame port (cdr args)))))
195 (make-prompt-tag "user-code"))
199 ;; XXX: Force a recompilation to avoid ABI issues.
201 ;; In 2.2.3, the bogus answer to <https://bugs.gnu.org/29226> was to
202 ;; ignore all available .go, not just those from ~/.cache, which in turn
203 ;; meant that we had to rebuild *everything*. Since this is too costly,
204 ;; we have to turn off '%fresh-auto-compile' with that version, so to
205 ;; avoid ABI breakage in the user's config file, we explicitly compile
206 ;; it (the problem remains if the user's config is spread on several
207 ;; modules.) See <https://bugs.gnu.org/29881>.
208 (unless (string=? (version) "2.2.3")
209 (set! %fresh-auto-compile #t))
211 (set! %load-should-auto-compile #t)
213 (save-module-excursion
215 (set-current-module user-module)
217 ;; Hide the "auto-compiling" messages.
218 (parameterize ((current-warning-port (%make-void-port "w")))
219 (call-with-prompt tag
221 (when (string=? (version) "2.2.3")
224 (compile-file file #:env user-module))
225 (const #f))) ;EACCES maybe, let's interpret it
227 ;; Give 'load' an absolute file name so that it doesn't try to
228 ;; search for FILE in %LOAD-PATH. Note: use 'load', not
229 ;; 'primitive-load', so that FILE is compiled, which then allows us
230 ;; to provide better error reporting with source line numbers.
231 (load (canonicalize-path file)))
234 ;; XXX: Errors are reported from the pre-unwind handler below, but
235 ;; calling 'exit' from there has no effect, so we call it here.
237 (rec (handle-error . args)
238 ;; Capture the stack up to this procedure call, excluded, and pass
239 ;; the faulty stack frame to 'report-load-error'.
240 (let* ((stack (make-stack #t handle-error tag))
241 (frame (last-frame-with-source stack)))
243 (report-load-error file args frame)
248 (display (G_ "entering debugger; type ',bt' for a backtrace\n"))
249 (start-repl #:debug (make-debug (stack->vector stack) 0
250 (error-string frame args)
253 (newline (current-error-port))
254 (display-backtrace stack (current-error-port)))
258 (define (known-variable-definition variable)
259 "Search among the currently loaded modules one that defines a variable named
260 VARIABLE and return it, or #f if none was found."
261 (define (module<? m1 m2)
262 (match (module-name m2)
265 (match (module-name m1)
270 (let loop ((modules (list (resolve-module '() #f #f #:ensure #f)))
275 ;; Pick the "best" suggestion.
276 (match (sort suggestions module<?)
278 ((first _ ...) first)))
280 (if (set-contains? visited head)
281 (loop tail suggestions visited)
282 (let ((visited (set-insert head visited))
284 (hash-map->list (lambda (name module)
286 (module-submodules head)))))
287 (match (module-local-variable head variable)
288 (#f (loop next suggestions visited))
290 (match (module-name head)
291 (('gnu _ ...) head) ;must be that one
292 (_ (loop next (cons head suggestions) visited)))))))))))
294 (define %hint-color (color BOLD CYAN))
296 (define* (display-hint message #:optional (port (current-error-port)))
297 "Display MESSAGE, a l10n message possibly containing Texinfo markup, to
300 (if (color-output? port)
302 (colorize-string str %hint-color))
305 (display (colorize (G_ "hint: ")) port)
307 ;; XXX: We should arrange so that the initial indent is wider.
308 (parameterize ((%text-width (max 15 (- (terminal-columns) 5))))
309 (texi->plain-text message))
312 (define* (report-unbound-variable-error args #:key frame)
313 "Return the given unbound-variable error, where ARGS is the list of 'throw'
317 (print-exception (current-error-port) frame key args)))
319 (('unbound-variable proc message (variable) _ ...)
320 (match (known-variable-definition variable)
322 (display-hint (G_ "Did you forget a @code{use-modules} form?")))
324 (display-hint (format #f (G_ "Did you forget @code{(use-modules ~a)}?")
325 (module-name module))))))))
327 (define (check-module-matches-file module file)
328 "Check whether FILE starts with 'define-module MODULE' and print a hint if
330 ;; This is a common mistake when people start writing their own package
331 ;; definitions and try loading them with 'guix build -L …', so help them
332 ;; diagnose the problem.
334 (display-hint (format #f (G_ "File @file{~a} should probably start with:
336 @example\n(define-module ~a)\n@end example")
341 (let* ((sexp (call-with-input-file file read))
342 (loc (and (pair? sexp)
343 (source-properties->location (source-properties sexp)))))
345 (('define-module (names ...) _ ...)
346 (unless (equal? module names)
348 (G_ "module name ~a does not match file name '~a'~%")
349 names (module->source-file-name module))
352 (warning (G_ "~a: file is empty~%") file))
357 (define* (report-load-error file args #:optional frame)
358 "Report the failure to load FILE, a user-provided Scheme file.
359 ARGS is the list of arguments received by the 'throw' handler."
361 (('system-error . rest)
362 (let ((err (system-error-errno args)))
363 (report-error (G_ "failed to load '~a': ~a~%") file (strerror err))))
364 (('read-error "scm_i_lreadparen" message _ ...)
365 ;; Guile's missing-paren messages are obscure so we make them more
366 ;; intelligible here.
367 (if (string-suffix? "end of file" message)
368 (let ((location (string-drop-right message
369 (string-length "end of file"))))
370 (format (current-error-port) (G_ "~amissing closing parenthesis~%")
373 (('syntax-error proc message properties form . rest)
374 (let ((loc (source-properties->location properties)))
375 (report-error loc (G_ "~a~%") message)))
376 (('unbound-variable _ ...)
377 (report-unbound-variable-error args #:frame frame))
378 (((or 'srfi-34 '%exception) obj)
379 (if (message-condition? obj)
380 (report-error (and (error-location? obj)
381 (error-location obj))
383 (gettext (condition-message obj) %gettext-domain))
384 (report-error (G_ "exception thrown: ~s~%") obj))
385 (when (fix-hint? obj)
386 (display-hint (condition-fix-hint obj))))
388 (report-error (G_ "failed to load '~a':~%") file)
390 (((? symbol? proc) (? string? message) (args ...) . rest)
391 (display-error frame (current-error-port) proc message
394 ;; Some exceptions like 'git-error' do not follow Guile's convention
395 ;; above and need to be printed with 'print-exception'.
396 (print-exception (current-error-port) frame key args))))))
398 (define (warn-about-load-error file module args) ;FIXME: factorize with ↑
399 "Report the failure to load FILE, a user-provided Scheme file, without
400 exiting. ARGS is the list of arguments received by the 'throw' handler."
402 (('system-error . rest)
403 (let ((err (system-error-errno args)))
404 (warning (G_ "failed to load '~a': ~a~%") module (strerror err))))
405 (('syntax-error proc message properties form . rest)
406 (let ((loc (source-properties->location properties)))
407 (warning loc (G_ "~a~%") message)))
408 (('unbound-variable _ ...)
409 (report-unbound-variable-error args))
410 (((or 'srfi-34 '%exception) obj)
411 (if (message-condition? obj)
412 (warning (G_ "failed to load '~a': ~a~%")
414 (gettext (condition-message obj) %gettext-domain))
415 (warning (G_ "failed to load '~a': exception thrown: ~s~%")
418 (warning (G_ "failed to load '~a':~%") module)
419 (apply display-error #f (current-error-port) args)
420 (check-module-matches-file module file))))
422 (define (call-with-unbound-variable-handling thunk)
424 (make-prompt-tag "user-code"))
426 (catch 'unbound-variable
428 (call-with-prompt tag
432 (rec (handle-error . args)
433 (let* ((stack (make-stack #t handle-error tag))
434 (frame (and stack (last-frame-with-source stack))))
435 (report-unbound-variable-error args #:frame frame)
438 (define-syntax-rule (with-unbound-variable-handling exp ...)
439 "Capture 'unbound-variable' exceptions in the dynamic extent of EXP... and
440 report them in a user-friendly way."
441 (call-with-unbound-variable-handling (lambda () exp ...)))
443 (define %default-message-language
444 ;; Default language to use for messages.
445 (make-parameter "en"))
447 (define (current-message-language)
448 "Return the language used for messages according to the current locale.
449 Return %DEFAULT-MESSAGE-LANGUAGE if that information could not be obtained. The
450 result is an ISO-639-2 language code such as \"ar\", without the territory
452 (let ((locale (setlocale LC_MESSAGES)))
453 (match (string-index locale #\_)
455 (index (string-take locale index)))))
457 (define (install-locale)
458 "Install the current locale settings."
461 (setlocale LC_ALL ""))
463 (display-hint (G_ "Consider installing the @code{glibc-utf8-locales} or
464 @code{glibc-locales} package and defining @code{GUIX_LOCPATH}, along these
468 guix package -i glibc-utf8-locales
469 export GUIX_LOCPATH=\"$HOME/.guix-profile/lib/locale\"
472 See the \"Application Setup\" section in the manual, for more info.\n")))))
474 (define (initialize-guix)
475 "Perform the usual initialization for stand-alone Guix commands."
476 ;; By default don't annoy users with deprecation warnings. In practice,
477 ;; 'define-deprecated' in (ice-9 deprecated) arranges so that those warnings
478 ;; are emitted at expansion-time only, but there are cases where they could
479 ;; slip through, for instance when interpreting code.
480 (unless (getenv "GUILE_WARN_DEPRECATED")
481 (debug-disable 'warn-deprecated))
484 (textdomain %gettext-domain)
486 ;; Ignore SIGPIPE. If the daemon closes the connection, we prefer to be
487 ;; notified via an EPIPE later.
488 (sigaction SIGPIPE SIG_IGN)
490 (setvbuf (current-output-port) 'line)
491 (setvbuf (current-error-port) 'line))
493 (define* (show-version-and-exit #:optional (command (car (command-line))))
494 "Display version information for COMMAND and `(exit 0)'."
495 (simple-format #t "~a (~a) ~a~%"
496 command %guix-package-name %guix-version)
497 (format #t "Copyright ~a 2019 ~a"
498 ;; TRANSLATORS: Translate "(C)" to the copyright symbol
499 ;; (C-in-a-circle), if this symbol is available in the user's
500 ;; locale. Otherwise, do not translate "(C)"; leave it as-is. */
502 (G_ "the Guix authors\n"))
504 License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
505 This is free software: you are free to change and redistribute it.
506 There is NO WARRANTY, to the extent permitted by law.
510 (define (show-bug-report-information)
511 ;; TRANSLATORS: The placeholder indicates the bug-reporting address for this
512 ;; package. Please add another line saying "Report translation bugs to
513 ;; ...\n" with the address for translation bugs (typically your translation
514 ;; team's web or email address).
516 Report bugs to: ~a.") %guix-bug-report-address)
518 ~a home page: <~a>") %guix-package-name %guix-home-page-url)
520 General help using GNU software: <http://www.gnu.org/gethelp/>"))
523 (define (augmented-system-error-handler file)
524 "Return a 'system-error' handler that mentions FILE in its message."
525 (lambda (key proc fmt args errno)
526 ;; Augment the FMT and ARGS with information about TARGET (this
527 ;; information is missing as of Guile 2.0.11, making the exception
529 (apply throw key proc "~A: ~S"
530 (list (strerror (car errno)) file)
533 (define-syntax apply-formals
535 ((_ proc (args ...)) (proc args ...))
536 ((_ proc (arg1 args ... . rest)) (apply proc arg1 args ... rest))))
538 (define-syntax-rule (error-reporting-wrapper proc formals file)
539 "Wrap PROC such that its 'system-error' exceptions are augmented to mention
541 (let ((real-proc (@ (guile) proc)))
545 (apply-formals real-proc formals))
546 (augmented-system-error-handler file)))))
549 ;; We 'set!' the global binding because (gnu build ...) modules and similar
550 ;; typically don't use (guix ui).
551 (error-reporting-wrapper symlink (source target) target))
554 ;; Note: here we use 'set!', not #:replace, because UIs typically use
555 ;; 'copy-recursively', which doesn't use (guix ui).
556 (error-reporting-wrapper copy-file (source target) target))
558 (set! canonicalize-path
559 (error-reporting-wrapper canonicalize-path (file) file))
562 (error-reporting-wrapper delete-file (file) file))
565 (error-reporting-wrapper execlp (filename . args) filename))
567 (define (make-regexp* regexp . flags)
568 "Like 'make-regexp' but error out if REGEXP is invalid, reporting the error
570 (catch 'regular-expression-syntax
572 (apply make-regexp regexp flags))
573 (lambda (key proc message . rest)
574 (leave (G_ "'~a' is not a valid regular expression: ~a~%")
577 (define (string->number* str)
578 "Like `string->number', but error out with an error message on failure."
579 (or (string->number str)
580 (leave (G_ "~a: invalid number~%") str)))
582 (define (size->number str)
583 "Convert STR, a storage measurement representation such as \"1024\" or
584 \"1MiB\", to a number of bytes. Raise an error if STR could not be
587 (string-rindex str char-set:digit))
590 (and unit-pos (substring str (+ 1 unit-pos))))
592 (let* ((numstr (if unit-pos
593 (substring str 0 (+ 1 unit-pos))
595 (num (string->number numstr)))
597 (leave (G_ "invalid number: ~a~%") numstr))
599 ((compose inexact->exact round)
602 ((or "KiB" "K" "k") (expt 2 10))
603 ((or "MiB" "M") (expt 2 20))
604 ((or "GiB" "G") (expt 2 30))
605 ((or "TiB" "T") (expt 2 40))
606 ((or "PiB" "P") (expt 2 50))
607 ((or "EiB" "E") (expt 2 60))
608 ((or "ZiB" "Z") (expt 2 70))
609 ((or "YiB" "Y") (expt 2 80))
620 (leave (G_ "unknown unit: ~a~%") unit)))))))
622 (define (display-collision-resolution-hint collision)
623 "Display hints on how to resolve COLLISION, a &profile-collistion-error."
624 (define (top-most-entry entry)
625 (let loop ((entry entry))
626 (match (force (manifest-entry-parent entry))
628 (parent (loop parent)))))
630 (let* ((first (profile-collision-error-entry collision))
631 (second (profile-collision-error-conflict collision))
632 (name1 (manifest-entry-name (top-most-entry first)))
633 (name2 (manifest-entry-name (top-most-entry second))))
634 (if (string=? name1 name2)
635 (display-hint (format #f (G_ "You cannot have two different versions
636 or variants of @code{~a} in the same profile.")
638 (display-hint (format #f (G_ "Try upgrading both @code{~a} and @code{~a},
639 or remove one of them from the profile.")
642 (define (call-with-error-handling thunk)
643 "Call THUNK within a user-friendly error handler."
644 (define (port-filename* port)
645 ;; 'port-filename' returns #f for non-file ports, but it raises an
646 ;; exception for file ports that are closed. Work around that.
647 (and (not (port-closed? port))
648 (port-filename port)))
650 (guard (c ((package-input-error? c)
651 (let* ((package (package-error-package c))
652 (input (package-error-invalid-input c))
653 (location (package-location package))
654 (file (location-file location))
655 (line (location-line location))
656 (column (location-column location)))
657 (leave (G_ "~a:~a:~a: package `~a' has an invalid input: ~s~%")
659 (package-full-name package) input)))
660 ((package-cross-build-system-error? c)
661 (let* ((package (package-error-package c))
662 (loc (package-location package))
663 (system (package-build-system package)))
664 (leave (G_ "~a: ~a: build system `~a' does not support cross builds~%")
665 (location->string loc)
666 (package-full-name package)
667 (build-system-name system))))
668 ((gexp-input-error? c)
669 (let ((input (package-error-invalid-input c)))
670 (leave (G_ "~s: invalid G-expression input~%")
671 (gexp-error-invalid-input c))))
672 ((profile-not-found-error? c)
673 (leave (G_ "profile '~a' does not exist~%")
674 (profile-error-profile c)))
675 ((missing-generation-error? c)
676 (leave (G_ "generation ~a of profile '~a' does not exist~%")
677 (missing-generation-error-generation c)
678 (profile-error-profile c)))
679 ((unmatched-pattern-error? c)
680 (let ((pattern (unmatched-pattern-error-pattern c)))
681 (leave (G_ "package '~a~@[@~a~]~@[:~a~]' not found in profile~%")
682 (manifest-pattern-name pattern)
683 (manifest-pattern-version pattern)
684 (match (manifest-pattern-output pattern)
687 ((profile-collision-error? c)
688 (let ((entry (profile-collision-error-entry c))
689 (conflict (profile-collision-error-conflict c)))
690 (define (report-parent-entries entry)
691 (let ((parent (force (manifest-entry-parent entry))))
692 (when (manifest-entry? parent)
693 (report-error (G_ " ... propagated from ~a@~a~%")
694 (manifest-entry-name parent)
695 (manifest-entry-version parent))
696 (report-parent-entries parent))))
698 (define (manifest-entry-output* entry)
699 (match (manifest-entry-output entry)
701 (output (string-append ":" output))))
703 (report-error (G_ "profile contains conflicting entries for ~a~a~%")
704 (manifest-entry-name entry)
705 (manifest-entry-output* entry))
706 (report-error (G_ " first entry: ~a@~a~a ~a~%")
707 (manifest-entry-name entry)
708 (manifest-entry-version entry)
709 (manifest-entry-output* entry)
710 (manifest-entry-item entry))
711 (report-parent-entries entry)
712 (report-error (G_ " second entry: ~a@~a~a ~a~%")
713 (manifest-entry-name conflict)
714 (manifest-entry-version conflict)
715 (manifest-entry-output* conflict)
716 (manifest-entry-item conflict))
717 (report-parent-entries conflict)
718 (display-collision-resolution-hint c)
721 (let ((file (nar-error-file c))
722 (port (nar-error-port c)))
724 (leave (G_ "corrupt input while restoring '~a' from ~s~%")
725 file (or (port-filename* port) port))
726 (leave (G_ "corrupt input while restoring archive from ~s~%")
727 (or (port-filename* port) port)))))
728 ((store-connection-error? c)
729 (leave (G_ "failed to connect to `~a': ~a~%")
730 (store-connection-error-file c)
731 (strerror (store-connection-error-code c))))
732 ((store-protocol-error? c)
733 ;; FIXME: Server-provided error messages aren't i18n'd.
735 (store-protocol-error-message c)))
736 ((derivation-missing-output-error? c)
737 (leave (G_ "reference to invalid output '~a' of derivation '~a'~%")
738 (derivation-missing-output c)
739 (derivation-file-name (derivation-error-derivation c))))
740 ((file-search-error? c)
741 (leave (G_ "file '~a' could not be found in these \
742 directories:~{ ~a~}~%")
743 (file-search-error-file-name c)
744 (file-search-error-search-path c)))
746 (leave (G_ "program exited\
747 ~@[ with non-zero exit status ~a~]\
748 ~@[ terminated by signal ~a~]\
749 ~@[ stopped by signal ~a~]: ~s~%")
750 (invoke-error-exit-status c)
751 (invoke-error-term-signal c)
752 (invoke-error-stop-signal c)
753 (cons (invoke-error-program c)
754 (invoke-error-arguments c))))
755 ((and (error-location? c) (message-condition? c))
756 (report-error (error-location c) (G_ "~a~%")
757 (gettext (condition-message c) %gettext-domain))
759 (display-hint (condition-fix-hint c)))
761 ((and (message-condition? c) (fix-hint? c))
762 (report-error (G_ "~a~%")
763 (gettext (condition-message c) %gettext-domain))
764 (display-hint (condition-fix-hint c))
766 ((message-condition? c)
767 ;; Normally '&message' error conditions have an i18n'd message.
769 (gettext (condition-message c) %gettext-domain))))
770 ;; Catch EPIPE and the likes.
773 (lambda (key proc format-string format-args . rest)
774 (leave (G_ "~a: ~a~%") proc
775 (apply format #f format-string format-args))))))
777 (define-syntax-rule (leave-on-EPIPE exp ...)
778 "Run EXP... in a context when EPIPE errors are caught and lead to 'exit'
779 with successful exit code. This is useful when writing to the standard output
780 may lead to EPIPE, because the standard output is piped through 'head' or
786 ;; We really have to exit this brutally, otherwise Guile eventually
787 ;; attempts to flush all the ports, leading to an uncaught EPIPE down
789 (if (= EPIPE (system-error-errno args))
791 (apply throw args)))))
793 (define %guix-user-module
794 ;; Module in which user expressions are evaluated.
795 ;; Compute lazily to avoid circularity with (guix gexp).
797 (let ((module (make-module)))
798 (beautify-user-module! module)
799 ;; Use (guix gexp) so that one can use #~ & co.
800 (module-use! module (resolve-interface '(guix gexp)))
803 (define (read/eval str)
804 "Read and evaluate STR, raising an error if something goes wrong."
807 (call-with-input-string str read))
809 (leave (G_ "failed to read expression ~s: ~s~%")
813 (eval exp (force %guix-user-module)))
815 (report-error (G_ "failed to evaluate expression '~a':~%") exp)
817 (('syntax-error proc message properties form . rest)
818 (report-error (G_ "syntax error: ~a~%") message))
819 (((or 'srfi-34 '%exception) obj)
820 (if (message-condition? obj)
821 (report-error (G_ "~a~%")
822 (gettext (condition-message obj)
824 (report-error (G_ "exception thrown: ~s~%") obj)))
826 (apply display-error #f (current-error-port) args))
830 (define (read/eval-package-expression str)
831 "Read and evaluate STR and return the package it refers to, or exit an
833 (match (read/eval str)
836 (leave (G_ "expression ~s does not evaluate to a package~%")
839 (define (show-derivation-outputs derivation)
840 "Show the output file names of DERIVATION, which can be a derivation or a
842 (define (show-outputs derivation outputs)
843 (format #t "~{~a~%~}"
844 (map (cut derivation->output-path derivation <>)
849 (show-outputs derivation (derivation-output-names derivation)))
850 ((? derivation-input? input)
851 (show-outputs (derivation-input-derivation input)
852 (derivation-input-sub-derivations input)))))
854 (define* (check-available-space need
855 #:optional (directory (%store-prefix)))
856 "Make sure at least NEED bytes are available in DIRECTORY. Otherwise emit a
858 (let ((free (catch 'system-error
860 (free-disk-space directory))
862 (when (and free (>= need free))
863 (warning (G_ "at least ~,1h MB needed but only ~,1h MB available in ~a~%")
864 (/ need 1e6) (/ free 1e6) directory))))
866 (define (graft-derivation? drv)
867 "Return true if DRV is definitely a graft derivation, false otherwise."
868 (match (assq-ref (derivation-properties drv) 'type)
872 (define (profile-hook-derivation? drv)
873 "Return true if DRV is definitely a profile hook derivation, false otherwise."
874 (match (assq-ref (derivation-properties drv) 'type)
878 (define (colorize-store-file-name file)
879 "Colorize FILE, a store file name, such that the hash part is less prominent
881 (let ((len (string-length file))
882 (prefix (+ (string-length (%store-prefix)) 32 2)))
885 (string-append (colorize-string (string-take file prefix)
887 (string-drop file prefix)))))
889 (define* (show-what-to-build store drv
890 #:key dry-run? (use-substitutes? #t)
891 (mode (build-mode normal)))
892 "Show what will or would (depending on DRY-RUN?) be built in realizing the
893 derivations listed in DRV using MODE, a 'build-mode' value. The elements of
894 DRV can be either derivations or derivation inputs.
896 Return #t if there's something to build, #f otherwise. When USE-SUBSTITUTES?,
897 check and report what is prerequisites are available for download."
900 ((? derivation? drv) (derivation-input drv))
901 ((? derivation-input? input) input))
904 (define substitutable-info
905 ;; Call 'substitutation-oracle' upfront so we don't end up launching the
906 ;; substituter many times. This makes a big difference, especially when
907 ;; DRV is a long list as is the case with 'guix environment'.
909 (substitution-oracle store inputs #:mode mode)
912 (define colorized-store-item
913 (if (color-output? (current-error-port))
914 colorize-store-file-name
917 (let*-values (((build download)
918 (derivation-build-plan store inputs
923 (match (fold (lambda (drv acc)
924 (let ((file (derivation-file-name drv)))
926 ((#:graft graft #:hook hook #:build build)
928 ((graft-derivation? drv)
929 `(#:graft ,(cons file graft)
932 ((profile-hook-derivation? drv)
934 #:hook ,(cons file hook)
939 #:build ,(cons file build))))))))
940 '(#:graft () #:hook () #:build ())
942 ((#:graft graft #:hook hook #:build build)
943 (values graft hook build)))))
944 (define installed-size
945 (reduce + 0 (map substitutable-nar-size download)))
947 (define download-size
948 (/ (reduce + 0 (map substitutable-download-size download))
951 (define display-download-size?
952 ;; Sometimes narinfos lack information about the download size. Only
953 ;; display when we have information for all of DOWNLOAD.
954 (not (any (compose zero? substitutable-download-size) download)))
958 (format (current-error-port)
959 (N_ "~:[The following derivation would be built:~%~{ ~a~%~}~;~]"
960 "~:[The following derivations would be built:~%~{ ~a~%~}~;~]"
962 (null? build) (map colorized-store-item build))
963 (if display-download-size?
964 (format (current-error-port)
965 ;; TRANSLATORS: "MB" is for "megabyte"; it should be
966 ;; translated to the corresponding abbreviation.
967 (G_ "~:[~,1h MB would be downloaded:~%~{ ~a~%~}~;~]")
970 (map (compose colorized-store-item substitutable-path)
972 (format (current-error-port)
973 (N_ "~:[The following file would be downloaded:~%~{ ~a~%~}~;~]"
974 "~:[The following files would be downloaded:~%~{ ~a~%~}~;~]"
977 (map (compose colorized-store-item substitutable-path)
979 (format (current-error-port)
980 (N_ "~:[The following graft would be made:~%~{ ~a~%~}~;~]"
981 "~:[The following grafts would be made:~%~{ ~a~%~}~;~]"
983 (null? graft) (map colorized-store-item graft))
984 (format (current-error-port)
985 (N_ "~:[The following profile hook would be built:~%~{ ~a~%~}~;~]"
986 "~:[The following profile hooks would be built:~%~{ ~a~%~}~;~]"
988 (null? hook) (map colorized-store-item hook)))
990 (format (current-error-port)
991 (N_ "~:[The following derivation will be built:~%~{ ~a~%~}~;~]"
992 "~:[The following derivations will be built:~%~{ ~a~%~}~;~]"
994 (null? build) (map colorized-store-item build))
995 (if display-download-size?
996 (format (current-error-port)
997 ;; TRANSLATORS: "MB" is for "megabyte"; it should be
998 ;; translated to the corresponding abbreviation.
999 (G_ "~:[~,1h MB will be downloaded:~%~{ ~a~%~}~;~]")
1002 (map (compose colorized-store-item substitutable-path)
1004 (format (current-error-port)
1005 (N_ "~:[The following file will be downloaded:~%~{ ~a~%~}~;~]"
1006 "~:[The following files will be downloaded:~%~{ ~a~%~}~;~]"
1009 (map (compose colorized-store-item substitutable-path)
1011 (format (current-error-port)
1012 (N_ "~:[The following graft will be made:~%~{ ~a~%~}~;~]"
1013 "~:[The following grafts will be made:~%~{ ~a~%~}~;~]"
1015 (null? graft) (map colorized-store-item graft))
1016 (format (current-error-port)
1017 (N_ "~:[The following profile hook will be built:~%~{ ~a~%~}~;~]"
1018 "~:[The following profile hooks will be built:~%~{ ~a~%~}~;~]"
1020 (null? hook) (map colorized-store-item hook))))
1022 (check-available-space installed-size)
1026 (define show-what-to-build*
1027 (store-lift show-what-to-build))
1029 (define (right-arrow port)
1030 "Return either a string containing the 'RIGHT ARROW' character, or an ASCII
1031 replacement if PORT is not Unicode-capable."
1032 (let ((encoding (port-encoding port))
1034 (catch 'encoding-error
1036 (call-with-output-string
1038 (set-port-encoding! port encoding)
1039 (set-port-conversion-strategy! port 'error)
1040 (display arrow port))))
1041 (lambda (key . args)
1044 (define* (show-manifest-transaction store manifest transaction
1046 "Display what will/would be installed/removed from MANIFEST by TRANSACTION."
1047 (define (package-strings name version output item)
1048 (map (lambda (name version output item)
1049 (format #f " ~a~:[:~a~;~*~]\t~a\t~a"
1051 (equal? output "out") output version
1053 (package-output store item output)
1055 name version output item))
1057 (define → ;an arrow that can be represented on stderr
1058 (right-arrow (current-error-port)))
1060 (define (upgrade-string name old-version new-version output item)
1061 (format #f " ~a~:[:~a~;~*~]\t~a ~a ~a\t~a"
1062 name (equal? output "out") output
1063 old-version → new-version
1065 (package-output store item output)
1068 (let-values (((remove install upgrade downgrade)
1069 (manifest-transaction-effects manifest transaction)))
1071 ((($ <manifest-entry> name version output item) ..1)
1072 (let ((len (length name))
1073 (remove (package-strings name version output item)))
1075 (format (current-error-port)
1076 (N_ "The following package would be removed:~%~{~a~%~}~%"
1077 "The following packages would be removed:~%~{~a~%~}~%"
1080 (format (current-error-port)
1081 (N_ "The following package will be removed:~%~{~a~%~}~%"
1082 "The following packages will be removed:~%~{~a~%~}~%"
1087 (((($ <manifest-entry> name old-version)
1088 . ($ <manifest-entry> _ new-version output item)) ..1)
1089 (let ((len (length name))
1090 (downgrade (map upgrade-string
1091 name old-version new-version output item)))
1093 (format (current-error-port)
1094 (N_ "The following package would be downgraded:~%~{~a~%~}~%"
1095 "The following packages would be downgraded:~%~{~a~%~}~%"
1098 (format (current-error-port)
1099 (N_ "The following package will be downgraded:~%~{~a~%~}~%"
1100 "The following packages will be downgraded:~%~{~a~%~}~%"
1105 (((($ <manifest-entry> name old-version)
1106 . ($ <manifest-entry> _ new-version output item)) ..1)
1107 (let ((len (length name))
1108 (upgrade (map upgrade-string
1109 name old-version new-version output item)))
1111 (format (current-error-port)
1112 (N_ "The following package would be upgraded:~%~{~a~%~}~%"
1113 "The following packages would be upgraded:~%~{~a~%~}~%"
1116 (format (current-error-port)
1117 (N_ "The following package will be upgraded:~%~{~a~%~}~%"
1118 "The following packages will be upgraded:~%~{~a~%~}~%"
1123 ((($ <manifest-entry> name version output item _) ..1)
1124 (let ((len (length name))
1125 (install (package-strings name version output item)))
1127 (format (current-error-port)
1128 (N_ "The following package would be installed:~%~{~a~%~}~%"
1129 "The following packages would be installed:~%~{~a~%~}~%"
1132 (format (current-error-port)
1133 (N_ "The following package will be installed:~%~{~a~%~}~%"
1134 "The following packages will be installed:~%~{~a~%~}~%"
1139 (define-syntax with-error-handling
1141 "Run BODY within a user-friendly error condition handler."
1143 (call-with-error-handling
1147 (define* (fill-paragraph str width #:optional (column 0))
1148 "Fill STR such that each line contains at most WIDTH characters, assuming
1149 that the first character is at COLUMN.
1151 When STR contains a single line break surrounded by other characters, it is
1152 converted to a space; sequences of more than one line break are preserved."
1153 (define (maybe-break chr result)
1155 ((column newlines chars)
1158 `(,column ,(+ 1 newlines) ,chars))
1160 (let* ((spaces (if (and (pair? chars) (eqv? (car chars) #\.)) 2 1))
1161 (chars (case newlines
1164 (append (make-list spaces #\space) chars))
1166 (append (make-list newlines #\newline) chars))))
1167 (column (case newlines
1169 ((1) (+ spaces column))
1171 (let ((chars (cons chr chars))
1172 (column (+ 1 column)))
1173 (if (> column width)
1174 (let*-values (((before after)
1175 (break (cut eqv? #\space <>) chars))
1185 (drop-while (cut eqv? #\space <>)
1187 `(,column 0 ,chars))) ; unbreakable
1188 `(,column 0 ,chars)))))))))
1190 (match (string-fold maybe-break
1193 ((column newlines chars)
1194 (list->string (reverse chars)))))
1202 (make-parameter (terminal-columns)))
1204 (set! (@@ (texinfo plain-text) wrap*)
1205 ;; XXX: Monkey patch this private procedure to let 'package->recutils'
1206 ;; parameterize the fill of description field correctly.
1208 (let ((indent (fluid-ref (@@ (texinfo plain-text) *indent*))))
1209 (fill-string (string-concatenate strings)
1210 #:line-width (%text-width) #:initial-indent indent
1211 #:subsequent-indent indent))))
1213 (define (texi->plain-text str)
1214 "Return a plain-text representation of texinfo fragment STR."
1215 ;; 'texi-fragment->stexi' uses a string port so make sure it's a
1216 ;; Unicode-capable one (see <http://bugs.gnu.org/11197>.)
1217 (with-fluids ((%default-port-encoding "UTF-8"))
1218 (stexi->plain-text (texi-fragment->stexi str))))
1220 (define (package-field-string package field-accessor)
1221 "Return a plain-text representation of PACKAGE field."
1222 (and=> (field-accessor package)
1223 (compose texi->plain-text P_)))
1225 (define (package-description-string package)
1226 "Return a plain-text representation of PACKAGE description field."
1227 (package-field-string package package-description))
1229 (define (package-synopsis-string package)
1230 "Return a plain-text representation of PACKAGE synopsis field."
1231 (package-field-string package package-synopsis))
1233 (define (string->recutils str)
1234 "Return a version of STR where newlines have been replaced by newlines
1235 followed by \"+ \", which makes for a valid multi-line field value in the
1238 (string-fold-right (lambda (chr result)
1239 (if (eqv? chr #\newline)
1240 (cons* chr #\+ #\space result)
1245 (define (hyperlink uri text)
1246 "Return a string that denotes a hyperlink using an OSC escape sequence as
1248 <https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda>."
1249 (string-append "\x1b]8;;" uri "\x1b\\"
1250 text "\x1b]8;;\x1b\\"))
1252 (define* (supports-hyperlinks? #:optional (port (current-output-port)))
1253 "Return true if PORT is a terminal that supports hyperlink escapes."
1254 ;; Note that terminals are supposed to ignore OSC escapes they don't
1255 ;; understand (this is the case of xterm as of version 349, for instance.)
1256 ;; However, Emacs comint as of 26.3 does not ignore it and instead lets it
1257 ;; through, hence the 'INSIDE_EMACS' special case below.
1258 (and (isatty?* port)
1259 (not (getenv "INSIDE_EMACS"))))
1261 (define* (file-hyperlink file #:optional (text file))
1262 "Return TEXT with escapes for a hyperlink to FILE."
1263 (hyperlink (string-append "file://" (gethostname)
1264 (encode-and-join-uri-path
1265 (string-split file #\/)))
1268 (define (location->hyperlink location)
1269 "Return a string corresponding to LOCATION, with escapes for a hyperlink."
1270 (let ((str (location->string location))
1271 (file (if (string-prefix? "/" (location-file location))
1272 (location-file location)
1273 (search-path %load-path (location-file location)))))
1275 (file-hyperlink file str)
1278 (define* (package->recutils p port #:optional (width (%text-width))
1280 (hyperlinks? (supports-hyperlinks? port))
1282 "Write to PORT a `recutils' record of package P, arranging to fit within
1283 WIDTH columns. EXTRA-FIELDS is a list of symbol/value pairs to emit. When
1284 HYPERLINKS? is true, emit hyperlink escape sequences when appropriate."
1286 ;; The available number of columns once we've taken into account space for
1287 ;; the initial "+ " prefix.
1288 (if (> width 2) (- width 2) width))
1290 (define (dependencies->recutils packages)
1291 (let ((list (string-join (delete-duplicates
1292 (map package-full-name
1293 (sort packages package<?))) " ")))
1295 (fill-paragraph list width*
1296 (string-length "dependencies: ")))))
1298 (define (package<? p1 p2)
1299 (string<? (package-full-name p1) (package-full-name p2)))
1301 ;; Note: Don't i18n field names so that people can post-process it.
1302 (format port "name: ~a~%" (package-name p))
1303 (format port "version: ~a~%" (package-version p))
1304 (format port "outputs: ~a~%" (string-join (package-outputs p)))
1305 (format port "systems: ~a~%"
1306 (string-join (package-transitive-supported-systems p)))
1307 (format port "dependencies: ~a~%"
1308 (match (package-direct-inputs p)
1309 (((labels inputs . _) ...)
1310 (dependencies->recutils (filter package? inputs)))))
1311 (format port "location: ~a~%"
1312 (or (and=> (package-location p)
1313 (if hyperlinks? location->hyperlink location->string))
1316 ;; Note: Starting from version 1.6 or recutils, hyphens are not allowed in
1317 ;; field identifiers.
1318 (format port "homepage: ~a~%" (package-home-page p))
1320 (format port "license: ~a~%"
1321 (match (package-license p)
1322 (((? license? licenses) ...)
1323 (string-join (map license-name licenses)
1325 ((? license? license)
1326 (let ((text (license-name license))
1327 (uri (license-uri license)))
1328 (if (and hyperlinks? uri (string-prefix? "http" uri))
1329 (hyperlink uri text)
1333 (format port "synopsis: ~a~%"
1334 (string-map (match-lambda
1337 (or (and=> (package-synopsis-string p) P_)
1342 (parameterize ((%text-width width*))
1344 (string-append "description: "
1345 (or (and=> (package-description p) P_)
1348 (for-each (match-lambda
1350 (let ((field (symbol->string field)))
1351 (format port "~a: ~a~%"
1353 (fill-paragraph (object->string value) width*
1354 (string-length field))))))
1363 (define (relevance obj regexps metrics)
1364 "Compute a \"relevance score\" for OBJ as a function of its number of
1365 matches of REGEXPS and accordingly to METRICS. METRICS is list of
1366 field/weight pairs, where FIELD is a procedure that returns a string or list
1367 of strings describing OBJ, and WEIGHT is a positive integer denoting the
1368 weight of this field in the final score.
1370 A score of zero means that OBJ does not match any of REGEXPS. The higher the
1371 score, the more relevant OBJ is to REGEXPS."
1372 (define (score regexp str)
1373 (fold-matches regexp str 0
1376 (if (string=? (match:substring m) str)
1380 (define (regexp->score regexp)
1381 (let ((score-regexp (lambda (str) (score regexp str))))
1382 (fold (lambda (metric relevance)
1388 (+ relevance (* (score-regexp str) weight)))
1390 (+ relevance (* weight (apply + (map score-regexp lst)))))))))
1393 (let ((scores (map regexp->score regexps)))
1394 ;; Return zero if one of REGEXPS doesn't match.
1395 (if (any zero? scores)
1397 (reduce + 0 scores))))
1399 (define %package-metrics
1400 ;; Metrics used to compute the "relevance score" of a package against a set
1402 `((,package-name . 4)
1404 ;; Match against uncommon outputs.
1406 (filter (lambda (output)
1408 ;; Some common outpus shared by many packages.
1409 '("out" "doc" "debug" "lib" "include" "bin"))))
1410 (package-outputs package)))
1413 ;; Match regexps on the raw Texinfo since formatting it is quite expensive
1414 ;; and doesn't have much of an effect on search results.
1416 (and=> (package-synopsis package) P_)) . 3)
1418 (and=> (package-description package) P_)) . 2)
1421 (match (and=> (package-location type) location-file)
1422 ((? string? file) (basename file ".scm"))
1426 (define (package-relevance package regexps)
1427 "Return a score denoting the relevance of PACKAGE for REGEXPS. A score of
1428 zero means that PACKAGE does not match any of REGEXPS."
1429 (relevance package regexps %package-metrics))
1431 (define* (display-search-results matches port
1433 (command "guix search")
1434 (print package->recutils))
1435 "Display MATCHES, a list of object/score pairs, by calling PRINT on each of
1436 them. If PORT is a terminal, print at most a full screen of results."
1441 (and first-line (isatty? port)
1442 (terminal-rows port)))
1444 (define (line-count str)
1445 (string-count str #\newline))
1447 (let loop ((matches matches))
1449 (((package . score) rest ...)
1450 (let* ((links? (supports-hyperlinks? port))
1451 (text (call-with-output-string
1454 #:hyperlinks? links?
1456 `((relevance . ,score)))))))
1458 (> (port-line port) first-line) ;print at least one result
1459 (> (+ 4 (line-count text) (port-line port))
1461 (unless (null? rest)
1462 (display-hint (format #f (G_ "Run @code{~a ... | less} \
1463 to view all the results.")
1472 (define (string->generations str)
1473 "Return the list of generations matching a pattern in STR. This function
1474 accepts the following patterns: \"1\", \"1,2,3\", \"1..9\", \"1..\", \"..9\"."
1475 (define (maybe-integer)
1476 (let ((x (string->number str)))
1480 (define (maybe-comma-separated-integers)
1481 (let ((lst (delete-duplicates
1483 (string-split str #\,)))))
1484 (and (every integer? lst)
1487 (cond ((maybe-integer)
1490 ((maybe-comma-separated-integers)
1493 ((string-match "^([0-9]+)\\.\\.([0-9]+)$" str)
1496 (let ((s (string->number (match:substring match 1)))
1497 (e (string->number (match:substring match 2))))
1498 (and (every integer? (list s e))
1500 (iota (1+ (- e s)) s)))))
1501 ((string-match "^([0-9]+)\\.\\.$" str)
1504 (let ((s (string->number (match:substring match 1))))
1507 ((string-match "^\\.\\.([0-9]+)$" str)
1510 (let ((e (string->number (match:substring match 1))))
1515 (define (string->duration str)
1516 "Return the duration matching a pattern in STR. This function accepts the
1517 following patterns: \"1d\", \"1w\", \"1m\"."
1518 (define (hours->duration hours match)
1519 (make-time time-duration 0
1520 (* 3600 hours (string->number (match:substring match 1)))))
1522 (cond ((string-match "^([0-9]+)s$" str)
1525 (make-time time-duration 0
1526 (string->number (match:substring match 1)))))
1527 ((string-match "^([0-9]+)h$" str)
1530 (hours->duration 1 match)))
1531 ((string-match "^([0-9]+)d$" str)
1534 (hours->duration 24 match)))
1535 ((string-match "^([0-9]+)w$" str)
1538 (hours->duration (* 24 7) match)))
1539 ((string-match "^([0-9]+)m$" str)
1542 (hours->duration (* 24 30) match)))
1545 (define* (matching-generations str profile
1546 #:key (duration-relation <=))
1547 "Return the list of available generations matching a pattern in STR. See
1548 'string->generations' and 'string->duration' for the list of valid patterns.
1549 When STR is a duration pattern, return all the generations whose ctime has
1550 DURATION-RELATION with the current time."
1551 (define (valid-generations lst)
1552 (define (valid-generation? n)
1553 (any (cut = n <>) (generation-numbers profile)))
1555 (fold-right (lambda (x acc)
1556 (if (valid-generation? x)
1562 (define (filter-generations generations)
1566 (drop-while (cut > n <>)
1567 (generation-numbers profile)))
1569 (valid-generations (iota n 1)))
1571 (valid-generations lst))
1574 (define (filter-by-duration duration)
1575 (define (time-at-midnight time)
1576 ;; Return TIME at midnight by setting nanoseconds, seconds, minutes, and
1578 (let ((d (time-utc->date time)))
1581 (date-day d) (date-month d)
1582 (date-year d) (date-zone-offset d)))))
1584 (define generation-ctime-alist
1585 (map (lambda (number)
1589 (generation-time profile number)))))
1590 (generation-numbers profile)))
1595 (let ((s (time-second
1596 (subtract-duration (time-at-midnight (current-time))
1598 (delete #f (map (lambda (x)
1599 (and (duration-relation s (cdr x))
1601 generation-ctime-alist))))))
1603 (cond ((string->generations str)
1606 ((string->duration str)
1611 (condition (&message
1612 (message (format #f (G_ "invalid syntax: ~a~%")
1615 (define (display-generation profile number)
1616 "Display a one-line summary of generation NUMBER of PROFILE."
1617 (unless (zero? number)
1618 (let* ((file (generation-file-name profile number))
1619 (link (if (supports-hyperlinks?)
1620 (cut file-hyperlink file <>)
1622 (header (format #f (link (highlight (G_ "Generation ~a\t~a")))
1626 (generation-time profile number))
1627 ;; TRANSLATORS: This is a format-string for date->string.
1628 ;; Please choose a format that corresponds to the
1629 ;; usual way of presenting dates in your locale.
1630 ;; See https://www.gnu.org/software/guile/manual/html_node/SRFI_002d19-Date-to-string.html
1632 (G_ "~b ~d ~Y ~T"))))
1633 (current (generation-number profile)))
1634 (if (= number current)
1635 ;; TRANSLATORS: The word "current" here is an adjective for
1636 ;; "Generation", as in "current generation". Use the appropriate
1637 ;; gender where applicable.
1638 (format #t (G_ "~a\t(current)~%") header)
1639 (format #t "~a~%" header)))))
1641 (define (display-profile-content-diff profile gen1 gen2)
1642 "Display the changed packages in PROFILE GEN2 compared to generation GEN1."
1644 (define (equal-entry? first second)
1645 (string= (manifest-entry-item first) (manifest-entry-item second)))
1647 (define (display-entry entry prefix)
1649 (($ <manifest-entry> name version output location _)
1650 (format #t " ~a ~a\t~a\t~a\t~a~%" prefix name version output location))))
1652 (define (list-entries number)
1653 (manifest-entries (profile-manifest (generation-file-name profile number))))
1655 (define (display-diff profile old new)
1656 (display-generation profile new)
1657 (let ((added (lset-difference
1658 equal-entry? (list-entries new) (list-entries old)))
1659 (removed (lset-difference
1660 equal-entry? (list-entries old) (list-entries new))))
1661 (for-each (cut display-entry <> "+") added)
1662 (for-each (cut display-entry <> "-") removed)
1665 (display-diff profile gen1 gen2))
1667 (define (profile-lock-handler profile errno . _)
1668 "Handle failure to acquire PROFILE's lock."
1669 ;; NFS mounts can return ENOLCK. When that happens, there's not much that
1670 ;; can be done, so warn the user and keep going.
1671 (if (= errno ENOLCK)
1672 (warning (G_ "cannot lock profile ~a: ~a~%")
1673 profile (strerror errno))
1674 (leave (G_ "profile ~a is locked by another process~%")
1677 (define profile-lock-file
1678 (cut string-append <> ".lock"))
1680 (define-syntax-rule (with-profile-lock profile exp ...)
1681 "Grab PROFILE's lock and evaluate EXP... Call 'leave' if the lock is
1683 (with-file-lock/no-wait (profile-lock-file profile)
1684 (cut profile-lock-handler profile <...>)
1687 (define (display-profile-content profile number)
1688 "Display the packages in PROFILE, generation NUMBER, in a human-readable
1690 (for-each (match-lambda
1691 (($ <manifest-entry> name version output location _)
1692 (format #t " ~a\t~a\t~a\t~a~%"
1693 name version output location)))
1695 ;; Show most recently installed packages last.
1698 (profile-manifest (generation-file-name profile number))))))
1700 (define (display-generation-change previous current)
1701 (format #t (G_ "switched from generation ~a to ~a~%") previous current))
1703 (define (roll-back* store profile)
1704 "Like 'roll-back', but display what is happening."
1707 (roll-back store profile))
1708 display-generation-change))
1710 (define (switch-to-generation* profile number)
1711 "Like 'switch-generation', but display what is happening."
1712 (let ((previous (switch-to-generation profile number)))
1713 (display-generation-change previous number)))
1715 (define (delete-generation* store profile generation)
1716 "Like 'delete-generation', but display what is going on."
1717 (format #t (G_ "deleting ~a~%")
1718 (generation-file-name profile generation))
1719 (delete-generation store profile generation))
1721 (define* (package-specification->name+version+output spec
1722 #:optional (output "out"))
1723 "Parse package specification SPEC and return three value: the specified
1724 package name, version number (or #f), and output name (or OUTPUT). SPEC may
1725 optionally contain a version number and an output name, as in these examples:
1732 (let*-values (((name sub-drv)
1733 (match (string-rindex spec #\:)
1734 (#f (values spec output))
1735 (colon (values (substring spec 0 colon)
1736 (substring spec (+ 1 colon))))))
1738 (package-name->name+version name)))
1739 (values name version sub-drv)))
1743 ;;; Command-line option processing.
1746 (define (show-guix-usage)
1747 (format (current-error-port)
1748 (G_ "Try `guix --help' for more information.~%"))
1751 (define (command-files)
1752 "Return the list of source files that define Guix sub-commands."
1754 (and=> (search-path %load-path "guix.scm")
1755 (compose (cut string-append <> "/guix/scripts")
1759 (cut string-suffix? ".scm" <>))
1762 (scandir directory dot-scm?)
1766 "Return the list of Guix command names."
1767 (map (compose (cut string-drop-right <> 4)
1771 (define (show-guix-help)
1772 (define (internal? command)
1773 (member command '("substitute" "authenticate" "offload"
1774 "perform-download")))
1776 (format #t (G_ "Usage: guix COMMAND ARGS...
1777 Run COMMAND with ARGS.\n"))
1779 (format #t (G_ "COMMAND must be one of the sub-commands listed below:\n"))
1781 ;; TODO: Display a synopsis of each command.
1782 (format #t "~{ ~a~%~}" (sort (remove internal? (commands))
1784 (show-bug-report-information))
1786 (define (run-guix-command command . args)
1787 "Run COMMAND with the given ARGS. Report an error when COMMAND is not
1792 (resolve-interface `(guix scripts ,command)))
1794 (format (current-error-port)
1795 (G_ "guix: ~a: command not found~%") command)
1796 (show-guix-usage))))
1798 (let ((command-main (module-ref module
1799 (symbol-append 'guix- command))))
1800 (parameterize ((program-name command))
1801 ;; Disable canonicalization so we don't don't stat unreasonably.
1802 (with-fluids ((%file-port-name-canonicalization #f))
1806 (apply command-main args))
1808 ;; Abuse 'exit-hook' (which is normally meant to be used by the
1809 ;; REPL) to run things like profiling hooks upon completion.
1810 (run-hook exit-hook)))))))
1812 (define (run-guix . args)
1813 "Run the 'guix' command defined by command line ARGS.
1814 Unlike 'guix-main', this procedure assumes that locale, i18n support,
1815 and signal handling has already been set up."
1816 (define option? (cut string-prefix? "-" <>))
1818 ;; The default %LOAD-EXTENSIONS includes the empty string, which doubles the
1819 ;; number of 'stat' calls per entry in %LOAD-PATH. Shamelessly remove it.
1820 (set! %load-extensions '(".scm"))
1824 (format (current-error-port)
1825 (G_ "guix: missing command name~%"))
1827 ((or ("-h") ("--help"))
1829 ((or ("-V") ("--version"))
1830 (show-version-and-exit "guix"))
1831 (((? option? o) args ...)
1832 (format (current-error-port)
1833 (G_ "guix: unrecognized option '~a'~%") o)
1836 (apply run-guix-command (string->symbol command)
1841 (apply run-guix-command
1842 (string->symbol command)
1845 (define (guix-main arg0 . args)
1847 (apply run-guix args))
1849 ;;; ui.scm ends here