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