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