utils.scm 61 KB

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