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 build utils) #:select (dump-port))
37 #:use-module ((guix build syscalls) #:select (mkdtemp! fdatasync))
38 #:use-module (ice-9 format)
39 #:autoload (ice-9 popen) (open-pipe*)
40 #:autoload (ice-9 rdelim) (read-line)
41 #:use-module (ice-9 regex)
42 #:use-module (ice-9 match)
43 #:use-module (ice-9 format)
44 #:use-module ((ice-9 iconv) #:prefix iconv:)
45 #:use-module (system foreign)
46 #:re-export (memoize) ; for backwards compatibility
47 #:export (strip-keyword-arguments
48 default-keyword-arguments
49 substitute-keyword-arguments
50 ensure-keyword-arguments
52 current-source-directory
60 source-properties->location
61 location->source-properties
63 nix-system->gnu-triplet
64 gnu-triplet->nix-system
66 %current-target-system
67 package-name->name+version
75 string-replace-substring
76 arguments-from-environment-variable
81 call-with-temporary-output-file
82 call-with-temporary-directory
83 with-atomic-file-output
91 call-with-decompressed-port
92 compressed-output-port
93 call-with-compressed-output-port
94 canonical-newline-port))
98 ;;; Filtering & pipes.
101 (define (filtered-port command input)
102 "Return an input port where data drained from INPUT is filtered through
103 COMMAND (a list). In addition, return a list of PIDs that the caller must
104 wait. When INPUT is a file port, it must be unbuffered; otherwise, any
105 buffered data is lost."
106 (let loop ((input input)
108 (if (file-port? input)
111 (match (primitive-fork)
117 (close-port (current-input-port))
118 (dup2 (fileno input) 0)
119 (close-port (current-output-port))
120 (dup2 (fileno out) 1)
123 (apply execl (car command) command))
125 (format (current-error-port)
126 "filtered-port: failed to execute '~{~a ~}': ~a~%"
127 command (strerror (system-error-errno args))))))
129 (primitive-_exit 1))))
132 (values in (cons child pids))))))
134 ;; INPUT is not a file port, so fork just for the sake of tunneling it
135 ;; through a file port.
138 (match (primitive-fork)
144 (dump-port input out))
146 (false-if-exception (close out))
147 (primitive-_exit 0))))
150 (loop in (cons child pids)))))))))
152 (define (decompressed-port compression input)
153 "Return an input port where INPUT is decompressed according to COMPRESSION,
154 a symbol such as 'xz."
156 ((or #f 'none) (values input '()))
157 ('bzip2 (filtered-port `(,%bzip2 "-dc") input))
158 ('xz (filtered-port `(,%xz "-dc" "-T0") input))
159 ('gzip (filtered-port `(,%gzip "-dc") input))
160 (else (error "unsupported compression scheme" compression))))
162 (define (compressed-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 "-c") input))
168 ('xz (filtered-port `(,%xz "-c" "-T0") input))
169 ('gzip (filtered-port `(,%gzip "-c") input))
170 (else (error "unsupported compression scheme" compression))))
172 (define (call-with-decompressed-port compression port proc)
173 "Call PROC with a wrapper around PORT, a file port, that decompresses data
174 read from PORT according to COMPRESSION, a symbol such as 'xz."
175 (let-values (((decompressed pids)
176 (decompressed-port compression port)))
182 (close-port decompressed)
183 (unless (every (compose zero? cdr waitpid) pids)
184 (error "decompressed-port failure" pids))))))
186 (define (filtered-output-port command output)
187 "Return an output port. Data written to that port is filtered through
188 COMMAND and written to OUTPUT, an output file port. In addition, return a
189 list of PIDs to wait for. OUTPUT must be unbuffered; otherwise, any buffered
193 (match (primitive-fork)
199 (close-port (current-input-port))
201 (close-port (current-output-port))
202 (dup2 (fileno output) 1)
205 (apply execl (car command) command))
207 (format (current-error-port)
208 "filtered-output-port: failed to execute '~{~a ~}': ~a~%"
209 command (strerror (system-error-errno args))))))
211 (primitive-_exit 1))))
214 (values out (list child)))))))
216 (define* (compressed-output-port compression output
218 "Return an output port whose input is compressed according to COMPRESSION,
219 a symbol such as 'xz, and then written to OUTPUT. In addition return a list
220 of PIDs to wait for. OPTIONS is a list of strings passed to the compression
221 program--e.g., '(\"--fast\")."
223 ((or #f 'none) (values output '()))
224 ('bzip2 (filtered-output-port `(,%bzip2 "-c" ,@options) output))
225 ('xz (filtered-output-port `(,%xz "-c" "-T0" ,@options) output))
226 ('gzip (filtered-output-port `(,%gzip "-c" ,@options) output))
227 (else (error "unsupported compression scheme" compression))))
229 (define* (call-with-compressed-output-port compression port proc
231 "Call PROC with a wrapper around PORT, a file port, that compresses data
232 that goes to PORT according to COMPRESSION, a symbol such as 'xz. OPTIONS is
233 a list of command-line arguments passed to the compression program."
234 (let-values (((compressed pids)
235 (compressed-output-port compression port
242 (close-port compressed)
243 (unless (every (compose zero? cdr waitpid) pids)
244 (error "compressed-output-port failure" pids))))))
246 (define* (edit-expression source-properties proc #:key (encoding "UTF-8"))
247 "Edit the expression specified by SOURCE-PROPERTIES using PROC, which should
248 be a procedure that takes the original expression in string and returns a new
249 one. ENCODING will be used to interpret all port I/O, it default to UTF-8.
250 This procedure returns #t on success."
251 (with-fluids ((%default-port-encoding encoding))
252 (let* ((file (assq-ref source-properties 'filename))
253 (line (assq-ref source-properties 'line))
254 (column (assq-ref source-properties 'column))
255 (in (open-input-file file))
256 ;; The start byte position of the expression.
257 (start (begin (while (not (and (= line (port-line in))
258 (= column (port-column in))))
259 (when (eof-object? (read-char in))
260 (error (format #f "~a: end of file~%" in))))
262 ;; The end byte position of the expression.
263 (end (begin (read in) (ftell in))))
264 (seek in 0 SEEK_SET) ; read from the beginning of the file.
265 (let* ((pre-bv (get-bytevector-n in start))
266 ;; The expression in string form.
267 (str (iconv:bytevector->string
268 (get-bytevector-n in (- end start))
270 (post-bv (get-bytevector-all in))
272 ;; Verify the edited expression is still a scheme expression.
273 (call-with-input-string str* read)
274 ;; Update the file with edited expression.
275 (with-atomic-file-output file
277 (put-bytevector out pre-bv)
279 ;; post-bv maybe the end-of-file object.
280 (when (not (eof-object? post-bv))
281 (put-bytevector out post-bv))
286 ;;; Keyword arguments.
289 (define (strip-keyword-arguments keywords args)
290 "Remove all of the keyword arguments listed in KEYWORDS from ARGS."
291 (let loop ((args args)
296 (((? keyword? kw) arg . rest)
298 (if (memq kw keywords)
300 (cons* arg kw result))))
302 (loop tail (cons head result))))))
304 (define (default-keyword-arguments args defaults)
305 "Return ARGS augmented with any keyword/value from DEFAULTS for
306 keywords not already present in ARGS."
307 (let loop ((defaults defaults)
314 (cons* kw value args))))
318 (define-syntax collect-default-args
323 (collect-default-args rest ...))
324 ((_ (kw _ dflt) rest ...)
325 (cons* kw dflt (collect-default-args rest ...)))))
327 (define-syntax substitute-keyword-arguments
329 "Return a new list of arguments where the value for keyword arg KW is
330 replaced by EXP. EXP is evaluated in a context where VAR is bound to the
331 previous value of the keyword argument, or DFLT if given."
332 ((_ original-args ((kw var dflt ...) exp) ...)
333 (let loop ((args (default-keyword-arguments
335 (collect-default-args (kw var dflt ...) ...)))
338 ((kw var rest (... ...))
339 (loop rest (cons* exp kw before)))
342 (loop rest (cons x before)))
344 (reverse before)))))))
346 (define (delkw kw lst)
347 "Remove KW and its associated value from LST, a keyword/value list such
348 as '(#:foo 1 #:bar 2)."
354 ((kw? value rest ...)
356 (append (reverse result) rest)
357 (loop rest (cons* value kw? result)))))))
359 (define (ensure-keyword-arguments args kw/values)
360 "Force the keywords arguments KW/VALUES in the keyword argument list ARGS.
363 (ensure-keyword-arguments '(#:foo 2) '(#:foo 2))
366 (ensure-keyword-arguments '(#:foo 2) '(#:bar 3))
369 (ensure-keyword-arguments '(#:foo 2) '(#:bar 3 #:foo 42))
370 => (#:foo 42 #:bar 3)
372 (let loop ((args args)
373 (kw/values kw/values)
377 (append (reverse result) kw/values))
379 (match (memq kw kw/values)
381 (loop rest (delkw kw kw/values) (cons* value kw result)))
383 (loop rest kw/values (cons* value kw result))))))))
390 (define* (nix-system->gnu-triplet
391 #:optional (system (%current-system)) (vendor "unknown"))
392 "Return a guess of the GNU triplet corresponding to Nix system
396 (string-append "arm-" vendor "-linux-gnueabihf"))
398 (let* ((dash (string-index system #\-))
399 (arch (substring system 0 dash))
400 (os (substring system (+ 1 dash))))
403 (if (string=? os "linux")
407 (define (gnu-triplet->nix-system triplet)
408 "Return the Nix system type corresponding to TRIPLET, a GNU triplet as
409 returned by `config.guess'."
410 (let ((triplet (cond ((string-match "^i[345]86-(.*)$" triplet)
413 (string-append "i686-" (match:substring m 1))))
415 (cond ((string-match "^arm[^-]*-([^-]+-)?linux-gnueabihf" triplet)
417 ((string-match "^([^-]+)-([^-]+-)?linux-gnu.*" triplet)
420 ;; Nix omits `-gnu' for GNU/Linux.
421 (string-append (match:substring m 1) "-linux")))
422 ((string-match "^([^-]+)-([^-]+-)?([[:alpha:]]+)([0-9]+\\.?)*$" triplet)
425 ;; Nix strip the version number from names such as `gnu0.3',
426 ;; `darwin10.2.0', etc., and always strips the vendor part.
427 (string-append (match:substring m 1) "-"
428 (match:substring m 3))))
431 (define %current-system
432 ;; System type as expected by Nix, usually ARCHITECTURE-KERNEL.
433 ;; By default, this is equal to (gnu-triplet->nix-system %host-type).
434 (make-parameter %system))
436 (define %current-target-system
437 ;; Either #f or a GNU triplet representing the target system we are
438 ;; cross-building to.
441 (define* (package-name->name+version spec
442 #:optional (delimiter #\@))
443 "Given SPEC, a package name like \"foo@0.9.1b\", return two values: \"foo\"
444 and \"0.9.1b\". When the version part is unavailable, SPEC and #f are
445 returned. Both parts must not contain any '@'. Optionally, DELIMITER can be
446 a character other than '@'."
447 (match (string-rindex spec delimiter)
448 (#f (values spec #f))
449 (idx (values (substring spec 0 idx)
450 (substring spec (1+ idx))))))
452 (define* (target-mingw? #:optional (target (%current-target-system)))
454 (string-suffix? "-mingw32" target)))
456 (define version-compare
458 (let ((sym (or (dynamic-func "strverscmp" (dynamic-link))
459 (error "could not find `strverscmp' (from GNU libc)"))))
460 (pointer->procedure int sym (list '* '*)))))
462 "Return '> when A denotes a newer version than B,
463 '< when A denotes a older version than B,
464 or '= when they denote equal versions."
465 (let ((result (strverscmp (string->pointer a) (string->pointer b))))
466 (cond ((positive? result) '>)
467 ((negative? result) '<)
470 (define (version-prefix version-string num-parts)
471 "Truncate version-string to the first num-parts components of the version.
472 For example, (version-prefix \"2.1.47.4.23\" 3) returns \"2.1.47\""
473 (string-join (take (string-split version-string #\.) num-parts) "."))
476 (define (version-major+minor version-string)
477 "Return \"<major>.<minor>\", where major and minor are the major and
478 minor version numbers from version-string."
479 (version-prefix version-string 2))
481 (define (version>? a b)
482 "Return #t when A denotes a version strictly newer than B."
483 (eq? '> (version-compare a b)))
485 (define (version>=? a b)
486 "Return #t when A denotes a version newer or equal to B."
487 (case (version-compare a b)
491 (define (guile-version>? str)
492 "Return #t if the running Guile version is greater than STR."
493 ;; Note: Using (version>? (version) "2.0.5") or similar doesn't work,
494 ;; because the result of (version) can have a prefix, like "2.0.5-deb1".
495 (version>? (string-append (major-version) "."
500 (define (file-extension file)
501 "Return the extension of FILE or #f if there is none."
502 (let ((dot (string-rindex file #\.)))
503 (and dot (substring file (+ 1 dot) (string-length file)))))
505 (define (file-sans-extension file)
506 "Return the substring of FILE without its extension, if any."
507 (let ((dot (string-rindex file #\.)))
509 (substring file 0 dot)
512 (define (compressed-file? file)
513 "Return true if FILE denotes a compressed file."
514 (->bool (member (file-extension file)
515 '("gz" "bz2" "xz" "lz" "lzma" "tgz" "tbz2" "zip"))))
517 (define (switch-symlinks link target)
518 "Atomically switch LINK, a symbolic link, to point to TARGET. Works
519 both when LINK already exists and when it does not."
520 (let ((pivot (string-append link ".new")))
521 (symlink target pivot)
522 (rename-file pivot link)))
524 (define* (string-replace-substring str substr replacement
527 (end (string-length str)))
528 "Replace all occurrences of SUBSTR in the START--END range of STR by
530 (match (string-length substr)
532 (error "string-replace-substring: empty substring"))
534 (let loop ((start start)
535 (pieces (list (substring str 0 start))))
536 (match (string-contains str substr start end)
538 (string-concatenate-reverse
539 (cons (substring str start) pieces)))
541 (loop (+ index substr-length)
543 (substring str start index)
546 (define (arguments-from-environment-variable variable)
547 "Retrieve value of environment variable denoted by string VARIABLE in the
548 form of a list of strings (`char-set:graphic' tokens) suitable for consumption
549 by `args-fold', if VARIABLE is defined, otherwise return an empty list."
550 (let ((env (getenv variable)))
552 (string-tokenize env char-set:graphic)
555 (define (call-with-temporary-output-file proc)
556 "Call PROC with a name of a temporary file and open output port to that
557 file; close the file and delete it when leaving the dynamic extent of this
559 (let* ((directory (or (getenv "TMPDIR") "/tmp"))
560 (template (string-append directory "/guix-file.XXXXXX"))
561 (out (mkstemp! template)))
568 (false-if-exception (close out))
569 (false-if-exception (delete-file template))))))
571 (define (call-with-temporary-directory proc)
572 "Call PROC with a name of a temporary directory; close the directory and
573 delete it when leaving the dynamic extent of this call."
574 (let* ((directory (or (getenv "TMPDIR") "/tmp"))
575 (template (string-append directory "/guix-directory.XXXXXX"))
576 (tmp-dir (mkdtemp! template)))
582 (false-if-exception (rmdir tmp-dir))))))
584 (define (with-atomic-file-output file proc)
585 "Call PROC with an output port for the file that is going to replace FILE.
586 Upon success, FILE is atomically replaced by what has been written to the
587 output port, and PROC's result is returned."
588 (let* ((template (string-append file ".XXXXXX"))
589 (out (mkstemp! template)))
590 (with-throw-handler #t
592 (let ((result (proc out)))
595 (rename-file template file)
598 (false-if-exception (delete-file template))
601 (define (cache-directory)
602 "Return the cache directory for Guix, by default ~/.cache/guix."
603 (string-append (or (getenv "XDG_CACHE_HOME")
604 (and=> (or (getenv "HOME")
605 (passwd:dir (getpwuid (getuid))))
606 (cut string-append <> "/.cache")))
609 (define (readlink* file)
610 "Call 'readlink' until the result is not a symlink."
611 (define %max-symlink-depth 50)
613 (let loop ((file file)
615 (define (absolute target)
616 (if (absolute-file-name? target)
618 (string-append (dirname file) "/" target)))
620 (if (>= depth %max-symlink-depth)
626 (values #t (readlink file)))
628 (let ((errno (system-error-errno args)))
629 (if (or (= errno EINVAL))
631 (apply throw args))))))
632 (lambda (success? target)
634 (loop (absolute target) (+ depth 1))
637 (define (canonical-newline-port port)
638 "Return an input port that wraps PORT such that all newlines consist
639 of a single carriage return."
640 (define (get-position)
641 (if (port-has-port-position? port) (port-position port) #f))
642 (define (set-position! position)
643 (if (port-has-set-port-position!? port)
644 (set-port-position! position port)
646 (define (close) (close-port port))
647 (define (read! bv start n)
649 (byte (get-u8 port)))
650 (cond ((eof-object? byte) count)
652 (bytevector-u8-set! bv (+ start count) byte)
654 ;; XXX: consume all LFs even if not followed by CR.
655 ((eqv? byte (char->integer #\return)) (loop count (get-u8 port)))
657 (bytevector-u8-set! bv (+ start count) byte)
658 (loop (+ count 1) (get-u8 port))))))
659 (make-custom-binary-input-port "canonical-newline-port"
669 (define (absolute-dirname file)
670 "Return the absolute name of the directory containing FILE, or #f upon
672 (match (search-path %load-path file)
675 ;; If there are relative names in %LOAD-PATH, FILE can be relative and
676 ;; needs to be canonicalized.
677 (if (string-prefix? "/" file)
679 (canonicalize-path (dirname file))))))
681 (define-syntax current-source-directory
683 "Return the absolute name of the current directory, or #f if it could not
687 (match (assq 'filename (syntax-source s))
688 (('filename . (? string? file-name))
689 ;; If %FILE-PORT-NAME-CANONICALIZATION is 'relative, then FILE-NAME
690 ;; can be relative. In that case, we try to find out at run time
691 ;; the absolute file name by looking at %LOAD-PATH; doing this at
692 ;; run time rather than expansion time is necessary to allow files
693 ;; to be moved on the file system.
694 (cond ((not file-name)
695 #f) ;raising an error would upset Geiser users
696 ((string-prefix? "/" file-name)
699 #`(absolute-dirname #,file-name))))
703 ;; A source location.
704 (define-record-type <location>
705 (make-location file line column)
707 (file location-file) ; file name
708 (line location-line) ; 1-indexed line
709 (column location-column)) ; 0-indexed column
712 (mlambda (file line column)
713 "Return the <location> object for the given FILE, LINE, and COLUMN."
714 (and line column file
715 (make-location file line column))))
717 (define (source-properties->location loc)
718 "Return a location object based on the info in LOC, an alist as returned
719 by Guile's `source-properties', `frame-source', `current-source-location',
721 (let ((file (assq-ref loc 'filename))
722 (line (assq-ref loc 'line))
723 (col (assq-ref loc 'column)))
724 ;; In accordance with the GCS, start line and column numbers at 1. Note
725 ;; that unlike LINE and `port-column', COL is actually 1-indexed here...
726 (location file (and line (+ line 1)) col)))
728 (define (location->source-properties loc)
729 "Return the source property association list based on the info in LOC,
731 `((line . ,(and=> (location-line loc) 1-))
732 (column . ,(location-column loc))
733 (filename . ,(location-file loc))))