utils.scm 35 KB

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