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