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