utils.scm 41 KB

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