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