utils.scm 34 KB

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