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