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