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