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