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>
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 ;; Avoid "overrides core binding" warning.
61 #:use-module (srfi srfi-1)
62 #:use-module (srfi srfi-11)
63 #:use-module (srfi srfi-19)
64 #:use-module (srfi srfi-26)
65 #:use-module (srfi srfi-31)
66 #:use-module (srfi srfi-34)
67 #:use-module (srfi srfi-35)
68 #:autoload (ice-9 ftw) (scandir)
69 #:use-module (ice-9 match)
70 #:use-module (ice-9 format)
71 #:use-module (ice-9 regex)
72 #:autoload (system base compile) (compile-file)
73 #:autoload (system repl repl) (start-repl)
74 #:autoload (system repl debug) (make-debug stack->vector)
75 #:autoload (web uri) (encode-and-join-uri-path)
76 #:use-module (texinfo)
77 #:use-module (texinfo plain-text)
78 #:use-module (texinfo string-utils)
80 ;; Re-exports for backward compatibility.
81 #:re-export (G_ N_ P_ ;now in (guix i18n)
83 warning info report-error leave ;now in (guix diagnostics)
85 guix-warning-port program-name)
86 #:export (display-hint
91 show-bug-report-information
95 show-derivation-outputs
98 show-manifest-transaction
99 call-with-error-handling
101 with-unbound-variable-handling
104 read/eval-package-expression
105 check-available-space
109 package-description-string
110 package-synopsis-string
113 package-specification->name+version+output
122 display-search-results
129 display-profile-content
130 display-profile-content-diff
132 switch-to-generation*
135 %default-message-language
136 current-message-language
144 ;;; User interface facilities for command-line tools.
148 (define (print-unbound-variable-error port key args default-printer)
149 ;; Print unbound variable errors more nicely, and in the right language.
151 ((proc message (variable) _ ...)
152 ;; We can always omit PROC because when it's useful (i.e., different from
153 ;; "module-lookup"), it gets displayed before.
154 (format port (G_ "error: ~a: unbound variable") variable))
158 (set-exception-printer! 'unbound-variable print-unbound-variable-error)
160 (define (make-user-module modules)
161 "Return a new user module with the additional MODULES loaded."
162 ;; Module in which the machine description file is loaded.
163 (let ((module (make-fresh-user-module)))
164 (for-each (lambda (iface)
165 (module-use! module (resolve-interface iface)))
169 (define (last-frame-with-source stack)
170 "Walk stack upwards and return the last frame that has source location
171 information, or #f if it could not be found."
172 (define (frame-with-source frame)
173 ;; Walk from FRAME upwards until source location information is found.
174 (let loop ((frame frame)
179 ;; On Guile 3, the latest frame with source may be that of
180 ;; 'raise-exception' in boot-9.scm. Skip it.
181 (if (and (frame-source frame)
182 (not (eq? 'raise-exception (frame-procedure-name frame))))
184 (loop (frame-previous frame) frame)))))
186 (let* ((depth (stack-length stack))
187 (last (and (> depth 0) (stack-ref stack 0))))
188 (frame-with-source (if (> depth 1)
189 (stack-ref stack 1) ;skip the 'throw' frame
192 (define* (load* file user-module
193 #:key (on-error 'nothing-special))
194 "Load the user provided Scheme source code FILE."
195 (define (error-string frame args)
196 (call-with-output-string
198 (apply display-error frame port (cdr args)))))
201 (make-prompt-tag "user-code"))
205 ;; XXX: Force a recompilation to avoid ABI issues.
207 ;; In 2.2.3, the bogus answer to <https://bugs.gnu.org/29226> was to
208 ;; ignore all available .go, not just those from ~/.cache, which in turn
209 ;; meant that we had to rebuild *everything*. Since this is too costly,
210 ;; we have to turn off '%fresh-auto-compile' with that version, so to
211 ;; avoid ABI breakage in the user's config file, we explicitly compile
212 ;; it (the problem remains if the user's config is spread on several
213 ;; modules.) See <https://bugs.gnu.org/29881>.
214 (unless (string=? (version) "2.2.3")
215 (set! %fresh-auto-compile #t))
217 (set! %load-should-auto-compile #t)
219 (save-module-excursion
221 (set-current-module user-module)
223 ;; Hide the "auto-compiling" messages.
224 (parameterize ((current-warning-port (%make-void-port "w")))
225 (call-with-prompt tag
227 (when (string=? (version) "2.2.3")
230 (compile-file file #:env user-module))
231 (const #f))) ;EACCES maybe, let's interpret it
233 ;; Give 'load' an absolute file name so that it doesn't try to
234 ;; search for FILE in %LOAD-PATH. Note: use 'load', not
235 ;; 'primitive-load', so that FILE is compiled, which then allows us
236 ;; to provide better error reporting with source line numbers.
237 (load (canonicalize-path file)))
240 ;; XXX: Errors are reported from the pre-unwind handler below, but
241 ;; calling 'exit' from there has no effect, so we call it here.
243 (rec (handle-error . args)
244 ;; Capture the stack up to this procedure call, excluded, and pass
245 ;; the faulty stack frame to 'report-load-error'.
246 (let* ((stack (make-stack #t handle-error tag))
247 (frame (last-frame-with-source stack)))
249 (report-load-error file args frame)
254 (display (G_ "entering debugger; type ',bt' for a backtrace\n"))
255 (start-repl #:debug (make-debug (stack->vector stack) 0
256 (error-string frame args)
259 (newline (current-error-port))
260 (display-backtrace stack (current-error-port)))
264 (define (known-variable-definition variable)
265 "Search among the currently loaded modules one that defines a variable named
266 VARIABLE and return it, or #f if none was found."
267 (define (module<? m1 m2)
268 (match (module-name m2)
271 (match (module-name m1)
276 (let loop ((modules (list (resolve-module '() #f #f #:ensure #f)))
281 ;; Pick the "best" suggestion.
282 (match (sort suggestions module<?)
284 ((first _ ...) first)))
286 (if (set-contains? visited head)
287 (loop tail suggestions visited)
288 (let ((visited (set-insert head visited))
290 (hash-map->list (lambda (name module)
292 (module-submodules head)))))
293 (match (module-local-variable head variable)
294 (#f (loop next suggestions visited))
296 (match (module-name head)
297 (('gnu _ ...) head) ;must be that one
298 (_ (loop next (cons head suggestions) visited)))))))))))
300 (define %hint-color (color BOLD CYAN))
302 (define* (display-hint message #:optional (port (current-error-port)))
303 "Display MESSAGE, a l10n message possibly containing Texinfo markup, to
306 (if (color-output? port)
308 (colorize-string str %hint-color))
311 (display (colorize (G_ "hint: ")) port)
313 ;; XXX: We should arrange so that the initial indent is wider.
314 (parameterize ((%text-width (max 15 (- (terminal-columns) 5))))
315 (texi->plain-text message))
318 (define* (report-unbound-variable-error args #:key frame)
319 "Return the given unbound-variable error, where ARGS is the list of 'throw'
323 (print-exception (current-error-port) frame key args)))
325 (('unbound-variable proc message (variable) _ ...)
326 (match (known-variable-definition variable)
328 (display-hint (G_ "Did you forget a @code{use-modules} form?")))
330 (display-hint (format #f (G_ "Did you forget @code{(use-modules ~a)}?")
331 (module-name module))))))))
333 (define (check-module-matches-file module file)
334 "Check whether FILE starts with 'define-module MODULE' and print a hint if
336 ;; This is a common mistake when people start writing their own package
337 ;; definitions and try loading them with 'guix build -L …', so help them
338 ;; diagnose the problem.
340 (display-hint (format #f (G_ "File @file{~a} should probably start with:
342 @example\n(define-module ~a)\n@end example")
347 (let* ((sexp (call-with-input-file file read))
348 (loc (and (pair? sexp)
349 (source-properties->location (source-properties sexp)))))
351 (('define-module (names ...) _ ...)
352 (unless (equal? module names)
354 (G_ "module name ~a does not match file name '~a'~%")
355 names (module->source-file-name module))
358 (warning (G_ "~a: file is empty~%") file))
363 (define* (report-load-error file args #:optional frame)
364 "Report the failure to load FILE, a user-provided Scheme file.
365 ARGS is the list of arguments received by the 'throw' handler."
367 (('system-error . rest)
368 (let ((err (system-error-errno args)))
369 (report-error (G_ "failed to load '~a': ~a~%") file (strerror err))))
370 (('read-error "scm_i_lreadparen" message _ ...)
371 ;; Guile's missing-paren messages are obscure so we make them more
372 ;; intelligible here.
373 (if (string-suffix? "end of file" message)
374 (let ((location (string-drop-right message
375 (string-length "end of file"))))
376 (format (current-error-port) (G_ "~amissing closing parenthesis~%")
379 (('syntax-error proc message properties form subform . rest)
380 (let ((loc (source-properties->location properties)))
381 (report-error loc (G_ "~s: ~a~%")
382 (or subform form) message)))
383 (('unbound-variable _ ...)
384 (report-unbound-variable-error args #:frame frame))
385 (((or 'srfi-34 '%exception) obj)
386 (if (message-condition? obj)
387 (report-error (and (error-location? obj)
388 (error-location obj))
390 (gettext (condition-message obj) %gettext-domain))
391 (report-error (G_ "exception thrown: ~s~%") obj))
392 (when (fix-hint? obj)
393 (display-hint (condition-fix-hint obj))))
395 (report-error (G_ "failed to load '~a':~%") file)
397 (((? symbol? proc) (? string? message) (args ...) . rest)
398 (display-error frame (current-error-port) proc message
401 ;; Some exceptions like 'git-error' do not follow Guile's convention
402 ;; above and need to be printed with 'print-exception'.
403 (print-exception (current-error-port) frame key args))))))
405 (define (warn-about-load-error file module args) ;FIXME: factorize with ↑
406 "Report the failure to load FILE, a user-provided Scheme file, without
407 exiting. ARGS is the list of arguments received by the 'throw' handler."
409 (('system-error . rest)
410 (let ((err (system-error-errno args)))
411 (warning (G_ "failed to load '~a': ~a~%") module (strerror err))))
412 (('syntax-error proc message properties form . rest)
413 (let ((loc (source-properties->location properties)))
414 (warning loc (G_ "~a~%") message)))
415 (('unbound-variable _ ...)
416 (report-unbound-variable-error args))
417 (((or 'srfi-34 '%exception) obj)
418 (if (message-condition? obj)
419 (warning (G_ "failed to load '~a': ~a~%")
421 (gettext (condition-message obj) %gettext-domain))
422 (warning (G_ "failed to load '~a': exception thrown: ~s~%")
425 (warning (G_ "failed to load '~a':~%") module)
426 (apply display-error #f (current-error-port) args)
427 (check-module-matches-file module file))))
429 (define (call-with-unbound-variable-handling thunk)
431 (make-prompt-tag "user-code"))
433 (catch 'unbound-variable
435 (call-with-prompt tag
439 (rec (handle-error . args)
440 (let* ((stack (make-stack #t handle-error tag))
441 (frame (and stack (last-frame-with-source stack))))
442 (report-unbound-variable-error args #:frame frame)
445 (define-syntax-rule (with-unbound-variable-handling exp ...)
446 "Capture 'unbound-variable' exceptions in the dynamic extent of EXP... and
447 report them in a user-friendly way."
448 (call-with-unbound-variable-handling (lambda () exp ...)))
450 (define %default-message-language
451 ;; Default language to use for messages.
452 (make-parameter "en"))
454 (define (current-message-language)
455 "Return the language used for messages according to the current locale.
456 Return %DEFAULT-MESSAGE-LANGUAGE if that information could not be obtained. The
457 result is an ISO-639-2 language code such as \"ar\", without the territory
459 (let ((locale (setlocale LC_MESSAGES)))
460 (match (string-index locale #\_)
462 (index (string-take locale index)))))
464 (define (install-locale)
465 "Install the current locale settings."
468 (setlocale LC_ALL ""))
470 (display-hint (G_ "Consider installing the @code{glibc-utf8-locales} or
471 @code{glibc-locales} package and defining @code{GUIX_LOCPATH}, along these
475 guix package -i glibc-utf8-locales
476 export GUIX_LOCPATH=\"$HOME/.guix-profile/lib/locale\"
479 See the \"Application Setup\" section in the manual, for more info.\n")))))
481 (define (initialize-guix)
482 "Perform the usual initialization for stand-alone Guix commands."
483 ;; By default don't annoy users with deprecation warnings. In practice,
484 ;; 'define-deprecated' in (ice-9 deprecated) arranges so that those warnings
485 ;; are emitted at expansion-time only, but there are cases where they could
486 ;; slip through, for instance when interpreting code.
487 (unless (getenv "GUILE_WARN_DEPRECATED")
488 (debug-disable 'warn-deprecated))
491 (textdomain %gettext-domain)
493 ;; Ignore SIGPIPE. If the daemon closes the connection, we prefer to be
494 ;; notified via an EPIPE later.
495 (sigaction SIGPIPE SIG_IGN)
497 (setvbuf (current-output-port) 'line)
498 (setvbuf (current-error-port) 'line))
500 (define* (show-version-and-exit #:optional (command (car (command-line))))
501 "Display version information for COMMAND and `(exit 0)'."
502 (simple-format #t "~a (~a) ~a~%"
503 command %guix-package-name %guix-version)
504 (format #t "Copyright ~a 2020 ~a"
505 ;; TRANSLATORS: Translate "(C)" to the copyright symbol
506 ;; (C-in-a-circle), if this symbol is available in the user's
507 ;; locale. Otherwise, do not translate "(C)"; leave it as-is. */
509 (G_ "the Guix authors\n"))
511 License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
512 This is free software: you are free to change and redistribute it.
513 There is NO WARRANTY, to the extent permitted by law.
517 (define (show-bug-report-information)
518 ;; TRANSLATORS: The placeholder indicates the bug-reporting address for this
519 ;; package. Please add another line saying "Report translation bugs to
520 ;; ...\n" with the address for translation bugs (typically your translation
521 ;; team's web or email address).
523 Report bugs to: ~a.") %guix-bug-report-address)
525 ~a home page: <~a>") %guix-package-name %guix-home-page-url)
527 General help using GNU software: <http://www.gnu.org/gethelp/>"))
530 (define (augmented-system-error-handler file)
531 "Return a 'system-error' handler that mentions FILE in its message."
532 (lambda (key proc fmt args errno)
533 ;; Augment the FMT and ARGS with information about TARGET (this
534 ;; information is missing as of Guile 2.0.11, making the exception
536 (apply throw key proc "~A: ~S"
537 (list (strerror (car errno)) file)
540 (define-syntax apply-formals
542 ((_ proc (args ...)) (proc args ...))
543 ((_ proc (arg1 args ... . rest)) (apply proc arg1 args ... rest))))
545 (define-syntax-rule (error-reporting-wrapper proc formals file)
546 "Wrap PROC such that its 'system-error' exceptions are augmented to mention
548 (let ((real-proc (@ (guile) proc)))
552 (apply-formals real-proc formals))
553 (augmented-system-error-handler file)))))
556 ;; We 'set!' the global binding because (gnu build ...) modules and similar
557 ;; typically don't use (guix ui).
558 (error-reporting-wrapper symlink (source target) target))
561 ;; Note: here we use 'set!', not #:replace, because UIs typically use
562 ;; 'copy-recursively', which doesn't use (guix ui).
563 (error-reporting-wrapper copy-file (source target) target))
565 (set! canonicalize-path
566 (error-reporting-wrapper canonicalize-path (file) file))
569 (error-reporting-wrapper delete-file (file) file))
572 (error-reporting-wrapper execlp (filename . args) filename))
574 (define (make-regexp* regexp . flags)
575 "Like 'make-regexp' but error out if REGEXP is invalid, reporting the error
577 (catch 'regular-expression-syntax
579 (apply make-regexp regexp flags))
580 (lambda (key proc message . rest)
581 (leave (G_ "'~a' is not a valid regular expression: ~a~%")
584 (define (string->number* str)
585 "Like `string->number', but error out with an error message on failure."
586 (or (string->number str)
587 (leave (G_ "~a: invalid number~%") str)))
589 (define (size->number str)
590 "Convert STR, a storage measurement representation such as \"1024\" or
591 \"1MiB\", to a number of bytes. Raise an error if STR could not be
594 (string-rindex str char-set:digit))
597 (and unit-pos (substring str (+ 1 unit-pos))))
599 (let* ((numstr (if unit-pos
600 (substring str 0 (+ 1 unit-pos))
602 (num (string->number numstr)))
604 (leave (G_ "invalid number: ~a~%") numstr))
606 ((compose inexact->exact round)
609 ((or "KiB" "K" "k") (expt 2 10))
610 ((or "MiB" "M") (expt 2 20))
611 ((or "GiB" "G") (expt 2 30))
612 ((or "TiB" "T") (expt 2 40))
613 ((or "PiB" "P") (expt 2 50))
614 ((or "EiB" "E") (expt 2 60))
615 ((or "ZiB" "Z") (expt 2 70))
616 ((or "YiB" "Y") (expt 2 80))
627 (leave (G_ "unknown unit: ~a~%") unit)))))))
629 (define (display-collision-resolution-hint collision)
630 "Display hints on how to resolve COLLISION, a &profile-collistion-error."
631 (define (top-most-entry entry)
632 (let loop ((entry entry))
633 (match (force (manifest-entry-parent entry))
635 (parent (loop parent)))))
637 (let* ((first (profile-collision-error-entry collision))
638 (second (profile-collision-error-conflict collision))
639 (name1 (manifest-entry-name (top-most-entry first)))
640 (name2 (manifest-entry-name (top-most-entry second))))
641 (if (string=? name1 name2)
642 (display-hint (format #f (G_ "You cannot have two different versions
643 or variants of @code{~a} in the same profile.")
645 (display-hint (format #f (G_ "Try upgrading both @code{~a} and @code{~a},
646 or remove one of them from the profile.")
649 (define (call-with-error-handling thunk)
650 "Call THUNK within a user-friendly error handler."
651 (define (port-filename* port)
652 ;; 'port-filename' returns #f for non-file ports, but it raises an
653 ;; exception for file ports that are closed. Work around that.
654 (and (not (port-closed? port))
655 (port-filename port)))
657 (guard (c ((package-input-error? c)
658 (let* ((package (package-error-package c))
659 (input (package-error-invalid-input c))
660 (location (package-location package))
661 (file (location-file location))
662 (line (location-line location))
663 (column (location-column location)))
664 (leave (G_ "~a:~a:~a: package `~a' has an invalid input: ~s~%")
666 (package-full-name package) input)))
667 ((package-cross-build-system-error? c)
668 (let* ((package (package-error-package c))
669 (loc (package-location package))
670 (system (package-build-system package)))
671 (leave (G_ "~a: ~a: build system `~a' does not support cross builds~%")
672 (location->string loc)
673 (package-full-name package)
674 (build-system-name system))))
675 ((gexp-input-error? c)
676 (let ((input (package-error-invalid-input c)))
677 (leave (G_ "~s: invalid G-expression input~%")
678 (gexp-error-invalid-input c))))
679 ((profile-not-found-error? c)
680 (leave (G_ "profile '~a' does not exist~%")
681 (profile-error-profile c)))
682 ((missing-generation-error? c)
683 (leave (G_ "generation ~a of profile '~a' does not exist~%")
684 (missing-generation-error-generation c)
685 (profile-error-profile c)))
686 ((unmatched-pattern-error? c)
687 (let ((pattern (unmatched-pattern-error-pattern c)))
688 (leave (G_ "package '~a~@[@~a~]~@[:~a~]' not found in profile~%")
689 (manifest-pattern-name pattern)
690 (manifest-pattern-version pattern)
691 (match (manifest-pattern-output pattern)
694 ((profile-collision-error? c)
695 (let ((entry (profile-collision-error-entry c))
696 (conflict (profile-collision-error-conflict c)))
697 (define (report-parent-entries entry)
698 (let ((parent (force (manifest-entry-parent entry))))
699 (when (manifest-entry? parent)
700 (report-error (G_ " ... propagated from ~a@~a~%")
701 (manifest-entry-name parent)
702 (manifest-entry-version parent))
703 (report-parent-entries parent))))
705 (define (manifest-entry-output* entry)
706 (match (manifest-entry-output entry)
708 (output (string-append ":" output))))
710 (report-error (G_ "profile contains conflicting entries for ~a~a~%")
711 (manifest-entry-name entry)
712 (manifest-entry-output* entry))
713 (report-error (G_ " first entry: ~a@~a~a ~a~%")
714 (manifest-entry-name entry)
715 (manifest-entry-version entry)
716 (manifest-entry-output* entry)
717 (manifest-entry-item entry))
718 (report-parent-entries entry)
719 (report-error (G_ " second entry: ~a@~a~a ~a~%")
720 (manifest-entry-name conflict)
721 (manifest-entry-version conflict)
722 (manifest-entry-output* conflict)
723 (manifest-entry-item conflict))
724 (report-parent-entries conflict)
725 (display-collision-resolution-hint c)
728 (let ((file (nar-error-file c))
729 (port (nar-error-port c)))
731 (leave (G_ "corrupt input while restoring '~a' from ~s~%")
732 file (or (port-filename* port) port))
733 (leave (G_ "corrupt input while restoring archive from ~s~%")
734 (or (port-filename* port) port)))))
735 ((store-connection-error? c)
736 (leave (G_ "failed to connect to `~a': ~a~%")
737 (store-connection-error-file c)
738 (strerror (store-connection-error-code c))))
739 ((store-protocol-error? c)
740 ;; FIXME: Server-provided error messages aren't i18n'd.
742 (store-protocol-error-message c)))
743 ((derivation-missing-output-error? c)
744 (leave (G_ "reference to invalid output '~a' of derivation '~a'~%")
745 (derivation-missing-output c)
746 (derivation-file-name (derivation-error-derivation c))))
747 ((file-search-error? c)
748 (leave (G_ "file '~a' could not be found in these \
749 directories:~{ ~a~}~%")
750 (file-search-error-file-name c)
751 (file-search-error-search-path c)))
753 (leave (G_ "program exited\
754 ~@[ with non-zero exit status ~a~]\
755 ~@[ terminated by signal ~a~]\
756 ~@[ stopped by signal ~a~]: ~s~%")
757 (invoke-error-exit-status c)
758 (invoke-error-term-signal c)
759 (invoke-error-stop-signal c)
760 (cons (invoke-error-program c)
761 (invoke-error-arguments c))))
762 ((and (error-location? c) (message-condition? c))
763 (report-error (error-location c) (G_ "~a~%")
764 (gettext (condition-message c) %gettext-domain))
766 (display-hint (condition-fix-hint c)))
768 ((and (message-condition? c) (fix-hint? c))
769 (report-error (G_ "~a~%")
770 (gettext (condition-message c) %gettext-domain))
771 (display-hint (condition-fix-hint c))
773 ((message-condition? c)
774 ;; Normally '&message' error conditions have an i18n'd message.
776 (gettext (condition-message c) %gettext-domain))))
777 ;; Catch EPIPE and the likes.
780 (lambda (key proc format-string format-args . rest)
781 (leave (G_ "~a: ~a~%") proc
782 (apply format #f format-string format-args))))))
784 (define-syntax-rule (leave-on-EPIPE exp ...)
785 "Run EXP... in a context when EPIPE errors are caught and lead to 'exit'
786 with successful exit code. This is useful when writing to the standard output
787 may lead to EPIPE, because the standard output is piped through 'head' or
793 ;; We really have to exit this brutally, otherwise Guile eventually
794 ;; attempts to flush all the ports, leading to an uncaught EPIPE down
796 (if (= EPIPE (system-error-errno args))
798 (apply throw args)))))
800 (define %guix-user-module
801 ;; Module in which user expressions are evaluated.
802 ;; Compute lazily to avoid circularity with (guix gexp).
804 (let ((module (make-module)))
805 (beautify-user-module! module)
806 ;; Use (guix gexp) so that one can use #~ & co.
807 (module-use! module (resolve-interface '(guix gexp)))
810 (define (read/eval str)
811 "Read and evaluate STR, raising an error if something goes wrong."
814 (call-with-input-string str read))
816 (leave (G_ "failed to read expression ~s: ~s~%")
820 (eval exp (force %guix-user-module)))
822 (report-error (G_ "failed to evaluate expression '~a':~%") exp)
824 (('syntax-error proc message properties form . rest)
825 (report-error (G_ "syntax error: ~a~%") message))
826 (((or 'srfi-34 '%exception) obj)
827 (if (message-condition? obj)
828 (report-error (G_ "~a~%")
829 (gettext (condition-message obj)
831 (report-error (G_ "exception thrown: ~s~%") obj)))
833 (apply display-error #f (current-error-port) args))
837 (define (read/eval-package-expression str)
838 "Read and evaluate STR and return the package it refers to, or exit an
840 (match (read/eval str)
843 (leave (G_ "expression ~s does not evaluate to a package~%")
846 (define (show-derivation-outputs derivation)
847 "Show the output file names of DERIVATION, which can be a derivation or a
849 (define (show-outputs derivation outputs)
850 (format #t "~{~a~%~}"
851 (map (cut derivation->output-path derivation <>)
856 (show-outputs derivation (derivation-output-names derivation)))
857 ((? derivation-input? input)
858 (show-outputs (derivation-input-derivation input)
859 (derivation-input-sub-derivations input)))))
861 (define* (check-available-space need
862 #:optional (directory (%store-prefix)))
863 "Make sure at least NEED bytes are available in DIRECTORY. Otherwise emit a
865 (let ((free (catch 'system-error
867 (free-disk-space directory))
869 (when (and free (>= need free))
870 (warning (G_ "at least ~,1h MB needed but only ~,1h MB available in ~a~%")
871 (/ need 1e6) (/ free 1e6) directory))))
873 (define (graft-derivation? drv)
874 "Return true if DRV is definitely a graft derivation, false otherwise."
875 (match (assq-ref (derivation-properties drv) 'type)
879 (define (profile-hook-derivation? drv)
880 "Return true if DRV is definitely a profile hook derivation, false otherwise."
881 (match (assq-ref (derivation-properties drv) 'type)
885 (define (colorize-store-file-name file)
886 "Colorize FILE, a store file name, such that the hash part is less prominent
888 (let ((len (string-length file))
889 (prefix (+ (string-length (%store-prefix)) 32 2)))
892 (string-append (colorize-string (string-take file prefix)
894 (string-drop file prefix)))))
896 (define* (show-what-to-build store drv
897 #:key dry-run? (use-substitutes? #t)
898 (mode (build-mode normal)))
899 "Show what will or would (depending on DRY-RUN?) be built in realizing the
900 derivations listed in DRV using MODE, a 'build-mode' value. The elements of
901 DRV can be either derivations or derivation inputs.
903 Return #t if there's something to build, #f otherwise. When USE-SUBSTITUTES?,
904 check and report what is prerequisites are available for download."
907 ((? derivation? drv) (derivation-input drv))
908 ((? derivation-input? input) input))
911 (define substitutable-info
912 ;; Call 'substitutation-oracle' upfront so we don't end up launching the
913 ;; substituter many times. This makes a big difference, especially when
914 ;; DRV is a long list as is the case with 'guix environment'.
916 (substitution-oracle store inputs #:mode mode)
919 (define colorized-store-item
920 (if (color-output? (current-error-port))
921 colorize-store-file-name
924 (let*-values (((build download)
925 (derivation-build-plan store inputs
930 (match (fold (lambda (drv acc)
931 (let ((file (derivation-file-name drv)))
933 ((#:graft graft #:hook hook #:build build)
935 ((graft-derivation? drv)
936 `(#:graft ,(cons file graft)
939 ((profile-hook-derivation? drv)
941 #:hook ,(cons file hook)
946 #:build ,(cons file build))))))))
947 '(#:graft () #:hook () #:build ())
949 ((#:graft graft #:hook hook #:build build)
950 (values graft hook build)))))
951 (define installed-size
952 (reduce + 0 (map substitutable-nar-size download)))
954 (define download-size
955 (/ (reduce + 0 (map substitutable-download-size download))
958 (define display-download-size?
959 ;; Sometimes narinfos lack information about the download size. Only
960 ;; display when we have information for all of DOWNLOAD.
961 (not (any (compose zero? substitutable-download-size) download)))
965 (format (current-error-port)
966 (N_ "~:[The following derivation would be built:~%~{ ~a~%~}~;~]"
967 "~:[The following derivations would be built:~%~{ ~a~%~}~;~]"
969 (null? build) (map colorized-store-item build))
970 (if display-download-size?
971 (format (current-error-port)
972 ;; TRANSLATORS: "MB" is for "megabyte"; it should be
973 ;; translated to the corresponding abbreviation.
974 (G_ "~:[~,1h MB would be downloaded:~%~{ ~a~%~}~;~]")
977 (map (compose colorized-store-item substitutable-path)
979 (format (current-error-port)
980 (N_ "~:[The following file would be downloaded:~%~{ ~a~%~}~;~]"
981 "~:[The following files would be downloaded:~%~{ ~a~%~}~;~]"
984 (map (compose colorized-store-item substitutable-path)
986 (format (current-error-port)
987 (N_ "~:[The following graft would be made:~%~{ ~a~%~}~;~]"
988 "~:[The following grafts would be made:~%~{ ~a~%~}~;~]"
990 (null? graft) (map colorized-store-item graft))
991 (format (current-error-port)
992 (N_ "~:[The following profile hook would be built:~%~{ ~a~%~}~;~]"
993 "~:[The following profile hooks would be built:~%~{ ~a~%~}~;~]"
995 (null? hook) (map colorized-store-item hook)))
997 (format (current-error-port)
998 (N_ "~:[The following derivation will be built:~%~{ ~a~%~}~;~]"
999 "~:[The following derivations will be built:~%~{ ~a~%~}~;~]"
1001 (null? build) (map colorized-store-item build))
1002 (if display-download-size?
1003 (format (current-error-port)
1004 ;; TRANSLATORS: "MB" is for "megabyte"; it should be
1005 ;; translated to the corresponding abbreviation.
1006 (G_ "~:[~,1h MB will be downloaded:~%~{ ~a~%~}~;~]")
1009 (map (compose colorized-store-item substitutable-path)
1011 (format (current-error-port)
1012 (N_ "~:[The following file will be downloaded:~%~{ ~a~%~}~;~]"
1013 "~:[The following files will be downloaded:~%~{ ~a~%~}~;~]"
1016 (map (compose colorized-store-item substitutable-path)
1018 (format (current-error-port)
1019 (N_ "~:[The following graft will be made:~%~{ ~a~%~}~;~]"
1020 "~:[The following grafts will be made:~%~{ ~a~%~}~;~]"
1022 (null? graft) (map colorized-store-item graft))
1023 (format (current-error-port)
1024 (N_ "~:[The following profile hook will be built:~%~{ ~a~%~}~;~]"
1025 "~:[The following profile hooks will be built:~%~{ ~a~%~}~;~]"
1027 (null? hook) (map colorized-store-item hook))))
1029 (check-available-space installed-size)
1033 (define show-what-to-build*
1034 (store-lift show-what-to-build))
1036 (define (right-arrow port)
1037 "Return either a string containing the 'RIGHT ARROW' character, or an ASCII
1038 replacement if PORT is not Unicode-capable."
1039 (let ((encoding (port-encoding port))
1041 (catch 'encoding-error
1043 (call-with-output-string
1045 (set-port-encoding! port encoding)
1046 (set-port-conversion-strategy! port 'error)
1047 (display arrow port))))
1048 (lambda (key . args)
1051 (define* (show-manifest-transaction store manifest transaction
1053 "Display what will/would be installed/removed from MANIFEST by TRANSACTION."
1054 (define (package-strings name version output item)
1055 (map (lambda (name version output item)
1056 (format #f " ~a~:[:~a~;~*~]\t~a\t~a"
1058 (equal? output "out") output version
1060 (package-output store item output)
1062 name version output item))
1064 (define → ;an arrow that can be represented on stderr
1065 (right-arrow (current-error-port)))
1067 (define (upgrade-string name old-version new-version output item)
1068 (format #f " ~a~:[:~a~;~*~]\t~a ~a ~a\t~a"
1069 name (equal? output "out") output
1070 old-version → new-version
1072 (package-output store item output)
1075 (let-values (((remove install upgrade downgrade)
1076 (manifest-transaction-effects manifest transaction)))
1078 ((($ <manifest-entry> name version output item) ..1)
1079 (let ((len (length name))
1080 (remove (package-strings name version output item)))
1082 (format (current-error-port)
1083 (N_ "The following package would be removed:~%~{~a~%~}~%"
1084 "The following packages would be removed:~%~{~a~%~}~%"
1087 (format (current-error-port)
1088 (N_ "The following package will be removed:~%~{~a~%~}~%"
1089 "The following packages will be removed:~%~{~a~%~}~%"
1094 (((($ <manifest-entry> name old-version)
1095 . ($ <manifest-entry> _ new-version output item)) ..1)
1096 (let ((len (length name))
1097 (downgrade (map upgrade-string
1098 name old-version new-version output item)))
1100 (format (current-error-port)
1101 (N_ "The following package would be downgraded:~%~{~a~%~}~%"
1102 "The following packages would be downgraded:~%~{~a~%~}~%"
1105 (format (current-error-port)
1106 (N_ "The following package will be downgraded:~%~{~a~%~}~%"
1107 "The following packages will be downgraded:~%~{~a~%~}~%"
1112 (((($ <manifest-entry> name old-version)
1113 . ($ <manifest-entry> _ new-version output item)) ..1)
1114 (let ((len (length name))
1115 (upgrade (map upgrade-string
1116 name old-version new-version output item)))
1118 (format (current-error-port)
1119 (N_ "The following package would be upgraded:~%~{~a~%~}~%"
1120 "The following packages would be upgraded:~%~{~a~%~}~%"
1123 (format (current-error-port)
1124 (N_ "The following package will be upgraded:~%~{~a~%~}~%"
1125 "The following packages will be upgraded:~%~{~a~%~}~%"
1130 ((($ <manifest-entry> name version output item _) ..1)
1131 (let ((len (length name))
1132 (install (package-strings name version output item)))
1134 (format (current-error-port)
1135 (N_ "The following package would be installed:~%~{~a~%~}~%"
1136 "The following packages would be installed:~%~{~a~%~}~%"
1139 (format (current-error-port)
1140 (N_ "The following package will be installed:~%~{~a~%~}~%"
1141 "The following packages will be installed:~%~{~a~%~}~%"
1146 (define-syntax with-error-handling
1148 "Run BODY within a user-friendly error condition handler."
1150 (call-with-error-handling
1154 (define* (fill-paragraph str width #:optional (column 0))
1155 "Fill STR such that each line contains at most WIDTH characters, assuming
1156 that the first character is at COLUMN.
1158 When STR contains a single line break surrounded by other characters, it is
1159 converted to a space; sequences of more than one line break are preserved."
1160 (define (maybe-break chr result)
1162 ((column newlines chars)
1165 `(,column ,(+ 1 newlines) ,chars))
1167 (let* ((spaces (if (and (pair? chars) (eqv? (car chars) #\.)) 2 1))
1168 (chars (case newlines
1171 (append (make-list spaces #\space) chars))
1173 (append (make-list newlines #\newline) chars))))
1174 (column (case newlines
1176 ((1) (+ spaces column))
1178 (let ((chars (cons chr chars))
1179 (column (+ 1 column)))
1180 (if (> column width)
1181 (let*-values (((before after)
1182 (break (cut eqv? #\space <>) chars))
1192 (drop-while (cut eqv? #\space <>)
1194 `(,column 0 ,chars))) ; unbreakable
1195 `(,column 0 ,chars)))))))))
1197 (match (string-fold maybe-break
1200 ((column newlines chars)
1201 (list->string (reverse chars)))))
1209 (make-parameter (terminal-columns)))
1211 (set! (@@ (texinfo plain-text) wrap*)
1212 ;; XXX: Monkey patch this private procedure to let 'package->recutils'
1213 ;; parameterize the fill of description field correctly.
1215 (let ((indent (fluid-ref (@@ (texinfo plain-text) *indent*))))
1216 (fill-string (string-concatenate strings)
1217 #:line-width (%text-width) #:initial-indent indent
1218 #:subsequent-indent indent))))
1220 (define (texi->plain-text str)
1221 "Return a plain-text representation of texinfo fragment STR."
1222 ;; 'texi-fragment->stexi' uses a string port so make sure it's a
1223 ;; Unicode-capable one (see <http://bugs.gnu.org/11197>.)
1224 (with-fluids ((%default-port-encoding "UTF-8"))
1225 (stexi->plain-text (texi-fragment->stexi str))))
1227 (define (package-field-string package field-accessor)
1228 "Return a plain-text representation of PACKAGE field."
1229 (and=> (field-accessor package)
1230 (compose texi->plain-text P_)))
1232 (define (package-description-string package)
1233 "Return a plain-text representation of PACKAGE description field."
1234 (package-field-string package package-description))
1236 (define (package-synopsis-string package)
1237 "Return a plain-text representation of PACKAGE synopsis field."
1238 (package-field-string package package-synopsis))
1240 (define (string->recutils str)
1241 "Return a version of STR where newlines have been replaced by newlines
1242 followed by \"+ \", which makes for a valid multi-line field value in the
1245 (string-fold-right (lambda (chr result)
1246 (if (eqv? chr #\newline)
1247 (cons* chr #\+ #\space result)
1252 (define (hyperlink uri text)
1253 "Return a string that denotes a hyperlink using an OSC escape sequence as
1255 <https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda>."
1256 (string-append "\x1b]8;;" uri "\x1b\\"
1257 text "\x1b]8;;\x1b\\"))
1259 (define* (supports-hyperlinks? #:optional (port (current-output-port)))
1260 "Return true if PORT is a terminal that supports hyperlink escapes."
1261 ;; Note that terminals are supposed to ignore OSC escapes they don't
1262 ;; understand (this is the case of xterm as of version 349, for instance.)
1263 ;; However, Emacs comint as of 26.3 does not ignore it and instead lets it
1264 ;; through, hence the 'INSIDE_EMACS' special case below.
1265 (and (isatty?* port)
1266 (not (getenv "INSIDE_EMACS"))))
1268 (define* (file-hyperlink file #:optional (text file))
1269 "Return TEXT with escapes for a hyperlink to FILE."
1270 (hyperlink (string-append "file://" (gethostname)
1271 (encode-and-join-uri-path
1272 (string-split file #\/)))
1275 (define (location->hyperlink location)
1276 "Return a string corresponding to LOCATION, with escapes for a hyperlink."
1277 (let ((str (location->string location))
1278 (file (if (string-prefix? "/" (location-file location))
1279 (location-file location)
1280 (search-path %load-path (location-file location)))))
1282 (file-hyperlink file str)
1285 (define* (package->recutils p port #:optional (width (%text-width))
1287 (hyperlinks? (supports-hyperlinks? port))
1289 "Write to PORT a `recutils' record of package P, arranging to fit within
1290 WIDTH columns. EXTRA-FIELDS is a list of symbol/value pairs to emit. When
1291 HYPERLINKS? is true, emit hyperlink escape sequences when appropriate."
1293 ;; The available number of columns once we've taken into account space for
1294 ;; the initial "+ " prefix.
1295 (if (> width 2) (- width 2) width))
1297 (define (dependencies->recutils packages)
1298 (let ((list (string-join (delete-duplicates
1299 (map package-full-name
1300 (sort packages package<?))) " ")))
1302 (fill-paragraph list width*
1303 (string-length "dependencies: ")))))
1305 (define (package<? p1 p2)
1306 (string<? (package-full-name p1) (package-full-name p2)))
1308 ;; Note: Don't i18n field names so that people can post-process it.
1309 (format port "name: ~a~%" (package-name p))
1310 (format port "version: ~a~%" (package-version p))
1311 (format port "outputs: ~a~%" (string-join (package-outputs p)))
1312 (format port "systems: ~a~%"
1313 (string-join (package-transitive-supported-systems p)))
1314 (format port "dependencies: ~a~%"
1315 (match (package-direct-inputs p)
1316 (((labels inputs . _) ...)
1317 (dependencies->recutils (filter package? inputs)))))
1318 (format port "location: ~a~%"
1319 (or (and=> (package-location p)
1320 (if hyperlinks? location->hyperlink location->string))
1323 ;; Note: Starting from version 1.6 or recutils, hyphens are not allowed in
1324 ;; field identifiers.
1325 (format port "homepage: ~a~%" (package-home-page p))
1327 (format port "license: ~a~%"
1328 (match (package-license p)
1329 (((? license? licenses) ...)
1330 (string-join (map license-name licenses)
1332 ((? license? license)
1333 (let ((text (license-name license))
1334 (uri (license-uri license)))
1335 (if (and hyperlinks? uri (string-prefix? "http" uri))
1336 (hyperlink uri text)
1340 (format port "synopsis: ~a~%"
1341 (string-map (match-lambda
1344 (or (and=> (package-synopsis-string p) P_)
1349 (parameterize ((%text-width width*))
1351 (string-append "description: "
1352 (or (and=> (package-description p) P_)
1355 (for-each (match-lambda
1357 (let ((field (symbol->string field)))
1358 (format port "~a: ~a~%"
1360 (fill-paragraph (object->string value) width*
1361 (string-length field))))))
1370 (define (relevance obj regexps metrics)
1371 "Compute a \"relevance score\" for OBJ as a function of its number of
1372 matches of REGEXPS and accordingly to METRICS. METRICS is list of
1373 field/weight pairs, where FIELD is a procedure that returns a string or list
1374 of strings describing OBJ, and WEIGHT is a positive integer denoting the
1375 weight of this field in the final score.
1377 A score of zero means that OBJ does not match any of REGEXPS. The higher the
1378 score, the more relevant OBJ is to REGEXPS."
1379 (define (score regexp str)
1380 (fold-matches regexp str 0
1383 (if (string=? (match:substring m) str)
1387 (define (regexp->score regexp)
1388 (let ((score-regexp (lambda (str) (score regexp str))))
1389 (fold (lambda (metric relevance)
1395 (+ relevance (* (score-regexp str) weight)))
1397 (+ relevance (* weight (apply + (map score-regexp lst)))))))))
1400 (let ((scores (map regexp->score regexps)))
1401 ;; Return zero if one of REGEXPS doesn't match.
1402 (if (any zero? scores)
1404 (reduce + 0 scores))))
1406 (define %package-metrics
1407 ;; Metrics used to compute the "relevance score" of a package against a set
1409 `((,package-name . 4)
1411 ;; Match against uncommon outputs.
1413 (filter (lambda (output)
1415 ;; Some common outpus shared by many packages.
1416 '("out" "doc" "debug" "lib" "include" "bin"))))
1417 (package-outputs package)))
1420 ;; Match regexps on the raw Texinfo since formatting it is quite expensive
1421 ;; and doesn't have much of an effect on search results.
1423 (and=> (package-synopsis package) P_)) . 3)
1425 (and=> (package-description package) P_)) . 2)
1428 (match (and=> (package-location type) location-file)
1429 ((? string? file) (basename file ".scm"))
1433 (define (package-relevance package regexps)
1434 "Return a score denoting the relevance of PACKAGE for REGEXPS. A score of
1435 zero means that PACKAGE does not match any of REGEXPS."
1436 (relevance package regexps %package-metrics))
1438 (define* (display-search-results matches port
1440 (command "guix search")
1441 (print package->recutils))
1442 "Display MATCHES, a list of object/score pairs, by calling PRINT on each of
1443 them. If PORT is a terminal, print at most a full screen of results."
1448 (and first-line (isatty? port)
1449 (terminal-rows port)))
1451 (define (line-count str)
1452 (string-count str #\newline))
1454 (let loop ((matches matches))
1456 (((package . score) rest ...)
1457 (let* ((links? (supports-hyperlinks? port))
1458 (text (call-with-output-string
1461 #:hyperlinks? links?
1463 `((relevance . ,score)))))))
1465 (> (port-line port) first-line) ;print at least one result
1466 (> (+ 4 (line-count text) (port-line port))
1468 (unless (null? rest)
1469 (display-hint (format #f (G_ "Run @code{~a ... | less} \
1470 to view all the results.")
1479 (define (string->generations str)
1480 "Return the list of generations matching a pattern in STR. This function
1481 accepts the following patterns: \"1\", \"1,2,3\", \"1..9\", \"1..\", \"..9\"."
1482 (define (maybe-integer)
1483 (let ((x (string->number str)))
1487 (define (maybe-comma-separated-integers)
1488 (let ((lst (delete-duplicates
1490 (string-split str #\,)))))
1491 (and (every integer? lst)
1494 (cond ((maybe-integer)
1497 ((maybe-comma-separated-integers)
1500 ((string-match "^([0-9]+)\\.\\.([0-9]+)$" str)
1503 (let ((s (string->number (match:substring match 1)))
1504 (e (string->number (match:substring match 2))))
1505 (and (every integer? (list s e))
1507 (iota (1+ (- e s)) s)))))
1508 ((string-match "^([0-9]+)\\.\\.$" str)
1511 (let ((s (string->number (match:substring match 1))))
1514 ((string-match "^\\.\\.([0-9]+)$" str)
1517 (let ((e (string->number (match:substring match 1))))
1522 (define (string->duration str)
1523 "Return the duration matching a pattern in STR. This function accepts the
1524 following patterns: \"1d\", \"1w\", \"1m\"."
1525 (define (hours->duration hours match)
1526 (make-time time-duration 0
1527 (* 3600 hours (string->number (match:substring match 1)))))
1529 (cond ((string-match "^([0-9]+)s$" str)
1532 (make-time time-duration 0
1533 (string->number (match:substring match 1)))))
1534 ((string-match "^([0-9]+)h$" str)
1537 (hours->duration 1 match)))
1538 ((string-match "^([0-9]+)d$" str)
1541 (hours->duration 24 match)))
1542 ((string-match "^([0-9]+)w$" str)
1545 (hours->duration (* 24 7) match)))
1546 ((string-match "^([0-9]+)m$" str)
1549 (hours->duration (* 24 30) match)))
1552 (define* (matching-generations str profile
1553 #:key (duration-relation <=))
1554 "Return the list of available generations matching a pattern in STR. See
1555 'string->generations' and 'string->duration' for the list of valid patterns.
1556 When STR is a duration pattern, return all the generations whose ctime has
1557 DURATION-RELATION with the current time."
1558 (define (valid-generations lst)
1559 (define (valid-generation? n)
1560 (any (cut = n <>) (generation-numbers profile)))
1562 (fold-right (lambda (x acc)
1563 (if (valid-generation? x)
1569 (define (filter-generations generations)
1573 (drop-while (cut > n <>)
1574 (generation-numbers profile)))
1576 (valid-generations (iota n 1)))
1578 (valid-generations lst))
1581 (define (filter-by-duration duration)
1582 (define (time-at-midnight time)
1583 ;; Return TIME at midnight by setting nanoseconds, seconds, minutes, and
1585 (let ((d (time-utc->date time)))
1588 (date-day d) (date-month d)
1589 (date-year d) (date-zone-offset d)))))
1591 (define generation-ctime-alist
1592 (map (lambda (number)
1596 (generation-time profile number)))))
1597 (generation-numbers profile)))
1602 (let ((s (time-second
1603 (subtract-duration (time-at-midnight (current-time))
1605 (delete #f (map (lambda (x)
1606 (and (duration-relation s (cdr x))
1608 generation-ctime-alist))))))
1610 (cond ((string->generations str)
1613 ((string->duration str)
1618 (condition (&message
1619 (message (format #f (G_ "invalid syntax: ~a~%")
1622 (define (display-generation profile number)
1623 "Display a one-line summary of generation NUMBER of PROFILE."
1624 (unless (zero? number)
1625 (let* ((file (generation-file-name profile number))
1626 (link (if (supports-hyperlinks?)
1627 (cut file-hyperlink file <>)
1629 (header (format #f (link (highlight (G_ "Generation ~a\t~a")))
1633 (generation-time profile number))
1634 ;; TRANSLATORS: This is a format-string for date->string.
1635 ;; Please choose a format that corresponds to the
1636 ;; usual way of presenting dates in your locale.
1637 ;; See https://www.gnu.org/software/guile/manual/html_node/SRFI_002d19-Date-to-string.html
1639 (G_ "~b ~d ~Y ~T"))))
1640 (current (generation-number profile)))
1641 (if (= number current)
1642 ;; TRANSLATORS: The word "current" here is an adjective for
1643 ;; "Generation", as in "current generation". Use the appropriate
1644 ;; gender where applicable.
1645 (format #t (G_ "~a\t(current)~%") header)
1646 (format #t "~a~%" header)))))
1648 (define (display-profile-content-diff profile gen1 gen2)
1649 "Display the changed packages in PROFILE GEN2 compared to generation GEN1."
1651 (define (equal-entry? first second)
1652 (string= (manifest-entry-item first) (manifest-entry-item second)))
1654 (define (display-entry entry prefix)
1656 (($ <manifest-entry> name version output location _)
1657 (format #t " ~a ~a\t~a\t~a\t~a~%" prefix name version output location))))
1659 (define (list-entries number)
1660 (manifest-entries (profile-manifest (generation-file-name profile number))))
1662 (define (display-diff profile old new)
1663 (display-generation profile new)
1664 (let ((added (lset-difference
1665 equal-entry? (list-entries new) (list-entries old)))
1666 (removed (lset-difference
1667 equal-entry? (list-entries old) (list-entries new))))
1668 (for-each (cut display-entry <> "+") added)
1669 (for-each (cut display-entry <> "-") removed)
1672 (display-diff profile gen1 gen2))
1674 (define (profile-lock-handler profile errno . _)
1675 "Handle failure to acquire PROFILE's lock."
1676 ;; NFS mounts can return ENOLCK. When that happens, there's not much that
1677 ;; can be done, so warn the user and keep going.
1678 (if (= errno ENOLCK)
1679 (warning (G_ "cannot lock profile ~a: ~a~%")
1680 profile (strerror errno))
1681 (leave (G_ "profile ~a is locked by another process~%")
1684 (define profile-lock-file
1685 (cut string-append <> ".lock"))
1687 (define-syntax-rule (with-profile-lock profile exp ...)
1688 "Grab PROFILE's lock and evaluate EXP... Call 'leave' if the lock is
1690 (with-file-lock/no-wait (profile-lock-file profile)
1691 (cut profile-lock-handler profile <...>)
1694 (define (display-profile-content profile number)
1695 "Display the packages in PROFILE, generation NUMBER, in a human-readable
1697 (for-each (match-lambda
1698 (($ <manifest-entry> name version output location _)
1699 (format #t " ~a\t~a\t~a\t~a~%"
1700 name version output location)))
1702 ;; Show most recently installed packages last.
1705 (profile-manifest (generation-file-name profile number))))))
1707 (define (display-generation-change previous current)
1708 (format #t (G_ "switched from generation ~a to ~a~%") previous current))
1710 (define (roll-back* store profile)
1711 "Like 'roll-back', but display what is happening."
1714 (roll-back store profile))
1715 display-generation-change))
1717 (define (switch-to-generation* profile number)
1718 "Like 'switch-generation', but display what is happening."
1719 (let ((previous (switch-to-generation profile number)))
1720 (display-generation-change previous number)))
1722 (define (delete-generation* store profile generation)
1723 "Like 'delete-generation', but display what is going on."
1724 (format #t (G_ "deleting ~a~%")
1725 (generation-file-name profile generation))
1726 (delete-generation store profile generation))
1728 (define* (package-specification->name+version+output spec
1729 #:optional (output "out"))
1730 "Parse package specification SPEC and return three value: the specified
1731 package name, version number (or #f), and output name (or OUTPUT). SPEC may
1732 optionally contain a version number and an output name, as in these examples:
1739 (let*-values (((name sub-drv)
1740 (match (string-rindex spec #\:)
1741 (#f (values spec output))
1742 (colon (values (substring spec 0 colon)
1743 (substring spec (+ 1 colon))))))
1745 (package-name->name+version name)))
1746 (values name version sub-drv)))
1750 ;;; Command-line option processing.
1753 (define (show-guix-usage)
1754 (format (current-error-port)
1755 (G_ "Try `guix --help' for more information.~%"))
1758 (define (command-files)
1759 "Return the list of source files that define Guix sub-commands."
1761 (and=> (search-path %load-path "guix.scm")
1762 (compose (cut string-append <> "/guix/scripts")
1766 (cut string-suffix? ".scm" <>))
1769 (scandir directory dot-scm?)
1773 "Return the list of Guix command names."
1774 (map (compose (cut string-drop-right <> 4)
1778 (define (show-guix-help)
1779 (define (internal? command)
1780 (member command '("substitute" "authenticate" "offload"
1781 "perform-download")))
1783 (format #t (G_ "Usage: guix COMMAND ARGS...
1784 Run COMMAND with ARGS.\n"))
1786 (format #t (G_ "COMMAND must be one of the sub-commands listed below:\n"))
1788 ;; TODO: Display a synopsis of each command.
1789 (format #t "~{ ~a~%~}" (sort (remove internal? (commands))
1791 (show-bug-report-information))
1793 (define (run-guix-command command . args)
1794 "Run COMMAND with the given ARGS. Report an error when COMMAND is not
1799 (resolve-interface `(guix scripts ,command)))
1801 (format (current-error-port)
1802 (G_ "guix: ~a: command not found~%") command)
1803 (show-guix-usage))))
1805 (let ((command-main (module-ref module
1806 (symbol-append 'guix- command))))
1807 (parameterize ((program-name command))
1808 ;; Disable canonicalization so we don't don't stat unreasonably.
1809 (with-fluids ((%file-port-name-canonicalization #f))
1813 (apply command-main args))
1815 ;; Abuse 'exit-hook' (which is normally meant to be used by the
1816 ;; REPL) to run things like profiling hooks upon completion.
1817 (run-hook exit-hook)))))))
1819 (define (run-guix . args)
1820 "Run the 'guix' command defined by command line ARGS.
1821 Unlike 'guix-main', this procedure assumes that locale, i18n support,
1822 and signal handling has already been set up."
1823 (define option? (cut string-prefix? "-" <>))
1825 ;; The default %LOAD-EXTENSIONS includes the empty string, which doubles the
1826 ;; number of 'stat' calls per entry in %LOAD-PATH. Shamelessly remove it.
1827 (set! %load-extensions '(".scm"))
1831 (format (current-error-port)
1832 (G_ "guix: missing command name~%"))
1834 ((or ("-h") ("--help"))
1836 ((or ("-V") ("--version"))
1837 (show-version-and-exit "guix"))
1838 (((? option? o) args ...)
1839 (format (current-error-port)
1840 (G_ "guix: unrecognized option '~a'~%") o)
1843 (apply run-guix-command (string->symbol command)
1848 (apply run-guix-command
1849 (string->symbol command)
1852 (define (guix-main arg0 . args)
1854 (apply run-guix args))
1856 ;;; ui.scm ends here