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
99 show-manifest-transaction
100 call-with-error-handling
102 with-unbound-variable-handling
105 read/eval-package-expression
106 check-available-space
111 package-description-string
112 package-synopsis-string
115 package-specification->name+version+output
124 display-search-results
131 display-profile-content
132 display-profile-content-diff
134 switch-to-generation*
137 %default-message-language
138 current-message-language
146 ;;; User interface facilities for command-line tools.
150 (define (print-unbound-variable-error port key args default-printer)
151 ;; Print unbound variable errors more nicely, and in the right language.
153 ((proc message (variable) _ ...)
154 ;; We can always omit PROC because when it's useful (i.e., different from
155 ;; "module-lookup"), it gets displayed before.
156 (format port (G_ "error: ~a: unbound variable") variable))
160 (set-exception-printer! 'unbound-variable print-unbound-variable-error)
162 (define (make-user-module modules)
163 "Return a new user module with the additional MODULES loaded."
164 ;; Module in which the machine description file is loaded.
165 (let ((module (make-fresh-user-module)))
166 (for-each (lambda (iface)
167 (module-use! module (resolve-interface iface)))
171 (define (last-frame-with-source stack)
172 "Walk stack upwards and return the last frame that has source location
173 information, or #f if it could not be found."
174 (define (frame-with-source frame)
175 ;; Walk from FRAME upwards until source location information is found.
176 (let loop ((frame frame)
181 ;; On Guile 3, the latest frame with source may be that of
182 ;; 'raise-exception' in boot-9.scm. Skip it.
183 (if (and (frame-source frame)
184 (not (eq? 'raise-exception (frame-procedure-name frame))))
186 (loop (frame-previous frame) frame)))))
188 (let* ((depth (stack-length stack))
189 (last (and (> depth 0) (stack-ref stack 0))))
190 (frame-with-source (if (> depth 1)
191 (stack-ref stack 1) ;skip the 'throw' frame
194 (define* (load* file user-module
195 #:key (on-error 'nothing-special))
196 "Load the user provided Scheme source code FILE."
197 (define (error-string frame args)
198 (call-with-output-string
200 (apply display-error frame port (cdr args)))))
203 (make-prompt-tag "user-code"))
207 ;; XXX: Force a recompilation to avoid ABI issues.
209 ;; In 2.2.3, the bogus answer to <https://bugs.gnu.org/29226> was to
210 ;; ignore all available .go, not just those from ~/.cache, which in turn
211 ;; meant that we had to rebuild *everything*. Since this is too costly,
212 ;; we have to turn off '%fresh-auto-compile' with that version, so to
213 ;; avoid ABI breakage in the user's config file, we explicitly compile
214 ;; it (the problem remains if the user's config is spread on several
215 ;; modules.) See <https://bugs.gnu.org/29881>.
216 (unless (string=? (version) "2.2.3")
217 (set! %fresh-auto-compile #t))
219 (set! %load-should-auto-compile #t)
221 (save-module-excursion
223 (set-current-module user-module)
225 ;; Hide the "auto-compiling" messages.
226 (parameterize ((current-warning-port (%make-void-port "w")))
227 (call-with-prompt tag
229 (when (string=? (version) "2.2.3")
232 (compile-file file #:env user-module))
233 (const #f))) ;EACCES maybe, let's interpret it
235 ;; Give 'load' an absolute file name so that it doesn't try to
236 ;; search for FILE in %LOAD-PATH. Note: use 'load', not
237 ;; 'primitive-load', so that FILE is compiled, which then allows us
238 ;; to provide better error reporting with source line numbers.
239 (load (canonicalize-path file)))
242 ;; XXX: Errors are reported from the pre-unwind handler below, but
243 ;; calling 'exit' from there has no effect, so we call it here.
245 (rec (handle-error . args)
246 ;; Capture the stack up to this procedure call, excluded, and pass
247 ;; the faulty stack frame to 'report-load-error'.
248 (let* ((stack (make-stack #t handle-error tag))
249 (frame (last-frame-with-source stack)))
251 (report-load-error file args frame)
256 (display (G_ "entering debugger; type ',bt' for a backtrace\n"))
257 (start-repl #:debug (make-debug (stack->vector stack) 0
258 (error-string frame args)
261 (newline (current-error-port))
262 (display-backtrace stack (current-error-port)))
266 (define (known-variable-definition variable)
267 "Search among the currently loaded modules one that defines a variable named
268 VARIABLE and return it, or #f if none was found."
269 (define (module<? m1 m2)
270 (match (module-name m2)
273 (match (module-name m1)
278 (let loop ((modules (list (resolve-module '() #f #f #:ensure #f)))
283 ;; Pick the "best" suggestion.
284 (match (sort suggestions module<?)
286 ((first _ ...) first)))
288 (if (set-contains? visited head)
289 (loop tail suggestions visited)
290 (let ((visited (set-insert head visited))
292 (hash-map->list (lambda (name module)
294 (module-submodules head)))))
295 (match (module-local-variable head variable)
296 (#f (loop next suggestions visited))
298 (match (module-name head)
299 (('gnu _ ...) head) ;must be that one
300 (_ (loop next (cons head suggestions) visited)))))))))))
302 (define %hint-color (color BOLD CYAN))
304 (define* (display-hint message #:optional (port (current-error-port)))
305 "Display MESSAGE, a l10n message possibly containing Texinfo markup, to
308 (if (color-output? port)
310 (colorize-string str %hint-color))
313 (display (colorize (G_ "hint: ")) port)
315 ;; XXX: We should arrange so that the initial indent is wider.
316 (parameterize ((%text-width (max 15 (- (terminal-columns) 5))))
317 (texi->plain-text message))
320 (define* (report-unbound-variable-error args #:key frame)
321 "Return the given unbound-variable error, where ARGS is the list of 'throw'
325 (print-exception (current-error-port) frame key args)))
327 (('unbound-variable proc message (variable) _ ...)
328 (match (known-variable-definition variable)
330 (display-hint (G_ "Did you forget a @code{use-modules} form?")))
332 (display-hint (format #f (G_ "Did you forget @code{(use-modules ~a)}?")
333 (module-name module))))))))
335 (define (check-module-matches-file module file)
336 "Check whether FILE starts with 'define-module MODULE' and print a hint if
338 ;; This is a common mistake when people start writing their own package
339 ;; definitions and try loading them with 'guix build -L …', so help them
340 ;; diagnose the problem.
342 (display-hint (format #f (G_ "File @file{~a} should probably start with:
344 @example\n(define-module ~a)\n@end example")
349 (let* ((sexp (call-with-input-file file read))
350 (loc (and (pair? sexp)
351 (source-properties->location (source-properties sexp)))))
353 (('define-module (names ...) _ ...)
354 (unless (equal? module names)
356 (G_ "module name ~a does not match file name '~a'~%")
357 names (module->source-file-name module))
360 (warning (G_ "~a: file is empty~%") file))
365 (define* (report-load-error file args #:optional frame)
366 "Report the failure to load FILE, a user-provided Scheme file.
367 ARGS is the list of arguments received by the 'throw' handler."
369 (('system-error . rest)
370 (let ((err (system-error-errno args)))
371 (report-error (G_ "failed to load '~a': ~a~%") file (strerror err))))
372 (('read-error "scm_i_lreadparen" message _ ...)
373 ;; Guile's missing-paren messages are obscure so we make them more
374 ;; intelligible here.
375 (if (string-suffix? "end of file" message)
376 (let ((location (string-drop-right message
377 (string-length "end of file"))))
378 (format (current-error-port) (G_ "~amissing closing parenthesis~%")
381 (('syntax-error proc message properties form subform . rest)
382 (let ((loc (source-properties->location properties)))
383 (report-error loc (G_ "~s: ~a~%")
384 (or subform form) message)))
385 (('unbound-variable _ ...)
386 (report-unbound-variable-error args #:frame frame))
387 (((or 'srfi-34 '%exception) obj)
388 (if (message-condition? obj)
389 (report-error (and (error-location? obj)
390 (error-location obj))
392 (gettext (condition-message obj) %gettext-domain))
393 (report-error (G_ "exception thrown: ~s~%") obj))
394 (when (fix-hint? obj)
395 (display-hint (condition-fix-hint obj))))
397 (report-error (G_ "failed to load '~a':~%") file)
399 (((? symbol? proc) (? string? message) (args ...) . rest)
400 (display-error frame (current-error-port) proc message
403 ;; Some exceptions like 'git-error' do not follow Guile's convention
404 ;; above and need to be printed with 'print-exception'.
405 (print-exception (current-error-port) frame key args))))))
407 (define (warn-about-load-error file module args) ;FIXME: factorize with ↑
408 "Report the failure to load FILE, a user-provided Scheme file, without
409 exiting. ARGS is the list of arguments received by the 'throw' handler."
411 (('system-error . rest)
412 (let ((err (system-error-errno args)))
413 (warning (G_ "failed to load '~a': ~a~%") module (strerror err))))
414 (('syntax-error proc message properties form . rest)
415 (let ((loc (source-properties->location properties)))
416 (warning loc (G_ "~a~%") message)))
417 (('unbound-variable _ ...)
418 (report-unbound-variable-error args))
419 (((or 'srfi-34 '%exception) obj)
420 (if (message-condition? obj)
421 (warning (G_ "failed to load '~a': ~a~%")
423 (gettext (condition-message obj) %gettext-domain))
424 (warning (G_ "failed to load '~a': exception thrown: ~s~%")
427 (warning (G_ "failed to load '~a':~%") module)
428 (apply display-error #f (current-error-port) args)
429 (check-module-matches-file module file))))
431 (define (call-with-unbound-variable-handling thunk)
433 (make-prompt-tag "user-code"))
435 (catch 'unbound-variable
437 (call-with-prompt tag
441 (rec (handle-error . args)
442 (let* ((stack (make-stack #t handle-error tag))
443 (frame (and stack (last-frame-with-source stack))))
444 (report-unbound-variable-error args #:frame frame)
447 (define-syntax-rule (with-unbound-variable-handling exp ...)
448 "Capture 'unbound-variable' exceptions in the dynamic extent of EXP... and
449 report them in a user-friendly way."
450 (call-with-unbound-variable-handling (lambda () exp ...)))
452 (define %default-message-language
453 ;; Default language to use for messages.
454 (make-parameter "en"))
456 (define (current-message-language)
457 "Return the language used for messages according to the current locale.
458 Return %DEFAULT-MESSAGE-LANGUAGE if that information could not be obtained. The
459 result is an ISO-639-2 language code such as \"ar\", without the territory
461 (let ((locale (setlocale LC_MESSAGES)))
462 (match (string-index locale #\_)
464 (index (string-take locale index)))))
466 (define (install-locale)
467 "Install the current locale settings."
470 (setlocale LC_ALL ""))
472 (display-hint (G_ "Consider installing the @code{glibc-utf8-locales} or
473 @code{glibc-locales} package and defining @code{GUIX_LOCPATH}, along these
477 guix package -i glibc-utf8-locales
478 export GUIX_LOCPATH=\"$HOME/.guix-profile/lib/locale\"
481 See the \"Application Setup\" section in the manual, for more info.\n")))))
483 (define (initialize-guix)
484 "Perform the usual initialization for stand-alone Guix commands."
485 ;; By default don't annoy users with deprecation warnings. In practice,
486 ;; 'define-deprecated' in (ice-9 deprecated) arranges so that those warnings
487 ;; are emitted at expansion-time only, but there are cases where they could
488 ;; slip through, for instance when interpreting code.
489 (unless (getenv "GUILE_WARN_DEPRECATED")
490 (debug-disable 'warn-deprecated))
493 (textdomain %gettext-domain)
495 ;; Ignore SIGPIPE. If the daemon closes the connection, we prefer to be
496 ;; notified via an EPIPE later.
497 (sigaction SIGPIPE SIG_IGN)
499 (setvbuf (current-output-port) 'line)
500 (setvbuf (current-error-port) 'line))
502 (define* (show-version-and-exit #:optional (command (car (command-line))))
503 "Display version information for COMMAND and `(exit 0)'."
504 (simple-format #t "~a (~a) ~a~%"
505 command %guix-package-name %guix-version)
506 (format #t "Copyright ~a 2020 ~a"
507 ;; TRANSLATORS: Translate "(C)" to the copyright symbol
508 ;; (C-in-a-circle), if this symbol is available in the user's
509 ;; locale. Otherwise, do not translate "(C)"; leave it as-is. */
511 (G_ "the Guix authors\n"))
513 License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
514 This is free software: you are free to change and redistribute it.
515 There is NO WARRANTY, to the extent permitted by law.
519 (define (show-bug-report-information)
520 ;; TRANSLATORS: The placeholder indicates the bug-reporting address for this
521 ;; package. Please add another line saying "Report translation bugs to
522 ;; ...\n" with the address for translation bugs (typically your translation
523 ;; team's web or email address).
525 Report bugs to: ~a.") %guix-bug-report-address)
527 ~a home page: <~a>") %guix-package-name %guix-home-page-url)
529 General help using GNU software: <http://www.gnu.org/gethelp/>"))
532 (define (augmented-system-error-handler file)
533 "Return a 'system-error' handler that mentions FILE in its message."
534 (lambda (key proc fmt args errno)
535 ;; Augment the FMT and ARGS with information about TARGET (this
536 ;; information is missing as of Guile 2.0.11, making the exception
538 (apply throw key proc "~A: ~S"
539 (list (strerror (car errno)) file)
542 (define-syntax apply-formals
544 ((_ proc (args ...)) (proc args ...))
545 ((_ proc (arg1 args ... . rest)) (apply proc arg1 args ... rest))))
547 (define-syntax-rule (error-reporting-wrapper proc formals file)
548 "Wrap PROC such that its 'system-error' exceptions are augmented to mention
550 (let ((real-proc (@ (guile) proc)))
554 (apply-formals real-proc formals))
555 (augmented-system-error-handler file)))))
558 ;; We 'set!' the global binding because (gnu build ...) modules and similar
559 ;; typically don't use (guix ui).
560 (error-reporting-wrapper symlink (source target) target))
563 ;; Note: here we use 'set!', not #:replace, because UIs typically use
564 ;; 'copy-recursively', which doesn't use (guix ui).
565 (error-reporting-wrapper copy-file (source target) target))
567 (set! canonicalize-path
568 (error-reporting-wrapper canonicalize-path (file) file))
571 (error-reporting-wrapper delete-file (file) file))
574 (error-reporting-wrapper execlp (filename . args) filename))
576 (define (make-regexp* regexp . flags)
577 "Like 'make-regexp' but error out if REGEXP is invalid, reporting the error
579 (catch 'regular-expression-syntax
581 (apply make-regexp regexp flags))
582 (lambda (key proc message . rest)
583 (leave (G_ "'~a' is not a valid regular expression: ~a~%")
586 (define (string->number* str)
587 "Like `string->number', but error out with an error message on failure."
588 (or (string->number str)
589 (leave (G_ "~a: invalid number~%") str)))
591 (define (size->number str)
592 "Convert STR, a storage measurement representation such as \"1024\" or
593 \"1MiB\", to a number of bytes. Raise an error if STR could not be
597 (char-set-union (char-set #\.) char-set:digit)))
600 (and unit-pos (substring str (+ 1 unit-pos))))
602 (let* ((numstr (if unit-pos
603 (substring str 0 (+ 1 unit-pos))
605 (num (string->number numstr)))
607 (leave (G_ "invalid number: ~a~%") numstr))
609 ((compose inexact->exact round)
612 ((or "KiB" "K" "k") (expt 2 10))
613 ((or "MiB" "M") (expt 2 20))
614 ((or "GiB" "G") (expt 2 30))
615 ((or "TiB" "T") (expt 2 40))
616 ((or "PiB" "P") (expt 2 50))
617 ((or "EiB" "E") (expt 2 60))
618 ((or "ZiB" "Z") (expt 2 70))
619 ((or "YiB" "Y") (expt 2 80))
630 (leave (G_ "unknown unit: ~a~%") unit)))))))
632 (define (display-collision-resolution-hint collision)
633 "Display hints on how to resolve COLLISION, a &profile-collistion-error."
634 (define (top-most-entry entry)
635 (let loop ((entry entry))
636 (match (force (manifest-entry-parent entry))
638 (parent (loop parent)))))
640 (let* ((first (profile-collision-error-entry collision))
641 (second (profile-collision-error-conflict collision))
642 (name1 (manifest-entry-name (top-most-entry first)))
643 (name2 (manifest-entry-name (top-most-entry second))))
644 (if (string=? name1 name2)
645 (display-hint (format #f (G_ "You cannot have two different versions
646 or variants of @code{~a} in the same profile.")
648 (display-hint (format #f (G_ "Try upgrading both @code{~a} and @code{~a},
649 or remove one of them from the profile.")
652 (define (call-with-error-handling thunk)
653 "Call THUNK within a user-friendly error handler."
654 (define (port-filename* port)
655 ;; 'port-filename' returns #f for non-file ports, but it raises an
656 ;; exception for file ports that are closed. Work around that.
657 (and (not (port-closed? port))
658 (port-filename port)))
660 (guard (c ((package-input-error? c)
661 (let* ((package (package-error-package c))
662 (input (package-error-invalid-input c))
663 (location (package-location package))
664 (file (location-file location))
665 (line (location-line location))
666 (column (location-column location)))
667 (leave (G_ "~a:~a:~a: package `~a' has an invalid input: ~s~%")
669 (package-full-name package) input)))
670 ((package-cross-build-system-error? c)
671 (let* ((package (package-error-package c))
672 (loc (package-location package))
673 (system (package-build-system package)))
674 (leave (G_ "~a: ~a: build system `~a' does not support cross builds~%")
675 (location->string loc)
676 (package-full-name package)
677 (build-system-name system))))
678 ((gexp-input-error? c)
679 (let ((input (package-error-invalid-input c)))
680 (leave (G_ "~s: invalid G-expression input~%")
681 (gexp-error-invalid-input c))))
682 ((profile-not-found-error? c)
683 (leave (G_ "profile '~a' does not exist~%")
684 (profile-error-profile c)))
685 ((missing-generation-error? c)
686 (leave (G_ "generation ~a of profile '~a' does not exist~%")
687 (missing-generation-error-generation c)
688 (profile-error-profile c)))
689 ((unmatched-pattern-error? c)
690 (let ((pattern (unmatched-pattern-error-pattern c)))
691 (leave (G_ "package '~a~@[@~a~]~@[:~a~]' not found in profile~%")
692 (manifest-pattern-name pattern)
693 (manifest-pattern-version pattern)
694 (match (manifest-pattern-output pattern)
697 ((profile-collision-error? c)
698 (let ((entry (profile-collision-error-entry c))
699 (conflict (profile-collision-error-conflict c)))
700 (define (report-parent-entries entry)
701 (let ((parent (force (manifest-entry-parent entry))))
702 (when (manifest-entry? parent)
703 (report-error (G_ " ... propagated from ~a@~a~%")
704 (manifest-entry-name parent)
705 (manifest-entry-version parent))
706 (report-parent-entries parent))))
708 (define (manifest-entry-output* entry)
709 (match (manifest-entry-output entry)
711 (output (string-append ":" output))))
713 (report-error (G_ "profile contains conflicting entries for ~a~a~%")
714 (manifest-entry-name entry)
715 (manifest-entry-output* entry))
716 (report-error (G_ " first entry: ~a@~a~a ~a~%")
717 (manifest-entry-name entry)
718 (manifest-entry-version entry)
719 (manifest-entry-output* entry)
720 (manifest-entry-item entry))
721 (report-parent-entries entry)
722 (report-error (G_ " second entry: ~a@~a~a ~a~%")
723 (manifest-entry-name conflict)
724 (manifest-entry-version conflict)
725 (manifest-entry-output* conflict)
726 (manifest-entry-item conflict))
727 (report-parent-entries conflict)
728 (display-collision-resolution-hint c)
731 (let ((file (nar-error-file c))
732 (port (nar-error-port c)))
734 (leave (G_ "corrupt input while restoring '~a' from ~s~%")
735 file (or (port-filename* port) port))
736 (leave (G_ "corrupt input while restoring archive from ~s~%")
737 (or (port-filename* port) port)))))
738 ((store-connection-error? c)
739 (leave (G_ "failed to connect to `~a': ~a~%")
740 (store-connection-error-file c)
741 (strerror (store-connection-error-code c))))
742 ((store-protocol-error? c)
743 ;; FIXME: Server-provided error messages aren't i18n'd.
745 (store-protocol-error-message c)))
746 ((derivation-missing-output-error? c)
747 (leave (G_ "reference to invalid output '~a' of derivation '~a'~%")
748 (derivation-missing-output c)
749 (derivation-file-name (derivation-error-derivation c))))
750 ((file-search-error? c)
751 (leave (G_ "file '~a' could not be found in these \
752 directories:~{ ~a~}~%")
753 (file-search-error-file-name c)
754 (file-search-error-search-path c)))
756 (leave (G_ "program exited\
757 ~@[ with non-zero exit status ~a~]\
758 ~@[ terminated by signal ~a~]\
759 ~@[ stopped by signal ~a~]: ~s~%")
760 (invoke-error-exit-status c)
761 (invoke-error-term-signal c)
762 (invoke-error-stop-signal c)
763 (cons (invoke-error-program c)
764 (invoke-error-arguments c))))
765 ((and (error-location? c) (message-condition? c))
766 (report-error (error-location c) (G_ "~a~%")
767 (gettext (condition-message c) %gettext-domain))
769 (display-hint (condition-fix-hint c)))
771 ((and (message-condition? c) (fix-hint? c))
772 (report-error (G_ "~a~%")
773 (gettext (condition-message c) %gettext-domain))
774 (display-hint (condition-fix-hint c))
777 ;; On Guile 3.0.0, exceptions such as 'unbound-variable' are
778 ;; compound and include a '&message'. However, that message only
779 ;; contains the format string. Thus, special-case it here to
780 ;; avoid displaying a bare format string.
783 ((exception-predicate &exception-with-kind-and-args) c))
787 ((message-condition? c)
788 ;; Normally '&message' error conditions have an i18n'd message.
790 (gettext (condition-message c) %gettext-domain))))
791 ;; Catch EPIPE and the likes.
794 (lambda (key proc format-string format-args . rest)
795 (leave (G_ "~a: ~a~%") proc
796 (apply format #f format-string format-args))))))
798 (define-syntax-rule (leave-on-EPIPE exp ...)
799 "Run EXP... in a context when EPIPE errors are caught and lead to 'exit'
800 with successful exit code. This is useful when writing to the standard output
801 may lead to EPIPE, because the standard output is piped through 'head' or
807 ;; We really have to exit this brutally, otherwise Guile eventually
808 ;; attempts to flush all the ports, leading to an uncaught EPIPE down
810 (if (= EPIPE (system-error-errno args))
812 (apply throw args)))))
814 (define %guix-user-module
815 ;; Module in which user expressions are evaluated.
816 ;; Compute lazily to avoid circularity with (guix gexp).
818 (let ((module (make-module)))
819 (beautify-user-module! module)
820 ;; Use (guix gexp) so that one can use #~ & co.
821 (module-use! module (resolve-interface '(guix gexp)))
824 (define (read/eval str)
825 "Read and evaluate STR, raising an error if something goes wrong."
828 (call-with-input-string str read))
830 (leave (G_ "failed to read expression ~s: ~s~%")
834 (eval exp (force %guix-user-module)))
836 (report-error (G_ "failed to evaluate expression '~a':~%") exp)
838 (('syntax-error proc message properties form . rest)
839 (report-error (G_ "syntax error: ~a~%") message))
840 (((or 'srfi-34 '%exception) obj)
841 (if (message-condition? obj)
842 (report-error (G_ "~a~%")
843 (gettext (condition-message obj)
845 (report-error (G_ "exception thrown: ~s~%") obj)))
847 (apply display-error #f (current-error-port) args))
851 (define (read/eval-package-expression str)
852 "Read and evaluate STR and return the package it refers to, or exit an
854 (match (read/eval str)
857 (leave (G_ "expression ~s does not evaluate to a package~%")
860 (define (show-derivation-outputs derivation)
861 "Show the output file names of DERIVATION, which can be a derivation or a
863 (define (show-outputs derivation outputs)
864 (format #t "~{~a~%~}"
865 (map (cut derivation->output-path derivation <>)
870 (show-outputs derivation (derivation-output-names derivation)))
871 ((? derivation-input? input)
872 (show-outputs (derivation-input-derivation input)
873 (derivation-input-sub-derivations input)))))
875 (define* (check-available-space need
876 #:optional (directory (%store-prefix)))
877 "Make sure at least NEED bytes are available in DIRECTORY. Otherwise emit a
879 (let ((free (catch 'system-error
881 (free-disk-space directory))
883 (when (and free (>= need free))
884 (warning (G_ "at least ~,1h MB needed but only ~,1h MB available in ~a~%")
885 (/ need 1e6) (/ free 1e6) directory))))
887 (define (graft-derivation? drv)
888 "Return true if DRV is definitely a graft derivation, false otherwise."
889 (match (assq-ref (derivation-properties drv) 'type)
893 (define (profile-hook-derivation? drv)
894 "Return true if DRV is definitely a profile hook derivation, false otherwise."
895 (match (assq-ref (derivation-properties drv) 'type)
899 (define (colorize-store-file-name file)
900 "Colorize FILE, a store file name, such that the hash part is less prominent
902 (let ((len (string-length file))
903 (prefix (+ (string-length (%store-prefix)) 32 2)))
906 (string-append (colorize-string (string-take file prefix)
908 (string-drop file prefix)))))
910 (define* (show-what-to-build store drv
911 #:key dry-run? (use-substitutes? #t)
912 (mode (build-mode normal)))
913 "Show what will or would (depending on DRY-RUN?) be built in realizing the
914 derivations listed in DRV using MODE, a 'build-mode' value. The elements of
915 DRV can be either derivations or derivation inputs.
917 Return two values: a Boolean indicating whether there's something to build,
918 and a Boolean indicating whether there's something to download. When
919 USE-SUBSTITUTES?, check and report what is prerequisites are available for
923 ((? derivation? drv) (derivation-input drv))
924 ((? derivation-input? input) input))
927 (define substitutable-info
928 ;; Call 'substitutation-oracle' upfront so we don't end up launching the
929 ;; substituter many times. This makes a big difference, especially when
930 ;; DRV is a long list as is the case with 'guix environment'.
932 (substitution-oracle store inputs #:mode mode)
935 (define colorized-store-item
936 (if (color-output? (current-error-port))
937 colorize-store-file-name
940 (let*-values (((build/full download)
941 (derivation-build-plan store inputs
946 (match (fold (lambda (drv acc)
947 (let ((file (derivation-file-name drv)))
949 ((#:graft graft #:hook hook #:build build)
951 ((graft-derivation? drv)
952 `(#:graft ,(cons file graft)
955 ((profile-hook-derivation? drv)
957 #:hook ,(cons file hook)
962 #:build ,(cons file build))))))))
963 '(#:graft () #:hook () #:build ())
965 ((#:graft graft #:hook hook #:build build)
966 (values graft hook build)))))
967 (define installed-size
968 (reduce + 0 (map substitutable-nar-size download)))
970 (define download-size
971 (/ (reduce + 0 (map substitutable-download-size download))
974 (define display-download-size?
975 ;; Sometimes narinfos lack information about the download size. Only
976 ;; display when we have information for all of DOWNLOAD.
977 (not (any (compose zero? substitutable-download-size) download)))
981 (format (current-error-port)
982 (N_ "~:[The following derivation would be built:~%~{ ~a~%~}~;~]"
983 "~:[The following derivations would be built:~%~{ ~a~%~}~;~]"
985 (null? build) (map colorized-store-item build))
986 (if display-download-size?
987 (format (current-error-port)
988 ;; TRANSLATORS: "MB" is for "megabyte"; it should be
989 ;; translated to the corresponding abbreviation.
990 (G_ "~:[~,1h MB would be downloaded:~%~{ ~a~%~}~;~]")
993 (map (compose colorized-store-item substitutable-path)
995 (format (current-error-port)
996 (N_ "~:[The following file would be downloaded:~%~{ ~a~%~}~;~]"
997 "~:[The following files would be downloaded:~%~{ ~a~%~}~;~]"
1000 (map (compose colorized-store-item substitutable-path)
1002 (format (current-error-port)
1003 (N_ "~:[The following graft would be made:~%~{ ~a~%~}~;~]"
1004 "~:[The following grafts would be made:~%~{ ~a~%~}~;~]"
1006 (null? graft) (map colorized-store-item graft))
1007 (format (current-error-port)
1008 (N_ "~:[The following profile hook would be built:~%~{ ~a~%~}~;~]"
1009 "~:[The following profile hooks would be built:~%~{ ~a~%~}~;~]"
1011 (null? hook) (map colorized-store-item hook)))
1013 (format (current-error-port)
1014 (N_ "~:[The following derivation will be built:~%~{ ~a~%~}~;~]"
1015 "~:[The following derivations will be built:~%~{ ~a~%~}~;~]"
1017 (null? build) (map colorized-store-item build))
1018 (if display-download-size?
1019 (format (current-error-port)
1020 ;; TRANSLATORS: "MB" is for "megabyte"; it should be
1021 ;; translated to the corresponding abbreviation.
1022 (G_ "~:[~,1h MB will be downloaded:~%~{ ~a~%~}~;~]")
1025 (map (compose colorized-store-item substitutable-path)
1027 (format (current-error-port)
1028 (N_ "~:[The following file will be downloaded:~%~{ ~a~%~}~;~]"
1029 "~:[The following files will be downloaded:~%~{ ~a~%~}~;~]"
1032 (map (compose colorized-store-item substitutable-path)
1034 (format (current-error-port)
1035 (N_ "~:[The following graft will be made:~%~{ ~a~%~}~;~]"
1036 "~:[The following grafts will be made:~%~{ ~a~%~}~;~]"
1038 (null? graft) (map colorized-store-item graft))
1039 (format (current-error-port)
1040 (N_ "~:[The following profile hook will be built:~%~{ ~a~%~}~;~]"
1041 "~:[The following profile hooks will be built:~%~{ ~a~%~}~;~]"
1043 (null? hook) (map colorized-store-item hook))))
1045 (check-available-space installed-size)
1047 (values (pair? build/full) (pair? download))))
1049 (define show-what-to-build*
1050 (store-lift show-what-to-build))
1052 (define* (build-notifier #:key (dry-run? #f) (use-substitutes? #t))
1053 "Return a procedure suitable for 'with-build-handler' that, when
1054 'build-things' is called, invokes 'show-what-to-build' to display the build
1055 plan. When DRY-RUN? is true, the 'with-build-handler' form returns without
1056 any build happening."
1058 (char-set-complement (char-set #\,)))
1060 (define (read-derivation-from-file* item)
1061 (catch 'system-error
1063 (read-derivation-from-file item))
1066 (lambda (continue store things mode)
1068 ;; List of derivation inputs to build. Filter out non-existent '.drv'
1069 ;; files because the daemon transparently tries to substitute them.
1070 (filter-map (match-lambda
1071 (((? derivation-path? drv) . output)
1072 (let ((drv (read-derivation-from-file* drv))
1073 (outputs (string-tokenize output not-comma)))
1074 (and drv (derivation-input drv outputs))))
1075 ((? derivation-path? drv)
1076 (and=> (read-derivation-from-file* drv)
1082 (let-values (((build? download?)
1083 (show-what-to-build store inputs
1085 #:use-substitutes? use-substitutes?
1088 (unless (and (or build? download?)
1092 (define (right-arrow port)
1093 "Return either a string containing the 'RIGHT ARROW' character, or an ASCII
1094 replacement if PORT is not Unicode-capable."
1095 (let ((encoding (port-encoding port))
1097 (catch 'encoding-error
1099 (call-with-output-string
1101 (set-port-encoding! port encoding)
1102 (set-port-conversion-strategy! port 'error)
1103 (display arrow port))))
1104 (lambda (key . args)
1107 (define* (tabulate rows #:key (initial-indent 0) (max-width 25)
1109 "Return a list of strings where each string is a tabulated representation of
1110 an element of ROWS. All the ROWS must be lists of the same number of cells.
1112 Add INITIAL-INDENT white space at the beginning of each row. Ensure that
1113 columns are at most MAX-WIDTH characters wide. Use INTER-COLUMN as a
1114 separator between subsequent columns."
1115 (define column-widths
1116 ;; List of column widths.
1117 (let loop ((rows rows)
1122 (((column rest ...) ...)
1124 (cons (min (apply max (map string-length column))
1129 (make-string initial-indent #\space))
1131 (define (string-pad-right* str len)
1132 (if (> (string-length str) len)
1134 (string-pad-right str len)))
1138 (string-append indent
1140 (map string-pad-right* row column-widths)
1144 (define* (show-manifest-transaction store manifest transaction
1146 "Display what will/would be installed/removed from MANIFEST by TRANSACTION."
1147 (define (package-strings names versions outputs)
1148 (tabulate (zip (map (lambda (name output)
1149 (if (string=? output "out")
1151 (string-append name ":" output)))
1154 #:initial-indent 3))
1156 (define → ;an arrow that can be represented on stderr
1157 (right-arrow (current-error-port)))
1159 (define (upgrade-string names old-version new-version outputs)
1160 (tabulate (zip (map (lambda (name output)
1161 (if (string=? output "out")
1163 (string-append name ":" output)))
1165 (map (lambda (old new)
1166 (if (string=? old new)
1167 (G_ "(dependencies changed)")
1168 (string-append old " " → " " new)))
1169 old-version new-version))
1170 #:initial-indent 3))
1172 (let-values (((remove install upgrade downgrade)
1173 (manifest-transaction-effects manifest transaction)))
1175 ((($ <manifest-entry> name version output item) ..1)
1176 (let ((len (length name))
1177 (remove (package-strings name version output)))
1179 (format (current-error-port)
1180 (N_ "The following package would be removed:~%~{~a~%~}~%"
1181 "The following packages would be removed:~%~{~a~%~}~%"
1184 (format (current-error-port)
1185 (N_ "The following package will be removed:~%~{~a~%~}~%"
1186 "The following packages will be removed:~%~{~a~%~}~%"
1191 (((($ <manifest-entry> name old-version)
1192 . ($ <manifest-entry> _ new-version output item)) ..1)
1193 (let ((len (length name))
1194 (downgrade (upgrade-string name old-version new-version
1197 (format (current-error-port)
1198 (N_ "The following package would be downgraded:~%~{~a~%~}~%"
1199 "The following packages would be downgraded:~%~{~a~%~}~%"
1202 (format (current-error-port)
1203 (N_ "The following package will be downgraded:~%~{~a~%~}~%"
1204 "The following packages will be downgraded:~%~{~a~%~}~%"
1209 (((($ <manifest-entry> name old-version)
1210 . ($ <manifest-entry> _ new-version output item)) ..1)
1211 (let ((len (length name))
1212 (upgrade (upgrade-string name
1213 old-version new-version
1216 (format (current-error-port)
1217 (N_ "The following package would be upgraded:~%~{~a~%~}~%"
1218 "The following packages would be upgraded:~%~{~a~%~}~%"
1221 (format (current-error-port)
1222 (N_ "The following package will be upgraded:~%~{~a~%~}~%"
1223 "The following packages will be upgraded:~%~{~a~%~}~%"
1228 ((($ <manifest-entry> name version output item _) ..1)
1229 (let ((len (length name))
1230 (install (package-strings name version output)))
1232 (format (current-error-port)
1233 (N_ "The following package would be installed:~%~{~a~%~}~%"
1234 "The following packages would be installed:~%~{~a~%~}~%"
1237 (format (current-error-port)
1238 (N_ "The following package will be installed:~%~{~a~%~}~%"
1239 "The following packages will be installed:~%~{~a~%~}~%"
1244 (define-syntax with-error-handling
1246 "Run BODY within a user-friendly error condition handler."
1248 (call-with-error-handling
1252 (define* (indented-string str indent
1253 #:key (initial-indent? #t))
1254 "Return STR with each newline preceded by IDENT spaces. When
1255 INITIAL-INDENT? is true, the first line is also indented."
1256 (define indent-string
1257 (make-list indent #\space))
1260 (string-fold-right (lambda (chr result)
1261 (if (eqv? chr #\newline)
1262 (cons chr (append indent-string result))
1266 (string-append (list->string indent-string) str)
1269 (define* (fill-paragraph str width #:optional (column 0))
1270 "Fill STR such that each line contains at most WIDTH characters, assuming
1271 that the first character is at COLUMN.
1273 When STR contains a single line break surrounded by other characters, it is
1274 converted to a space; sequences of more than one line break are preserved."
1275 (define (maybe-break chr result)
1277 ((column newlines chars)
1280 `(,column ,(+ 1 newlines) ,chars))
1282 (let* ((spaces (if (and (pair? chars) (eqv? (car chars) #\.)) 2 1))
1283 (chars (case newlines
1286 (append (make-list spaces #\space) chars))
1288 (append (make-list newlines #\newline) chars))))
1289 (column (case newlines
1291 ((1) (+ spaces column))
1293 (let ((chars (cons chr chars))
1294 (column (+ 1 column)))
1295 (if (> column width)
1296 (let*-values (((before after)
1297 (break (cut eqv? #\space <>) chars))
1307 (drop-while (cut eqv? #\space <>)
1309 `(,column 0 ,chars))) ; unbreakable
1310 `(,column 0 ,chars)))))))))
1312 (match (string-fold maybe-break
1315 ((column newlines chars)
1316 (list->string (reverse chars)))))
1324 ;; '*line-width*' was introduced in Guile 2.2.7/3.0.1. On older versions of
1325 ;; Guile, monkey-patch 'wrap*' below.
1326 (if (defined? '*line-width*)
1327 (let ((parameter (fluid->parameter *line-width*)))
1328 (parameter (terminal-columns))
1330 (make-parameter (terminal-columns))))
1332 (unless (defined? '*line-width*) ;Guile < 2.2.7
1333 (set! (@@ (texinfo plain-text) wrap*)
1334 ;; XXX: Monkey patch this private procedure to let 'package->recutils'
1335 ;; parameterize the fill of description field correctly.
1337 (let ((indent (fluid-ref (@@ (texinfo plain-text) *indent*))))
1338 (fill-string (string-concatenate strings)
1339 #:line-width (%text-width) #:initial-indent indent
1340 #:subsequent-indent indent)))))
1342 (define (texi->plain-text str)
1343 "Return a plain-text representation of texinfo fragment STR."
1344 ;; 'texi-fragment->stexi' uses a string port so make sure it's a
1345 ;; Unicode-capable one (see <http://bugs.gnu.org/11197>.)
1346 (with-fluids ((%default-port-encoding "UTF-8"))
1347 (stexi->plain-text (texi-fragment->stexi str))))
1349 (define (package-field-string package field-accessor)
1350 "Return a plain-text representation of PACKAGE field."
1351 (and=> (field-accessor package)
1352 (compose texi->plain-text P_)))
1354 (define (package-description-string package)
1355 "Return a plain-text representation of PACKAGE description field."
1356 (package-field-string package package-description))
1358 (define (package-synopsis-string package)
1359 "Return a plain-text representation of PACKAGE synopsis field."
1360 (package-field-string package package-synopsis))
1362 (define (string->recutils str)
1363 "Return a version of STR where newlines have been replaced by newlines
1364 followed by \"+ \", which makes for a valid multi-line field value in the
1367 (string-fold-right (lambda (chr result)
1368 (if (eqv? chr #\newline)
1369 (cons* chr #\+ #\space result)
1374 (define (hyperlink uri text)
1375 "Return a string that denotes a hyperlink using an OSC escape sequence as
1377 <https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda>."
1378 (string-append "\x1b]8;;" uri "\x1b\\"
1379 text "\x1b]8;;\x1b\\"))
1381 (define* (supports-hyperlinks? #:optional (port (current-output-port)))
1382 "Return true if PORT is a terminal that supports hyperlink escapes."
1383 ;; Note that terminals are supposed to ignore OSC escapes they don't
1384 ;; understand (this is the case of xterm as of version 349, for instance.)
1385 ;; However, Emacs comint as of 26.3 does not ignore it and instead lets it
1386 ;; through, hence the 'INSIDE_EMACS' special case below.
1387 (and (isatty?* port)
1388 (not (getenv "INSIDE_EMACS"))))
1390 (define* (file-hyperlink file #:optional (text file))
1391 "Return TEXT with escapes for a hyperlink to FILE."
1392 (hyperlink (string-append "file://" (gethostname)
1393 (encode-and-join-uri-path
1394 (string-split file #\/)))
1397 (define (location->hyperlink location)
1398 "Return a string corresponding to LOCATION, with escapes for a hyperlink."
1399 (let ((str (location->string location))
1400 (file (if (string-prefix? "/" (location-file location))
1401 (location-file location)
1402 (search-path %load-path (location-file location)))))
1404 (file-hyperlink file str)
1407 (define* (package->recutils p port #:optional (width (%text-width))
1409 (hyperlinks? (supports-hyperlinks? port))
1411 "Write to PORT a `recutils' record of package P, arranging to fit within
1412 WIDTH columns. EXTRA-FIELDS is a list of symbol/value pairs to emit. When
1413 HYPERLINKS? is true, emit hyperlink escape sequences when appropriate."
1415 ;; The available number of columns once we've taken into account space for
1416 ;; the initial "+ " prefix.
1417 (if (> width 2) (- width 2) width))
1419 (define (dependencies->recutils packages)
1420 (let ((list (string-join (delete-duplicates
1421 (map package-full-name
1422 (sort packages package<?))) " ")))
1424 (fill-paragraph list width*
1425 (string-length "dependencies: ")))))
1427 (define (package<? p1 p2)
1428 (string<? (package-full-name p1) (package-full-name p2)))
1430 ;; Note: Don't i18n field names so that people can post-process it.
1431 (format port "name: ~a~%" (package-name p))
1432 (format port "version: ~a~%" (package-version p))
1433 (format port "outputs: ~a~%" (string-join (package-outputs p)))
1434 (format port "systems: ~a~%"
1435 (string-join (package-transitive-supported-systems p)))
1436 (format port "dependencies: ~a~%"
1437 (match (package-direct-inputs p)
1438 (((labels inputs . _) ...)
1439 (dependencies->recutils (filter package? inputs)))))
1440 (format port "location: ~a~%"
1441 (or (and=> (package-location p)
1442 (if hyperlinks? location->hyperlink location->string))
1445 ;; Note: Starting from version 1.6 or recutils, hyphens are not allowed in
1446 ;; field identifiers.
1447 (format port "homepage: ~a~%" (package-home-page p))
1449 (format port "license: ~a~%"
1450 (match (package-license p)
1451 (((? license? licenses) ...)
1452 (string-join (map license-name licenses)
1454 ((? license? license)
1455 (let ((text (license-name license))
1456 (uri (license-uri license)))
1457 (if (and hyperlinks? uri (string-prefix? "http" uri))
1458 (hyperlink uri text)
1462 (format port "synopsis: ~a~%"
1463 (string-map (match-lambda
1466 (or (and=> (package-synopsis-string p) P_)
1471 (parameterize ((%text-width width*))
1473 (string-append "description: "
1474 (or (and=> (package-description p) P_)
1477 (for-each (match-lambda
1479 (let ((field (symbol->string field)))
1480 (format port "~a: ~a~%"
1482 (fill-paragraph (object->string value) width*
1483 (string-length field))))))
1492 (define (relevance obj regexps metrics)
1493 "Compute a \"relevance score\" for OBJ as a function of its number of
1494 matches of REGEXPS and accordingly to METRICS. METRICS is list of
1495 field/weight pairs, where FIELD is a procedure that returns a string or list
1496 of strings describing OBJ, and WEIGHT is a positive integer denoting the
1497 weight of this field in the final score.
1499 A score of zero means that OBJ does not match any of REGEXPS. The higher the
1500 score, the more relevant OBJ is to REGEXPS."
1501 (define (score regexp str)
1502 (fold-matches regexp str 0
1505 (if (string=? (match:substring m) str)
1509 (define (regexp->score regexp)
1510 (let ((score-regexp (lambda (str) (score regexp str))))
1511 (fold (lambda (metric relevance)
1517 (+ relevance (* (score-regexp str) weight)))
1519 (+ relevance (* weight (apply + (map score-regexp lst)))))))))
1522 (let ((scores (map regexp->score regexps)))
1523 ;; Return zero if one of REGEXPS doesn't match.
1524 (if (any zero? scores)
1526 (reduce + 0 scores))))
1528 (define %package-metrics
1529 ;; Metrics used to compute the "relevance score" of a package against a set
1531 `((,package-name . 4)
1533 ;; Match against uncommon outputs.
1535 (filter (lambda (output)
1537 ;; Some common outpus shared by many packages.
1538 '("out" "doc" "debug" "lib" "include" "bin"))))
1539 (package-outputs package)))
1542 ;; Match regexps on the raw Texinfo since formatting it is quite expensive
1543 ;; and doesn't have much of an effect on search results.
1545 (and=> (package-synopsis package) P_)) . 3)
1547 (and=> (package-description package) P_)) . 2)
1550 (match (and=> (package-location type) location-file)
1551 ((? string? file) (basename file ".scm"))
1555 (define (package-relevance package regexps)
1556 "Return a score denoting the relevance of PACKAGE for REGEXPS. A score of
1557 zero means that PACKAGE does not match any of REGEXPS."
1558 (relevance package regexps %package-metrics))
1560 (define* (display-search-results matches port
1562 (command "guix search")
1563 (print package->recutils))
1564 "Display MATCHES, a list of object/score pairs, by calling PRINT on each of
1565 them. If PORT is a terminal, print at most a full screen of results."
1570 (and first-line (isatty? port)
1571 (terminal-rows port)))
1573 (define (line-count str)
1574 (string-count str #\newline))
1576 (let loop ((matches matches))
1578 (((package . score) rest ...)
1579 (let* ((links? (supports-hyperlinks? port))
1580 (text (call-with-output-string
1583 #:hyperlinks? links?
1585 `((relevance . ,score)))))))
1586 (if (and (not (getenv "INSIDE_EMACS"))
1588 (> (port-line port) first-line) ;print at least one result
1589 (> (+ 4 (line-count text) (port-line port))
1591 (unless (null? rest)
1592 (display-hint (format #f (G_ "Run @code{~a ... | less} \
1593 to view all the results.")
1602 (define (string->generations str)
1603 "Return the list of generations matching a pattern in STR. This function
1604 accepts the following patterns: \"1\", \"1,2,3\", \"1..9\", \"1..\", \"..9\"."
1605 (define (maybe-integer)
1606 (let ((x (string->number str)))
1610 (define (maybe-comma-separated-integers)
1611 (let ((lst (delete-duplicates
1613 (string-split str #\,)))))
1614 (and (every integer? lst)
1617 (cond ((maybe-integer)
1620 ((maybe-comma-separated-integers)
1623 ((string-match "^([0-9]+)\\.\\.([0-9]+)$" str)
1626 (let ((s (string->number (match:substring match 1)))
1627 (e (string->number (match:substring match 2))))
1628 (and (every integer? (list s e))
1630 (iota (1+ (- e s)) s)))))
1631 ((string-match "^([0-9]+)\\.\\.$" str)
1634 (let ((s (string->number (match:substring match 1))))
1637 ((string-match "^\\.\\.([0-9]+)$" str)
1640 (let ((e (string->number (match:substring match 1))))
1645 (define (string->duration str)
1646 "Return the duration matching a pattern in STR. This function accepts the
1647 following patterns: \"1d\", \"1w\", \"1m\"."
1648 (define (hours->duration hours match)
1649 (make-time time-duration 0
1650 (* 3600 hours (string->number (match:substring match 1)))))
1652 (cond ((string-match "^([0-9]+)s$" str)
1655 (make-time time-duration 0
1656 (string->number (match:substring match 1)))))
1657 ((string-match "^([0-9]+)h$" str)
1660 (hours->duration 1 match)))
1661 ((string-match "^([0-9]+)d$" str)
1664 (hours->duration 24 match)))
1665 ((string-match "^([0-9]+)w$" str)
1668 (hours->duration (* 24 7) match)))
1669 ((string-match "^([0-9]+)m$" str)
1672 (hours->duration (* 24 30) match)))
1675 (define* (matching-generations str profile
1676 #:key (duration-relation <=))
1677 "Return the list of available generations matching a pattern in STR. See
1678 'string->generations' and 'string->duration' for the list of valid patterns.
1679 When STR is a duration pattern, return all the generations whose ctime has
1680 DURATION-RELATION with the current time."
1681 (define (valid-generations lst)
1682 (define (valid-generation? n)
1683 (any (cut = n <>) (generation-numbers profile)))
1685 (fold-right (lambda (x acc)
1686 (if (valid-generation? x)
1692 (define (filter-generations generations)
1696 (drop-while (cut > n <>)
1697 (generation-numbers profile)))
1699 (valid-generations (iota n 1)))
1701 (valid-generations lst))
1704 (define (filter-by-duration duration)
1705 (define (time-at-midnight time)
1706 ;; Return TIME at midnight by setting nanoseconds, seconds, minutes, and
1708 (let ((d (time-utc->date time)))
1711 (date-day d) (date-month d)
1712 (date-year d) (date-zone-offset d)))))
1714 (define generation-ctime-alist
1715 (map (lambda (number)
1719 (generation-time profile number)))))
1720 (generation-numbers profile)))
1725 (let ((s (time-second
1726 (subtract-duration (time-at-midnight (current-time))
1728 (delete #f (map (lambda (x)
1729 (and (duration-relation s (cdr x))
1731 generation-ctime-alist))))))
1733 (cond ((string->generations str)
1736 ((string->duration str)
1741 (condition (&message
1742 (message (format #f (G_ "invalid syntax: ~a~%")
1745 (define (display-generation profile number)
1746 "Display a one-line summary of generation NUMBER of PROFILE."
1747 (unless (zero? number)
1748 (let* ((file (generation-file-name profile number))
1749 (link (if (supports-hyperlinks?)
1750 (cut file-hyperlink file <>)
1752 (header (format #f (link (highlight (G_ "Generation ~a\t~a")))
1756 (generation-time profile number))
1757 ;; TRANSLATORS: This is a format-string for date->string.
1758 ;; Please choose a format that corresponds to the
1759 ;; usual way of presenting dates in your locale.
1760 ;; See https://www.gnu.org/software/guile/manual/html_node/SRFI_002d19-Date-to-string.html
1762 (G_ "~b ~d ~Y ~T"))))
1763 (current (generation-number profile)))
1764 (if (= number current)
1765 ;; TRANSLATORS: The word "current" here is an adjective for
1766 ;; "Generation", as in "current generation". Use the appropriate
1767 ;; gender where applicable.
1768 (format #t (G_ "~a\t(current)~%") header)
1769 (format #t "~a~%" header)))))
1771 (define (display-profile-content-diff profile gen1 gen2)
1772 "Display the changed packages in PROFILE GEN2 compared to generation GEN1."
1774 (define (equal-entry? first second)
1775 (string= (manifest-entry-item first) (manifest-entry-item second)))
1777 (define (display-entry entry prefix)
1779 (($ <manifest-entry> name version output location _)
1780 (format #t " ~a ~a\t~a\t~a\t~a~%" prefix name version output location))))
1782 (define (list-entries number)
1783 (manifest-entries (profile-manifest (generation-file-name profile number))))
1785 (define (display-diff profile old new)
1786 (display-generation profile new)
1787 (let ((added (lset-difference
1788 equal-entry? (list-entries new) (list-entries old)))
1789 (removed (lset-difference
1790 equal-entry? (list-entries old) (list-entries new))))
1791 (for-each (cut display-entry <> "+") added)
1792 (for-each (cut display-entry <> "-") removed)
1795 (display-diff profile gen1 gen2))
1797 (define (profile-lock-handler profile errno . _)
1798 "Handle failure to acquire PROFILE's lock."
1799 ;; NFS mounts can return ENOLCK. When that happens, there's not much that
1800 ;; can be done, so warn the user and keep going.
1801 (if (= errno ENOLCK)
1802 (warning (G_ "cannot lock profile ~a: ~a~%")
1803 profile (strerror errno))
1804 (leave (G_ "profile ~a is locked by another process~%")
1807 (define profile-lock-file
1808 (cut string-append <> ".lock"))
1810 (define-syntax-rule (with-profile-lock profile exp ...)
1811 "Grab PROFILE's lock and evaluate EXP... Call 'leave' if the lock is
1813 (with-file-lock/no-wait (profile-lock-file profile)
1814 (cut profile-lock-handler profile <...>)
1817 (define (display-profile-content profile number)
1818 "Display the packages in PROFILE, generation NUMBER, in a human-readable
1820 (for-each (match-lambda
1821 (($ <manifest-entry> name version output location _)
1822 (format #t " ~a\t~a\t~a\t~a~%"
1823 name version output location)))
1825 ;; Show most recently installed packages last.
1828 (profile-manifest (generation-file-name profile number))))))
1830 (define (display-generation-change previous current)
1831 (format #t (G_ "switched from generation ~a to ~a~%") previous current))
1833 (define (roll-back* store profile)
1834 "Like 'roll-back', but display what is happening."
1837 (roll-back store profile))
1838 display-generation-change))
1840 (define (switch-to-generation* profile number)
1841 "Like 'switch-generation', but display what is happening."
1842 (let ((previous (switch-to-generation profile number)))
1843 (display-generation-change previous number)))
1845 (define (delete-generation* store profile generation)
1846 "Like 'delete-generation', but display what is going on."
1847 (format #t (G_ "deleting ~a~%")
1848 (generation-file-name profile generation))
1849 (delete-generation store profile generation))
1851 (define* (package-specification->name+version+output spec
1852 #:optional (output "out"))
1853 "Parse package specification SPEC and return three value: the specified
1854 package name, version number (or #f), and output name (or OUTPUT). SPEC may
1855 optionally contain a version number and an output name, as in these examples:
1862 (let*-values (((name sub-drv)
1863 (match (string-rindex spec #\:)
1864 (#f (values spec output))
1865 (colon (values (substring spec 0 colon)
1866 (substring spec (+ 1 colon))))))
1868 (package-name->name+version name)))
1869 (values name version sub-drv)))
1873 ;;; Command-line option processing.
1876 (define (show-guix-usage)
1877 (format (current-error-port)
1878 (G_ "Try `guix --help' for more information.~%"))
1881 (define (command-files)
1882 "Return the list of source files that define Guix sub-commands."
1884 (and=> (search-path %load-path "guix.scm")
1885 (compose (cut string-append <> "/guix/scripts")
1889 (cut string-suffix? ".scm" <>))
1892 (scandir directory dot-scm?)
1896 "Return the list of Guix command names."
1897 (map (compose (cut string-drop-right <> 4)
1901 (define (show-guix-help)
1902 (define (internal? command)
1903 (member command '("substitute" "authenticate" "offload"
1904 "perform-download")))
1906 (format #t (G_ "Usage: guix COMMAND ARGS...
1907 Run COMMAND with ARGS.\n"))
1909 (format #t (G_ "COMMAND must be one of the sub-commands listed below:\n"))
1911 ;; TODO: Display a synopsis of each command.
1912 (format #t "~{ ~a~%~}" (sort (remove internal? (commands))
1914 (show-bug-report-information))
1916 (define (run-guix-command command . args)
1917 "Run COMMAND with the given ARGS. Report an error when COMMAND is not
1922 (resolve-interface `(guix scripts ,command)))
1924 (format (current-error-port)
1925 (G_ "guix: ~a: command not found~%") command)
1926 (show-guix-usage))))
1928 (let ((command-main (module-ref module
1929 (symbol-append 'guix- command))))
1930 (parameterize ((program-name command))
1931 ;; Disable canonicalization so we don't don't stat unreasonably.
1932 (with-fluids ((%file-port-name-canonicalization #f))
1936 (apply command-main args))
1938 ;; Abuse 'exit-hook' (which is normally meant to be used by the
1939 ;; REPL) to run things like profiling hooks upon completion.
1940 (run-hook exit-hook)))))))
1942 (define (run-guix . args)
1943 "Run the 'guix' command defined by command line ARGS.
1944 Unlike 'guix-main', this procedure assumes that locale, i18n support,
1945 and signal handling has already been set up."
1946 (define option? (cut string-prefix? "-" <>))
1948 ;; The default %LOAD-EXTENSIONS includes the empty string, which doubles the
1949 ;; number of 'stat' calls per entry in %LOAD-PATH. Shamelessly remove it.
1950 (set! %load-extensions '(".scm"))
1954 (format (current-error-port)
1955 (G_ "guix: missing command name~%"))
1957 ((or ("-h") ("--help"))
1959 ((or ("-V") ("--version"))
1960 (show-version-and-exit "guix"))
1961 (((? option? o) args ...)
1962 (format (current-error-port)
1963 (G_ "guix: unrecognized option '~a'~%") o)
1966 (apply run-guix-command (string->symbol command)
1971 (apply run-guix-command
1972 (string->symbol command)
1975 (define (guix-main arg0 . args)
1977 (apply run-guix args))
1979 ;;; ui.scm ends here