1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2012, 2013, 2014, 2015, 2016, 2017 Ludovic Courtès <ludo@gnu.org>
3 ;;; Copyright © 2013, 2014, 2015 Mark H Weaver <mhw@netris.org>
4 ;;; Copyright © 2014 Eric Bavier <bavier@member.fsf.org>
5 ;;; Copyright © 2014 Ian Denhardt <ian@zenhack.net>
6 ;;; Copyright © 2016 Mathieu Lirzin <mthl@gnu.org>
7 ;;; Copyright © 2015 David Thompson <davet@gnu.org>
8 ;;; Copyright © 2017 Efraim Flashner <efraim@flashner.co.il>
10 ;;; This file is part of GNU Guix.
12 ;;; GNU Guix is free software; you can redistribute it and/or modify it
13 ;;; under the terms of the GNU General Public License as published by
14 ;;; the Free Software Foundation; either version 3 of the License, or (at
15 ;;; your option) any later version.
17 ;;; GNU Guix is distributed in the hope that it will be useful, but
18 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;;; GNU General Public License for more details.
22 ;;; You should have received a copy of the GNU General Public License
23 ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
25 (define-module (guix utils)
26 #:use-module (guix config)
27 #:use-module (srfi srfi-1)
28 #:use-module (srfi srfi-9)
29 #:use-module (srfi srfi-11)
30 #:use-module (srfi srfi-26)
31 #:use-module (srfi srfi-39)
32 #:use-module (ice-9 binary-ports)
33 #:autoload (rnrs io ports) (make-custom-binary-input-port)
34 #:use-module ((rnrs bytevectors) #:select (bytevector-u8-set!))
35 #:use-module (guix memoization)
36 #:use-module (guix records)
37 #:use-module ((guix build utils) #:select (dump-port mkdir-p))
38 #:use-module ((guix build syscalls) #:select (mkdtemp! fdatasync))
39 #:use-module (ice-9 format)
40 #:autoload (ice-9 popen) (open-pipe*)
41 #:autoload (ice-9 rdelim) (read-line)
42 #:use-module (ice-9 regex)
43 #:use-module (ice-9 match)
44 #:use-module (ice-9 format)
45 #:use-module ((ice-9 iconv) #:prefix iconv:)
46 #:use-module (system foreign)
47 #:re-export (memoize) ; for backwards compatibility
48 #:export (strip-keyword-arguments
49 default-keyword-arguments
50 substitute-keyword-arguments
51 ensure-keyword-arguments
53 current-source-directory
61 source-properties->location
62 location->source-properties
64 nix-system->gnu-triplet
65 gnu-triplet->nix-system
67 %current-target-system
68 package-name->name+version
76 string-replace-substring
77 arguments-from-environment-variable
82 call-with-temporary-output-file
83 call-with-temporary-directory
84 with-atomic-file-output
95 call-with-decompressed-port
96 compressed-output-port
97 call-with-compressed-output-port
98 canonical-newline-port
102 make-progress-reporter
104 call-with-progress-reporter))
108 ;;; Filtering & pipes.
111 (define (filtered-port command input)
112 "Return an input port where data drained from INPUT is filtered through
113 COMMAND (a list). In addition, return a list of PIDs that the caller must
114 wait. When INPUT is a file port, it must be unbuffered; otherwise, any
115 buffered data is lost."
116 (let loop ((input input)
118 (if (file-port? input)
121 (match (primitive-fork)
127 (close-port (current-input-port))
128 (dup2 (fileno input) 0)
129 (close-port (current-output-port))
130 (dup2 (fileno out) 1)
133 (apply execl (car command) command))
135 (format (current-error-port)
136 "filtered-port: failed to execute '~{~a ~}': ~a~%"
137 command (strerror (system-error-errno args))))))
139 (primitive-_exit 1))))
142 (values in (cons child pids))))))
144 ;; INPUT is not a file port, so fork just for the sake of tunneling it
145 ;; through a file port.
148 (match (primitive-fork)
154 (dump-port input out))
156 (false-if-exception (close out))
157 (primitive-_exit 0))))
160 (loop in (cons child pids)))))))))
162 (define (decompressed-port compression input)
163 "Return an input port where INPUT is decompressed according to COMPRESSION,
164 a symbol such as 'xz."
166 ((or #f 'none) (values input '()))
167 ('bzip2 (filtered-port `(,%bzip2 "-dc") input))
168 ('xz (filtered-port `(,%xz "-dc" "-T0") input))
169 ('gzip (filtered-port `(,%gzip "-dc") input))
170 (else (error "unsupported compression scheme" compression))))
172 (define (compressed-port compression input)
173 "Return an input port where INPUT is decompressed according to COMPRESSION,
174 a symbol such as 'xz."
176 ((or #f 'none) (values input '()))
177 ('bzip2 (filtered-port `(,%bzip2 "-c") input))
178 ('xz (filtered-port `(,%xz "-c" "-T0") input))
179 ('gzip (filtered-port `(,%gzip "-c") input))
180 (else (error "unsupported compression scheme" compression))))
182 (define (call-with-decompressed-port compression port proc)
183 "Call PROC with a wrapper around PORT, a file port, that decompresses data
184 read from PORT according to COMPRESSION, a symbol such as 'xz."
185 (let-values (((decompressed pids)
186 (decompressed-port compression port)))
192 (close-port decompressed)
193 (unless (every (compose zero? cdr waitpid) pids)
194 (error "decompressed-port failure" pids))))))
196 (define (filtered-output-port command output)
197 "Return an output port. Data written to that port is filtered through
198 COMMAND and written to OUTPUT, an output file port. In addition, return a
199 list of PIDs to wait for. OUTPUT must be unbuffered; otherwise, any buffered
203 (match (primitive-fork)
209 (close-port (current-input-port))
211 (close-port (current-output-port))
212 (dup2 (fileno output) 1)
215 (apply execl (car command) command))
217 (format (current-error-port)
218 "filtered-output-port: failed to execute '~{~a ~}': ~a~%"
219 command (strerror (system-error-errno args))))))
221 (primitive-_exit 1))))
224 (values out (list child)))))))
226 (define* (compressed-output-port compression output
228 "Return an output port whose input is compressed according to COMPRESSION,
229 a symbol such as 'xz, and then written to OUTPUT. In addition return a list
230 of PIDs to wait for. OPTIONS is a list of strings passed to the compression
231 program--e.g., '(\"--fast\")."
233 ((or #f 'none) (values output '()))
234 ('bzip2 (filtered-output-port `(,%bzip2 "-c" ,@options) output))
235 ('xz (filtered-output-port `(,%xz "-c" "-T0" ,@options) output))
236 ('gzip (filtered-output-port `(,%gzip "-c" ,@options) output))
237 (else (error "unsupported compression scheme" compression))))
239 (define* (call-with-compressed-output-port compression port proc
241 "Call PROC with a wrapper around PORT, a file port, that compresses data
242 that goes to PORT according to COMPRESSION, a symbol such as 'xz. OPTIONS is
243 a list of command-line arguments passed to the compression program."
244 (let-values (((compressed pids)
245 (compressed-output-port compression port
252 (close-port compressed)
253 (unless (every (compose zero? cdr waitpid) pids)
254 (error "compressed-output-port failure" pids))))))
256 (define* (edit-expression source-properties proc #:key (encoding "UTF-8"))
257 "Edit the expression specified by SOURCE-PROPERTIES using PROC, which should
258 be a procedure that takes the original expression in string and returns a new
259 one. ENCODING will be used to interpret all port I/O, it default to UTF-8.
260 This procedure returns #t on success."
261 (with-fluids ((%default-port-encoding encoding))
262 (let* ((file (assq-ref source-properties 'filename))
263 (line (assq-ref source-properties 'line))
264 (column (assq-ref source-properties 'column))
265 (in (open-input-file file))
266 ;; The start byte position of the expression.
267 (start (begin (while (not (and (= line (port-line in))
268 (= column (port-column in))))
269 (when (eof-object? (read-char in))
270 (error (format #f "~a: end of file~%" in))))
272 ;; The end byte position of the expression.
273 (end (begin (read in) (ftell in))))
274 (seek in 0 SEEK_SET) ; read from the beginning of the file.
275 (let* ((pre-bv (get-bytevector-n in start))
276 ;; The expression in string form.
277 (str (iconv:bytevector->string
278 (get-bytevector-n in (- end start))
280 (post-bv (get-bytevector-all in))
282 ;; Verify the edited expression is still a scheme expression.
283 (call-with-input-string str* read)
284 ;; Update the file with edited expression.
285 (with-atomic-file-output file
287 (put-bytevector out pre-bv)
289 ;; post-bv maybe the end-of-file object.
290 (when (not (eof-object? post-bv))
291 (put-bytevector out post-bv))
296 ;;; Keyword arguments.
299 (define (strip-keyword-arguments keywords args)
300 "Remove all of the keyword arguments listed in KEYWORDS from ARGS."
301 (let loop ((args args)
306 (((? keyword? kw) arg . rest)
308 (if (memq kw keywords)
310 (cons* arg kw result))))
312 (loop tail (cons head result))))))
314 (define (default-keyword-arguments args defaults)
315 "Return ARGS augmented with any keyword/value from DEFAULTS for
316 keywords not already present in ARGS."
317 (let loop ((defaults defaults)
324 (cons* kw value args))))
328 (define-syntax collect-default-args
333 (collect-default-args rest ...))
334 ((_ (kw _ dflt) rest ...)
335 (cons* kw dflt (collect-default-args rest ...)))))
337 (define-syntax substitute-keyword-arguments
339 "Return a new list of arguments where the value for keyword arg KW is
340 replaced by EXP. EXP is evaluated in a context where VAR is bound to the
341 previous value of the keyword argument, or DFLT if given."
342 ((_ original-args ((kw var dflt ...) exp) ...)
343 (let loop ((args (default-keyword-arguments
345 (collect-default-args (kw var dflt ...) ...)))
348 ((kw var rest (... ...))
349 (loop rest (cons* exp kw before)))
352 (loop rest (cons x before)))
354 (reverse before)))))))
356 (define (delkw kw lst)
357 "Remove KW and its associated value from LST, a keyword/value list such
358 as '(#:foo 1 #:bar 2)."
364 ((kw? value rest ...)
366 (append (reverse result) rest)
367 (loop rest (cons* value kw? result)))))))
369 (define (ensure-keyword-arguments args kw/values)
370 "Force the keywords arguments KW/VALUES in the keyword argument list ARGS.
373 (ensure-keyword-arguments '(#:foo 2) '(#:foo 2))
376 (ensure-keyword-arguments '(#:foo 2) '(#:bar 3))
379 (ensure-keyword-arguments '(#:foo 2) '(#:bar 3 #:foo 42))
380 => (#:foo 42 #:bar 3)
382 (let loop ((args args)
383 (kw/values kw/values)
387 (append (reverse result) kw/values))
389 (match (memq kw kw/values)
391 (loop rest (delkw kw kw/values) (cons* value kw result)))
393 (loop rest kw/values (cons* value kw result))))))))
400 (define* (nix-system->gnu-triplet
401 #:optional (system (%current-system)) (vendor "unknown"))
402 "Return a guess of the GNU triplet corresponding to Nix system
406 (string-append "arm-" vendor "-linux-gnueabihf"))
408 (let* ((dash (string-index system #\-))
409 (arch (substring system 0 dash))
410 (os (substring system (+ 1 dash))))
413 (if (string=? os "linux")
417 (define (gnu-triplet->nix-system triplet)
418 "Return the Nix system type corresponding to TRIPLET, a GNU triplet as
419 returned by `config.guess'."
420 (let ((triplet (cond ((string-match "^i[345]86-(.*)$" triplet)
423 (string-append "i686-" (match:substring m 1))))
425 (cond ((string-match "^arm[^-]*-([^-]+-)?linux-gnueabihf" triplet)
427 ((string-match "^([^-]+)-([^-]+-)?linux-gnu.*" triplet)
430 ;; Nix omits `-gnu' for GNU/Linux.
431 (string-append (match:substring m 1) "-linux")))
432 ((string-match "^([^-]+)-([^-]+-)?([[:alpha:]]+)([0-9]+\\.?)*$" triplet)
435 ;; Nix strip the version number from names such as `gnu0.3',
436 ;; `darwin10.2.0', etc., and always strips the vendor part.
437 (string-append (match:substring m 1) "-"
438 (match:substring m 3))))
441 (define %current-system
442 ;; System type as expected by Nix, usually ARCHITECTURE-KERNEL.
443 ;; By default, this is equal to (gnu-triplet->nix-system %host-type).
444 (make-parameter %system))
446 (define %current-target-system
447 ;; Either #f or a GNU triplet representing the target system we are
448 ;; cross-building to.
451 (define* (package-name->name+version spec
452 #:optional (delimiter #\@))
453 "Given SPEC, a package name like \"foo@0.9.1b\", return two values: \"foo\"
454 and \"0.9.1b\". When the version part is unavailable, SPEC and #f are
455 returned. Both parts must not contain any '@'. Optionally, DELIMITER can be
456 a character other than '@'."
457 (match (string-rindex spec delimiter)
458 (#f (values spec #f))
459 (idx (values (substring spec 0 idx)
460 (substring spec (1+ idx))))))
462 (define* (target-mingw? #:optional (target (%current-target-system)))
464 (string-suffix? "-mingw32" target)))
466 (define version-compare
468 (let ((sym (or (dynamic-func "strverscmp" (dynamic-link))
469 (error "could not find `strverscmp' (from GNU libc)"))))
470 (pointer->procedure int sym (list '* '*)))))
472 "Return '> when A denotes a newer version than B,
473 '< when A denotes a older version than B,
474 or '= when they denote equal versions."
475 (let ((result (strverscmp (string->pointer a) (string->pointer b))))
476 (cond ((positive? result) '>)
477 ((negative? result) '<)
480 (define (version-prefix version-string num-parts)
481 "Truncate version-string to the first num-parts components of the version.
482 For example, (version-prefix \"2.1.47.4.23\" 3) returns \"2.1.47\""
483 (string-join (take (string-split version-string #\.) num-parts) "."))
486 (define (version-major+minor version-string)
487 "Return \"<major>.<minor>\", where major and minor are the major and
488 minor version numbers from version-string."
489 (version-prefix version-string 2))
491 (define (version>? a b)
492 "Return #t when A denotes a version strictly newer than B."
493 (eq? '> (version-compare a b)))
495 (define (version>=? a b)
496 "Return #t when A denotes a version newer or equal to B."
497 (case (version-compare a b)
501 (define (guile-version>? str)
502 "Return #t if the running Guile version is greater than STR."
503 ;; Note: Using (version>? (version) "2.0.5") or similar doesn't work,
504 ;; because the result of (version) can have a prefix, like "2.0.5-deb1".
505 (version>? (string-append (major-version) "."
510 (define (file-extension file)
511 "Return the extension of FILE or #f if there is none."
512 (let ((dot (string-rindex file #\.)))
513 (and dot (substring file (+ 1 dot) (string-length file)))))
515 (define (file-sans-extension file)
516 "Return the substring of FILE without its extension, if any."
517 (let ((dot (string-rindex file #\.)))
519 (substring file 0 dot)
522 (define (compressed-file? file)
523 "Return true if FILE denotes a compressed file."
524 (->bool (member (file-extension file)
525 '("gz" "bz2" "xz" "lz" "lzma" "tgz" "tbz2" "zip"))))
527 (define (switch-symlinks link target)
528 "Atomically switch LINK, a symbolic link, to point to TARGET. Works
529 both when LINK already exists and when it does not."
530 (let ((pivot (string-append link ".new")))
531 (symlink target pivot)
532 (rename-file pivot link)))
534 (define* (string-replace-substring str substr replacement
537 (end (string-length str)))
538 "Replace all occurrences of SUBSTR in the START--END range of STR by
540 (match (string-length substr)
542 (error "string-replace-substring: empty substring"))
544 (let loop ((start start)
545 (pieces (list (substring str 0 start))))
546 (match (string-contains str substr start end)
548 (string-concatenate-reverse
549 (cons (substring str start) pieces)))
551 (loop (+ index substr-length)
553 (substring str start index)
556 (define (arguments-from-environment-variable variable)
557 "Retrieve value of environment variable denoted by string VARIABLE in the
558 form of a list of strings (`char-set:graphic' tokens) suitable for consumption
559 by `args-fold', if VARIABLE is defined, otherwise return an empty list."
560 (let ((env (getenv variable)))
562 (string-tokenize env char-set:graphic)
565 (define (call-with-temporary-output-file proc)
566 "Call PROC with a name of a temporary file and open output port to that
567 file; close the file and delete it when leaving the dynamic extent of this
569 (let* ((directory (or (getenv "TMPDIR") "/tmp"))
570 (template (string-append directory "/guix-file.XXXXXX"))
571 (out (mkstemp! template)))
578 (false-if-exception (close out))
579 (false-if-exception (delete-file template))))))
581 (define (call-with-temporary-directory proc)
582 "Call PROC with a name of a temporary directory; close the directory and
583 delete it when leaving the dynamic extent of this call."
584 (let* ((directory (or (getenv "TMPDIR") "/tmp"))
585 (template (string-append directory "/guix-directory.XXXXXX"))
586 (tmp-dir (mkdtemp! template)))
592 (false-if-exception (rmdir tmp-dir))))))
594 (define (with-atomic-file-output file proc)
595 "Call PROC with an output port for the file that is going to replace FILE.
596 Upon success, FILE is atomically replaced by what has been written to the
597 output port, and PROC's result is returned."
598 (let* ((template (string-append file ".XXXXXX"))
599 (out (mkstemp! template)))
600 (with-throw-handler #t
602 (let ((result (proc out)))
605 (rename-file template file)
608 (false-if-exception (delete-file template))
611 (define* (xdg-directory variable suffix #:key (ensure? #t))
612 "Return the name of the XDG directory that matches VARIABLE and SUFFIX,
613 after making sure that it exists if ENSURE? is true. VARIABLE is an
614 environment variable name like \"XDG_CONFIG_HOME\"; SUFFIX is a suffix like
615 \"/.config\". Honor the XDG specs,
616 <http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html>."
617 (let ((dir (and=> (or (getenv variable)
618 (and=> (or (getenv "HOME")
619 (passwd:dir (getpwuid (getuid))))
620 (cut string-append <> suffix)))
621 (cut string-append <> "/guix"))))
626 (define config-directory
627 (cut xdg-directory "XDG_CONFIG_HOME" "/.config" <...>))
629 (define cache-directory
630 (cut xdg-directory "XDG_CACHE_HOME" "/.cache" <...>))
632 (define (readlink* file)
633 "Call 'readlink' until the result is not a symlink."
634 (define %max-symlink-depth 50)
636 (let loop ((file file)
638 (define (absolute target)
639 (if (absolute-file-name? target)
641 (string-append (dirname file) "/" target)))
643 (if (>= depth %max-symlink-depth)
649 (values #t (readlink file)))
651 (let ((errno (system-error-errno args)))
652 (if (or (= errno EINVAL))
654 (apply throw args))))))
655 (lambda (success? target)
657 (loop (absolute target) (+ depth 1))
660 (define (canonical-newline-port port)
661 "Return an input port that wraps PORT such that all newlines consist
662 of a single carriage return."
663 (define (get-position)
664 (if (port-has-port-position? port) (port-position port) #f))
665 (define (set-position! position)
666 (if (port-has-set-port-position!? port)
667 (set-port-position! position port)
669 (define (close) (close-port port))
670 (define (read! bv start n)
672 (byte (get-u8 port)))
673 (cond ((eof-object? byte) count)
675 (bytevector-u8-set! bv (+ start count) byte)
677 ;; XXX: consume all LFs even if not followed by CR.
678 ((eqv? byte (char->integer #\return)) (loop count (get-u8 port)))
680 (bytevector-u8-set! bv (+ start count) byte)
681 (loop (+ count 1) (get-u8 port))))))
682 (make-custom-binary-input-port "canonical-newline-port"
692 (define (absolute-dirname file)
693 "Return the absolute name of the directory containing FILE, or #f upon
695 (match (search-path %load-path file)
698 ;; If there are relative names in %LOAD-PATH, FILE can be relative and
699 ;; needs to be canonicalized.
700 (if (string-prefix? "/" file)
702 (canonicalize-path (dirname file))))))
704 (define-syntax current-source-directory
706 "Return the absolute name of the current directory, or #f if it could not
710 (match (assq 'filename (or (syntax-source s) '()))
711 (('filename . (? string? file-name))
712 ;; If %FILE-PORT-NAME-CANONICALIZATION is 'relative, then FILE-NAME
713 ;; can be relative. In that case, we try to find out at run time
714 ;; the absolute file name by looking at %LOAD-PATH; doing this at
715 ;; run time rather than expansion time is necessary to allow files
716 ;; to be moved on the file system.
717 (cond ((not file-name)
718 #f) ;raising an error would upset Geiser users
719 ((string-prefix? "/" file-name)
722 #`(absolute-dirname #,file-name))))
726 ;; A source location.
727 (define-record-type <location>
728 (make-location file line column)
730 (file location-file) ; file name
731 (line location-line) ; 1-indexed line
732 (column location-column)) ; 0-indexed column
735 (mlambda (file line column)
736 "Return the <location> object for the given FILE, LINE, and COLUMN."
737 (and line column file
738 (make-location file line column))))
740 (define (source-properties->location loc)
741 "Return a location object based on the info in LOC, an alist as returned
742 by Guile's `source-properties', `frame-source', `current-source-location',
744 (let ((file (assq-ref loc 'filename))
745 (line (assq-ref loc 'line))
746 (col (assq-ref loc 'column)))
747 ;; In accordance with the GCS, start line and column numbers at 1. Note
748 ;; that unlike LINE and `port-column', COL is actually 1-indexed here...
749 (location file (and line (+ line 1)) col)))
751 (define (location->source-properties loc)
752 "Return the source property association list based on the info in LOC,
754 `((line . ,(and=> (location-line loc) 1-))
755 (column . ,(location-column loc))
756 (filename . ,(location-file loc))))
760 ;;; Progress reporter.
763 (define-record-type* <progress-reporter>
764 progress-reporter make-progress-reporter progress-reporter?
765 (start progress-reporter-start) ; thunk
766 (report progress-reporter-report) ; procedure
767 (stop progress-reporter-stop)) ; thunk
769 (define (call-with-progress-reporter reporter proc)
770 "Start REPORTER for progress reporting, and call @code{(@var{proc} report)}
771 with the resulting report procedure. When @var{proc} returns, the REPORTER is
774 (($ <progress-reporter> start report stop)
775 (dynamic-wind start (lambda () (proc report)) stop))))
778 ;;; eval: (put 'call-with-progress-reporter 'scheme-indent-function 1)