utils.scm 43 KB

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