gnu: add convmv.
[jackhill/guix/guix.git] / guix / ui.scm
CommitLineData
233e7676 1;;; GNU Guix --- Functional package management for GNU
09edf136 2;;; Copyright © 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Ludovic Courtès <ludo@gnu.org>
cbdfa50d 3;;; Copyright © 2013, 2018 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>
85c3fbf5 12;;; Copyright © 2018 Kyle Meyer <kyle@kyleam.com>
15cc7e6a 13;;; Copyright © 2018 Ricardo Wurmus <rekado@elephly.net>
387e6b9e
CM
14;;; Copyright © 2019 Chris Marusich <cmmarusich@gmail.com>
15;;; Copyright © 2019 Tobias Geerinckx-Rice <me@tobias.gr>
d2cdef65 16;;; Copyright © 2019 Simon Tournier <zimon.toutoune@gmail.com>
e70a8847 17;;; Copyright © 2020 Arun Isaac <arunisaac@systemreboot.net>
073c34d7 18;;;
233e7676 19;;; This file is part of GNU Guix.
073c34d7 20;;;
233e7676 21;;; GNU Guix is free software; you can redistribute it and/or modify it
073c34d7
LC
22;;; under the terms of the GNU General Public License as published by
23;;; the Free Software Foundation; either version 3 of the License, or (at
24;;; your option) any later version.
25;;;
233e7676 26;;; GNU Guix is distributed in the hope that it will be useful, but
073c34d7
LC
27;;; WITHOUT ANY WARRANTY; without even the implied warranty of
28;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29;;; GNU General Public License for more details.
30;;;
31;;; You should have received a copy of the GNU General Public License
233e7676 32;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
073c34d7
LC
33
34(define-module (guix ui)
37eed374 35 #:use-module (guix i18n)
9e1e0460 36 #:use-module (guix colors)
1b5ee3bd 37 #:use-module (guix diagnostics)
3e43166f 38 #:use-module (guix gexp)
b5bfa477 39 #:use-module (guix sets)
073c34d7
LC
40 #:use-module (guix utils)
41 #:use-module (guix store)
cdd5d6f9 42 #:use-module (guix config)
073c34d7 43 #:use-module (guix packages)
5d7a8584 44 #:use-module (guix profiles)
9bb2b96a 45 #:use-module (guix derivations)
b7071bc5
LC
46 #:use-module (guix build-system)
47 #:use-module (guix serialization)
edd25a8c
LC
48 #:use-module ((guix licenses)
49 #:select (license? license-name license-uri))
dcfc6f21 50 #:use-module ((guix build syscalls)
55e1dfa4
LC
51 #:select (free-disk-space terminal-columns terminal-rows
52 with-file-lock/no-wait))
cbdfa50d 53 #:use-module ((guix build utils)
24cb66d1
LC
54 ;; XXX: All we need are the bindings related to
55 ;; '&invoke-error'. However, to work around the bug described
56 ;; in 5d669883ecc104403c5d3ba7d172e9c02234577c, #:hide
57 ;; unwanted bindings instead of #:select'ing the needed
58 ;; bindings.
5a2639f9
LC
59 #:hide (package-name->name+version
60 ;; Avoid "overrides core binding" warning.
61 delete))
299112d3
LC
62 #:use-module (srfi srfi-1)
63 #:use-module (srfi srfi-11)
2cd09108 64 #:use-module (srfi srfi-19)
073c34d7 65 #:use-module (srfi srfi-26)
2abcc97f 66 #:use-module (srfi srfi-31)
073c34d7 67 #:use-module (srfi srfi-34)
c1d52c71 68 #:use-module (srfi srfi-35)
e31ff8b8 69 #:autoload (ice-9 ftw) (scandir)
64fc89b6 70 #:use-module (ice-9 match)
9bb2b96a 71 #:use-module (ice-9 format)
2cd09108 72 #:use-module (ice-9 regex)
c39693d7 73 #:autoload (ice-9 popen) (open-pipe* close-pipe)
f44c7aac 74 #:autoload (system base compile) (compile-file)
db030303
LC
75 #:autoload (system repl repl) (start-repl)
76 #:autoload (system repl debug) (make-debug stack->vector)
7f0f38b5 77 #:autoload (web uri) (encode-and-join-uri-path)
1cd4027c
ML
78 #:use-module (texinfo)
79 #:use-module (texinfo plain-text)
80 #:use-module (texinfo string-utils)
1b5ee3bd
LC
81
82 ;; Re-exports for backward compatibility.
83 #:re-export (G_ N_ P_ ;now in (guix i18n)
84
85 warning info report-error leave ;now in (guix diagnostics)
86 location->string
87 guix-warning-port program-name)
88 #:export (display-hint
7ea1432e
DT
89 make-user-module
90 load*
4ae7559f 91 warn-about-load-error
cdd5d6f9 92 show-version-and-exit
3441e164 93 show-bug-report-information
fd688c82 94 make-regexp*
969e678e 95 string->number*
1d6243cf 96 size->number
fa394eb9 97 show-derivation-outputs
07ce23e0 98 build-notifier
9bb2b96a 99 show-what-to-build
4d043ab6 100 show-what-to-build*
5d7a8584 101 show-manifest-transaction
073c34d7 102 call-with-error-handling
64fc89b6 103 with-error-handling
2d2f98ef 104 with-unbound-variable-handling
df36e629 105 leave-on-EPIPE
ac5de156 106 read/eval
eb0880e7 107 read/eval-package-expression
8120b23e 108 check-available-space
7b322d3c 109 indented-string
299112d3 110 fill-paragraph
0649321d 111 %text-width
2748ee3b 112 texi->plain-text
1cd4027c 113 package-description-string
689db38e 114 package-synopsis-string
299112d3 115 string->recutils
e49951eb 116 package->recutils
2876b989 117 package-specification->name+version+output
4311cf96 118
7f0f38b5 119 supports-hyperlinks?
2d6bd5ed 120 hyperlink
fa983b82 121 file-hyperlink
7f0f38b5
LC
122 location->hyperlink
123
c7ae219e
LC
124 relevance
125 package-relevance
4311cf96
LC
126 display-search-results
127
55e1dfa4 128 with-profile-lock
2cd09108
NK
129 string->generations
130 string->duration
e49de93a 131 matching-generations
ad18c7e6
LC
132 display-generation
133 display-profile-content
e95ae7c2 134 display-profile-content-diff
06d45f45
LC
135 roll-back*
136 switch-to-generation*
137 delete-generation*
a725504a
LC
138
139 %default-message-language
140 current-message-language
141
e49951eb 142 run-guix-command
caa6732e 143 run-guix
5d9f9ad6 144 guix-main))
073c34d7
LC
145
146;;; Commentary:
147;;;
148;;; User interface facilities for command-line tools.
149;;;
150;;; Code:
151
dc856223
LC
152(define (print-unbound-variable-error port key args default-printer)
153 ;; Print unbound variable errors more nicely, and in the right language.
154 (match args
155 ((proc message (variable) _ ...)
156 ;; We can always omit PROC because when it's useful (i.e., different from
157 ;; "module-lookup"), it gets displayed before.
2d2f98ef 158 (format port (G_ "error: ~a: unbound variable") variable))
dc856223
LC
159 (_
160 (default-printer))))
161
162(set-exception-printer! 'unbound-variable print-unbound-variable-error)
163
7ea1432e
DT
164(define (make-user-module modules)
165 "Return a new user module with the additional MODULES loaded."
166 ;; Module in which the machine description file is loaded.
167 (let ((module (make-fresh-user-module)))
168 (for-each (lambda (iface)
169 (module-use! module (resolve-interface iface)))
170 modules)
171 module))
172
7f2f6a2c
LC
173(define (last-frame-with-source stack)
174 "Walk stack upwards and return the last frame that has source location
175information, or #f if it could not be found."
2abcc97f
LC
176 (define (frame-with-source frame)
177 ;; Walk from FRAME upwards until source location information is found.
178 (let loop ((frame frame)
179 (previous frame))
180 (if (not frame)
181 previous
abbb9871
LC
182
183 ;; On Guile 3, the latest frame with source may be that of
184 ;; 'raise-exception' in boot-9.scm. Skip it.
185 (if (and (frame-source frame)
186 (not (eq? 'raise-exception (frame-procedure-name frame))))
2abcc97f
LC
187 frame
188 (loop (frame-previous frame) frame)))))
189
7f2f6a2c
LC
190 (let* ((depth (stack-length stack))
191 (last (and (> depth 0) (stack-ref stack 0))))
192 (frame-with-source (if (> depth 1)
193 (stack-ref stack 1) ;skip the 'throw' frame
194 last))))
195
196(define* (load* file user-module
197 #:key (on-error 'nothing-special))
198 "Load the user provided Scheme source code FILE."
db030303
LC
199 (define (error-string frame args)
200 (call-with-output-string
f44c7aac
LC
201 (lambda (port)
202 (apply display-error frame port (cdr args)))))
db030303
LC
203
204 (define tag
205 (make-prompt-tag "user-code"))
206
7ea1432e
DT
207 (catch #t
208 (lambda ()
2abcc97f 209 ;; XXX: Force a recompilation to avoid ABI issues.
92423868
LC
210 ;;
211 ;; In 2.2.3, the bogus answer to <https://bugs.gnu.org/29226> was to
212 ;; ignore all available .go, not just those from ~/.cache, which in turn
213 ;; meant that we had to rebuild *everything*. Since this is too costly,
f44c7aac
LC
214 ;; we have to turn off '%fresh-auto-compile' with that version, so to
215 ;; avoid ABI breakage in the user's config file, we explicitly compile
216 ;; it (the problem remains if the user's config is spread on several
217 ;; modules.) See <https://bugs.gnu.org/29881>.
7949c140
LC
218 (unless (string=? (version) "2.2.3")
219 (set! %fresh-auto-compile #t))
92423868 220
2abcc97f 221 (set! %load-should-auto-compile #t)
7ea1432e
DT
222
223 (save-module-excursion
224 (lambda ()
225 (set-current-module user-module)
7ea1432e 226
2abcc97f
LC
227 ;; Hide the "auto-compiling" messages.
228 (parameterize ((current-warning-port (%make-void-port "w")))
db030303
LC
229 (call-with-prompt tag
230 (lambda ()
7949c140
LC
231 (when (string=? (version) "2.2.3")
232 (catch 'system-error
233 (lambda ()
234 (compile-file file #:env user-module))
235 (const #f))) ;EACCES maybe, let's interpret it
236
db030303
LC
237 ;; Give 'load' an absolute file name so that it doesn't try to
238 ;; search for FILE in %LOAD-PATH. Note: use 'load', not
694e10af
VL
239 ;; 'primitive-load', so that FILE is compiled, which then allows
240 ;; us to provide better error reporting with source line numbers.
db030303
LC
241 (load (canonicalize-path file)))
242 (const #f))))))
2abcc97f
LC
243 (lambda _
244 ;; XXX: Errors are reported from the pre-unwind handler below, but
245 ;; calling 'exit' from there has no effect, so we call it here.
246 (exit 1))
247 (rec (handle-error . args)
248 ;; Capture the stack up to this procedure call, excluded, and pass
249 ;; the faulty stack frame to 'report-load-error'.
db030303 250 (let* ((stack (make-stack #t handle-error tag))
7f2f6a2c 251 (frame (last-frame-with-source stack)))
db030303
LC
252
253 (report-load-error file args frame)
254
255 (case on-error
256 ((debug)
257 (newline)
69daee23 258 (display (G_ "entering debugger; type ',bt' for a backtrace\n"))
db030303
LC
259 (start-repl #:debug (make-debug (stack->vector stack) 0
260 (error-string frame args)
261 #f)))
262 ((backtrace)
263 (newline (current-error-port))
264 (display-backtrace stack (current-error-port)))
265 (else
266 #t))))))
2abcc97f 267
a2985bb1
LC
268(define (known-variable-definition variable)
269 "Search among the currently loaded modules one that defines a variable named
270VARIABLE and return it, or #f if none was found."
271 (define (module<? m1 m2)
272 (match (module-name m2)
273 (('gnu _ ...) #t)
274 (('guix _ ...)
275 (match (module-name m1)
276 (('gnu _ ...) #f)
277 (_ #t)))
278 (_ #f)))
279
b5bfa477
LC
280 (let loop ((modules (list (resolve-module '() #f #f #:ensure #f)))
281 (suggestions '())
282 (visited (setq)))
a2985bb1
LC
283 (match modules
284 (()
285 ;; Pick the "best" suggestion.
286 (match (sort suggestions module<?)
287 (() #f)
288 ((first _ ...) first)))
289 ((head tail ...)
b5bfa477
LC
290 (if (set-contains? visited head)
291 (loop tail suggestions visited)
292 (let ((visited (set-insert head visited))
293 (next (append tail
294 (hash-map->list (lambda (name module)
295 module)
296 (module-submodules head)))))
297 (match (module-local-variable head variable)
298 (#f (loop next suggestions visited))
299 (_
300 (match (module-name head)
301 (('gnu _ ...) head) ;must be that one
302 (_ (loop next (cons head suggestions) visited)))))))))))
a2985bb1 303
1b5ee3bd
LC
304(define %hint-color (color BOLD CYAN))
305
935542fb
LC
306(define* (display-hint message #:optional (port (current-error-port)))
307 "Display MESSAGE, a l10n message possibly containing Texinfo markup, to
308PORT."
a7ae18b1
LC
309 (define colorize
310 (if (color-output? port)
311 (lambda (str)
2569ef9d 312 (colorize-string str %hint-color))
a7ae18b1
LC
313 identity))
314
315 (display (colorize (G_ "hint: ")) port)
316 (display
317 ;; XXX: We should arrange so that the initial indent is wider.
318 (parameterize ((%text-width (max 15 (- (terminal-columns) 5))))
319 (texi->plain-text message))
320 port))
935542fb 321
2d2f98ef
LC
322(define* (report-unbound-variable-error args #:key frame)
323 "Return the given unbound-variable error, where ARGS is the list of 'throw'
324arguments."
325 (match args
326 ((key . args)
327 (print-exception (current-error-port) frame key args)))
328 (match args
329 (('unbound-variable proc message (variable) _ ...)
330 (match (known-variable-definition variable)
331 (#f
332 (display-hint (G_ "Did you forget a @code{use-modules} form?")))
333 ((? module? module)
334 (display-hint (format #f (G_ "Did you forget @code{(use-modules ~a)}?")
335 (module-name module))))))))
336
a2a94b6e
LC
337(define (check-module-matches-file module file)
338 "Check whether FILE starts with 'define-module MODULE' and print a hint if
339it doesn't."
340 ;; This is a common mistake when people start writing their own package
341 ;; definitions and try loading them with 'guix build -L …', so help them
342 ;; diagnose the problem.
343 (define (hint)
344 (display-hint (format #f (G_ "File @file{~a} should probably start with:
345
346@example\n(define-module ~a)\n@end example")
347 file module)))
348
349 (catch 'system-error
350 (lambda ()
351 (let* ((sexp (call-with-input-file file read))
352 (loc (and (pair? sexp)
353 (source-properties->location (source-properties sexp)))))
354 (match sexp
355 (('define-module (names ...) _ ...)
356 (unless (equal? module names)
357 (warning loc
358 (G_ "module name ~a does not match file name '~a'~%")
359 names (module->source-file-name module))
360 (hint)))
361 ((? eof-object?)
362 (warning (G_ "~a: file is empty~%") file))
363 (else
364 (hint)))))
365 (const #f)))
366
2abcc97f 367(define* (report-load-error file args #:optional frame)
db030303 368 "Report the failure to load FILE, a user-provided Scheme file.
1151f6ae
LC
369ARGS is the list of arguments received by the 'throw' handler."
370 (match args
e465d9e1 371 (('system-error . rest)
1151f6ae 372 (let ((err (system-error-errno args)))
69daee23 373 (report-error (G_ "failed to load '~a': ~a~%") file (strerror err))))
a6e22d84
LC
374 (('read-error "scm_i_lreadparen" message _ ...)
375 ;; Guile's missing-paren messages are obscure so we make them more
376 ;; intelligible here.
377 (if (string-suffix? "end of file" message)
378 (let ((location (string-drop-right message
379 (string-length "end of file"))))
380 (format (current-error-port) (G_ "~amissing closing parenthesis~%")
381 location))
382 (apply throw args)))
47212fc7 383 (('syntax-error proc message properties form subform . rest)
1151f6ae 384 (let ((loc (source-properties->location properties)))
47212fc7
LC
385 (report-error loc (G_ "~s: ~a~%")
386 (or subform form) message)))
2d2f98ef
LC
387 (('unbound-variable _ ...)
388 (report-unbound-variable-error args #:frame frame))
7f3bbfaf 389 (((or 'srfi-34 '%exception) obj)
f816dba6 390 (if (message-condition? obj)
40262771
LC
391 (report-error (and (error-location? obj)
392 (error-location obj))
393 (G_ "~a~%")
394 (gettext (condition-message obj) %gettext-domain))
23735137
LC
395 (report-error (G_ "exception thrown: ~s~%") obj))
396 (when (fix-hint? obj)
935542fb 397 (display-hint (condition-fix-hint obj))))
70a50305 398 ((key args ...)
69daee23 399 (report-error (G_ "failed to load '~a':~%") file)
70a50305
LC
400 (match args
401 (((? symbol? proc) (? string? message) (args ...) . rest)
402 (display-error frame (current-error-port) proc message
403 args rest))
404 (_
405 ;; Some exceptions like 'git-error' do not follow Guile's convention
406 ;; above and need to be printed with 'print-exception'.
407 (print-exception (current-error-port) frame key args))))))
1151f6ae 408
a2a94b6e 409(define (warn-about-load-error file module args) ;FIXME: factorize with ↑
4ae7559f
LC
410 "Report the failure to load FILE, a user-provided Scheme file, without
411exiting. ARGS is the list of arguments received by the 'throw' handler."
412 (match args
e465d9e1 413 (('system-error . rest)
4ae7559f 414 (let ((err (system-error-errno args)))
a2a94b6e 415 (warning (G_ "failed to load '~a': ~a~%") module (strerror err))))
4ae7559f
LC
416 (('syntax-error proc message properties form . rest)
417 (let ((loc (source-properties->location properties)))
40262771 418 (warning loc (G_ "~a~%") message)))
723bdb8e
LC
419 (('unbound-variable _ ...)
420 (report-unbound-variable-error args))
7f3bbfaf 421 (((or 'srfi-34 '%exception) obj)
f816dba6 422 (if (message-condition? obj)
69daee23 423 (warning (G_ "failed to load '~a': ~a~%")
f816dba6
LC
424 file
425 (gettext (condition-message obj) %gettext-domain))
69daee23 426 (warning (G_ "failed to load '~a': exception thrown: ~s~%")
f816dba6 427 file obj)))
4ae7559f 428 ((error args ...)
a2a94b6e
LC
429 (warning (G_ "failed to load '~a':~%") module)
430 (apply display-error #f (current-error-port) args)
431 (check-module-matches-file module file))))
4ae7559f 432
2d2f98ef
LC
433(define (call-with-unbound-variable-handling thunk)
434 (define tag
435 (make-prompt-tag "user-code"))
436
437 (catch 'unbound-variable
438 (lambda ()
439 (call-with-prompt tag
440 thunk
441 (const #f)))
442 (const #t)
443 (rec (handle-error . args)
444 (let* ((stack (make-stack #t handle-error tag))
445 (frame (and stack (last-frame-with-source stack))))
446 (report-unbound-variable-error args #:frame frame)
447 (exit 1)))))
448
449(define-syntax-rule (with-unbound-variable-handling exp ...)
450 "Capture 'unbound-variable' exceptions in the dynamic extent of EXP... and
451report them in a user-friendly way."
452 (call-with-unbound-variable-handling (lambda () exp ...)))
453
a725504a
LC
454(define %default-message-language
455 ;; Default language to use for messages.
456 (make-parameter "en"))
457
458(define (current-message-language)
459 "Return the language used for messages according to the current locale.
460Return %DEFAULT-MESSAGE-LANGUAGE if that information could not be obtained. The
461result is an ISO-639-2 language code such as \"ar\", without the territory
462part."
463 (let ((locale (setlocale LC_MESSAGES)))
464 (match (string-index locale #\_)
465 (#f locale)
466 (index (string-take locale index)))))
467
b2a886f6
LC
468(define (install-locale)
469 "Install the current locale settings."
470 (catch 'system-error
471 (lambda _
472 (setlocale LC_ALL ""))
473 (lambda args
26db747a
LC
474 (display-hint (G_ "Consider installing the @code{glibc-utf8-locales} or
475@code{glibc-locales} package and defining @code{GUIX_LOCPATH}, along these
476lines:
477
478@example
479guix package -i glibc-utf8-locales
480export GUIX_LOCPATH=\"$HOME/.guix-profile/lib/locale\"
481@end example
482
483See the \"Application Setup\" section in the manual, for more info.\n")))))
b2a886f6 484
e49951eb 485(define (initialize-guix)
633f045f 486 "Perform the usual initialization for stand-alone Guix commands."
ce92d269
LC
487 ;; By default don't annoy users with deprecation warnings. In practice,
488 ;; 'define-deprecated' in (ice-9 deprecated) arranges so that those warnings
489 ;; are emitted at expansion-time only, but there are cases where they could
490 ;; slip through, for instance when interpreting code.
491 (unless (getenv "GUILE_WARN_DEPRECATED")
492 (debug-disable 'warn-deprecated))
493
e49951eb 494 (install-locale)
39e9f95d 495 (textdomain %gettext-domain)
e14c3929
LC
496
497 ;; Ignore SIGPIPE. If the daemon closes the connection, we prefer to be
498 ;; notified via an EPIPE later.
499 (sigaction SIGPIPE SIG_IGN)
500
76832d34
LC
501 (setvbuf (current-output-port) 'line)
502 (setvbuf (current-error-port) 'line))
e49951eb 503
cdd5d6f9
LC
504(define* (show-version-and-exit #:optional (command (car (command-line))))
505 "Display version information for COMMAND and `(exit 0)'."
506 (simple-format #t "~a (~a) ~a~%"
507 command %guix-package-name %guix-version)
09edf136 508 (format #t "Copyright ~a 2020 ~a"
d925cdc3
LC
509 ;; TRANSLATORS: Translate "(C)" to the copyright symbol
510 ;; (C-in-a-circle), if this symbol is available in the user's
511 ;; locale. Otherwise, do not translate "(C)"; leave it as-is. */
69daee23
LC
512 (G_ "(C)")
513 (G_ "the Guix authors\n"))
514 (display (G_"\
64a967cc
LC
515License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
516This is free software: you are free to change and redistribute it.
517There is NO WARRANTY, to the extent permitted by law.
518"))
cdd5d6f9
LC
519 (exit 0))
520
3441e164 521(define (show-bug-report-information)
cf5f2ad3
ML
522 ;; TRANSLATORS: The placeholder indicates the bug-reporting address for this
523 ;; package. Please add another line saying "Report translation bugs to
524 ;; ...\n" with the address for translation bugs (typically your translation
525 ;; team's web or email address).
69daee23 526 (format #t (G_ "
3441e164 527Report bugs to: ~a.") %guix-bug-report-address)
69daee23 528 (format #t (G_ "
3441e164 529~a home page: <~a>") %guix-package-name %guix-home-page-url)
69daee23 530 (display (G_ "
3441e164
LC
531General help using GNU software: <http://www.gnu.org/gethelp/>"))
532 (newline))
533
e7ff0543
LC
534(define (augmented-system-error-handler file)
535 "Return a 'system-error' handler that mentions FILE in its message."
536 (lambda (key proc fmt args errno)
537 ;; Augment the FMT and ARGS with information about TARGET (this
538 ;; information is missing as of Guile 2.0.11, making the exception
539 ;; uninformative.)
540 (apply throw key proc "~A: ~S"
541 (list (strerror (car errno)) file)
542 (list errno))))
543
6616a352
TS
544(define-syntax apply-formals
545 (syntax-rules ()
546 ((_ proc (args ...)) (proc args ...))
547 ((_ proc (arg1 args ... . rest)) (apply proc arg1 args ... rest))))
548
549(define-syntax-rule (error-reporting-wrapper proc formals file)
e7ff0543
LC
550 "Wrap PROC such that its 'system-error' exceptions are augmented to mention
551FILE."
552 (let ((real-proc (@ (guile) proc)))
6616a352 553 (lambda formals
e7ff0543
LC
554 (catch 'system-error
555 (lambda ()
6616a352 556 (apply-formals real-proc formals))
e7ff0543
LC
557 (augmented-system-error-handler file)))))
558
7522a016
LC
559(set! symlink
560 ;; We 'set!' the global binding because (gnu build ...) modules and similar
561 ;; typically don't use (guix ui).
e7ff0543 562 (error-reporting-wrapper symlink (source target) target))
44fd6ef1 563
9b14107f
LC
564(set! copy-file
565 ;; Note: here we use 'set!', not #:replace, because UIs typically use
566 ;; 'copy-recursively', which doesn't use (guix ui).
e7ff0543
LC
567 (error-reporting-wrapper copy-file (source target) target))
568
6d30b1b2
LC
569(set! canonicalize-path
570 (error-reporting-wrapper canonicalize-path (file) file))
571
90b144d2
LC
572(set! delete-file
573 (error-reporting-wrapper delete-file (file) file))
574
6616a352
TS
575(set! execlp
576 (error-reporting-wrapper execlp (filename . args) filename))
9b14107f 577
fd688c82
LC
578(define (make-regexp* regexp . flags)
579 "Like 'make-regexp' but error out if REGEXP is invalid, reporting the error
580nicely."
581 (catch 'regular-expression-syntax
582 (lambda ()
583 (apply make-regexp regexp flags))
584 (lambda (key proc message . rest)
69daee23 585 (leave (G_ "'~a' is not a valid regular expression: ~a~%")
fd688c82
LC
586 regexp message))))
587
969e678e
LC
588(define (string->number* str)
589 "Like `string->number', but error out with an error message on failure."
590 (or (string->number str)
69daee23 591 (leave (G_ "~a: invalid number~%") str)))
969e678e 592
1d6243cf
LC
593(define (size->number str)
594 "Convert STR, a storage measurement representation such as \"1024\" or
595\"1MiB\", to a number of bytes. Raise an error if STR could not be
596interpreted."
597 (define unit-pos
fa99c4bb
LC
598 (string-rindex str
599 (char-set-union (char-set #\.) char-set:digit)))
1d6243cf
LC
600
601 (define unit
602 (and unit-pos (substring str (+ 1 unit-pos))))
603
604 (let* ((numstr (if unit-pos
605 (substring str 0 (+ 1 unit-pos))
606 str))
607 (num (string->number numstr)))
608 (unless num
69daee23 609 (leave (G_ "invalid number: ~a~%") numstr))
1d6243cf
LC
610
611 ((compose inexact->exact round)
612 (* num
613 (match unit
4a44d7bb
LC
614 ((or "KiB" "K" "k") (expt 2 10))
615 ((or "MiB" "M") (expt 2 20))
616 ((or "GiB" "G") (expt 2 30))
617 ((or "TiB" "T") (expt 2 40))
618 ((or "PiB" "P") (expt 2 50))
619 ((or "EiB" "E") (expt 2 60))
620 ((or "ZiB" "Z") (expt 2 70))
621 ((or "YiB" "Y") (expt 2 80))
622 ("kB" (expt 10 3))
1d6243cf
LC
623 ("MB" (expt 10 6))
624 ("GB" (expt 10 9))
625 ("TB" (expt 10 12))
4a44d7bb
LC
626 ("PB" (expt 10 15))
627 ("EB" (expt 10 18))
628 ("ZB" (expt 10 21))
629 ("YB" (expt 10 24))
1d6243cf 630 ("" 1)
e465d9e1 631 (x
69daee23 632 (leave (G_ "unknown unit: ~a~%") unit)))))))
1d6243cf 633
3b80b813
LC
634(define (display-collision-resolution-hint collision)
635 "Display hints on how to resolve COLLISION, a &profile-collistion-error."
636 (define (top-most-entry entry)
637 (let loop ((entry entry))
638 (match (force (manifest-entry-parent entry))
639 (#f entry)
640 (parent (loop parent)))))
641
642 (let* ((first (profile-collision-error-entry collision))
643 (second (profile-collision-error-conflict collision))
644 (name1 (manifest-entry-name (top-most-entry first)))
645 (name2 (manifest-entry-name (top-most-entry second))))
646 (if (string=? name1 name2)
647 (display-hint (format #f (G_ "You cannot have two different versions
648or variants of @code{~a} in the same profile.")
649 name1))
650 (display-hint (format #f (G_ "Try upgrading both @code{~a} and @code{~a},
651or remove one of them from the profile.")
652 name1 name2)))))
653
073c34d7
LC
654(define (call-with-error-handling thunk)
655 "Call THUNK within a user-friendly error handler."
bec7f352
LC
656 (define (port-filename* port)
657 ;; 'port-filename' returns #f for non-file ports, but it raises an
658 ;; exception for file ports that are closed. Work around that.
659 (and (not (port-closed? port))
660 (port-filename port)))
661
073c34d7
LC
662 (guard (c ((package-input-error? c)
663 (let* ((package (package-error-package c))
664 (input (package-error-invalid-input c))
665 (location (package-location package))
666 (file (location-file location))
667 (line (location-line location))
668 (column (location-column location)))
69daee23 669 (leave (G_ "~a:~a:~a: package `~a' has an invalid input: ~s~%")
073c34d7
LC
670 file line column
671 (package-full-name package) input)))
9b222abe
LC
672 ((package-cross-build-system-error? c)
673 (let* ((package (package-error-package c))
674 (loc (package-location package))
675 (system (package-build-system package)))
69daee23 676 (leave (G_ "~a: ~a: build system `~a' does not support cross builds~%")
9b222abe
LC
677 (location->string loc)
678 (package-full-name package)
679 (build-system-name system))))
3e43166f
LC
680 ((gexp-input-error? c)
681 (let ((input (package-error-invalid-input c)))
69daee23 682 (leave (G_ "~s: invalid G-expression input~%")
3e43166f 683 (gexp-error-invalid-input c))))
c0c018f1 684 ((profile-not-found-error? c)
69daee23 685 (leave (G_ "profile '~a' does not exist~%")
c0c018f1
AK
686 (profile-error-profile c)))
687 ((missing-generation-error? c)
69daee23 688 (leave (G_ "generation ~a of profile '~a' does not exist~%")
c0c018f1
AK
689 (missing-generation-error-generation c)
690 (profile-error-profile c)))
487cbb01
LC
691 ((unmatched-pattern-error? c)
692 (let ((pattern (unmatched-pattern-error-pattern c)))
693 (leave (G_ "package '~a~@[@~a~]~@[:~a~]' not found in profile~%")
694 (manifest-pattern-name pattern)
695 (manifest-pattern-version pattern)
696 (match (manifest-pattern-output pattern)
697 ("out" #f)
698 (output output)))))
a654dc4b
LC
699 ((profile-collision-error? c)
700 (let ((entry (profile-collision-error-entry c))
701 (conflict (profile-collision-error-conflict c)))
702 (define (report-parent-entries entry)
703 (let ((parent (force (manifest-entry-parent entry))))
704 (when (manifest-entry? parent)
705 (report-error (G_ " ... propagated from ~a@~a~%")
706 (manifest-entry-name parent)
707 (manifest-entry-version parent))
708 (report-parent-entries parent))))
709
0d2ecf8b
LC
710 (define (manifest-entry-output* entry)
711 (match (manifest-entry-output entry)
712 ("out" "")
713 (output (string-append ":" output))))
714
3fb6464b 715 (report-error (G_ "profile contains conflicting entries for ~a~a~%")
a654dc4b 716 (manifest-entry-name entry)
3fb6464b 717 (manifest-entry-output* entry))
0d2ecf8b 718 (report-error (G_ " first entry: ~a@~a~a ~a~%")
a654dc4b
LC
719 (manifest-entry-name entry)
720 (manifest-entry-version entry)
0d2ecf8b 721 (manifest-entry-output* entry)
a654dc4b
LC
722 (manifest-entry-item entry))
723 (report-parent-entries entry)
0d2ecf8b 724 (report-error (G_ " second entry: ~a@~a~a ~a~%")
a654dc4b
LC
725 (manifest-entry-name conflict)
726 (manifest-entry-version conflict)
0d2ecf8b 727 (manifest-entry-output* conflict)
a654dc4b
LC
728 (manifest-entry-item conflict))
729 (report-parent-entries conflict)
3b80b813 730 (display-collision-resolution-hint c)
a654dc4b 731 (exit 1)))
b7071bc5
LC
732 ((nar-error? c)
733 (let ((file (nar-error-file c))
734 (port (nar-error-port c)))
735 (if file
69daee23 736 (leave (G_ "corrupt input while restoring '~a' from ~s~%")
bec7f352 737 file (or (port-filename* port) port))
69daee23 738 (leave (G_ "corrupt input while restoring archive from ~s~%")
bec7f352 739 (or (port-filename* port) port)))))
f9e8a123 740 ((store-connection-error? c)
69daee23 741 (leave (G_ "failed to connect to `~a': ~a~%")
f9e8a123
LC
742 (store-connection-error-file c)
743 (strerror (store-connection-error-code c))))
744 ((store-protocol-error? c)
073c34d7 745 ;; FIXME: Server-provided error messages aren't i18n'd.
e6b065b2 746 (leave (G_ "~a~%")
f9e8a123 747 (store-protocol-error-message c)))
f304c9c2 748 ((derivation-missing-output-error? c)
69daee23 749 (leave (G_ "reference to invalid output '~a' of derivation '~a'~%")
f304c9c2
LC
750 (derivation-missing-output c)
751 (derivation-file-name (derivation-error-derivation c))))
d26e1967 752 ((file-search-error? c)
69daee23 753 (leave (G_ "file '~a' could not be found in these \
d26e1967
LC
754directories:~{ ~a~}~%")
755 (file-search-error-file-name c)
756 (file-search-error-search-path c)))
cbdfa50d
MW
757 ((invoke-error? c)
758 (leave (G_ "program exited\
759~@[ with non-zero exit status ~a~]\
760~@[ terminated by signal ~a~]\
761~@[ stopped by signal ~a~]: ~s~%")
762 (invoke-error-exit-status c)
763 (invoke-error-term-signal c)
764 (invoke-error-stop-signal c)
765 (cons (invoke-error-program c)
766 (invoke-error-arguments c))))
23735137 767 ((and (error-location? c) (message-condition? c))
40262771
LC
768 (report-error (error-location c) (G_ "~a~%")
769 (gettext (condition-message c) %gettext-domain))
e1ba6d49
LC
770 (when (fix-hint? c)
771 (display-hint (condition-fix-hint c)))
399993f8 772 (exit 1))
4a8d536f 773 ((and (message-condition? c) (fix-hint? c))
40262771
LC
774 (report-error (G_ "~a~%")
775 (gettext (condition-message c) %gettext-domain))
4a8d536f
LC
776 (display-hint (condition-fix-hint c))
777 (exit 1))
a07d5e55 778
a65ffbea 779 ;; On Guile 3.0.0, exceptions such as 'unbound-variable' are
a07d5e55
LC
780 ;; compound and include a '&message'. However, that message only
781 ;; contains the format string. Thus, special-case it here to
782 ;; avoid displaying a bare format string.
783 ((cond-expand
784 (guile-3
785 ((exception-predicate &exception-with-kind-and-args) c))
786 (else #f))
787 (raise c))
788
c1d52c71
LC
789 ((message-condition? c)
790 ;; Normally '&message' error conditions have an i18n'd message.
69daee23 791 (leave (G_ "~a~%")
12703d08 792 (gettext (condition-message c) %gettext-domain))))
e14c3929
LC
793 ;; Catch EPIPE and the likes.
794 (catch 'system-error
795 thunk
bde8c0e6 796 (lambda (key proc format-string format-args . rest)
69daee23 797 (leave (G_ "~a: ~a~%") proc
bde8c0e6 798 (apply format #f format-string format-args))))))
073c34d7 799
df36e629 800(define-syntax-rule (leave-on-EPIPE exp ...)
694e10af 801 "Run EXP... in a context where EPIPE errors are caught and lead to 'exit'
df36e629
LC
802with successful exit code. This is useful when writing to the standard output
803may lead to EPIPE, because the standard output is piped through 'head' or
804similar."
805 (catch 'system-error
806 (lambda ()
807 exp ...)
808 (lambda args
809 ;; We really have to exit this brutally, otherwise Guile eventually
810 ;; attempts to flush all the ports, leading to an uncaught EPIPE down
811 ;; the path.
812 (if (= EPIPE (system-error-errno args))
813 (primitive-_exit 0)
814 (apply throw args)))))
815
56b82106
LC
816(define %guix-user-module
817 ;; Module in which user expressions are evaluated.
07254feb
LC
818 ;; Compute lazily to avoid circularity with (guix gexp).
819 (delay
820 (let ((module (make-module)))
821 (beautify-user-module! module)
822 ;; Use (guix gexp) so that one can use #~ & co.
823 (module-use! module (resolve-interface '(guix gexp)))
824 module)))
56b82106 825
ac5de156
LC
826(define (read/eval str)
827 "Read and evaluate STR, raising an error if something goes wrong."
eb0880e7
LC
828 (let ((exp (catch #t
829 (lambda ()
830 (call-with-input-string str read))
831 (lambda args
69daee23 832 (leave (G_ "failed to read expression ~s: ~s~%")
eb0880e7 833 str args)))))
ac5de156
LC
834 (catch #t
835 (lambda ()
07254feb 836 (eval exp (force %guix-user-module)))
ac5de156 837 (lambda args
69daee23 838 (report-error (G_ "failed to evaluate expression '~a':~%") exp)
41766807
LC
839 (match args
840 (('syntax-error proc message properties form . rest)
69daee23 841 (report-error (G_ "syntax error: ~a~%") message))
7f3bbfaf 842 (((or 'srfi-34 '%exception) obj)
f816dba6 843 (if (message-condition? obj)
69daee23 844 (report-error (G_ "~a~%")
f816dba6
LC
845 (gettext (condition-message obj)
846 %gettext-domain))
69daee23 847 (report-error (G_ "exception thrown: ~s~%") obj)))
41766807
LC
848 ((error args ...)
849 (apply display-error #f (current-error-port) args))
850 (what? #f))
851 (exit 1)))))
ac5de156
LC
852
853(define (read/eval-package-expression str)
854 "Read and evaluate STR and return the package it refers to, or exit an
855error."
856 (match (read/eval str)
857 ((? package? p) p)
e465d9e1 858 (x
69daee23 859 (leave (G_ "expression ~s does not evaluate to a package~%")
ac5de156 860 str))))
eb0880e7 861
fa394eb9 862(define (show-derivation-outputs derivation)
08c95ba2
LC
863 "Show the output file names of DERIVATION, which can be a derivation or a
864derivation input."
865 (define (show-outputs derivation outputs)
866 (format #t "~{~a~%~}"
867 (map (cut derivation->output-path derivation <>)
868 outputs)))
869
870 (match derivation
871 ((? derivation?)
872 (show-outputs derivation (derivation-output-names derivation)))
873 ((? derivation-input? input)
874 (show-outputs (derivation-input-derivation input)
875 (derivation-input-sub-derivations input)))))
fa394eb9 876
8120b23e
LC
877(define* (check-available-space need
878 #:optional (directory (%store-prefix)))
879 "Make sure at least NEED bytes are available in DIRECTORY. Otherwise emit a
dcfc6f21
LC
880warning."
881 (let ((free (catch 'system-error
882 (lambda ()
8120b23e 883 (free-disk-space directory))
dcfc6f21
LC
884 (const #f))))
885 (when (and free (>= need free))
886 (warning (G_ "at least ~,1h MB needed but only ~,1h MB available in ~a~%")
8120b23e 887 (/ need 1e6) (/ free 1e6) directory))))
dcfc6f21 888
d4aa147e
LC
889(define (graft-derivation? drv)
890 "Return true if DRV is definitely a graft derivation, false otherwise."
891 (match (assq-ref (derivation-properties drv) 'type)
892 ('graft #t)
893 (_ #f)))
894
80eebee9
RW
895(define (profile-hook-derivation? drv)
896 "Return true if DRV is definitely a profile hook derivation, false otherwise."
897 (match (assq-ref (derivation-properties drv) 'type)
898 ('profile-hook #t)
899 (_ #f)))
900
8b4615ab
LC
901(define (colorize-store-file-name file)
902 "Colorize FILE, a store file name, such that the hash part is less prominent
903that the rest."
904 (let ((len (string-length file))
905 (prefix (+ (string-length (%store-prefix)) 32 2)))
906 (if (< len prefix)
907 file
908 (string-append (colorize-string (string-take file prefix)
909 (color DARK))
910 (string-drop file prefix)))))
911
dd36b51b 912(define* (show-what-to-build store drv
58c08df0
LC
913 #:key dry-run? (use-substitutes? #t)
914 (mode (build-mode normal)))
9bb2b96a 915 "Show what will or would (depending on DRY-RUN?) be built in realizing the
d38d4ffa
LC
916derivations listed in DRV using MODE, a 'build-mode' value. The elements of
917DRV can be either derivations or derivation inputs.
918
883a1765
LC
919Return two values: a Boolean indicating whether there's something to build,
920and a Boolean indicating whether there's something to download. When
921USE-SUBSTITUTES?, check and report what is prerequisites are available for
922download."
d38d4ffa
LC
923 (define inputs
924 (map (match-lambda
925 ((? derivation? drv) (derivation-input drv))
926 ((? derivation-input? input) input))
927 drv))
928
2dc98729 929 (define substitutable-info
694e10af 930 ;; Call 'substitution-oracle' upfront so we don't end up launching the
e9651e39
LC
931 ;; substituter many times. This makes a big difference, especially when
932 ;; DRV is a long list as is the case with 'guix environment'.
933 (if use-substitutes?
d74392a8 934 (substitution-oracle store inputs #:mode mode)
e9651e39
LC
935 (const #f)))
936
8b4615ab
LC
937 (define colorized-store-item
938 (if (color-output? (current-error-port))
939 colorize-store-file-name
940 identity))
941
bec34741 942 (let*-values (((build/full download)
d38d4ffa 943 (derivation-build-plan store inputs
9844d009
LC
944 #:mode mode
945 #:substitutable-info
946 substitutable-info))
80eebee9 947 ((graft hook build)
9844d009
LC
948 (match (fold (lambda (drv acc)
949 (let ((file (derivation-file-name drv)))
80eebee9
RW
950 (match acc
951 ((#:graft graft #:hook hook #:build build)
952 (cond
953 ((graft-derivation? drv)
954 `(#:graft ,(cons file graft)
955 #:hook ,hook
956 #:build ,build))
957 ((profile-hook-derivation? drv)
958 `(#:graft ,graft
959 #:hook ,(cons file hook)
960 #:build ,build))
961 (else
962 `(#:graft ,graft
963 #:hook ,hook
964 #:build ,(cons file build))))))))
965 '(#:graft () #:hook () #:build ())
bec34741 966 build/full)
80eebee9
RW
967 ((#:graft graft #:hook hook #:build build)
968 (values graft hook build)))))
dcfc6f21
LC
969 (define installed-size
970 (reduce + 0 (map substitutable-nar-size download)))
971
d9bad2f0
LC
972 (define download-size
973 (/ (reduce + 0 (map substitutable-download-size download))
974 1e6))
975
976 (define display-download-size?
977 ;; Sometimes narinfos lack information about the download size. Only
978 ;; display when we have information for all of DOWNLOAD.
979 (not (any (compose zero? substitutable-download-size) download)))
980
9bb2b96a 981 (if dry-run?
dd36b51b
LC
982 (begin
983 (format (current-error-port)
83e61a73
LC
984 (N_ "~:[The following derivation would be built:~%~{ ~a~%~}~;~]"
985 "~:[The following derivations would be built:~%~{ ~a~%~}~;~]"
dd36b51b 986 (length build))
8b4615ab 987 (null? build) (map colorized-store-item build))
d9bad2f0
LC
988 (if display-download-size?
989 (format (current-error-port)
990 ;; TRANSLATORS: "MB" is for "megabyte"; it should be
991 ;; translated to the corresponding abbreviation.
992 (G_ "~:[~,1h MB would be downloaded:~%~{ ~a~%~}~;~]")
993 (null? download)
994 download-size
8b4615ab
LC
995 (map (compose colorized-store-item substitutable-path)
996 download))
d9bad2f0
LC
997 (format (current-error-port)
998 (N_ "~:[The following file would be downloaded:~%~{ ~a~%~}~;~]"
999 "~:[The following files would be downloaded:~%~{ ~a~%~}~;~]"
1000 (length download))
1001 (null? download)
8b4615ab
LC
1002 (map (compose colorized-store-item substitutable-path)
1003 download)))
d4aa147e
LC
1004 (format (current-error-port)
1005 (N_ "~:[The following graft would be made:~%~{ ~a~%~}~;~]"
1006 "~:[The following grafts would be made:~%~{ ~a~%~}~;~]"
1007 (length graft))
8b4615ab 1008 (null? graft) (map colorized-store-item graft))
80eebee9
RW
1009 (format (current-error-port)
1010 (N_ "~:[The following profile hook would be built:~%~{ ~a~%~}~;~]"
1011 "~:[The following profile hooks would be built:~%~{ ~a~%~}~;~]"
1012 (length hook))
8b4615ab 1013 (null? hook) (map colorized-store-item hook)))
dd36b51b
LC
1014 (begin
1015 (format (current-error-port)
83e61a73
LC
1016 (N_ "~:[The following derivation will be built:~%~{ ~a~%~}~;~]"
1017 "~:[The following derivations will be built:~%~{ ~a~%~}~;~]"
dd36b51b 1018 (length build))
8b4615ab 1019 (null? build) (map colorized-store-item build))
d9bad2f0
LC
1020 (if display-download-size?
1021 (format (current-error-port)
1022 ;; TRANSLATORS: "MB" is for "megabyte"; it should be
1023 ;; translated to the corresponding abbreviation.
1024 (G_ "~:[~,1h MB will be downloaded:~%~{ ~a~%~}~;~]")
1025 (null? download)
1026 download-size
8b4615ab
LC
1027 (map (compose colorized-store-item substitutable-path)
1028 download))
d9bad2f0
LC
1029 (format (current-error-port)
1030 (N_ "~:[The following file will be downloaded:~%~{ ~a~%~}~;~]"
1031 "~:[The following files will be downloaded:~%~{ ~a~%~}~;~]"
1032 (length download))
1033 (null? download)
8b4615ab
LC
1034 (map (compose colorized-store-item substitutable-path)
1035 download)))
d4aa147e
LC
1036 (format (current-error-port)
1037 (N_ "~:[The following graft will be made:~%~{ ~a~%~}~;~]"
1038 "~:[The following grafts will be made:~%~{ ~a~%~}~;~]"
1039 (length graft))
8b4615ab 1040 (null? graft) (map colorized-store-item graft))
80eebee9
RW
1041 (format (current-error-port)
1042 (N_ "~:[The following profile hook will be built:~%~{ ~a~%~}~;~]"
1043 "~:[The following profile hooks will be built:~%~{ ~a~%~}~;~]"
1044 (length hook))
8b4615ab 1045 (null? hook) (map colorized-store-item hook))))
dcfc6f21
LC
1046
1047 (check-available-space installed-size)
1048
883a1765 1049 (values (pair? build/full) (pair? download))))
9bb2b96a 1050
4d043ab6
DT
1051(define show-what-to-build*
1052 (store-lift show-what-to-build))
1053
07ce23e0
LC
1054(define* (build-notifier #:key (dry-run? #f) (use-substitutes? #t))
1055 "Return a procedure suitable for 'with-build-handler' that, when
1056'build-things' is called, invokes 'show-what-to-build' to display the build
1057plan. When DRY-RUN? is true, the 'with-build-handler' form returns without
1058any build happening."
1059 (define not-comma
1060 (char-set-complement (char-set #\,)))
1061
1062 (define (read-derivation-from-file* item)
1063 (catch 'system-error
1064 (lambda ()
1065 (read-derivation-from-file item))
1066 (const #f)))
1067
1068 (lambda (continue store things mode)
1069 (define inputs
1070 ;; List of derivation inputs to build. Filter out non-existent '.drv'
1071 ;; files because the daemon transparently tries to substitute them.
1072 (filter-map (match-lambda
1073 (((? derivation-path? drv) . output)
1074 (let ((drv (read-derivation-from-file* drv))
1075 (outputs (string-tokenize output not-comma)))
1076 (and drv (derivation-input drv outputs))))
1077 ((? derivation-path? drv)
1078 (and=> (read-derivation-from-file* drv)
1079 derivation-input))
1080 (_
1081 #f))
1082 things))
1083
9b771305
LC
1084 (let-values (((build? download?)
1085 (show-what-to-build store inputs
1086 #:dry-run? dry-run?
1087 #:use-substitutes? use-substitutes?
1088 #:mode mode)))
1089
1090 (unless (and (or build? download?)
1091 dry-run?)
1092 (continue #t)))))
07ce23e0 1093
5d7a8584
AK
1094(define (right-arrow port)
1095 "Return either a string containing the 'RIGHT ARROW' character, or an ASCII
1096replacement if PORT is not Unicode-capable."
1062063a
LC
1097 (let ((encoding (port-encoding port))
1098 (arrow "→"))
1099 (catch 'encoding-error
1100 (lambda ()
1101 (call-with-output-string
1102 (lambda (port)
1103 (set-port-encoding! port encoding)
1104 (set-port-conversion-strategy! port 'error)
1105 (display arrow port))))
1106 (lambda (key . args)
1107 "->"))))
5d7a8584 1108
3e5ab0a7
LC
1109(define* (tabulate rows #:key (initial-indent 0) (max-width 25)
1110 (inter-column " "))
1111 "Return a list of strings where each string is a tabulated representation of
1112an element of ROWS. All the ROWS must be lists of the same number of cells.
1113
1114Add INITIAL-INDENT white space at the beginning of each row. Ensure that
1115columns are at most MAX-WIDTH characters wide. Use INTER-COLUMN as a
1116separator between subsequent columns."
1117 (define column-widths
1118 ;; List of column widths.
1119 (let loop ((rows rows)
1120 (widths '()))
1121 (match rows
1122 (((? null?) ...)
1123 (reverse widths))
1124 (((column rest ...) ...)
1125 (loop rest
1126 (cons (min (apply max (map string-length column))
1127 max-width)
1128 widths))))))
1129
1130 (define indent
1131 (make-string initial-indent #\space))
1132
1133 (define (string-pad-right* str len)
1134 (if (> (string-length str) len)
1135 str
1136 (string-pad-right str len)))
1137
1138 (map (lambda (row)
1139 (string-trim-right
1140 (string-append indent
1141 (string-join
1142 (map string-pad-right* row column-widths)
1143 inter-column))))
1144 rows))
1145
5d7a8584
AK
1146(define* (show-manifest-transaction store manifest transaction
1147 #:key dry-run?)
1148 "Display what will/would be installed/removed from MANIFEST by TRANSACTION."
8465f1f6
LC
1149 (define (package-strings names versions outputs)
1150 (tabulate (zip (map (lambda (name output)
1151 (if (string=? output "out")
1152 name
1153 (string-append name ":" output)))
1154 names outputs)
1155 versions)
1156 #:initial-indent 3))
5d7a8584
AK
1157
1158 (define → ;an arrow that can be represented on stderr
1159 (right-arrow (current-error-port)))
1160
3e5ab0a7
LC
1161 (define (upgrade-string names old-version new-version outputs)
1162 (tabulate (zip (map (lambda (name output)
1163 (if (string=? output "out")
1164 name
1165 (string-append name ":" output)))
1166 names outputs)
1167 (map (lambda (old new)
1168 (if (string=? old new)
5c83dd1d 1169 (G_ "(dependencies or package changed)")
3e5ab0a7
LC
1170 (string-append old " " → " " new)))
1171 old-version new-version))
1172 #:initial-indent 3))
5d7a8584 1173
46b23e1a 1174 (let-values (((remove install upgrade downgrade)
5d7a8584
AK
1175 (manifest-transaction-effects manifest transaction)))
1176 (match remove
1177 ((($ <manifest-entry> name version output item) ..1)
1178 (let ((len (length name))
8465f1f6 1179 (remove (package-strings name version output)))
5d7a8584
AK
1180 (if dry-run?
1181 (format (current-error-port)
1182 (N_ "The following package would be removed:~%~{~a~%~}~%"
1183 "The following packages would be removed:~%~{~a~%~}~%"
1184 len)
1185 remove)
1186 (format (current-error-port)
1187 (N_ "The following package will be removed:~%~{~a~%~}~%"
1188 "The following packages will be removed:~%~{~a~%~}~%"
1189 len)
1190 remove))))
30906825 1191 (x #f))
46b23e1a
LC
1192 (match downgrade
1193 (((($ <manifest-entry> name old-version)
1194 . ($ <manifest-entry> _ new-version output item)) ..1)
1195 (let ((len (length name))
3e5ab0a7
LC
1196 (downgrade (upgrade-string name old-version new-version
1197 output)))
46b23e1a
LC
1198 (if dry-run?
1199 (format (current-error-port)
1200 (N_ "The following package would be downgraded:~%~{~a~%~}~%"
1201 "The following packages would be downgraded:~%~{~a~%~}~%"
1202 len)
1203 downgrade)
1204 (format (current-error-port)
1205 (N_ "The following package will be downgraded:~%~{~a~%~}~%"
1206 "The following packages will be downgraded:~%~{~a~%~}~%"
1207 len)
1208 downgrade))))
30906825 1209 (x #f))
5d7a8584
AK
1210 (match upgrade
1211 (((($ <manifest-entry> name old-version)
1212 . ($ <manifest-entry> _ new-version output item)) ..1)
1213 (let ((len (length name))
3e5ab0a7
LC
1214 (upgrade (upgrade-string name
1215 old-version new-version
1216 output)))
5d7a8584
AK
1217 (if dry-run?
1218 (format (current-error-port)
1219 (N_ "The following package would be upgraded:~%~{~a~%~}~%"
1220 "The following packages would be upgraded:~%~{~a~%~}~%"
1221 len)
1222 upgrade)
1223 (format (current-error-port)
1224 (N_ "The following package will be upgraded:~%~{~a~%~}~%"
1225 "The following packages will be upgraded:~%~{~a~%~}~%"
1226 len)
1227 upgrade))))
30906825 1228 (x #f))
5d7a8584
AK
1229 (match install
1230 ((($ <manifest-entry> name version output item _) ..1)
1231 (let ((len (length name))
8465f1f6 1232 (install (package-strings name version output)))
5d7a8584
AK
1233 (if dry-run?
1234 (format (current-error-port)
1235 (N_ "The following package would be installed:~%~{~a~%~}~%"
1236 "The following packages would be installed:~%~{~a~%~}~%"
1237 len)
1238 install)
1239 (format (current-error-port)
1240 (N_ "The following package will be installed:~%~{~a~%~}~%"
1241 "The following packages will be installed:~%~{~a~%~}~%"
1242 len)
1243 install))))
30906825 1244 (x #f))))
5d7a8584 1245
073c34d7
LC
1246(define-syntax with-error-handling
1247 (syntax-rules ()
1248 "Run BODY within a user-friendly error condition handler."
1249 ((_ body ...)
1250 (call-with-error-handling
1251 (lambda ()
1252 body ...)))))
1253
7b322d3c
LC
1254(define* (indented-string str indent
1255 #:key (initial-indent? #t))
694e10af 1256 "Return STR with each newline preceded by INDENT spaces. When
7b322d3c
LC
1257INITIAL-INDENT? is true, the first line is also indented."
1258 (define indent-string
1259 (make-list indent #\space))
1260
1261 (list->string
1262 (string-fold-right (lambda (chr result)
1263 (if (eqv? chr #\newline)
1264 (cons chr (append indent-string result))
1265 (cons chr result)))
1266 '()
1267 (if initial-indent?
1268 (string-append (list->string indent-string) str)
1269 str))))
1270
299112d3
LC
1271(define* (fill-paragraph str width #:optional (column 0))
1272 "Fill STR such that each line contains at most WIDTH characters, assuming
1273that the first character is at COLUMN.
1274
1275When STR contains a single line break surrounded by other characters, it is
1276converted to a space; sequences of more than one line break are preserved."
1277 (define (maybe-break chr result)
1278 (match result
1279 ((column newlines chars)
1280 (case chr
1281 ((#\newline)
1282 `(,column ,(+ 1 newlines) ,chars))
1283 (else
3a09e1d2
CS
1284 (let* ((spaces (if (and (pair? chars) (eqv? (car chars) #\.)) 2 1))
1285 (chars (case newlines
1286 ((0) chars)
1287 ((1)
1288 (append (make-list spaces #\space) chars))
1289 (else
1290 (append (make-list newlines #\newline) chars))))
1291 (column (case newlines
1292 ((0) column)
1293 ((1) (+ spaces column))
1294 (else 0))))
299112d3
LC
1295 (let ((chars (cons chr chars))
1296 (column (+ 1 column)))
1297 (if (> column width)
1298 (let*-values (((before after)
1299 (break (cut eqv? #\space <>) chars))
1300 ((len)
1301 (length before)))
1302 (if (<= len width)
1303 `(,len
1304 0
1305 ,(if (null? after)
1306 before
3a09e1d2
CS
1307 (append before
1308 (cons #\newline
1309 (drop-while (cut eqv? #\space <>)
1310 after)))))
299112d3
LC
1311 `(,column 0 ,chars))) ; unbreakable
1312 `(,column 0 ,chars)))))))))
1313
1314 (match (string-fold maybe-break
1315 `(,column 0 ())
1316 str)
30906825 1317 ((column newlines chars)
299112d3
LC
1318 (list->string (reverse chars)))))
1319
2876b989
LC
1320\f
1321;;;
1322;;; Packages.
1323;;;
1324
1cd4027c 1325(define %text-width
3c1ea8dc
LC
1326 ;; '*line-width*' was introduced in Guile 2.2.7/3.0.1. On older versions of
1327 ;; Guile, monkey-patch 'wrap*' below.
1328 (if (defined? '*line-width*)
1329 (let ((parameter (fluid->parameter *line-width*)))
1330 (parameter (terminal-columns))
1331 parameter)
1332 (make-parameter (terminal-columns))))
1333
1334(unless (defined? '*line-width*) ;Guile < 2.2.7
1335 (set! (@@ (texinfo plain-text) wrap*)
1336 ;; XXX: Monkey patch this private procedure to let 'package->recutils'
1337 ;; parameterize the fill of description field correctly.
1338 (lambda strings
1339 (let ((indent (fluid-ref (@@ (texinfo plain-text) *indent*))))
1340 (fill-string (string-concatenate strings)
1341 #:line-width (%text-width) #:initial-indent indent
1342 #:subsequent-indent indent)))))
1cd4027c
ML
1343
1344(define (texi->plain-text str)
1345 "Return a plain-text representation of texinfo fragment STR."
08d7e359
LC
1346 ;; 'texi-fragment->stexi' uses a string port so make sure it's a
1347 ;; Unicode-capable one (see <http://bugs.gnu.org/11197>.)
1348 (with-fluids ((%default-port-encoding "UTF-8"))
1349 (stexi->plain-text (texi-fragment->stexi str))))
1cd4027c 1350
689db38e
AK
1351(define (package-field-string package field-accessor)
1352 "Return a plain-text representation of PACKAGE field."
1353 (and=> (field-accessor package)
1354 (compose texi->plain-text P_)))
1355
1cd4027c
ML
1356(define (package-description-string package)
1357 "Return a plain-text representation of PACKAGE description field."
689db38e
AK
1358 (package-field-string package package-description))
1359
1360(define (package-synopsis-string package)
1361 "Return a plain-text representation of PACKAGE synopsis field."
1362 (package-field-string package package-synopsis))
1cd4027c 1363
299112d3
LC
1364(define (string->recutils str)
1365 "Return a version of STR where newlines have been replaced by newlines
1366followed by \"+ \", which makes for a valid multi-line field value in the
1367`recutils' syntax."
1368 (list->string
1369 (string-fold-right (lambda (chr result)
1370 (if (eqv? chr #\newline)
1371 (cons* chr #\+ #\space result)
1372 (cons chr result)))
1373 '()
1374 str)))
1375
7f0f38b5
LC
1376(define (hyperlink uri text)
1377 "Return a string that denotes a hyperlink using an OSC escape sequence as
1378documented at
1379<https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda>."
1380 (string-append "\x1b]8;;" uri "\x1b\\"
1381 text "\x1b]8;;\x1b\\"))
1382
055f0525 1383(define* (supports-hyperlinks? #:optional (port (current-output-port)))
7f0f38b5
LC
1384 "Return true if PORT is a terminal that supports hyperlink escapes."
1385 ;; Note that terminals are supposed to ignore OSC escapes they don't
1386 ;; understand (this is the case of xterm as of version 349, for instance.)
1387 ;; However, Emacs comint as of 26.3 does not ignore it and instead lets it
1388 ;; through, hence the 'INSIDE_EMACS' special case below.
1389 (and (isatty?* port)
1390 (not (getenv "INSIDE_EMACS"))))
1391
fa983b82
LC
1392(define* (file-hyperlink file #:optional (text file))
1393 "Return TEXT with escapes for a hyperlink to FILE."
1394 (hyperlink (string-append "file://" (gethostname)
1395 (encode-and-join-uri-path
1396 (string-split file #\/)))
1397 text))
1398
7f0f38b5
LC
1399(define (location->hyperlink location)
1400 "Return a string corresponding to LOCATION, with escapes for a hyperlink."
1401 (let ((str (location->string location))
1402 (file (if (string-prefix? "/" (location-file location))
1403 (location-file location)
1404 (search-path %load-path (location-file location)))))
1405 (if file
fa983b82 1406 (file-hyperlink file str)
7f0f38b5
LC
1407 str)))
1408
4ee79f22 1409(define* (package->recutils p port #:optional (width (%text-width))
7f0f38b5
LC
1410 #:key
1411 (hyperlinks? (supports-hyperlinks? port))
1412 (extra-fields '()))
299112d3 1413 "Write to PORT a `recutils' record of package P, arranging to fit within
7f0f38b5
LC
1414WIDTH columns. EXTRA-FIELDS is a list of symbol/value pairs to emit. When
1415HYPERLINKS? is true, emit hyperlink escape sequences when appropriate."
069d43a7
LC
1416 (define width*
1417 ;; The available number of columns once we've taken into account space for
1418 ;; the initial "+ " prefix.
1419 (if (> width 2) (- width 2) width))
1420
20ffce82 1421 (define (dependencies->recutils packages)
dbde386e
SB
1422 (let ((list (string-join (delete-duplicates
1423 (map package-full-name
1424 (sort packages package<?))) " ")))
20ffce82 1425 (string->recutils
069d43a7 1426 (fill-paragraph list width*
20ffce82
LC
1427 (string-length "dependencies: ")))))
1428
9c0fc279
CR
1429 (define (package<? p1 p2)
1430 (string<? (package-full-name p1) (package-full-name p2)))
1431
299112d3
LC
1432 ;; Note: Don't i18n field names so that people can post-process it.
1433 (format port "name: ~a~%" (package-name p))
1434 (format port "version: ~a~%" (package-version p))
6bf99bac 1435 (format port "outputs: ~a~%" (string-join (package-outputs p)))
5763ad92
LC
1436 (format port "systems: ~a~%"
1437 (string-join (package-transitive-supported-systems p)))
9c0fc279
CR
1438 (format port "dependencies: ~a~%"
1439 (match (package-direct-inputs p)
5e6feee6
EB
1440 (((labels inputs . _) ...)
1441 (dependencies->recutils (filter package? inputs)))))
299112d3 1442 (format port "location: ~a~%"
7f0f38b5
LC
1443 (or (and=> (package-location p)
1444 (if hyperlinks? location->hyperlink location->string))
69daee23 1445 (G_ "unknown")))
8fa3e6b3
LC
1446
1447 ;; Note: Starting from version 1.6 or recutils, hyphens are not allowed in
1448 ;; field identifiers.
1449 (format port "homepage: ~a~%" (package-home-page p))
1450
299112d3
LC
1451 (format port "license: ~a~%"
1452 (match (package-license p)
1453 (((? license? licenses) ...)
1454 (string-join (map license-name licenses)
1455 ", "))
1456 ((? license? license)
edd25a8c
LC
1457 (let ((text (license-name license))
1458 (uri (license-uri license)))
1459 (if (and hyperlinks? uri (string-prefix? "http" uri))
1460 (hyperlink uri text)
1461 text)))
299112d3 1462 (x
69daee23 1463 (G_ "unknown"))))
299112d3
LC
1464 (format port "synopsis: ~a~%"
1465 (string-map (match-lambda
4ee79f22
LC
1466 (#\newline #\space)
1467 (chr chr))
a1da0904 1468 (or (package-synopsis-string p) "")))
4ee79f22 1469 (format port "~a~%"
1cd4027c
ML
1470 (string->recutils
1471 (string-trim-right
069d43a7 1472 (parameterize ((%text-width width*))
bd03e99f
AI
1473 (string-append "description: "
1474 (or (package-description-string p) "")))
4ee79f22
LC
1475 #\newline)))
1476 (for-each (match-lambda
1477 ((field . value)
1478 (let ((field (symbol->string field)))
1479 (format port "~a: ~a~%"
1480 field
1481 (fill-paragraph (object->string value) width*
1482 (string-length field))))))
1483 extra-fields)
1484 (newline port))
299112d3 1485
4311cf96
LC
1486\f
1487;;;
1488;;; Searching.
1489;;;
1490
c7ae219e
LC
1491(define (relevance obj regexps metrics)
1492 "Compute a \"relevance score\" for OBJ as a function of its number of
1493matches of REGEXPS and accordingly to METRICS. METRICS is list of
387e6b9e
CM
1494field/weight pairs, where FIELD is a procedure that returns a string or list
1495of strings describing OBJ, and WEIGHT is a positive integer denoting the
1496weight of this field in the final score.
c7ae219e
LC
1497
1498A score of zero means that OBJ does not match any of REGEXPS. The higher the
1499score, the more relevant OBJ is to REGEXPS."
d2cdef65 1500 (define (score regexp str)
1501 (fold-matches regexp str 0
1502 (lambda (m score)
1503 (+ score
1504 (if (string=? (match:substring m) str)
1505 5 ;exact match
1506 1)))))
1507
1508 (define (regexp->score regexp)
1509 (let ((score-regexp (lambda (str) (score regexp str))))
1510 (fold (lambda (metric relevance)
1511 (match metric
1512 ((field . weight)
1513 (match (field obj)
1514 (#f relevance)
1515 ((? string? str)
1516 (+ relevance (* (score-regexp str) weight)))
1517 ((lst ...)
1518 (+ relevance (* weight (apply + (map score-regexp lst)))))))))
1519 0 metrics)))
1520
e70a8847
AI
1521 (let loop ((regexps regexps)
1522 (total-score 0))
1523 (match regexps
1524 ((head . tail)
1525 (let ((score (regexp->score head)))
1526 ;; Return zero if one of PATTERNS doesn't match.
1527 (if (zero? score)
1528 0
1529 (loop tail (+ total-score score)))))
1530 (() total-score))))
c7ae219e
LC
1531
1532(define %package-metrics
1533 ;; Metrics used to compute the "relevance score" of a package against a set
1534 ;; of regexps.
304a53f6 1535 `((,package-name . 4)
94aeec0a 1536
387e6b9e
CM
1537 ;; Match against uncommon outputs.
1538 (,(lambda (package)
1539 (filter (lambda (output)
1540 (not (member output
694e10af 1541 ;; Some common outputs shared by many packages.
387e6b9e
CM
1542 '("out" "doc" "debug" "lib" "include" "bin"))))
1543 (package-outputs package)))
1544 . 1)
1545
94aeec0a
LC
1546 ;; Match regexps on the raw Texinfo since formatting it is quite expensive
1547 ;; and doesn't have much of an effect on search results.
1548 (,(lambda (package)
1549 (and=> (package-synopsis package) P_)) . 3)
1550 (,(lambda (package)
1551 (and=> (package-description package) P_)) . 2)
1552
304a53f6
LC
1553 (,(lambda (type)
1554 (match (and=> (package-location type) location-file)
1555 ((? string? file) (basename file ".scm"))
1556 (#f "")))
1557 . 1)))
c7ae219e
LC
1558
1559(define (package-relevance package regexps)
1560 "Return a score denoting the relevance of PACKAGE for REGEXPS. A score of
1561zero means that PACKAGE does not match any of REGEXPS."
1562 (relevance package regexps %package-metrics))
1563
c39693d7
LC
1564(define (call-with-paginated-output-port proc)
1565 (if (isatty?* (current-output-port))
1566 ;; Set 'LESS' so that 'less' exits if everything fits on the screen (F),
1567 ;; lets ANSI escapes through (r), does not send the termcap
e66f243e
LC
1568 ;; initialization string (X). Set it unconditionally because some
1569 ;; distros set it to something that doesn't work here.
1570 (let ((pager (with-environment-variables `(("LESS" "FrX"))
c39693d7
LC
1571 (open-pipe* OPEN_WRITE
1572 (or (getenv "GUIX_PAGER") (getenv "PAGER")
1573 "less")))))
1574 (dynamic-wind
1575 (const #t)
1576 (lambda () (proc pager))
1577 (lambda () (close-pipe pager))))
1578 (proc (current-output-port))))
1579
1580(define-syntax-rule (with-paginated-output-port port exp ...)
1581 "Evaluate EXP... with PORT bound to a port that talks to the pager if
1582standard output is a tty, or with PORT set to the current output port."
1583 (call-with-paginated-output-port (lambda (port) exp ...)))
1584
4311cf96
LC
1585(define* (display-search-results matches port
1586 #:key
1587 (command "guix search")
1588 (print package->recutils))
1589 "Display MATCHES, a list of object/score pairs, by calling PRINT on each of
1590them. If PORT is a terminal, print at most a full screen of results."
1591 (define first-line
1592 (port-line port))
1593
1594 (define max-rows
1595 (and first-line (isatty? port)
1596 (terminal-rows port)))
1597
1598 (define (line-count str)
1599 (string-count str #\newline))
1600
c39693d7
LC
1601 (with-paginated-output-port paginated
1602 (let loop ((matches matches))
1603 (match matches
1604 (((package . score) rest ...)
1605 (let* ((links? (supports-hyperlinks? port)))
1606 (print package paginated
1607 #:hyperlinks? links?
1608 #:extra-fields `((relevance . ,score)))
1609 (loop rest)))
1610 (()
1611 #t)))))
4311cf96
LC
1612
1613\f
2cd09108
NK
1614(define (string->generations str)
1615 "Return the list of generations matching a pattern in STR. This function
1616accepts the following patterns: \"1\", \"1,2,3\", \"1..9\", \"1..\", \"..9\"."
1617 (define (maybe-integer)
1618 (let ((x (string->number str)))
1619 (and (integer? x)
1620 x)))
1621
1622 (define (maybe-comma-separated-integers)
1623 (let ((lst (delete-duplicates
1624 (map string->number
1625 (string-split str #\,)))))
1626 (and (every integer? lst)
1627 lst)))
1628
1629 (cond ((maybe-integer)
1630 =>
1631 list)
1632 ((maybe-comma-separated-integers)
1633 =>
1634 identity)
1635 ((string-match "^([0-9]+)\\.\\.([0-9]+)$" str)
1636 =>
1637 (lambda (match)
1638 (let ((s (string->number (match:substring match 1)))
1639 (e (string->number (match:substring match 2))))
1640 (and (every integer? (list s e))
1641 (<= s e)
1642 (iota (1+ (- e s)) s)))))
1643 ((string-match "^([0-9]+)\\.\\.$" str)
1644 =>
1645 (lambda (match)
1646 (let ((s (string->number (match:substring match 1))))
1647 (and (integer? s)
1648 `(>= ,s)))))
1649 ((string-match "^\\.\\.([0-9]+)$" str)
1650 =>
1651 (lambda (match)
1652 (let ((e (string->number (match:substring match 1))))
1653 (and (integer? e)
1654 `(<= ,e)))))
1655 (else #f)))
1656
1657(define (string->duration str)
1658 "Return the duration matching a pattern in STR. This function accepts the
1659following patterns: \"1d\", \"1w\", \"1m\"."
1660 (define (hours->duration hours match)
1661 (make-time time-duration 0
1662 (* 3600 hours (string->number (match:substring match 1)))))
1663
638c5b79
LC
1664 (cond ((string-match "^([0-9]+)s$" str)
1665 =>
1666 (lambda (match)
1667 (make-time time-duration 0
1668 (string->number (match:substring match 1)))))
1669 ((string-match "^([0-9]+)h$" str)
30d2397f 1670 =>
638c5b79
LC
1671 (lambda (match)
1672 (hours->duration 1 match)))
1673 ((string-match "^([0-9]+)d$" str)
2cd09108
NK
1674 =>
1675 (lambda (match)
1676 (hours->duration 24 match)))
1677 ((string-match "^([0-9]+)w$" str)
1678 =>
1679 (lambda (match)
1680 (hours->duration (* 24 7) match)))
1681 ((string-match "^([0-9]+)m$" str)
1682 =>
1683 (lambda (match)
1684 (hours->duration (* 24 30) match)))
1685 (else #f)))
1686
e49de93a
LC
1687(define* (matching-generations str profile
1688 #:key (duration-relation <=))
1689 "Return the list of available generations matching a pattern in STR. See
1690'string->generations' and 'string->duration' for the list of valid patterns.
1691When STR is a duration pattern, return all the generations whose ctime has
1692DURATION-RELATION with the current time."
1693 (define (valid-generations lst)
1694 (define (valid-generation? n)
1695 (any (cut = n <>) (generation-numbers profile)))
1696
1697 (fold-right (lambda (x acc)
1698 (if (valid-generation? x)
1699 (cons x acc)
1700 acc))
1701 '()
1702 lst))
1703
1704 (define (filter-generations generations)
1705 (match generations
1706 (() '())
1707 (('>= n)
1708 (drop-while (cut > n <>)
1709 (generation-numbers profile)))
1710 (('<= n)
1711 (valid-generations (iota n 1)))
1712 ((lst ..1)
1713 (valid-generations lst))
30906825 1714 (x #f)))
e49de93a
LC
1715
1716 (define (filter-by-duration duration)
1717 (define (time-at-midnight time)
1718 ;; Return TIME at midnight by setting nanoseconds, seconds, minutes, and
1719 ;; hours to zeros.
1720 (let ((d (time-utc->date time)))
1721 (date->time-utc
1722 (make-date 0 0 0 0
1723 (date-day d) (date-month d)
1724 (date-year d) (date-zone-offset d)))))
1725
1726 (define generation-ctime-alist
1727 (map (lambda (number)
1728 (cons number
1729 (time-second
1730 (time-at-midnight
1731 (generation-time profile number)))))
1732 (generation-numbers profile)))
1733
1734 (match duration
1735 (#f #f)
1736 (res
1737 (let ((s (time-second
1738 (subtract-duration (time-at-midnight (current-time))
1739 duration))))
1740 (delete #f (map (lambda (x)
1741 (and (duration-relation s (cdr x))
1742 (first x)))
1743 generation-ctime-alist))))))
1744
1745 (cond ((string->generations str)
1746 =>
1747 filter-generations)
1748 ((string->duration str)
1749 =>
1750 filter-by-duration)
5c3d4430
LC
1751 (else
1752 (raise
1753 (condition (&message
1754 (message (format #f (G_ "invalid syntax: ~a~%")
1755 str))))))))
e49de93a 1756
ad18c7e6
LC
1757(define (display-generation profile number)
1758 "Display a one-line summary of generation NUMBER of PROFILE."
1759 (unless (zero? number)
055f0525
LC
1760 (let* ((file (generation-file-name profile number))
1761 (link (if (supports-hyperlinks?)
1762 (cut file-hyperlink file <>)
c2f9ea2b 1763 identity))
055f0525
LC
1764 (header (format #f (link (highlight (G_ "Generation ~a\t~a")))
1765 number
1766 (date->string
1767 (time-utc->date
1768 (generation-time profile number))
1769 ;; TRANSLATORS: This is a format-string for date->string.
1770 ;; Please choose a format that corresponds to the
1771 ;; usual way of presenting dates in your locale.
1772 ;; See https://www.gnu.org/software/guile/manual/html_node/SRFI_002d19-Date-to-string.html
1773 ;; for details.
1774 (G_ "~b ~d ~Y ~T"))))
1775 (current (generation-number profile)))
ad18c7e6 1776 (if (= number current)
3bd9672c
LC
1777 ;; TRANSLATORS: The word "current" here is an adjective for
1778 ;; "Generation", as in "current generation". Use the appropriate
1779 ;; gender where applicable.
69daee23 1780 (format #t (G_ "~a\t(current)~%") header)
ad18c7e6
LC
1781 (format #t "~a~%" header)))))
1782
e95ae7c2 1783(define (display-profile-content-diff profile gen1 gen2)
dc013aff 1784 "Display the changed packages in PROFILE GEN2 compared to generation GEN1."
e95ae7c2
RJ
1785
1786 (define (equal-entry? first second)
1787 (string= (manifest-entry-item first) (manifest-entry-item second)))
1788
1789 (define (display-entry entry prefix)
1790 (match entry
1791 (($ <manifest-entry> name version output location _)
1792 (format #t " ~a ~a\t~a\t~a\t~a~%" prefix name version output location))))
1793
1794 (define (list-entries number)
1795 (manifest-entries (profile-manifest (generation-file-name profile number))))
1796
1797 (define (display-diff profile old new)
1798 (display-generation profile new)
1799 (let ((added (lset-difference
1800 equal-entry? (list-entries new) (list-entries old)))
1801 (removed (lset-difference
1802 equal-entry? (list-entries old) (list-entries new))))
1803 (for-each (cut display-entry <> "+") added)
88bdbb2a
RJ
1804 (for-each (cut display-entry <> "-") removed)
1805 (newline)))
e95ae7c2
RJ
1806
1807 (display-diff profile gen1 gen2))
1808
55e1dfa4
LC
1809(define (profile-lock-handler profile errno . _)
1810 "Handle failure to acquire PROFILE's lock."
3f8e890d
LC
1811 ;; NFS mounts can return ENOLCK. When that happens, there's not much that
1812 ;; can be done, so warn the user and keep going.
1813 (if (= errno ENOLCK)
1814 (warning (G_ "cannot lock profile ~a: ~a~%")
1815 profile (strerror errno))
1816 (leave (G_ "profile ~a is locked by another process~%")
1817 profile)))
55e1dfa4
LC
1818
1819(define profile-lock-file
1820 (cut string-append <> ".lock"))
1821
1822(define-syntax-rule (with-profile-lock profile exp ...)
1823 "Grab PROFILE's lock and evaluate EXP... Call 'leave' if the lock is
1824already taken."
1825 (with-file-lock/no-wait (profile-lock-file profile)
1826 (cut profile-lock-handler profile <...>)
1827 exp ...))
1828
ad18c7e6
LC
1829(define (display-profile-content profile number)
1830 "Display the packages in PROFILE, generation NUMBER, in a human-readable
1831way."
1832 (for-each (match-lambda
1833 (($ <manifest-entry> name version output location _)
1834 (format #t " ~a\t~a\t~a\t~a~%"
1835 name version output location)))
1836
1837 ;; Show most recently installed packages last.
1838 (reverse
1839 (manifest-entries
1840 (profile-manifest (generation-file-name profile number))))))
1841
06d45f45 1842(define (display-generation-change previous current)
69daee23 1843 (format #t (G_ "switched from generation ~a to ~a~%") previous current))
06d45f45
LC
1844
1845(define (roll-back* store profile)
1846 "Like 'roll-back', but display what is happening."
1847 (call-with-values
1848 (lambda ()
1849 (roll-back store profile))
1850 display-generation-change))
1851
1852(define (switch-to-generation* profile number)
1853 "Like 'switch-generation', but display what is happening."
1854 (let ((previous (switch-to-generation profile number)))
1855 (display-generation-change previous number)))
1856
1857(define (delete-generation* store profile generation)
1858 "Like 'delete-generation', but display what is going on."
69daee23 1859 (format #t (G_ "deleting ~a~%")
06d45f45
LC
1860 (generation-file-name profile generation))
1861 (delete-generation store profile generation))
1862
2876b989
LC
1863(define* (package-specification->name+version+output spec
1864 #:optional (output "out"))
1865 "Parse package specification SPEC and return three value: the specified
1866package name, version number (or #f), and output name (or OUTPUT). SPEC may
1867optionally contain a version number and an output name, as in these examples:
1868
1869 guile
1b846da8 1870 guile@2.0.9
2876b989 1871 guile:debug
1b846da8 1872 guile@2.0.9:debug
2876b989
LC
1873"
1874 (let*-values (((name sub-drv)
1875 (match (string-rindex spec #\:)
1876 (#f (values spec output))
1877 (colon (values (substring spec 0 colon)
1878 (substring spec (+ 1 colon))))))
1879 ((name version)
1880 (package-name->name+version name)))
1881 (values name version sub-drv)))
1882
1883\f
1884;;;
1885;;; Command-line option processing.
1886;;;
1887
e49951eb 1888(define (show-guix-usage)
e49951eb 1889 (format (current-error-port)
69daee23 1890 (G_ "Try `guix --help' for more information.~%"))
25c93676 1891 (exit 1))
e49951eb 1892
e31ff8b8
LC
1893(define (command-files)
1894 "Return the list of source files that define Guix sub-commands."
1895 (define directory
1896 (and=> (search-path %load-path "guix.scm")
1897 (compose (cut string-append <> "/guix/scripts")
1898 dirname)))
1899
2b8cf44f
LC
1900 (define dot-scm?
1901 (cut string-suffix? ".scm" <>))
1902
e31ff8b8 1903 (if directory
09d809db 1904 (scandir directory dot-scm?)
e31ff8b8
LC
1905 '()))
1906
1907(define (commands)
1908 "Return the list of Guix command names."
1909 (map (compose (cut string-drop-right <> 4)
1910 basename)
1911 (command-files)))
1912
1913(define (show-guix-help)
59f734f3 1914 (define (internal? command)
94d92c77
LC
1915 (member command '("substitute" "authenticate" "offload"
1916 "perform-download")))
59f734f3 1917
69daee23 1918 (format #t (G_ "Usage: guix COMMAND ARGS...
e31ff8b8
LC
1919Run COMMAND with ARGS.\n"))
1920 (newline)
69daee23 1921 (format #t (G_ "COMMAND must be one of the sub-commands listed below:\n"))
e31ff8b8
LC
1922 (newline)
1923 ;; TODO: Display a synopsis of each command.
59f734f3
LC
1924 (format #t "~{ ~a~%~}" (sort (remove internal? (commands))
1925 string<?))
e31ff8b8
LC
1926 (show-bug-report-information))
1927
ec5d0a85
LC
1928(define (run-guix-command command . args)
1929 "Run COMMAND with the given ARGS. Report an error when COMMAND is not
1930found."
1931 (define module
1932 (catch 'misc-error
1933 (lambda ()
1934 (resolve-interface `(guix scripts ,command)))
1935 (lambda -
25c93676 1936 (format (current-error-port)
69daee23 1937 (G_ "guix: ~a: command not found~%") command)
25c93676 1938 (show-guix-usage))))
ec5d0a85
LC
1939
1940 (let ((command-main (module-ref module
1941 (symbol-append 'guix- command))))
1942 (parameterize ((program-name command))
14d5ca2e
LC
1943 ;; Disable canonicalization so we don't don't stat unreasonably.
1944 (with-fluids ((%file-port-name-canonicalization #f))
f4453df9
LC
1945 (dynamic-wind
1946 (const #f)
1947 (lambda ()
1948 (apply command-main args))
1949 (lambda ()
1950 ;; Abuse 'exit-hook' (which is normally meant to be used by the
1951 ;; REPL) to run things like profiling hooks upon completion.
1952 (run-hook exit-hook)))))))
ec5d0a85 1953
caa6732e
AK
1954(define (run-guix . args)
1955 "Run the 'guix' command defined by command line ARGS.
1956Unlike 'guix-main', this procedure assumes that locale, i18n support,
694e10af 1957and signal handling have already been set up."
caa6732e
AK
1958 (define option? (cut string-prefix? "-" <>))
1959
cbee9559
LC
1960 ;; The default %LOAD-EXTENSIONS includes the empty string, which doubles the
1961 ;; number of 'stat' calls per entry in %LOAD-PATH. Shamelessly remove it.
1962 (set! %load-extensions '(".scm"))
1963
caa6732e
AK
1964 (match args
1965 (()
1966 (format (current-error-port)
69daee23 1967 (G_ "guix: missing command name~%"))
caa6732e
AK
1968 (show-guix-usage))
1969 ((or ("-h") ("--help"))
1970 (show-guix-help))
85c3fbf5 1971 ((or ("-V") ("--version"))
caa6732e
AK
1972 (show-version-and-exit "guix"))
1973 (((? option? o) args ...)
1974 (format (current-error-port)
69daee23 1975 (G_ "guix: unrecognized option '~a'~%") o)
caa6732e 1976 (show-guix-usage))
2ab5fdc4
LC
1977 (("help" command)
1978 (apply run-guix-command (string->symbol command)
1979 '("--help")))
caa6732e
AK
1980 (("help" args ...)
1981 (show-guix-help))
1982 ((command args ...)
1983 (apply run-guix-command
1984 (string->symbol command)
1985 args))))
1986
e49951eb
MW
1987(define (guix-main arg0 . args)
1988 (initialize-guix)
caa6732e 1989 (apply run-guix args))
e49951eb 1990
073c34d7 1991;;; ui.scm ends here