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>
9 ;;; Copyright © 2017 Mathieu Othacehe <m.othacehe@gmail.com>
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-35)
33 #:use-module (srfi srfi-39)
34 #:use-module (ice-9 binary-ports)
35 #:autoload (rnrs io ports) (make-custom-binary-input-port)
36 #:use-module ((rnrs bytevectors) #:select (bytevector-u8-set!))
37 #:use-module (guix memoization)
38 #:use-module ((guix build utils) #:select (dump-port mkdir-p))
39 #:use-module ((guix build syscalls) #:select (mkdtemp! fdatasync))
40 #:use-module (ice-9 format)
41 #:autoload (ice-9 popen) (open-pipe*)
42 #:autoload (ice-9 rdelim) (read-line)
43 #:use-module (ice-9 regex)
44 #:use-module (ice-9 match)
45 #:use-module (ice-9 format)
46 #:use-module ((ice-9 iconv) #:prefix iconv:)
47 #:use-module (system foreign)
48 #:re-export (memoize) ; for backwards compatibility
49 #:export (strip-keyword-arguments
50 default-keyword-arguments
51 substitute-keyword-arguments
52 ensure-keyword-arguments
54 current-source-directory
62 source-properties->location
63 location->source-properties
73 nix-system->gnu-triplet
74 gnu-triplet->nix-system
76 %current-target-system
77 package-name->name+version
87 string-replace-substring
88 arguments-from-environment-variable
93 call-with-temporary-output-file
94 call-with-temporary-directory
95 with-atomic-file-output
106 call-with-decompressed-port
107 compressed-output-port
108 call-with-compressed-output-port
109 canonical-newline-port))
113 ;;; Filtering & pipes.
116 (define (filtered-port command input)
117 "Return an input port where data drained from INPUT is filtered through
118 COMMAND (a list). In addition, return a list of PIDs that the caller must
119 wait. When INPUT is a file port, it must be unbuffered; otherwise, any
120 buffered data is lost."
121 (let loop ((input input)
123 (if (file-port? input)
126 (match (primitive-fork)
132 (close-port (current-input-port))
133 (dup2 (fileno input) 0)
134 (close-port (current-output-port))
135 (dup2 (fileno out) 1)
138 (apply execl (car command) command))
140 (format (current-error-port)
141 "filtered-port: failed to execute '~{~a ~}': ~a~%"
142 command (strerror (system-error-errno args))))))
144 (primitive-_exit 1))))
147 (values in (cons child pids))))))
149 ;; INPUT is not a file port, so fork just for the sake of tunneling it
150 ;; through a file port.
153 (match (primitive-fork)
159 (dump-port input out))
162 (false-if-exception (close out))
163 (primitive-_exit 0))))
167 (loop in (cons child pids)))))))))
169 (define (decompressed-port compression input)
170 "Return an input port where INPUT is decompressed according to COMPRESSION,
171 a symbol such as 'xz."
173 ((or #f 'none) (values input '()))
174 ('bzip2 (filtered-port `(,%bzip2 "-dc") input))
175 ('xz (filtered-port `(,%xz "-dc" "-T0") input))
176 ('gzip (filtered-port `(,%gzip "-dc") input))
177 (else (error "unsupported compression scheme" compression))))
179 (define (compressed-port compression input)
180 "Return an input port where INPUT is decompressed according to COMPRESSION,
181 a symbol such as 'xz."
183 ((or #f 'none) (values input '()))
184 ('bzip2 (filtered-port `(,%bzip2 "-c") input))
185 ('xz (filtered-port `(,%xz "-c" "-T0") input))
186 ('gzip (filtered-port `(,%gzip "-c") input))
187 (else (error "unsupported compression scheme" compression))))
189 (define (call-with-decompressed-port compression port proc)
190 "Call PROC with a wrapper around PORT, a file port, that decompresses data
191 read from PORT according to COMPRESSION, a symbol such as 'xz."
192 (let-values (((decompressed pids)
193 (decompressed-port compression port)))
199 (close-port decompressed)
200 (unless (every (compose zero? cdr waitpid) pids)
201 (error "decompressed-port failure" pids))))))
203 (define (filtered-output-port command output)
204 "Return an output port. Data written to that port is filtered through
205 COMMAND and written to OUTPUT, an output file port. In addition, return a
206 list of PIDs to wait for. OUTPUT must be unbuffered; otherwise, any buffered
210 (match (primitive-fork)
216 (close-port (current-input-port))
218 (close-port (current-output-port))
219 (dup2 (fileno output) 1)
222 (apply execl (car command) command))
224 (format (current-error-port)
225 "filtered-output-port: failed to execute '~{~a ~}': ~a~%"
226 command (strerror (system-error-errno args))))))
228 (primitive-_exit 1))))
231 (values out (list child)))))))
233 (define* (compressed-output-port compression output
235 "Return an output port whose input is compressed according to COMPRESSION,
236 a symbol such as 'xz, and then written to OUTPUT. In addition return a list
237 of PIDs to wait for. OPTIONS is a list of strings passed to the compression
238 program--e.g., '(\"--fast\")."
240 ((or #f 'none) (values output '()))
241 ('bzip2 (filtered-output-port `(,%bzip2 "-c" ,@options) output))
242 ('xz (filtered-output-port `(,%xz "-c" "-T0" ,@options) output))
243 ('gzip (filtered-output-port `(,%gzip "-c" ,@options) output))
244 (else (error "unsupported compression scheme" compression))))
246 (define* (call-with-compressed-output-port compression port proc
248 "Call PROC with a wrapper around PORT, a file port, that compresses data
249 that goes to PORT according to COMPRESSION, a symbol such as 'xz. OPTIONS is
250 a list of command-line arguments passed to the compression program."
251 (let-values (((compressed pids)
252 (compressed-output-port compression port
259 (close-port compressed)
260 (unless (every (compose zero? cdr waitpid) pids)
261 (error "compressed-output-port failure" pids))))))
263 (define* (edit-expression source-properties proc #:key (encoding "UTF-8"))
264 "Edit the expression specified by SOURCE-PROPERTIES using PROC, which should
265 be a procedure that takes the original expression in string and returns a new
266 one. ENCODING will be used to interpret all port I/O, it default to UTF-8.
267 This procedure returns #t on success."
268 (with-fluids ((%default-port-encoding encoding))
269 (let* ((file (assq-ref source-properties 'filename))
270 (line (assq-ref source-properties 'line))
271 (column (assq-ref source-properties 'column))
272 (in (open-input-file file))
273 ;; The start byte position of the expression.
274 (start (begin (while (not (and (= line (port-line in))
275 (= column (port-column in))))
276 (when (eof-object? (read-char in))
277 (error (format #f "~a: end of file~%" in))))
279 ;; The end byte position of the expression.
280 (end (begin (read in) (ftell in))))
281 (seek in 0 SEEK_SET) ; read from the beginning of the file.
282 (let* ((pre-bv (get-bytevector-n in start))
283 ;; The expression in string form.
284 (str (iconv:bytevector->string
285 (get-bytevector-n in (- end start))
287 (post-bv (get-bytevector-all in))
289 ;; Verify the edited expression is still a scheme expression.
290 (call-with-input-string str* read)
291 ;; Update the file with edited expression.
292 (with-atomic-file-output file
294 (put-bytevector out pre-bv)
296 ;; post-bv maybe the end-of-file object.
297 (when (not (eof-object? post-bv))
298 (put-bytevector out post-bv))
303 ;;; Keyword arguments.
306 (define (strip-keyword-arguments keywords args)
307 "Remove all of the keyword arguments listed in KEYWORDS from ARGS."
308 (let loop ((args args)
313 (((? keyword? kw) arg . rest)
315 (if (memq kw keywords)
317 (cons* arg kw result))))
319 (loop tail (cons head result))))))
321 (define (default-keyword-arguments args defaults)
322 "Return ARGS augmented with any keyword/value from DEFAULTS for
323 keywords not already present in ARGS."
324 (let loop ((defaults defaults)
331 (cons* kw value args))))
335 (define-syntax collect-default-args
340 (collect-default-args rest ...))
341 ((_ (kw _ dflt) rest ...)
342 (cons* kw dflt (collect-default-args rest ...)))))
344 (define-syntax substitute-keyword-arguments
346 "Return a new list of arguments where the value for keyword arg KW is
347 replaced by EXP. EXP is evaluated in a context where VAR is bound to the
348 previous value of the keyword argument, or DFLT if given."
349 ((_ original-args ((kw var dflt ...) exp) ...)
350 (let loop ((args (default-keyword-arguments
352 (collect-default-args (kw var dflt ...) ...)))
355 ((kw var rest (... ...))
356 (loop rest (cons* exp kw before)))
359 (loop rest (cons x before)))
361 (reverse before)))))))
363 (define (delkw kw lst)
364 "Remove KW and its associated value from LST, a keyword/value list such
365 as '(#:foo 1 #:bar 2)."
371 ((kw? value rest ...)
373 (append (reverse result) rest)
374 (loop rest (cons* value kw? result)))))))
376 (define (ensure-keyword-arguments args kw/values)
377 "Force the keywords arguments KW/VALUES in the keyword argument list ARGS.
380 (ensure-keyword-arguments '(#:foo 2) '(#:foo 2))
383 (ensure-keyword-arguments '(#:foo 2) '(#:bar 3))
386 (ensure-keyword-arguments '(#:foo 2) '(#:bar 3 #:foo 42))
387 => (#:foo 42 #:bar 3)
389 (let loop ((args args)
390 (kw/values kw/values)
394 (append (reverse result) kw/values))
396 (match (memq kw kw/values)
398 (loop rest (delkw kw kw/values) (cons* value kw result)))
400 (loop rest kw/values (cons* value kw result))))))))
407 (define* (nix-system->gnu-triplet
408 #:optional (system (%current-system)) (vendor "unknown"))
409 "Return a guess of the GNU triplet corresponding to Nix system
413 (string-append "arm-" vendor "-linux-gnueabihf"))
415 (let* ((dash (string-index system #\-))
416 (arch (substring system 0 dash))
417 (os (substring system (+ 1 dash))))
420 (if (string=? os "linux")
424 (define (gnu-triplet->nix-system triplet)
425 "Return the Nix system type corresponding to TRIPLET, a GNU triplet as
426 returned by `config.guess'."
427 (let ((triplet (cond ((string-match "^i[345]86-(.*)$" triplet)
430 (string-append "i686-" (match:substring m 1))))
432 (cond ((string-match "^arm[^-]*-([^-]+-)?linux-gnueabihf" triplet)
434 ((string-match "^([^-]+)-([^-]+-)?linux-gnu.*" triplet)
437 ;; Nix omits `-gnu' for GNU/Linux.
438 (string-append (match:substring m 1) "-linux")))
439 ((string-match "^([^-]+)-([^-]+-)?([[:alpha:]]+)([0-9]+\\.?)*$" triplet)
442 ;; Nix strip the version number from names such as `gnu0.3',
443 ;; `darwin10.2.0', etc., and always strips the vendor part.
444 (string-append (match:substring m 1) "-"
445 (match:substring m 3))))
448 (define %current-system
449 ;; System type as expected by Nix, usually ARCHITECTURE-KERNEL.
450 ;; By default, this is equal to (gnu-triplet->nix-system %host-type).
451 (make-parameter %system))
453 (define %current-target-system
454 ;; Either #f or a GNU triplet representing the target system we are
455 ;; cross-building to.
458 (define* (package-name->name+version spec
459 #:optional (delimiter #\@))
460 "Given SPEC, a package name like \"foo@0.9.1b\", return two values: \"foo\"
461 and \"0.9.1b\". When the version part is unavailable, SPEC and #f are
462 returned. Both parts must not contain any '@'. Optionally, DELIMITER can be
463 a character other than '@'."
464 (match (string-rindex spec delimiter)
465 (#f (values spec #f))
466 (idx (values (substring spec 0 idx)
467 (substring spec (1+ idx))))))
469 (define* (target-mingw? #:optional (target (%current-target-system)))
471 (string-suffix? "-mingw32" target)))
473 (define (target-arm32?)
474 (string-prefix? "arm" (or (%current-target-system) (%current-system))))
476 (define version-compare
478 (let ((sym (or (dynamic-func "strverscmp" (dynamic-link))
479 (error "could not find `strverscmp' (from GNU libc)"))))
480 (pointer->procedure int sym (list '* '*)))))
482 "Return '> when A denotes a newer version than B,
483 '< when A denotes a older version than B,
484 or '= when they denote equal versions."
485 (let ((result (strverscmp (string->pointer a) (string->pointer b))))
486 (cond ((positive? result) '>)
487 ((negative? result) '<)
490 (define (version-prefix version-string num-parts)
491 "Truncate version-string to the first num-parts components of the version.
492 For example, (version-prefix \"2.1.47.4.23\" 3) returns \"2.1.47\""
493 (string-join (take (string-split version-string #\.) num-parts) "."))
496 (define (version-major+minor version-string)
497 "Return \"<major>.<minor>\", where major and minor are the major and
498 minor version numbers from version-string."
499 (version-prefix version-string 2))
501 (define (version-major version-string)
502 "Return the major version number as string from the version-string."
503 (version-prefix version-string 1))
505 (define (version>? a b)
506 "Return #t when A denotes a version strictly newer than B."
507 (eq? '> (version-compare a b)))
509 (define (version>=? a b)
510 "Return #t when A denotes a version newer or equal to B."
511 (case (version-compare a b)
515 (define (guile-version>? str)
516 "Return #t if the running Guile version is greater than STR."
517 ;; Note: Using (version>? (version) "2.0.5") or similar doesn't work,
518 ;; because the result of (version) can have a prefix, like "2.0.5-deb1".
519 (version>? (string-append (major-version) "."
524 (define (file-extension file)
525 "Return the extension of FILE or #f if there is none."
526 (let ((dot (string-rindex file #\.)))
527 (and dot (substring file (+ 1 dot) (string-length file)))))
529 (define (file-sans-extension file)
530 "Return the substring of FILE without its extension, if any."
531 (let ((dot (string-rindex file #\.)))
533 (substring file 0 dot)
536 (define (compressed-file? file)
537 "Return true if FILE denotes a compressed file."
538 (->bool (member (file-extension file)
539 '("gz" "bz2" "xz" "lz" "lzma" "tgz" "tbz2" "zip"))))
541 (define (switch-symlinks link target)
542 "Atomically switch LINK, a symbolic link, to point to TARGET. Works
543 both when LINK already exists and when it does not."
544 (let ((pivot (string-append link ".new")))
545 (symlink target pivot)
546 (rename-file pivot link)))
548 (define* (string-replace-substring str substr replacement
551 (end (string-length str)))
552 "Replace all occurrences of SUBSTR in the START--END range of STR by
554 (match (string-length substr)
556 (error "string-replace-substring: empty substring"))
558 (let loop ((start start)
559 (pieces (list (substring str 0 start))))
560 (match (string-contains str substr start end)
562 (string-concatenate-reverse
563 (cons (substring str start) pieces)))
565 (loop (+ index substr-length)
567 (substring str start index)
570 (define (arguments-from-environment-variable variable)
571 "Retrieve value of environment variable denoted by string VARIABLE in the
572 form of a list of strings (`char-set:graphic' tokens) suitable for consumption
573 by `args-fold', if VARIABLE is defined, otherwise return an empty list."
574 (let ((env (getenv variable)))
576 (string-tokenize env char-set:graphic)
579 (define (call-with-temporary-output-file proc)
580 "Call PROC with a name of a temporary file and open output port to that
581 file; close the file and delete it when leaving the dynamic extent of this
583 (let* ((directory (or (getenv "TMPDIR") "/tmp"))
584 (template (string-append directory "/guix-file.XXXXXX"))
585 (out (mkstemp! template)))
592 (false-if-exception (close out))
593 (false-if-exception (delete-file template))))))
595 (define (call-with-temporary-directory proc)
596 "Call PROC with a name of a temporary directory; close the directory and
597 delete it when leaving the dynamic extent of this call."
598 (let* ((directory (or (getenv "TMPDIR") "/tmp"))
599 (template (string-append directory "/guix-directory.XXXXXX"))
600 (tmp-dir (mkdtemp! template)))
606 (false-if-exception (rmdir tmp-dir))))))
608 (define (with-atomic-file-output file proc)
609 "Call PROC with an output port for the file that is going to replace FILE.
610 Upon success, FILE is atomically replaced by what has been written to the
611 output port, and PROC's result is returned."
612 (let* ((template (string-append file ".XXXXXX"))
613 (out (mkstemp! template)))
614 (with-throw-handler #t
616 (let ((result (proc out)))
619 (rename-file template file)
622 (false-if-exception (delete-file template))
625 (define* (xdg-directory variable suffix #:key (ensure? #t))
626 "Return the name of the XDG directory that matches VARIABLE and SUFFIX,
627 after making sure that it exists if ENSURE? is true. VARIABLE is an
628 environment variable name like \"XDG_CONFIG_HOME\"; SUFFIX is a suffix like
629 \"/.config\". Honor the XDG specs,
630 <http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html>."
631 (let ((dir (and=> (or (getenv variable)
632 (and=> (or (getenv "HOME")
633 (passwd:dir (getpwuid (getuid))))
634 (cut string-append <> suffix)))
635 (cut string-append <> "/guix"))))
640 (define config-directory
641 (cut xdg-directory "XDG_CONFIG_HOME" "/.config" <...>))
643 (define cache-directory
644 (cut xdg-directory "XDG_CACHE_HOME" "/.cache" <...>))
646 (define (readlink* file)
647 "Call 'readlink' until the result is not a symlink."
648 (define %max-symlink-depth 50)
650 (let loop ((file file)
652 (define (absolute target)
653 (if (absolute-file-name? target)
655 (string-append (dirname file) "/" target)))
657 (if (>= depth %max-symlink-depth)
663 (values #t (readlink file)))
665 (let ((errno (system-error-errno args)))
666 (if (or (= errno EINVAL))
668 (apply throw args))))))
669 (lambda (success? target)
671 (loop (absolute target) (+ depth 1))
674 (define (canonical-newline-port port)
675 "Return an input port that wraps PORT such that all newlines consist
676 of a single carriage return."
677 (define (get-position)
678 (if (port-has-port-position? port) (port-position port) #f))
679 (define (set-position! position)
680 (if (port-has-set-port-position!? port)
681 (set-port-position! position port)
683 (define (close) (close-port port))
684 (define (read! bv start n)
686 (byte (get-u8 port)))
687 (cond ((eof-object? byte) count)
689 (bytevector-u8-set! bv (+ start count) byte)
691 ;; XXX: consume all LFs even if not followed by CR.
692 ((eqv? byte (char->integer #\return)) (loop count (get-u8 port)))
694 (bytevector-u8-set! bv (+ start count) byte)
695 (loop (+ count 1) (get-u8 port))))))
696 (make-custom-binary-input-port "canonical-newline-port"
706 (define (absolute-dirname file)
707 "Return the absolute name of the directory containing FILE, or #f upon
709 (match (search-path %load-path file)
712 ;; If there are relative names in %LOAD-PATH, FILE can be relative and
713 ;; needs to be canonicalized.
714 (if (string-prefix? "/" file)
716 (canonicalize-path (dirname file))))))
718 (define-syntax current-source-directory
720 "Return the absolute name of the current directory, or #f if it could not
724 (match (assq 'filename (or (syntax-source s) '()))
725 (('filename . (? string? file-name))
726 ;; If %FILE-PORT-NAME-CANONICALIZATION is 'relative, then FILE-NAME
727 ;; can be relative. In that case, we try to find out at run time
728 ;; the absolute file name by looking at %LOAD-PATH; doing this at
729 ;; run time rather than expansion time is necessary to allow files
730 ;; to be moved on the file system.
731 (cond ((not file-name)
732 #f) ;raising an error would upset Geiser users
733 ((string-prefix? "/" file-name)
736 #`(absolute-dirname #,file-name))))
740 ;; A source location.
741 (define-record-type <location>
742 (make-location file line column)
744 (file location-file) ; file name
745 (line location-line) ; 1-indexed line
746 (column location-column)) ; 0-indexed column
749 (mlambda (file line column)
750 "Return the <location> object for the given FILE, LINE, and COLUMN."
751 (and line column file
752 (make-location file line column))))
754 (define (source-properties->location loc)
755 "Return a location object based on the info in LOC, an alist as returned
756 by Guile's `source-properties', `frame-source', `current-source-location',
758 (let ((file (assq-ref loc 'filename))
759 (line (assq-ref loc 'line))
760 (col (assq-ref loc 'column)))
761 ;; In accordance with the GCS, start line and column numbers at 1. Note
762 ;; that unlike LINE and `port-column', COL is actually 1-indexed here...
763 (location file (and line (+ line 1)) col)))
765 (define (location->source-properties loc)
766 "Return the source property association list based on the info in LOC,
768 `((line . ,(and=> (location-line loc) 1-))
769 (column . ,(location-column loc))
770 (filename . ,(location-file loc))))
772 (define-condition-type &error-location &error
774 (location error-location)) ;<location>
776 (define-condition-type &fix-hint &condition
778 (hint condition-fix-hint)) ;string
781 ;;; eval: (put 'call-with-progress-reporter 'scheme-indent-function 1)