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