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