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