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