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