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