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