utils.scm 31 KB

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