utils.scm 55 KB

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