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