utils.scm 31 KB

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