1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2012, 2013, 2014, 2015, 2016, 2017 Ludovic Courtès <ludo@gnu.org>
3 ;;; Copyright © 2013 Mark H Weaver <mhw@netris.org>
4 ;;; Copyright © 2013 Nikita Karetnikov <nikita@karetnikov.org>
5 ;;; Copyright © 2014 Cyril Roelandt <tipecaml@gmail.com>
6 ;;; Copyright © 2014 Cyrill Schenkel <cyrill.schenkel@gmail.com>
7 ;;; Copyright © 2014, 2015, 2017 Alex Kost <alezost@gmail.com>
8 ;;; Copyright © 2015 David Thompson <davet@gnu.org>
9 ;;; Copyright © 2015, 2016 Mathieu Lirzin <mthl@gnu.org>
10 ;;; Copyright © 2016 Roel Janssen <roel@gnu.org>
11 ;;; Copyright © 2016 Benz Schenk <benz.schenk@uzh.ch>
13 ;;; This file is part of GNU Guix.
15 ;;; GNU Guix is free software; you can redistribute it and/or modify it
16 ;;; under the terms of the GNU General Public License as published by
17 ;;; the Free Software Foundation; either version 3 of the License, or (at
18 ;;; your option) any later version.
20 ;;; GNU Guix is distributed in the hope that it will be useful, but
21 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
22 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 ;;; GNU General Public License for more details.
25 ;;; You should have received a copy of the GNU General Public License
26 ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
28 (define-module (guix ui)
29 #:use-module (guix i18n)
30 #:use-module (guix gexp)
31 #:use-module (guix utils)
32 #:use-module (guix store)
33 #:use-module (guix config)
34 #:use-module (guix packages)
35 #:use-module (guix profiles)
36 #:use-module (guix derivations)
37 #:use-module (guix combinators)
38 #:use-module (guix build-system)
39 #:use-module (guix serialization)
40 #:use-module ((guix licenses) #:select (license? license-name))
41 #:use-module ((guix build syscalls)
42 #:select (free-disk-space terminal-columns))
43 #:use-module (srfi srfi-1)
44 #:use-module (srfi srfi-11)
45 #:use-module (srfi srfi-19)
46 #:use-module (srfi srfi-26)
47 #:use-module (srfi srfi-31)
48 #:use-module (srfi srfi-34)
49 #:use-module (srfi srfi-35)
50 #:autoload (ice-9 ftw) (scandir)
51 #:use-module (ice-9 match)
52 #:use-module (ice-9 format)
53 #:use-module (ice-9 regex)
54 #:autoload (system repl repl) (start-repl)
55 #:autoload (system repl debug) (make-debug stack->vector)
56 #:use-module (texinfo)
57 #:use-module (texinfo plain-text)
58 #:use-module (texinfo string-utils)
59 #:re-export (G_ N_ P_) ;backward compatibility
60 #:export (report-error
66 show-bug-report-information
70 show-derivation-outputs
73 show-manifest-transaction
74 call-with-error-handling
78 read/eval-package-expression
83 package-description-string
84 package-synopsis-string
87 package-specification->name+version+output
94 display-profile-content
95 display-profile-content-diff
109 ;;; User interface facilities for command-line tools.
113 (define-syntax-rule (define-diagnostic name prefix)
114 "Create a diagnostic macro (i.e., NAME), which will prepend PREFIX to all
118 (define (augmented-format-string fmt)
119 (string-append "~:[~*~;guix ~a: ~]~a" (syntax->datum fmt)))
122 ((name (underscore fmt) args (... ...))
123 (and (string? (syntax->datum #'fmt))
124 (free-identifier=? #'underscore #'G_))
125 (with-syntax ((fmt* (augmented-format-string #'fmt))
126 (prefix (datum->syntax x prefix)))
127 #'(format (guix-warning-port) (gettext fmt*)
128 (program-name) (program-name) prefix
130 ((name (N-underscore singular plural n) args (... ...))
131 (and (string? (syntax->datum #'singular))
132 (string? (syntax->datum #'plural))
133 (free-identifier=? #'N-underscore #'N_))
134 (with-syntax ((s (augmented-format-string #'singular))
135 (p (augmented-format-string #'plural))
136 (prefix (datum->syntax x prefix)))
137 #'(format (guix-warning-port)
138 (ngettext s p n %gettext-domain)
139 (program-name) (program-name) prefix
140 args (... ...))))))))
142 (define-diagnostic warning "warning: ") ; emit a warning
143 (define-diagnostic info "")
145 (define-diagnostic report-error "error: ")
146 (define-syntax-rule (leave args ...)
147 "Emit an error message and exit."
149 (report-error args ...)
152 (define (print-unbound-variable-error port key args default-printer)
153 ;; Print unbound variable errors more nicely, and in the right language.
155 ((proc message (variable) _ ...)
156 ;; We can always omit PROC because when it's useful (i.e., different from
157 ;; "module-lookup"), it gets displayed before.
158 (format port (G_ "~a: unbound variable") variable))
162 (set-exception-printer! 'unbound-variable print-unbound-variable-error)
164 (define (make-user-module modules)
165 "Return a new user module with the additional MODULES loaded."
166 ;; Module in which the machine description file is loaded.
167 (let ((module (make-fresh-user-module)))
168 (for-each (lambda (iface)
169 (module-use! module (resolve-interface iface)))
173 (define* (load* file user-module
174 #:key (on-error 'nothing-special))
175 "Load the user provided Scheme source code FILE."
176 (define (frame-with-source frame)
177 ;; Walk from FRAME upwards until source location information is found.
178 (let loop ((frame frame)
182 (if (frame-source frame)
184 (loop (frame-previous frame) frame)))))
186 (define (error-string frame args)
187 (call-with-output-string
189 (apply display-error frame port (cdr args)))))
192 (make-prompt-tag "user-code"))
196 ;; XXX: Force a recompilation to avoid ABI issues.
197 (set! %fresh-auto-compile #t)
198 (set! %load-should-auto-compile #t)
200 (save-module-excursion
202 (set-current-module user-module)
204 ;; Hide the "auto-compiling" messages.
205 (parameterize ((current-warning-port (%make-void-port "w")))
206 (call-with-prompt tag
208 ;; Give 'load' an absolute file name so that it doesn't try to
209 ;; search for FILE in %LOAD-PATH. Note: use 'load', not
210 ;; 'primitive-load', so that FILE is compiled, which then allows us
211 ;; to provide better error reporting with source line numbers.
212 (load (canonicalize-path file)))
215 ;; XXX: Errors are reported from the pre-unwind handler below, but
216 ;; calling 'exit' from there has no effect, so we call it here.
218 (rec (handle-error . args)
219 ;; Capture the stack up to this procedure call, excluded, and pass
220 ;; the faulty stack frame to 'report-load-error'.
221 (let* ((stack (make-stack #t handle-error tag))
222 (depth (stack-length stack))
223 (last (and (> depth 0) (stack-ref stack 0)))
224 (frame (frame-with-source
226 (stack-ref stack 1) ;skip the 'throw' frame
229 (report-load-error file args frame)
234 (display (G_ "entering debugger; type ',bt' for a backtrace\n"))
235 (start-repl #:debug (make-debug (stack->vector stack) 0
236 (error-string frame args)
239 (newline (current-error-port))
240 (display-backtrace stack (current-error-port)))
244 (define (known-variable-definition variable)
245 "Search among the currently loaded modules one that defines a variable named
246 VARIABLE and return it, or #f if none was found."
247 (define (module<? m1 m2)
248 (match (module-name m2)
251 (match (module-name m1)
256 (let loop ((modules (list (resolve-module '() #f #f #:ensure #f)))
260 ;; Pick the "best" suggestion.
261 (match (sort suggestions module<?)
263 ((first _ ...) first)))
265 (let ((next (append tail
266 (hash-map->list (lambda (name module)
268 (module-submodules head)))))
269 (match (module-local-variable head variable)
270 (#f (loop next suggestions))
272 (match (module-name head)
273 (('gnu _ ...) head) ;must be that one
274 (_ (loop next (cons head suggestions)))))))))))
276 (define* (display-hint message #:optional (port (current-error-port)))
277 "Display MESSAGE, a l10n message possibly containing Texinfo markup, to
279 (format port (G_ "hint: ~a~%")
280 (fill-paragraph (texi->plain-text message)
281 (terminal-columns) 8)))
283 (define* (report-load-error file args #:optional frame)
284 "Report the failure to load FILE, a user-provided Scheme file.
285 ARGS is the list of arguments received by the 'throw' handler."
287 (('system-error . rest)
288 (let ((err (system-error-errno args)))
289 (report-error (G_ "failed to load '~a': ~a~%") file (strerror err))))
290 (('read-error "scm_i_lreadparen" message _ ...)
291 ;; Guile's missing-paren messages are obscure so we make them more
292 ;; intelligible here.
293 (if (string-suffix? "end of file" message)
294 (let ((location (string-drop-right message
295 (string-length "end of file"))))
296 (format (current-error-port) (G_ "~amissing closing parenthesis~%")
299 (('syntax-error proc message properties form . rest)
300 (let ((loc (source-properties->location properties)))
301 (format (current-error-port) (G_ "~a: error: ~a~%")
302 (location->string loc) message)))
303 (('unbound-variable proc message (variable) _ ...)
306 (print-exception (current-error-port) frame key args)))
307 (match (known-variable-definition variable)
309 (display-hint (G_ "Did you forget a @code{use-modules} form?")))
311 (display-hint (format #f (G_ "Try adding @code{(use-modules ~a)}.")
312 (module-name module))))))
314 (if (message-condition? obj)
315 (if (error-location? obj)
316 (format (current-error-port)
317 (G_ "~a: error: ~a~%")
318 (location->string (error-location obj))
319 (gettext (condition-message obj)
321 (report-error (G_ "~a~%")
322 (gettext (condition-message obj)
324 (report-error (G_ "exception thrown: ~s~%") obj))
325 (when (fix-hint? obj)
326 (display-hint (condition-fix-hint obj))))
328 (report-error (G_ "failed to load '~a':~%") file)
329 (apply display-error frame (current-error-port) args))))
331 (define (warn-about-load-error file args) ;FIXME: factorize with ↑
332 "Report the failure to load FILE, a user-provided Scheme file, without
333 exiting. ARGS is the list of arguments received by the 'throw' handler."
335 (('system-error . rest)
336 (let ((err (system-error-errno args)))
337 (warning (G_ "failed to load '~a': ~a~%") file (strerror err))))
338 (('syntax-error proc message properties form . rest)
339 (let ((loc (source-properties->location properties)))
340 (format (current-error-port) (G_ "~a: warning: ~a~%")
341 (location->string loc) message)))
343 (if (message-condition? obj)
344 (warning (G_ "failed to load '~a': ~a~%")
346 (gettext (condition-message obj) %gettext-domain))
347 (warning (G_ "failed to load '~a': exception thrown: ~s~%")
350 (warning (G_ "failed to load '~a':~%") file)
351 (apply display-error #f (current-error-port) args))))
353 (define (install-locale)
354 "Install the current locale settings."
357 (setlocale LC_ALL ""))
359 (warning (G_ "failed to install locale: ~a~%")
360 (strerror (system-error-errno args))))))
362 (define (initialize-guix)
363 "Perform the usual initialization for stand-alone Guix commands."
364 ;; By default don't annoy users with deprecation warnings. In practice,
365 ;; 'define-deprecated' in (ice-9 deprecated) arranges so that those warnings
366 ;; are emitted at expansion-time only, but there are cases where they could
367 ;; slip through, for instance when interpreting code.
368 (unless (getenv "GUILE_WARN_DEPRECATED")
369 (debug-disable 'warn-deprecated))
372 (textdomain %gettext-domain)
374 ;; Ignore SIGPIPE. If the daemon closes the connection, we prefer to be
375 ;; notified via an EPIPE later.
376 (sigaction SIGPIPE SIG_IGN)
378 (setvbuf (current-output-port) _IOLBF)
379 (setvbuf (current-error-port) _IOLBF))
381 (define* (show-version-and-exit #:optional (command (car (command-line))))
382 "Display version information for COMMAND and `(exit 0)'."
383 (simple-format #t "~a (~a) ~a~%"
384 command %guix-package-name %guix-version)
385 (format #t "Copyright ~a 2017 ~a"
386 ;; TRANSLATORS: Translate "(C)" to the copyright symbol
387 ;; (C-in-a-circle), if this symbol is available in the user's
388 ;; locale. Otherwise, do not translate "(C)"; leave it as-is. */
390 (G_ "the Guix authors\n"))
392 License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
393 This is free software: you are free to change and redistribute it.
394 There is NO WARRANTY, to the extent permitted by law.
398 (define (show-bug-report-information)
399 ;; TRANSLATORS: The placeholder indicates the bug-reporting address for this
400 ;; package. Please add another line saying "Report translation bugs to
401 ;; ...\n" with the address for translation bugs (typically your translation
402 ;; team's web or email address).
404 Report bugs to: ~a.") %guix-bug-report-address)
406 ~a home page: <~a>") %guix-package-name %guix-home-page-url)
408 General help using GNU software: <http://www.gnu.org/gethelp/>"))
411 (define (augmented-system-error-handler file)
412 "Return a 'system-error' handler that mentions FILE in its message."
413 (lambda (key proc fmt args errno)
414 ;; Augment the FMT and ARGS with information about TARGET (this
415 ;; information is missing as of Guile 2.0.11, making the exception
417 (apply throw key proc "~A: ~S"
418 (list (strerror (car errno)) file)
421 (define-syntax-rule (error-reporting-wrapper proc (args ...) file)
422 "Wrap PROC such that its 'system-error' exceptions are augmented to mention
424 (let ((real-proc (@ (guile) proc)))
428 (real-proc args ...))
429 (augmented-system-error-handler file)))))
432 ;; We 'set!' the global binding because (gnu build ...) modules and similar
433 ;; typically don't use (guix ui).
434 (error-reporting-wrapper symlink (source target) target))
437 ;; Note: here we use 'set!', not #:replace, because UIs typically use
438 ;; 'copy-recursively', which doesn't use (guix ui).
439 (error-reporting-wrapper copy-file (source target) target))
441 (set! canonicalize-path
442 (error-reporting-wrapper canonicalize-path (file) file))
445 (define (make-regexp* regexp . flags)
446 "Like 'make-regexp' but error out if REGEXP is invalid, reporting the error
448 (catch 'regular-expression-syntax
450 (apply make-regexp regexp flags))
451 (lambda (key proc message . rest)
452 (leave (G_ "'~a' is not a valid regular expression: ~a~%")
455 (define (string->number* str)
456 "Like `string->number', but error out with an error message on failure."
457 (or (string->number str)
458 (leave (G_ "~a: invalid number~%") str)))
460 (define (size->number str)
461 "Convert STR, a storage measurement representation such as \"1024\" or
462 \"1MiB\", to a number of bytes. Raise an error if STR could not be
465 (string-rindex str char-set:digit))
468 (and unit-pos (substring str (+ 1 unit-pos))))
470 (let* ((numstr (if unit-pos
471 (substring str 0 (+ 1 unit-pos))
473 (num (string->number numstr)))
475 (leave (G_ "invalid number: ~a~%") numstr))
477 ((compose inexact->exact round)
480 ((or "KiB" "K" "k") (expt 2 10))
481 ((or "MiB" "M") (expt 2 20))
482 ((or "GiB" "G") (expt 2 30))
483 ((or "TiB" "T") (expt 2 40))
484 ((or "PiB" "P") (expt 2 50))
485 ((or "EiB" "E") (expt 2 60))
486 ((or "ZiB" "Z") (expt 2 70))
487 ((or "YiB" "Y") (expt 2 80))
498 (leave (G_ "unknown unit: ~a~%") unit)))))))
500 (define (call-with-error-handling thunk)
501 "Call THUNK within a user-friendly error handler."
502 (define (port-filename* port)
503 ;; 'port-filename' returns #f for non-file ports, but it raises an
504 ;; exception for file ports that are closed. Work around that.
505 (and (not (port-closed? port))
506 (port-filename port)))
508 (guard (c ((package-input-error? c)
509 (let* ((package (package-error-package c))
510 (input (package-error-invalid-input c))
511 (location (package-location package))
512 (file (location-file location))
513 (line (location-line location))
514 (column (location-column location)))
515 (leave (G_ "~a:~a:~a: package `~a' has an invalid input: ~s~%")
517 (package-full-name package) input)))
518 ((package-cross-build-system-error? c)
519 (let* ((package (package-error-package c))
520 (loc (package-location package))
521 (system (package-build-system package)))
522 (leave (G_ "~a: ~a: build system `~a' does not support cross builds~%")
523 (location->string loc)
524 (package-full-name package)
525 (build-system-name system))))
526 ((gexp-input-error? c)
527 (let ((input (package-error-invalid-input c)))
528 (leave (G_ "~s: invalid G-expression input~%")
529 (gexp-error-invalid-input c))))
530 ((profile-not-found-error? c)
531 (leave (G_ "profile '~a' does not exist~%")
532 (profile-error-profile c)))
533 ((missing-generation-error? c)
534 (leave (G_ "generation ~a of profile '~a' does not exist~%")
535 (missing-generation-error-generation c)
536 (profile-error-profile c)))
537 ((profile-collision-error? c)
538 (let ((entry (profile-collision-error-entry c))
539 (conflict (profile-collision-error-conflict c)))
540 (define (report-parent-entries entry)
541 (let ((parent (force (manifest-entry-parent entry))))
542 (when (manifest-entry? parent)
543 (report-error (G_ " ... propagated from ~a@~a~%")
544 (manifest-entry-name parent)
545 (manifest-entry-version parent))
546 (report-parent-entries parent))))
548 (report-error (G_ "profile contains conflicting entries for ~a:~a~%")
549 (manifest-entry-name entry)
550 (manifest-entry-output entry))
551 (report-error (G_ " first entry: ~a@~a:~a ~a~%")
552 (manifest-entry-name entry)
553 (manifest-entry-version entry)
554 (manifest-entry-output entry)
555 (manifest-entry-item entry))
556 (report-parent-entries entry)
557 (report-error (G_ " second entry: ~a@~a:~a ~a~%")
558 (manifest-entry-name conflict)
559 (manifest-entry-version conflict)
560 (manifest-entry-output conflict)
561 (manifest-entry-item conflict))
562 (report-parent-entries conflict)
565 (let ((file (nar-error-file c))
566 (port (nar-error-port c)))
568 (leave (G_ "corrupt input while restoring '~a' from ~s~%")
569 file (or (port-filename* port) port))
570 (leave (G_ "corrupt input while restoring archive from ~s~%")
571 (or (port-filename* port) port)))))
572 ((nix-connection-error? c)
573 (leave (G_ "failed to connect to `~a': ~a~%")
574 (nix-connection-error-file c)
575 (strerror (nix-connection-error-code c))))
576 ((nix-protocol-error? c)
577 ;; FIXME: Server-provided error messages aren't i18n'd.
578 (leave (G_ "build failed: ~a~%")
579 (nix-protocol-error-message c)))
580 ((derivation-missing-output-error? c)
581 (leave (G_ "reference to invalid output '~a' of derivation '~a'~%")
582 (derivation-missing-output c)
583 (derivation-file-name (derivation-error-derivation c))))
584 ((file-search-error? c)
585 (leave (G_ "file '~a' could not be found in these \
586 directories:~{ ~a~}~%")
587 (file-search-error-file-name c)
588 (file-search-error-search-path c)))
589 ((and (error-location? c) (message-condition? c))
590 (format (current-error-port)
591 (G_ "~a: error: ~a~%")
592 (location->string (error-location c))
593 (gettext (condition-message c) %gettext-domain)))
594 ((message-condition? c)
595 ;; Normally '&message' error conditions have an i18n'd message.
597 (gettext (condition-message c) %gettext-domain))))
598 ;; Catch EPIPE and the likes.
601 (lambda (key proc format-string format-args . rest)
602 (leave (G_ "~a: ~a~%") proc
603 (apply format #f format-string format-args))))))
605 (define-syntax-rule (leave-on-EPIPE exp ...)
606 "Run EXP... in a context when EPIPE errors are caught and lead to 'exit'
607 with successful exit code. This is useful when writing to the standard output
608 may lead to EPIPE, because the standard output is piped through 'head' or
614 ;; We really have to exit this brutally, otherwise Guile eventually
615 ;; attempts to flush all the ports, leading to an uncaught EPIPE down
617 (if (= EPIPE (system-error-errno args))
619 (apply throw args)))))
621 (define %guix-user-module
622 ;; Module in which user expressions are evaluated.
623 ;; Compute lazily to avoid circularity with (guix gexp).
625 (let ((module (make-module)))
626 (beautify-user-module! module)
627 ;; Use (guix gexp) so that one can use #~ & co.
628 (module-use! module (resolve-interface '(guix gexp)))
631 (define (read/eval str)
632 "Read and evaluate STR, raising an error if something goes wrong."
635 (call-with-input-string str read))
637 (leave (G_ "failed to read expression ~s: ~s~%")
641 (eval exp (force %guix-user-module)))
643 (report-error (G_ "failed to evaluate expression '~a':~%") exp)
645 (('syntax-error proc message properties form . rest)
646 (report-error (G_ "syntax error: ~a~%") message))
648 (if (message-condition? obj)
649 (report-error (G_ "~a~%")
650 (gettext (condition-message obj)
652 (report-error (G_ "exception thrown: ~s~%") obj)))
654 (apply display-error #f (current-error-port) args))
658 (define (read/eval-package-expression str)
659 "Read and evaluate STR and return the package it refers to, or exit an
661 (match (read/eval str)
664 (leave (G_ "expression ~s does not evaluate to a package~%")
667 (define (show-derivation-outputs derivation)
668 "Show the output file names of DERIVATION."
669 (format #t "~{~a~%~}"
672 (derivation->output-path derivation out-name)))
673 (derivation-outputs derivation))))
675 (define (check-available-space need)
676 "Make sure at least NEED bytes are available in the store. Otherwise emit a
678 (let ((free (catch 'system-error
680 (free-disk-space (%store-prefix)))
682 (when (and free (>= need free))
683 (warning (G_ "at least ~,1h MB needed but only ~,1h MB available in ~a~%")
684 (/ need 1e6) (/ free 1e6) (%store-prefix)))))
686 (define* (show-what-to-build store drv
687 #:key dry-run? (use-substitutes? #t)
688 (mode (build-mode normal)))
689 "Show what will or would (depending on DRY-RUN?) be built in realizing the
690 derivations listed in DRV using MODE, a 'build-mode' value. Return #t if
691 there's something to build, #f otherwise. When USE-SUBSTITUTES?, check and
692 report what is prerequisites are available for download."
693 (define substitutable-info
694 ;; Call 'substitutation-oracle' upfront so we don't end up launching the
695 ;; substituter many times. This makes a big difference, especially when
696 ;; DRV is a long list as is the case with 'guix environment'.
698 (substitution-oracle store drv #:mode mode)
701 (define (built-or-substitutable? drv)
702 (or (null? (derivation-outputs drv))
703 (let ((out (derivation->output-path drv))) ;XXX: assume "out" exists
704 (or (valid-path? store out)
705 (substitutable-info out)))))
707 (let*-values (((build download)
708 (fold2 (lambda (drv build download)
710 (derivation-prerequisites-to-build
714 substitutable-info)))
715 (values (append b build)
716 (append d download))))
719 ((build) ; add the DRV themselves
721 (append (map derivation-file-name
722 (remove built-or-substitutable? drv))
723 (map derivation-input-path build))))
724 ((download) ; add the references of DOWNLOAD
728 (filter-map (lambda (item)
729 (if (valid-path? store item)
731 (substitutable-info item)))
733 substitutable-references
736 (define installed-size
737 (reduce + 0 (map substitutable-nar-size download)))
739 (define download-size
740 (/ (reduce + 0 (map substitutable-download-size download))
743 (define display-download-size?
744 ;; Sometimes narinfos lack information about the download size. Only
745 ;; display when we have information for all of DOWNLOAD.
746 (not (any (compose zero? substitutable-download-size) download)))
750 (format (current-error-port)
751 (N_ "~:[The following derivation would be built:~%~{ ~a~%~}~;~]"
752 "~:[The following derivations would be built:~%~{ ~a~%~}~;~]"
755 (if display-download-size?
756 (format (current-error-port)
757 ;; TRANSLATORS: "MB" is for "megabyte"; it should be
758 ;; translated to the corresponding abbreviation.
759 (G_ "~:[~,1h MB would be downloaded:~%~{ ~a~%~}~;~]")
762 (map substitutable-path download))
763 (format (current-error-port)
764 (N_ "~:[The following file would be downloaded:~%~{ ~a~%~}~;~]"
765 "~:[The following files would be downloaded:~%~{ ~a~%~}~;~]"
768 (map substitutable-path download))))
770 (format (current-error-port)
771 (N_ "~:[The following derivation will be built:~%~{ ~a~%~}~;~]"
772 "~:[The following derivations will be built:~%~{ ~a~%~}~;~]"
775 (if display-download-size?
776 (format (current-error-port)
777 ;; TRANSLATORS: "MB" is for "megabyte"; it should be
778 ;; translated to the corresponding abbreviation.
779 (G_ "~:[~,1h MB will be downloaded:~%~{ ~a~%~}~;~]")
782 (map substitutable-path download))
783 (format (current-error-port)
784 (N_ "~:[The following file will be downloaded:~%~{ ~a~%~}~;~]"
785 "~:[The following files will be downloaded:~%~{ ~a~%~}~;~]"
788 (map substitutable-path download)))))
790 (check-available-space installed-size)
794 (define show-what-to-build*
795 (store-lift show-what-to-build))
797 (define (right-arrow port)
798 "Return either a string containing the 'RIGHT ARROW' character, or an ASCII
799 replacement if PORT is not Unicode-capable."
800 (let ((encoding (port-encoding port))
802 (catch 'encoding-error
804 (call-with-output-string
806 (set-port-encoding! port encoding)
807 (set-port-conversion-strategy! port 'error)
808 (display arrow port))))
812 (define* (show-manifest-transaction store manifest transaction
814 "Display what will/would be installed/removed from MANIFEST by TRANSACTION."
815 (define (package-strings name version output item)
816 (map (lambda (name version output item)
817 (format #f " ~a~:[:~a~;~*~]\t~a\t~a"
819 (equal? output "out") output version
821 (package-output store item output)
823 name version output item))
825 (define → ;an arrow that can be represented on stderr
826 (right-arrow (current-error-port)))
828 (define (upgrade-string name old-version new-version output item)
829 (format #f " ~a~:[:~a~;~*~]\t~a ~a ~a\t~a"
830 name (equal? output "out") output
831 old-version → new-version
833 (package-output store item output)
836 (let-values (((remove install upgrade downgrade)
837 (manifest-transaction-effects manifest transaction)))
839 ((($ <manifest-entry> name version output item) ..1)
840 (let ((len (length name))
841 (remove (package-strings name version output item)))
843 (format (current-error-port)
844 (N_ "The following package would be removed:~%~{~a~%~}~%"
845 "The following packages would be removed:~%~{~a~%~}~%"
848 (format (current-error-port)
849 (N_ "The following package will be removed:~%~{~a~%~}~%"
850 "The following packages will be removed:~%~{~a~%~}~%"
855 (((($ <manifest-entry> name old-version)
856 . ($ <manifest-entry> _ new-version output item)) ..1)
857 (let ((len (length name))
858 (downgrade (map upgrade-string
859 name old-version new-version output item)))
861 (format (current-error-port)
862 (N_ "The following package would be downgraded:~%~{~a~%~}~%"
863 "The following packages would be downgraded:~%~{~a~%~}~%"
866 (format (current-error-port)
867 (N_ "The following package will be downgraded:~%~{~a~%~}~%"
868 "The following packages will be downgraded:~%~{~a~%~}~%"
873 (((($ <manifest-entry> name old-version)
874 . ($ <manifest-entry> _ new-version output item)) ..1)
875 (let ((len (length name))
876 (upgrade (map upgrade-string
877 name old-version new-version output item)))
879 (format (current-error-port)
880 (N_ "The following package would be upgraded:~%~{~a~%~}~%"
881 "The following packages would be upgraded:~%~{~a~%~}~%"
884 (format (current-error-port)
885 (N_ "The following package will be upgraded:~%~{~a~%~}~%"
886 "The following packages will be upgraded:~%~{~a~%~}~%"
891 ((($ <manifest-entry> name version output item _) ..1)
892 (let ((len (length name))
893 (install (package-strings name version output item)))
895 (format (current-error-port)
896 (N_ "The following package would be installed:~%~{~a~%~}~%"
897 "The following packages would be installed:~%~{~a~%~}~%"
900 (format (current-error-port)
901 (N_ "The following package will be installed:~%~{~a~%~}~%"
902 "The following packages will be installed:~%~{~a~%~}~%"
907 (define-syntax with-error-handling
909 "Run BODY within a user-friendly error condition handler."
911 (call-with-error-handling
915 (define (location->string loc)
916 "Return a human-friendly, GNU-standard representation of LOC."
918 (#f (G_ "<unknown location>"))
919 (($ <location> file line column)
920 (format #f "~a:~a:~a" file line column))))
922 (define* (fill-paragraph str width #:optional (column 0))
923 "Fill STR such that each line contains at most WIDTH characters, assuming
924 that the first character is at COLUMN.
926 When STR contains a single line break surrounded by other characters, it is
927 converted to a space; sequences of more than one line break are preserved."
928 (define (maybe-break chr result)
930 ((column newlines chars)
933 `(,column ,(+ 1 newlines) ,chars))
935 (let* ((spaces (if (and (pair? chars) (eqv? (car chars) #\.)) 2 1))
936 (chars (case newlines
939 (append (make-list spaces #\space) chars))
941 (append (make-list newlines #\newline) chars))))
942 (column (case newlines
944 ((1) (+ spaces column))
946 (let ((chars (cons chr chars))
947 (column (+ 1 column)))
949 (let*-values (((before after)
950 (break (cut eqv? #\space <>) chars))
960 (drop-while (cut eqv? #\space <>)
962 `(,column 0 ,chars))) ; unbreakable
963 `(,column 0 ,chars)))))))))
965 (match (string-fold maybe-break
968 ((column newlines chars)
969 (list->string (reverse chars)))))
977 (make-parameter (terminal-columns)))
979 (set! (@@ (texinfo plain-text) wrap*)
980 ;; XXX: Monkey patch this private procedure to let 'package->recutils'
981 ;; parameterize the fill of description field correctly.
983 (let ((indent (fluid-ref (@@ (texinfo plain-text) *indent*))))
984 (fill-string (string-concatenate strings)
985 #:line-width (%text-width) #:initial-indent indent
986 #:subsequent-indent indent))))
988 (define (texi->plain-text str)
989 "Return a plain-text representation of texinfo fragment STR."
990 ;; 'texi-fragment->stexi' uses a string port so make sure it's a
991 ;; Unicode-capable one (see <http://bugs.gnu.org/11197>.)
992 (with-fluids ((%default-port-encoding "UTF-8"))
993 (stexi->plain-text (texi-fragment->stexi str))))
995 (define (package-field-string package field-accessor)
996 "Return a plain-text representation of PACKAGE field."
997 (and=> (field-accessor package)
998 (compose texi->plain-text P_)))
1000 (define (package-description-string package)
1001 "Return a plain-text representation of PACKAGE description field."
1002 (package-field-string package package-description))
1004 (define (package-synopsis-string package)
1005 "Return a plain-text representation of PACKAGE synopsis field."
1006 (package-field-string package package-synopsis))
1008 (define (string->recutils str)
1009 "Return a version of STR where newlines have been replaced by newlines
1010 followed by \"+ \", which makes for a valid multi-line field value in the
1013 (string-fold-right (lambda (chr result)
1014 (if (eqv? chr #\newline)
1015 (cons* chr #\+ #\space result)
1020 (define* (package->recutils p port #:optional (width (%text-width))
1021 #:key (extra-fields '()))
1022 "Write to PORT a `recutils' record of package P, arranging to fit within
1023 WIDTH columns. EXTRA-FIELDS is a list of symbol/value pairs to emit."
1025 ;; The available number of columns once we've taken into account space for
1026 ;; the initial "+ " prefix.
1027 (if (> width 2) (- width 2) width))
1029 (define (dependencies->recutils packages)
1030 (let ((list (string-join (delete-duplicates
1031 (map package-full-name
1032 (sort packages package<?))) " ")))
1034 (fill-paragraph list width*
1035 (string-length "dependencies: ")))))
1037 (define (package<? p1 p2)
1038 (string<? (package-full-name p1) (package-full-name p2)))
1040 ;; Note: Don't i18n field names so that people can post-process it.
1041 (format port "name: ~a~%" (package-name p))
1042 (format port "version: ~a~%" (package-version p))
1043 (format port "outputs: ~a~%" (string-join (package-outputs p)))
1044 (format port "systems: ~a~%"
1045 (string-join (package-transitive-supported-systems p)))
1046 (format port "dependencies: ~a~%"
1047 (match (package-direct-inputs p)
1048 (((labels inputs . _) ...)
1049 (dependencies->recutils (filter package? inputs)))))
1050 (format port "location: ~a~%"
1051 (or (and=> (package-location p) location->string)
1054 ;; Note: Starting from version 1.6 or recutils, hyphens are not allowed in
1055 ;; field identifiers.
1056 (format port "homepage: ~a~%" (package-home-page p))
1058 (format port "license: ~a~%"
1059 (match (package-license p)
1060 (((? license? licenses) ...)
1061 (string-join (map license-name licenses)
1063 ((? license? license)
1064 (license-name license))
1067 (format port "synopsis: ~a~%"
1068 (string-map (match-lambda
1071 (or (and=> (package-synopsis-string p) P_)
1076 (parameterize ((%text-width width*))
1078 (string-append "description: "
1079 (or (and=> (package-description p) P_)
1082 (for-each (match-lambda
1084 (let ((field (symbol->string field)))
1085 (format port "~a: ~a~%"
1087 (fill-paragraph (object->string value) width*
1088 (string-length field))))))
1092 (define (relevance obj regexps metrics)
1093 "Compute a \"relevance score\" for OBJ as a function of its number of
1094 matches of REGEXPS and accordingly to METRICS. METRICS is list of
1095 field/weight pairs, where FIELD is a procedure that returns a string
1096 describing OBJ, and WEIGHT is a positive integer denoting the weight of this
1097 field in the final score.
1099 A score of zero means that OBJ does not match any of REGEXPS. The higher the
1100 score, the more relevant OBJ is to REGEXPS."
1102 (let ((counts (filter-map (lambda (regexp)
1103 (match (regexp-exec regexp str)
1105 (m (match:count m))))
1107 ;; Compute a score that's proportional to the number of regexps matched
1108 ;; and to the number of matches for each regexp.
1109 (* (length counts) (reduce + 0 counts))))
1111 (fold (lambda (metric relevance)
1117 (* (score str) weight)))))))
1121 (define %package-metrics
1122 ;; Metrics used to compute the "relevance score" of a package against a set
1124 `((,package-name . 4)
1125 (,package-synopsis-string . 3)
1126 (,package-description-string . 2)
1128 (match (and=> (package-location type) location-file)
1129 ((? string? file) (basename file ".scm"))
1133 (define (package-relevance package regexps)
1134 "Return a score denoting the relevance of PACKAGE for REGEXPS. A score of
1135 zero means that PACKAGE does not match any of REGEXPS."
1136 (relevance package regexps %package-metrics))
1138 (define (string->generations str)
1139 "Return the list of generations matching a pattern in STR. This function
1140 accepts the following patterns: \"1\", \"1,2,3\", \"1..9\", \"1..\", \"..9\"."
1141 (define (maybe-integer)
1142 (let ((x (string->number str)))
1146 (define (maybe-comma-separated-integers)
1147 (let ((lst (delete-duplicates
1149 (string-split str #\,)))))
1150 (and (every integer? lst)
1153 (cond ((maybe-integer)
1156 ((maybe-comma-separated-integers)
1159 ((string-match "^([0-9]+)\\.\\.([0-9]+)$" str)
1162 (let ((s (string->number (match:substring match 1)))
1163 (e (string->number (match:substring match 2))))
1164 (and (every integer? (list s e))
1166 (iota (1+ (- e s)) s)))))
1167 ((string-match "^([0-9]+)\\.\\.$" str)
1170 (let ((s (string->number (match:substring match 1))))
1173 ((string-match "^\\.\\.([0-9]+)$" str)
1176 (let ((e (string->number (match:substring match 1))))
1181 (define (string->duration str)
1182 "Return the duration matching a pattern in STR. This function accepts the
1183 following patterns: \"1d\", \"1w\", \"1m\"."
1184 (define (hours->duration hours match)
1185 (make-time time-duration 0
1186 (* 3600 hours (string->number (match:substring match 1)))))
1188 (cond ((string-match "^([0-9]+)s$" str)
1191 (make-time time-duration 0
1192 (string->number (match:substring match 1)))))
1193 ((string-match "^([0-9]+)h$" str)
1196 (hours->duration 1 match)))
1197 ((string-match "^([0-9]+)d$" str)
1200 (hours->duration 24 match)))
1201 ((string-match "^([0-9]+)w$" str)
1204 (hours->duration (* 24 7) match)))
1205 ((string-match "^([0-9]+)m$" str)
1208 (hours->duration (* 24 30) match)))
1211 (define* (matching-generations str profile
1212 #:key (duration-relation <=))
1213 "Return the list of available generations matching a pattern in STR. See
1214 'string->generations' and 'string->duration' for the list of valid patterns.
1215 When STR is a duration pattern, return all the generations whose ctime has
1216 DURATION-RELATION with the current time."
1217 (define (valid-generations lst)
1218 (define (valid-generation? n)
1219 (any (cut = n <>) (generation-numbers profile)))
1221 (fold-right (lambda (x acc)
1222 (if (valid-generation? x)
1228 (define (filter-generations generations)
1232 (drop-while (cut > n <>)
1233 (generation-numbers profile)))
1235 (valid-generations (iota n 1)))
1237 (valid-generations lst))
1240 (define (filter-by-duration duration)
1241 (define (time-at-midnight time)
1242 ;; Return TIME at midnight by setting nanoseconds, seconds, minutes, and
1244 (let ((d (time-utc->date time)))
1247 (date-day d) (date-month d)
1248 (date-year d) (date-zone-offset d)))))
1250 (define generation-ctime-alist
1251 (map (lambda (number)
1255 (generation-time profile number)))))
1256 (generation-numbers profile)))
1261 (let ((s (time-second
1262 (subtract-duration (time-at-midnight (current-time))
1264 (delete #f (map (lambda (x)
1265 (and (duration-relation s (cdr x))
1267 generation-ctime-alist))))))
1269 (cond ((string->generations str)
1272 ((string->duration str)
1277 (define (display-generation profile number)
1278 "Display a one-line summary of generation NUMBER of PROFILE."
1279 (unless (zero? number)
1280 (let ((header (format #f (G_ "Generation ~a\t~a") number
1283 (generation-time profile number))
1285 (current (generation-number profile)))
1286 (if (= number current)
1287 ;; TRANSLATORS: The word "current" here is an adjective for
1288 ;; "Generation", as in "current generation". Use the appropriate
1289 ;; gender where applicable.
1290 (format #t (G_ "~a\t(current)~%") header)
1291 (format #t "~a~%" header)))))
1293 (define (display-profile-content-diff profile gen1 gen2)
1294 "Display the changed packages in PROFILE GEN2 compared to generation GEN2."
1296 (define (equal-entry? first second)
1297 (string= (manifest-entry-item first) (manifest-entry-item second)))
1299 (define (display-entry entry prefix)
1301 (($ <manifest-entry> name version output location _)
1302 (format #t " ~a ~a\t~a\t~a\t~a~%" prefix name version output location))))
1304 (define (list-entries number)
1305 (manifest-entries (profile-manifest (generation-file-name profile number))))
1307 (define (display-diff profile old new)
1308 (display-generation profile new)
1309 (let ((added (lset-difference
1310 equal-entry? (list-entries new) (list-entries old)))
1311 (removed (lset-difference
1312 equal-entry? (list-entries old) (list-entries new))))
1313 (for-each (cut display-entry <> "+") added)
1314 (for-each (cut display-entry <> "-") removed)
1317 (display-diff profile gen1 gen2))
1319 (define (display-profile-content profile number)
1320 "Display the packages in PROFILE, generation NUMBER, in a human-readable
1322 (for-each (match-lambda
1323 (($ <manifest-entry> name version output location _)
1324 (format #t " ~a\t~a\t~a\t~a~%"
1325 name version output location)))
1327 ;; Show most recently installed packages last.
1330 (profile-manifest (generation-file-name profile number))))))
1332 (define (display-generation-change previous current)
1333 (format #t (G_ "switched from generation ~a to ~a~%") previous current))
1335 (define (roll-back* store profile)
1336 "Like 'roll-back', but display what is happening."
1339 (roll-back store profile))
1340 display-generation-change))
1342 (define (switch-to-generation* profile number)
1343 "Like 'switch-generation', but display what is happening."
1344 (let ((previous (switch-to-generation profile number)))
1345 (display-generation-change previous number)))
1347 (define (delete-generation* store profile generation)
1348 "Like 'delete-generation', but display what is going on."
1349 (format #t (G_ "deleting ~a~%")
1350 (generation-file-name profile generation))
1351 (delete-generation store profile generation))
1353 (define* (package-specification->name+version+output spec
1354 #:optional (output "out"))
1355 "Parse package specification SPEC and return three value: the specified
1356 package name, version number (or #f), and output name (or OUTPUT). SPEC may
1357 optionally contain a version number and an output name, as in these examples:
1364 (let*-values (((name sub-drv)
1365 (match (string-rindex spec #\:)
1366 (#f (values spec output))
1367 (colon (values (substring spec 0 colon)
1368 (substring spec (+ 1 colon))))))
1370 (package-name->name+version name)))
1371 (values name version sub-drv)))
1375 ;;; Command-line option processing.
1378 (define (show-guix-usage)
1379 (format (current-error-port)
1380 (G_ "Try `guix --help' for more information.~%"))
1383 (define (command-files)
1384 "Return the list of source files that define Guix sub-commands."
1386 (and=> (search-path %load-path "guix.scm")
1387 (compose (cut string-append <> "/guix/scripts")
1391 (cut string-suffix? ".scm" <>))
1394 (scandir directory dot-scm?)
1398 "Return the list of Guix command names."
1399 (map (compose (cut string-drop-right <> 4)
1403 (define (show-guix-help)
1404 (define (internal? command)
1405 (member command '("substitute" "authenticate" "offload"
1406 "perform-download")))
1408 (format #t (G_ "Usage: guix COMMAND ARGS...
1409 Run COMMAND with ARGS.\n"))
1411 (format #t (G_ "COMMAND must be one of the sub-commands listed below:\n"))
1413 ;; TODO: Display a synopsis of each command.
1414 (format #t "~{ ~a~%~}" (sort (remove internal? (commands))
1416 (show-bug-report-information))
1418 (define program-name
1419 ;; Name of the command-line program currently executing, or #f.
1420 (make-parameter #f))
1422 (define (run-guix-command command . args)
1423 "Run COMMAND with the given ARGS. Report an error when COMMAND is not
1428 (resolve-interface `(guix scripts ,command)))
1430 (format (current-error-port)
1431 (G_ "guix: ~a: command not found~%") command)
1432 (show-guix-usage))))
1434 (let ((command-main (module-ref module
1435 (symbol-append 'guix- command))))
1436 (parameterize ((program-name command))
1437 ;; Disable canonicalization so we don't don't stat unreasonably.
1438 (with-fluids ((%file-port-name-canonicalization #f))
1442 (apply command-main args))
1444 ;; Abuse 'exit-hook' (which is normally meant to be used by the
1445 ;; REPL) to run things like profiling hooks upon completion.
1446 (run-hook exit-hook)))))))
1448 (define (run-guix . args)
1449 "Run the 'guix' command defined by command line ARGS.
1450 Unlike 'guix-main', this procedure assumes that locale, i18n support,
1451 and signal handling has already been set up."
1452 (define option? (cut string-prefix? "-" <>))
1454 ;; The default %LOAD-EXTENSIONS includes the empty string, which doubles the
1455 ;; number of 'stat' calls per entry in %LOAD-PATH. Shamelessly remove it.
1456 (set! %load-extensions '(".scm"))
1460 (format (current-error-port)
1461 (G_ "guix: missing command name~%"))
1463 ((or ("-h") ("--help"))
1466 (show-version-and-exit "guix"))
1467 (((? option? o) args ...)
1468 (format (current-error-port)
1469 (G_ "guix: unrecognized option '~a'~%") o)
1472 (apply run-guix-command (string->symbol command)
1477 (apply run-guix-command
1478 (string->symbol command)
1481 (define guix-warning-port
1482 (make-parameter (current-warning-port)))
1484 (define (guix-main arg0 . args)
1486 (apply run-guix args))
1488 ;;; ui.scm ends here