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