derivations: Simplify 'substitution-oracle'.
[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 inputs #:mode mode)
839 (const #f)))
840
841 (let*-values (((build download)
842 (derivation-build-plan store inputs
843 #:mode mode
844 #:substitutable-info
845 substitutable-info))
846 ((graft hook build)
847 (match (fold (lambda (drv acc)
848 (let ((file (derivation-file-name drv)))
849 (match acc
850 ((#:graft graft #:hook hook #:build build)
851 (cond
852 ((graft-derivation? drv)
853 `(#:graft ,(cons file graft)
854 #:hook ,hook
855 #:build ,build))
856 ((profile-hook-derivation? drv)
857 `(#:graft ,graft
858 #:hook ,(cons file hook)
859 #:build ,build))
860 (else
861 `(#:graft ,graft
862 #:hook ,hook
863 #:build ,(cons file build))))))))
864 '(#:graft () #:hook () #:build ())
865 build)
866 ((#:graft graft #:hook hook #:build build)
867 (values graft hook build)))))
868 (define installed-size
869 (reduce + 0 (map substitutable-nar-size download)))
870
871 (define download-size
872 (/ (reduce + 0 (map substitutable-download-size download))
873 1e6))
874
875 (define display-download-size?
876 ;; Sometimes narinfos lack information about the download size. Only
877 ;; display when we have information for all of DOWNLOAD.
878 (not (any (compose zero? substitutable-download-size) download)))
879
880 (if dry-run?
881 (begin
882 (format (current-error-port)
883 (N_ "~:[The following derivation would be built:~%~{ ~a~%~}~;~]"
884 "~:[The following derivations would be built:~%~{ ~a~%~}~;~]"
885 (length build))
886 (null? build) build)
887 (if display-download-size?
888 (format (current-error-port)
889 ;; TRANSLATORS: "MB" is for "megabyte"; it should be
890 ;; translated to the corresponding abbreviation.
891 (G_ "~:[~,1h MB would be downloaded:~%~{ ~a~%~}~;~]")
892 (null? download)
893 download-size
894 (map substitutable-path download))
895 (format (current-error-port)
896 (N_ "~:[The following file would be downloaded:~%~{ ~a~%~}~;~]"
897 "~:[The following files would be downloaded:~%~{ ~a~%~}~;~]"
898 (length download))
899 (null? download)
900 (map substitutable-path download)))
901 (format (current-error-port)
902 (N_ "~:[The following graft would be made:~%~{ ~a~%~}~;~]"
903 "~:[The following grafts would be made:~%~{ ~a~%~}~;~]"
904 (length graft))
905 (null? graft) graft)
906 (format (current-error-port)
907 (N_ "~:[The following profile hook would be built:~%~{ ~a~%~}~;~]"
908 "~:[The following profile hooks would be built:~%~{ ~a~%~}~;~]"
909 (length hook))
910 (null? hook) hook))
911 (begin
912 (format (current-error-port)
913 (N_ "~:[The following derivation will be built:~%~{ ~a~%~}~;~]"
914 "~:[The following derivations will be built:~%~{ ~a~%~}~;~]"
915 (length build))
916 (null? build) build)
917 (if display-download-size?
918 (format (current-error-port)
919 ;; TRANSLATORS: "MB" is for "megabyte"; it should be
920 ;; translated to the corresponding abbreviation.
921 (G_ "~:[~,1h MB will be downloaded:~%~{ ~a~%~}~;~]")
922 (null? download)
923 download-size
924 (map substitutable-path download))
925 (format (current-error-port)
926 (N_ "~:[The following file will be downloaded:~%~{ ~a~%~}~;~]"
927 "~:[The following files will be downloaded:~%~{ ~a~%~}~;~]"
928 (length download))
929 (null? download)
930 (map substitutable-path download)))
931 (format (current-error-port)
932 (N_ "~:[The following graft will be made:~%~{ ~a~%~}~;~]"
933 "~:[The following grafts will be made:~%~{ ~a~%~}~;~]"
934 (length graft))
935 (null? graft) graft)
936 (format (current-error-port)
937 (N_ "~:[The following profile hook will be built:~%~{ ~a~%~}~;~]"
938 "~:[The following profile hooks will be built:~%~{ ~a~%~}~;~]"
939 (length hook))
940 (null? hook) hook)))
941
942 (check-available-space installed-size)
943
944 (pair? build)))
945
946 (define show-what-to-build*
947 (store-lift show-what-to-build))
948
949 (define (right-arrow port)
950 "Return either a string containing the 'RIGHT ARROW' character, or an ASCII
951 replacement if PORT is not Unicode-capable."
952 (let ((encoding (port-encoding port))
953 (arrow "→"))
954 (catch 'encoding-error
955 (lambda ()
956 (call-with-output-string
957 (lambda (port)
958 (set-port-encoding! port encoding)
959 (set-port-conversion-strategy! port 'error)
960 (display arrow port))))
961 (lambda (key . args)
962 "->"))))
963
964 (define* (show-manifest-transaction store manifest transaction
965 #:key dry-run?)
966 "Display what will/would be installed/removed from MANIFEST by TRANSACTION."
967 (define (package-strings name version output item)
968 (map (lambda (name version output item)
969 (format #f " ~a~:[:~a~;~*~]\t~a\t~a"
970 name
971 (equal? output "out") output version
972 (if (package? item)
973 (package-output store item output)
974 item)))
975 name version output item))
976
977 (define → ;an arrow that can be represented on stderr
978 (right-arrow (current-error-port)))
979
980 (define (upgrade-string name old-version new-version output item)
981 (format #f " ~a~:[:~a~;~*~]\t~a ~a ~a\t~a"
982 name (equal? output "out") output
983 old-version → new-version
984 (if (package? item)
985 (package-output store item output)
986 item)))
987
988 (let-values (((remove install upgrade downgrade)
989 (manifest-transaction-effects manifest transaction)))
990 (match remove
991 ((($ <manifest-entry> name version output item) ..1)
992 (let ((len (length name))
993 (remove (package-strings name version output item)))
994 (if dry-run?
995 (format (current-error-port)
996 (N_ "The following package would be removed:~%~{~a~%~}~%"
997 "The following packages would be removed:~%~{~a~%~}~%"
998 len)
999 remove)
1000 (format (current-error-port)
1001 (N_ "The following package will be removed:~%~{~a~%~}~%"
1002 "The following packages will be removed:~%~{~a~%~}~%"
1003 len)
1004 remove))))
1005 (x #f))
1006 (match downgrade
1007 (((($ <manifest-entry> name old-version)
1008 . ($ <manifest-entry> _ new-version output item)) ..1)
1009 (let ((len (length name))
1010 (downgrade (map upgrade-string
1011 name old-version new-version output item)))
1012 (if dry-run?
1013 (format (current-error-port)
1014 (N_ "The following package would be downgraded:~%~{~a~%~}~%"
1015 "The following packages would be downgraded:~%~{~a~%~}~%"
1016 len)
1017 downgrade)
1018 (format (current-error-port)
1019 (N_ "The following package will be downgraded:~%~{~a~%~}~%"
1020 "The following packages will be downgraded:~%~{~a~%~}~%"
1021 len)
1022 downgrade))))
1023 (x #f))
1024 (match upgrade
1025 (((($ <manifest-entry> name old-version)
1026 . ($ <manifest-entry> _ new-version output item)) ..1)
1027 (let ((len (length name))
1028 (upgrade (map upgrade-string
1029 name old-version new-version output item)))
1030 (if dry-run?
1031 (format (current-error-port)
1032 (N_ "The following package would be upgraded:~%~{~a~%~}~%"
1033 "The following packages would be upgraded:~%~{~a~%~}~%"
1034 len)
1035 upgrade)
1036 (format (current-error-port)
1037 (N_ "The following package will be upgraded:~%~{~a~%~}~%"
1038 "The following packages will be upgraded:~%~{~a~%~}~%"
1039 len)
1040 upgrade))))
1041 (x #f))
1042 (match install
1043 ((($ <manifest-entry> name version output item _) ..1)
1044 (let ((len (length name))
1045 (install (package-strings name version output item)))
1046 (if dry-run?
1047 (format (current-error-port)
1048 (N_ "The following package would be installed:~%~{~a~%~}~%"
1049 "The following packages would be installed:~%~{~a~%~}~%"
1050 len)
1051 install)
1052 (format (current-error-port)
1053 (N_ "The following package will be installed:~%~{~a~%~}~%"
1054 "The following packages will be installed:~%~{~a~%~}~%"
1055 len)
1056 install))))
1057 (x #f))))
1058
1059 (define-syntax with-error-handling
1060 (syntax-rules ()
1061 "Run BODY within a user-friendly error condition handler."
1062 ((_ body ...)
1063 (call-with-error-handling
1064 (lambda ()
1065 body ...)))))
1066
1067 (define* (fill-paragraph str width #:optional (column 0))
1068 "Fill STR such that each line contains at most WIDTH characters, assuming
1069 that the first character is at COLUMN.
1070
1071 When STR contains a single line break surrounded by other characters, it is
1072 converted to a space; sequences of more than one line break are preserved."
1073 (define (maybe-break chr result)
1074 (match result
1075 ((column newlines chars)
1076 (case chr
1077 ((#\newline)
1078 `(,column ,(+ 1 newlines) ,chars))
1079 (else
1080 (let* ((spaces (if (and (pair? chars) (eqv? (car chars) #\.)) 2 1))
1081 (chars (case newlines
1082 ((0) chars)
1083 ((1)
1084 (append (make-list spaces #\space) chars))
1085 (else
1086 (append (make-list newlines #\newline) chars))))
1087 (column (case newlines
1088 ((0) column)
1089 ((1) (+ spaces column))
1090 (else 0))))
1091 (let ((chars (cons chr chars))
1092 (column (+ 1 column)))
1093 (if (> column width)
1094 (let*-values (((before after)
1095 (break (cut eqv? #\space <>) chars))
1096 ((len)
1097 (length before)))
1098 (if (<= len width)
1099 `(,len
1100 0
1101 ,(if (null? after)
1102 before
1103 (append before
1104 (cons #\newline
1105 (drop-while (cut eqv? #\space <>)
1106 after)))))
1107 `(,column 0 ,chars))) ; unbreakable
1108 `(,column 0 ,chars)))))))))
1109
1110 (match (string-fold maybe-break
1111 `(,column 0 ())
1112 str)
1113 ((column newlines chars)
1114 (list->string (reverse chars)))))
1115
1116 \f
1117 ;;;
1118 ;;; Packages.
1119 ;;;
1120
1121 (define %text-width
1122 (make-parameter (terminal-columns)))
1123
1124 (set! (@@ (texinfo plain-text) wrap*)
1125 ;; XXX: Monkey patch this private procedure to let 'package->recutils'
1126 ;; parameterize the fill of description field correctly.
1127 (lambda strings
1128 (let ((indent (fluid-ref (@@ (texinfo plain-text) *indent*))))
1129 (fill-string (string-concatenate strings)
1130 #:line-width (%text-width) #:initial-indent indent
1131 #:subsequent-indent indent))))
1132
1133 (define (texi->plain-text str)
1134 "Return a plain-text representation of texinfo fragment STR."
1135 ;; 'texi-fragment->stexi' uses a string port so make sure it's a
1136 ;; Unicode-capable one (see <http://bugs.gnu.org/11197>.)
1137 (with-fluids ((%default-port-encoding "UTF-8"))
1138 (stexi->plain-text (texi-fragment->stexi str))))
1139
1140 (define (package-field-string package field-accessor)
1141 "Return a plain-text representation of PACKAGE field."
1142 (and=> (field-accessor package)
1143 (compose texi->plain-text P_)))
1144
1145 (define (package-description-string package)
1146 "Return a plain-text representation of PACKAGE description field."
1147 (package-field-string package package-description))
1148
1149 (define (package-synopsis-string package)
1150 "Return a plain-text representation of PACKAGE synopsis field."
1151 (package-field-string package package-synopsis))
1152
1153 (define (string->recutils str)
1154 "Return a version of STR where newlines have been replaced by newlines
1155 followed by \"+ \", which makes for a valid multi-line field value in the
1156 `recutils' syntax."
1157 (list->string
1158 (string-fold-right (lambda (chr result)
1159 (if (eqv? chr #\newline)
1160 (cons* chr #\+ #\space result)
1161 (cons chr result)))
1162 '()
1163 str)))
1164
1165 (define* (package->recutils p port #:optional (width (%text-width))
1166 #:key (extra-fields '()))
1167 "Write to PORT a `recutils' record of package P, arranging to fit within
1168 WIDTH columns. EXTRA-FIELDS is a list of symbol/value pairs to emit."
1169 (define width*
1170 ;; The available number of columns once we've taken into account space for
1171 ;; the initial "+ " prefix.
1172 (if (> width 2) (- width 2) width))
1173
1174 (define (dependencies->recutils packages)
1175 (let ((list (string-join (delete-duplicates
1176 (map package-full-name
1177 (sort packages package<?))) " ")))
1178 (string->recutils
1179 (fill-paragraph list width*
1180 (string-length "dependencies: ")))))
1181
1182 (define (package<? p1 p2)
1183 (string<? (package-full-name p1) (package-full-name p2)))
1184
1185 ;; Note: Don't i18n field names so that people can post-process it.
1186 (format port "name: ~a~%" (package-name p))
1187 (format port "version: ~a~%" (package-version p))
1188 (format port "outputs: ~a~%" (string-join (package-outputs p)))
1189 (format port "systems: ~a~%"
1190 (string-join (package-transitive-supported-systems p)))
1191 (format port "dependencies: ~a~%"
1192 (match (package-direct-inputs p)
1193 (((labels inputs . _) ...)
1194 (dependencies->recutils (filter package? inputs)))))
1195 (format port "location: ~a~%"
1196 (or (and=> (package-location p) location->string)
1197 (G_ "unknown")))
1198
1199 ;; Note: Starting from version 1.6 or recutils, hyphens are not allowed in
1200 ;; field identifiers.
1201 (format port "homepage: ~a~%" (package-home-page p))
1202
1203 (format port "license: ~a~%"
1204 (match (package-license p)
1205 (((? license? licenses) ...)
1206 (string-join (map license-name licenses)
1207 ", "))
1208 ((? license? license)
1209 (license-name license))
1210 (x
1211 (G_ "unknown"))))
1212 (format port "synopsis: ~a~%"
1213 (string-map (match-lambda
1214 (#\newline #\space)
1215 (chr chr))
1216 (or (and=> (package-synopsis-string p) P_)
1217 "")))
1218 (format port "~a~%"
1219 (string->recutils
1220 (string-trim-right
1221 (parameterize ((%text-width width*))
1222 (texi->plain-text
1223 (string-append "description: "
1224 (or (and=> (package-description p) P_)
1225 ""))))
1226 #\newline)))
1227 (for-each (match-lambda
1228 ((field . value)
1229 (let ((field (symbol->string field)))
1230 (format port "~a: ~a~%"
1231 field
1232 (fill-paragraph (object->string value) width*
1233 (string-length field))))))
1234 extra-fields)
1235 (newline port))
1236
1237 \f
1238 ;;;
1239 ;;; Searching.
1240 ;;;
1241
1242 (define (relevance obj regexps metrics)
1243 "Compute a \"relevance score\" for OBJ as a function of its number of
1244 matches of REGEXPS and accordingly to METRICS. METRICS is list of
1245 field/weight pairs, where FIELD is a procedure that returns a string or list
1246 of strings describing OBJ, and WEIGHT is a positive integer denoting the
1247 weight of this field in the final score.
1248
1249 A score of zero means that OBJ does not match any of REGEXPS. The higher the
1250 score, the more relevant OBJ is to REGEXPS."
1251 (define (score str)
1252 (define scores
1253 (map (lambda (regexp)
1254 (fold-matches regexp str 0
1255 (lambda (m score)
1256 (+ score
1257 (if (string=? (match:substring m) str)
1258 5 ;exact match
1259 1)))))
1260 regexps))
1261
1262 ;; Return zero if one of REGEXPS doesn't match.
1263 (if (any zero? scores)
1264 0
1265 (reduce + 0 scores)))
1266
1267 (fold (lambda (metric relevance)
1268 (match metric
1269 ((field . weight)
1270 (match (field obj)
1271 (#f relevance)
1272 ((? string? str)
1273 (+ relevance (* (score str) weight)))
1274 ((lst ...)
1275 (+ relevance (* weight (apply + (map score lst)))))))))
1276 0
1277 metrics))
1278
1279 (define %package-metrics
1280 ;; Metrics used to compute the "relevance score" of a package against a set
1281 ;; of regexps.
1282 `((,package-name . 4)
1283
1284 ;; Match against uncommon outputs.
1285 (,(lambda (package)
1286 (filter (lambda (output)
1287 (not (member output
1288 ;; Some common outpus shared by many packages.
1289 '("out" "doc" "debug" "lib" "include" "bin"))))
1290 (package-outputs package)))
1291 . 1)
1292
1293 ;; Match regexps on the raw Texinfo since formatting it is quite expensive
1294 ;; and doesn't have much of an effect on search results.
1295 (,(lambda (package)
1296 (and=> (package-synopsis package) P_)) . 3)
1297 (,(lambda (package)
1298 (and=> (package-description package) P_)) . 2)
1299
1300 (,(lambda (type)
1301 (match (and=> (package-location type) location-file)
1302 ((? string? file) (basename file ".scm"))
1303 (#f "")))
1304 . 1)))
1305
1306 (define (package-relevance package regexps)
1307 "Return a score denoting the relevance of PACKAGE for REGEXPS. A score of
1308 zero means that PACKAGE does not match any of REGEXPS."
1309 (relevance package regexps %package-metrics))
1310
1311 (define* (display-search-results matches port
1312 #:key
1313 (command "guix search")
1314 (print package->recutils))
1315 "Display MATCHES, a list of object/score pairs, by calling PRINT on each of
1316 them. If PORT is a terminal, print at most a full screen of results."
1317 (define first-line
1318 (port-line port))
1319
1320 (define max-rows
1321 (and first-line (isatty? port)
1322 (terminal-rows port)))
1323
1324 (define (line-count str)
1325 (string-count str #\newline))
1326
1327 (let loop ((matches matches))
1328 (match matches
1329 (((package . score) rest ...)
1330 (let ((text (call-with-output-string
1331 (lambda (port)
1332 (print package port
1333 #:extra-fields
1334 `((relevance . ,score)))))))
1335 (if (and max-rows
1336 (> (port-line port) first-line) ;print at least one result
1337 (> (+ 4 (line-count text) (port-line port))
1338 max-rows))
1339 (unless (null? rest)
1340 (display-hint (format #f (G_ "Run @code{~a ... | less} \
1341 to view all the results.")
1342 command)))
1343 (begin
1344 (display text port)
1345 (loop rest)))))
1346 (()
1347 #t))))
1348
1349 \f
1350 (define (string->generations str)
1351 "Return the list of generations matching a pattern in STR. This function
1352 accepts the following patterns: \"1\", \"1,2,3\", \"1..9\", \"1..\", \"..9\"."
1353 (define (maybe-integer)
1354 (let ((x (string->number str)))
1355 (and (integer? x)
1356 x)))
1357
1358 (define (maybe-comma-separated-integers)
1359 (let ((lst (delete-duplicates
1360 (map string->number
1361 (string-split str #\,)))))
1362 (and (every integer? lst)
1363 lst)))
1364
1365 (cond ((maybe-integer)
1366 =>
1367 list)
1368 ((maybe-comma-separated-integers)
1369 =>
1370 identity)
1371 ((string-match "^([0-9]+)\\.\\.([0-9]+)$" str)
1372 =>
1373 (lambda (match)
1374 (let ((s (string->number (match:substring match 1)))
1375 (e (string->number (match:substring match 2))))
1376 (and (every integer? (list s e))
1377 (<= s e)
1378 (iota (1+ (- e s)) s)))))
1379 ((string-match "^([0-9]+)\\.\\.$" str)
1380 =>
1381 (lambda (match)
1382 (let ((s (string->number (match:substring match 1))))
1383 (and (integer? s)
1384 `(>= ,s)))))
1385 ((string-match "^\\.\\.([0-9]+)$" str)
1386 =>
1387 (lambda (match)
1388 (let ((e (string->number (match:substring match 1))))
1389 (and (integer? e)
1390 `(<= ,e)))))
1391 (else #f)))
1392
1393 (define (string->duration str)
1394 "Return the duration matching a pattern in STR. This function accepts the
1395 following patterns: \"1d\", \"1w\", \"1m\"."
1396 (define (hours->duration hours match)
1397 (make-time time-duration 0
1398 (* 3600 hours (string->number (match:substring match 1)))))
1399
1400 (cond ((string-match "^([0-9]+)s$" str)
1401 =>
1402 (lambda (match)
1403 (make-time time-duration 0
1404 (string->number (match:substring match 1)))))
1405 ((string-match "^([0-9]+)h$" str)
1406 =>
1407 (lambda (match)
1408 (hours->duration 1 match)))
1409 ((string-match "^([0-9]+)d$" str)
1410 =>
1411 (lambda (match)
1412 (hours->duration 24 match)))
1413 ((string-match "^([0-9]+)w$" str)
1414 =>
1415 (lambda (match)
1416 (hours->duration (* 24 7) match)))
1417 ((string-match "^([0-9]+)m$" str)
1418 =>
1419 (lambda (match)
1420 (hours->duration (* 24 30) match)))
1421 (else #f)))
1422
1423 (define* (matching-generations str profile
1424 #:key (duration-relation <=))
1425 "Return the list of available generations matching a pattern in STR. See
1426 'string->generations' and 'string->duration' for the list of valid patterns.
1427 When STR is a duration pattern, return all the generations whose ctime has
1428 DURATION-RELATION with the current time."
1429 (define (valid-generations lst)
1430 (define (valid-generation? n)
1431 (any (cut = n <>) (generation-numbers profile)))
1432
1433 (fold-right (lambda (x acc)
1434 (if (valid-generation? x)
1435 (cons x acc)
1436 acc))
1437 '()
1438 lst))
1439
1440 (define (filter-generations generations)
1441 (match generations
1442 (() '())
1443 (('>= n)
1444 (drop-while (cut > n <>)
1445 (generation-numbers profile)))
1446 (('<= n)
1447 (valid-generations (iota n 1)))
1448 ((lst ..1)
1449 (valid-generations lst))
1450 (x #f)))
1451
1452 (define (filter-by-duration duration)
1453 (define (time-at-midnight time)
1454 ;; Return TIME at midnight by setting nanoseconds, seconds, minutes, and
1455 ;; hours to zeros.
1456 (let ((d (time-utc->date time)))
1457 (date->time-utc
1458 (make-date 0 0 0 0
1459 (date-day d) (date-month d)
1460 (date-year d) (date-zone-offset d)))))
1461
1462 (define generation-ctime-alist
1463 (map (lambda (number)
1464 (cons number
1465 (time-second
1466 (time-at-midnight
1467 (generation-time profile number)))))
1468 (generation-numbers profile)))
1469
1470 (match duration
1471 (#f #f)
1472 (res
1473 (let ((s (time-second
1474 (subtract-duration (time-at-midnight (current-time))
1475 duration))))
1476 (delete #f (map (lambda (x)
1477 (and (duration-relation s (cdr x))
1478 (first x)))
1479 generation-ctime-alist))))))
1480
1481 (cond ((string->generations str)
1482 =>
1483 filter-generations)
1484 ((string->duration str)
1485 =>
1486 filter-by-duration)
1487 (else #f)))
1488
1489 (define (display-generation profile number)
1490 "Display a one-line summary of generation NUMBER of PROFILE."
1491 (unless (zero? number)
1492 (let ((header (format #f (highlight (G_ "Generation ~a\t~a")) number
1493 (date->string
1494 (time-utc->date
1495 (generation-time profile number))
1496 ;; TRANSLATORS: This is a format-string for date->string.
1497 ;; Please choose a format that corresponds to the
1498 ;; usual way of presenting dates in your locale.
1499 ;; See https://www.gnu.org/software/guile/manual/html_node/SRFI_002d19-Date-to-string.html
1500 ;; for details.
1501 (G_ "~b ~d ~Y ~T"))))
1502 (current (generation-number profile)))
1503 (if (= number current)
1504 ;; TRANSLATORS: The word "current" here is an adjective for
1505 ;; "Generation", as in "current generation". Use the appropriate
1506 ;; gender where applicable.
1507 (format #t (G_ "~a\t(current)~%") header)
1508 (format #t "~a~%" header)))))
1509
1510 (define (display-profile-content-diff profile gen1 gen2)
1511 "Display the changed packages in PROFILE GEN2 compared to generation GEN1."
1512
1513 (define (equal-entry? first second)
1514 (string= (manifest-entry-item first) (manifest-entry-item second)))
1515
1516 (define (display-entry entry prefix)
1517 (match entry
1518 (($ <manifest-entry> name version output location _)
1519 (format #t " ~a ~a\t~a\t~a\t~a~%" prefix name version output location))))
1520
1521 (define (list-entries number)
1522 (manifest-entries (profile-manifest (generation-file-name profile number))))
1523
1524 (define (display-diff profile old new)
1525 (display-generation profile new)
1526 (let ((added (lset-difference
1527 equal-entry? (list-entries new) (list-entries old)))
1528 (removed (lset-difference
1529 equal-entry? (list-entries old) (list-entries new))))
1530 (for-each (cut display-entry <> "+") added)
1531 (for-each (cut display-entry <> "-") removed)
1532 (newline)))
1533
1534 (display-diff profile gen1 gen2))
1535
1536 (define (display-profile-content profile number)
1537 "Display the packages in PROFILE, generation NUMBER, in a human-readable
1538 way."
1539 (for-each (match-lambda
1540 (($ <manifest-entry> name version output location _)
1541 (format #t " ~a\t~a\t~a\t~a~%"
1542 name version output location)))
1543
1544 ;; Show most recently installed packages last.
1545 (reverse
1546 (manifest-entries
1547 (profile-manifest (generation-file-name profile number))))))
1548
1549 (define (display-generation-change previous current)
1550 (format #t (G_ "switched from generation ~a to ~a~%") previous current))
1551
1552 (define (roll-back* store profile)
1553 "Like 'roll-back', but display what is happening."
1554 (call-with-values
1555 (lambda ()
1556 (roll-back store profile))
1557 display-generation-change))
1558
1559 (define (switch-to-generation* profile number)
1560 "Like 'switch-generation', but display what is happening."
1561 (let ((previous (switch-to-generation profile number)))
1562 (display-generation-change previous number)))
1563
1564 (define (delete-generation* store profile generation)
1565 "Like 'delete-generation', but display what is going on."
1566 (format #t (G_ "deleting ~a~%")
1567 (generation-file-name profile generation))
1568 (delete-generation store profile generation))
1569
1570 (define* (package-specification->name+version+output spec
1571 #:optional (output "out"))
1572 "Parse package specification SPEC and return three value: the specified
1573 package name, version number (or #f), and output name (or OUTPUT). SPEC may
1574 optionally contain a version number and an output name, as in these examples:
1575
1576 guile
1577 guile@2.0.9
1578 guile:debug
1579 guile@2.0.9:debug
1580 "
1581 (let*-values (((name sub-drv)
1582 (match (string-rindex spec #\:)
1583 (#f (values spec output))
1584 (colon (values (substring spec 0 colon)
1585 (substring spec (+ 1 colon))))))
1586 ((name version)
1587 (package-name->name+version name)))
1588 (values name version sub-drv)))
1589
1590 \f
1591 ;;;
1592 ;;; Command-line option processing.
1593 ;;;
1594
1595 (define (show-guix-usage)
1596 (format (current-error-port)
1597 (G_ "Try `guix --help' for more information.~%"))
1598 (exit 1))
1599
1600 (define (command-files)
1601 "Return the list of source files that define Guix sub-commands."
1602 (define directory
1603 (and=> (search-path %load-path "guix.scm")
1604 (compose (cut string-append <> "/guix/scripts")
1605 dirname)))
1606
1607 (define dot-scm?
1608 (cut string-suffix? ".scm" <>))
1609
1610 (if directory
1611 (scandir directory dot-scm?)
1612 '()))
1613
1614 (define (commands)
1615 "Return the list of Guix command names."
1616 (map (compose (cut string-drop-right <> 4)
1617 basename)
1618 (command-files)))
1619
1620 (define (show-guix-help)
1621 (define (internal? command)
1622 (member command '("substitute" "authenticate" "offload"
1623 "perform-download")))
1624
1625 (format #t (G_ "Usage: guix COMMAND ARGS...
1626 Run COMMAND with ARGS.\n"))
1627 (newline)
1628 (format #t (G_ "COMMAND must be one of the sub-commands listed below:\n"))
1629 (newline)
1630 ;; TODO: Display a synopsis of each command.
1631 (format #t "~{ ~a~%~}" (sort (remove internal? (commands))
1632 string<?))
1633 (show-bug-report-information))
1634
1635 (define (run-guix-command command . args)
1636 "Run COMMAND with the given ARGS. Report an error when COMMAND is not
1637 found."
1638 (define module
1639 (catch 'misc-error
1640 (lambda ()
1641 (resolve-interface `(guix scripts ,command)))
1642 (lambda -
1643 (format (current-error-port)
1644 (G_ "guix: ~a: command not found~%") command)
1645 (show-guix-usage))))
1646
1647 (let ((command-main (module-ref module
1648 (symbol-append 'guix- command))))
1649 (parameterize ((program-name command))
1650 ;; Disable canonicalization so we don't don't stat unreasonably.
1651 (with-fluids ((%file-port-name-canonicalization #f))
1652 (dynamic-wind
1653 (const #f)
1654 (lambda ()
1655 (apply command-main args))
1656 (lambda ()
1657 ;; Abuse 'exit-hook' (which is normally meant to be used by the
1658 ;; REPL) to run things like profiling hooks upon completion.
1659 (run-hook exit-hook)))))))
1660
1661 (define (run-guix . args)
1662 "Run the 'guix' command defined by command line ARGS.
1663 Unlike 'guix-main', this procedure assumes that locale, i18n support,
1664 and signal handling has already been set up."
1665 (define option? (cut string-prefix? "-" <>))
1666
1667 ;; The default %LOAD-EXTENSIONS includes the empty string, which doubles the
1668 ;; number of 'stat' calls per entry in %LOAD-PATH. Shamelessly remove it.
1669 (set! %load-extensions '(".scm"))
1670
1671 (match args
1672 (()
1673 (format (current-error-port)
1674 (G_ "guix: missing command name~%"))
1675 (show-guix-usage))
1676 ((or ("-h") ("--help"))
1677 (show-guix-help))
1678 ((or ("-V") ("--version"))
1679 (show-version-and-exit "guix"))
1680 (((? option? o) args ...)
1681 (format (current-error-port)
1682 (G_ "guix: unrecognized option '~a'~%") o)
1683 (show-guix-usage))
1684 (("help" command)
1685 (apply run-guix-command (string->symbol command)
1686 '("--help")))
1687 (("help" args ...)
1688 (show-guix-help))
1689 ((command args ...)
1690 (apply run-guix-command
1691 (string->symbol command)
1692 args))))
1693
1694 (define (guix-main arg0 . args)
1695 (initialize-guix)
1696 (apply run-guix args))
1697
1698 ;;; ui.scm ends here