utils.scm 61 KB

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