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