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