1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 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 Mathieu Othacehe <m.othacehe@gmail.com>
9 ;;; Copyright © 2018, 2020 Marius Bakke <marius@gnu.org>
11 ;;; This file is part of GNU Guix.
13 ;;; GNU Guix is free software; you can redistribute it and/or modify it
14 ;;; under the terms of the GNU General Public License as published by
15 ;;; the Free Software Foundation; either version 3 of the License, or (at
16 ;;; your option) any later version.
18 ;;; GNU Guix is distributed in the hope that it will be useful, but
19 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;;; GNU General Public License for more details.
23 ;;; You should have received a copy of the GNU General Public License
24 ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
26 (define-module (guix utils)
27 #:use-module (guix config)
28 #:use-module (srfi srfi-1)
29 #:use-module (srfi srfi-9)
30 #:use-module (srfi srfi-11)
31 #:use-module (srfi srfi-26)
32 #:use-module (srfi srfi-39)
33 #:use-module (ice-9 ftw)
34 #:use-module (rnrs io ports) ;need 'port-position' etc.
35 #:use-module ((rnrs bytevectors) #:select (bytevector-u8-set!))
36 #:use-module (guix memoization)
37 #:use-module ((guix build utils) #:select (dump-port mkdir-p delete-file-recursively))
38 #:use-module ((guix build syscalls) #:select (mkdtemp! fdatasync))
39 #:use-module (guix diagnostics) ;<location>, &error-location, etc.
40 #:use-module (ice-9 format)
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 (<location> ;for backwards compatibility
52 source-properties->location
53 location->source-properties
62 #:export (strip-keyword-arguments
63 default-keyword-arguments
64 substitute-keyword-arguments
65 ensure-keyword-arguments
67 current-source-directory
69 nix-system->gnu-triplet
70 gnu-triplet->nix-system
72 %current-target-system
73 package-name->name+version
89 string-replace-substring
92 tarball-sans-extension
95 call-with-temporary-output-file
96 call-with-temporary-directory
97 with-atomic-file-output
99 with-environment-variables
100 arguments-from-environment-variable
111 call-with-decompressed-port
112 compressed-output-port
113 call-with-compressed-output-port
114 canonical-newline-port))
118 ;;; Environment variables.
121 (define (call-with-environment-variables variables thunk)
122 "Call THUNK with the environment VARIABLES set."
123 (let ((environment (environ)))
126 (for-each (match-lambda
128 (setenv variable value)))
132 (environ environment)))))
134 (define-syntax-rule (with-environment-variables variables exp ...)
135 "Evaluate EXP with the given environment VARIABLES set."
136 (call-with-environment-variables variables
137 (lambda () exp ...)))
139 (define (arguments-from-environment-variable variable)
140 "Retrieve value of environment variable denoted by string VARIABLE in the
141 form of a list of strings (`char-set:graphic' tokens) suitable for consumption
142 by `args-fold', if VARIABLE is defined, otherwise return an empty list."
143 (let ((env (getenv variable)))
145 (string-tokenize env char-set:graphic)
150 ;;; Filtering & pipes.
153 (define (filtered-port command input)
154 "Return an input port where data drained from INPUT is filtered through
155 COMMAND (a list). In addition, return a list of PIDs that the caller must
156 wait. When INPUT is a file port, it must be unbuffered; otherwise, any
157 buffered data is lost."
158 (let loop ((input input)
160 (if (file-port? input)
163 (match (primitive-fork)
169 (close-port (current-input-port))
170 (dup2 (fileno input) 0)
171 (close-port (current-output-port))
172 (dup2 (fileno out) 1)
175 (apply execl (car command) command))
177 (format (current-error-port)
178 "filtered-port: failed to execute '~{~a ~}': ~a~%"
179 command (strerror (system-error-errno args))))))
181 (primitive-_exit 1))))
184 (values in (cons child pids))))))
186 ;; INPUT is not a file port, so fork just for the sake of tunneling it
187 ;; through a file port.
190 (match (primitive-fork)
196 (dump-port input out))
199 (false-if-exception (close out))
200 (primitive-_exit 0))))
204 (loop in (cons child pids)))))))))
206 (define (lzip-port proc port . args)
207 "Return the lzip port produced by calling PROC (a symbol) on PORT and ARGS.
208 Raise an error if lzlib support is missing."
209 (let* ((lzlib (false-if-exception (resolve-interface '(guix lzlib))))
210 (supported? (and lzlib
211 ((module-ref lzlib 'lzlib-available?)))))
213 (let ((make-port (module-ref lzlib proc)))
214 (values (make-port port) '()))
215 (error "lzip compression not supported" lzlib))))
217 (define (decompressed-port compression input)
218 "Return an input port where INPUT is decompressed according to COMPRESSION,
219 a symbol such as 'xz."
221 ((or #f 'none) (values input '()))
222 ('bzip2 (filtered-port `(,%bzip2 "-dc") input))
223 ('xz (filtered-port `(,%xz "-dc") input))
224 ('gzip (filtered-port `(,%gzip "-dc") input))
225 ('lzip (values (lzip-port 'make-lzip-input-port input)
227 (_ (error "unsupported compression scheme" compression))))
229 (define (compressed-port compression input)
230 "Return an input port where INPUT is compressed according to COMPRESSION,
231 a symbol such as 'xz."
233 ((or #f 'none) (values input '()))
234 ('bzip2 (filtered-port `(,%bzip2 "-c") input))
235 ('xz (filtered-port `(,%xz "-c") input))
236 ('gzip (filtered-port `(,%gzip "-c") input))
237 ('lzip (values (lzip-port 'make-lzip-input-port/compressed input)
239 (_ (error "unsupported compression scheme" compression))))
241 (define (call-with-decompressed-port compression port proc)
242 "Call PROC with a wrapper around PORT, a file port, that decompresses data
243 read from PORT according to COMPRESSION, a symbol such as 'xz."
244 (let-values (((decompressed pids)
245 (decompressed-port compression port)))
251 (close-port decompressed)
252 (unless (every (compose zero? cdr waitpid) pids)
253 (error "decompressed-port failure" pids))))))
255 (define (filtered-output-port command output)
256 "Return an output port. Data written to that port is filtered through
257 COMMAND and written to OUTPUT, an output file port. In addition, return a
258 list of PIDs to wait for. OUTPUT must be unbuffered; otherwise, any buffered
262 (match (primitive-fork)
268 (close-port (current-input-port))
270 (close-port (current-output-port))
271 (dup2 (fileno output) 1)
274 (apply execl (car command) command))
276 (format (current-error-port)
277 "filtered-output-port: failed to execute '~{~a ~}': ~a~%"
278 command (strerror (system-error-errno args))))))
280 (primitive-_exit 1))))
283 (values out (list child)))))))
285 (define* (compressed-output-port compression output
287 "Return an output port whose input is compressed according to COMPRESSION,
288 a symbol such as 'xz, and then written to OUTPUT. In addition return a list
289 of PIDs to wait for. OPTIONS is a list of strings passed to the compression
290 program--e.g., '(\"--fast\")."
292 ((or #f 'none) (values output '()))
293 ('bzip2 (filtered-output-port `(,%bzip2 "-c" ,@options) output))
294 ('xz (filtered-output-port `(,%xz "-c" ,@options) output))
295 ('gzip (filtered-output-port `(,%gzip "-c" ,@options) output))
296 ('lzip (values (lzip-port 'make-lzip-output-port output)
298 (_ (error "unsupported compression scheme" compression))))
300 (define* (call-with-compressed-output-port compression port proc
302 "Call PROC with a wrapper around PORT, a file port, that compresses data
303 that goes to PORT according to COMPRESSION, a symbol such as 'xz. OPTIONS is
304 a list of command-line arguments passed to the compression program."
305 (let-values (((compressed pids)
306 (compressed-output-port compression port
313 (close-port compressed)
314 (unless (every (compose zero? cdr waitpid) pids)
315 (error "compressed-output-port failure" pids))))))
317 (define* (edit-expression source-properties proc #:key (encoding "UTF-8"))
318 "Edit the expression specified by SOURCE-PROPERTIES using PROC, which should
319 be a procedure that takes the original expression in string and returns a new
320 one. ENCODING will be used to interpret all port I/O, it default to UTF-8.
321 This procedure returns #t on success."
322 (with-fluids ((%default-port-encoding encoding))
323 (let* ((file (assq-ref source-properties 'filename))
324 (line (assq-ref source-properties 'line))
325 (column (assq-ref source-properties 'column))
326 (in (open-input-file file))
327 ;; The start byte position of the expression.
328 (start (begin (while (not (and (= line (port-line in))
329 (= column (port-column in))))
330 (when (eof-object? (read-char in))
331 (error (format #f "~a: end of file~%" in))))
333 ;; The end byte position of the expression.
334 (end (begin (read in) (ftell in))))
335 (seek in 0 SEEK_SET) ; read from the beginning of the file.
336 (let* ((pre-bv (get-bytevector-n in start))
337 ;; The expression in string form.
338 (str (iconv:bytevector->string
339 (get-bytevector-n in (- end start))
341 (post-bv (get-bytevector-all in))
343 ;; Verify the edited expression is still a scheme expression.
344 (call-with-input-string str* read)
345 ;; Update the file with edited expression.
346 (with-atomic-file-output file
348 (put-bytevector out pre-bv)
350 ;; post-bv maybe the end-of-file object.
351 (when (not (eof-object? post-bv))
352 (put-bytevector out post-bv))
357 ;;; Keyword arguments.
360 (define (strip-keyword-arguments keywords args)
361 "Remove all of the keyword arguments listed in KEYWORDS from ARGS."
362 (let loop ((args args)
367 (((? keyword? kw) arg . rest)
369 (if (memq kw keywords)
371 (cons* arg kw result))))
373 (loop tail (cons head result))))))
375 (define (default-keyword-arguments args defaults)
376 "Return ARGS augmented with any keyword/value from DEFAULTS for
377 keywords not already present in ARGS."
378 (let loop ((defaults defaults)
385 (cons* kw value args))))
389 (define-syntax collect-default-args
394 (collect-default-args rest ...))
395 ((_ (kw _ dflt) rest ...)
396 (cons* kw dflt (collect-default-args rest ...)))))
398 (define-syntax substitute-keyword-arguments
400 "Return a new list of arguments where the value for keyword arg KW is
401 replaced by EXP. EXP is evaluated in a context where VAR is bound to the
402 previous value of the keyword argument, or DFLT if given."
403 ((_ original-args ((kw var dflt ...) exp) ...)
404 (let loop ((args (default-keyword-arguments
406 (collect-default-args (kw var dflt ...) ...)))
409 ((kw var rest (... ...))
410 (loop rest (cons* exp kw before)))
413 (loop rest (cons x before)))
415 (reverse before)))))))
417 (define (delkw kw lst)
418 "Remove KW and its associated value from LST, a keyword/value list such
419 as '(#:foo 1 #:bar 2)."
425 ((kw? value rest ...)
427 (append (reverse result) rest)
428 (loop rest (cons* value kw? result)))))))
430 (define (ensure-keyword-arguments args kw/values)
431 "Force the keywords arguments KW/VALUES in the keyword argument list ARGS.
434 (ensure-keyword-arguments '(#:foo 2) '(#:foo 2))
437 (ensure-keyword-arguments '(#:foo 2) '(#:bar 3))
440 (ensure-keyword-arguments '(#:foo 2) '(#:bar 3 #:foo 42))
441 => (#:foo 42 #:bar 3)
443 (let loop ((args args)
444 (kw/values kw/values)
448 (append (reverse result) kw/values))
450 (match (memq kw kw/values)
452 (loop rest (delkw kw kw/values) (cons* value kw result)))
454 (loop rest kw/values (cons* value kw result))))))))
461 (define* (nix-system->gnu-triplet
462 #:optional (system (%current-system)) (vendor "unknown"))
463 "Return a guess of the GNU triplet corresponding to Nix system
467 (string-append "arm-" vendor "-linux-gnueabihf"))
469 (let* ((dash (string-index system #\-))
470 (arch (substring system 0 dash))
471 (os (substring system (+ 1 dash))))
474 (if (string=? os "linux")
478 (define (gnu-triplet->nix-system triplet)
479 "Return the Nix system type corresponding to TRIPLET, a GNU triplet as
480 returned by `config.guess'."
481 (let ((triplet (cond ((string-match "^i[345]86-(.*)$" triplet)
484 (string-append "i686-" (match:substring m 1))))
486 (cond ((string-match "^arm[^-]*-([^-]+-)?linux-gnueabihf" triplet)
488 ((string-match "^([^-]+)-([^-]+-)?linux-gnu.*" triplet)
491 ;; Nix omits `-gnu' for GNU/Linux.
492 (string-append (match:substring m 1) "-linux")))
493 ((string-match "^([^-]+)-([^-]+-)?([[:alpha:]]+)([0-9]+\\.?)*$" triplet)
496 ;; Nix strip the version number from names such as `gnu0.3',
497 ;; `darwin10.2.0', etc., and always strips the vendor part.
498 (string-append (match:substring m 1) "-"
499 (match:substring m 3))))
502 (define %current-system
503 ;; System type as expected by Nix, usually ARCHITECTURE-KERNEL.
504 ;; By default, this is equal to (gnu-triplet->nix-system %host-type).
505 (make-parameter %system))
507 (define %current-target-system
508 ;; Either #f or a GNU triplet representing the target system we are
509 ;; cross-building to.
512 (define* (package-name->name+version spec
513 #:optional (delimiter #\@))
514 "Given SPEC, a package name like \"foo@0.9.1b\", return two values: \"foo\"
515 and \"0.9.1b\". When the version part is unavailable, SPEC and #f are
516 returned. Both parts must not contain any '@'. Optionally, DELIMITER can be
517 a character other than '@'."
518 (match (string-rindex spec delimiter)
519 (#f (values spec #f))
520 (idx (values (substring spec 0 idx)
521 (substring spec (1+ idx))))))
523 (define* (target-mingw? #:optional (target (%current-target-system)))
525 (string-suffix? "-mingw32" target)))
527 (define* (target-arm32? #:optional (target (or (%current-target-system)
529 (string-prefix? "arm" target))
531 (define* (target-aarch64? #:optional (target (or (%current-target-system)
533 (string-prefix? "aarch64" target))
535 (define* (target-arm? #:optional (target (or (%current-target-system)
537 (or (target-arm32? target) (target-aarch64? target)))
539 (define* (target-64bit? #:optional (system (or (%current-target-system)
541 (any (cut string-prefix? <> system) '("x86_64" "aarch64" "mips64" "ppc64")))
543 (define* (cc-for-target #:optional (target (%current-target-system)))
545 (string-append target "-gcc")
548 (define version-compare
550 (let ((sym (or (dynamic-func "strverscmp" (dynamic-link))
551 (error "could not find `strverscmp' (from GNU libc)"))))
552 (pointer->procedure int sym (list '* '*)))))
554 "Return '> when A denotes a newer version than B,
555 '< when A denotes a older version than B,
556 or '= when they denote equal versions."
557 (let ((result (strverscmp (string->pointer a) (string->pointer b))))
558 (cond ((positive? result) '>)
559 ((negative? result) '<)
562 (define (version-prefix version-string num-parts)
563 "Truncate version-string to the first num-parts components of the version.
564 For example, (version-prefix \"2.1.47.4.23\" 3) returns \"2.1.47\""
565 (string-join (take (string-split version-string #\.) num-parts) "."))
568 (define (version-major+minor version-string)
569 "Return \"<major>.<minor>\", where major and minor are the major and
570 minor version numbers from version-string."
571 (version-prefix version-string 2))
573 (define (version-major version-string)
574 "Return the major version number as string from the version-string."
575 (version-prefix version-string 1))
577 (define (version>? a b)
578 "Return #t when A denotes a version strictly newer than B."
579 (eq? '> (version-compare a b)))
581 (define (version>=? a b)
582 "Return #t when A denotes a version newer or equal to B."
583 (case (version-compare a b)
587 (define (guile-version>? str)
588 "Return #t if the running Guile version is greater than STR."
589 ;; Note: Using (version>? (version) "2.0.5") or similar doesn't work,
590 ;; because the result of (version) can have a prefix, like "2.0.5-deb1".
591 (version>? (string-append (major-version) "."
596 (define version-prefix?
597 (let ((not-dot (char-set-complement (char-set #\.))))
599 "Return true if V1 is a version prefix of V2:
601 (version-prefix? \"4.1\" \"4.16.2\") => #f
602 (version-prefix? \"4.1\" \"4.1.2\") => #t
604 (define (list-prefix? lst1 lst2)
611 (and (equal? head1 head2)
612 (list-prefix? tail1 tail2)))))))
614 (list-prefix? (string-tokenize v1 not-dot)
615 (string-tokenize v2 not-dot)))))
622 (define (file-extension file)
623 "Return the extension of FILE or #f if there is none."
624 (let ((dot (string-rindex file #\.)))
625 (and dot (substring file (+ 1 dot) (string-length file)))))
627 (define (file-sans-extension file)
628 "Return the substring of FILE without its extension, if any."
629 (let ((dot (string-rindex file #\.)))
631 (substring file 0 dot)
634 (define (tarball-sans-extension tarball)
635 "Return TARBALL without its .tar.* or .zip extension."
636 (let ((end (or (string-contains tarball ".tar")
637 (string-contains tarball ".zip"))))
638 (substring tarball 0 end)))
640 (define (compressed-file? file)
641 "Return true if FILE denotes a compressed file."
642 (->bool (member (file-extension file)
643 '("gz" "bz2" "xz" "lz" "lzma" "tgz" "tbz2" "zip"))))
645 (define (switch-symlinks link target)
646 "Atomically switch LINK, a symbolic link, to point to TARGET. Works
647 both when LINK already exists and when it does not."
648 (let ((pivot (string-append link ".new")))
649 (symlink target pivot)
650 (rename-file pivot link)))
652 (define* (string-replace-substring str substr replacement
655 (end (string-length str)))
656 "Replace all occurrences of SUBSTR in the START--END range of STR by
658 (match (string-length substr)
660 (error "string-replace-substring: empty substring"))
662 (let loop ((start start)
663 (pieces (list (substring str 0 start))))
664 (match (string-contains str substr start end)
666 (string-concatenate-reverse
667 (cons (substring str start) pieces)))
669 (loop (+ index substr-length)
671 (substring str start index)
674 (define (call-with-temporary-output-file proc)
675 "Call PROC with a name of a temporary file and open output port to that
676 file; close the file and delete it when leaving the dynamic extent of this
678 (let* ((directory (or (getenv "TMPDIR") "/tmp"))
679 (template (string-append directory "/guix-file.XXXXXX"))
680 (out (mkstemp! template)))
687 (false-if-exception (close out))
688 (false-if-exception (delete-file template))))))
690 (define (call-with-temporary-directory proc)
691 "Call PROC with a name of a temporary directory; close the directory and
692 delete it when leaving the dynamic extent of this call."
693 (let* ((directory (or (getenv "TMPDIR") "/tmp"))
694 (template (string-append directory "/guix-directory.XXXXXX"))
695 (tmp-dir (mkdtemp! template)))
701 (false-if-exception (delete-file-recursively tmp-dir))))))
703 (define (with-atomic-file-output file proc)
704 "Call PROC with an output port for the file that is going to replace FILE.
705 Upon success, FILE is atomically replaced by what has been written to the
706 output port, and PROC's result is returned."
707 (let* ((template (string-append file ".XXXXXX"))
708 (out (mkstemp! template)))
709 (with-throw-handler #t
711 (let ((result (proc out)))
714 (rename-file template file)
717 (false-if-exception (delete-file template))
720 (define* (xdg-directory variable suffix #:key (ensure? #t))
721 "Return the name of the XDG directory that matches VARIABLE and SUFFIX,
722 after making sure that it exists if ENSURE? is true. VARIABLE is an
723 environment variable name like \"XDG_CONFIG_HOME\"; SUFFIX is a suffix like
724 \"/.config\". Honor the XDG specs,
725 <http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html>."
726 (let ((dir (and=> (or (getenv variable)
727 (and=> (or (getenv "HOME")
728 (passwd:dir (getpwuid (getuid))))
729 (cut string-append <> suffix)))
730 (cut string-append <> "/guix"))))
735 (define config-directory
736 (cut xdg-directory "XDG_CONFIG_HOME" "/.config" <...>))
738 (define cache-directory
739 (cut xdg-directory "XDG_CACHE_HOME" "/.cache" <...>))
741 (define (readlink* file)
742 "Call 'readlink' until the result is not a symlink."
743 (define %max-symlink-depth 50)
745 (let loop ((file file)
747 (define (absolute target)
748 (if (absolute-file-name? target)
750 (string-append (dirname file) "/" target)))
752 (if (>= depth %max-symlink-depth)
758 (values #t (readlink file)))
760 (let ((errno (system-error-errno args)))
761 (if (or (= errno EINVAL))
763 (apply throw args))))))
764 (lambda (success? target)
766 (loop (absolute target) (+ depth 1))
769 (define (canonical-newline-port port)
770 "Return an input port that wraps PORT such that all newlines consist
771 of a single linefeed."
772 (define (get-position)
773 (if (port-has-port-position? port) (port-position port) #f))
774 (define (set-position! position)
775 (if (port-has-set-port-position!? port)
776 (set-port-position! position port)
778 (define (close) (close-port port))
779 (define (read! bv start n)
781 (byte (get-u8 port)))
782 (cond ((eof-object? byte) count)
783 ;; XXX: consume all CRs even if not followed by LF.
784 ((eqv? byte (char->integer #\return)) (loop count (get-u8 port)))
786 (bytevector-u8-set! bv (+ start count) byte)
789 (bytevector-u8-set! bv (+ start count) byte)
790 (loop (+ count 1) (get-u8 port))))))
791 (make-custom-binary-input-port "canonical-newline-port"
801 (define absolute-dirname
802 ;; Memoize to avoid repeated 'stat' storms from 'search-path'.
804 "Return the absolute name of the directory containing FILE, or #f upon
806 (match (search-path %load-path file)
809 ;; If there are relative names in %LOAD-PATH, FILE can be relative and
810 ;; needs to be canonicalized.
811 (if (string-prefix? "/" file)
813 (canonicalize-path (dirname file)))))))
815 (define-syntax current-source-directory
817 "Return the absolute name of the current directory, or #f if it could not
821 (match (assq 'filename (or (syntax-source s) '()))
822 (('filename . (? string? file-name))
823 ;; If %FILE-PORT-NAME-CANONICALIZATION is 'relative, then FILE-NAME
824 ;; can be relative. In that case, we try to find out at run time
825 ;; the absolute file name by looking at %LOAD-PATH; doing this at
826 ;; run time rather than expansion time is necessary to allow files
827 ;; to be moved on the file system.
828 (if (string-prefix? "/" file-name)
830 #`(absolute-dirname #,file-name)))
831 ((or ('filename . #f) #f)
832 ;; raising an error would upset Geiser users
836 ;;; eval: (put 'call-with-progress-reporter 'scheme-indent-function 1)