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