utils.scm 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623
  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 Andreas Enge <andreas@enge.fr>
  4. ;;; Copyright © 2013 Nikita Karetnikov <nikita@karetnikov.org>
  5. ;;; Copyright © 2015, 2018, 2021 Mark H Weaver <mhw@netris.org>
  6. ;;; Copyright © 2018 Arun Isaac <arunisaac@systemreboot.net>
  7. ;;; Copyright © 2018, 2019 Ricardo Wurmus <rekado@elephly.net>
  8. ;;; Copyright © 2020 Efraim Flashner <efraim@flashner.co.il>
  9. ;;; Copyright © 2020, 2021 Maxim Cournoyer <maxim.cournoyer@gmail.com>
  10. ;;; Copyright © 2021 Maxime Devos <maximedevos@telenet.be>
  11. ;;; Copyright © 2021 Brendan Tildesley <mail@brendan.scot>
  12. ;;;
  13. ;;; This file is part of GNU Guix.
  14. ;;;
  15. ;;; GNU Guix is free software; you can redistribute it and/or modify it
  16. ;;; under the terms of the GNU General Public License as published by
  17. ;;; the Free Software Foundation; either version 3 of the License, or (at
  18. ;;; your option) any later version.
  19. ;;;
  20. ;;; GNU Guix is distributed in the hope that it will be useful, but
  21. ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
  22. ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. ;;; GNU General Public License for more details.
  24. ;;;
  25. ;;; You should have received a copy of the GNU General Public License
  26. ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
  27. (define-module (guix build utils)
  28. #:use-module (srfi srfi-1)
  29. #:use-module (srfi srfi-11)
  30. #:use-module (srfi srfi-26)
  31. #:use-module (srfi srfi-34)
  32. #:use-module (srfi srfi-35)
  33. #:use-module (srfi srfi-60)
  34. #:use-module (ice-9 ftw)
  35. #:use-module (ice-9 match)
  36. #:use-module (ice-9 regex)
  37. #:use-module (ice-9 rdelim)
  38. #:use-module (ice-9 format)
  39. #:use-module (ice-9 threads)
  40. #:use-module (rnrs bytevectors)
  41. #:use-module (rnrs io ports)
  42. #:re-export (alist-cons
  43. alist-delete
  44. ;; Note: Re-export 'delete' to allow for proper syntax matching
  45. ;; in 'modify-phases' forms. See
  46. ;; <https://debbugs.gnu.org/cgi/bugreport.cgi?bug=26805#16>.
  47. delete)
  48. #:export (%store-directory
  49. store-file-name?
  50. strip-store-file-name
  51. package-name->name+version
  52. parallel-job-count
  53. compressor
  54. tarball?
  55. %xz-parallel-args
  56. directory-exists?
  57. executable-file?
  58. symbolic-link?
  59. call-with-temporary-output-file
  60. call-with-ascii-input-file
  61. elf-file?
  62. ar-file?
  63. gzip-file?
  64. reset-gzip-timestamp
  65. with-directory-excursion
  66. mkdir-p
  67. install-file
  68. make-file-writable
  69. copy-recursively
  70. delete-file-recursively
  71. file-name-predicate
  72. find-files
  73. false-if-file-not-found
  74. search-path-as-list
  75. set-path-environment-variable
  76. search-path-as-string->list
  77. list->search-path-as-string
  78. which
  79. search-input-file
  80. search-input-directory
  81. search-error?
  82. search-error-path
  83. search-error-file
  84. every*
  85. alist-cons-before
  86. alist-cons-after
  87. alist-replace
  88. modify-phases
  89. with-atomic-file-replacement
  90. substitute
  91. substitute*
  92. dump-port
  93. set-file-time
  94. patch-shebang
  95. patch-makefile-SHELL
  96. patch-/usr/bin/file
  97. fold-port-matches
  98. remove-store-references
  99. wrapped-program?
  100. wrap-program
  101. wrap-script
  102. wrap-error?
  103. wrap-error-program
  104. wrap-error-type
  105. invoke
  106. invoke-error?
  107. invoke-error-program
  108. invoke-error-arguments
  109. invoke-error-exit-status
  110. invoke-error-term-signal
  111. invoke-error-stop-signal
  112. report-invoke-error
  113. invoke/quiet
  114. make-desktop-entry-file
  115. locale-category->string))
  116. ;;;
  117. ;;; Guile 2.0 compatibility later.
  118. ;;;
  119. ;; The bootstrap Guile is Guile 2.0, so provide a compatibility layer.
  120. (cond-expand
  121. ((and guile-2 (not guile-2.2))
  122. (define (setvbuf port mode . rest)
  123. (apply (@ (guile) setvbuf) port
  124. (match mode
  125. ('line _IOLBF)
  126. ('block _IOFBF)
  127. ('none _IONBF)
  128. (_ mode)) ;an _IO* integer
  129. rest))
  130. (module-replace! (current-module) '(setvbuf)))
  131. (else #f))
  132. ;;;
  133. ;;; Compression helpers.
  134. ;;;
  135. (define (compressor file-name)
  136. "Return the name of the compressor package/binary used to compress or
  137. decompress FILE-NAME, based on its file extension, else false."
  138. (cond ((string-suffix? "gz" file-name) "gzip")
  139. ((string-suffix? "Z" file-name) "gzip")
  140. ((string-suffix? "bz2" file-name) "bzip2")
  141. ((string-suffix? "lz" file-name) "lzip")
  142. ((string-suffix? "zip" file-name) "unzip")
  143. ((string-suffix? "xz" file-name) "xz")
  144. (else #f))) ;no compression used/unknown file extension
  145. (define (tarball? file-name)
  146. "True when FILE-NAME has a tar file extension."
  147. (string-match "\\.(tar(\\..*)?|tgz|tbz)$" file-name))
  148. (define (%xz-parallel-args)
  149. "The xz arguments required to enable bit-reproducible, multi-threaded
  150. compression."
  151. (list "--memlimit=50%"
  152. (format #f "--threads=~a" (max 2 (parallel-job-count)))))
  153. ;;;
  154. ;;; Directories.
  155. ;;;
  156. (define (%store-directory)
  157. "Return the directory name of the store."
  158. (or (getenv "NIX_STORE_DIR") ;outside of builder
  159. (getenv "NIX_STORE") ;inside builder, set by the daemon
  160. "/gnu/store"))
  161. (define (store-file-name? file)
  162. "Return true if FILE is in the store."
  163. (string-prefix? (%store-directory) file))
  164. (define (strip-store-file-name file)
  165. "Strip the '/gnu/store' and hash from FILE, a store file name. The result
  166. is typically a \"PACKAGE-VERSION\" string."
  167. (string-drop file
  168. (+ 34 (string-length (%store-directory)))))
  169. (define (package-name->name+version name)
  170. "Given NAME, a package name like \"foo-0.9.1b\", return two values:
  171. \"foo\" and \"0.9.1b\". When the version part is unavailable, NAME and
  172. #f are returned. The first hyphen followed by a digit is considered to
  173. introduce the version part."
  174. ;; See also `DrvName' in Nix.
  175. (define number?
  176. (cut char-set-contains? char-set:digit <>))
  177. (let loop ((chars (string->list name))
  178. (prefix '()))
  179. (match chars
  180. (()
  181. (values name #f))
  182. ((#\- (? number? n) rest ...)
  183. (values (list->string (reverse prefix))
  184. (list->string (cons n rest))))
  185. ((head tail ...)
  186. (loop tail (cons head prefix))))))
  187. (define parallel-job-count
  188. ;; Number of processes to be passed next to GNU Make's `-j' argument.
  189. (make-parameter
  190. (match (getenv "NIX_BUILD_CORES") ;set by the daemon
  191. (#f 1)
  192. ("0" (current-processor-count))
  193. (x (or (string->number x) 1)))))
  194. (define (directory-exists? dir)
  195. "Return #t if DIR exists and is a directory."
  196. (let ((s (stat dir #f)))
  197. (and s
  198. (eq? 'directory (stat:type s)))))
  199. (define (executable-file? file)
  200. "Return #t if FILE exists and is executable."
  201. (let ((s (stat file #f)))
  202. (and s
  203. (not (zero? (logand (stat:mode s) #o100))))))
  204. (define (symbolic-link? file)
  205. "Return #t if FILE is a symbolic link (aka. \"symlink\".)"
  206. (eq? (stat:type (lstat file)) 'symlink))
  207. (define (call-with-temporary-output-file proc)
  208. "Call PROC with a name of a temporary file and open output port to that
  209. file; close the file and delete it when leaving the dynamic extent of this
  210. call."
  211. (let* ((directory (or (getenv "TMPDIR") "/tmp"))
  212. (template (string-append directory "/guix-file.XXXXXX"))
  213. (out (mkstemp! template)))
  214. (dynamic-wind
  215. (lambda ()
  216. #t)
  217. (lambda ()
  218. (proc template out))
  219. (lambda ()
  220. (false-if-exception (close out))
  221. (false-if-exception (delete-file template))))))
  222. (define (call-with-ascii-input-file file proc)
  223. "Open FILE as an ASCII or binary file, and pass the resulting port to
  224. PROC. FILE is closed when PROC's dynamic extent is left. Return the
  225. return values of applying PROC to the port."
  226. (let ((port (with-fluids ((%default-port-encoding #f))
  227. ;; Use "b" so that `open-file' ignores `coding:' cookies.
  228. (open-file file "rb"))))
  229. (dynamic-wind
  230. (lambda ()
  231. #t)
  232. (lambda ()
  233. (proc port))
  234. (lambda ()
  235. (close-input-port port)))))
  236. (define (file-header-match header)
  237. "Return a procedure that returns true when its argument is a file starting
  238. with the bytes in HEADER, a bytevector."
  239. (define len
  240. (bytevector-length header))
  241. (lambda (file)
  242. "Return true if FILE starts with the right magic bytes."
  243. (define (get-header)
  244. (call-with-input-file file
  245. (lambda (port)
  246. (get-bytevector-n port len))
  247. #:binary #t #:guess-encoding #f))
  248. (catch 'system-error
  249. (lambda ()
  250. (equal? (get-header) header))
  251. (lambda args
  252. (if (= EISDIR (system-error-errno args))
  253. #f ;FILE is a directory
  254. (apply throw args))))))
  255. (define %elf-magic-bytes
  256. ;; Magic bytes of ELF files. See <elf.h>.
  257. (u8-list->bytevector (map char->integer (string->list "\x7FELF"))))
  258. (define elf-file?
  259. (file-header-match %elf-magic-bytes))
  260. (define %ar-magic-bytes
  261. ;; Magic bytes of archives created by 'ar'. See <ar.h>.
  262. (u8-list->bytevector (map char->integer (string->list "!<arch>\n"))))
  263. (define ar-file?
  264. (file-header-match %ar-magic-bytes))
  265. (define %gzip-magic-bytes
  266. ;; Magic bytes of gzip file. Beware, it's a small header so there could be
  267. ;; false positives.
  268. #vu8(#x1f #x8b))
  269. (define gzip-file?
  270. (file-header-match %gzip-magic-bytes))
  271. (define* (reset-gzip-timestamp file #:key (keep-mtime? #t))
  272. "If FILE is a gzip file, reset its embedded timestamp (as with 'gzip
  273. --no-name') and return true. Otherwise return #f. When KEEP-MTIME? is true,
  274. preserve FILE's modification time."
  275. (let ((stat (stat file))
  276. (port (open file O_RDWR)))
  277. (dynamic-wind
  278. (const #t)
  279. (lambda ()
  280. (and (= 4 (seek port 4 SEEK_SET))
  281. (put-bytevector port #vu8(0 0 0 0))))
  282. (lambda ()
  283. (close-port port)
  284. (set-file-time file stat)))))
  285. (define-syntax-rule (with-directory-excursion dir body ...)
  286. "Run BODY with DIR as the process's current directory."
  287. (let ((init (getcwd)))
  288. (dynamic-wind
  289. (lambda ()
  290. (chdir dir))
  291. (lambda ()
  292. body ...)
  293. (lambda ()
  294. (chdir init)))))
  295. (define (mkdir-p dir)
  296. "Create directory DIR and all its ancestors."
  297. (define absolute?
  298. (string-prefix? "/" dir))
  299. (define not-slash
  300. (char-set-complement (char-set #\/)))
  301. (let loop ((components (string-tokenize dir not-slash))
  302. (root (if absolute?
  303. ""
  304. ".")))
  305. (match components
  306. ((head tail ...)
  307. (let ((path (string-append root "/" head)))
  308. (catch 'system-error
  309. (lambda ()
  310. (mkdir path)
  311. (loop tail path))
  312. (lambda args
  313. (if (= EEXIST (system-error-errno args))
  314. (loop tail path)
  315. (apply throw args))))))
  316. (() #t))))
  317. (define (install-file file directory)
  318. "Create DIRECTORY if it does not exist and copy FILE in there under the same
  319. name."
  320. (mkdir-p directory)
  321. (copy-file file (string-append directory "/" (basename file))))
  322. (define (make-file-writable file)
  323. "Make FILE writable for its owner."
  324. (let ((stat (lstat file))) ;XXX: symlinks
  325. (chmod file (logior #o600 (stat:perms stat)))))
  326. (define* (copy-recursively source destination
  327. #:key
  328. (log (current-output-port))
  329. (follow-symlinks? #f)
  330. (copy-file copy-file)
  331. keep-mtime? keep-permissions?)
  332. "Copy SOURCE directory to DESTINATION. Follow symlinks if FOLLOW-SYMLINKS?
  333. is true; otherwise, just preserve them. Call COPY-FILE to copy regular files.
  334. When KEEP-MTIME? is true, keep the modification time of the files in SOURCE on
  335. those of DESTINATION. When KEEP-PERMISSIONS? is true, preserve file
  336. permissions. Write verbose output to the LOG port."
  337. (define strip-source
  338. (let ((len (string-length source)))
  339. (lambda (file)
  340. (substring file len))))
  341. (file-system-fold (const #t) ; enter?
  342. (lambda (file stat result) ; leaf
  343. (let ((dest (string-append destination
  344. (strip-source file))))
  345. (format log "`~a' -> `~a'~%" file dest)
  346. (case (stat:type stat)
  347. ((symlink)
  348. (let ((target (readlink file)))
  349. (symlink target dest)))
  350. (else
  351. (copy-file file dest)
  352. (when keep-permissions?
  353. (chmod dest (stat:perms stat)))))
  354. (when keep-mtime?
  355. (set-file-time dest stat))))
  356. (lambda (dir stat result) ; down
  357. (let ((target (string-append destination
  358. (strip-source dir))))
  359. (mkdir-p target)))
  360. (lambda (dir stat result) ; up
  361. (let ((target (string-append destination
  362. (strip-source dir))))
  363. (when keep-mtime?
  364. (set-file-time target stat))
  365. (when keep-permissions?
  366. (chmod target (stat:perms stat)))))
  367. (const #t) ; skip
  368. (lambda (file stat errno result)
  369. (format (current-error-port) "i/o error: ~a: ~a~%"
  370. file (strerror errno))
  371. #f)
  372. #t
  373. source
  374. (if follow-symlinks?
  375. stat
  376. lstat)))
  377. (define-syntax-rule (warn-on-error expr file)
  378. (catch 'system-error
  379. (lambda ()
  380. expr)
  381. (lambda args
  382. (format (current-error-port)
  383. "warning: failed to delete ~a: ~a~%"
  384. file (strerror
  385. (system-error-errno args))))))
  386. (define* (delete-file-recursively dir
  387. #:key follow-mounts?)
  388. "Delete DIR recursively, like `rm -rf', without following symlinks. Don't
  389. follow mount points either, unless FOLLOW-MOUNTS? is true. Report but ignore
  390. errors."
  391. (let ((dev (stat:dev (lstat dir))))
  392. (file-system-fold (lambda (dir stat result) ; enter?
  393. (or follow-mounts?
  394. (= dev (stat:dev stat))))
  395. (lambda (file stat result) ; leaf
  396. (warn-on-error (delete-file file) file))
  397. (const #t) ; down
  398. (lambda (dir stat result) ; up
  399. (warn-on-error (rmdir dir) dir))
  400. (const #t) ; skip
  401. (lambda (file stat errno result)
  402. (format (current-error-port)
  403. "warning: failed to delete ~a: ~a~%"
  404. file (strerror errno)))
  405. #t
  406. dir
  407. ;; Don't follow symlinks.
  408. lstat)))
  409. (define (file-name-predicate regexp)
  410. "Return a predicate that returns true when passed a file name whose base
  411. name matches REGEXP."
  412. (let ((file-rx (if (regexp? regexp)
  413. regexp
  414. (make-regexp regexp))))
  415. (lambda (file stat)
  416. (regexp-exec file-rx (basename file)))))
  417. (define* (find-files dir #:optional (pred (const #t))
  418. #:key (stat lstat)
  419. directories?
  420. fail-on-error?)
  421. "Return the lexicographically sorted list of files under DIR for which PRED
  422. returns true. PRED is passed two arguments: the absolute file name, and its
  423. stat buffer; the default predicate always returns true. PRED can also be a
  424. regular expression, in which case it is equivalent to (file-name-predicate
  425. PRED). STAT is used to obtain file information; using 'lstat' means that
  426. symlinks are not followed. If DIRECTORIES? is true, then directories will
  427. also be included. If FAIL-ON-ERROR? is true, raise an exception upon error."
  428. (let ((pred (if (procedure? pred)
  429. pred
  430. (file-name-predicate pred))))
  431. ;; Sort the result to get deterministic results.
  432. (sort (file-system-fold (const #t)
  433. (lambda (file stat result) ; leaf
  434. (if (pred file stat)
  435. (cons file result)
  436. result))
  437. (lambda (dir stat result) ; down
  438. (if (and directories?
  439. (pred dir stat))
  440. (cons dir result)
  441. result))
  442. (lambda (dir stat result) ; up
  443. result)
  444. (lambda (file stat result) ; skip
  445. result)
  446. (lambda (file stat errno result)
  447. (format (current-error-port) "find-files: ~a: ~a~%"
  448. file (strerror errno))
  449. (when fail-on-error?
  450. (error "find-files failed"))
  451. result)
  452. '()
  453. dir
  454. stat)
  455. string<?)))
  456. (define-syntax-rule (false-if-file-not-found exp)
  457. "Evaluate EXP but return #f if it raises to 'system-error with ENOENT."
  458. (catch 'system-error
  459. (lambda () exp)
  460. (lambda args
  461. (if (= ENOENT (system-error-errno args))
  462. #f
  463. (apply throw args)))))
  464. ;;;
  465. ;;; Search paths.
  466. ;;;
  467. (define* (search-path-as-list files input-dirs
  468. #:key (type 'directory) pattern)
  469. "Return the list of directories among FILES of the given TYPE (a symbol as
  470. returned by 'stat:type') that exist in INPUT-DIRS. Example:
  471. (search-path-as-list '(\"share/emacs/site-lisp\" \"share/emacs/24.1\")
  472. (list \"/package1\" \"/package2\" \"/package3\"))
  473. => (\"/package1/share/emacs/site-lisp\"
  474. \"/package3/share/emacs/site-lisp\")
  475. When PATTERN is true, it is a regular expression denoting file names to look
  476. for under the directories designated by FILES. For example:
  477. (search-path-as-list '(\"xml\") (list docbook-xml docbook-xsl)
  478. #:type 'regular
  479. #:pattern \"^catalog\\\\.xml$\")
  480. => (\"/…/xml/dtd/docbook/catalog.xml\"
  481. \"/…/xml/xsl/docbook-xsl-1.78.1/catalog.xml\")
  482. "
  483. (append-map (lambda (input)
  484. (append-map (lambda (file)
  485. (let ((file (string-append input "/" file)))
  486. (if pattern
  487. (find-files file (lambda (file stat)
  488. (and stat
  489. (eq? type (stat:type stat))
  490. ((file-name-predicate pattern) file stat)))
  491. #:stat stat
  492. #:directories? #t)
  493. (let ((stat (stat file #f)))
  494. (if (and stat (eq? type (stat:type stat)))
  495. (list file)
  496. '())))))
  497. files))
  498. (delete-duplicates input-dirs)))
  499. (define (list->search-path-as-string lst separator)
  500. (if separator
  501. (string-join lst separator)
  502. (match lst
  503. ((head rest ...) head)
  504. (() ""))))
  505. (define* (search-path-as-string->list path #:optional (separator #\:))
  506. (if separator
  507. (string-tokenize path
  508. (char-set-complement (char-set separator)))
  509. (list path)))
  510. (define* (set-path-environment-variable env-var files input-dirs
  511. #:key
  512. (separator ":")
  513. (type 'directory)
  514. pattern)
  515. "Look for each of FILES of the given TYPE (a symbol as returned by
  516. 'stat:type') in INPUT-DIRS. Set ENV-VAR to a SEPARATOR-separated path
  517. accordingly. Example:
  518. (set-path-environment-variable \"PKG_CONFIG\"
  519. '(\"lib/pkgconfig\")
  520. (list package1 package2))
  521. When PATTERN is not #f, it must be a regular expression (really a string)
  522. denoting file names to look for under the directories designated by FILES:
  523. (set-path-environment-variable \"XML_CATALOG_FILES\"
  524. '(\"xml\")
  525. (list docbook-xml docbook-xsl)
  526. #:type 'regular
  527. #:pattern \"^catalog\\\\.xml$\")
  528. "
  529. (let* ((path (search-path-as-list files input-dirs
  530. #:type type
  531. #:pattern pattern))
  532. (value (list->search-path-as-string path separator)))
  533. (if (string-null? value)
  534. (begin
  535. ;; Never set ENV-VAR to an empty string because often, the empty
  536. ;; string is equivalent to ".". This is the case for
  537. ;; GUILE_LOAD_PATH in Guile 2.0, for instance.
  538. (unsetenv env-var)
  539. (format #t "environment variable `~a' unset~%" env-var))
  540. (begin
  541. (setenv env-var value)
  542. (format #t "environment variable `~a' set to `~a'~%"
  543. env-var value)))))
  544. (define (which program)
  545. "Return the complete file name for PROGRAM as found in $PATH, or #f if
  546. PROGRAM could not be found."
  547. (search-path (search-path-as-string->list (getenv "PATH"))
  548. program))
  549. (define-condition-type &search-error &error
  550. search-error?
  551. (path search-error-path)
  552. (file search-error-file))
  553. (define (search-input-file inputs file)
  554. "Find a file named FILE among the INPUTS and return its absolute file name.
  555. FILE must be a string like \"bin/sh\". If FILE is not found, an exception is
  556. raised."
  557. (match inputs
  558. (((_ . directories) ...)
  559. ;; Accept both "bin/sh" and "/bin/sh" as FILE argument.
  560. (let ((file (string-trim file #\/)))
  561. (or (search-path directories file)
  562. (raise
  563. (condition (&search-error (path directories) (file file)))))))))
  564. (define (search-input-directory inputs directory)
  565. "Find a sub-directory named DIRECTORY among the INPUTS and return its
  566. absolute file name.
  567. DIRECTORY must be a string like \"xml/dtd/docbook\". If DIRECTORY is not
  568. found, an exception is raised."
  569. (match inputs
  570. (((_ . directories) ...)
  571. (or (any (lambda (parent)
  572. (let ((directory (string-append parent "/" directory)))
  573. (and (directory-exists? directory)
  574. directory)))
  575. directories)
  576. (raise (condition
  577. (&search-error (path directories) (file directory))))))))
  578. ;;;
  579. ;;; Phases.
  580. ;;;
  581. ;;; In (guix build gnu-build-system), there are separate phases (configure,
  582. ;;; build, test, install). They are represented as a list of name/procedure
  583. ;;; pairs. The following procedures make it easy to change the list of
  584. ;;; phases.
  585. ;;;
  586. (define (every* pred lst)
  587. "This is like 'every', but process all the elements of LST instead of
  588. stopping as soon as PRED returns false. This is useful when PRED has side
  589. effects, such as displaying warnings or error messages."
  590. (let loop ((lst lst)
  591. (result #t))
  592. (match lst
  593. (()
  594. result)
  595. ((head . tail)
  596. (loop tail (and (pred head) result))))))
  597. (define* (alist-cons-before reference key value alist
  598. #:optional (key=? equal?))
  599. "Insert the KEY/VALUE pair before the first occurrence of a pair whose key
  600. is REFERENCE in ALIST. Use KEY=? to compare keys."
  601. (let-values (((before after)
  602. (break (match-lambda
  603. ((k . _)
  604. (key=? k reference)))
  605. alist)))
  606. (append before (alist-cons key value after))))
  607. (define* (alist-cons-after reference key value alist
  608. #:optional (key=? equal?))
  609. "Insert the KEY/VALUE pair after the first occurrence of a pair whose key
  610. is REFERENCE in ALIST. Use KEY=? to compare keys."
  611. (let-values (((before after)
  612. (break (match-lambda
  613. ((k . _)
  614. (key=? k reference)))
  615. alist)))
  616. (match after
  617. ((reference after ...)
  618. (append before (cons* reference `(,key . ,value) after)))
  619. (()
  620. (append before `((,key . ,value)))))))
  621. (define* (alist-replace key value alist #:optional (key=? equal?))
  622. "Replace the first pair in ALIST whose car is KEY with the KEY/VALUE pair.
  623. An error is raised when no such pair exists."
  624. (let-values (((before after)
  625. (break (match-lambda
  626. ((k . _)
  627. (key=? k key)))
  628. alist)))
  629. (match after
  630. ((_ after ...)
  631. (append before (alist-cons key value after))))))
  632. (define-syntax-rule (modify-phases phases mod-spec ...)
  633. "Modify PHASES sequentially as per each MOD-SPEC, which may have one of the
  634. following forms:
  635. (delete <old-phase-name>)
  636. (replace <old-phase-name> <new-phase>)
  637. (add-before <old-phase-name> <new-phase-name> <new-phase>)
  638. (add-after <old-phase-name> <new-phase-name> <new-phase>)
  639. Where every <*-phase-name> is an expression evaluating to a symbol, and
  640. <new-phase> an expression evaluating to a procedure."
  641. (let* ((phases* phases)
  642. (phases* (%modify-phases phases* mod-spec))
  643. ...)
  644. phases*))
  645. (define-syntax %modify-phases
  646. (syntax-rules (delete replace add-before add-after)
  647. ((_ phases (delete old-phase-name))
  648. (alist-delete old-phase-name phases))
  649. ((_ phases (replace old-phase-name new-phase))
  650. (alist-replace old-phase-name new-phase phases))
  651. ((_ phases (add-before old-phase-name new-phase-name new-phase))
  652. (alist-cons-before old-phase-name new-phase-name new-phase phases))
  653. ((_ phases (add-after old-phase-name new-phase-name new-phase))
  654. (alist-cons-after old-phase-name new-phase-name new-phase phases))))
  655. ;;;
  656. ;;; Program invocation.
  657. ;;;
  658. (define-condition-type &invoke-error &error
  659. invoke-error?
  660. (program invoke-error-program)
  661. (arguments invoke-error-arguments)
  662. (exit-status invoke-error-exit-status)
  663. (term-signal invoke-error-term-signal)
  664. (stop-signal invoke-error-stop-signal))
  665. (define (invoke program . args)
  666. "Invoke PROGRAM with the given ARGS. Raise an exception
  667. if the exit code is non-zero; otherwise return #t."
  668. (let ((code (apply system* program args)))
  669. (unless (zero? code)
  670. (raise (condition (&invoke-error
  671. (program program)
  672. (arguments args)
  673. (exit-status (status:exit-val code))
  674. (term-signal (status:term-sig code))
  675. (stop-signal (status:stop-sig code))))))
  676. #t))
  677. (define* (report-invoke-error c #:optional (port (current-error-port)))
  678. "Report to PORT about C, an '&invoke-error' condition, in a human-friendly
  679. way."
  680. (format port "command~{ ~s~} failed with ~:[signal~;status~] ~a~%"
  681. (cons (invoke-error-program c)
  682. (invoke-error-arguments c))
  683. (invoke-error-exit-status c)
  684. (or (invoke-error-exit-status c)
  685. (invoke-error-term-signal c)
  686. (invoke-error-stop-signal c))))
  687. (define (open-pipe-with-stderr program . args)
  688. "Run PROGRAM with ARGS in an input pipe, but, unlike 'open-pipe*', redirect
  689. both its standard output and standard error to the pipe. Return two value:
  690. the pipe to read PROGRAM's data from, and the PID of the child process running
  691. PROGRAM."
  692. ;; 'open-pipe*' doesn't attempt to capture stderr in any way, which is why
  693. ;; we need to roll our own.
  694. (match (pipe)
  695. ((input . output)
  696. (match (primitive-fork)
  697. (0
  698. (dynamic-wind
  699. (const #t)
  700. (lambda ()
  701. (close-port input)
  702. (dup2 (fileno output) 1)
  703. (dup2 (fileno output) 2)
  704. (apply execlp program program args))
  705. (lambda ()
  706. (primitive-exit 127))))
  707. (pid
  708. (close-port output)
  709. (values input pid))))))
  710. (define (invoke/quiet program . args)
  711. "Invoke PROGRAM with ARGS and capture PROGRAM's standard output and standard
  712. error. If PROGRAM succeeds, print nothing and return the unspecified value;
  713. otherwise, raise a '&message' error condition that includes the status code
  714. and the output of PROGRAM."
  715. (let-values (((pipe pid)
  716. (apply open-pipe-with-stderr program args)))
  717. (let loop ((lines '()))
  718. (match (read-line pipe)
  719. ((? eof-object?)
  720. (close-port pipe)
  721. (match (waitpid pid)
  722. ((_ . status)
  723. (unless (zero? status)
  724. (let-syntax ((G_ (syntax-rules () ;for xgettext
  725. ((_ str) str))))
  726. (raise (condition
  727. (&message
  728. (message (format #f (G_ "'~a~{ ~a~}' exited \
  729. with status ~a; output follows:~%~%~{ ~a~%~}")
  730. program args
  731. (or (status:exit-val status)
  732. status)
  733. (reverse lines)))))))))))
  734. (line
  735. (loop (cons line lines)))))))
  736. ;;;
  737. ;;; Text substitution (aka. sed).
  738. ;;;
  739. (define (with-atomic-file-replacement file proc)
  740. "Call PROC with two arguments: an input port for FILE, and an output
  741. port for the file that is going to replace FILE. Upon success, FILE is
  742. atomically replaced by what has been written to the output port, and
  743. PROC's result is returned."
  744. (let* ((template (string-append file ".XXXXXX"))
  745. (out (mkstemp! template))
  746. (mode (stat:mode (stat file))))
  747. (with-throw-handler #t
  748. (lambda ()
  749. (call-with-input-file file
  750. (lambda (in)
  751. (let ((result (proc in out)))
  752. (close out)
  753. (chmod template mode)
  754. (rename-file template file)
  755. result))))
  756. (lambda (key . args)
  757. (false-if-exception (delete-file template))))))
  758. (define (unused-private-use-code-point s)
  759. "Find a code point within a Unicode Private Use Area that is not
  760. present in S, and return the corresponding character object. If one
  761. cannot be found, return false."
  762. (define (scan lo hi)
  763. (and (<= lo hi)
  764. (let ((c (integer->char lo)))
  765. (if (string-index s c)
  766. (scan (+ lo 1) hi)
  767. c))))
  768. (or (scan #xE000 #xF8FF)
  769. (scan #xF0000 #xFFFFD)
  770. (scan #x100000 #x10FFFD)))
  771. (define (replace-char c1 c2 s)
  772. "Return a string which is equal to S except with all instances of C1
  773. replaced by C2. If C1 and C2 are equal, return S."
  774. (if (char=? c1 c2)
  775. s
  776. (string-map (lambda (c)
  777. (if (char=? c c1)
  778. c2
  779. c))
  780. s)))
  781. (define (substitute file pattern+procs)
  782. "PATTERN+PROCS is a list of regexp/two-argument-procedure pairs. For each
  783. line of FILE, and for each PATTERN that it matches, call the corresponding
  784. PROC as (PROC LINE MATCHES); PROC must return the line that will be written as
  785. a substitution of the original line. Be careful about using '$' to match the
  786. end of a line; by itself it won't match the terminating newline of a line."
  787. (let ((rx+proc (map (match-lambda
  788. (((? regexp? pattern) . proc)
  789. (cons pattern proc))
  790. ((pattern . proc)
  791. (cons (make-regexp pattern regexp/extended)
  792. proc)))
  793. pattern+procs)))
  794. (with-atomic-file-replacement file
  795. (lambda (in out)
  796. (let loop ((line (read-line in 'concat)))
  797. (if (eof-object? line)
  798. #t
  799. ;; Work around the fact that Guile's regexp-exec does not handle
  800. ;; NUL characters (a limitation of the underlying GNU libc's
  801. ;; regexec) by temporarily replacing them by an unused private
  802. ;; Unicode code point.
  803. ;; TODO: Use SRFI-115 instead, once available in Guile.
  804. (let* ((nul* (or (and (string-index line #\nul)
  805. (unused-private-use-code-point line))
  806. #\nul))
  807. (line* (replace-char #\nul nul* line))
  808. (line1* (fold (lambda (r+p line)
  809. (match r+p
  810. ((regexp . proc)
  811. (match (list-matches regexp line)
  812. ((and m+ (_ _ ...))
  813. (proc line m+))
  814. (_ line)))))
  815. line*
  816. rx+proc))
  817. (line1 (replace-char nul* #\nul line1*)))
  818. (display line1 out)
  819. (loop (read-line in 'concat)))))))))
  820. (define-syntax let-matches
  821. ;; Helper macro for `substitute*'.
  822. (syntax-rules (_)
  823. ((let-matches index match (_ vars ...) body ...)
  824. (let-matches (+ 1 index) match (vars ...)
  825. body ...))
  826. ((let-matches index match (var vars ...) body ...)
  827. (let ((var (match:substring match index)))
  828. (let-matches (+ 1 index) match (vars ...)
  829. body ...)))
  830. ((let-matches index match () body ...)
  831. (begin body ...))))
  832. (define-syntax substitute*
  833. (syntax-rules ()
  834. "Substitute REGEXP in FILE by the string returned by BODY. BODY is
  835. evaluated with each MATCH-VAR bound to the corresponding positional regexp
  836. sub-expression. For example:
  837. (substitute* file
  838. ((\"hello\")
  839. \"good morning\\n\")
  840. ((\"foo([a-z]+)bar(.*)$\" all letters end)
  841. (string-append \"baz\" letters end)))
  842. Here, anytime a line of FILE contains \"hello\", it is replaced by \"good
  843. morning\". Anytime a line of FILE matches the second regexp, ALL is bound to
  844. the complete match, LETTERS is bound to the first sub-expression, and END is
  845. bound to the last one.
  846. When one of the MATCH-VAR is `_', no variable is bound to the corresponding
  847. match substring.
  848. Alternatively, FILE may be a list of file names, in which case they are
  849. all subject to the substitutions.
  850. Be careful about using '$' to match the end of a line; by itself it won't
  851. match the terminating newline of a line."
  852. ((substitute* file ((regexp match-var ...) body ...) ...)
  853. (let ()
  854. (define (substitute-one-file file-name)
  855. (substitute
  856. file-name
  857. (list (cons regexp
  858. (lambda (l m+)
  859. ;; Iterate over matches M+ and return the
  860. ;; modified line based on L.
  861. (let loop ((m* m+) ; matches
  862. (o 0) ; offset in L
  863. (r '())) ; result
  864. (match m*
  865. (()
  866. (let ((r (cons (substring l o) r)))
  867. (string-concatenate-reverse r)))
  868. ((m . rest)
  869. (let-matches 0 m (match-var ...)
  870. (loop rest
  871. (match:end m)
  872. (cons*
  873. (begin body ...)
  874. (substring l o (match:start m))
  875. r))))))))
  876. ...)))
  877. (match file
  878. ((files (... ...))
  879. (for-each substitute-one-file files))
  880. ((? string? f)
  881. (substitute-one-file f)))))))
  882. ;;;
  883. ;;; Patching shebangs---e.g., /bin/sh -> /gnu/store/xyz...-bash/bin/sh.
  884. ;;;
  885. (define* (dump-port in out
  886. #:optional len
  887. #:key (buffer-size 16384)
  888. (progress (lambda (t k) (k))))
  889. "Read LEN bytes from IN or as much data as possible if LEN is #f, and write
  890. it to OUT, using chunks of BUFFER-SIZE bytes. Call PROGRESS at the beginning
  891. and after each successful transfer of BUFFER-SIZE bytes or less, passing it
  892. the total number of bytes transferred and the continuation of the transfer as
  893. a thunk."
  894. (define buffer
  895. (make-bytevector buffer-size))
  896. (define (loop total bytes)
  897. (or (eof-object? bytes)
  898. (and len (= total len))
  899. (let ((total (+ total bytes)))
  900. (put-bytevector out buffer 0 bytes)
  901. (progress total
  902. (lambda ()
  903. (loop total
  904. (get-bytevector-n! in buffer 0
  905. (if len
  906. (min (- len total) buffer-size)
  907. buffer-size))))))))
  908. ;; Make sure PROGRESS is called when we start so that it can measure
  909. ;; throughput.
  910. (progress 0
  911. (lambda ()
  912. (loop 0 (get-bytevector-n! in buffer 0
  913. (if len
  914. (min len buffer-size)
  915. buffer-size))))))
  916. (define AT_SYMLINK_NOFOLLOW
  917. ;; Guile 2.0 did not define this constant, hence this hack.
  918. (let ((variable (module-variable the-root-module 'AT_SYMLINK_NOFOLLOW)))
  919. (if variable
  920. (variable-ref variable)
  921. 256))) ;for GNU/Linux
  922. (define (set-file-time file stat)
  923. "Set the atime/mtime of FILE to that specified by STAT."
  924. (utime file
  925. (stat:atime stat)
  926. (stat:mtime stat)
  927. (stat:atimensec stat)
  928. (stat:mtimensec stat)
  929. AT_SYMLINK_NOFOLLOW))
  930. (define (get-char* p)
  931. ;; We call it `get-char', but that's really a binary version
  932. ;; thereof. (The real `get-char' cannot be used here because our
  933. ;; bootstrap Guile is hacked to always use UTF-8.)
  934. (match (get-u8 p)
  935. ((? integer? x) (integer->char x))
  936. (x x)))
  937. (define patch-shebang
  938. (let ((shebang-rx (make-regexp "^[[:blank:]]*(/[[:graph:]]+)[[:blank:]]*([[:graph:]]*)(.*)$")))
  939. (lambda* (file
  940. #:optional
  941. (path (search-path-as-string->list (getenv "PATH")))
  942. #:key (keep-mtime? #t))
  943. "Replace the #! interpreter file name in FILE by a valid one found in
  944. PATH, when FILE actually starts with a shebang. Return #t when FILE was
  945. patched, #f otherwise. When KEEP-MTIME? is true, the atime/mtime of
  946. FILE are kept unchanged."
  947. (define (patch p interpreter rest-of-line)
  948. (let* ((template (string-append file ".XXXXXX"))
  949. (out (mkstemp! template))
  950. (st (stat file))
  951. (mode (stat:mode st)))
  952. (with-throw-handler #t
  953. (lambda ()
  954. (format out "#!~a~a~%"
  955. interpreter rest-of-line)
  956. (dump-port p out)
  957. (close out)
  958. (chmod template mode)
  959. (rename-file template file)
  960. (when keep-mtime?
  961. (set-file-time file st))
  962. #t)
  963. (lambda (key . args)
  964. (format (current-error-port)
  965. "patch-shebang: ~a: error: ~a ~s~%"
  966. file key args)
  967. (false-if-exception (delete-file template))
  968. #f))))
  969. (call-with-ascii-input-file file
  970. (lambda (p)
  971. (and (eq? #\# (get-char* p))
  972. (eq? #\! (get-char* p))
  973. (let ((line (false-if-exception (read-line p))))
  974. (and=> (and line (regexp-exec shebang-rx line))
  975. (lambda (m)
  976. (let* ((interp (match:substring m 1))
  977. (arg1 (match:substring m 2))
  978. (rest (match:substring m 3))
  979. (has-env (string-suffix? "/env" interp))
  980. (cmd (if has-env arg1 (basename interp)))
  981. (bin (search-path path cmd)))
  982. (if bin
  983. (if (string=? bin interp)
  984. #f ; nothing to do
  985. (if has-env
  986. (begin
  987. (format (current-error-port)
  988. "patch-shebang: ~a: changing `~a' to `~a'~%"
  989. file (string-append interp " " arg1) bin)
  990. (patch p bin rest))
  991. (begin
  992. (format (current-error-port)
  993. "patch-shebang: ~a: changing `~a' to `~a'~%"
  994. file interp bin)
  995. (patch p bin
  996. (if (string-null? arg1)
  997. ""
  998. (string-append " " arg1 rest))))))
  999. (begin
  1000. (format (current-error-port)
  1001. "patch-shebang: ~a: warning: no binary for interpreter `~a' found in $PATH~%"
  1002. file (basename cmd))
  1003. #f))))))))))))
  1004. (define* (patch-makefile-SHELL file #:key (keep-mtime? #t))
  1005. "Patch the `SHELL' variable in FILE, which is supposedly a makefile.
  1006. When KEEP-MTIME? is true, the atime/mtime of FILE are kept unchanged."
  1007. ;; For instance, Gettext-generated po/Makefile.in.in do not honor $SHELL.
  1008. ;; XXX: Unlike with `patch-shebang', FILE is always touched.
  1009. (define (find-shell name)
  1010. (let ((shell (which name)))
  1011. (unless shell
  1012. (format (current-error-port)
  1013. "patch-makefile-SHELL: warning: no binary for shell `~a' found in $PATH~%"
  1014. name))
  1015. shell))
  1016. (let ((st (stat file)))
  1017. ;; Consider FILE is using an 8-bit encoding to avoid errors.
  1018. (with-fluids ((%default-port-encoding #f))
  1019. (substitute* file
  1020. (("^ *SHELL[[:blank:]]*:?=[[:blank:]]*([[:graph:]]*/)([[:graph:]]+)(.*)$"
  1021. _ dir shell args)
  1022. (let* ((old (string-append dir shell))
  1023. (new (or (find-shell shell) old)))
  1024. (unless (string=? new old)
  1025. (format (current-error-port)
  1026. "patch-makefile-SHELL: ~a: changing `SHELL' from `~a' to `~a'~%"
  1027. file old new))
  1028. (string-append "SHELL = " new args)))))
  1029. (when keep-mtime?
  1030. (set-file-time file st))))
  1031. (define* (patch-/usr/bin/file file
  1032. #:key
  1033. (file-command (which "file"))
  1034. (keep-mtime? #t))
  1035. "Patch occurrences of \"/usr/bin/file\" in FILE, replacing them with
  1036. FILE-COMMAND. When KEEP-MTIME? is true, keep FILE's modification time
  1037. unchanged."
  1038. (if (not file-command)
  1039. (format (current-error-port)
  1040. "patch-/usr/bin/file: warning: \
  1041. no replacement 'file' command, doing nothing~%")
  1042. (let ((st (stat file)))
  1043. ;; Consider FILE is using an 8-bit encoding to avoid errors.
  1044. (with-fluids ((%default-port-encoding #f))
  1045. (substitute* file
  1046. (("/usr/bin/file")
  1047. (begin
  1048. (format (current-error-port)
  1049. "patch-/usr/bin/file: ~a: changing `~a' to `~a'~%"
  1050. file "/usr/bin/file" file-command)
  1051. file-command))))
  1052. (when keep-mtime?
  1053. (set-file-time file st)))))
  1054. (define* (fold-port-matches proc init pattern port
  1055. #:optional (unmatched (lambda (_ r) r)))
  1056. "Read from PORT character-by-character; for each match against
  1057. PATTERN, call (PROC MATCH RESULT), where RESULT is seeded with INIT.
  1058. PATTERN is a list of SRFI-14 char-sets. Call (UNMATCHED CHAR RESULT)
  1059. for each unmatched character."
  1060. (define initial-pattern
  1061. ;; The poor developer's regexp.
  1062. (if (string? pattern)
  1063. (map char-set (string->list pattern))
  1064. pattern))
  1065. ;; Note: we're not really striving for performance here...
  1066. (let loop ((chars '())
  1067. (pattern initial-pattern)
  1068. (matched '())
  1069. (result init))
  1070. (cond ((null? chars)
  1071. (loop (list (get-char* port))
  1072. pattern
  1073. matched
  1074. result))
  1075. ((null? pattern)
  1076. (loop chars
  1077. initial-pattern
  1078. '()
  1079. (proc (list->string (reverse matched)) result)))
  1080. ((eof-object? (car chars))
  1081. (fold-right unmatched result matched))
  1082. ((char-set-contains? (car pattern) (car chars))
  1083. (loop (cdr chars)
  1084. (cdr pattern)
  1085. (cons (car chars) matched)
  1086. result))
  1087. ((null? matched) ; common case
  1088. (loop (cdr chars)
  1089. pattern
  1090. matched
  1091. (unmatched (car chars) result)))
  1092. (else
  1093. (let ((matched (reverse matched)))
  1094. (loop (append (cdr matched) chars)
  1095. initial-pattern
  1096. '()
  1097. (unmatched (car matched) result)))))))
  1098. (define* (remove-store-references file
  1099. #:optional (store (%store-directory)))
  1100. "Remove from FILE occurrences of file names in STORE; return #t when
  1101. store paths were encountered in FILE, #f otherwise. This procedure is
  1102. known as `nuke-refs' in Nixpkgs."
  1103. (define pattern
  1104. (let ((nix-base32-chars
  1105. '(#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9
  1106. #\a #\b #\c #\d #\f #\g #\h #\i #\j #\k #\l #\m #\n
  1107. #\p #\q #\r #\s #\v #\w #\x #\y #\z)))
  1108. `(,@(map char-set (string->list store))
  1109. ,(char-set #\/)
  1110. ,@(make-list 32 (list->char-set nix-base32-chars))
  1111. ,(char-set #\-))))
  1112. (with-fluids ((%default-port-encoding #f))
  1113. (with-atomic-file-replacement file
  1114. (lambda (in out)
  1115. ;; We cannot use `regexp-exec' here because it cannot deal with
  1116. ;; strings containing NUL characters.
  1117. (format #t "removing store references from `~a'...~%" file)
  1118. (setvbuf in 'block 65536)
  1119. (setvbuf out 'block 65536)
  1120. (fold-port-matches (lambda (match result)
  1121. (put-bytevector out (string->utf8 store))
  1122. (put-u8 out (char->integer #\/))
  1123. (put-bytevector out
  1124. (string->utf8
  1125. "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee-"))
  1126. #t)
  1127. #f
  1128. pattern
  1129. in
  1130. (lambda (char result)
  1131. (put-u8 out (char->integer char))
  1132. result))))))
  1133. (define-condition-type &wrap-error &error
  1134. wrap-error?
  1135. (program wrap-error-program)
  1136. (type wrap-error-type))
  1137. (define (wrapped-program? prog)
  1138. "Return #t if PROG is a program that was moved and wrapped by 'wrap-program'."
  1139. (and (file-exists? prog)
  1140. (let ((base (basename prog)))
  1141. (and (string-prefix? "." base)
  1142. (string-suffix? "-real" base)))))
  1143. (define* (wrap-program prog #:key (sh (which "bash")) #:rest vars)
  1144. "Make a wrapper for PROG. VARS should look like this:
  1145. '(VARIABLE DELIMITER POSITION LIST-OF-DIRECTORIES)
  1146. where DELIMITER is optional. ':' will be used if DELIMITER is not given.
  1147. For example, this command:
  1148. (wrap-program \"foo\"
  1149. '(\"PATH\" \":\" = (\"/gnu/.../bar/bin\"))
  1150. '(\"CERT_PATH\" suffix (\"/gnu/.../baz/certs\"
  1151. \"/qux/certs\")))
  1152. will copy 'foo' to '.foo-real' and create the file 'foo' with the following
  1153. contents:
  1154. #!location/of/bin/bash
  1155. export PATH=\"/gnu/.../bar/bin\"
  1156. export CERT_PATH=\"$CERT_PATH${CERT_PATH:+:}/gnu/.../baz/certs:/qux/certs\"
  1157. exec -a $0 location/of/.foo-real \"$@\"
  1158. This is useful for scripts that expect particular programs to be in $PATH, for
  1159. programs that expect particular shared libraries to be in $LD_LIBRARY_PATH, or
  1160. modules in $GUILE_LOAD_PATH, etc.
  1161. If PROG has previously been wrapped by 'wrap-program', the wrapper is extended
  1162. with definitions for VARS. If it is not, SH will be used as interpreter."
  1163. (define vars/filtered
  1164. (match vars
  1165. ((#:sh _ . vars) vars)
  1166. (vars vars)))
  1167. (define wrapped-file
  1168. (string-append (dirname prog) "/." (basename prog) "-real"))
  1169. (define already-wrapped?
  1170. (file-exists? wrapped-file))
  1171. (define (last-line port)
  1172. ;; Return the last line read from PORT and leave PORT's cursor right
  1173. ;; before it.
  1174. (let loop ((previous-line-offset 0)
  1175. (previous-line "")
  1176. (position (seek port 0 SEEK_CUR)))
  1177. (match (read-line port 'concat)
  1178. ((? eof-object?)
  1179. (seek port previous-line-offset SEEK_SET)
  1180. previous-line)
  1181. ((? string? line)
  1182. (loop position line (+ (string-length line) position))))))
  1183. (define (export-variable lst)
  1184. ;; Return a string that exports an environment variable.
  1185. (match lst
  1186. ((var sep '= rest)
  1187. (format #f "export ~a=\"~a\""
  1188. var (string-join rest sep)))
  1189. ((var sep 'prefix rest)
  1190. (format #f "export ~a=\"~a${~a:+~a}$~a\""
  1191. var (string-join rest sep) var sep var))
  1192. ((var sep 'suffix rest)
  1193. (format #f "export ~a=\"$~a${~a+~a}~a\""
  1194. var var var sep (string-join rest sep)))
  1195. ((var '= rest)
  1196. (format #f "export ~a=\"~a\""
  1197. var (string-join rest ":")))
  1198. ((var 'prefix rest)
  1199. (format #f "export ~a=\"~a${~a:+:}$~a\""
  1200. var (string-join rest ":") var var))
  1201. ((var 'suffix rest)
  1202. (format #f "export ~a=\"$~a${~a:+:}~a\""
  1203. var var var (string-join rest ":")))))
  1204. (when (wrapped-program? prog)
  1205. (error (string-append prog " is a wrapper. Refusing to wrap.")))
  1206. (if already-wrapped?
  1207. ;; PROG is already a wrapper: add the new "export VAR=VALUE" lines just
  1208. ;; before the last line.
  1209. (let* ((port (open-file prog "r+"))
  1210. (last (last-line port)))
  1211. (for-each (lambda (var)
  1212. (display (export-variable var) port)
  1213. (newline port))
  1214. vars/filtered)
  1215. (display last port)
  1216. (close-port port))
  1217. ;; PROG is not wrapped yet: create a shell script that sets VARS.
  1218. (let ((prog-tmp (string-append wrapped-file "-tmp")))
  1219. (link prog wrapped-file)
  1220. (call-with-output-file prog-tmp
  1221. (lambda (port)
  1222. (format port
  1223. "#!~a~%~a~%exec -a \"$0\" \"~a\" \"$@\"~%"
  1224. sh
  1225. (string-join (map export-variable vars/filtered) "\n")
  1226. (canonicalize-path wrapped-file))))
  1227. (chmod prog-tmp #o755)
  1228. (rename-file prog-tmp prog))))
  1229. (define wrap-script
  1230. (let ((interpreter-regex
  1231. (make-regexp
  1232. (string-append "^#! ?(/[^ ]+/bin/("
  1233. (string-join '("python[^ ]*"
  1234. "Rscript"
  1235. "perl"
  1236. "ruby"
  1237. "bash"
  1238. "sh") "|")
  1239. "))( ?.*)")))
  1240. (coding-line-regex
  1241. (make-regexp
  1242. ".*#.*coding[=:][[:space:]]*([-a-zA-Z_0-9.]+)")))
  1243. (lambda* (prog #:key (guile (which "guile")) #:rest vars)
  1244. "Wrap the script PROG such that VARS are set first. The format of VARS
  1245. is the same as in the WRAP-PROGRAM procedure. This procedure differs from
  1246. WRAP-PROGRAM in that it does not create a separate shell script. Instead,
  1247. PROG is modified directly by prepending a Guile script, which is interpreted
  1248. as a comment in the script's language.
  1249. Special encoding comments as supported by Python are recreated on the second
  1250. line.
  1251. Note that this procedure can only be used once per file as Guile scripts are
  1252. not supported."
  1253. (define update-env
  1254. (match-lambda
  1255. ((var sep '= rest)
  1256. `(setenv ,var ,(string-join rest sep)))
  1257. ((var sep 'prefix rest)
  1258. `(let ((current (getenv ,var)))
  1259. (setenv ,var (if current
  1260. (string-append ,(string-join rest sep)
  1261. ,sep current)
  1262. ,(string-join rest sep)))))
  1263. ((var sep 'suffix rest)
  1264. `(let ((current (getenv ,var)))
  1265. (setenv ,var (if current
  1266. (string-append current ,sep
  1267. ,(string-join rest sep))
  1268. ,(string-join rest sep)))))
  1269. ((var '= rest)
  1270. `(setenv ,var ,(string-join rest ":")))
  1271. ((var 'prefix rest)
  1272. `(let ((current (getenv ,var)))
  1273. (setenv ,var (if current
  1274. (string-append ,(string-join rest ":")
  1275. ":" current)
  1276. ,(string-join rest ":")))))
  1277. ((var 'suffix rest)
  1278. `(let ((current (getenv ,var)))
  1279. (setenv ,var (if current
  1280. (string-append current ":"
  1281. ,(string-join rest ":"))
  1282. ,(string-join rest ":")))))))
  1283. (let-values (((interpreter args coding-line)
  1284. (call-with-ascii-input-file prog
  1285. (lambda (p)
  1286. (let ((first-match
  1287. (false-if-exception
  1288. (regexp-exec interpreter-regex (read-line p)))))
  1289. (values (and first-match (match:substring first-match 1))
  1290. (and first-match (match:substring first-match 3))
  1291. (false-if-exception
  1292. (and=> (regexp-exec coding-line-regex (read-line p))
  1293. (lambda (m) (match:substring m 0))))))))))
  1294. (if interpreter
  1295. (let* ((header (format #f "\
  1296. #!~a --no-auto-compile
  1297. #!#; ~a
  1298. #\\-~s
  1299. #\\-~s
  1300. "
  1301. guile
  1302. (or coding-line "Guix wrapper")
  1303. (cons 'begin (map update-env
  1304. (match vars
  1305. ((#:guile _ . vars) vars)
  1306. (_ vars))))
  1307. `(let ((cl (command-line)))
  1308. (apply execl ,interpreter
  1309. (car cl)
  1310. (append
  1311. ',(string-tokenize args char-set:graphic)
  1312. cl)))))
  1313. (template (string-append prog ".XXXXXX"))
  1314. (out (mkstemp! template))
  1315. (st (stat prog))
  1316. (mode (stat:mode st)))
  1317. (with-throw-handler #t
  1318. (lambda ()
  1319. (call-with-ascii-input-file prog
  1320. (lambda (p)
  1321. (display header out)
  1322. (dump-port p out)
  1323. (close out)
  1324. (chmod template mode)
  1325. (rename-file template prog)
  1326. (set-file-time prog st))))
  1327. (lambda (key . args)
  1328. (format (current-error-port)
  1329. "wrap-script: ~a: error: ~a ~s~%"
  1330. prog key args)
  1331. (false-if-exception (delete-file template))
  1332. (raise (condition
  1333. (&wrap-error (program prog)
  1334. (type key))))
  1335. #f)))
  1336. (raise (condition
  1337. (&wrap-error (program prog)
  1338. (type 'no-interpreter-found)))))))))
  1339. (define* (make-desktop-entry-file destination #:key
  1340. (type "Application") ; One of "Application", "Link" or "Directory".
  1341. (version "1.1")
  1342. name
  1343. (generic-name name)
  1344. (no-display #f)
  1345. comment
  1346. icon
  1347. (hidden #f)
  1348. only-show-in
  1349. not-show-in
  1350. (d-bus-activatable #f)
  1351. try-exec
  1352. exec
  1353. path
  1354. (terminal #f)
  1355. actions
  1356. mime-type
  1357. (categories "Application")
  1358. implements
  1359. keywords
  1360. (startup-notify #t)
  1361. startup-w-m-class
  1362. #:rest all-args)
  1363. "Create a desktop entry file at DESTINATION.
  1364. You must specify NAME.
  1365. Values can be booleans, numbers, strings or list of strings.
  1366. Additionally, locales can be specified with an alist where the key is the
  1367. locale. The #f key specifies the default. Example:
  1368. #:name '((#f \"I love Guix\") (\"fr\" \"J'aime Guix\"))
  1369. produces
  1370. Name=I love Guix
  1371. Name[fr]=J'aime Guix
  1372. For a complete description of the format, see the specifications at
  1373. https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html."
  1374. (define (escape-semicolon s)
  1375. (string-join (string-split s #\;) "\\;"))
  1376. (define* (parse key value #:optional locale)
  1377. (set! value (match value
  1378. (#t "true")
  1379. (#f "false")
  1380. ((? number? n) n)
  1381. ((? string? s) (escape-semicolon s))
  1382. ((? list? value)
  1383. (catch 'wrong-type-arg
  1384. (lambda () (string-join (map escape-semicolon value) ";"))
  1385. (lambda args (error "List arguments can only contain strings: ~a" args))))
  1386. (_ (error "Value must be a boolean, number, string or list of strings"))))
  1387. (format #t "~a=~a~%"
  1388. (if locale
  1389. (format #f "~a[~a]" key locale)
  1390. key)
  1391. value))
  1392. (define key-error-message "This procedure only takes key arguments beside DESTINATION")
  1393. (unless name
  1394. (error "Missing NAME key argument"))
  1395. (unless (member #:type all-args)
  1396. (set! all-args (append (list #:type type) all-args)))
  1397. (mkdir-p (dirname destination))
  1398. (with-output-to-file destination
  1399. (lambda ()
  1400. (format #t "[Desktop Entry]~%")
  1401. (let loop ((args all-args))
  1402. (match args
  1403. (() #t)
  1404. ((_) (error key-error-message))
  1405. ((key value . ...)
  1406. (unless (keyword? key)
  1407. (error key-error-message))
  1408. (set! key
  1409. (string-join (map string-titlecase
  1410. (string-split (symbol->string
  1411. (keyword->symbol key))
  1412. #\-))
  1413. ""))
  1414. (match value
  1415. (((_ . _) . _)
  1416. (for-each (lambda (locale-subvalue)
  1417. (parse key
  1418. (if (and (list? (cdr locale-subvalue))
  1419. (= 1 (length (cdr locale-subvalue))))
  1420. ;; Support both proper and improper lists for convenience.
  1421. (cadr locale-subvalue)
  1422. (cdr locale-subvalue))
  1423. (car locale-subvalue)))
  1424. value))
  1425. (_
  1426. (parse key value)))
  1427. (loop (cddr args))))))))
  1428. ;;;
  1429. ;;; Locales.
  1430. ;;;
  1431. (define (locale-category->string category)
  1432. "Return the name of locale category CATEGORY, one of the 'LC_' constants.
  1433. If CATEGORY is a bitwise or of several 'LC_' constants, an approximation is
  1434. returned."
  1435. (letrec-syntax ((convert (syntax-rules ()
  1436. ((_)
  1437. (number->string category))
  1438. ((_ first rest ...)
  1439. (if (= first category)
  1440. (symbol->string 'first)
  1441. (convert rest ...))))))
  1442. (convert LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE
  1443. LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGES LC_MONETARY
  1444. LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE
  1445. LC_TIME)))
  1446. ;;; Local Variables:
  1447. ;;; eval: (put 'call-with-output-file/atomic 'scheme-indent-function 1)
  1448. ;;; eval: (put 'call-with-ascii-input-file 'scheme-indent-function 1)
  1449. ;;; eval: (put 'with-throw-handler 'scheme-indent-function 1)
  1450. ;;; eval: (put 'let-matches 'scheme-indent-function 3)
  1451. ;;; eval: (put 'with-atomic-file-replacement 'scheme-indent-function 1)
  1452. ;;; End: