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