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