utils.scm 43 KB

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