ui: Factorize '&message' handling.
[jackhill/guix/guix.git] / guix / ui.scm
1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Ludovic Courtès <ludo@gnu.org>
3 ;;; Copyright © 2013, 2018 Mark H Weaver <mhw@netris.org>
4 ;;; Copyright © 2013 Nikita Karetnikov <nikita@karetnikov.org>
5 ;;; Copyright © 2014 Cyril Roelandt <tipecaml@gmail.com>
6 ;;; Copyright © 2014 Cyrill Schenkel <cyrill.schenkel@gmail.com>
7 ;;; Copyright © 2014, 2015, 2017 Alex Kost <alezost@gmail.com>
8 ;;; Copyright © 2015 David Thompson <davet@gnu.org>
9 ;;; Copyright © 2015, 2016 Mathieu Lirzin <mthl@gnu.org>
10 ;;; Copyright © 2016 Roel Janssen <roel@gnu.org>
11 ;;; Copyright © 2016 Benz Schenk <benz.schenk@uzh.ch>
12 ;;; Copyright © 2018 Kyle Meyer <kyle@kyleam.com>
13 ;;; Copyright © 2018 Ricardo Wurmus <rekado@elephly.net>
14 ;;; Copyright © 2019 Chris Marusich <cmmarusich@gmail.com>
15 ;;; Copyright © 2019 Tobias Geerinckx-Rice <me@tobias.gr>
16 ;;; Copyright © 2019 Simon Tournier <zimon.toutoune@gmail.com>
17 ;;; Copyright © 2020 Arun Isaac <arunisaac@systemreboot.net>
18 ;;;
19 ;;; This file is part of GNU Guix.
20 ;;;
21 ;;; GNU Guix is free software; you can redistribute it and/or modify it
22 ;;; under the terms of the GNU General Public License as published by
23 ;;; the Free Software Foundation; either version 3 of the License, or (at
24 ;;; your option) any later version.
25 ;;;
26 ;;; GNU Guix is distributed in the hope that it will be useful, but
27 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
28 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29 ;;; GNU General Public License for more details.
30 ;;;
31 ;;; You should have received a copy of the GNU General Public License
32 ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
33
34 (define-module (guix ui)
35 #:use-module (guix i18n)
36 #:use-module (guix colors)
37 #:use-module (guix diagnostics)
38 #:use-module (guix gexp)
39 #:use-module (guix sets)
40 #:use-module (guix utils)
41 #:use-module (guix store)
42 #:use-module (guix config)
43 #:use-module (guix packages)
44 #:use-module (guix profiles)
45 #:use-module (guix derivations)
46 #:use-module (guix build-system)
47 #:use-module (guix serialization)
48 #:use-module ((guix licenses)
49 #:select (license? license-name license-uri))
50 #:use-module ((guix build syscalls)
51 #:select (free-disk-space terminal-columns terminal-rows
52 with-file-lock/no-wait))
53 #:use-module ((guix build utils)
54 ;; XXX: All we need are the bindings related to
55 ;; '&invoke-error'. However, to work around the bug described
56 ;; in 5d669883ecc104403c5d3ba7d172e9c02234577c, #:hide
57 ;; unwanted bindings instead of #:select'ing the needed
58 ;; bindings.
59 #:hide (package-name->name+version
60 ;; Avoid "overrides core binding" warning.
61 delete))
62 #:use-module (srfi srfi-1)
63 #:use-module (srfi srfi-11)
64 #:use-module (srfi srfi-19)
65 #:use-module (srfi srfi-26)
66 #:use-module (srfi srfi-31)
67 #:use-module (srfi srfi-34)
68 #:use-module (srfi srfi-35)
69 #:autoload (ice-9 ftw) (scandir)
70 #:use-module (ice-9 match)
71 #:use-module (ice-9 format)
72 #:use-module (ice-9 regex)
73 #:autoload (ice-9 popen) (open-pipe* close-pipe)
74 #:autoload (system base compile) (compile-file)
75 #:autoload (system repl repl) (start-repl)
76 #:autoload (system repl debug) (make-debug stack->vector)
77 #:autoload (web uri) (encode-and-join-uri-path)
78 #:use-module (texinfo)
79 #:use-module (texinfo plain-text)
80 #:use-module (texinfo string-utils)
81
82 ;; Re-exports for backward compatibility.
83 #:re-export (G_ N_ P_ ;now in (guix i18n)
84
85 warning info report-error leave ;now in (guix diagnostics)
86 location->string
87 guix-warning-port program-name)
88 #:export (display-hint
89 make-user-module
90 load*
91 warn-about-load-error
92 show-version-and-exit
93 show-bug-report-information
94 make-regexp*
95 string->number*
96 size->number
97 show-derivation-outputs
98 build-notifier
99 show-what-to-build
100 show-what-to-build*
101 show-manifest-transaction
102 call-with-error-handling
103 with-error-handling
104 with-unbound-variable-handling
105 leave-on-EPIPE
106 read/eval
107 read/eval-package-expression
108 check-available-space
109 indented-string
110 fill-paragraph
111 %text-width
112 texi->plain-text
113 package-description-string
114 package-synopsis-string
115 string->recutils
116 package->recutils
117 package-specification->name+version+output
118
119 supports-hyperlinks?
120 hyperlink
121 file-hyperlink
122 location->hyperlink
123
124 with-paginated-output-port
125 relevance
126 package-relevance
127 display-search-results
128
129 with-profile-lock
130 string->generations
131 string->duration
132 matching-generations
133 display-generation
134 display-profile-content
135 display-profile-content-diff
136 roll-back*
137 switch-to-generation*
138 delete-generation*
139
140 %default-message-language
141 current-message-language
142
143 run-guix-command
144 run-guix
145 guix-main))
146
147 ;;; Commentary:
148 ;;;
149 ;;; User interface facilities for command-line tools.
150 ;;;
151 ;;; Code:
152
153 (define (print-unbound-variable-error port key args default-printer)
154 ;; Print unbound variable errors more nicely, and in the right language.
155 (match args
156 ((proc message (variable) _ ...)
157 ;; We can always omit PROC because when it's useful (i.e., different from
158 ;; "module-lookup"), it gets displayed before.
159 (format port (G_ "error: ~a: unbound variable") variable))
160 (_
161 (default-printer))))
162
163 (set-exception-printer! 'unbound-variable print-unbound-variable-error)
164
165 (define (make-user-module modules)
166 "Return a new user module with the additional MODULES loaded."
167 ;; Module in which the machine description file is loaded.
168 (let ((module (make-fresh-user-module)))
169 (for-each (lambda (iface)
170 (module-use! module (resolve-interface iface)))
171 modules)
172 module))
173
174 (define (last-frame-with-source stack)
175 "Walk stack upwards and return the last frame that has source location
176 information, or #f if it could not be found."
177 (define (frame-with-source frame)
178 ;; Walk from FRAME upwards until source location information is found.
179 (let loop ((frame frame)
180 (previous frame))
181 (if (not frame)
182 previous
183
184 ;; On Guile 3, the latest frame with source may be that of
185 ;; 'raise-exception' in boot-9.scm. Skip it.
186 (if (and (frame-source frame)
187 (not (eq? 'raise-exception (frame-procedure-name frame))))
188 frame
189 (loop (frame-previous frame) frame)))))
190
191 (let* ((depth (stack-length stack))
192 (last (and (> depth 0) (stack-ref stack 0))))
193 (frame-with-source (if (> depth 1)
194 (stack-ref stack 1) ;skip the 'throw' frame
195 last))))
196
197 (define* (load* file user-module
198 #:key (on-error 'nothing-special))
199 "Load the user provided Scheme source code FILE."
200 (define (error-string frame args)
201 (call-with-output-string
202 (lambda (port)
203 (apply display-error frame port (cdr args)))))
204
205 (define tag
206 (make-prompt-tag "user-code"))
207
208 (catch #t
209 (lambda ()
210 ;; XXX: Force a recompilation to avoid ABI issues.
211 ;;
212 ;; In 2.2.3, the bogus answer to <https://bugs.gnu.org/29226> was to
213 ;; ignore all available .go, not just those from ~/.cache, which in turn
214 ;; meant that we had to rebuild *everything*. Since this is too costly,
215 ;; we have to turn off '%fresh-auto-compile' with that version, so to
216 ;; avoid ABI breakage in the user's config file, we explicitly compile
217 ;; it (the problem remains if the user's config is spread on several
218 ;; modules.) See <https://bugs.gnu.org/29881>.
219 (unless (string=? (version) "2.2.3")
220 (set! %fresh-auto-compile #t))
221
222 (set! %load-should-auto-compile #t)
223
224 (save-module-excursion
225 (lambda ()
226 (set-current-module user-module)
227
228 ;; Hide the "auto-compiling" messages.
229 (parameterize ((current-warning-port (%make-void-port "w")))
230 (call-with-prompt tag
231 (lambda ()
232 (when (string=? (version) "2.2.3")
233 (catch 'system-error
234 (lambda ()
235 (compile-file file #:env user-module))
236 (const #f))) ;EACCES maybe, let's interpret it
237
238 ;; Give 'load' an absolute file name so that it doesn't try to
239 ;; search for FILE in %LOAD-PATH. Note: use 'load', not
240 ;; 'primitive-load', so that FILE is compiled, which then allows
241 ;; us to provide better error reporting with source line numbers.
242 (load (canonicalize-path file)))
243 (const #f))))))
244 (lambda _
245 ;; XXX: Errors are reported from the pre-unwind handler below, but
246 ;; calling 'exit' from there has no effect, so we call it here.
247 (exit 1))
248 (rec (handle-error . args)
249 ;; Capture the stack up to this procedure call, excluded, and pass
250 ;; the faulty stack frame to 'report-load-error'.
251 (let* ((stack (make-stack #t handle-error tag))
252 (frame (last-frame-with-source stack)))
253
254 (report-load-error file args frame)
255
256 (case on-error
257 ((debug)
258 (newline)
259 (display (G_ "entering debugger; type ',bt' for a backtrace\n"))
260 (start-repl #:debug (make-debug (stack->vector stack) 0
261 (error-string frame args)
262 #f)))
263 ((backtrace)
264 (newline (current-error-port))
265 (display-backtrace stack (current-error-port)))
266 (else
267 #t))))))
268
269 (define (known-variable-definition variable)
270 "Search among the currently loaded modules one that defines a variable named
271 VARIABLE and return it, or #f if none was found."
272 (define (module<? m1 m2)
273 (match (module-name m2)
274 (('gnu _ ...) #t)
275 (('guix _ ...)
276 (match (module-name m1)
277 (('gnu _ ...) #f)
278 (_ #t)))
279 (_ #f)))
280
281 (let loop ((modules (list (resolve-module '() #f #f #:ensure #f)))
282 (suggestions '())
283 (visited (setq)))
284 (match modules
285 (()
286 ;; Pick the "best" suggestion.
287 (match (sort suggestions module<?)
288 (() #f)
289 ((first _ ...) first)))
290 ((head tail ...)
291 (if (set-contains? visited head)
292 (loop tail suggestions visited)
293 (let ((visited (set-insert head visited))
294 (next (append tail
295 (hash-map->list (lambda (name module)
296 module)
297 (module-submodules head)))))
298 (match (module-local-variable head variable)
299 (#f (loop next suggestions visited))
300 (_
301 (match (module-name head)
302 (('gnu _ ...) head) ;must be that one
303 (_ (loop next (cons head suggestions) visited)))))))))))
304
305 (define %hint-color (color BOLD CYAN))
306
307 (define* (display-hint message #:optional (port (current-error-port)))
308 "Display MESSAGE, a l10n message possibly containing Texinfo markup, to
309 PORT."
310 (define colorize
311 (if (color-output? port)
312 (lambda (str)
313 (colorize-string str %hint-color))
314 identity))
315
316 (display (colorize (G_ "hint: ")) port)
317 (display
318 ;; XXX: We should arrange so that the initial indent is wider.
319 (parameterize ((%text-width (max 15 (- (terminal-columns) 5))))
320 (texi->plain-text message))
321 port))
322
323 (define* (report-unbound-variable-error args #:key frame)
324 "Return the given unbound-variable error, where ARGS is the list of 'throw'
325 arguments."
326 (match args
327 ((key . args)
328 (print-exception (current-error-port) frame key args)))
329 (match args
330 (('unbound-variable proc message (variable) _ ...)
331 (match (known-variable-definition variable)
332 (#f
333 (display-hint (G_ "Did you forget a @code{use-modules} form?")))
334 ((? module? module)
335 (display-hint (format #f (G_ "Did you forget @code{(use-modules ~a)}?")
336 (module-name module))))))))
337
338 (define (check-module-matches-file module file)
339 "Check whether FILE starts with 'define-module MODULE' and print a hint if
340 it doesn't."
341 ;; This is a common mistake when people start writing their own package
342 ;; definitions and try loading them with 'guix build -L …', so help them
343 ;; diagnose the problem.
344 (define (hint)
345 (display-hint (format #f (G_ "File @file{~a} should probably start with:
346
347 @example\n(define-module ~a)\n@end example")
348 file module)))
349
350 (catch 'system-error
351 (lambda ()
352 (let* ((sexp (call-with-input-file file read))
353 (loc (and (pair? sexp)
354 (source-properties->location (source-properties sexp)))))
355 (match sexp
356 (('define-module (names ...) _ ...)
357 (unless (equal? module names)
358 (warning loc
359 (G_ "module name ~a does not match file name '~a'~%")
360 names (module->source-file-name module))
361 (hint)))
362 ((? eof-object?)
363 (warning (G_ "~a: file is empty~%") file))
364 (else
365 (hint)))))
366 (const #f)))
367
368 (define* (report-load-error file args #:optional frame)
369 "Report the failure to load FILE, a user-provided Scheme file.
370 ARGS is the list of arguments received by the 'throw' handler."
371 (match args
372 (('system-error . rest)
373 (let ((err (system-error-errno args)))
374 (report-error (G_ "failed to load '~a': ~a~%") file (strerror err))))
375 (('read-error "scm_i_lreadparen" message _ ...)
376 ;; Guile's missing-paren messages are obscure so we make them more
377 ;; intelligible here.
378 (if (string-suffix? "end of file" message)
379 (let ((location (string-drop-right message
380 (string-length "end of file"))))
381 (format (current-error-port) (G_ "~amissing closing parenthesis~%")
382 location))
383 (apply throw args)))
384 (('syntax-error proc message properties form subform . rest)
385 (let ((loc (source-properties->location properties)))
386 (report-error loc (G_ "~s: ~a~%")
387 (or subform form) message)))
388 (('unbound-variable _ ...)
389 (report-unbound-variable-error args #:frame frame))
390 (((or 'srfi-34 '%exception) obj)
391 (if (message-condition? obj)
392 (report-error (and (error-location? obj)
393 (error-location obj))
394 (G_ "~a~%")
395 (gettext (condition-message obj) %gettext-domain))
396 (report-error (G_ "exception thrown: ~s~%") obj))
397 (when (fix-hint? obj)
398 (display-hint (condition-fix-hint obj))))
399 ((key args ...)
400 (report-error (G_ "failed to load '~a':~%") file)
401 (match args
402 (((? symbol? proc) (? string? message) (args ...) . rest)
403 (display-error frame (current-error-port) proc message
404 args rest))
405 (_
406 ;; Some exceptions like 'git-error' do not follow Guile's convention
407 ;; above and need to be printed with 'print-exception'.
408 (print-exception (current-error-port) frame key args))))))
409
410 (define (warn-about-load-error file module args) ;FIXME: factorize with ↑
411 "Report the failure to load FILE, a user-provided Scheme file, without
412 exiting. ARGS is the list of arguments received by the 'throw' handler."
413 (match args
414 (('system-error . rest)
415 (let ((err (system-error-errno args)))
416 (warning (G_ "failed to load '~a': ~a~%") module (strerror err))))
417 (('syntax-error proc message properties form . rest)
418 (let ((loc (source-properties->location properties)))
419 (warning loc (G_ "~a~%") message)))
420 (('unbound-variable _ ...)
421 (report-unbound-variable-error args))
422 (((or 'srfi-34 '%exception) obj)
423 (if (message-condition? obj)
424 (warning (G_ "failed to load '~a': ~a~%")
425 file
426 (gettext (condition-message obj) %gettext-domain))
427 (warning (G_ "failed to load '~a': exception thrown: ~s~%")
428 file obj)))
429 ((error args ...)
430 (warning (G_ "failed to load '~a':~%") module)
431 (apply display-error #f (current-error-port) args)
432 (check-module-matches-file module file))))
433
434 (define (call-with-unbound-variable-handling thunk)
435 (define tag
436 (make-prompt-tag "user-code"))
437
438 (catch 'unbound-variable
439 (lambda ()
440 (call-with-prompt tag
441 thunk
442 (const #f)))
443 (const #t)
444 (rec (handle-error . args)
445 (let* ((stack (make-stack #t handle-error tag))
446 (frame (and stack (last-frame-with-source stack))))
447 (report-unbound-variable-error args #:frame frame)
448 (exit 1)))))
449
450 (define-syntax-rule (with-unbound-variable-handling exp ...)
451 "Capture 'unbound-variable' exceptions in the dynamic extent of EXP... and
452 report them in a user-friendly way."
453 (call-with-unbound-variable-handling (lambda () exp ...)))
454
455 (define %default-message-language
456 ;; Default language to use for messages.
457 (make-parameter "en"))
458
459 (define (current-message-language)
460 "Return the language used for messages according to the current locale.
461 Return %DEFAULT-MESSAGE-LANGUAGE if that information could not be obtained. The
462 result is an ISO-639-2 language code such as \"ar\", without the territory
463 part."
464 (let ((locale (setlocale LC_MESSAGES)))
465 (match (string-index locale #\_)
466 (#f locale)
467 (index (string-take locale index)))))
468
469 (define (install-locale)
470 "Install the current locale settings."
471 (catch 'system-error
472 (lambda _
473 (setlocale LC_ALL ""))
474 (lambda args
475 (display-hint (G_ "Consider installing the @code{glibc-utf8-locales} or
476 @code{glibc-locales} package and defining @code{GUIX_LOCPATH}, along these
477 lines:
478
479 @example
480 guix package -i glibc-utf8-locales
481 export GUIX_LOCPATH=\"$HOME/.guix-profile/lib/locale\"
482 @end example
483
484 See the \"Application Setup\" section in the manual, for more info.\n")))))
485
486 (define (initialize-guix)
487 "Perform the usual initialization for stand-alone Guix commands."
488 ;; By default don't annoy users with deprecation warnings. In practice,
489 ;; 'define-deprecated' in (ice-9 deprecated) arranges so that those warnings
490 ;; are emitted at expansion-time only, but there are cases where they could
491 ;; slip through, for instance when interpreting code.
492 (unless (getenv "GUILE_WARN_DEPRECATED")
493 (debug-disable 'warn-deprecated))
494
495 (install-locale)
496 (textdomain %gettext-domain)
497
498 ;; Ignore SIGPIPE. If the daemon closes the connection, we prefer to be
499 ;; notified via an EPIPE later.
500 (sigaction SIGPIPE SIG_IGN)
501
502 (setvbuf (current-output-port) 'line)
503 (setvbuf (current-error-port) 'line))
504
505 (define* (show-version-and-exit #:optional (command (car (command-line))))
506 "Display version information for COMMAND and `(exit 0)'."
507 (simple-format #t "~a (~a) ~a~%"
508 command %guix-package-name %guix-version)
509 (format #t "Copyright ~a 2020 ~a"
510 ;; TRANSLATORS: Translate "(C)" to the copyright symbol
511 ;; (C-in-a-circle), if this symbol is available in the user's
512 ;; locale. Otherwise, do not translate "(C)"; leave it as-is. */
513 (G_ "(C)")
514 (G_ "the Guix authors\n"))
515 (display (G_"\
516 License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
517 This is free software: you are free to change and redistribute it.
518 There is NO WARRANTY, to the extent permitted by law.
519 "))
520 (exit 0))
521
522 (define (show-bug-report-information)
523 ;; TRANSLATORS: The placeholder indicates the bug-reporting address for this
524 ;; package. Please add another line saying "Report translation bugs to
525 ;; ...\n" with the address for translation bugs (typically your translation
526 ;; team's web or email address).
527 (format #t (G_ "
528 Report bugs to: ~a.") %guix-bug-report-address)
529 (format #t (G_ "
530 ~a home page: <~a>") %guix-package-name %guix-home-page-url)
531 (display (G_ "
532 General help using GNU software: <http://www.gnu.org/gethelp/>"))
533 (newline))
534
535 (define (augmented-system-error-handler file)
536 "Return a 'system-error' handler that mentions FILE in its message."
537 (lambda (key proc fmt args errno)
538 ;; Augment the FMT and ARGS with information about TARGET (this
539 ;; information is missing as of Guile 2.0.11, making the exception
540 ;; uninformative.)
541 (apply throw key proc "~A: ~S"
542 (list (strerror (car errno)) file)
543 (list errno))))
544
545 (define-syntax apply-formals
546 (syntax-rules ()
547 ((_ proc (args ...)) (proc args ...))
548 ((_ proc (arg1 args ... . rest)) (apply proc arg1 args ... rest))))
549
550 (define-syntax-rule (error-reporting-wrapper proc formals file)
551 "Wrap PROC such that its 'system-error' exceptions are augmented to mention
552 FILE."
553 (let ((real-proc (@ (guile) proc)))
554 (lambda formals
555 (catch 'system-error
556 (lambda ()
557 (apply-formals real-proc formals))
558 (augmented-system-error-handler file)))))
559
560 (set! symlink
561 ;; We 'set!' the global binding because (gnu build ...) modules and similar
562 ;; typically don't use (guix ui).
563 (error-reporting-wrapper symlink (source target) target))
564
565 (set! copy-file
566 ;; Note: here we use 'set!', not #:replace, because UIs typically use
567 ;; 'copy-recursively', which doesn't use (guix ui).
568 (error-reporting-wrapper copy-file (source target) target))
569
570 (set! canonicalize-path
571 (error-reporting-wrapper canonicalize-path (file) file))
572
573 (set! delete-file
574 (error-reporting-wrapper delete-file (file) file))
575
576 (set! execlp
577 (error-reporting-wrapper execlp (filename . args) filename))
578
579 (define (make-regexp* regexp . flags)
580 "Like 'make-regexp' but error out if REGEXP is invalid, reporting the error
581 nicely."
582 (catch 'regular-expression-syntax
583 (lambda ()
584 (apply make-regexp regexp flags))
585 (lambda (key proc message . rest)
586 (leave (G_ "'~a' is not a valid regular expression: ~a~%")
587 regexp message))))
588
589 (define (string->number* str)
590 "Like `string->number', but error out with an error message on failure."
591 (or (string->number str)
592 (leave (G_ "~a: invalid number~%") str)))
593
594 (define (size->number str)
595 "Convert STR, a storage measurement representation such as \"1024\" or
596 \"1MiB\", to a number of bytes. Raise an error if STR could not be
597 interpreted."
598 (define unit-pos
599 (string-rindex str
600 (char-set-union (char-set #\.) char-set:digit)))
601
602 (define unit
603 (and unit-pos (substring str (+ 1 unit-pos))))
604
605 (let* ((numstr (if unit-pos
606 (substring str 0 (+ 1 unit-pos))
607 str))
608 (num (string->number numstr)))
609 (unless num
610 (leave (G_ "invalid number: ~a~%") numstr))
611
612 ((compose inexact->exact round)
613 (* num
614 (match unit
615 ((or "KiB" "K" "k") (expt 2 10))
616 ((or "MiB" "M") (expt 2 20))
617 ((or "GiB" "G") (expt 2 30))
618 ((or "TiB" "T") (expt 2 40))
619 ((or "PiB" "P") (expt 2 50))
620 ((or "EiB" "E") (expt 2 60))
621 ((or "ZiB" "Z") (expt 2 70))
622 ((or "YiB" "Y") (expt 2 80))
623 ("kB" (expt 10 3))
624 ("MB" (expt 10 6))
625 ("GB" (expt 10 9))
626 ("TB" (expt 10 12))
627 ("PB" (expt 10 15))
628 ("EB" (expt 10 18))
629 ("ZB" (expt 10 21))
630 ("YB" (expt 10 24))
631 ("" 1)
632 (x
633 (leave (G_ "unknown unit: ~a~%") unit)))))))
634
635 (define (display-collision-resolution-hint collision)
636 "Display hints on how to resolve COLLISION, a &profile-collistion-error."
637 (define (top-most-entry entry)
638 (let loop ((entry entry))
639 (match (force (manifest-entry-parent entry))
640 (#f entry)
641 (parent (loop parent)))))
642
643 (let* ((first (profile-collision-error-entry collision))
644 (second (profile-collision-error-conflict collision))
645 (name1 (manifest-entry-name (top-most-entry first)))
646 (name2 (manifest-entry-name (top-most-entry second))))
647 (if (string=? name1 name2)
648 (display-hint (format #f (G_ "You cannot have two different versions
649 or variants of @code{~a} in the same profile.")
650 name1))
651 (display-hint (format #f (G_ "Try upgrading both @code{~a} and @code{~a},
652 or remove one of them from the profile.")
653 name1 name2)))))
654
655 (cond-expand
656 (guile-3
657 ;; On Guile 3.0, in 'call-with-error-handling' we need to re-raise. To
658 ;; preserve useful backtraces in case of unhandled errors, we want that to
659 ;; happen before the stack has been unwound, hence 'guard*'.
660 (define-syntax-rule (guard* (var clauses ...) exp ...)
661 "This variant of SRFI-34 'guard' does not unwind the stack before
662 evaluating the tests and bodies of CLAUSES."
663 (with-exception-handler
664 (lambda (var)
665 (cond clauses ... (else (raise var))))
666 (lambda () exp ...)
667 #:unwind? #f)))
668 (else
669 (define-syntax-rule (guard* (var clauses ...) exp ...)
670 (guard (var clauses ...) exp ...))))
671
672 (define (call-with-error-handling thunk)
673 "Call THUNK within a user-friendly error handler."
674 (define (port-filename* port)
675 ;; 'port-filename' returns #f for non-file ports, but it raises an
676 ;; exception for file ports that are closed. Work around that.
677 (and (not (port-closed? port))
678 (port-filename port)))
679
680 (guard* (c ((package-input-error? c)
681 (let* ((package (package-error-package c))
682 (input (package-error-invalid-input c))
683 (location (package-location package))
684 (file (location-file location))
685 (line (location-line location))
686 (column (location-column location)))
687 (leave (G_ "~a:~a:~a: package `~a' has an invalid input: ~s~%")
688 file line column
689 (package-full-name package) input)))
690 ((package-cross-build-system-error? c)
691 (let* ((package (package-error-package c))
692 (loc (package-location package))
693 (system (package-build-system package)))
694 (leave (G_ "~a: ~a: build system `~a' does not support cross builds~%")
695 (location->string loc)
696 (package-full-name package)
697 (build-system-name system))))
698 ((gexp-input-error? c)
699 (let ((input (package-error-invalid-input c)))
700 (leave (G_ "~s: invalid G-expression input~%")
701 (gexp-error-invalid-input c))))
702 ((profile-not-found-error? c)
703 (leave (G_ "profile '~a' does not exist~%")
704 (profile-error-profile c)))
705 ((missing-generation-error? c)
706 (leave (G_ "generation ~a of profile '~a' does not exist~%")
707 (missing-generation-error-generation c)
708 (profile-error-profile c)))
709 ((unmatched-pattern-error? c)
710 (let ((pattern (unmatched-pattern-error-pattern c)))
711 (leave (G_ "package '~a~@[@~a~]~@[:~a~]' not found in profile~%")
712 (manifest-pattern-name pattern)
713 (manifest-pattern-version pattern)
714 (match (manifest-pattern-output pattern)
715 ("out" #f)
716 (output output)))))
717 ((profile-collision-error? c)
718 (let ((entry (profile-collision-error-entry c))
719 (conflict (profile-collision-error-conflict c)))
720 (define (report-parent-entries entry)
721 (let ((parent (force (manifest-entry-parent entry))))
722 (when (manifest-entry? parent)
723 (report-error (G_ " ... propagated from ~a@~a~%")
724 (manifest-entry-name parent)
725 (manifest-entry-version parent))
726 (report-parent-entries parent))))
727
728 (define (manifest-entry-output* entry)
729 (match (manifest-entry-output entry)
730 ("out" "")
731 (output (string-append ":" output))))
732
733 (report-error (G_ "profile contains conflicting entries for ~a~a~%")
734 (manifest-entry-name entry)
735 (manifest-entry-output* entry))
736 (report-error (G_ " first entry: ~a@~a~a ~a~%")
737 (manifest-entry-name entry)
738 (manifest-entry-version entry)
739 (manifest-entry-output* entry)
740 (manifest-entry-item entry))
741 (report-parent-entries entry)
742 (report-error (G_ " second entry: ~a@~a~a ~a~%")
743 (manifest-entry-name conflict)
744 (manifest-entry-version conflict)
745 (manifest-entry-output* conflict)
746 (manifest-entry-item conflict))
747 (report-parent-entries conflict)
748 (display-collision-resolution-hint c)
749 (exit 1)))
750 ((nar-error? c)
751 (let ((file (nar-error-file c))
752 (port (nar-error-port c)))
753 (if file
754 (leave (G_ "corrupt input while restoring '~a' from ~s~%")
755 file (or (port-filename* port) port))
756 (leave (G_ "corrupt input while restoring archive from ~s~%")
757 (or (port-filename* port) port)))))
758 ((store-connection-error? c)
759 (leave (G_ "failed to connect to `~a': ~a~%")
760 (store-connection-error-file c)
761 (strerror (store-connection-error-code c))))
762 ((store-protocol-error? c)
763 ;; FIXME: Server-provided error messages aren't i18n'd.
764 (leave (G_ "~a~%")
765 (store-protocol-error-message c)))
766 ((derivation-missing-output-error? c)
767 (leave (G_ "reference to invalid output '~a' of derivation '~a'~%")
768 (derivation-missing-output c)
769 (derivation-file-name (derivation-error-derivation c))))
770 ((file-search-error? c)
771 (leave (G_ "file '~a' could not be found in these \
772 directories:~{ ~a~}~%")
773 (file-search-error-file-name c)
774 (file-search-error-search-path c)))
775 ((invoke-error? c)
776 (leave (G_ "program exited\
777 ~@[ with non-zero exit status ~a~]\
778 ~@[ terminated by signal ~a~]\
779 ~@[ stopped by signal ~a~]: ~s~%")
780 (invoke-error-exit-status c)
781 (invoke-error-term-signal c)
782 (invoke-error-stop-signal c)
783 (cons (invoke-error-program c)
784 (invoke-error-arguments c))))
785 ((message-condition? c)
786 ;; Normally '&message' error conditions have an i18n'd message.
787 (report-error (and (error-location? c) (error-location c))
788 (G_ "~a~%")
789 (gettext (condition-message c) %gettext-domain))
790 (when (fix-hint? c)
791 (display-hint (condition-fix-hint c)))
792 (exit 1))
793
794 ;; On Guile 3.0.0, exceptions such as 'unbound-variable' are
795 ;; compound and include a '&message'. However, that message only
796 ;; contains the format string. Thus, special-case it here to
797 ;; avoid displaying a bare format string.
798 ;;
799 ;; Furthermore, use of 'guard*' ensures that the stack has not
800 ;; been unwound when we re-raise, since that would otherwise show
801 ;; useless backtraces.
802 ((cond-expand
803 (guile-3
804 ((exception-predicate &exception-with-kind-and-args) c))
805 (else #f))
806 (raise c)))
807 ;; Catch EPIPE and the likes.
808 (catch 'system-error
809 thunk
810 (lambda (key proc format-string format-args . rest)
811 (leave (G_ "~a: ~a~%") proc
812 (apply format #f format-string format-args))))))
813
814 (define-syntax-rule (leave-on-EPIPE exp ...)
815 "Run EXP... in a context where EPIPE errors are caught and lead to 'exit'
816 with successful exit code. This is useful when writing to the standard output
817 may lead to EPIPE, because the standard output is piped through 'head' or
818 similar."
819 (catch 'system-error
820 (lambda ()
821 exp ...)
822 (lambda args
823 ;; We really have to exit this brutally, otherwise Guile eventually
824 ;; attempts to flush all the ports, leading to an uncaught EPIPE down
825 ;; the path.
826 (if (= EPIPE (system-error-errno args))
827 (primitive-_exit 0)
828 (apply throw args)))))
829
830 (define %guix-user-module
831 ;; Module in which user expressions are evaluated.
832 ;; Compute lazily to avoid circularity with (guix gexp).
833 (delay
834 (let ((module (make-module)))
835 (beautify-user-module! module)
836 ;; Use (guix gexp) so that one can use #~ & co.
837 (module-use! module (resolve-interface '(guix gexp)))
838 module)))
839
840 (define (read/eval str)
841 "Read and evaluate STR, raising an error if something goes wrong."
842 (let ((exp (catch #t
843 (lambda ()
844 (call-with-input-string str read))
845 (lambda args
846 (leave (G_ "failed to read expression ~s: ~s~%")
847 str args)))))
848 (catch #t
849 (lambda ()
850 (eval exp (force %guix-user-module)))
851 (lambda args
852 (report-error (G_ "failed to evaluate expression '~a':~%") exp)
853 (match args
854 (('syntax-error proc message properties form . rest)
855 (report-error (G_ "syntax error: ~a~%") message))
856 (((or 'srfi-34 '%exception) obj)
857 (if (message-condition? obj)
858 (report-error (G_ "~a~%")
859 (gettext (condition-message obj)
860 %gettext-domain))
861 (report-error (G_ "exception thrown: ~s~%") obj)))
862 ((error args ...)
863 (apply display-error #f (current-error-port) args))
864 (what? #f))
865 (exit 1)))))
866
867 (define (read/eval-package-expression str)
868 "Read and evaluate STR and return the package it refers to, or exit an
869 error."
870 (match (read/eval str)
871 ((? package? p) p)
872 (x
873 (leave (G_ "expression ~s does not evaluate to a package~%")
874 str))))
875
876 (define (show-derivation-outputs derivation)
877 "Show the output file names of DERIVATION, which can be a derivation or a
878 derivation input."
879 (define (show-outputs derivation outputs)
880 (format #t "~{~a~%~}"
881 (map (cut derivation->output-path derivation <>)
882 outputs)))
883
884 (match derivation
885 ((? derivation?)
886 (show-outputs derivation (derivation-output-names derivation)))
887 ((? derivation-input? input)
888 (show-outputs (derivation-input-derivation input)
889 (derivation-input-sub-derivations input)))))
890
891 (define* (check-available-space need
892 #:optional (directory (%store-prefix)))
893 "Make sure at least NEED bytes are available in DIRECTORY. Otherwise emit a
894 warning."
895 (let ((free (catch 'system-error
896 (lambda ()
897 (free-disk-space directory))
898 (const #f))))
899 (when (and free (>= need free))
900 (warning (G_ "at least ~,1h MB needed but only ~,1h MB available in ~a~%")
901 (/ need 1e6) (/ free 1e6) directory))))
902
903 (define (graft-derivation? drv)
904 "Return true if DRV is definitely a graft derivation, false otherwise."
905 (match (assq-ref (derivation-properties drv) 'type)
906 ('graft #t)
907 (_ #f)))
908
909 (define (profile-hook-derivation? drv)
910 "Return true if DRV is definitely a profile hook derivation, false otherwise."
911 (match (assq-ref (derivation-properties drv) 'type)
912 ('profile-hook #t)
913 (_ #f)))
914
915 (define (colorize-store-file-name file)
916 "Colorize FILE, a store file name, such that the hash part is less prominent
917 that the rest."
918 (let ((len (string-length file))
919 (prefix (+ (string-length (%store-prefix)) 32 2)))
920 (if (< len prefix)
921 file
922 (string-append (colorize-string (string-take file prefix)
923 (color DARK))
924 (string-drop file prefix)))))
925
926 (define* (show-what-to-build store drv
927 #:key dry-run? (use-substitutes? #t)
928 (mode (build-mode normal)))
929 "Show what will or would (depending on DRY-RUN?) be built in realizing the
930 derivations listed in DRV using MODE, a 'build-mode' value. The elements of
931 DRV can be either derivations or derivation inputs.
932
933 Return two values: a Boolean indicating whether there's something to build,
934 and a Boolean indicating whether there's something to download. When
935 USE-SUBSTITUTES?, check and report what is prerequisites are available for
936 download."
937 (define inputs
938 (map (match-lambda
939 ((? derivation? drv) (derivation-input drv))
940 ((? derivation-input? input) input))
941 drv))
942
943 (define substitutable-info
944 ;; Call 'substitution-oracle' upfront so we don't end up launching the
945 ;; substituter many times. This makes a big difference, especially when
946 ;; DRV is a long list as is the case with 'guix environment'.
947 (if use-substitutes?
948 (substitution-oracle store inputs #:mode mode)
949 (const #f)))
950
951 (define colorized-store-item
952 (if (color-output? (current-error-port))
953 colorize-store-file-name
954 identity))
955
956 (let*-values (((build/full download)
957 (derivation-build-plan store inputs
958 #:mode mode
959 #:substitutable-info
960 substitutable-info))
961 ((graft hook build)
962 (match (fold (lambda (drv acc)
963 (let ((file (derivation-file-name drv)))
964 (match acc
965 ((#:graft graft #:hook hook #:build build)
966 (cond
967 ((graft-derivation? drv)
968 `(#:graft ,(cons file graft)
969 #:hook ,hook
970 #:build ,build))
971 ((profile-hook-derivation? drv)
972 `(#:graft ,graft
973 #:hook ,(cons file hook)
974 #:build ,build))
975 (else
976 `(#:graft ,graft
977 #:hook ,hook
978 #:build ,(cons file build))))))))
979 '(#:graft () #:hook () #:build ())
980 build/full)
981 ((#:graft graft #:hook hook #:build build)
982 (values graft hook build)))))
983 (define installed-size
984 (reduce + 0 (map substitutable-nar-size download)))
985
986 (define download-size
987 (/ (reduce + 0 (map substitutable-download-size download))
988 1e6))
989
990 (define display-download-size?
991 ;; Sometimes narinfos lack information about the download size. Only
992 ;; display when we have information for all of DOWNLOAD.
993 (not (any (compose zero? substitutable-download-size) download)))
994
995 (if dry-run?
996 (begin
997 (format (current-error-port)
998 (N_ "~:[The following derivation would be built:~%~{ ~a~%~}~;~]"
999 "~:[The following derivations would be built:~%~{ ~a~%~}~;~]"
1000 (length build))
1001 (null? build) (map colorized-store-item build))
1002 (if display-download-size?
1003 (format (current-error-port)
1004 ;; TRANSLATORS: "MB" is for "megabyte"; it should be
1005 ;; translated to the corresponding abbreviation.
1006 (G_ "~:[~,1h MB would be downloaded:~%~{ ~a~%~}~;~]")
1007 (null? download)
1008 download-size
1009 (map (compose colorized-store-item substitutable-path)
1010 download))
1011 (format (current-error-port)
1012 (N_ "~:[The following file would be downloaded:~%~{ ~a~%~}~;~]"
1013 "~:[The following files would be downloaded:~%~{ ~a~%~}~;~]"
1014 (length download))
1015 (null? download)
1016 (map (compose colorized-store-item substitutable-path)
1017 download)))
1018 (format (current-error-port)
1019 (N_ "~:[The following graft would be made:~%~{ ~a~%~}~;~]"
1020 "~:[The following grafts would be made:~%~{ ~a~%~}~;~]"
1021 (length graft))
1022 (null? graft) (map colorized-store-item graft))
1023 (format (current-error-port)
1024 (N_ "~:[The following profile hook would be built:~%~{ ~a~%~}~;~]"
1025 "~:[The following profile hooks would be built:~%~{ ~a~%~}~;~]"
1026 (length hook))
1027 (null? hook) (map colorized-store-item hook)))
1028 (begin
1029 (format (current-error-port)
1030 (N_ "~:[The following derivation will be built:~%~{ ~a~%~}~;~]"
1031 "~:[The following derivations will be built:~%~{ ~a~%~}~;~]"
1032 (length build))
1033 (null? build) (map colorized-store-item build))
1034 (if display-download-size?
1035 (format (current-error-port)
1036 ;; TRANSLATORS: "MB" is for "megabyte"; it should be
1037 ;; translated to the corresponding abbreviation.
1038 (G_ "~:[~,1h MB will be downloaded:~%~{ ~a~%~}~;~]")
1039 (null? download)
1040 download-size
1041 (map (compose colorized-store-item substitutable-path)
1042 download))
1043 (format (current-error-port)
1044 (N_ "~:[The following file will be downloaded:~%~{ ~a~%~}~;~]"
1045 "~:[The following files will be downloaded:~%~{ ~a~%~}~;~]"
1046 (length download))
1047 (null? download)
1048 (map (compose colorized-store-item substitutable-path)
1049 download)))
1050 (format (current-error-port)
1051 (N_ "~:[The following graft will be made:~%~{ ~a~%~}~;~]"
1052 "~:[The following grafts will be made:~%~{ ~a~%~}~;~]"
1053 (length graft))
1054 (null? graft) (map colorized-store-item graft))
1055 (format (current-error-port)
1056 (N_ "~:[The following profile hook will be built:~%~{ ~a~%~}~;~]"
1057 "~:[The following profile hooks will be built:~%~{ ~a~%~}~;~]"
1058 (length hook))
1059 (null? hook) (map colorized-store-item hook))))
1060
1061 (check-available-space installed-size)
1062
1063 (values (pair? build/full) (pair? download))))
1064
1065 (define show-what-to-build*
1066 (store-lift show-what-to-build))
1067
1068 (define* (build-notifier #:key (dry-run? #f) (use-substitutes? #t))
1069 "Return a procedure suitable for 'with-build-handler' that, when
1070 'build-things' is called, invokes 'show-what-to-build' to display the build
1071 plan. When DRY-RUN? is true, the 'with-build-handler' form returns without
1072 any build happening."
1073 (define not-comma
1074 (char-set-complement (char-set #\,)))
1075
1076 (define (read-derivation-from-file* item)
1077 (catch 'system-error
1078 (lambda ()
1079 (read-derivation-from-file item))
1080 (const #f)))
1081
1082 (lambda (continue store things mode)
1083 (define inputs
1084 ;; List of derivation inputs to build. Filter out non-existent '.drv'
1085 ;; files because the daemon transparently tries to substitute them.
1086 (filter-map (match-lambda
1087 (((? derivation-path? drv) . output)
1088 (let ((drv (read-derivation-from-file* drv))
1089 (outputs (string-tokenize output not-comma)))
1090 (and drv (derivation-input drv outputs))))
1091 ((? derivation-path? drv)
1092 (and=> (read-derivation-from-file* drv)
1093 derivation-input))
1094 (_
1095 #f))
1096 things))
1097
1098 (let-values (((build? download?)
1099 (show-what-to-build store inputs
1100 #:dry-run? dry-run?
1101 #:use-substitutes? use-substitutes?
1102 #:mode mode)))
1103
1104 (unless (and (or build? download?)
1105 dry-run?)
1106 (continue #t)))))
1107
1108 (define (right-arrow port)
1109 "Return either a string containing the 'RIGHT ARROW' character, or an ASCII
1110 replacement if PORT is not Unicode-capable."
1111 (let ((encoding (port-encoding port))
1112 (arrow "→"))
1113 (catch 'encoding-error
1114 (lambda ()
1115 (call-with-output-string
1116 (lambda (port)
1117 (set-port-encoding! port encoding)
1118 (set-port-conversion-strategy! port 'error)
1119 (display arrow port))))
1120 (lambda (key . args)
1121 "->"))))
1122
1123 (define* (tabulate rows #:key (initial-indent 0) (max-width 25)
1124 (inter-column " "))
1125 "Return a list of strings where each string is a tabulated representation of
1126 an element of ROWS. All the ROWS must be lists of the same number of cells.
1127
1128 Add INITIAL-INDENT white space at the beginning of each row. Ensure that
1129 columns are at most MAX-WIDTH characters wide. Use INTER-COLUMN as a
1130 separator between subsequent columns."
1131 (define column-widths
1132 ;; List of column widths.
1133 (let loop ((rows rows)
1134 (widths '()))
1135 (match rows
1136 (((? null?) ...)
1137 (reverse widths))
1138 (((column rest ...) ...)
1139 (loop rest
1140 (cons (min (apply max (map string-length column))
1141 max-width)
1142 widths))))))
1143
1144 (define indent
1145 (make-string initial-indent #\space))
1146
1147 (define (string-pad-right* str len)
1148 (if (> (string-length str) len)
1149 str
1150 (string-pad-right str len)))
1151
1152 (map (lambda (row)
1153 (string-trim-right
1154 (string-append indent
1155 (string-join
1156 (map string-pad-right* row column-widths)
1157 inter-column))))
1158 rows))
1159
1160 (define* (show-manifest-transaction store manifest transaction
1161 #:key dry-run?)
1162 "Display what will/would be installed/removed from MANIFEST by TRANSACTION."
1163 (define (package-strings names versions outputs)
1164 (tabulate (zip (map (lambda (name output)
1165 (if (string=? output "out")
1166 name
1167 (string-append name ":" output)))
1168 names outputs)
1169 versions)
1170 #:initial-indent 3))
1171
1172 (define → ;an arrow that can be represented on stderr
1173 (right-arrow (current-error-port)))
1174
1175 (define (upgrade-string names old-version new-version outputs)
1176 (tabulate (zip (map (lambda (name output)
1177 (if (string=? output "out")
1178 name
1179 (string-append name ":" output)))
1180 names outputs)
1181 (map (lambda (old new)
1182 (if (string=? old new)
1183 (G_ "(dependencies or package changed)")
1184 (string-append old " " → " " new)))
1185 old-version new-version))
1186 #:initial-indent 3))
1187
1188 (let-values (((remove install upgrade downgrade)
1189 (manifest-transaction-effects manifest transaction)))
1190 (match remove
1191 ((($ <manifest-entry> name version output item) ..1)
1192 (let ((len (length name))
1193 (remove (package-strings name version output)))
1194 (if dry-run?
1195 (format (current-error-port)
1196 (N_ "The following package would be removed:~%~{~a~%~}~%"
1197 "The following packages would be removed:~%~{~a~%~}~%"
1198 len)
1199 remove)
1200 (format (current-error-port)
1201 (N_ "The following package will be removed:~%~{~a~%~}~%"
1202 "The following packages will be removed:~%~{~a~%~}~%"
1203 len)
1204 remove))))
1205 (x #f))
1206 (match downgrade
1207 (((($ <manifest-entry> name old-version)
1208 . ($ <manifest-entry> _ new-version output item)) ..1)
1209 (let ((len (length name))
1210 (downgrade (upgrade-string name old-version new-version
1211 output)))
1212 (if dry-run?
1213 (format (current-error-port)
1214 (N_ "The following package would be downgraded:~%~{~a~%~}~%"
1215 "The following packages would be downgraded:~%~{~a~%~}~%"
1216 len)
1217 downgrade)
1218 (format (current-error-port)
1219 (N_ "The following package will be downgraded:~%~{~a~%~}~%"
1220 "The following packages will be downgraded:~%~{~a~%~}~%"
1221 len)
1222 downgrade))))
1223 (x #f))
1224 (match upgrade
1225 (((($ <manifest-entry> name old-version)
1226 . ($ <manifest-entry> _ new-version output item)) ..1)
1227 (let ((len (length name))
1228 (upgrade (upgrade-string name
1229 old-version new-version
1230 output)))
1231 (if dry-run?
1232 (format (current-error-port)
1233 (N_ "The following package would be upgraded:~%~{~a~%~}~%"
1234 "The following packages would be upgraded:~%~{~a~%~}~%"
1235 len)
1236 upgrade)
1237 (format (current-error-port)
1238 (N_ "The following package will be upgraded:~%~{~a~%~}~%"
1239 "The following packages will be upgraded:~%~{~a~%~}~%"
1240 len)
1241 upgrade))))
1242 (x #f))
1243 (match install
1244 ((($ <manifest-entry> name version output item _) ..1)
1245 (let ((len (length name))
1246 (install (package-strings name version output)))
1247 (if dry-run?
1248 (format (current-error-port)
1249 (N_ "The following package would be installed:~%~{~a~%~}~%"
1250 "The following packages would be installed:~%~{~a~%~}~%"
1251 len)
1252 install)
1253 (format (current-error-port)
1254 (N_ "The following package will be installed:~%~{~a~%~}~%"
1255 "The following packages will be installed:~%~{~a~%~}~%"
1256 len)
1257 install))))
1258 (x #f))))
1259
1260 (define-syntax with-error-handling
1261 (syntax-rules ()
1262 "Run BODY within a user-friendly error condition handler."
1263 ((_ body ...)
1264 (call-with-error-handling
1265 (lambda ()
1266 body ...)))))
1267
1268 (define* (indented-string str indent
1269 #:key (initial-indent? #t))
1270 "Return STR with each newline preceded by INDENT spaces. When
1271 INITIAL-INDENT? is true, the first line is also indented."
1272 (define indent-string
1273 (make-list indent #\space))
1274
1275 (list->string
1276 (string-fold-right (lambda (chr result)
1277 (if (eqv? chr #\newline)
1278 (cons chr (append indent-string result))
1279 (cons chr result)))
1280 '()
1281 (if initial-indent?
1282 (string-append (list->string indent-string) str)
1283 str))))
1284
1285 (define* (fill-paragraph str width #:optional (column 0))
1286 "Fill STR such that each line contains at most WIDTH characters, assuming
1287 that the first character is at COLUMN.
1288
1289 When STR contains a single line break surrounded by other characters, it is
1290 converted to a space; sequences of more than one line break are preserved."
1291 (define (maybe-break chr result)
1292 (match result
1293 ((column newlines chars)
1294 (case chr
1295 ((#\newline)
1296 `(,column ,(+ 1 newlines) ,chars))
1297 (else
1298 (let* ((spaces (if (and (pair? chars) (eqv? (car chars) #\.)) 2 1))
1299 (chars (case newlines
1300 ((0) chars)
1301 ((1)
1302 (append (make-list spaces #\space) chars))
1303 (else
1304 (append (make-list newlines #\newline) chars))))
1305 (column (case newlines
1306 ((0) column)
1307 ((1) (+ spaces column))
1308 (else 0))))
1309 (let ((chars (cons chr chars))
1310 (column (+ 1 column)))
1311 (if (> column width)
1312 (let*-values (((before after)
1313 (break (cut eqv? #\space <>) chars))
1314 ((len)
1315 (length before)))
1316 (if (<= len width)
1317 `(,len
1318 0
1319 ,(if (null? after)
1320 before
1321 (append before
1322 (cons #\newline
1323 (drop-while (cut eqv? #\space <>)
1324 after)))))
1325 `(,column 0 ,chars))) ; unbreakable
1326 `(,column 0 ,chars)))))))))
1327
1328 (match (string-fold maybe-break
1329 `(,column 0 ())
1330 str)
1331 ((column newlines chars)
1332 (list->string (reverse chars)))))
1333
1334 \f
1335 ;;;
1336 ;;; Packages.
1337 ;;;
1338
1339 (define %text-width
1340 ;; '*line-width*' was introduced in Guile 2.2.7/3.0.1. On older versions of
1341 ;; Guile, monkey-patch 'wrap*' below.
1342 (if (defined? '*line-width*)
1343 (let ((parameter (fluid->parameter *line-width*)))
1344 (parameter (terminal-columns))
1345 parameter)
1346 (make-parameter (terminal-columns))))
1347
1348 (unless (defined? '*line-width*) ;Guile < 2.2.7
1349 (set! (@@ (texinfo plain-text) wrap*)
1350 ;; XXX: Monkey patch this private procedure to let 'package->recutils'
1351 ;; parameterize the fill of description field correctly.
1352 (lambda strings
1353 (let ((indent (fluid-ref (@@ (texinfo plain-text) *indent*))))
1354 (fill-string (string-concatenate strings)
1355 #:line-width (%text-width) #:initial-indent indent
1356 #:subsequent-indent indent)))))
1357
1358 (define (texi->plain-text str)
1359 "Return a plain-text representation of texinfo fragment STR."
1360 ;; 'texi-fragment->stexi' uses a string port so make sure it's a
1361 ;; Unicode-capable one (see <http://bugs.gnu.org/11197>.)
1362 (with-fluids ((%default-port-encoding "UTF-8"))
1363 (stexi->plain-text (texi-fragment->stexi str))))
1364
1365 (define (package-field-string package field-accessor)
1366 "Return a plain-text representation of PACKAGE field."
1367 (and=> (field-accessor package)
1368 (compose texi->plain-text P_)))
1369
1370 (define (package-description-string package)
1371 "Return a plain-text representation of PACKAGE description field."
1372 (package-field-string package package-description))
1373
1374 (define (package-synopsis-string package)
1375 "Return a plain-text representation of PACKAGE synopsis field."
1376 (package-field-string package package-synopsis))
1377
1378 (define (string->recutils str)
1379 "Return a version of STR where newlines have been replaced by newlines
1380 followed by \"+ \", which makes for a valid multi-line field value in the
1381 `recutils' syntax."
1382 (list->string
1383 (string-fold-right (lambda (chr result)
1384 (if (eqv? chr #\newline)
1385 (cons* chr #\+ #\space result)
1386 (cons chr result)))
1387 '()
1388 str)))
1389
1390 (define (hyperlink uri text)
1391 "Return a string that denotes a hyperlink using an OSC escape sequence as
1392 documented at
1393 <https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda>."
1394 (string-append "\x1b]8;;" uri "\x1b\\"
1395 text "\x1b]8;;\x1b\\"))
1396
1397 (define* (supports-hyperlinks? #:optional (port (current-output-port)))
1398 "Return true if PORT is a terminal that supports hyperlink escapes."
1399 ;; Note that terminals are supposed to ignore OSC escapes they don't
1400 ;; understand (this is the case of xterm as of version 349, for instance.)
1401 ;; However, Emacs comint as of 26.3 does not ignore it and instead lets it
1402 ;; through, hence the 'INSIDE_EMACS' special case below.
1403 (and (isatty?* port)
1404 (not (getenv "INSIDE_EMACS"))))
1405
1406 (define* (file-hyperlink file #:optional (text file))
1407 "Return TEXT with escapes for a hyperlink to FILE."
1408 (hyperlink (string-append "file://" (gethostname)
1409 (encode-and-join-uri-path
1410 (string-split file #\/)))
1411 text))
1412
1413 (define (location->hyperlink location)
1414 "Return a string corresponding to LOCATION, with escapes for a hyperlink."
1415 (let ((str (location->string location))
1416 (file (if (string-prefix? "/" (location-file location))
1417 (location-file location)
1418 (search-path %load-path (location-file location)))))
1419 (if file
1420 (file-hyperlink file str)
1421 str)))
1422
1423 (define* (package->recutils p port #:optional (width (%text-width))
1424 #:key
1425 (hyperlinks? (supports-hyperlinks? port))
1426 (extra-fields '()))
1427 "Write to PORT a `recutils' record of package P, arranging to fit within
1428 WIDTH columns. EXTRA-FIELDS is a list of symbol/value pairs to emit. When
1429 HYPERLINKS? is true, emit hyperlink escape sequences when appropriate."
1430 (define width*
1431 ;; The available number of columns once we've taken into account space for
1432 ;; the initial "+ " prefix.
1433 (if (> width 2) (- width 2) width))
1434
1435 (define (dependencies->recutils packages)
1436 (let ((list (string-join (delete-duplicates
1437 (map package-full-name
1438 (sort packages package<?))) " ")))
1439 (string->recutils
1440 (fill-paragraph list width*
1441 (string-length "dependencies: ")))))
1442
1443 (define (package<? p1 p2)
1444 (string<? (package-full-name p1) (package-full-name p2)))
1445
1446 ;; Note: Don't i18n field names so that people can post-process it.
1447 (format port "name: ~a~%" (package-name p))
1448 (format port "version: ~a~%" (package-version p))
1449 (format port "outputs: ~a~%" (string-join (package-outputs p)))
1450 (format port "systems: ~a~%"
1451 (string-join (package-transitive-supported-systems p)))
1452 (format port "dependencies: ~a~%"
1453 (match (package-direct-inputs p)
1454 (((labels inputs . _) ...)
1455 (dependencies->recutils (filter package? inputs)))))
1456 (format port "location: ~a~%"
1457 (or (and=> (package-location p)
1458 (if hyperlinks? location->hyperlink location->string))
1459 (G_ "unknown")))
1460
1461 ;; Note: Starting from version 1.6 or recutils, hyphens are not allowed in
1462 ;; field identifiers.
1463 (format port "homepage: ~a~%" (package-home-page p))
1464
1465 (format port "license: ~a~%"
1466 (match (package-license p)
1467 (((? license? licenses) ...)
1468 (string-join (map license-name licenses)
1469 ", "))
1470 ((? license? license)
1471 (let ((text (license-name license))
1472 (uri (license-uri license)))
1473 (if (and hyperlinks? uri (string-prefix? "http" uri))
1474 (hyperlink uri text)
1475 text)))
1476 (x
1477 (G_ "unknown"))))
1478 (format port "synopsis: ~a~%"
1479 (string-map (match-lambda
1480 (#\newline #\space)
1481 (chr chr))
1482 (or (package-synopsis-string p) "")))
1483 (format port "~a~%"
1484 (string->recutils
1485 (string-trim-right
1486 (parameterize ((%text-width width*))
1487 ;; Call 'texi->plain-text' on the concatenated string to account
1488 ;; for the width of "description:" in paragraph filling.
1489 (texi->plain-text
1490 (string-append "description: "
1491 (or (and=> (package-description p) P_)
1492 ""))))
1493 #\newline)))
1494 (for-each (match-lambda
1495 ((field . value)
1496 (let ((field (symbol->string field)))
1497 (format port "~a: ~a~%"
1498 field
1499 (fill-paragraph (object->string value) width*
1500 (string-length field))))))
1501 extra-fields)
1502 (newline port))
1503
1504 \f
1505 ;;;
1506 ;;; Searching.
1507 ;;;
1508
1509 (define (relevance obj regexps metrics)
1510 "Compute a \"relevance score\" for OBJ as a function of its number of
1511 matches of REGEXPS and accordingly to METRICS. METRICS is list of
1512 field/weight pairs, where FIELD is a procedure that returns a string or list
1513 of strings describing OBJ, and WEIGHT is a positive integer denoting the
1514 weight of this field in the final score.
1515
1516 A score of zero means that OBJ does not match any of REGEXPS. The higher the
1517 score, the more relevant OBJ is to REGEXPS."
1518 (define (score regexp str)
1519 (fold-matches regexp str 0
1520 (lambda (m score)
1521 (+ score
1522 (if (string=? (match:substring m) str)
1523 5 ;exact match
1524 1)))))
1525
1526 (define (regexp->score regexp)
1527 (let ((score-regexp (lambda (str) (score regexp str))))
1528 (fold (lambda (metric relevance)
1529 (match metric
1530 ((field . weight)
1531 (match (field obj)
1532 (#f relevance)
1533 ((? string? str)
1534 (+ relevance (* (score-regexp str) weight)))
1535 ((lst ...)
1536 (+ relevance (* weight (apply + (map score-regexp lst)))))))))
1537 0 metrics)))
1538
1539 (let loop ((regexps regexps)
1540 (total-score 0))
1541 (match regexps
1542 ((head . tail)
1543 (let ((score (regexp->score head)))
1544 ;; Return zero if one of PATTERNS doesn't match.
1545 (if (zero? score)
1546 0
1547 (loop tail (+ total-score score)))))
1548 (() total-score))))
1549
1550 (define %package-metrics
1551 ;; Metrics used to compute the "relevance score" of a package against a set
1552 ;; of regexps.
1553 `((,package-name . 4)
1554
1555 ;; Match against uncommon outputs.
1556 (,(lambda (package)
1557 (filter (lambda (output)
1558 (not (member output
1559 ;; Some common outputs shared by many packages.
1560 '("out" "doc" "debug" "lib" "include" "bin"))))
1561 (package-outputs package)))
1562 . 1)
1563
1564 ;; Match regexps on the raw Texinfo since formatting it is quite expensive
1565 ;; and doesn't have much of an effect on search results.
1566 (,(lambda (package)
1567 (and=> (package-synopsis package) P_)) . 3)
1568 (,(lambda (package)
1569 (and=> (package-description package) P_)) . 2)
1570
1571 (,(lambda (type)
1572 (match (and=> (package-location type) location-file)
1573 ((? string? file) (basename file ".scm"))
1574 (#f "")))
1575 . 1)))
1576
1577 (define (package-relevance package regexps)
1578 "Return a score denoting the relevance of PACKAGE for REGEXPS. A score of
1579 zero means that PACKAGE does not match any of REGEXPS."
1580 (relevance package regexps %package-metrics))
1581
1582 (define (call-with-paginated-output-port proc)
1583 (if (isatty?* (current-output-port))
1584 ;; Set 'LESS' so that 'less' exits if everything fits on the screen (F),
1585 ;; lets ANSI escapes through (r), does not send the termcap
1586 ;; initialization string (X). Set it unconditionally because some
1587 ;; distros set it to something that doesn't work here.
1588 (let ((pager (with-environment-variables `(("LESS" "FrX"))
1589 (open-pipe* OPEN_WRITE
1590 (or (getenv "GUIX_PAGER") (getenv "PAGER")
1591 "less")))))
1592 (dynamic-wind
1593 (const #t)
1594 (lambda () (proc pager))
1595 (lambda () (close-pipe pager))))
1596 (proc (current-output-port))))
1597
1598 (define-syntax-rule (with-paginated-output-port port exp ...)
1599 "Evaluate EXP... with PORT bound to a port that talks to the pager if
1600 standard output is a tty, or with PORT set to the current output port."
1601 (call-with-paginated-output-port (lambda (port) exp ...)))
1602
1603 (define* (display-search-results matches port
1604 #:key
1605 (command "guix search")
1606 (print package->recutils))
1607 "Display MATCHES, a list of object/score pairs, by calling PRINT on each of
1608 them. If PORT is a terminal, print at most a full screen of results."
1609 (define first-line
1610 (port-line port))
1611
1612 (define max-rows
1613 (and first-line (isatty? port)
1614 (terminal-rows port)))
1615
1616 (define (line-count str)
1617 (string-count str #\newline))
1618
1619 (with-paginated-output-port paginated
1620 (let loop ((matches matches))
1621 (match matches
1622 (((package . score) rest ...)
1623 (let* ((links? (supports-hyperlinks? port)))
1624 (print package paginated
1625 #:hyperlinks? links?
1626 #:extra-fields `((relevance . ,score)))
1627 (loop rest)))
1628 (()
1629 #t)))))
1630
1631 \f
1632 (define (string->generations str)
1633 "Return the list of generations matching a pattern in STR. This function
1634 accepts the following patterns: \"1\", \"1,2,3\", \"1..9\", \"1..\", \"..9\"."
1635 (define (maybe-integer)
1636 (let ((x (string->number str)))
1637 (and (integer? x)
1638 x)))
1639
1640 (define (maybe-comma-separated-integers)
1641 (let ((lst (delete-duplicates
1642 (map string->number
1643 (string-split str #\,)))))
1644 (and (every integer? lst)
1645 lst)))
1646
1647 (cond ((maybe-integer)
1648 =>
1649 list)
1650 ((maybe-comma-separated-integers)
1651 =>
1652 identity)
1653 ((string-match "^([0-9]+)\\.\\.([0-9]+)$" str)
1654 =>
1655 (lambda (match)
1656 (let ((s (string->number (match:substring match 1)))
1657 (e (string->number (match:substring match 2))))
1658 (and (every integer? (list s e))
1659 (<= s e)
1660 (iota (1+ (- e s)) s)))))
1661 ((string-match "^([0-9]+)\\.\\.$" str)
1662 =>
1663 (lambda (match)
1664 (let ((s (string->number (match:substring match 1))))
1665 (and (integer? s)
1666 `(>= ,s)))))
1667 ((string-match "^\\.\\.([0-9]+)$" str)
1668 =>
1669 (lambda (match)
1670 (let ((e (string->number (match:substring match 1))))
1671 (and (integer? e)
1672 `(<= ,e)))))
1673 (else #f)))
1674
1675 (define (string->duration str)
1676 "Return the duration matching a pattern in STR. This function accepts the
1677 following patterns: \"1d\", \"1w\", \"1m\"."
1678 (define (hours->duration hours match)
1679 (make-time time-duration 0
1680 (* 3600 hours (string->number (match:substring match 1)))))
1681
1682 (cond ((string-match "^([0-9]+)s$" str)
1683 =>
1684 (lambda (match)
1685 (make-time time-duration 0
1686 (string->number (match:substring match 1)))))
1687 ((string-match "^([0-9]+)h$" str)
1688 =>
1689 (lambda (match)
1690 (hours->duration 1 match)))
1691 ((string-match "^([0-9]+)d$" str)
1692 =>
1693 (lambda (match)
1694 (hours->duration 24 match)))
1695 ((string-match "^([0-9]+)w$" str)
1696 =>
1697 (lambda (match)
1698 (hours->duration (* 24 7) match)))
1699 ((string-match "^([0-9]+)m$" str)
1700 =>
1701 (lambda (match)
1702 (hours->duration (* 24 30) match)))
1703 (else #f)))
1704
1705 (define* (matching-generations str profile
1706 #:key (duration-relation <=))
1707 "Return the list of available generations matching a pattern in STR. See
1708 'string->generations' and 'string->duration' for the list of valid patterns.
1709 When STR is a duration pattern, return all the generations whose ctime has
1710 DURATION-RELATION with the current time."
1711 (define (valid-generations lst)
1712 (define (valid-generation? n)
1713 (any (cut = n <>) (generation-numbers profile)))
1714
1715 (fold-right (lambda (x acc)
1716 (if (valid-generation? x)
1717 (cons x acc)
1718 acc))
1719 '()
1720 lst))
1721
1722 (define (filter-generations generations)
1723 (match generations
1724 (() '())
1725 (('>= n)
1726 (drop-while (cut > n <>)
1727 (generation-numbers profile)))
1728 (('<= n)
1729 (valid-generations (iota n 1)))
1730 ((lst ..1)
1731 (valid-generations lst))
1732 (x #f)))
1733
1734 (define (filter-by-duration duration)
1735 (define (time-at-midnight time)
1736 ;; Return TIME at midnight by setting nanoseconds, seconds, minutes, and
1737 ;; hours to zeros.
1738 (let ((d (time-utc->date time)))
1739 (date->time-utc
1740 (make-date 0 0 0 0
1741 (date-day d) (date-month d)
1742 (date-year d) (date-zone-offset d)))))
1743
1744 (define generation-ctime-alist
1745 (map (lambda (number)
1746 (cons number
1747 (time-second
1748 (time-at-midnight
1749 (generation-time profile number)))))
1750 (generation-numbers profile)))
1751
1752 (match duration
1753 (#f #f)
1754 (res
1755 (let ((s (time-second
1756 (subtract-duration (time-at-midnight (current-time))
1757 duration))))
1758 (delete #f (map (lambda (x)
1759 (and (duration-relation s (cdr x))
1760 (first x)))
1761 generation-ctime-alist))))))
1762
1763 (cond ((string->generations str)
1764 =>
1765 filter-generations)
1766 ((string->duration str)
1767 =>
1768 filter-by-duration)
1769 (else
1770 (raise
1771 (condition (&message
1772 (message (format #f (G_ "invalid syntax: ~a~%")
1773 str))))))))
1774
1775 (define (display-generation profile number)
1776 "Display a one-line summary of generation NUMBER of PROFILE."
1777 (unless (zero? number)
1778 (let* ((file (generation-file-name profile number))
1779 (link (if (supports-hyperlinks?)
1780 (cut file-hyperlink file <>)
1781 identity))
1782 (header (format #f (link (highlight (G_ "Generation ~a\t~a")))
1783 number
1784 (date->string
1785 (time-utc->date
1786 (generation-time profile number))
1787 ;; TRANSLATORS: This is a format-string for date->string.
1788 ;; Please choose a format that corresponds to the
1789 ;; usual way of presenting dates in your locale.
1790 ;; See https://www.gnu.org/software/guile/manual/html_node/SRFI_002d19-Date-to-string.html
1791 ;; for details.
1792 (G_ "~b ~d ~Y ~T"))))
1793 (current (generation-number profile)))
1794 (if (= number current)
1795 ;; TRANSLATORS: The word "current" here is an adjective for
1796 ;; "Generation", as in "current generation". Use the appropriate
1797 ;; gender where applicable.
1798 (format #t (G_ "~a\t(current)~%") header)
1799 (format #t "~a~%" header)))))
1800
1801 (define (display-profile-content-diff profile gen1 gen2)
1802 "Display the changed packages in PROFILE GEN2 compared to generation GEN1."
1803
1804 (define (equal-entry? first second)
1805 (string= (manifest-entry-item first) (manifest-entry-item second)))
1806
1807 (define (display-entry entry prefix)
1808 (match entry
1809 (($ <manifest-entry> name version output location _)
1810 (format #t " ~a ~a\t~a\t~a\t~a~%" prefix name version output location))))
1811
1812 (define (list-entries number)
1813 (manifest-entries (profile-manifest (generation-file-name profile number))))
1814
1815 (define (display-diff profile old new)
1816 (display-generation profile new)
1817 (let ((added (lset-difference
1818 equal-entry? (list-entries new) (list-entries old)))
1819 (removed (lset-difference
1820 equal-entry? (list-entries old) (list-entries new))))
1821 (for-each (cut display-entry <> "+") added)
1822 (for-each (cut display-entry <> "-") removed)
1823 (newline)))
1824
1825 (display-diff profile gen1 gen2))
1826
1827 (define (profile-lock-handler profile errno . _)
1828 "Handle failure to acquire PROFILE's lock."
1829 ;; NFS mounts can return ENOLCK. When that happens, there's not much that
1830 ;; can be done, so warn the user and keep going.
1831 (if (= errno ENOLCK)
1832 (warning (G_ "cannot lock profile ~a: ~a~%")
1833 profile (strerror errno))
1834 (leave (G_ "profile ~a is locked by another process~%")
1835 profile)))
1836
1837 (define profile-lock-file
1838 (cut string-append <> ".lock"))
1839
1840 (define-syntax-rule (with-profile-lock profile exp ...)
1841 "Grab PROFILE's lock and evaluate EXP... Call 'leave' if the lock is
1842 already taken."
1843 (with-file-lock/no-wait (profile-lock-file profile)
1844 (cut profile-lock-handler profile <...>)
1845 exp ...))
1846
1847 (define (display-profile-content profile number)
1848 "Display the packages in PROFILE, generation NUMBER, in a human-readable
1849 way."
1850 (for-each (match-lambda
1851 (($ <manifest-entry> name version output location _)
1852 (format #t " ~a\t~a\t~a\t~a~%"
1853 name version output location)))
1854
1855 ;; Show most recently installed packages last.
1856 (reverse
1857 (manifest-entries
1858 (profile-manifest (generation-file-name profile number))))))
1859
1860 (define (display-generation-change previous current)
1861 (format #t (G_ "switched from generation ~a to ~a~%") previous current))
1862
1863 (define (roll-back* store profile)
1864 "Like 'roll-back', but display what is happening."
1865 (call-with-values
1866 (lambda ()
1867 (roll-back store profile))
1868 display-generation-change))
1869
1870 (define (switch-to-generation* profile number)
1871 "Like 'switch-generation', but display what is happening."
1872 (let ((previous (switch-to-generation profile number)))
1873 (display-generation-change previous number)))
1874
1875 (define (delete-generation* store profile generation)
1876 "Like 'delete-generation', but display what is going on."
1877 (format #t (G_ "deleting ~a~%")
1878 (generation-file-name profile generation))
1879 (delete-generation store profile generation))
1880
1881 (define* (package-specification->name+version+output spec
1882 #:optional (output "out"))
1883 "Parse package specification SPEC and return three value: the specified
1884 package name, version number (or #f), and output name (or OUTPUT). SPEC may
1885 optionally contain a version number and an output name, as in these examples:
1886
1887 guile
1888 guile@2.0.9
1889 guile:debug
1890 guile@2.0.9:debug
1891 "
1892 (let*-values (((name sub-drv)
1893 (match (string-rindex spec #\:)
1894 (#f (values spec output))
1895 (colon (values (substring spec 0 colon)
1896 (substring spec (+ 1 colon))))))
1897 ((name version)
1898 (package-name->name+version name)))
1899 (values name version sub-drv)))
1900
1901 \f
1902 ;;;
1903 ;;; Command-line option processing.
1904 ;;;
1905
1906 (define (show-guix-usage)
1907 (format (current-error-port)
1908 (G_ "Try `guix --help' for more information.~%"))
1909 (exit 1))
1910
1911 (define (command-files)
1912 "Return the list of source files that define Guix sub-commands."
1913 (define directory
1914 (and=> (search-path %load-path "guix.scm")
1915 (compose (cut string-append <> "/guix/scripts")
1916 dirname)))
1917
1918 (define dot-scm?
1919 (cut string-suffix? ".scm" <>))
1920
1921 (if directory
1922 (scandir directory dot-scm?)
1923 '()))
1924
1925 (define (commands)
1926 "Return the list of Guix command names."
1927 (map (compose (cut string-drop-right <> 4)
1928 basename)
1929 (command-files)))
1930
1931 (define (show-guix-help)
1932 (define (internal? command)
1933 (member command '("substitute" "authenticate" "offload"
1934 "perform-download")))
1935
1936 (format #t (G_ "Usage: guix COMMAND ARGS...
1937 Run COMMAND with ARGS.\n"))
1938 (newline)
1939 (format #t (G_ "COMMAND must be one of the sub-commands listed below:\n"))
1940 (newline)
1941 ;; TODO: Display a synopsis of each command.
1942 (format #t "~{ ~a~%~}" (sort (remove internal? (commands))
1943 string<?))
1944 (show-bug-report-information))
1945
1946 (define (run-guix-command command . args)
1947 "Run COMMAND with the given ARGS. Report an error when COMMAND is not
1948 found."
1949 (define module
1950 (catch 'misc-error
1951 (lambda ()
1952 (resolve-interface `(guix scripts ,command)))
1953 (lambda -
1954 (format (current-error-port)
1955 (G_ "guix: ~a: command not found~%") command)
1956 (show-guix-usage))))
1957
1958 (let ((command-main (module-ref module
1959 (symbol-append 'guix- command))))
1960 (parameterize ((program-name command))
1961 ;; Disable canonicalization so we don't don't stat unreasonably.
1962 (with-fluids ((%file-port-name-canonicalization #f))
1963 (dynamic-wind
1964 (const #f)
1965 (lambda ()
1966 (apply command-main args))
1967 (lambda ()
1968 ;; Abuse 'exit-hook' (which is normally meant to be used by the
1969 ;; REPL) to run things like profiling hooks upon completion.
1970 (run-hook exit-hook)))))))
1971
1972 (define (run-guix . args)
1973 "Run the 'guix' command defined by command line ARGS.
1974 Unlike 'guix-main', this procedure assumes that locale, i18n support,
1975 and signal handling have already been set up."
1976 (define option? (cut string-prefix? "-" <>))
1977
1978 ;; The default %LOAD-EXTENSIONS includes the empty string, which doubles the
1979 ;; number of 'stat' calls per entry in %LOAD-PATH. Shamelessly remove it.
1980 (set! %load-extensions '(".scm"))
1981
1982 (match args
1983 (()
1984 (format (current-error-port)
1985 (G_ "guix: missing command name~%"))
1986 (show-guix-usage))
1987 ((or ("-h") ("--help"))
1988 (show-guix-help))
1989 ((or ("-V") ("--version"))
1990 (show-version-and-exit "guix"))
1991 (((? option? o) args ...)
1992 (format (current-error-port)
1993 (G_ "guix: unrecognized option '~a'~%") o)
1994 (show-guix-usage))
1995 (("help" command)
1996 (apply run-guix-command (string->symbol command)
1997 '("--help")))
1998 (("help" args ...)
1999 (show-guix-help))
2000 ((command args ...)
2001 (apply run-guix-command
2002 (string->symbol command)
2003 args))))
2004
2005 (define (guix-main arg0 . args)
2006 (initialize-guix)
2007 (apply run-guix args))
2008
2009 ;;; Local Variables:
2010 ;;; eval: (put 'guard* 'scheme-indent-function 2)
2011 ;;; End:
2012
2013 ;;; ui.scm ends here