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