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