utils.scm 64 KB

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