ui: Improve reporting of 'system-error' exceptions.
[jackhill/guix/guix.git] / guix / ui.scm
1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2012, 2013, 2014 Ludovic Courtès <ludo@gnu.org>
3 ;;; Copyright © 2013 Mark H Weaver <mhw@netris.org>
4 ;;; Copyright © 2013 Nikita Karetnikov <nikita@karetnikov.org>
5 ;;;
6 ;;; This file is part of GNU Guix.
7 ;;;
8 ;;; GNU Guix is free software; you can redistribute it and/or modify it
9 ;;; under the terms of the GNU General Public License as published by
10 ;;; the Free Software Foundation; either version 3 of the License, or (at
11 ;;; your option) any later version.
12 ;;;
13 ;;; GNU Guix is distributed in the hope that it will be useful, but
14 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 ;;; GNU General Public License for more details.
17 ;;;
18 ;;; You should have received a copy of the GNU General Public License
19 ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
20
21 (define-module (guix ui)
22 #:use-module (guix utils)
23 #:use-module (guix store)
24 #:use-module (guix config)
25 #:use-module (guix packages)
26 #:use-module (guix build-system)
27 #:use-module (guix derivations)
28 #:use-module ((guix licenses) #:select (license? license-name))
29 #:use-module (srfi srfi-1)
30 #:use-module (srfi srfi-11)
31 #:use-module (srfi srfi-19)
32 #:use-module (srfi srfi-26)
33 #:use-module (srfi srfi-34)
34 #:use-module (srfi srfi-35)
35 #:use-module (srfi srfi-37)
36 #:autoload (ice-9 ftw) (scandir)
37 #:use-module (ice-9 match)
38 #:use-module (ice-9 format)
39 #:use-module (ice-9 regex)
40 #:export (_
41 N_
42 leave
43 show-version-and-exit
44 show-bug-report-information
45 string->number*
46 show-what-to-build
47 call-with-error-handling
48 with-error-handling
49 read/eval
50 read/eval-package-expression
51 location->string
52 switch-symlinks
53 config-directory
54 fill-paragraph
55 string->recutils
56 package->recutils
57 package-specification->name+version+output
58 string->generations
59 string->duration
60 args-fold*
61 run-guix-command
62 program-name
63 guix-warning-port
64 warning
65 guix-main))
66
67 ;;; Commentary:
68 ;;;
69 ;;; User interface facilities for command-line tools.
70 ;;;
71 ;;; Code:
72
73 (define %gettext-domain
74 "guix")
75
76 (define _ (cut gettext <> %gettext-domain))
77 (define N_ (cut ngettext <> <> <> %gettext-domain))
78
79 (define-syntax-rule (define-diagnostic name prefix)
80 "Create a diagnostic macro (i.e., NAME), which will prepend PREFIX to all
81 messages."
82 (define-syntax name
83 (lambda (x)
84 (define (augmented-format-string fmt)
85 (string-append "~:[~*~;guix ~a: ~]~a" (syntax->datum fmt)))
86
87 (syntax-case x ()
88 ((name (underscore fmt) args (... ...))
89 (and (string? (syntax->datum #'fmt))
90 (free-identifier=? #'underscore #'_))
91 (with-syntax ((fmt* (augmented-format-string #'fmt))
92 (prefix (datum->syntax x prefix)))
93 #'(format (guix-warning-port) (gettext fmt*)
94 (program-name) (program-name) prefix
95 args (... ...))))
96 ((name (N-underscore singular plural n) args (... ...))
97 (and (string? (syntax->datum #'singular))
98 (string? (syntax->datum #'plural))
99 (free-identifier=? #'N-underscore #'N_))
100 (with-syntax ((s (augmented-format-string #'singular))
101 (p (augmented-format-string #'plural))
102 (prefix (datum->syntax x prefix)))
103 #'(format (guix-warning-port)
104 (ngettext s p n %gettext-domain)
105 (program-name) (program-name) prefix
106 args (... ...))))))))
107
108 (define-diagnostic warning "warning: ") ; emit a warning
109
110 (define-diagnostic report-error "error: ")
111 (define-syntax-rule (leave args ...)
112 "Emit an error message and exit."
113 (begin
114 (report-error args ...)
115 (exit 1)))
116
117 (define (install-locale)
118 "Install the current locale settings."
119 (catch 'system-error
120 (lambda _
121 (setlocale LC_ALL ""))
122 (lambda args
123 (warning (_ "failed to install locale: ~a~%")
124 (strerror (system-error-errno args))))))
125
126 (define (initialize-guix)
127 "Perform the usual initialization for stand-alone Guix commands."
128 (install-locale)
129 (textdomain %gettext-domain)
130
131 ;; Ignore SIGPIPE. If the daemon closes the connection, we prefer to be
132 ;; notified via an EPIPE later.
133 (sigaction SIGPIPE SIG_IGN)
134
135 (setvbuf (current-output-port) _IOLBF)
136 (setvbuf (current-error-port) _IOLBF))
137
138 (define* (show-version-and-exit #:optional (command (car (command-line))))
139 "Display version information for COMMAND and `(exit 0)'."
140 (simple-format #t "~a (~a) ~a~%"
141 command %guix-package-name %guix-version)
142 (display (_ "Copyright (C) 2014 the Guix authors
143 License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
144 This is free software: you are free to change and redistribute it.
145 There is NO WARRANTY, to the extent permitted by law.
146 "))
147 (exit 0))
148
149 (define (show-bug-report-information)
150 (format #t (_ "
151 Report bugs to: ~a.") %guix-bug-report-address)
152 (format #t (_ "
153 ~a home page: <~a>") %guix-package-name %guix-home-page-url)
154 (display (_ "
155 General help using GNU software: <http://www.gnu.org/gethelp/>"))
156 (newline))
157
158 (define (string->number* str)
159 "Like `string->number', but error out with an error message on failure."
160 (or (string->number str)
161 (leave (_ "~a: invalid number~%") str)))
162
163 (define (call-with-error-handling thunk)
164 "Call THUNK within a user-friendly error handler."
165 (guard (c ((package-input-error? c)
166 (let* ((package (package-error-package c))
167 (input (package-error-invalid-input c))
168 (location (package-location package))
169 (file (location-file location))
170 (line (location-line location))
171 (column (location-column location)))
172 (leave (_ "~a:~a:~a: package `~a' has an invalid input: ~s~%")
173 file line column
174 (package-full-name package) input)))
175 ((package-cross-build-system-error? c)
176 (let* ((package (package-error-package c))
177 (loc (package-location package))
178 (system (package-build-system package)))
179 (leave (_ "~a: ~a: build system `~a' does not support cross builds~%")
180 (location->string loc)
181 (package-full-name package)
182 (build-system-name system))))
183 ((nix-connection-error? c)
184 (leave (_ "failed to connect to `~a': ~a~%")
185 (nix-connection-error-file c)
186 (strerror (nix-connection-error-code c))))
187 ((nix-protocol-error? c)
188 ;; FIXME: Server-provided error messages aren't i18n'd.
189 (leave (_ "build failed: ~a~%")
190 (nix-protocol-error-message c)))
191 ((message-condition? c)
192 ;; Normally '&message' error conditions have an i18n'd message.
193 (leave (_ "~a~%") (gettext (condition-message c)))))
194 ;; Catch EPIPE and the likes.
195 (catch 'system-error
196 thunk
197 (lambda (key proc format-string format-args . rest)
198 (leave (_ "~a: ~a~%") proc
199 (apply format #f format-string format-args))))))
200
201 (define (read/eval str)
202 "Read and evaluate STR, raising an error if something goes wrong."
203 (let ((exp (catch #t
204 (lambda ()
205 (call-with-input-string str read))
206 (lambda args
207 (leave (_ "failed to read expression ~s: ~s~%")
208 str args)))))
209 (catch #t
210 (lambda ()
211 (eval exp the-scm-module))
212 (lambda args
213 (leave (_ "failed to evaluate expression `~a': ~s~%")
214 exp args)))))
215
216 (define (read/eval-package-expression str)
217 "Read and evaluate STR and return the package it refers to, or exit an
218 error."
219 (match (read/eval str)
220 ((? package? p) p)
221 (_
222 (leave (_ "expression ~s does not evaluate to a package~%")
223 str))))
224
225 (define* (show-what-to-build store drv
226 #:key dry-run? (use-substitutes? #t))
227 "Show what will or would (depending on DRY-RUN?) be built in realizing the
228 derivations listed in DRV. Return #t if there's something to build, #f
229 otherwise. When USE-SUBSTITUTES?, check and report what is prerequisites are
230 available for download."
231 (let*-values (((build download)
232 (fold2 (lambda (drv build download)
233 (let-values (((b d)
234 (derivation-prerequisites-to-build
235 store drv
236 #:use-substitutes?
237 use-substitutes?)))
238 (values (append b build)
239 (append d download))))
240 '() '()
241 drv))
242 ((build) ; add the DRV themselves
243 (delete-duplicates
244 (append (map derivation-file-name
245 (remove (lambda (drv)
246 (let ((out (derivation->output-path
247 drv)))
248 (or (valid-path? store out)
249 (and use-substitutes?
250 (has-substitutes? store
251 out)))))
252 drv))
253 (map derivation-input-path build))))
254 ((download) ; add the references of DOWNLOAD
255 (if use-substitutes?
256 (delete-duplicates
257 (append download
258 (remove (cut valid-path? store <>)
259 (append-map
260 substitutable-references
261 (substitutable-path-info store
262 download)))))
263 download)))
264 ;; TODO: Show the installed size of DOWNLOAD.
265 (if dry-run?
266 (begin
267 (format (current-error-port)
268 (N_ "~:[The following derivation would be built:~%~{ ~a~%~}~;~]"
269 "~:[The following derivations would be built:~%~{ ~a~%~}~;~]"
270 (length build))
271 (null? build) build)
272 (format (current-error-port)
273 (N_ "~:[The following file would be downloaded:~%~{ ~a~%~}~;~]"
274 "~:[The following files would be downloaded:~%~{ ~a~%~}~;~]"
275 (length download))
276 (null? download) download))
277 (begin
278 (format (current-error-port)
279 (N_ "~:[The following derivation will be built:~%~{ ~a~%~}~;~]"
280 "~:[The following derivations will be built:~%~{ ~a~%~}~;~]"
281 (length build))
282 (null? build) build)
283 (format (current-error-port)
284 (N_ "~:[The following file will be downloaded:~%~{ ~a~%~}~;~]"
285 "~:[The following files will be downloaded:~%~{ ~a~%~}~;~]"
286 (length download))
287 (null? download) download)))
288 (pair? build)))
289
290 (define-syntax with-error-handling
291 (syntax-rules ()
292 "Run BODY within a user-friendly error condition handler."
293 ((_ body ...)
294 (call-with-error-handling
295 (lambda ()
296 body ...)))))
297
298 (define (location->string loc)
299 "Return a human-friendly, GNU-standard representation of LOC."
300 (match loc
301 (#f (_ "<unknown location>"))
302 (($ <location> file line column)
303 (format #f "~a:~a:~a" file line column))))
304
305 (define (switch-symlinks link target)
306 "Atomically switch LINK, a symbolic link, to point to TARGET. Works
307 both when LINK already exists and when it does not."
308 (let ((pivot (string-append link ".new")))
309 (symlink target pivot)
310 (rename-file pivot link)))
311
312 (define (config-directory)
313 "Return the name of the configuration directory, after making sure that it
314 exists. Honor the XDG specs,
315 <http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html>."
316 (let ((dir (and=> (or (getenv "XDG_CONFIG_HOME")
317 (and=> (getenv "HOME")
318 (cut string-append <> "/.config")))
319 (cut string-append <> "/guix"))))
320 (catch 'system-error
321 (lambda ()
322 (mkdir dir)
323 dir)
324 (lambda args
325 (match (system-error-errno args)
326 ((or EEXIST 0)
327 dir)
328 (err
329 (leave (_ "failed to create configuration directory `~a': ~a~%")
330 dir (strerror err))))))))
331
332 (define* (fill-paragraph str width #:optional (column 0))
333 "Fill STR such that each line contains at most WIDTH characters, assuming
334 that the first character is at COLUMN.
335
336 When STR contains a single line break surrounded by other characters, it is
337 converted to a space; sequences of more than one line break are preserved."
338 (define (maybe-break chr result)
339 (match result
340 ((column newlines chars)
341 (case chr
342 ((#\newline)
343 `(,column ,(+ 1 newlines) ,chars))
344 (else
345 (let ((chars (case newlines
346 ((0) chars)
347 ((1) (cons #\space chars))
348 (else
349 (append (make-list newlines #\newline) chars))))
350 (column (case newlines
351 ((0) column)
352 ((1) (+ 1 column))
353 (else 0))))
354 (let ((chars (cons chr chars))
355 (column (+ 1 column)))
356 (if (> column width)
357 (let*-values (((before after)
358 (break (cut eqv? #\space <>) chars))
359 ((len)
360 (length before)))
361 (if (<= len width)
362 `(,len
363 0
364 ,(if (null? after)
365 before
366 (append before (cons #\newline (cdr after)))))
367 `(,column 0 ,chars))) ; unbreakable
368 `(,column 0 ,chars)))))))))
369
370 (match (string-fold maybe-break
371 `(,column 0 ())
372 str)
373 ((_ _ chars)
374 (list->string (reverse chars)))))
375
376 \f
377 ;;;
378 ;;; Packages.
379 ;;;
380
381 (define (string->recutils str)
382 "Return a version of STR where newlines have been replaced by newlines
383 followed by \"+ \", which makes for a valid multi-line field value in the
384 `recutils' syntax."
385 (list->string
386 (string-fold-right (lambda (chr result)
387 (if (eqv? chr #\newline)
388 (cons* chr #\+ #\space result)
389 (cons chr result)))
390 '()
391 str)))
392
393 (define* (package->recutils p port
394 #:optional (width (or (and=> (getenv "WIDTH")
395 string->number)
396 80)))
397 "Write to PORT a `recutils' record of package P, arranging to fit within
398 WIDTH columns."
399 (define (description->recutils str)
400 (let ((str (_ str)))
401 (string->recutils
402 (fill-paragraph str width
403 (string-length "description: ")))))
404
405 ;; Note: Don't i18n field names so that people can post-process it.
406 (format port "name: ~a~%" (package-name p))
407 (format port "version: ~a~%" (package-version p))
408 (format port "location: ~a~%"
409 (or (and=> (package-location p) location->string)
410 (_ "unknown")))
411
412 ;; Note: Starting from version 1.6 or recutils, hyphens are not allowed in
413 ;; field identifiers.
414 (format port "homepage: ~a~%" (package-home-page p))
415
416 (format port "license: ~a~%"
417 (match (package-license p)
418 (((? license? licenses) ...)
419 (string-join (map license-name licenses)
420 ", "))
421 ((? license? license)
422 (license-name license))
423 (x
424 (_ "unknown"))))
425 (format port "synopsis: ~a~%"
426 (string-map (match-lambda
427 (#\newline #\space)
428 (chr chr))
429 (or (and=> (package-synopsis p) _)
430 "")))
431 (format port "description: ~a~%"
432 (and=> (package-description p) description->recutils))
433 (newline port))
434
435 (define (string->generations str)
436 "Return the list of generations matching a pattern in STR. This function
437 accepts the following patterns: \"1\", \"1,2,3\", \"1..9\", \"1..\", \"..9\"."
438 (define (maybe-integer)
439 (let ((x (string->number str)))
440 (and (integer? x)
441 x)))
442
443 (define (maybe-comma-separated-integers)
444 (let ((lst (delete-duplicates
445 (map string->number
446 (string-split str #\,)))))
447 (and (every integer? lst)
448 lst)))
449
450 (cond ((maybe-integer)
451 =>
452 list)
453 ((maybe-comma-separated-integers)
454 =>
455 identity)
456 ((string-match "^([0-9]+)\\.\\.([0-9]+)$" str)
457 =>
458 (lambda (match)
459 (let ((s (string->number (match:substring match 1)))
460 (e (string->number (match:substring match 2))))
461 (and (every integer? (list s e))
462 (<= s e)
463 (iota (1+ (- e s)) s)))))
464 ((string-match "^([0-9]+)\\.\\.$" str)
465 =>
466 (lambda (match)
467 (let ((s (string->number (match:substring match 1))))
468 (and (integer? s)
469 `(>= ,s)))))
470 ((string-match "^\\.\\.([0-9]+)$" str)
471 =>
472 (lambda (match)
473 (let ((e (string->number (match:substring match 1))))
474 (and (integer? e)
475 `(<= ,e)))))
476 (else #f)))
477
478 (define (string->duration str)
479 "Return the duration matching a pattern in STR. This function accepts the
480 following patterns: \"1d\", \"1w\", \"1m\"."
481 (define (hours->duration hours match)
482 (make-time time-duration 0
483 (* 3600 hours (string->number (match:substring match 1)))))
484
485 (cond ((string-match "^([0-9]+)d$" str)
486 =>
487 (lambda (match)
488 (hours->duration 24 match)))
489 ((string-match "^([0-9]+)w$" str)
490 =>
491 (lambda (match)
492 (hours->duration (* 24 7) match)))
493 ((string-match "^([0-9]+)m$" str)
494 =>
495 (lambda (match)
496 (hours->duration (* 24 30) match)))
497 (else #f)))
498
499 (define* (package-specification->name+version+output spec
500 #:optional (output "out"))
501 "Parse package specification SPEC and return three value: the specified
502 package name, version number (or #f), and output name (or OUTPUT). SPEC may
503 optionally contain a version number and an output name, as in these examples:
504
505 guile
506 guile-2.0.9
507 guile:debug
508 guile-2.0.9:debug
509 "
510 (let*-values (((name sub-drv)
511 (match (string-rindex spec #\:)
512 (#f (values spec output))
513 (colon (values (substring spec 0 colon)
514 (substring spec (+ 1 colon))))))
515 ((name version)
516 (package-name->name+version name)))
517 (values name version sub-drv)))
518
519 \f
520 ;;;
521 ;;; Command-line option processing.
522 ;;;
523
524 (define (args-fold* options unrecognized-option-proc operand-proc . seeds)
525 "A wrapper on top of `args-fold' that does proper user-facing error
526 reporting."
527 (catch 'misc-error
528 (lambda ()
529 (apply args-fold options unrecognized-option-proc
530 operand-proc seeds))
531 (lambda (key proc msg args . rest)
532 ;; XXX: MSG is not i18n'd.
533 (leave (_ "invalid argument: ~a~%")
534 (apply format #f msg args)))))
535
536 (define (show-guix-usage)
537 (format (current-error-port)
538 (_ "Try `guix --help' for more information.~%"))
539 (exit 1))
540
541 (define (command-files)
542 "Return the list of source files that define Guix sub-commands."
543 (define directory
544 (and=> (search-path %load-path "guix.scm")
545 (compose (cut string-append <> "/guix/scripts")
546 dirname)))
547
548 (define dot-scm?
549 (cut string-suffix? ".scm" <>))
550
551 ;; In Guile 2.0.5 `scandir' would return "." and ".." regardless even though
552 ;; they don't match `dot-scm?'. Work around it by doing additional
553 ;; filtering.
554 (if directory
555 (filter dot-scm? (scandir directory dot-scm?))
556 '()))
557
558 (define (commands)
559 "Return the list of Guix command names."
560 (map (compose (cut string-drop-right <> 4)
561 basename)
562 (command-files)))
563
564 (define (show-guix-help)
565 (define (internal? command)
566 (member command '("substitute-binary" "authenticate" "offload")))
567
568 (format #t (_ "Usage: guix COMMAND ARGS...
569 Run COMMAND with ARGS.\n"))
570 (newline)
571 (format #t (_ "COMMAND must be one of the sub-commands listed below:\n"))
572 (newline)
573 ;; TODO: Display a synopsis of each command.
574 (format #t "~{ ~a~%~}" (sort (remove internal? (commands))
575 string<?))
576 (show-bug-report-information))
577
578 (define program-name
579 ;; Name of the command-line program currently executing, or #f.
580 (make-parameter #f))
581
582 (define (run-guix-command command . args)
583 "Run COMMAND with the given ARGS. Report an error when COMMAND is not
584 found."
585 (define module
586 (catch 'misc-error
587 (lambda ()
588 (resolve-interface `(guix scripts ,command)))
589 (lambda -
590 (format (current-error-port)
591 (_ "guix: ~a: command not found~%") command)
592 (show-guix-usage))))
593
594 (let ((command-main (module-ref module
595 (symbol-append 'guix- command))))
596 (parameterize ((program-name command))
597 (apply command-main args))))
598
599 (define guix-warning-port
600 (make-parameter (current-warning-port)))
601
602 (define (guix-main arg0 . args)
603 (initialize-guix)
604 (let ()
605 (define (option? str) (string-prefix? "-" str))
606 (match args
607 (()
608 (format (current-error-port)
609 (_ "guix: missing command name~%"))
610 (show-guix-usage))
611 ((or ("-h") ("--help"))
612 (show-guix-help))
613 (("--version")
614 (show-version-and-exit "guix"))
615 (((? option? o) args ...)
616 (format (current-error-port)
617 (_ "guix: unrecognized option '~a'~%") o)
618 (show-guix-usage))
619 ((command args ...)
620 (apply run-guix-command
621 (string->symbol command)
622 args)))))
623
624 ;;; ui.scm ends here