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