Merge branch 'master' into core-updates
[jackhill/guix/guix.git] / guix / ui.scm
1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2012, 2013, 2014, 2015, 2016, 2017, 2018 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 ;;;
13 ;;; This file is part of GNU Guix.
14 ;;;
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.
19 ;;;
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.
24 ;;;
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/>.
27
28 (define-module (guix ui)
29 #:use-module (guix i18n)
30 #:use-module (guix gexp)
31 #:use-module (guix sets)
32 #:use-module (guix utils)
33 #:use-module (guix store)
34 #:use-module (guix config)
35 #:use-module (guix packages)
36 #:use-module (guix profiles)
37 #:use-module (guix derivations)
38 #:use-module (guix combinators)
39 #:use-module (guix build-system)
40 #:use-module (guix serialization)
41 #:use-module ((guix licenses) #:select (license? license-name))
42 #:use-module ((guix build syscalls)
43 #:select (free-disk-space terminal-columns))
44 #:use-module ((guix build utils)
45 #:select (invoke-error? invoke-error-program
46 invoke-error-arguments
47 invoke-error-exit-status
48 invoke-error-term-signal
49 invoke-error-stop-signal))
50 #:use-module (srfi srfi-1)
51 #:use-module (srfi srfi-11)
52 #:use-module (srfi srfi-19)
53 #:use-module (srfi srfi-26)
54 #:use-module (srfi srfi-31)
55 #:use-module (srfi srfi-34)
56 #:use-module (srfi srfi-35)
57 #:autoload (ice-9 ftw) (scandir)
58 #:use-module (ice-9 match)
59 #:use-module (ice-9 format)
60 #:use-module (ice-9 regex)
61 #:autoload (system base compile) (compile-file)
62 #:autoload (system repl repl) (start-repl)
63 #:autoload (system repl debug) (make-debug stack->vector)
64 #:use-module (texinfo)
65 #:use-module (texinfo plain-text)
66 #:use-module (texinfo string-utils)
67 #:re-export (G_ N_ P_) ;backward compatibility
68 #:export (report-error
69 display-hint
70 leave
71 make-user-module
72 load*
73 warn-about-load-error
74 show-version-and-exit
75 show-bug-report-information
76 make-regexp*
77 string->number*
78 size->number
79 show-derivation-outputs
80 show-what-to-build
81 show-what-to-build*
82 show-manifest-transaction
83 call-with-error-handling
84 with-error-handling
85 leave-on-EPIPE
86 read/eval
87 read/eval-package-expression
88 location->string
89 fill-paragraph
90 %text-width
91 texi->plain-text
92 package-description-string
93 package-synopsis-string
94 string->recutils
95 package->recutils
96 package-specification->name+version+output
97 relevance
98 package-relevance
99 string->generations
100 string->duration
101 matching-generations
102 display-generation
103 display-profile-content
104 display-profile-content-diff
105 roll-back*
106 switch-to-generation*
107 delete-generation*
108 run-guix-command
109 run-guix
110 program-name
111 guix-warning-port
112 warning
113 info
114 guix-main))
115
116 ;;; Commentary:
117 ;;;
118 ;;; User interface facilities for command-line tools.
119 ;;;
120 ;;; Code:
121
122 (define-syntax-rule (define-diagnostic name prefix)
123 "Create a diagnostic macro (i.e., NAME), which will prepend PREFIX to all
124 messages."
125 (define-syntax name
126 (lambda (x)
127 (define (augmented-format-string fmt)
128 (string-append "~:[~*~;guix ~a: ~]~a" (syntax->datum fmt)))
129
130 (syntax-case x ()
131 ((name (underscore fmt) args (... ...))
132 (and (string? (syntax->datum #'fmt))
133 (free-identifier=? #'underscore #'G_))
134 (with-syntax ((fmt* (augmented-format-string #'fmt))
135 (prefix (datum->syntax x prefix)))
136 #'(format (guix-warning-port) (gettext fmt*)
137 (program-name) (program-name) prefix
138 args (... ...))))
139 ((name (N-underscore singular plural n) args (... ...))
140 (and (string? (syntax->datum #'singular))
141 (string? (syntax->datum #'plural))
142 (free-identifier=? #'N-underscore #'N_))
143 (with-syntax ((s (augmented-format-string #'singular))
144 (p (augmented-format-string #'plural))
145 (prefix (datum->syntax x prefix)))
146 #'(format (guix-warning-port)
147 (ngettext s p n %gettext-domain)
148 (program-name) (program-name) prefix
149 args (... ...))))))))
150
151 (define-diagnostic warning "warning: ") ; emit a warning
152 (define-diagnostic info "")
153
154 (define-diagnostic report-error "error: ")
155 (define-syntax-rule (leave args ...)
156 "Emit an error message and exit."
157 (begin
158 (report-error args ...)
159 (exit 1)))
160
161 (define (print-unbound-variable-error port key args default-printer)
162 ;; Print unbound variable errors more nicely, and in the right language.
163 (match args
164 ((proc message (variable) _ ...)
165 ;; We can always omit PROC because when it's useful (i.e., different from
166 ;; "module-lookup"), it gets displayed before.
167 (format port (G_ "~a: unbound variable") variable))
168 (_
169 (default-printer))))
170
171 (set-exception-printer! 'unbound-variable print-unbound-variable-error)
172
173 (define (make-user-module modules)
174 "Return a new user module with the additional MODULES loaded."
175 ;; Module in which the machine description file is loaded.
176 (let ((module (make-fresh-user-module)))
177 (for-each (lambda (iface)
178 (module-use! module (resolve-interface iface)))
179 modules)
180 module))
181
182 (define* (load* file user-module
183 #:key (on-error 'nothing-special))
184 "Load the user provided Scheme source code FILE."
185 (define (frame-with-source frame)
186 ;; Walk from FRAME upwards until source location information is found.
187 (let loop ((frame frame)
188 (previous frame))
189 (if (not frame)
190 previous
191 (if (frame-source frame)
192 frame
193 (loop (frame-previous frame) frame)))))
194
195 (define (error-string frame args)
196 (call-with-output-string
197 (lambda (port)
198 (apply display-error frame port (cdr args)))))
199
200 (define tag
201 (make-prompt-tag "user-code"))
202
203 (catch #t
204 (lambda ()
205 ;; XXX: Force a recompilation to avoid ABI issues.
206 ;;
207 ;; In 2.2.3, the bogus answer to <https://bugs.gnu.org/29226> was to
208 ;; ignore all available .go, not just those from ~/.cache, which in turn
209 ;; meant that we had to rebuild *everything*. Since this is too costly,
210 ;; we have to turn off '%fresh-auto-compile' with that version, so to
211 ;; avoid ABI breakage in the user's config file, we explicitly compile
212 ;; it (the problem remains if the user's config is spread on several
213 ;; modules.) See <https://bugs.gnu.org/29881>.
214 (unless (string=? (version) "2.2.3")
215 (set! %fresh-auto-compile #t))
216
217 (set! %load-should-auto-compile #t)
218
219 (save-module-excursion
220 (lambda ()
221 (set-current-module user-module)
222
223 ;; Hide the "auto-compiling" messages.
224 (parameterize ((current-warning-port (%make-void-port "w")))
225 (call-with-prompt tag
226 (lambda ()
227 (when (string=? (version) "2.2.3")
228 (catch 'system-error
229 (lambda ()
230 (compile-file file #:env user-module))
231 (const #f))) ;EACCES maybe, let's interpret it
232
233 ;; Give 'load' an absolute file name so that it doesn't try to
234 ;; search for FILE in %LOAD-PATH. Note: use 'load', not
235 ;; 'primitive-load', so that FILE is compiled, which then allows us
236 ;; to provide better error reporting with source line numbers.
237 (load (canonicalize-path file)))
238 (const #f))))))
239 (lambda _
240 ;; XXX: Errors are reported from the pre-unwind handler below, but
241 ;; calling 'exit' from there has no effect, so we call it here.
242 (exit 1))
243 (rec (handle-error . args)
244 ;; Capture the stack up to this procedure call, excluded, and pass
245 ;; the faulty stack frame to 'report-load-error'.
246 (let* ((stack (make-stack #t handle-error tag))
247 (depth (stack-length stack))
248 (last (and (> depth 0) (stack-ref stack 0)))
249 (frame (frame-with-source
250 (if (> depth 1)
251 (stack-ref stack 1) ;skip the 'throw' frame
252 last))))
253
254 (report-load-error file args frame)
255
256 (case on-error
257 ((debug)
258 (newline)
259 (display (G_ "entering debugger; type ',bt' for a backtrace\n"))
260 (start-repl #:debug (make-debug (stack->vector stack) 0
261 (error-string frame args)
262 #f)))
263 ((backtrace)
264 (newline (current-error-port))
265 (display-backtrace stack (current-error-port)))
266 (else
267 #t))))))
268
269 (define (known-variable-definition variable)
270 "Search among the currently loaded modules one that defines a variable named
271 VARIABLE and return it, or #f if none was found."
272 (define (module<? m1 m2)
273 (match (module-name m2)
274 (('gnu _ ...) #t)
275 (('guix _ ...)
276 (match (module-name m1)
277 (('gnu _ ...) #f)
278 (_ #t)))
279 (_ #f)))
280
281 (let loop ((modules (list (resolve-module '() #f #f #:ensure #f)))
282 (suggestions '())
283 (visited (setq)))
284 (match modules
285 (()
286 ;; Pick the "best" suggestion.
287 (match (sort suggestions module<?)
288 (() #f)
289 ((first _ ...) first)))
290 ((head tail ...)
291 (if (set-contains? visited head)
292 (loop tail suggestions visited)
293 (let ((visited (set-insert head visited))
294 (next (append tail
295 (hash-map->list (lambda (name module)
296 module)
297 (module-submodules head)))))
298 (match (module-local-variable head variable)
299 (#f (loop next suggestions visited))
300 (_
301 (match (module-name head)
302 (('gnu _ ...) head) ;must be that one
303 (_ (loop next (cons head suggestions) visited)))))))))))
304
305 (define* (display-hint message #:optional (port (current-error-port)))
306 "Display MESSAGE, a l10n message possibly containing Texinfo markup, to
307 PORT."
308 (format port (G_ "hint: ~a~%")
309 ;; XXX: We should arrange so that the initial indent is wider.
310 (parameterize ((%text-width (max 15
311 (- (terminal-columns) 5))))
312 (texi->plain-text message))))
313
314 (define* (report-load-error file args #:optional frame)
315 "Report the failure to load FILE, a user-provided Scheme file.
316 ARGS is the list of arguments received by the 'throw' handler."
317 (match args
318 (('system-error . rest)
319 (let ((err (system-error-errno args)))
320 (report-error (G_ "failed to load '~a': ~a~%") file (strerror err))))
321 (('read-error "scm_i_lreadparen" message _ ...)
322 ;; Guile's missing-paren messages are obscure so we make them more
323 ;; intelligible here.
324 (if (string-suffix? "end of file" message)
325 (let ((location (string-drop-right message
326 (string-length "end of file"))))
327 (format (current-error-port) (G_ "~amissing closing parenthesis~%")
328 location))
329 (apply throw args)))
330 (('syntax-error proc message properties form . rest)
331 (let ((loc (source-properties->location properties)))
332 (format (current-error-port) (G_ "~a: error: ~a~%")
333 (location->string loc) message)))
334 (('unbound-variable proc message (variable) _ ...)
335 (match args
336 ((key . args)
337 (print-exception (current-error-port) frame key args)))
338 (match (known-variable-definition variable)
339 (#f
340 (display-hint (G_ "Did you forget a @code{use-modules} form?")))
341 (module
342 (display-hint (format #f (G_ "Did you forget @code{(use-modules ~a)}?")
343 (module-name module))))))
344 (('srfi-34 obj)
345 (if (message-condition? obj)
346 (if (error-location? obj)
347 (format (current-error-port)
348 (G_ "~a: error: ~a~%")
349 (location->string (error-location obj))
350 (gettext (condition-message obj)
351 %gettext-domain))
352 (report-error (G_ "~a~%")
353 (gettext (condition-message obj)
354 %gettext-domain)))
355 (report-error (G_ "exception thrown: ~s~%") obj))
356 (when (fix-hint? obj)
357 (display-hint (condition-fix-hint obj))))
358 ((error args ...)
359 (report-error (G_ "failed to load '~a':~%") file)
360 (apply display-error frame (current-error-port) args))))
361
362 (define (warn-about-load-error file args) ;FIXME: factorize with ↑
363 "Report the failure to load FILE, a user-provided Scheme file, without
364 exiting. ARGS is the list of arguments received by the 'throw' handler."
365 (match args
366 (('system-error . rest)
367 (let ((err (system-error-errno args)))
368 (warning (G_ "failed to load '~a': ~a~%") file (strerror err))))
369 (('syntax-error proc message properties form . rest)
370 (let ((loc (source-properties->location properties)))
371 (format (current-error-port) (G_ "~a: warning: ~a~%")
372 (location->string loc) message)))
373 (('srfi-34 obj)
374 (if (message-condition? obj)
375 (warning (G_ "failed to load '~a': ~a~%")
376 file
377 (gettext (condition-message obj) %gettext-domain))
378 (warning (G_ "failed to load '~a': exception thrown: ~s~%")
379 file obj)))
380 ((error args ...)
381 (warning (G_ "failed to load '~a':~%") file)
382 (apply display-error #f (current-error-port) args))))
383
384 (define (install-locale)
385 "Install the current locale settings."
386 (catch 'system-error
387 (lambda _
388 (setlocale LC_ALL ""))
389 (lambda args
390 (warning (G_ "failed to install locale: ~a~%")
391 (strerror (system-error-errno args))))))
392
393 (define (initialize-guix)
394 "Perform the usual initialization for stand-alone Guix commands."
395 ;; By default don't annoy users with deprecation warnings. In practice,
396 ;; 'define-deprecated' in (ice-9 deprecated) arranges so that those warnings
397 ;; are emitted at expansion-time only, but there are cases where they could
398 ;; slip through, for instance when interpreting code.
399 (unless (getenv "GUILE_WARN_DEPRECATED")
400 (debug-disable 'warn-deprecated))
401
402 (install-locale)
403 (textdomain %gettext-domain)
404
405 ;; Ignore SIGPIPE. If the daemon closes the connection, we prefer to be
406 ;; notified via an EPIPE later.
407 (sigaction SIGPIPE SIG_IGN)
408
409 (setvbuf (current-output-port) _IOLBF)
410 (setvbuf (current-error-port) _IOLBF))
411
412 (define* (show-version-and-exit #:optional (command (car (command-line))))
413 "Display version information for COMMAND and `(exit 0)'."
414 (simple-format #t "~a (~a) ~a~%"
415 command %guix-package-name %guix-version)
416 (format #t "Copyright ~a 2018 ~a"
417 ;; TRANSLATORS: Translate "(C)" to the copyright symbol
418 ;; (C-in-a-circle), if this symbol is available in the user's
419 ;; locale. Otherwise, do not translate "(C)"; leave it as-is. */
420 (G_ "(C)")
421 (G_ "the Guix authors\n"))
422 (display (G_"\
423 License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
424 This is free software: you are free to change and redistribute it.
425 There is NO WARRANTY, to the extent permitted by law.
426 "))
427 (exit 0))
428
429 (define (show-bug-report-information)
430 ;; TRANSLATORS: The placeholder indicates the bug-reporting address for this
431 ;; package. Please add another line saying "Report translation bugs to
432 ;; ...\n" with the address for translation bugs (typically your translation
433 ;; team's web or email address).
434 (format #t (G_ "
435 Report bugs to: ~a.") %guix-bug-report-address)
436 (format #t (G_ "
437 ~a home page: <~a>") %guix-package-name %guix-home-page-url)
438 (display (G_ "
439 General help using GNU software: <http://www.gnu.org/gethelp/>"))
440 (newline))
441
442 (define (augmented-system-error-handler file)
443 "Return a 'system-error' handler that mentions FILE in its message."
444 (lambda (key proc fmt args errno)
445 ;; Augment the FMT and ARGS with information about TARGET (this
446 ;; information is missing as of Guile 2.0.11, making the exception
447 ;; uninformative.)
448 (apply throw key proc "~A: ~S"
449 (list (strerror (car errno)) file)
450 (list errno))))
451
452 (define-syntax-rule (error-reporting-wrapper proc (args ...) file)
453 "Wrap PROC such that its 'system-error' exceptions are augmented to mention
454 FILE."
455 (let ((real-proc (@ (guile) proc)))
456 (lambda (args ...)
457 (catch 'system-error
458 (lambda ()
459 (real-proc args ...))
460 (augmented-system-error-handler file)))))
461
462 (set! symlink
463 ;; We 'set!' the global binding because (gnu build ...) modules and similar
464 ;; typically don't use (guix ui).
465 (error-reporting-wrapper symlink (source target) target))
466
467 (set! copy-file
468 ;; Note: here we use 'set!', not #:replace, because UIs typically use
469 ;; 'copy-recursively', which doesn't use (guix ui).
470 (error-reporting-wrapper copy-file (source target) target))
471
472 (set! canonicalize-path
473 (error-reporting-wrapper canonicalize-path (file) file))
474
475
476 (define (make-regexp* regexp . flags)
477 "Like 'make-regexp' but error out if REGEXP is invalid, reporting the error
478 nicely."
479 (catch 'regular-expression-syntax
480 (lambda ()
481 (apply make-regexp regexp flags))
482 (lambda (key proc message . rest)
483 (leave (G_ "'~a' is not a valid regular expression: ~a~%")
484 regexp message))))
485
486 (define (string->number* str)
487 "Like `string->number', but error out with an error message on failure."
488 (or (string->number str)
489 (leave (G_ "~a: invalid number~%") str)))
490
491 (define (size->number str)
492 "Convert STR, a storage measurement representation such as \"1024\" or
493 \"1MiB\", to a number of bytes. Raise an error if STR could not be
494 interpreted."
495 (define unit-pos
496 (string-rindex str char-set:digit))
497
498 (define unit
499 (and unit-pos (substring str (+ 1 unit-pos))))
500
501 (let* ((numstr (if unit-pos
502 (substring str 0 (+ 1 unit-pos))
503 str))
504 (num (string->number numstr)))
505 (unless num
506 (leave (G_ "invalid number: ~a~%") numstr))
507
508 ((compose inexact->exact round)
509 (* num
510 (match unit
511 ((or "KiB" "K" "k") (expt 2 10))
512 ((or "MiB" "M") (expt 2 20))
513 ((or "GiB" "G") (expt 2 30))
514 ((or "TiB" "T") (expt 2 40))
515 ((or "PiB" "P") (expt 2 50))
516 ((or "EiB" "E") (expt 2 60))
517 ((or "ZiB" "Z") (expt 2 70))
518 ((or "YiB" "Y") (expt 2 80))
519 ("kB" (expt 10 3))
520 ("MB" (expt 10 6))
521 ("GB" (expt 10 9))
522 ("TB" (expt 10 12))
523 ("PB" (expt 10 15))
524 ("EB" (expt 10 18))
525 ("ZB" (expt 10 21))
526 ("YB" (expt 10 24))
527 ("" 1)
528 (x
529 (leave (G_ "unknown unit: ~a~%") unit)))))))
530
531 (define (display-collision-resolution-hint collision)
532 "Display hints on how to resolve COLLISION, a &profile-collistion-error."
533 (define (top-most-entry entry)
534 (let loop ((entry entry))
535 (match (force (manifest-entry-parent entry))
536 (#f entry)
537 (parent (loop parent)))))
538
539 (let* ((first (profile-collision-error-entry collision))
540 (second (profile-collision-error-conflict collision))
541 (name1 (manifest-entry-name (top-most-entry first)))
542 (name2 (manifest-entry-name (top-most-entry second))))
543 (if (string=? name1 name2)
544 (display-hint (format #f (G_ "You cannot have two different versions
545 or variants of @code{~a} in the same profile.")
546 name1))
547 (display-hint (format #f (G_ "Try upgrading both @code{~a} and @code{~a},
548 or remove one of them from the profile.")
549 name1 name2)))))
550
551 (define (call-with-error-handling thunk)
552 "Call THUNK within a user-friendly error handler."
553 (define (port-filename* port)
554 ;; 'port-filename' returns #f for non-file ports, but it raises an
555 ;; exception for file ports that are closed. Work around that.
556 (and (not (port-closed? port))
557 (port-filename port)))
558
559 (guard (c ((package-input-error? c)
560 (let* ((package (package-error-package c))
561 (input (package-error-invalid-input c))
562 (location (package-location package))
563 (file (location-file location))
564 (line (location-line location))
565 (column (location-column location)))
566 (leave (G_ "~a:~a:~a: package `~a' has an invalid input: ~s~%")
567 file line column
568 (package-full-name package) input)))
569 ((package-cross-build-system-error? c)
570 (let* ((package (package-error-package c))
571 (loc (package-location package))
572 (system (package-build-system package)))
573 (leave (G_ "~a: ~a: build system `~a' does not support cross builds~%")
574 (location->string loc)
575 (package-full-name package)
576 (build-system-name system))))
577 ((gexp-input-error? c)
578 (let ((input (package-error-invalid-input c)))
579 (leave (G_ "~s: invalid G-expression input~%")
580 (gexp-error-invalid-input c))))
581 ((profile-not-found-error? c)
582 (leave (G_ "profile '~a' does not exist~%")
583 (profile-error-profile c)))
584 ((missing-generation-error? c)
585 (leave (G_ "generation ~a of profile '~a' does not exist~%")
586 (missing-generation-error-generation c)
587 (profile-error-profile c)))
588 ((profile-collision-error? c)
589 (let ((entry (profile-collision-error-entry c))
590 (conflict (profile-collision-error-conflict c)))
591 (define (report-parent-entries entry)
592 (let ((parent (force (manifest-entry-parent entry))))
593 (when (manifest-entry? parent)
594 (report-error (G_ " ... propagated from ~a@~a~%")
595 (manifest-entry-name parent)
596 (manifest-entry-version parent))
597 (report-parent-entries parent))))
598
599 (define (manifest-entry-output* entry)
600 (match (manifest-entry-output entry)
601 ("out" "")
602 (output (string-append ":" output))))
603
604 (report-error (G_ "profile contains conflicting entries for ~a~a~%")
605 (manifest-entry-name entry)
606 (manifest-entry-output* entry))
607 (report-error (G_ " first entry: ~a@~a~a ~a~%")
608 (manifest-entry-name entry)
609 (manifest-entry-version entry)
610 (manifest-entry-output* entry)
611 (manifest-entry-item entry))
612 (report-parent-entries entry)
613 (report-error (G_ " second entry: ~a@~a~a ~a~%")
614 (manifest-entry-name conflict)
615 (manifest-entry-version conflict)
616 (manifest-entry-output* conflict)
617 (manifest-entry-item conflict))
618 (report-parent-entries conflict)
619 (display-collision-resolution-hint c)
620 (exit 1)))
621 ((nar-error? c)
622 (let ((file (nar-error-file c))
623 (port (nar-error-port c)))
624 (if file
625 (leave (G_ "corrupt input while restoring '~a' from ~s~%")
626 file (or (port-filename* port) port))
627 (leave (G_ "corrupt input while restoring archive from ~s~%")
628 (or (port-filename* port) port)))))
629 ((nix-connection-error? c)
630 (leave (G_ "failed to connect to `~a': ~a~%")
631 (nix-connection-error-file c)
632 (strerror (nix-connection-error-code c))))
633 ((nix-protocol-error? c)
634 ;; FIXME: Server-provided error messages aren't i18n'd.
635 (leave (G_ "build failed: ~a~%")
636 (nix-protocol-error-message c)))
637 ((derivation-missing-output-error? c)
638 (leave (G_ "reference to invalid output '~a' of derivation '~a'~%")
639 (derivation-missing-output c)
640 (derivation-file-name (derivation-error-derivation c))))
641 ((file-search-error? c)
642 (leave (G_ "file '~a' could not be found in these \
643 directories:~{ ~a~}~%")
644 (file-search-error-file-name c)
645 (file-search-error-search-path c)))
646 ((invoke-error? c)
647 (leave (G_ "program exited\
648 ~@[ with non-zero exit status ~a~]\
649 ~@[ terminated by signal ~a~]\
650 ~@[ stopped by signal ~a~]: ~s~%")
651 (invoke-error-exit-status c)
652 (invoke-error-term-signal c)
653 (invoke-error-stop-signal c)
654 (cons (invoke-error-program c)
655 (invoke-error-arguments c))))
656 ((and (error-location? c) (message-condition? c))
657 (format (current-error-port)
658 (G_ "~a: error: ~a~%")
659 (location->string (error-location c))
660 (gettext (condition-message c) %gettext-domain))
661 (when (fix-hint? c)
662 (display-hint (condition-fix-hint c)))
663 (exit 1))
664 ((and (message-condition? c) (fix-hint? c))
665 (format (current-error-port) "~a: error: ~a~%"
666 (program-name)
667 (gettext (condition-message c) %gettext-domain))
668 (display-hint (condition-fix-hint c))
669 (exit 1))
670 ((message-condition? c)
671 ;; Normally '&message' error conditions have an i18n'd message.
672 (leave (G_ "~a~%")
673 (gettext (condition-message c) %gettext-domain))))
674 ;; Catch EPIPE and the likes.
675 (catch 'system-error
676 thunk
677 (lambda (key proc format-string format-args . rest)
678 (leave (G_ "~a: ~a~%") proc
679 (apply format #f format-string format-args))))))
680
681 (define-syntax-rule (leave-on-EPIPE exp ...)
682 "Run EXP... in a context when EPIPE errors are caught and lead to 'exit'
683 with successful exit code. This is useful when writing to the standard output
684 may lead to EPIPE, because the standard output is piped through 'head' or
685 similar."
686 (catch 'system-error
687 (lambda ()
688 exp ...)
689 (lambda args
690 ;; We really have to exit this brutally, otherwise Guile eventually
691 ;; attempts to flush all the ports, leading to an uncaught EPIPE down
692 ;; the path.
693 (if (= EPIPE (system-error-errno args))
694 (primitive-_exit 0)
695 (apply throw args)))))
696
697 (define %guix-user-module
698 ;; Module in which user expressions are evaluated.
699 ;; Compute lazily to avoid circularity with (guix gexp).
700 (delay
701 (let ((module (make-module)))
702 (beautify-user-module! module)
703 ;; Use (guix gexp) so that one can use #~ & co.
704 (module-use! module (resolve-interface '(guix gexp)))
705 module)))
706
707 (define (read/eval str)
708 "Read and evaluate STR, raising an error if something goes wrong."
709 (let ((exp (catch #t
710 (lambda ()
711 (call-with-input-string str read))
712 (lambda args
713 (leave (G_ "failed to read expression ~s: ~s~%")
714 str args)))))
715 (catch #t
716 (lambda ()
717 (eval exp (force %guix-user-module)))
718 (lambda args
719 (report-error (G_ "failed to evaluate expression '~a':~%") exp)
720 (match args
721 (('syntax-error proc message properties form . rest)
722 (report-error (G_ "syntax error: ~a~%") message))
723 (('srfi-34 obj)
724 (if (message-condition? obj)
725 (report-error (G_ "~a~%")
726 (gettext (condition-message obj)
727 %gettext-domain))
728 (report-error (G_ "exception thrown: ~s~%") obj)))
729 ((error args ...)
730 (apply display-error #f (current-error-port) args))
731 (what? #f))
732 (exit 1)))))
733
734 (define (read/eval-package-expression str)
735 "Read and evaluate STR and return the package it refers to, or exit an
736 error."
737 (match (read/eval str)
738 ((? package? p) p)
739 (x
740 (leave (G_ "expression ~s does not evaluate to a package~%")
741 str))))
742
743 (define (show-derivation-outputs derivation)
744 "Show the output file names of DERIVATION."
745 (format #t "~{~a~%~}"
746 (map (match-lambda
747 ((out-name . out)
748 (derivation->output-path derivation out-name)))
749 (derivation-outputs derivation))))
750
751 (define (check-available-space need)
752 "Make sure at least NEED bytes are available in the store. Otherwise emit a
753 warning."
754 (let ((free (catch 'system-error
755 (lambda ()
756 (free-disk-space (%store-prefix)))
757 (const #f))))
758 (when (and free (>= need free))
759 (warning (G_ "at least ~,1h MB needed but only ~,1h MB available in ~a~%")
760 (/ need 1e6) (/ free 1e6) (%store-prefix)))))
761
762 (define* (show-what-to-build store drv
763 #:key dry-run? (use-substitutes? #t)
764 (mode (build-mode normal)))
765 "Show what will or would (depending on DRY-RUN?) be built in realizing the
766 derivations listed in DRV using MODE, a 'build-mode' value. Return #t if
767 there's something to build, #f otherwise. When USE-SUBSTITUTES?, check and
768 report what is prerequisites are available for download."
769 (define substitutable-info
770 ;; Call 'substitutation-oracle' upfront so we don't end up launching the
771 ;; substituter many times. This makes a big difference, especially when
772 ;; DRV is a long list as is the case with 'guix environment'.
773 (if use-substitutes?
774 (substitution-oracle store drv #:mode mode)
775 (const #f)))
776
777 (define (built-or-substitutable? drv)
778 (or (null? (derivation-outputs drv))
779 (let ((out (derivation->output-path drv))) ;XXX: assume "out" exists
780 (or (valid-path? store out)
781 (substitutable-info out)))))
782
783 (let*-values (((build download)
784 (fold2 (lambda (drv build download)
785 (let-values (((b d)
786 (derivation-prerequisites-to-build
787 store drv
788 #:mode mode
789 #:substitutable-info
790 substitutable-info)))
791 (values (append b build)
792 (append d download))))
793 '() '()
794 drv))
795 ((build) ; add the DRV themselves
796 (delete-duplicates
797 (append (map derivation-file-name
798 (remove built-or-substitutable? drv))
799 (map derivation-input-path build))))
800 ((download) ; add the references of DOWNLOAD
801 (if use-substitutes?
802 (delete-duplicates
803 (append download
804 (filter-map (lambda (item)
805 (if (valid-path? store item)
806 #f
807 (substitutable-info item)))
808 (append-map
809 substitutable-references
810 download))))
811 download)))
812 (define installed-size
813 (reduce + 0 (map substitutable-nar-size download)))
814
815 (define download-size
816 (/ (reduce + 0 (map substitutable-download-size download))
817 1e6))
818
819 (define display-download-size?
820 ;; Sometimes narinfos lack information about the download size. Only
821 ;; display when we have information for all of DOWNLOAD.
822 (not (any (compose zero? substitutable-download-size) download)))
823
824 (if dry-run?
825 (begin
826 (format (current-error-port)
827 (N_ "~:[The following derivation would be built:~%~{ ~a~%~}~;~]"
828 "~:[The following derivations would be built:~%~{ ~a~%~}~;~]"
829 (length build))
830 (null? build) build)
831 (if display-download-size?
832 (format (current-error-port)
833 ;; TRANSLATORS: "MB" is for "megabyte"; it should be
834 ;; translated to the corresponding abbreviation.
835 (G_ "~:[~,1h MB would be downloaded:~%~{ ~a~%~}~;~]")
836 (null? download)
837 download-size
838 (map substitutable-path download))
839 (format (current-error-port)
840 (N_ "~:[The following file would be downloaded:~%~{ ~a~%~}~;~]"
841 "~:[The following files would be downloaded:~%~{ ~a~%~}~;~]"
842 (length download))
843 (null? download)
844 (map substitutable-path download))))
845 (begin
846 (format (current-error-port)
847 (N_ "~:[The following derivation will be built:~%~{ ~a~%~}~;~]"
848 "~:[The following derivations will be built:~%~{ ~a~%~}~;~]"
849 (length build))
850 (null? build) build)
851 (if display-download-size?
852 (format (current-error-port)
853 ;; TRANSLATORS: "MB" is for "megabyte"; it should be
854 ;; translated to the corresponding abbreviation.
855 (G_ "~:[~,1h MB will be downloaded:~%~{ ~a~%~}~;~]")
856 (null? download)
857 download-size
858 (map substitutable-path download))
859 (format (current-error-port)
860 (N_ "~:[The following file will be downloaded:~%~{ ~a~%~}~;~]"
861 "~:[The following files will be downloaded:~%~{ ~a~%~}~;~]"
862 (length download))
863 (null? download)
864 (map substitutable-path download)))))
865
866 (check-available-space installed-size)
867
868 (pair? build)))
869
870 (define show-what-to-build*
871 (store-lift show-what-to-build))
872
873 (define (right-arrow port)
874 "Return either a string containing the 'RIGHT ARROW' character, or an ASCII
875 replacement if PORT is not Unicode-capable."
876 (let ((encoding (port-encoding port))
877 (arrow "→"))
878 (catch 'encoding-error
879 (lambda ()
880 (call-with-output-string
881 (lambda (port)
882 (set-port-encoding! port encoding)
883 (set-port-conversion-strategy! port 'error)
884 (display arrow port))))
885 (lambda (key . args)
886 "->"))))
887
888 (define* (show-manifest-transaction store manifest transaction
889 #:key dry-run?)
890 "Display what will/would be installed/removed from MANIFEST by TRANSACTION."
891 (define (package-strings name version output item)
892 (map (lambda (name version output item)
893 (format #f " ~a~:[:~a~;~*~]\t~a\t~a"
894 name
895 (equal? output "out") output version
896 (if (package? item)
897 (package-output store item output)
898 item)))
899 name version output item))
900
901 (define → ;an arrow that can be represented on stderr
902 (right-arrow (current-error-port)))
903
904 (define (upgrade-string name old-version new-version output item)
905 (format #f " ~a~:[:~a~;~*~]\t~a ~a ~a\t~a"
906 name (equal? output "out") output
907 old-version → new-version
908 (if (package? item)
909 (package-output store item output)
910 item)))
911
912 (let-values (((remove install upgrade downgrade)
913 (manifest-transaction-effects manifest transaction)))
914 (match remove
915 ((($ <manifest-entry> name version output item) ..1)
916 (let ((len (length name))
917 (remove (package-strings name version output item)))
918 (if dry-run?
919 (format (current-error-port)
920 (N_ "The following package would be removed:~%~{~a~%~}~%"
921 "The following packages would be removed:~%~{~a~%~}~%"
922 len)
923 remove)
924 (format (current-error-port)
925 (N_ "The following package will be removed:~%~{~a~%~}~%"
926 "The following packages will be removed:~%~{~a~%~}~%"
927 len)
928 remove))))
929 (x #f))
930 (match downgrade
931 (((($ <manifest-entry> name old-version)
932 . ($ <manifest-entry> _ new-version output item)) ..1)
933 (let ((len (length name))
934 (downgrade (map upgrade-string
935 name old-version new-version output item)))
936 (if dry-run?
937 (format (current-error-port)
938 (N_ "The following package would be downgraded:~%~{~a~%~}~%"
939 "The following packages would be downgraded:~%~{~a~%~}~%"
940 len)
941 downgrade)
942 (format (current-error-port)
943 (N_ "The following package will be downgraded:~%~{~a~%~}~%"
944 "The following packages will be downgraded:~%~{~a~%~}~%"
945 len)
946 downgrade))))
947 (x #f))
948 (match upgrade
949 (((($ <manifest-entry> name old-version)
950 . ($ <manifest-entry> _ new-version output item)) ..1)
951 (let ((len (length name))
952 (upgrade (map upgrade-string
953 name old-version new-version output item)))
954 (if dry-run?
955 (format (current-error-port)
956 (N_ "The following package would be upgraded:~%~{~a~%~}~%"
957 "The following packages would be upgraded:~%~{~a~%~}~%"
958 len)
959 upgrade)
960 (format (current-error-port)
961 (N_ "The following package will be upgraded:~%~{~a~%~}~%"
962 "The following packages will be upgraded:~%~{~a~%~}~%"
963 len)
964 upgrade))))
965 (x #f))
966 (match install
967 ((($ <manifest-entry> name version output item _) ..1)
968 (let ((len (length name))
969 (install (package-strings name version output item)))
970 (if dry-run?
971 (format (current-error-port)
972 (N_ "The following package would be installed:~%~{~a~%~}~%"
973 "The following packages would be installed:~%~{~a~%~}~%"
974 len)
975 install)
976 (format (current-error-port)
977 (N_ "The following package will be installed:~%~{~a~%~}~%"
978 "The following packages will be installed:~%~{~a~%~}~%"
979 len)
980 install))))
981 (x #f))))
982
983 (define-syntax with-error-handling
984 (syntax-rules ()
985 "Run BODY within a user-friendly error condition handler."
986 ((_ body ...)
987 (call-with-error-handling
988 (lambda ()
989 body ...)))))
990
991 (define (location->string loc)
992 "Return a human-friendly, GNU-standard representation of LOC."
993 (match loc
994 (#f (G_ "<unknown location>"))
995 (($ <location> file line column)
996 (format #f "~a:~a:~a" file line column))))
997
998 (define* (fill-paragraph str width #:optional (column 0))
999 "Fill STR such that each line contains at most WIDTH characters, assuming
1000 that the first character is at COLUMN.
1001
1002 When STR contains a single line break surrounded by other characters, it is
1003 converted to a space; sequences of more than one line break are preserved."
1004 (define (maybe-break chr result)
1005 (match result
1006 ((column newlines chars)
1007 (case chr
1008 ((#\newline)
1009 `(,column ,(+ 1 newlines) ,chars))
1010 (else
1011 (let* ((spaces (if (and (pair? chars) (eqv? (car chars) #\.)) 2 1))
1012 (chars (case newlines
1013 ((0) chars)
1014 ((1)
1015 (append (make-list spaces #\space) chars))
1016 (else
1017 (append (make-list newlines #\newline) chars))))
1018 (column (case newlines
1019 ((0) column)
1020 ((1) (+ spaces column))
1021 (else 0))))
1022 (let ((chars (cons chr chars))
1023 (column (+ 1 column)))
1024 (if (> column width)
1025 (let*-values (((before after)
1026 (break (cut eqv? #\space <>) chars))
1027 ((len)
1028 (length before)))
1029 (if (<= len width)
1030 `(,len
1031 0
1032 ,(if (null? after)
1033 before
1034 (append before
1035 (cons #\newline
1036 (drop-while (cut eqv? #\space <>)
1037 after)))))
1038 `(,column 0 ,chars))) ; unbreakable
1039 `(,column 0 ,chars)))))))))
1040
1041 (match (string-fold maybe-break
1042 `(,column 0 ())
1043 str)
1044 ((column newlines chars)
1045 (list->string (reverse chars)))))
1046
1047 \f
1048 ;;;
1049 ;;; Packages.
1050 ;;;
1051
1052 (define %text-width
1053 (make-parameter (terminal-columns)))
1054
1055 (set! (@@ (texinfo plain-text) wrap*)
1056 ;; XXX: Monkey patch this private procedure to let 'package->recutils'
1057 ;; parameterize the fill of description field correctly.
1058 (lambda strings
1059 (let ((indent (fluid-ref (@@ (texinfo plain-text) *indent*))))
1060 (fill-string (string-concatenate strings)
1061 #:line-width (%text-width) #:initial-indent indent
1062 #:subsequent-indent indent))))
1063
1064 (define (texi->plain-text str)
1065 "Return a plain-text representation of texinfo fragment STR."
1066 ;; 'texi-fragment->stexi' uses a string port so make sure it's a
1067 ;; Unicode-capable one (see <http://bugs.gnu.org/11197>.)
1068 (with-fluids ((%default-port-encoding "UTF-8"))
1069 (stexi->plain-text (texi-fragment->stexi str))))
1070
1071 (define (package-field-string package field-accessor)
1072 "Return a plain-text representation of PACKAGE field."
1073 (and=> (field-accessor package)
1074 (compose texi->plain-text P_)))
1075
1076 (define (package-description-string package)
1077 "Return a plain-text representation of PACKAGE description field."
1078 (package-field-string package package-description))
1079
1080 (define (package-synopsis-string package)
1081 "Return a plain-text representation of PACKAGE synopsis field."
1082 (package-field-string package package-synopsis))
1083
1084 (define (string->recutils str)
1085 "Return a version of STR where newlines have been replaced by newlines
1086 followed by \"+ \", which makes for a valid multi-line field value in the
1087 `recutils' syntax."
1088 (list->string
1089 (string-fold-right (lambda (chr result)
1090 (if (eqv? chr #\newline)
1091 (cons* chr #\+ #\space result)
1092 (cons chr result)))
1093 '()
1094 str)))
1095
1096 (define* (package->recutils p port #:optional (width (%text-width))
1097 #:key (extra-fields '()))
1098 "Write to PORT a `recutils' record of package P, arranging to fit within
1099 WIDTH columns. EXTRA-FIELDS is a list of symbol/value pairs to emit."
1100 (define width*
1101 ;; The available number of columns once we've taken into account space for
1102 ;; the initial "+ " prefix.
1103 (if (> width 2) (- width 2) width))
1104
1105 (define (dependencies->recutils packages)
1106 (let ((list (string-join (delete-duplicates
1107 (map package-full-name
1108 (sort packages package<?))) " ")))
1109 (string->recutils
1110 (fill-paragraph list width*
1111 (string-length "dependencies: ")))))
1112
1113 (define (package<? p1 p2)
1114 (string<? (package-full-name p1) (package-full-name p2)))
1115
1116 ;; Note: Don't i18n field names so that people can post-process it.
1117 (format port "name: ~a~%" (package-name p))
1118 (format port "version: ~a~%" (package-version p))
1119 (format port "outputs: ~a~%" (string-join (package-outputs p)))
1120 (format port "systems: ~a~%"
1121 (string-join (package-transitive-supported-systems p)))
1122 (format port "dependencies: ~a~%"
1123 (match (package-direct-inputs p)
1124 (((labels inputs . _) ...)
1125 (dependencies->recutils (filter package? inputs)))))
1126 (format port "location: ~a~%"
1127 (or (and=> (package-location p) location->string)
1128 (G_ "unknown")))
1129
1130 ;; Note: Starting from version 1.6 or recutils, hyphens are not allowed in
1131 ;; field identifiers.
1132 (format port "homepage: ~a~%" (package-home-page p))
1133
1134 (format port "license: ~a~%"
1135 (match (package-license p)
1136 (((? license? licenses) ...)
1137 (string-join (map license-name licenses)
1138 ", "))
1139 ((? license? license)
1140 (license-name license))
1141 (x
1142 (G_ "unknown"))))
1143 (format port "synopsis: ~a~%"
1144 (string-map (match-lambda
1145 (#\newline #\space)
1146 (chr chr))
1147 (or (and=> (package-synopsis-string p) P_)
1148 "")))
1149 (format port "~a~%"
1150 (string->recutils
1151 (string-trim-right
1152 (parameterize ((%text-width width*))
1153 (texi->plain-text
1154 (string-append "description: "
1155 (or (and=> (package-description p) P_)
1156 ""))))
1157 #\newline)))
1158 (for-each (match-lambda
1159 ((field . value)
1160 (let ((field (symbol->string field)))
1161 (format port "~a: ~a~%"
1162 field
1163 (fill-paragraph (object->string value) width*
1164 (string-length field))))))
1165 extra-fields)
1166 (newline port))
1167
1168 (define (relevance obj regexps metrics)
1169 "Compute a \"relevance score\" for OBJ as a function of its number of
1170 matches of REGEXPS and accordingly to METRICS. METRICS is list of
1171 field/weight pairs, where FIELD is a procedure that returns a string
1172 describing OBJ, and WEIGHT is a positive integer denoting the weight of this
1173 field in the final score.
1174
1175 A score of zero means that OBJ does not match any of REGEXPS. The higher the
1176 score, the more relevant OBJ is to REGEXPS."
1177 (define (score str)
1178 (let ((counts (filter-map (lambda (regexp)
1179 (match (regexp-exec regexp str)
1180 (#f #f)
1181 (m (match:count m))))
1182 regexps)))
1183 ;; Compute a score that's proportional to the number of regexps matched
1184 ;; and to the number of matches for each regexp.
1185 (* (length counts) (reduce + 0 counts))))
1186
1187 (fold (lambda (metric relevance)
1188 (match metric
1189 ((field . weight)
1190 (match (field obj)
1191 (#f relevance)
1192 (str (+ relevance
1193 (* (score str) weight)))))))
1194 0
1195 metrics))
1196
1197 (define %package-metrics
1198 ;; Metrics used to compute the "relevance score" of a package against a set
1199 ;; of regexps.
1200 `((,package-name . 4)
1201 (,package-synopsis-string . 3)
1202 (,package-description-string . 2)
1203 (,(lambda (type)
1204 (match (and=> (package-location type) location-file)
1205 ((? string? file) (basename file ".scm"))
1206 (#f "")))
1207 . 1)))
1208
1209 (define (package-relevance package regexps)
1210 "Return a score denoting the relevance of PACKAGE for REGEXPS. A score of
1211 zero means that PACKAGE does not match any of REGEXPS."
1212 (relevance package regexps %package-metrics))
1213
1214 (define (string->generations str)
1215 "Return the list of generations matching a pattern in STR. This function
1216 accepts the following patterns: \"1\", \"1,2,3\", \"1..9\", \"1..\", \"..9\"."
1217 (define (maybe-integer)
1218 (let ((x (string->number str)))
1219 (and (integer? x)
1220 x)))
1221
1222 (define (maybe-comma-separated-integers)
1223 (let ((lst (delete-duplicates
1224 (map string->number
1225 (string-split str #\,)))))
1226 (and (every integer? lst)
1227 lst)))
1228
1229 (cond ((maybe-integer)
1230 =>
1231 list)
1232 ((maybe-comma-separated-integers)
1233 =>
1234 identity)
1235 ((string-match "^([0-9]+)\\.\\.([0-9]+)$" str)
1236 =>
1237 (lambda (match)
1238 (let ((s (string->number (match:substring match 1)))
1239 (e (string->number (match:substring match 2))))
1240 (and (every integer? (list s e))
1241 (<= s e)
1242 (iota (1+ (- e s)) s)))))
1243 ((string-match "^([0-9]+)\\.\\.$" str)
1244 =>
1245 (lambda (match)
1246 (let ((s (string->number (match:substring match 1))))
1247 (and (integer? s)
1248 `(>= ,s)))))
1249 ((string-match "^\\.\\.([0-9]+)$" str)
1250 =>
1251 (lambda (match)
1252 (let ((e (string->number (match:substring match 1))))
1253 (and (integer? e)
1254 `(<= ,e)))))
1255 (else #f)))
1256
1257 (define (string->duration str)
1258 "Return the duration matching a pattern in STR. This function accepts the
1259 following patterns: \"1d\", \"1w\", \"1m\"."
1260 (define (hours->duration hours match)
1261 (make-time time-duration 0
1262 (* 3600 hours (string->number (match:substring match 1)))))
1263
1264 (cond ((string-match "^([0-9]+)s$" str)
1265 =>
1266 (lambda (match)
1267 (make-time time-duration 0
1268 (string->number (match:substring match 1)))))
1269 ((string-match "^([0-9]+)h$" str)
1270 =>
1271 (lambda (match)
1272 (hours->duration 1 match)))
1273 ((string-match "^([0-9]+)d$" str)
1274 =>
1275 (lambda (match)
1276 (hours->duration 24 match)))
1277 ((string-match "^([0-9]+)w$" str)
1278 =>
1279 (lambda (match)
1280 (hours->duration (* 24 7) match)))
1281 ((string-match "^([0-9]+)m$" str)
1282 =>
1283 (lambda (match)
1284 (hours->duration (* 24 30) match)))
1285 (else #f)))
1286
1287 (define* (matching-generations str profile
1288 #:key (duration-relation <=))
1289 "Return the list of available generations matching a pattern in STR. See
1290 'string->generations' and 'string->duration' for the list of valid patterns.
1291 When STR is a duration pattern, return all the generations whose ctime has
1292 DURATION-RELATION with the current time."
1293 (define (valid-generations lst)
1294 (define (valid-generation? n)
1295 (any (cut = n <>) (generation-numbers profile)))
1296
1297 (fold-right (lambda (x acc)
1298 (if (valid-generation? x)
1299 (cons x acc)
1300 acc))
1301 '()
1302 lst))
1303
1304 (define (filter-generations generations)
1305 (match generations
1306 (() '())
1307 (('>= n)
1308 (drop-while (cut > n <>)
1309 (generation-numbers profile)))
1310 (('<= n)
1311 (valid-generations (iota n 1)))
1312 ((lst ..1)
1313 (valid-generations lst))
1314 (x #f)))
1315
1316 (define (filter-by-duration duration)
1317 (define (time-at-midnight time)
1318 ;; Return TIME at midnight by setting nanoseconds, seconds, minutes, and
1319 ;; hours to zeros.
1320 (let ((d (time-utc->date time)))
1321 (date->time-utc
1322 (make-date 0 0 0 0
1323 (date-day d) (date-month d)
1324 (date-year d) (date-zone-offset d)))))
1325
1326 (define generation-ctime-alist
1327 (map (lambda (number)
1328 (cons number
1329 (time-second
1330 (time-at-midnight
1331 (generation-time profile number)))))
1332 (generation-numbers profile)))
1333
1334 (match duration
1335 (#f #f)
1336 (res
1337 (let ((s (time-second
1338 (subtract-duration (time-at-midnight (current-time))
1339 duration))))
1340 (delete #f (map (lambda (x)
1341 (and (duration-relation s (cdr x))
1342 (first x)))
1343 generation-ctime-alist))))))
1344
1345 (cond ((string->generations str)
1346 =>
1347 filter-generations)
1348 ((string->duration str)
1349 =>
1350 filter-by-duration)
1351 (else #f)))
1352
1353 (define (display-generation profile number)
1354 "Display a one-line summary of generation NUMBER of PROFILE."
1355 (unless (zero? number)
1356 (let ((header (format #f (G_ "Generation ~a\t~a") number
1357 (date->string
1358 (time-utc->date
1359 (generation-time profile number))
1360 "~b ~d ~Y ~T")))
1361 (current (generation-number profile)))
1362 (if (= number current)
1363 ;; TRANSLATORS: The word "current" here is an adjective for
1364 ;; "Generation", as in "current generation". Use the appropriate
1365 ;; gender where applicable.
1366 (format #t (G_ "~a\t(current)~%") header)
1367 (format #t "~a~%" header)))))
1368
1369 (define (display-profile-content-diff profile gen1 gen2)
1370 "Display the changed packages in PROFILE GEN2 compared to generation GEN2."
1371
1372 (define (equal-entry? first second)
1373 (string= (manifest-entry-item first) (manifest-entry-item second)))
1374
1375 (define (display-entry entry prefix)
1376 (match entry
1377 (($ <manifest-entry> name version output location _)
1378 (format #t " ~a ~a\t~a\t~a\t~a~%" prefix name version output location))))
1379
1380 (define (list-entries number)
1381 (manifest-entries (profile-manifest (generation-file-name profile number))))
1382
1383 (define (display-diff profile old new)
1384 (display-generation profile new)
1385 (let ((added (lset-difference
1386 equal-entry? (list-entries new) (list-entries old)))
1387 (removed (lset-difference
1388 equal-entry? (list-entries old) (list-entries new))))
1389 (for-each (cut display-entry <> "+") added)
1390 (for-each (cut display-entry <> "-") removed)
1391 (newline)))
1392
1393 (display-diff profile gen1 gen2))
1394
1395 (define (display-profile-content profile number)
1396 "Display the packages in PROFILE, generation NUMBER, in a human-readable
1397 way."
1398 (for-each (match-lambda
1399 (($ <manifest-entry> name version output location _)
1400 (format #t " ~a\t~a\t~a\t~a~%"
1401 name version output location)))
1402
1403 ;; Show most recently installed packages last.
1404 (reverse
1405 (manifest-entries
1406 (profile-manifest (generation-file-name profile number))))))
1407
1408 (define (display-generation-change previous current)
1409 (format #t (G_ "switched from generation ~a to ~a~%") previous current))
1410
1411 (define (roll-back* store profile)
1412 "Like 'roll-back', but display what is happening."
1413 (call-with-values
1414 (lambda ()
1415 (roll-back store profile))
1416 display-generation-change))
1417
1418 (define (switch-to-generation* profile number)
1419 "Like 'switch-generation', but display what is happening."
1420 (let ((previous (switch-to-generation profile number)))
1421 (display-generation-change previous number)))
1422
1423 (define (delete-generation* store profile generation)
1424 "Like 'delete-generation', but display what is going on."
1425 (format #t (G_ "deleting ~a~%")
1426 (generation-file-name profile generation))
1427 (delete-generation store profile generation))
1428
1429 (define* (package-specification->name+version+output spec
1430 #:optional (output "out"))
1431 "Parse package specification SPEC and return three value: the specified
1432 package name, version number (or #f), and output name (or OUTPUT). SPEC may
1433 optionally contain a version number and an output name, as in these examples:
1434
1435 guile
1436 guile@2.0.9
1437 guile:debug
1438 guile@2.0.9:debug
1439 "
1440 (let*-values (((name sub-drv)
1441 (match (string-rindex spec #\:)
1442 (#f (values spec output))
1443 (colon (values (substring spec 0 colon)
1444 (substring spec (+ 1 colon))))))
1445 ((name version)
1446 (package-name->name+version name)))
1447 (values name version sub-drv)))
1448
1449 \f
1450 ;;;
1451 ;;; Command-line option processing.
1452 ;;;
1453
1454 (define (show-guix-usage)
1455 (format (current-error-port)
1456 (G_ "Try `guix --help' for more information.~%"))
1457 (exit 1))
1458
1459 (define (command-files)
1460 "Return the list of source files that define Guix sub-commands."
1461 (define directory
1462 (and=> (search-path %load-path "guix.scm")
1463 (compose (cut string-append <> "/guix/scripts")
1464 dirname)))
1465
1466 (define dot-scm?
1467 (cut string-suffix? ".scm" <>))
1468
1469 (if directory
1470 (scandir directory dot-scm?)
1471 '()))
1472
1473 (define (commands)
1474 "Return the list of Guix command names."
1475 (map (compose (cut string-drop-right <> 4)
1476 basename)
1477 (command-files)))
1478
1479 (define (show-guix-help)
1480 (define (internal? command)
1481 (member command '("substitute" "authenticate" "offload"
1482 "perform-download")))
1483
1484 (format #t (G_ "Usage: guix COMMAND ARGS...
1485 Run COMMAND with ARGS.\n"))
1486 (newline)
1487 (format #t (G_ "COMMAND must be one of the sub-commands listed below:\n"))
1488 (newline)
1489 ;; TODO: Display a synopsis of each command.
1490 (format #t "~{ ~a~%~}" (sort (remove internal? (commands))
1491 string<?))
1492 (show-bug-report-information))
1493
1494 (define program-name
1495 ;; Name of the command-line program currently executing, or #f.
1496 (make-parameter #f))
1497
1498 (define (run-guix-command command . args)
1499 "Run COMMAND with the given ARGS. Report an error when COMMAND is not
1500 found."
1501 (define module
1502 (catch 'misc-error
1503 (lambda ()
1504 (resolve-interface `(guix scripts ,command)))
1505 (lambda -
1506 (format (current-error-port)
1507 (G_ "guix: ~a: command not found~%") command)
1508 (show-guix-usage))))
1509
1510 (let ((command-main (module-ref module
1511 (symbol-append 'guix- command))))
1512 (parameterize ((program-name command))
1513 ;; Disable canonicalization so we don't don't stat unreasonably.
1514 (with-fluids ((%file-port-name-canonicalization #f))
1515 (dynamic-wind
1516 (const #f)
1517 (lambda ()
1518 (apply command-main args))
1519 (lambda ()
1520 ;; Abuse 'exit-hook' (which is normally meant to be used by the
1521 ;; REPL) to run things like profiling hooks upon completion.
1522 (run-hook exit-hook)))))))
1523
1524 (define (run-guix . args)
1525 "Run the 'guix' command defined by command line ARGS.
1526 Unlike 'guix-main', this procedure assumes that locale, i18n support,
1527 and signal handling has already been set up."
1528 (define option? (cut string-prefix? "-" <>))
1529
1530 ;; The default %LOAD-EXTENSIONS includes the empty string, which doubles the
1531 ;; number of 'stat' calls per entry in %LOAD-PATH. Shamelessly remove it.
1532 (set! %load-extensions '(".scm"))
1533
1534 (match args
1535 (()
1536 (format (current-error-port)
1537 (G_ "guix: missing command name~%"))
1538 (show-guix-usage))
1539 ((or ("-h") ("--help"))
1540 (show-guix-help))
1541 (("--version")
1542 (show-version-and-exit "guix"))
1543 (((? option? o) args ...)
1544 (format (current-error-port)
1545 (G_ "guix: unrecognized option '~a'~%") o)
1546 (show-guix-usage))
1547 (("help" command)
1548 (apply run-guix-command (string->symbol command)
1549 '("--help")))
1550 (("help" args ...)
1551 (show-guix-help))
1552 ((command args ...)
1553 (apply run-guix-command
1554 (string->symbol command)
1555 args))))
1556
1557 (define guix-warning-port
1558 (make-parameter (current-warning-port)))
1559
1560 (define (guix-main arg0 . args)
1561 (initialize-guix)
1562 (apply run-guix args))
1563
1564 ;;; ui.scm ends here