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