utils.scm 35 KB

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