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