utils.scm 42 KB

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