gexp: Add 'let-system'.
[jackhill/guix/guix.git] / guix / utils.scm
CommitLineData
233e7676 1;;; GNU Guix --- Functional package management for GNU
6a7c4636 2;;; Copyright © 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Ludovic Courtès <ludo@gnu.org>
3f00ff8b 3;;; Copyright © 2013, 2014, 2015 Mark H Weaver <mhw@netris.org>
516e3b6f 4;;; Copyright © 2014 Eric Bavier <bavier@member.fsf.org>
29a7c98a 5;;; Copyright © 2014 Ian Denhardt <ian@zenhack.net>
1b846da8 6;;; Copyright © 2016 Mathieu Lirzin <mthl@gnu.org>
bbd00d20 7;;; Copyright © 2015 David Thompson <davet@gnu.org>
e45b573c 8;;; Copyright © 2017 Mathieu Othacehe <m.othacehe@gmail.com>
259341cf 9;;; Copyright © 2018 Marius Bakke <mbakke@fastmail.com>
e3deeebb 10;;;
233e7676 11;;; This file is part of GNU Guix.
e3deeebb 12;;;
233e7676 13;;; GNU Guix is free software; you can redistribute it and/or modify it
e3deeebb
LC
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.
17;;;
233e7676 18;;; GNU Guix is distributed in the hope that it will be useful, but
e3deeebb
LC
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.
22;;;
23;;; You should have received a copy of the GNU General Public License
233e7676 24;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
e3deeebb
LC
25
26(define-module (guix utils)
00e219d1 27 #:use-module (guix config)
38b3122a 28 #:use-module (srfi srfi-1)
72d86963 29 #:use-module (srfi srfi-9)
01ac19dc 30 #:use-module (srfi srfi-11)
38b3122a 31 #:use-module (srfi srfi-26)
23735137 32 #:use-module (srfi srfi-35)
de4c3f26 33 #:use-module (srfi srfi-39)
27f7cbc9 34 #:use-module (ice-9 ftw)
6a7c4636 35 #:use-module (rnrs io ports) ;need 'port-position' etc.
c8be6f0d 36 #:use-module ((rnrs bytevectors) #:select (bytevector-u8-set!))
f9704f17 37 #:use-module (guix memoization)
27f7cbc9 38 #:use-module ((guix build utils) #:select (dump-port mkdir-p delete-file-recursively))
1752a17a 39 #:use-module ((guix build syscalls) #:select (mkdtemp! fdatasync))
38b3122a 40 #:use-module (ice-9 format)
98090557 41 #:use-module (ice-9 regex)
72d86963 42 #:use-module (ice-9 match)
8ef3401f 43 #:use-module (ice-9 format)
31044751 44 #:use-module ((ice-9 iconv) #:prefix iconv:)
2cd5c038 45 #:use-module (system foreign)
19e1d5f7 46 #:re-export (memoize) ; for backwards compatibility
4c0c4db0 47 #:export (strip-keyword-arguments
0af2c24e
LC
48 default-keyword-arguments
49 substitute-keyword-arguments
6071122b 50 ensure-keyword-arguments
ff352cfb 51
07c8a98c
LC
52 current-source-directory
53
64fc89b6 54 <location>
ff352cfb
LC
55 location
56 location?
57 location-file
58 location-line
59 location-column
60 source-properties->location
f7df1e3e 61 location->source-properties
ff352cfb 62
23735137
LC
63 &error-location
64 error-location?
65 error-location
66
67 &fix-hint
68 fix-hint?
69 condition-fix-hint
70
8eb80484 71 nix-system->gnu-triplet
98090557 72 gnu-triplet->nix-system
9b48fb88 73 %current-system
9c1edabd 74 %current-target-system
1b846da8 75 package-name->name+version
cba36e64 76 target-mingw?
e45b573c 77 target-arm32?
74f17180
MO
78 target-aarch64?
79 target-arm?
259341cf 80 target-64bit?
0d1e6ce4
MW
81 version-compare
82 version>?
cde1e967 83 version>=?
29a7c98a
ID
84 version-prefix
85 version-major+minor
47dc9a0d 86 version-major
7db3ff4a 87 guile-version>?
437f62f0 88 version-prefix?
56b943de 89 string-replace-substring
16eb115e 90 arguments-from-environment-variable
0fdd3bea 91 file-extension
ac10e0e1 92 file-sans-extension
da1027a7 93 tarball-sans-extension
089b1678 94 compressed-file?
3bb168b0 95 switch-symlinks
861693f3 96 call-with-temporary-output-file
db6e5e2b 97 call-with-temporary-directory
04d4c8a4 98 with-atomic-file-output
f0e492f0
LC
99
100 config-directory
739ab68b 101 cache-directory
f0e492f0 102
d50cb56d 103 readlink*
50a3d594 104 edit-expression
7a8024a3
LC
105
106 filtered-port
107 compressed-port
80dea563 108 decompressed-port
01ac19dc
LC
109 call-with-decompressed-port
110 compressed-output-port
c8be6f0d 111 call-with-compressed-output-port
8c348825 112 canonical-newline-port))
e3deeebb 113
38b3122a 114\f
e0fbbc88
LC
115;;;
116;;; Filtering & pipes.
117;;;
118
119(define (filtered-port command input)
120 "Return an input port where data drained from INPUT is filtered through
121COMMAND (a list). In addition, return a list of PIDs that the caller must
101d9f3f
LC
122wait. When INPUT is a file port, it must be unbuffered; otherwise, any
123buffered data is lost."
e0fbbc88 124 (let loop ((input input)
443eb4e9 125 (pids '()))
e0fbbc88
LC
126 (if (file-port? input)
127 (match (pipe)
128 ((in . out)
129 (match (primitive-fork)
130 (0
443eb4e9
LC
131 (dynamic-wind
132 (const #f)
133 (lambda ()
134 (close-port in)
135 (close-port (current-input-port))
136 (dup2 (fileno input) 0)
137 (close-port (current-output-port))
138 (dup2 (fileno out) 1)
139 (catch 'system-error
140 (lambda ()
141 (apply execl (car command) command))
142 (lambda args
143 (format (current-error-port)
144 "filtered-port: failed to execute '~{~a ~}': ~a~%"
145 command (strerror (system-error-errno args))))))
146 (lambda ()
147 (primitive-_exit 1))))
e0fbbc88
LC
148 (child
149 (close-port out)
150 (values in (cons child pids))))))
151
152 ;; INPUT is not a file port, so fork just for the sake of tunneling it
153 ;; through a file port.
154 (match (pipe)
155 ((in . out)
156 (match (primitive-fork)
157 (0
158 (dynamic-wind
159 (const #t)
160 (lambda ()
161 (close-port in)
162 (dump-port input out))
163 (lambda ()
5efa0e4d 164 (close-port input)
e0fbbc88 165 (false-if-exception (close out))
443eb4e9 166 (primitive-_exit 0))))
e0fbbc88 167 (child
5efa0e4d 168 (close-port input)
e0fbbc88
LC
169 (close-port out)
170 (loop in (cons child pids)))))))))
171
4e48923e
LC
172(define (lzip-port proc port . args)
173 "Return the lzip port produced by calling PROC (a symbol) on PORT and ARGS.
174Raise an error if lzlib support is missing."
175 (let* ((lzlib (false-if-exception (resolve-interface '(guix lzlib))))
176 (supported? (and lzlib
177 ((module-ref lzlib 'lzlib-available?)))))
178 (if supported?
179 (let ((make-port (module-ref lzlib proc)))
180 (values (make-port port) '()))
181 (error "lzip compression not supported" lzlib))))
182
7a8024a3
LC
183(define (decompressed-port compression input)
184 "Return an input port where INPUT is decompressed according to COMPRESSION,
185a symbol such as 'xz."
186 (match compression
187 ((or #f 'none) (values input '()))
188 ('bzip2 (filtered-port `(,%bzip2 "-dc") input))
e9be2c54 189 ('xz (filtered-port `(,%xz "-dc") input))
7a8024a3 190 ('gzip (filtered-port `(,%gzip "-dc") input))
4e48923e
LC
191 ('lzip (values (lzip-port 'make-lzip-input-port input)
192 '()))
193 (_ (error "unsupported compression scheme" compression))))
7a8024a3
LC
194
195(define (compressed-port compression input)
4e48923e 196 "Return an input port where INPUT is compressed according to COMPRESSION,
7a8024a3
LC
197a symbol such as 'xz."
198 (match compression
199 ((or #f 'none) (values input '()))
200 ('bzip2 (filtered-port `(,%bzip2 "-c") input))
e9be2c54 201 ('xz (filtered-port `(,%xz "-c") input))
7a8024a3 202 ('gzip (filtered-port `(,%gzip "-c") input))
4e48923e
LC
203 ('lzip (values (lzip-port 'make-lzip-input-port/compressed input)
204 '()))
205 (_ (error "unsupported compression scheme" compression))))
7a8024a3 206
01ac19dc
LC
207(define (call-with-decompressed-port compression port proc)
208 "Call PROC with a wrapper around PORT, a file port, that decompresses data
30ce8012 209read from PORT according to COMPRESSION, a symbol such as 'xz."
01ac19dc
LC
210 (let-values (((decompressed pids)
211 (decompressed-port compression port)))
212 (dynamic-wind
213 (const #f)
214 (lambda ()
01ac19dc
LC
215 (proc decompressed))
216 (lambda ()
217 (close-port decompressed)
218 (unless (every (compose zero? cdr waitpid) pids)
219 (error "decompressed-port failure" pids))))))
220
80dea563
LC
221(define (filtered-output-port command output)
222 "Return an output port. Data written to that port is filtered through
223COMMAND and written to OUTPUT, an output file port. In addition, return a
224list of PIDs to wait for. OUTPUT must be unbuffered; otherwise, any buffered
225data is lost."
226 (match (pipe)
227 ((in . out)
228 (match (primitive-fork)
229 (0
230 (dynamic-wind
231 (const #f)
232 (lambda ()
233 (close-port out)
234 (close-port (current-input-port))
235 (dup2 (fileno in) 0)
236 (close-port (current-output-port))
237 (dup2 (fileno output) 1)
238 (catch 'system-error
239 (lambda ()
240 (apply execl (car command) command))
241 (lambda args
242 (format (current-error-port)
243 "filtered-output-port: failed to execute '~{~a ~}': ~a~%"
244 command (strerror (system-error-errno args))))))
245 (lambda ()
246 (primitive-_exit 1))))
247 (child
248 (close-port in)
249 (values out (list child)))))))
250
62d2b571
LC
251(define* (compressed-output-port compression output
252 #:key (options '()))
80dea563
LC
253 "Return an output port whose input is compressed according to COMPRESSION,
254a symbol such as 'xz, and then written to OUTPUT. In addition return a list
62d2b571
LC
255of PIDs to wait for. OPTIONS is a list of strings passed to the compression
256program--e.g., '(\"--fast\")."
80dea563
LC
257 (match compression
258 ((or #f 'none) (values output '()))
62d2b571 259 ('bzip2 (filtered-output-port `(,%bzip2 "-c" ,@options) output))
e9be2c54 260 ('xz (filtered-output-port `(,%xz "-c" ,@options) output))
62d2b571 261 ('gzip (filtered-output-port `(,%gzip "-c" ,@options) output))
4e48923e
LC
262 ('lzip (values (lzip-port 'make-lzip-output-port output)
263 '()))
264 (_ (error "unsupported compression scheme" compression))))
80dea563 265
62d2b571
LC
266(define* (call-with-compressed-output-port compression port proc
267 #:key (options '()))
01ac19dc 268 "Call PROC with a wrapper around PORT, a file port, that compresses data
62d2b571
LC
269that goes to PORT according to COMPRESSION, a symbol such as 'xz. OPTIONS is
270a list of command-line arguments passed to the compression program."
01ac19dc 271 (let-values (((compressed pids)
62d2b571
LC
272 (compressed-output-port compression port
273 #:options options)))
01ac19dc
LC
274 (dynamic-wind
275 (const #f)
276 (lambda ()
01ac19dc
LC
277 (proc compressed))
278 (lambda ()
279 (close-port compressed)
280 (unless (every (compose zero? cdr waitpid) pids)
281 (error "compressed-output-port failure" pids))))))
282
50a3d594
SB
283(define* (edit-expression source-properties proc #:key (encoding "UTF-8"))
284 "Edit the expression specified by SOURCE-PROPERTIES using PROC, which should
285be a procedure that takes the original expression in string and returns a new
286one. ENCODING will be used to interpret all port I/O, it default to UTF-8.
287This procedure returns #t on success."
288 (with-fluids ((%default-port-encoding encoding))
289 (let* ((file (assq-ref source-properties 'filename))
290 (line (assq-ref source-properties 'line))
291 (column (assq-ref source-properties 'column))
292 (in (open-input-file file))
293 ;; The start byte position of the expression.
294 (start (begin (while (not (and (= line (port-line in))
295 (= column (port-column in))))
296 (when (eof-object? (read-char in))
297 (error (format #f "~a: end of file~%" in))))
298 (ftell in)))
299 ;; The end byte position of the expression.
300 (end (begin (read in) (ftell in))))
301 (seek in 0 SEEK_SET) ; read from the beginning of the file.
302 (let* ((pre-bv (get-bytevector-n in start))
303 ;; The expression in string form.
31044751 304 (str (iconv:bytevector->string
50a3d594
SB
305 (get-bytevector-n in (- end start))
306 (port-encoding in)))
307 (post-bv (get-bytevector-all in))
308 (str* (proc str)))
309 ;; Verify the edited expression is still a scheme expression.
310 (call-with-input-string str* read)
311 ;; Update the file with edited expression.
312 (with-atomic-file-output file
313 (lambda (out)
314 (put-bytevector out pre-bv)
315 (display str* out)
316 ;; post-bv maybe the end-of-file object.
317 (when (not (eof-object? post-bv))
318 (put-bytevector out post-bv))
319 #t))))))
320
e0fbbc88 321\f
de4c3f26 322;;;
958dd3ce 323;;; Keyword arguments.
de4c3f26
LC
324;;;
325
5e110382
LC
326(define (strip-keyword-arguments keywords args)
327 "Remove all of the keyword arguments listed in KEYWORDS from ARGS."
328 (let loop ((args args)
329 (result '()))
330 (match args
331 (()
332 (reverse result))
333 (((? keyword? kw) arg . rest)
334 (loop rest
335 (if (memq kw keywords)
336 result
337 (cons* arg kw result))))
338 ((head . tail)
339 (loop tail (cons head result))))))
340
0af2c24e
LC
341(define (default-keyword-arguments args defaults)
342 "Return ARGS augmented with any keyword/value from DEFAULTS for
343keywords not already present in ARGS."
344 (let loop ((defaults defaults)
345 (args args))
346 (match defaults
347 ((kw value rest ...)
348 (loop rest
347df601 349 (if (memq kw args)
0af2c24e
LC
350 args
351 (cons* kw value args))))
352 (()
353 args))))
354
b8b129eb
EB
355(define-syntax collect-default-args
356 (syntax-rules ()
357 ((_)
358 '())
359 ((_ (_ _) rest ...)
360 (collect-default-args rest ...))
361 ((_ (kw _ dflt) rest ...)
362 (cons* kw dflt (collect-default-args rest ...)))))
363
0af2c24e
LC
364(define-syntax substitute-keyword-arguments
365 (syntax-rules ()
366 "Return a new list of arguments where the value for keyword arg KW is
b8b129eb
EB
367replaced by EXP. EXP is evaluated in a context where VAR is bound to the
368previous value of the keyword argument, or DFLT if given."
369 ((_ original-args ((kw var dflt ...) exp) ...)
370 (let loop ((args (default-keyword-arguments
371 original-args
372 (collect-default-args (kw var dflt ...) ...)))
0af2c24e
LC
373 (before '()))
374 (match args
375 ((kw var rest (... ...))
376 (loop rest (cons* exp kw before)))
377 ...
378 ((x rest (... ...))
379 (loop rest (cons x before)))
380 (()
381 (reverse before)))))))
382
6071122b
LC
383(define (delkw kw lst)
384 "Remove KW and its associated value from LST, a keyword/value list such
385as '(#:foo 1 #:bar 2)."
386 (let loop ((lst lst)
387 (result '()))
388 (match lst
389 (()
390 (reverse result))
391 ((kw? value rest ...)
392 (if (eq? kw? kw)
393 (append (reverse result) rest)
394 (loop rest (cons* value kw? result)))))))
395
396(define (ensure-keyword-arguments args kw/values)
397 "Force the keywords arguments KW/VALUES in the keyword argument list ARGS.
398For instance:
399
400 (ensure-keyword-arguments '(#:foo 2) '(#:foo 2))
401 => (#:foo 2)
402
403 (ensure-keyword-arguments '(#:foo 2) '(#:bar 3))
404 => (#:foo 2 #:bar 3)
405
406 (ensure-keyword-arguments '(#:foo 2) '(#:bar 3 #:foo 42))
407 => (#:foo 42 #:bar 3)
408"
409 (let loop ((args args)
410 (kw/values kw/values)
411 (result '()))
412 (match args
413 (()
414 (append (reverse result) kw/values))
415 ((kw value rest ...)
416 (match (memq kw kw/values)
417 ((_ value . _)
418 (loop rest (delkw kw kw/values) (cons* value kw result)))
419 (#f
420 (loop rest kw/values (cons* value kw result))))))))
421
958dd3ce
LC
422\f
423;;;
424;;; System strings.
425;;;
426
8eb80484
MW
427(define* (nix-system->gnu-triplet
428 #:optional (system (%current-system)) (vendor "unknown"))
429 "Return a guess of the GNU triplet corresponding to Nix system
430identifier SYSTEM."
3f00ff8b
MW
431 (match system
432 ("armhf-linux"
433 (string-append "arm-" vendor "-linux-gnueabihf"))
434 (_
435 (let* ((dash (string-index system #\-))
436 (arch (substring system 0 dash))
437 (os (substring system (+ 1 dash))))
438 (string-append arch
439 "-" vendor "-"
440 (if (string=? os "linux")
441 "linux-gnu"
442 os))))))
8eb80484 443
98090557
LC
444(define (gnu-triplet->nix-system triplet)
445 "Return the Nix system type corresponding to TRIPLET, a GNU triplet as
446returned by `config.guess'."
447 (let ((triplet (cond ((string-match "^i[345]86-(.*)$" triplet)
448 =>
449 (lambda (m)
450 (string-append "i686-" (match:substring m 1))))
451 (else triplet))))
3f00ff8b
MW
452 (cond ((string-match "^arm[^-]*-([^-]+-)?linux-gnueabihf" triplet)
453 "armhf-linux")
454 ((string-match "^([^-]+)-([^-]+-)?linux-gnu.*" triplet)
98090557
LC
455 =>
456 (lambda (m)
457 ;; Nix omits `-gnu' for GNU/Linux.
458 (string-append (match:substring m 1) "-linux")))
459 ((string-match "^([^-]+)-([^-]+-)?([[:alpha:]]+)([0-9]+\\.?)*$" triplet)
460 =>
461 (lambda (m)
462 ;; Nix strip the version number from names such as `gnu0.3',
463 ;; `darwin10.2.0', etc., and always strips the vendor part.
464 (string-append (match:substring m 1) "-"
465 (match:substring m 3))))
466 (else triplet))))
467
468(define %current-system
469 ;; System type as expected by Nix, usually ARCHITECTURE-KERNEL.
d8eea3d2
LC
470 ;; By default, this is equal to (gnu-triplet->nix-system %host-type).
471 (make-parameter %system))
ff352cfb 472
9c1edabd
LC
473(define %current-target-system
474 ;; Either #f or a GNU triplet representing the target system we are
475 ;; cross-building to.
476 (make-parameter #f))
477
aa042770
LC
478(define* (package-name->name+version spec
479 #:optional (delimiter #\@))
1b846da8
ML
480 "Given SPEC, a package name like \"foo@0.9.1b\", return two values: \"foo\"
481and \"0.9.1b\". When the version part is unavailable, SPEC and #f are
aa042770
LC
482returned. Both parts must not contain any '@'. Optionally, DELIMITER can be
483a character other than '@'."
484 (match (string-rindex spec delimiter)
1b846da8
ML
485 (#f (values spec #f))
486 (idx (values (substring spec 0 idx)
487 (substring spec (1+ idx))))))
488
cba36e64
JN
489(define* (target-mingw? #:optional (target (%current-target-system)))
490 (and target
491 (string-suffix? "-mingw32" target)))
492
e45b573c
MO
493(define (target-arm32?)
494 (string-prefix? "arm" (or (%current-target-system) (%current-system))))
495
74f17180
MO
496(define (target-aarch64?)
497 (string-prefix? "aarch64" (or (%current-target-system) (%current-system))))
498
499(define (target-arm?)
500 (or (target-arm32?) (target-aarch64?)))
501
259341cf
MB
502(define (target-64bit?)
503 (let ((system (or (%current-target-system) (%current-system))))
504 (any (cut string-prefix? <> system) '("x86_64" "aarch64" "mips64" "ppc64"))))
505
0d1e6ce4
MW
506(define version-compare
507 (let ((strverscmp
508 (let ((sym (or (dynamic-func "strverscmp" (dynamic-link))
509 (error "could not find `strverscmp' (from GNU libc)"))))
510 (pointer->procedure int sym (list '* '*)))))
511 (lambda (a b)
512 "Return '> when A denotes a newer version than B,
513'< when A denotes a older version than B,
514or '= when they denote equal versions."
515 (let ((result (strverscmp (string->pointer a) (string->pointer b))))
516 (cond ((positive? result) '>)
517 ((negative? result) '<)
518 (else '=))))))
519
29a7c98a
ID
520(define (version-prefix version-string num-parts)
521 "Truncate version-string to the first num-parts components of the version.
522For example, (version-prefix \"2.1.47.4.23\" 3) returns \"2.1.47\""
523 (string-join (take (string-split version-string #\.) num-parts) "."))
524
525
526(define (version-major+minor version-string)
527 "Return \"<major>.<minor>\", where major and minor are the major and
528minor version numbers from version-string."
529 (version-prefix version-string 2))
530
47dc9a0d 531(define (version-major version-string)
532 "Return the major version number as string from the version-string."
533 (version-prefix version-string 1))
534
0d1e6ce4 535(define (version>? a b)
cde1e967 536 "Return #t when A denotes a version strictly newer than B."
0d1e6ce4
MW
537 (eq? '> (version-compare a b)))
538
cde1e967
LC
539(define (version>=? a b)
540 "Return #t when A denotes a version newer or equal to B."
541 (case (version-compare a b)
542 ((> =) #t)
543 (else #f)))
544
7db3ff4a
LC
545(define (guile-version>? str)
546 "Return #t if the running Guile version is greater than STR."
547 ;; Note: Using (version>? (version) "2.0.5") or similar doesn't work,
548 ;; because the result of (version) can have a prefix, like "2.0.5-deb1".
549 (version>? (string-append (major-version) "."
550 (minor-version) "."
551 (micro-version))
552 str))
553
437f62f0
LC
554(define version-prefix?
555 (let ((not-dot (char-set-complement (char-set #\.))))
556 (lambda (v1 v2)
557 "Return true if V1 is a version prefix of V2:
558
559 (version-prefix? \"4.1\" \"4.16.2\") => #f
560 (version-prefix? \"4.1\" \"4.1.2\") => #t
561"
562 (define (list-prefix? lst1 lst2)
563 (match lst1
564 (() #t)
565 ((head1 tail1 ...)
566 (match lst2
567 (() #f)
568 ((head2 tail2 ...)
569 (and (equal? head1 head2)
570 (list-prefix? tail1 tail2)))))))
571
572 (list-prefix? (string-tokenize v1 not-dot)
573 (string-tokenize v2 not-dot)))))
574
0fdd3bea
LC
575(define (file-extension file)
576 "Return the extension of FILE or #f if there is none."
577 (let ((dot (string-rindex file #\.)))
578 (and dot (substring file (+ 1 dot) (string-length file)))))
579
ac10e0e1
LC
580(define (file-sans-extension file)
581 "Return the substring of FILE without its extension, if any."
582 (let ((dot (string-rindex file #\.)))
583 (if dot
584 (substring file 0 dot)
585 file)))
586
da1027a7
HG
587(define (tarball-sans-extension tarball)
588 "Return TARBALL without its .tar.* or .zip extension."
589 (let ((end (or (string-contains tarball ".tar")
590 (string-contains tarball ".zip"))))
591 (substring tarball 0 end)))
592
089b1678
LC
593(define (compressed-file? file)
594 "Return true if FILE denotes a compressed file."
595 (->bool (member (file-extension file)
f4111243 596 '("gz" "bz2" "xz" "lz" "lzma" "tgz" "tbz2" "zip"))))
089b1678 597
3bb168b0
LC
598(define (switch-symlinks link target)
599 "Atomically switch LINK, a symbolic link, to point to TARGET. Works
600both when LINK already exists and when it does not."
601 (let ((pivot (string-append link ".new")))
602 (symlink target pivot)
603 (rename-file pivot link)))
604
56b943de
LC
605(define* (string-replace-substring str substr replacement
606 #:optional
607 (start 0)
608 (end (string-length str)))
609 "Replace all occurrences of SUBSTR in the START--END range of STR by
610REPLACEMENT."
611 (match (string-length substr)
612 (0
613 (error "string-replace-substring: empty substring"))
614 (substr-length
615 (let loop ((start start)
616 (pieces (list (substring str 0 start))))
617 (match (string-contains str substr start end)
618 (#f
619 (string-concatenate-reverse
620 (cons (substring str start) pieces)))
621 (index
622 (loop (+ index substr-length)
623 (cons* replacement
624 (substring str start index)
625 pieces))))))))
626
16eb115e
DP
627(define (arguments-from-environment-variable variable)
628 "Retrieve value of environment variable denoted by string VARIABLE in the
629form of a list of strings (`char-set:graphic' tokens) suitable for consumption
630by `args-fold', if VARIABLE is defined, otherwise return an empty list."
631 (let ((env (getenv variable)))
632 (if env
633 (string-tokenize env char-set:graphic)
634 '())))
635
861693f3
LC
636(define (call-with-temporary-output-file proc)
637 "Call PROC with a name of a temporary file and open output port to that
638file; close the file and delete it when leaving the dynamic extent of this
639call."
57db49cc
LC
640 (let* ((directory (or (getenv "TMPDIR") "/tmp"))
641 (template (string-append directory "/guix-file.XXXXXX"))
642 (out (mkstemp! template)))
861693f3
LC
643 (dynamic-wind
644 (lambda ()
645 #t)
646 (lambda ()
647 (proc template out))
648 (lambda ()
649 (false-if-exception (close out))
650 (false-if-exception (delete-file template))))))
04d4c8a4 651
db6e5e2b
DT
652(define (call-with-temporary-directory proc)
653 "Call PROC with a name of a temporary directory; close the directory and
654delete it when leaving the dynamic extent of this call."
655 (let* ((directory (or (getenv "TMPDIR") "/tmp"))
656 (template (string-append directory "/guix-directory.XXXXXX"))
657 (tmp-dir (mkdtemp! template)))
658 (dynamic-wind
659 (const #t)
660 (lambda ()
661 (proc tmp-dir))
662 (lambda ()
27f7cbc9 663 (false-if-exception (delete-file-recursively tmp-dir))))))
db6e5e2b 664
04d4c8a4
LC
665(define (with-atomic-file-output file proc)
666 "Call PROC with an output port for the file that is going to replace FILE.
667Upon success, FILE is atomically replaced by what has been written to the
668output port, and PROC's result is returned."
669 (let* ((template (string-append file ".XXXXXX"))
670 (out (mkstemp! template)))
671 (with-throw-handler #t
672 (lambda ()
673 (let ((result (proc out)))
1752a17a
LC
674 (fdatasync out)
675 (close-port out)
04d4c8a4
LC
676 (rename-file template file)
677 result))
678 (lambda (key . args)
c25637df
LC
679 (false-if-exception (delete-file template))
680 (close-port out)))))
861693f3 681
f0e492f0
LC
682(define* (xdg-directory variable suffix #:key (ensure? #t))
683 "Return the name of the XDG directory that matches VARIABLE and SUFFIX,
684after making sure that it exists if ENSURE? is true. VARIABLE is an
685environment variable name like \"XDG_CONFIG_HOME\"; SUFFIX is a suffix like
686\"/.config\". Honor the XDG specs,
687<http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html>."
688 (let ((dir (and=> (or (getenv variable)
689 (and=> (or (getenv "HOME")
690 (passwd:dir (getpwuid (getuid))))
691 (cut string-append <> suffix)))
692 (cut string-append <> "/guix"))))
693 (when ensure?
694 (mkdir-p dir))
695 dir))
696
697(define config-directory
698 (cut xdg-directory "XDG_CONFIG_HOME" "/.config" <...>))
699
700(define cache-directory
701 (cut xdg-directory "XDG_CACHE_HOME" "/.cache" <...>))
739ab68b 702
d50cb56d
LC
703(define (readlink* file)
704 "Call 'readlink' until the result is not a symlink."
705 (define %max-symlink-depth 50)
706
707 (let loop ((file file)
708 (depth 0))
709 (define (absolute target)
710 (if (absolute-file-name? target)
711 target
712 (string-append (dirname file) "/" target)))
713
714 (if (>= depth %max-symlink-depth)
715 file
716 (call-with-values
717 (lambda ()
718 (catch 'system-error
719 (lambda ()
720 (values #t (readlink file)))
721 (lambda args
722 (let ((errno (system-error-errno args)))
723 (if (or (= errno EINVAL))
724 (values #f file)
725 (apply throw args))))))
726 (lambda (success? target)
727 (if success?
728 (loop (absolute target) (+ depth 1))
729 file))))))
c8be6f0d
FB
730
731(define (canonical-newline-port port)
732 "Return an input port that wraps PORT such that all newlines consist
3149c002 733 of a single linefeed."
c8be6f0d
FB
734 (define (get-position)
735 (if (port-has-port-position? port) (port-position port) #f))
736 (define (set-position! position)
737 (if (port-has-set-port-position!? port)
738 (set-port-position! position port)
739 #f))
740 (define (close) (close-port port))
741 (define (read! bv start n)
742 (let loop ((count 0)
743 (byte (get-u8 port)))
744 (cond ((eof-object? byte) count)
3149c002
RV
745 ;; XXX: consume all CRs even if not followed by LF.
746 ((eqv? byte (char->integer #\return)) (loop count (get-u8 port)))
c8be6f0d
FB
747 ((= count (- n 1))
748 (bytevector-u8-set! bv (+ start count) byte)
749 n)
c8be6f0d
FB
750 (else
751 (bytevector-u8-set! bv (+ start count) byte)
752 (loop (+ count 1) (get-u8 port))))))
753 (make-custom-binary-input-port "canonical-newline-port"
754 read!
755 get-position
756 set-position!
757 close))
ff352cfb
LC
758\f
759;;;
760;;; Source location.
761;;;
762
87b711d2
LC
763(define absolute-dirname
764 ;; Memoize to avoid repeated 'stat' storms from 'search-path'.
765 (mlambda (file)
766 "Return the absolute name of the directory containing FILE, or #f upon
cbbbb7be 767failure."
87b711d2
LC
768 (match (search-path %load-path file)
769 (#f #f)
770 ((? string? file)
771 ;; If there are relative names in %LOAD-PATH, FILE can be relative and
772 ;; needs to be canonicalized.
773 (if (string-prefix? "/" file)
774 (dirname file)
775 (canonicalize-path (dirname file)))))))
cbbbb7be 776
5dbae738
LC
777(define-syntax current-source-directory
778 (lambda (s)
d4dd37fc
LC
779 "Return the absolute name of the current directory, or #f if it could not
780be determined."
5dbae738
LC
781 (syntax-case s ()
782 ((_)
82781d87 783 (match (assq 'filename (or (syntax-source s) '()))
5dbae738 784 (('filename . (? string? file-name))
d4dd37fc 785 ;; If %FILE-PORT-NAME-CANONICALIZATION is 'relative, then FILE-NAME
cbbbb7be
LC
786 ;; can be relative. In that case, we try to find out at run time
787 ;; the absolute file name by looking at %LOAD-PATH; doing this at
788 ;; run time rather than expansion time is necessary to allow files
789 ;; to be moved on the file system.
b997d432
AS
790 (if (string-prefix? "/" file-name)
791 (dirname file-name)
792 #`(absolute-dirname #,file-name)))
793 ((or ('filename . #f) #f)
794 ;; raising an error would upset Geiser users
5dbae738 795 #f))))))
07c8a98c 796
ff352cfb
LC
797;; A source location.
798(define-record-type <location>
799 (make-location file line column)
800 location?
801 (file location-file) ; file name
802 (line location-line) ; 1-indexed line
803 (column location-column)) ; 0-indexed column
804
3059a35a
LC
805(define (location file line column)
806 "Return the <location> object for the given FILE, LINE, and COLUMN."
807 (and line column file
808 (make-location file line column)))
ff352cfb
LC
809
810(define (source-properties->location loc)
811 "Return a location object based on the info in LOC, an alist as returned
812by Guile's `source-properties', `frame-source', `current-source-location',
813etc."
223fa5b3
LC
814 ;; In accordance with the GCS, start line and column numbers at 1. Note
815 ;; that unlike LINE and `port-column', COL is actually 1-indexed here...
816 (match loc
817 ((('line . line) ('column . col) ('filename . file)) ;common case
818 (and file line col
819 (make-location file (+ line 1) col)))
820 (#f
821 #f)
822 (_
823 (let ((file (assq-ref loc 'filename))
824 (line (assq-ref loc 'line))
825 (col (assq-ref loc 'column)))
826 (location file (and line (+ line 1)) col)))))
f7df1e3e
SB
827
828(define (location->source-properties loc)
829 "Return the source property association list based on the info in LOC,
830a location object."
831 `((line . ,(and=> (location-line loc) 1-))
832 (column . ,(location-column loc))
833 (filename . ,(location-file loc))))
79864851 834
23735137
LC
835(define-condition-type &error-location &error
836 error-location?
837 (location error-location)) ;<location>
838
839(define-condition-type &fix-hint &condition
840 fix-hint?
841 (hint condition-fix-hint)) ;string
842
79864851
SB
843;;; Local Variables:
844;;; eval: (put 'call-with-progress-reporter 'scheme-indent-function 1)
845;;; End: