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