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