utils.scm 51 KB

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