ui.scm 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195
  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, 2018 Mark H Weaver <mhw@netris.org>
  4. ;;; Copyright © 2013 Nikita Karetnikov <nikita@karetnikov.org>
  5. ;;; Copyright © 2014 Cyril Roelandt <tipecaml@gmail.com>
  6. ;;; Copyright © 2014 Cyrill Schenkel <cyrill.schenkel@gmail.com>
  7. ;;; Copyright © 2014, 2015, 2017 Alex Kost <alezost@gmail.com>
  8. ;;; Copyright © 2015 David Thompson <davet@gnu.org>
  9. ;;; Copyright © 2015, 2016 Mathieu Lirzin <mthl@gnu.org>
  10. ;;; Copyright © 2016 Roel Janssen <roel@gnu.org>
  11. ;;; Copyright © 2016 Benz Schenk <benz.schenk@uzh.ch>
  12. ;;; Copyright © 2018 Kyle Meyer <kyle@kyleam.com>
  13. ;;; Copyright © 2018 Ricardo Wurmus <rekado@elephly.net>
  14. ;;; Copyright © 2019 Chris Marusich <cmmarusich@gmail.com>
  15. ;;; Copyright © 2019, 2020 Tobias Geerinckx-Rice <me@tobias.gr>
  16. ;;; Copyright © 2019, 2021 Simon Tournier <zimon.toutoune@gmail.com>
  17. ;;; Copyright © 2020 Arun Isaac <arunisaac@systemreboot.net>
  18. ;;; Copyright © 2020 Maxim Cournoyer <maxim.cournoyer@gmail.com>
  19. ;;;
  20. ;;; This file is part of GNU Guix.
  21. ;;;
  22. ;;; GNU Guix is free software; you can redistribute it and/or modify it
  23. ;;; under the terms of the GNU General Public License as published by
  24. ;;; the Free Software Foundation; either version 3 of the License, or (at
  25. ;;; your option) any later version.
  26. ;;;
  27. ;;; GNU Guix is distributed in the hope that it will be useful, but
  28. ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
  29. ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  30. ;;; GNU General Public License for more details.
  31. ;;;
  32. ;;; You should have received a copy of the GNU General Public License
  33. ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
  34. (define-module (guix ui)
  35. #:use-module (guix i18n)
  36. #:use-module (guix colors)
  37. #:use-module (guix diagnostics)
  38. #:use-module (guix gexp)
  39. #:use-module (guix sets)
  40. #:use-module (guix utils)
  41. #:use-module (guix store)
  42. #:use-module (guix config)
  43. #:use-module (guix packages)
  44. #:use-module (guix profiles)
  45. #:use-module (guix derivations)
  46. #:use-module (guix build-system)
  47. #:use-module (guix serialization)
  48. #:use-module ((guix licenses)
  49. #:select (license? license-name license-uri))
  50. #:use-module ((guix build syscalls)
  51. #:select (free-disk-space terminal-columns terminal-rows
  52. with-file-lock/no-wait))
  53. #:use-module ((guix build utils)
  54. ;; XXX: All we need are the bindings related to
  55. ;; '&invoke-error'. However, to work around the bug described
  56. ;; in 5d669883ecc104403c5d3ba7d172e9c02234577c, #:hide
  57. ;; unwanted bindings instead of #:select'ing the needed
  58. ;; bindings.
  59. #:hide (package-name->name+version
  60. ;; Avoid "overrides core binding" warning.
  61. delete))
  62. #:use-module (srfi srfi-1)
  63. #:use-module (srfi srfi-9 gnu)
  64. #:use-module (srfi srfi-11)
  65. #:use-module (srfi srfi-19)
  66. #:use-module (srfi srfi-26)
  67. #:use-module (srfi srfi-31)
  68. #:use-module (srfi srfi-34)
  69. #:use-module (srfi srfi-35)
  70. #:autoload (ice-9 ftw) (scandir)
  71. #:use-module (ice-9 match)
  72. #:use-module (ice-9 format)
  73. #:use-module (ice-9 regex)
  74. #:autoload (ice-9 popen) (open-pipe* close-pipe)
  75. #:autoload (system repl repl) (start-repl)
  76. #:autoload (system repl debug) (make-debug stack->vector)
  77. #:autoload (web uri) (encode-and-join-uri-path)
  78. #:use-module (texinfo)
  79. #:use-module (texinfo plain-text)
  80. #:use-module (texinfo string-utils)
  81. ;; Re-exports for backward compatibility.
  82. #:re-export (G_ N_ P_ ;now in (guix i18n)
  83. warning info report-error leave ;now in (guix diagnostics)
  84. location->string
  85. guix-warning-port program-name)
  86. #:export (display-hint
  87. make-user-module
  88. load*
  89. warn-about-load-error
  90. show-version-and-exit
  91. show-bug-report-information
  92. make-regexp*
  93. string->number*
  94. size->number
  95. show-derivation-outputs
  96. build-notifier
  97. show-what-to-build
  98. show-what-to-build*
  99. show-manifest-transaction
  100. guard*
  101. call-with-error-handling
  102. with-error-handling
  103. with-unbound-variable-handling
  104. leave-on-EPIPE
  105. read/eval
  106. read/eval-package-expression
  107. check-available-space
  108. indented-string
  109. fill-paragraph
  110. %text-width
  111. texi->plain-text
  112. package-description-string
  113. package-synopsis-string
  114. string->recutils
  115. package->recutils
  116. package-specification->name+version+output
  117. supports-hyperlinks?
  118. hyperlink
  119. file-hyperlink
  120. location->hyperlink
  121. with-paginated-output-port
  122. relevance
  123. package-relevance
  124. display-search-results
  125. with-profile-lock
  126. string->generations
  127. string->duration
  128. matching-generations
  129. display-generation
  130. display-profile-content
  131. display-profile-content-diff
  132. roll-back*
  133. switch-to-generation*
  134. delete-generation*
  135. %default-message-language
  136. current-message-language
  137. run-guix-command
  138. run-guix
  139. guix-main))
  140. ;;; Commentary:
  141. ;;;
  142. ;;; User interface facilities for command-line tools.
  143. ;;;
  144. ;;; Code:
  145. (define (print-unbound-variable-error port key args default-printer)
  146. ;; Print unbound variable errors more nicely, and in the right language.
  147. (match args
  148. ((proc message (variable) _ ...)
  149. ;; We can always omit PROC because when it's useful (i.e., different from
  150. ;; "module-lookup"), it gets displayed before.
  151. (format port (G_ "error: ~a: unbound variable") variable))
  152. (_
  153. (default-printer))))
  154. (set-exception-printer! 'unbound-variable print-unbound-variable-error)
  155. (define (make-user-module modules)
  156. "Return a new user module with the additional MODULES loaded."
  157. ;; Module in which the machine description file is loaded.
  158. (let ((module (make-fresh-user-module)))
  159. (for-each (lambda (iface)
  160. (module-use! module (resolve-interface iface)))
  161. modules)
  162. module))
  163. (define (last-frame-with-source stack)
  164. "Walk stack upwards and return the last frame that has source location
  165. information, or #f if it could not be found."
  166. (define (frame-with-source frame)
  167. ;; Walk from FRAME upwards until source location information is found.
  168. (let loop ((frame frame)
  169. (previous frame))
  170. (if (not frame)
  171. previous
  172. ;; On Guile 3, the latest frame with source may be that of
  173. ;; 'raise-exception' in boot-9.scm. Skip it.
  174. (if (and (frame-source frame)
  175. (not (eq? 'raise-exception (frame-procedure-name frame))))
  176. frame
  177. (loop (frame-previous frame) frame)))))
  178. (let* ((depth (stack-length stack))
  179. (last (and (> depth 0) (stack-ref stack 0))))
  180. (frame-with-source (if (> depth 1)
  181. (stack-ref stack 1) ;skip the 'throw' frame
  182. last))))
  183. (define-syntax-rule (without-compiler-optimizations exp)
  184. ;; Compile with the baseline compiler (-O1), which is much less expensive
  185. ;; than -O2.
  186. (parameterize (((@ (system base compile) default-optimization-level) 1))
  187. exp))
  188. (define* (load* file user-module
  189. #:key (on-error 'nothing-special))
  190. "Load the user provided Scheme source code FILE."
  191. (define (error-string frame args)
  192. (call-with-output-string
  193. (lambda (port)
  194. (apply display-error frame port (cdr args)))))
  195. (define tag
  196. (make-prompt-tag "user-code"))
  197. (catch #t
  198. (lambda ()
  199. ;; XXX: Force a recompilation to avoid ABI issues.
  200. (set! %fresh-auto-compile #t)
  201. (set! %load-should-auto-compile #t)
  202. (save-module-excursion
  203. (lambda ()
  204. (set-current-module user-module)
  205. ;; Hide the "auto-compiling" messages.
  206. (parameterize ((current-warning-port (%make-void-port "w")))
  207. (call-with-prompt tag
  208. (lambda ()
  209. ;; Give 'load' an absolute file name so that it doesn't try to
  210. ;; search for FILE in %LOAD-PATH. Note: use 'load', not
  211. ;; 'primitive-load', so that FILE is compiled, which then allows
  212. ;; us to provide better error reporting with source line numbers.
  213. (without-compiler-optimizations
  214. (load (canonicalize-path file))))
  215. (const #f))))))
  216. (lambda _
  217. ;; XXX: Errors are reported from the pre-unwind handler below, but
  218. ;; calling 'exit' from there has no effect, so we call it here.
  219. (exit 1))
  220. (rec (handle-error . args)
  221. ;; Capture the stack up to this procedure call, excluded, and pass
  222. ;; the faulty stack frame to 'report-load-error'.
  223. (let* ((stack (make-stack #t handle-error tag))
  224. (frame (last-frame-with-source stack)))
  225. (report-load-error file args frame)
  226. (case on-error
  227. ((debug)
  228. (newline)
  229. (display (G_ "entering debugger; type ',bt' for a backtrace\n"))
  230. (start-repl #:debug (make-debug (stack->vector stack) 0
  231. (error-string frame args)
  232. #f)))
  233. ((backtrace)
  234. (newline (current-error-port))
  235. (display-backtrace stack (current-error-port)))
  236. (else
  237. #t))))))
  238. (define (known-variable-definition variable)
  239. "Search among the currently loaded modules one that defines a variable named
  240. VARIABLE and return it, or #f if none was found."
  241. (define (module<? m1 m2)
  242. (match (module-name m2)
  243. (('gnu _ ...) #t)
  244. (('guix _ ...)
  245. (match (module-name m1)
  246. (('gnu _ ...) #f)
  247. (_ #t)))
  248. (_ #f)))
  249. (let loop ((modules (list (resolve-module '() #f #f #:ensure #f)))
  250. (suggestions '())
  251. (visited (setq)))
  252. (match modules
  253. (()
  254. ;; Pick the "best" suggestion.
  255. (match (sort suggestions module<?)
  256. (() #f)
  257. ((first _ ...) first)))
  258. ((head tail ...)
  259. (if (set-contains? visited head)
  260. (loop tail suggestions visited)
  261. (let ((visited (set-insert head visited))
  262. (next (append tail
  263. (hash-map->list (lambda (name module)
  264. module)
  265. (module-submodules head)))))
  266. (match (and=> (module-public-interface head)
  267. (cut module-local-variable <> variable))
  268. (#f (loop next suggestions visited))
  269. (_
  270. (match (module-name head)
  271. (('gnu _ ...) head) ;must be that one
  272. (_ (loop next (cons head suggestions) visited)))))))))))
  273. (define %hint-color (color BOLD CYAN))
  274. (define* (display-hint message #:optional (port (current-error-port)))
  275. "Display MESSAGE, a l10n message possibly containing Texinfo markup, to
  276. PORT."
  277. (define colorize
  278. (if (color-output? port)
  279. (lambda (str)
  280. (colorize-string str %hint-color))
  281. identity))
  282. (display (colorize (G_ "hint: ")) port)
  283. (display
  284. ;; XXX: We should arrange so that the initial indent is wider.
  285. (parameterize ((%text-width (max 15 (- (terminal-columns) 5))))
  286. (texi->plain-text message))
  287. port))
  288. (define* (report-unbound-variable-error args #:key frame)
  289. "Return the given unbound-variable error, where ARGS is the list of 'throw'
  290. arguments."
  291. (match args
  292. ((key . args)
  293. (print-exception (current-error-port) frame key args)))
  294. (match args
  295. (('unbound-variable proc message (variable) _ ...)
  296. (match (known-variable-definition variable)
  297. (#f
  298. (display-hint (G_ "Did you forget a @code{use-modules} form?")))
  299. ((? module? module)
  300. (display-hint (format #f (G_ "Did you forget @code{(use-modules ~a)}?")
  301. (module-name module))))))))
  302. (define (check-module-matches-file module file)
  303. "Check whether FILE starts with 'define-module MODULE' and print a hint if
  304. it doesn't."
  305. ;; This is a common mistake when people start writing their own package
  306. ;; definitions and try loading them with 'guix build -L …', so help them
  307. ;; diagnose the problem.
  308. (define (hint)
  309. (display-hint (format #f (G_ "File @file{~a} should probably start with:
  310. @example\n(define-module ~a)\n@end example")
  311. file module)))
  312. (catch 'system-error
  313. (lambda ()
  314. (let* ((sexp (call-with-input-file file read))
  315. (loc (and (pair? sexp)
  316. (source-properties->location (source-properties sexp)))))
  317. (match sexp
  318. (('define-module (names ...) _ ...)
  319. (unless (equal? module names)
  320. (warning loc
  321. (G_ "module name ~a does not match file name '~a'~%")
  322. names (module->source-file-name module))
  323. (hint)))
  324. ((? eof-object?)
  325. (warning (G_ "~a: file is empty~%") file))
  326. (else
  327. (hint)))))
  328. (const #f)))
  329. (define* (report-load-error file args #:optional frame)
  330. "Report the failure to load FILE, a user-provided Scheme file.
  331. ARGS is the list of arguments received by the 'throw' handler."
  332. (match args
  333. (('system-error . rest)
  334. (let ((err (system-error-errno args)))
  335. (report-error (G_ "failed to load '~a': ~a~%") file (strerror err))))
  336. (('read-error _ message args ...)
  337. ;; Guile's missing-paren messages are obscure so we make them more
  338. ;; intelligible here.
  339. (if (or (string-suffix? "end of file" message) ;Guile < 3.0.6
  340. (and (string-contains message "unexpected end of input")
  341. (member '(#\)) args)))
  342. (let ((location (string-take message
  343. (+ 2 (string-contains message ": ")))))
  344. (format (current-error-port) (G_ "~amissing closing parenthesis~%")
  345. location))
  346. (apply throw args)))
  347. (('syntax-error proc message properties form subform . rest)
  348. (let ((loc (source-properties->location properties)))
  349. (report-error loc (G_ "~s: ~a~%")
  350. (or subform form) message)))
  351. (('unbound-variable _ ...)
  352. (report-unbound-variable-error args #:frame frame))
  353. (((or 'srfi-34 '%exception) obj)
  354. (cond ((message-condition? obj)
  355. (report-error (and (error-location? obj)
  356. (error-location obj))
  357. (G_ "~a~%")
  358. (gettext (condition-message obj) %gettext-domain)))
  359. ((formatted-message? obj)
  360. (apply report-error
  361. (and (error-location? obj) (error-location obj))
  362. (gettext (formatted-message-string obj) %gettext-domain)
  363. (formatted-message-arguments obj)))
  364. (else
  365. (report-error (G_ "exception thrown: ~s~%") obj)))
  366. (when (fix-hint? obj)
  367. (display-hint (condition-fix-hint obj))))
  368. ((key args ...)
  369. (report-error (G_ "failed to load '~a':~%") file)
  370. (match args
  371. (((? symbol? proc) (? string? message) (args ...) . rest)
  372. (display-error frame (current-error-port) proc message
  373. args rest))
  374. (_
  375. ;; Some exceptions like 'git-error' do not follow Guile's convention
  376. ;; above and need to be printed with 'print-exception'.
  377. (print-exception (current-error-port) frame key args))))))
  378. (define (warn-about-load-error file module args) ;FIXME: factorize with ↑
  379. "Report the failure to load FILE, a user-provided Scheme file, without
  380. exiting. ARGS is the list of arguments received by the 'throw' handler."
  381. (match args
  382. (('system-error . rest)
  383. (let ((err (system-error-errno args)))
  384. (warning (G_ "failed to load '~a': ~a~%") module (strerror err))))
  385. (('syntax-error proc message properties form . rest)
  386. (let ((loc (source-properties->location properties)))
  387. (warning loc (G_ "~a~%") message)))
  388. (('unbound-variable _ ...)
  389. (report-unbound-variable-error args))
  390. (((or 'srfi-34 '%exception) obj)
  391. (cond ((message-condition? obj)
  392. (warning (G_ "failed to load '~a': ~a~%")
  393. file
  394. (gettext (condition-message obj) %gettext-domain)))
  395. ((formatted-message? obj)
  396. (warning (G_ "failed to load '~a': ~a~%")
  397. file
  398. (apply format #f
  399. (gettext (formatted-message-string obj)
  400. %gettext-domain)
  401. (formatted-message-arguments obj))))
  402. (else
  403. (warning (G_ "failed to load '~a': exception thrown: ~s~%")
  404. file obj))))
  405. ((error args ...)
  406. (warning (G_ "failed to load '~a':~%") module)
  407. (apply display-error #f (current-error-port) args)
  408. (check-module-matches-file module file))))
  409. (define (call-with-unbound-variable-handling thunk)
  410. (define tag
  411. (make-prompt-tag "user-code"))
  412. (catch 'unbound-variable
  413. (lambda ()
  414. (call-with-prompt tag
  415. thunk
  416. (const #f)))
  417. (const #t)
  418. (rec (handle-error . args)
  419. (let* ((stack (make-stack #t handle-error tag))
  420. (frame (and stack (last-frame-with-source stack))))
  421. (report-unbound-variable-error args #:frame frame)
  422. (exit 1)))))
  423. (define-syntax-rule (with-unbound-variable-handling exp ...)
  424. "Capture 'unbound-variable' exceptions in the dynamic extent of EXP... and
  425. report them in a user-friendly way."
  426. (call-with-unbound-variable-handling (lambda () exp ...)))
  427. (define %default-message-language
  428. ;; Default language to use for messages.
  429. (make-parameter "en"))
  430. (define (current-message-language)
  431. "Return the language used for messages according to the current locale.
  432. Return %DEFAULT-MESSAGE-LANGUAGE if that information could not be obtained. The
  433. result is an ISO-639-2 language code such as \"ar\", without the territory
  434. part."
  435. (let ((locale (setlocale LC_MESSAGES)))
  436. (match (string-index locale #\_)
  437. (#f locale)
  438. (index (string-take locale index)))))
  439. (define (install-locale)
  440. "Install the current locale settings."
  441. (catch 'system-error
  442. (lambda _
  443. (setlocale LC_ALL ""))
  444. (lambda args
  445. (display-hint (G_ "Consider installing the @code{glibc-locales} package
  446. and defining @code{GUIX_LOCPATH}, along these lines:
  447. @example
  448. guix install glibc-locales
  449. export GUIX_LOCPATH=\"$HOME/.guix-profile/lib/locale\"
  450. @end example
  451. See the \"Application Setup\" section in the manual, for more info.\n"))
  452. ;; We're now running in the "C" locale. Try to install a UTF-8 locale
  453. ;; instead. This one is guaranteed to be available in 'guix' from 'guix
  454. ;; pull'.
  455. (false-if-exception (setlocale LC_ALL "en_US.utf8")))))
  456. (define (initialize-guix)
  457. "Perform the usual initialization for stand-alone Guix commands."
  458. ;; By default don't annoy users with deprecation warnings. In practice,
  459. ;; 'define-deprecated' in (ice-9 deprecated) arranges so that those warnings
  460. ;; are emitted at expansion-time only, but there are cases where they could
  461. ;; slip through, for instance when interpreting code.
  462. (unless (getenv "GUILE_WARN_DEPRECATED")
  463. (debug-disable 'warn-deprecated))
  464. (install-locale)
  465. (textdomain %gettext-domain)
  466. ;; Ignore SIGPIPE. If the daemon closes the connection, we prefer to be
  467. ;; notified via an EPIPE later.
  468. (sigaction SIGPIPE SIG_IGN)
  469. (setvbuf (current-output-port) 'line)
  470. (setvbuf (current-error-port) 'line))
  471. (define* (show-version-and-exit #:optional (command (car (command-line))))
  472. "Display version information for COMMAND and `(exit 0)'."
  473. (simple-format #t "~a (~a) ~a~%"
  474. command %guix-package-name %guix-version)
  475. (format #t "Copyright ~a 2021 ~a"
  476. ;; TRANSLATORS: Translate "(C)" to the copyright symbol
  477. ;; (C-in-a-circle), if this symbol is available in the user's
  478. ;; locale. Otherwise, do not translate "(C)"; leave it as-is. */
  479. (G_ "(C)")
  480. (G_ "the Guix authors\n"))
  481. (display (G_"\
  482. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
  483. This is free software: you are free to change and redistribute it.
  484. There is NO WARRANTY, to the extent permitted by law.
  485. "))
  486. (exit 0))
  487. (define (show-bug-report-information)
  488. ;; TRANSLATORS: The placeholder indicates the bug-reporting address for this
  489. ;; package. Please add another line saying "Report translation bugs to
  490. ;; ...\n" with the address for translation bugs (typically your translation
  491. ;; team's web or email address).
  492. (format #t (G_ "
  493. Report bugs to: ~a.") %guix-bug-report-address)
  494. (format #t (G_ "
  495. ~a home page: <~a>") %guix-package-name %guix-home-page-url)
  496. (format #t (G_ "
  497. General help using Guix and GNU software: <~a>")
  498. ;; TRANSLATORS: Change the "/en" bit of this URL appropriately if
  499. ;; the web site is translated in your language.
  500. (G_ "https://guix.gnu.org/en/help/"))
  501. (newline))
  502. (define (augmented-system-error-handler file)
  503. "Return a 'system-error' handler that mentions FILE in its message."
  504. (lambda (key proc fmt args errno)
  505. ;; Augment the FMT and ARGS with information about TARGET (this
  506. ;; information is missing as of Guile 2.0.11, making the exception
  507. ;; uninformative.)
  508. (apply throw key proc "~A: ~S"
  509. (list (strerror (car errno)) file)
  510. (list errno))))
  511. (define-syntax apply-formals
  512. (syntax-rules ()
  513. ((_ proc (args ...)) (proc args ...))
  514. ((_ proc (arg1 args ... . rest)) (apply proc arg1 args ... rest))))
  515. (define-syntax-rule (error-reporting-wrapper proc formals file)
  516. "Wrap PROC such that its 'system-error' exceptions are augmented to mention
  517. FILE."
  518. (let ((real-proc (@ (guile) proc)))
  519. (lambda formals
  520. (catch 'system-error
  521. (lambda ()
  522. (apply-formals real-proc formals))
  523. (augmented-system-error-handler file)))))
  524. (set! symlink
  525. ;; We 'set!' the global binding because (gnu build ...) modules and similar
  526. ;; typically don't use (guix ui).
  527. (error-reporting-wrapper symlink (source target) target))
  528. (set! copy-file
  529. ;; Note: here we use 'set!', not #:replace, because UIs typically use
  530. ;; 'copy-recursively', which doesn't use (guix ui).
  531. (error-reporting-wrapper copy-file (source target) target))
  532. (set! canonicalize-path
  533. (error-reporting-wrapper canonicalize-path (file) file))
  534. (set! delete-file
  535. (error-reporting-wrapper delete-file (file) file))
  536. (set! execlp
  537. (error-reporting-wrapper execlp (filename . args) filename))
  538. (define (make-regexp* regexp . flags)
  539. "Like 'make-regexp' but error out if REGEXP is invalid, reporting the error
  540. nicely."
  541. (catch 'regular-expression-syntax
  542. (lambda ()
  543. (apply make-regexp regexp flags))
  544. (lambda (key proc message . rest)
  545. (leave (G_ "'~a' is not a valid regular expression: ~a~%")
  546. regexp message))))
  547. (define (string->number* str)
  548. "Like `string->number', but error out with an error message on failure."
  549. (or (string->number str)
  550. (leave (G_ "~a: invalid number~%") str)))
  551. (define (size->number str)
  552. "Convert STR, a storage measurement representation such as \"1024\" or
  553. \"1MiB\", to a number of bytes. Raise an error if STR could not be
  554. interpreted."
  555. (define unit-pos
  556. (string-rindex str
  557. (char-set-union (char-set #\.) char-set:digit)))
  558. (define unit
  559. (and unit-pos (substring str (+ 1 unit-pos))))
  560. (let* ((numstr (if unit-pos
  561. (substring str 0 (+ 1 unit-pos))
  562. str))
  563. (num (string->number numstr)))
  564. (unless num
  565. (leave (G_ "invalid number: ~a~%") numstr))
  566. ((compose inexact->exact round)
  567. (* num
  568. (match unit
  569. ((or "KiB" "K" "k") (expt 2 10))
  570. ((or "MiB" "M") (expt 2 20))
  571. ((or "GiB" "G") (expt 2 30))
  572. ((or "TiB" "T") (expt 2 40))
  573. ((or "PiB" "P") (expt 2 50))
  574. ((or "EiB" "E") (expt 2 60))
  575. ((or "ZiB" "Z") (expt 2 70))
  576. ((or "YiB" "Y") (expt 2 80))
  577. ("kB" (expt 10 3))
  578. ("MB" (expt 10 6))
  579. ("GB" (expt 10 9))
  580. ("TB" (expt 10 12))
  581. ("PB" (expt 10 15))
  582. ("EB" (expt 10 18))
  583. ("ZB" (expt 10 21))
  584. ("YB" (expt 10 24))
  585. ("" 1)
  586. (x
  587. (leave (G_ "unknown unit: ~a~%") unit)))))))
  588. (define (display-collision-resolution-hint collision)
  589. "Display hints on how to resolve COLLISION, a &profile-collistion-error."
  590. (define (top-most-entry entry)
  591. (let loop ((entry entry))
  592. (match (force (manifest-entry-parent entry))
  593. (#f entry)
  594. (parent (loop parent)))))
  595. (let* ((first (profile-collision-error-entry collision))
  596. (second (profile-collision-error-conflict collision))
  597. (name1 (manifest-entry-name (top-most-entry first)))
  598. (name2 (manifest-entry-name (top-most-entry second))))
  599. (if (string=? name1 name2)
  600. (display-hint (format #f (G_ "You cannot have two different versions
  601. or variants of @code{~a} in the same profile.")
  602. name1))
  603. (display-hint (format #f (G_ "Try upgrading both @code{~a} and @code{~a},
  604. or remove one of them from the profile.")
  605. name1 name2)))))
  606. ;; On Guile 3.0, in 'call-with-error-handling' we need to re-raise. To
  607. ;; preserve useful backtraces in case of unhandled errors, we want that to
  608. ;; happen before the stack has been unwound, hence 'guard*'.
  609. (define-syntax-rule (guard* (var clauses ...) exp ...)
  610. "This variant of SRFI-34 'guard' does not unwind the stack before
  611. evaluating the tests and bodies of CLAUSES."
  612. (with-exception-handler
  613. (lambda (var)
  614. (cond clauses ... (else (raise var))))
  615. (lambda () exp ...)
  616. #:unwind? #f))
  617. (define (call-with-error-handling thunk)
  618. "Call THUNK within a user-friendly error handler."
  619. (define (port-filename* port)
  620. ;; 'port-filename' returns #f for non-file ports, but it raises an
  621. ;; exception for file ports that are closed. Work around that.
  622. (and (not (port-closed? port))
  623. (port-filename port)))
  624. (guard* (c ((package-input-error? c)
  625. (let* ((package (package-error-package c))
  626. (input (package-error-invalid-input c))
  627. (location (package-location package))
  628. (file (location-file location))
  629. (line (location-line location))
  630. (column (location-column location)))
  631. (leave (G_ "~a:~a:~a: package `~a' has an invalid input: ~s~%")
  632. file line column
  633. (package-full-name package) input)))
  634. ((package-cross-build-system-error? c)
  635. (let* ((package (package-error-package c))
  636. (loc (package-location package))
  637. (system (package-build-system package)))
  638. (leave (G_ "~a: ~a: build system `~a' does not support cross builds~%")
  639. (location->string loc)
  640. (package-full-name package)
  641. (build-system-name system))))
  642. ((gexp-input-error? c)
  643. (let ((input (gexp-error-invalid-input c)))
  644. (leave (G_ "~s: invalid G-expression input~%")
  645. (gexp-error-invalid-input c))))
  646. ((profile-not-found-error? c)
  647. (leave (G_ "profile '~a' does not exist~%")
  648. (profile-error-profile c)))
  649. ((missing-generation-error? c)
  650. (leave (G_ "generation ~a of profile '~a' does not exist~%")
  651. (missing-generation-error-generation c)
  652. (profile-error-profile c)))
  653. ((unmatched-pattern-error? c)
  654. (let ((pattern (unmatched-pattern-error-pattern c)))
  655. (leave (G_ "package '~a~@[@~a~]~@[:~a~]' not found in profile~%")
  656. (manifest-pattern-name pattern)
  657. (manifest-pattern-version pattern)
  658. (match (manifest-pattern-output pattern)
  659. ("out" #f)
  660. (output output)))))
  661. ((profile-collision-error? c)
  662. (let ((entry (profile-collision-error-entry c))
  663. (conflict (profile-collision-error-conflict c)))
  664. (define (report-parent-entries entry)
  665. (let ((parent (force (manifest-entry-parent entry))))
  666. (when (manifest-entry? parent)
  667. (report-error (G_ " ... propagated from ~a@~a~%")
  668. (manifest-entry-name parent)
  669. (manifest-entry-version parent))
  670. (report-parent-entries parent))))
  671. (define (manifest-entry-output* entry)
  672. (match (manifest-entry-output entry)
  673. ("out" "")
  674. (output (string-append ":" output))))
  675. (report-error (G_ "profile contains conflicting entries for ~a~a~%")
  676. (manifest-entry-name entry)
  677. (manifest-entry-output* entry))
  678. (report-error (G_ " first entry: ~a@~a~a ~a~%")
  679. (manifest-entry-name entry)
  680. (manifest-entry-version entry)
  681. (manifest-entry-output* entry)
  682. (manifest-entry-item entry))
  683. (report-parent-entries entry)
  684. (report-error (G_ " second entry: ~a@~a~a ~a~%")
  685. (manifest-entry-name conflict)
  686. (manifest-entry-version conflict)
  687. (manifest-entry-output* conflict)
  688. (manifest-entry-item conflict))
  689. (report-parent-entries conflict)
  690. (display-collision-resolution-hint c)
  691. (exit 1)))
  692. ((nar-error? c)
  693. (let ((file (nar-error-file c))
  694. (port (nar-error-port c)))
  695. (if file
  696. (leave (G_ "corrupt input while restoring '~a' from ~s~%")
  697. file (or (port-filename* port) port))
  698. (leave (G_ "corrupt input while restoring archive from ~s~%")
  699. (or (port-filename* port) port)))))
  700. ((store-connection-error? c)
  701. (leave (G_ "failed to connect to `~a': ~a~%")
  702. (store-connection-error-file c)
  703. (strerror (store-connection-error-code c))))
  704. ((store-protocol-error? c)
  705. ;; FIXME: Server-provided error messages aren't i18n'd.
  706. (leave (G_ "~a~%")
  707. (store-protocol-error-message c)))
  708. ((derivation-missing-output-error? c)
  709. (leave (G_ "reference to invalid output '~a' of derivation '~a'~%")
  710. (derivation-missing-output c)
  711. (derivation-file-name (derivation-error-derivation c))))
  712. ((file-search-error? c)
  713. (leave (G_ "file '~a' could not be found in these \
  714. directories:~{ ~a~}~%")
  715. (file-search-error-file-name c)
  716. (file-search-error-search-path c)))
  717. ((invoke-error? c)
  718. (leave (G_ "program exited\
  719. ~@[ with non-zero exit status ~a~]\
  720. ~@[ terminated by signal ~a~]\
  721. ~@[ stopped by signal ~a~]: ~s~%")
  722. (invoke-error-exit-status c)
  723. (invoke-error-term-signal c)
  724. (invoke-error-stop-signal c)
  725. (cons (invoke-error-program c)
  726. (invoke-error-arguments c))))
  727. ((formatted-message? c)
  728. (apply report-error
  729. (and (error-location? c) (error-location c))
  730. (gettext (formatted-message-string c) %gettext-domain)
  731. (formatted-message-arguments c))
  732. (when (fix-hint? c)
  733. (display-hint (condition-fix-hint c)))
  734. (exit 1))
  735. ;; On Guile 3.0.0, exceptions such as 'unbound-variable' are
  736. ;; compound and include a '&message'. However, that message only
  737. ;; contains the format string. Thus, special-case it here to
  738. ;; avoid displaying a bare format string.
  739. ;;
  740. ;; Furthermore, use of 'guard*' ensures that the stack has not
  741. ;; been unwound when we re-raise, since that would otherwise show
  742. ;; useless backtraces.
  743. (((exception-predicate &exception-with-kind-and-args) c)
  744. (if (eq? 'system-error (exception-kind c)) ;EPIPE & co.
  745. (match (exception-args c)
  746. ((proc format-string format-args . _)
  747. (leave (G_ "~a: ~a~%") proc
  748. (apply format #f format-string format-args))))
  749. (raise c)))
  750. ((message-condition? c)
  751. ;; Normally '&message' error conditions have an i18n'd message.
  752. (report-error (and (error-location? c) (error-location c))
  753. (G_ "~a~%")
  754. (gettext (condition-message c) %gettext-domain))
  755. (when (fix-hint? c)
  756. (display-hint (condition-fix-hint c)))
  757. (exit 1)))
  758. (thunk)))
  759. (define-syntax-rule (leave-on-EPIPE exp ...)
  760. "Run EXP... in a context where EPIPE errors are caught and lead to 'exit'
  761. with successful exit code. This is useful when writing to the standard output
  762. may lead to EPIPE, because the standard output is piped through 'head' or
  763. similar."
  764. (catch 'system-error
  765. (lambda ()
  766. exp ...)
  767. (lambda args
  768. ;; We really have to exit this brutally, otherwise Guile eventually
  769. ;; attempts to flush all the ports, leading to an uncaught EPIPE down
  770. ;; the path.
  771. (if (= EPIPE (system-error-errno args))
  772. (primitive-_exit 0)
  773. (apply throw args)))))
  774. (define %guix-user-module
  775. ;; Module in which user expressions are evaluated.
  776. ;; Compute lazily to avoid circularity with (guix gexp).
  777. (delay
  778. (let ((module (make-module)))
  779. (beautify-user-module! module)
  780. ;; Use (guix gexp) so that one can use #~ & co.
  781. (module-use! module (resolve-interface '(guix gexp)))
  782. module)))
  783. (define (read/eval str)
  784. "Read and evaluate STR, raising an error if something goes wrong."
  785. (let ((exp (catch #t
  786. (lambda ()
  787. (call-with-input-string str read))
  788. (lambda args
  789. (leave (G_ "failed to read expression ~s: ~s~%")
  790. str args)))))
  791. (catch #t
  792. (lambda ()
  793. (eval exp (force %guix-user-module)))
  794. (lambda args
  795. (report-error (G_ "failed to evaluate expression '~a':~%") exp)
  796. (match args
  797. (('syntax-error proc message properties form . rest)
  798. (report-error (G_ "syntax error: ~a~%") message))
  799. (((or 'srfi-34 '%exception) obj)
  800. (cond ((message-condition? obj)
  801. (report-error (G_ "~a~%")
  802. (gettext (condition-message obj)
  803. %gettext-domain)))
  804. ((formatted-message? obj)
  805. (apply report-error #f
  806. (gettext (formatted-message-string obj)
  807. %gettext-domain)
  808. (formatted-message-arguments obj)))
  809. (else
  810. (report-error (G_ "exception thrown: ~s~%") obj))))
  811. ((error args ...)
  812. (apply display-error #f (current-error-port) args))
  813. (what? #f))
  814. (exit 1)))))
  815. (define (read/eval-package-expression str)
  816. "Read and evaluate STR and return the package it refers to, or exit an
  817. error."
  818. (match (read/eval str)
  819. ((? package? p) p)
  820. (x
  821. (leave (G_ "expression ~s does not evaluate to a package~%")
  822. str))))
  823. (define (show-derivation-outputs derivation)
  824. "Show the output file names of DERIVATION, which can be a derivation or a
  825. derivation input."
  826. (define (show-outputs derivation outputs)
  827. (format #t "~{~a~%~}"
  828. (map (cut derivation->output-path derivation <>)
  829. outputs)))
  830. (match derivation
  831. ((? derivation?)
  832. (show-outputs derivation (derivation-output-names derivation)))
  833. ((? derivation-input? input)
  834. (show-outputs (derivation-input-derivation input)
  835. (derivation-input-sub-derivations input)))))
  836. (define* (check-available-space need
  837. #:optional (directory (%store-prefix)))
  838. "Make sure at least NEED bytes are available in DIRECTORY. Otherwise emit a
  839. warning."
  840. (let ((free (catch 'system-error
  841. (lambda ()
  842. (free-disk-space directory))
  843. (const #f))))
  844. (when (and free (>= need free))
  845. (warning (G_ "at least ~,1h MB needed but only ~,1h MB available in ~a~%")
  846. (/ need 1e6) (/ free 1e6) directory))))
  847. (define (graft-derivation? drv)
  848. "Return true if DRV is definitely a graft derivation, false otherwise."
  849. (match (assq-ref (derivation-properties drv) 'type)
  850. ('graft #t)
  851. (_ #f)))
  852. (define (profile-hook-derivation? drv)
  853. "Return true if DRV is definitely a profile hook derivation, false otherwise."
  854. (match (assq-ref (derivation-properties drv) 'type)
  855. ('profile-hook #t)
  856. (_ #f)))
  857. (define (colorize-store-file-name file)
  858. "Colorize FILE, a store file name, such that the hash part is less prominent
  859. that the rest."
  860. (let ((len (string-length file))
  861. (prefix (+ (string-length (%store-prefix)) 32 2)))
  862. (if (< len prefix)
  863. file
  864. (string-append (colorize-string (string-take file prefix)
  865. (color DARK))
  866. (string-drop file prefix)))))
  867. (define %default-verbosity
  868. ;; Default verbosity level for 'show-what-to-build'.
  869. 2)
  870. (define* (show-what-to-build store drv
  871. #:key dry-run? (use-substitutes? #t)
  872. (verbosity %default-verbosity)
  873. (mode (build-mode normal)))
  874. "Show what will or would (depending on DRY-RUN?) be built in realizing the
  875. derivations listed in DRV using MODE, a 'build-mode' value. The elements of
  876. DRV can be either derivations or derivation inputs.
  877. Return two values: a Boolean indicating whether there's something to build,
  878. and a Boolean indicating whether there's something to download.
  879. When USE-SUBSTITUTES?, check and report what is prerequisites are available
  880. for download. VERBOSITY is an integer indicating the level of details to be
  881. shown: level 2 and higher provide all the details, level 1 shows a high-level
  882. summary, and level 0 shows nothing."
  883. (define inputs
  884. (map (match-lambda
  885. ((? derivation? drv) (derivation-input drv))
  886. ((? derivation-input? input) input))
  887. drv))
  888. (define substitutable-info
  889. ;; Call 'substitution-oracle' upfront so we don't end up launching the
  890. ;; substituter many times. This makes a big difference, especially when
  891. ;; DRV is a long list as is the case with 'guix environment'.
  892. (if use-substitutes?
  893. (substitution-oracle store inputs #:mode mode)
  894. (const #f)))
  895. (define colorized-store-item
  896. (if (color-output? (current-error-port))
  897. colorize-store-file-name
  898. identity))
  899. (let*-values (((build/full download)
  900. (derivation-build-plan store inputs
  901. #:mode mode
  902. #:substitutable-info
  903. substitutable-info))
  904. ((graft hook build)
  905. (match (fold (lambda (drv acc)
  906. (let ((file (derivation-file-name drv)))
  907. (match acc
  908. ((#:graft graft #:hook hook #:build build)
  909. (cond
  910. ((graft-derivation? drv)
  911. `(#:graft ,(cons file graft)
  912. #:hook ,hook
  913. #:build ,build))
  914. ((profile-hook-derivation? drv)
  915. `(#:graft ,graft
  916. #:hook ,(cons file hook)
  917. #:build ,build))
  918. (else
  919. `(#:graft ,graft
  920. #:hook ,hook
  921. #:build ,(cons file build))))))))
  922. '(#:graft () #:hook () #:build ())
  923. build/full)
  924. ((#:graft graft #:hook hook #:build build)
  925. (values graft hook build)))))
  926. (define installed-size
  927. (reduce + 0 (map substitutable-nar-size download)))
  928. (define download-size
  929. (/ (reduce + 0 (map substitutable-download-size download))
  930. 1e6))
  931. (define display-download-size?
  932. ;; Sometimes narinfos lack information about the download size. Only
  933. ;; display when we have information for all of DOWNLOAD.
  934. (not (any (compose zero? substitutable-download-size) download)))
  935. ;; Combinatorial explosion ahead along two axes: DRY-RUN? and VERBOSITY.
  936. ;; Unfortunately, this is hardly avoidable for proper i18n.
  937. (if dry-run?
  938. (begin
  939. (unless (zero? verbosity)
  940. (format (current-error-port)
  941. (N_ "~:[The following derivation would be built:~%~{ ~a~%~}~;~]"
  942. "~:[The following derivations would be built:~%~{ ~a~%~}~;~]"
  943. (length build))
  944. (null? build) (map colorized-store-item build)))
  945. (cond ((>= verbosity 2)
  946. (if display-download-size?
  947. (format (current-error-port)
  948. ;; TRANSLATORS: "MB" is for "megabyte"; it should be
  949. ;; translated to the corresponding abbreviation.
  950. (G_ "~:[~,1h MB would be downloaded:~%~{ ~a~%~}~;~]")
  951. (null? download)
  952. download-size
  953. (map (compose colorized-store-item substitutable-path)
  954. download))
  955. (format (current-error-port)
  956. (N_ "~:[The following file would be downloaded:~%~{ ~a~%~}~;~]"
  957. "~:[The following files would be downloaded:~%~{ ~a~%~}~;~]"
  958. (length download))
  959. (null? download)
  960. (map (compose colorized-store-item substitutable-path)
  961. download)))
  962. (format (current-error-port)
  963. (N_ "~:[The following graft would be made:~%~{ ~a~%~}~;~]"
  964. "~:[The following grafts would be made:~%~{ ~a~%~}~;~]"
  965. (length graft))
  966. (null? graft) (map colorized-store-item graft))
  967. (format (current-error-port)
  968. (N_ "~:[The following profile hook would be built:~%~{ ~a~%~}~;~]"
  969. "~:[The following profile hooks would be built:~%~{ ~a~%~}~;~]"
  970. (length hook))
  971. (null? hook) (map colorized-store-item hook)))
  972. ((= verbosity 1)
  973. ;; Display the bare minimum; don't mention grafts and hooks.
  974. (unless (null? build)
  975. (newline (current-error-port)))
  976. (if display-download-size?
  977. (format (current-error-port)
  978. ;; TRANSLATORS: "MB" is for "megabyte"; it should be
  979. ;; translated to the corresponding abbreviation.
  980. (highlight (G_ "~:[~,1h MB would be downloaded~%~;~]"))
  981. (null? download) download-size)
  982. (format (current-error-port)
  983. (highlight
  984. (N_ "~:[~h item would be downloaded~%~;~]"
  985. "~:[~h items would be downloaded~%~;~]"
  986. (length download)))
  987. (null? download) (length download))))))
  988. (begin
  989. (unless (zero? verbosity)
  990. (format (current-error-port)
  991. (N_ "~:[The following derivation will be built:~%~{ ~a~%~}~;~]"
  992. "~:[The following derivations will be built:~%~{ ~a~%~}~;~]"
  993. (length build))
  994. (null? build) (map colorized-store-item build)))
  995. (cond ((>= verbosity 2)
  996. (if display-download-size?
  997. (format (current-error-port)
  998. ;; TRANSLATORS: "MB" is for "megabyte"; it should be
  999. ;; translated to the corresponding abbreviation.
  1000. (G_ "~:[~,1h MB will be downloaded:~%~{ ~a~%~}~;~]")
  1001. (null? download)
  1002. download-size
  1003. (map (compose colorized-store-item substitutable-path)
  1004. download))
  1005. (format (current-error-port)
  1006. (N_ "~:[The following file will be downloaded:~%~{ ~a~%~}~;~]"
  1007. "~:[The following files will be downloaded:~%~{ ~a~%~}~;~]"
  1008. (length download))
  1009. (null? download)
  1010. (map (compose colorized-store-item substitutable-path)
  1011. download)))
  1012. (format (current-error-port)
  1013. (N_ "~:[The following graft will be made:~%~{ ~a~%~}~;~]"
  1014. "~:[The following grafts will be made:~%~{ ~a~%~}~;~]"
  1015. (length graft))
  1016. (null? graft) (map colorized-store-item graft))
  1017. (format (current-error-port)
  1018. (N_ "~:[The following profile hook will be built:~%~{ ~a~%~}~;~]"
  1019. "~:[The following profile hooks will be built:~%~{ ~a~%~}~;~]"
  1020. (length hook))
  1021. (null? hook) (map colorized-store-item hook)))
  1022. ((= verbosity 1)
  1023. ;; Display the bare minimum; don't mention grafts and hooks.
  1024. (unless (null? build)
  1025. (newline (current-error-port)))
  1026. (if display-download-size?
  1027. (format (current-error-port)
  1028. ;; TRANSLATORS: "MB" is for "megabyte"; it should be
  1029. ;; translated to the corresponding abbreviation.
  1030. (highlight (G_ "~:[~,1h MB will be downloaded~%~;~]"))
  1031. (null? download) download-size)
  1032. (format (current-error-port)
  1033. (highlight
  1034. (N_ "~:[~h item will be downloaded~%~;~]"
  1035. "~:[~h items will be downloaded~%~;~]"
  1036. (length download)))
  1037. (null? download) (length download)))))))
  1038. (check-available-space installed-size)
  1039. (values (pair? build/full) (pair? download))))
  1040. (define show-what-to-build*
  1041. (store-lift show-what-to-build))
  1042. (define* (build-notifier #:key (dry-run? #f) (use-substitutes? #t)
  1043. (verbosity %default-verbosity))
  1044. "Return a procedure suitable for 'with-build-handler' that, when
  1045. 'build-things' is called, invokes 'show-what-to-build' to display the build
  1046. plan. When DRY-RUN? is true, the 'with-build-handler' form returns without
  1047. any build happening."
  1048. (define not-comma
  1049. (char-set-complement (char-set #\,)))
  1050. (define (read-derivation-from-file* item)
  1051. (catch 'system-error
  1052. (lambda ()
  1053. (read-derivation-from-file item))
  1054. (const #f)))
  1055. (lambda (continue store things mode)
  1056. (define inputs
  1057. ;; List of derivation inputs to build. Filter out non-existent '.drv'
  1058. ;; files because the daemon transparently tries to substitute them.
  1059. (filter-map (match-lambda
  1060. (((? derivation-path? drv) . output)
  1061. (let ((drv (read-derivation-from-file* drv))
  1062. (outputs (string-tokenize output not-comma)))
  1063. (and drv (derivation-input drv outputs))))
  1064. ((? derivation-path? drv)
  1065. (and=> (read-derivation-from-file* drv)
  1066. derivation-input))
  1067. (_
  1068. #f))
  1069. things))
  1070. (let-values (((build? download?)
  1071. (show-what-to-build store inputs
  1072. #:dry-run? dry-run?
  1073. #:use-substitutes? use-substitutes?
  1074. #:verbosity verbosity
  1075. #:mode mode)))
  1076. (unless (and (or build? download?)
  1077. dry-run?)
  1078. (continue #t)))))
  1079. (define (right-arrow port)
  1080. "Return either a string containing the 'RIGHT ARROW' character, or an ASCII
  1081. replacement if PORT is not Unicode-capable."
  1082. (let ((encoding (port-encoding port))
  1083. (arrow "→"))
  1084. (catch 'encoding-error
  1085. (lambda ()
  1086. (call-with-output-string
  1087. (lambda (port)
  1088. (set-port-encoding! port encoding)
  1089. (set-port-conversion-strategy! port 'error)
  1090. (display arrow port))))
  1091. (lambda (key . args)
  1092. "->"))))
  1093. (define* (tabulate rows #:key (initial-indent 0) (max-width 25)
  1094. (inter-column " "))
  1095. "Return a list of strings where each string is a tabulated representation of
  1096. an element of ROWS. All the ROWS must be lists of the same number of cells.
  1097. Add INITIAL-INDENT white space at the beginning of each row. Ensure that
  1098. columns are at most MAX-WIDTH characters wide. Use INTER-COLUMN as a
  1099. separator between subsequent columns."
  1100. (define column-widths
  1101. ;; List of column widths.
  1102. (let loop ((rows rows)
  1103. (widths '()))
  1104. (match rows
  1105. (((? null?) ...)
  1106. (reverse widths))
  1107. (((column rest ...) ...)
  1108. (loop rest
  1109. (cons (min (apply max (map string-length column))
  1110. max-width)
  1111. widths))))))
  1112. (define indent
  1113. (make-string initial-indent #\space))
  1114. (define (string-pad-right* str len)
  1115. (if (> (string-length str) len)
  1116. str
  1117. (string-pad-right str len)))
  1118. (map (lambda (row)
  1119. (string-trim-right
  1120. (string-append indent
  1121. (string-join
  1122. (map string-pad-right* row column-widths)
  1123. inter-column))))
  1124. rows))
  1125. (define* (show-manifest-transaction store manifest transaction
  1126. #:key dry-run?)
  1127. "Display what will/would be installed/removed from MANIFEST by TRANSACTION."
  1128. (define* (package-strings names versions outputs #:key old-versions)
  1129. (tabulate (stable-sort
  1130. (zip (map (lambda (name output)
  1131. (if (string=? output "out")
  1132. name
  1133. (string-append name ":" output)))
  1134. names outputs)
  1135. (if old-versions
  1136. (map (lambda (old new)
  1137. (if (string=? old new)
  1138. (G_ "(dependencies or package changed)")
  1139. (string-append old " " → " " new)))
  1140. old-versions versions)
  1141. versions))
  1142. (lambda (x y)
  1143. (string<? (first x) (first y))))
  1144. #:initial-indent 3))
  1145. (define → ;an arrow that can be represented on stderr
  1146. (right-arrow (current-error-port)))
  1147. (let-values (((remove install upgrade downgrade)
  1148. (manifest-transaction-effects manifest transaction)))
  1149. (match remove
  1150. ((($ <manifest-entry> name version output item) ..1)
  1151. (let ((len (length name))
  1152. (remove (package-strings name version output)))
  1153. (if dry-run?
  1154. (format (current-error-port)
  1155. (N_ "The following package would be removed:~%~{~a~%~}~%"
  1156. "The following packages would be removed:~%~{~a~%~}~%"
  1157. len)
  1158. remove)
  1159. (format (current-error-port)
  1160. (N_ "The following package will be removed:~%~{~a~%~}~%"
  1161. "The following packages will be removed:~%~{~a~%~}~%"
  1162. len)
  1163. remove))))
  1164. (x #f))
  1165. (match downgrade
  1166. (((($ <manifest-entry> name old-version)
  1167. . ($ <manifest-entry> _ new-version output item)) ..1)
  1168. (let ((len (length name))
  1169. (downgrade (package-strings name new-version output
  1170. #:old-versions old-version)))
  1171. (if dry-run?
  1172. (format (current-error-port)
  1173. (N_ "The following package would be downgraded:~%~{~a~%~}~%"
  1174. "The following packages would be downgraded:~%~{~a~%~}~%"
  1175. len)
  1176. downgrade)
  1177. (format (current-error-port)
  1178. (N_ "The following package will be downgraded:~%~{~a~%~}~%"
  1179. "The following packages will be downgraded:~%~{~a~%~}~%"
  1180. len)
  1181. downgrade))))
  1182. (x #f))
  1183. (match upgrade
  1184. (((($ <manifest-entry> name old-version)
  1185. . ($ <manifest-entry> _ new-version output item)) ..1)
  1186. (let ((len (length name))
  1187. (upgrade (package-strings name new-version output
  1188. #:old-versions old-version)))
  1189. (if dry-run?
  1190. (format (current-error-port)
  1191. (N_ "The following package would be upgraded:~%~{~a~%~}~%"
  1192. "The following packages would be upgraded:~%~{~a~%~}~%"
  1193. len)
  1194. upgrade)
  1195. (format (current-error-port)
  1196. (N_ "The following package will be upgraded:~%~{~a~%~}~%"
  1197. "The following packages will be upgraded:~%~{~a~%~}~%"
  1198. len)
  1199. upgrade))))
  1200. (x #f))
  1201. (match install
  1202. ((($ <manifest-entry> name version output item _) ..1)
  1203. (let ((len (length name))
  1204. (install (package-strings name version output)))
  1205. (if dry-run?
  1206. (format (current-error-port)
  1207. (N_ "The following package would be installed:~%~{~a~%~}~%"
  1208. "The following packages would be installed:~%~{~a~%~}~%"
  1209. len)
  1210. install)
  1211. (format (current-error-port)
  1212. (N_ "The following package will be installed:~%~{~a~%~}~%"
  1213. "The following packages will be installed:~%~{~a~%~}~%"
  1214. len)
  1215. install))))
  1216. (x #f))))
  1217. (define-syntax with-error-handling
  1218. (syntax-rules ()
  1219. "Run BODY within a user-friendly error condition handler."
  1220. ((_ body ...)
  1221. (call-with-error-handling
  1222. (lambda ()
  1223. body ...)))))
  1224. (define* (indented-string str indent
  1225. #:key (initial-indent? #t))
  1226. "Return STR with each newline preceded by INDENT spaces. When
  1227. INITIAL-INDENT? is true, the first line is also indented."
  1228. (define indent-string
  1229. (make-list indent #\space))
  1230. (list->string
  1231. (string-fold-right (lambda (chr result)
  1232. (if (eqv? chr #\newline)
  1233. (cons chr (append indent-string result))
  1234. (cons chr result)))
  1235. '()
  1236. (if initial-indent?
  1237. (string-append (list->string indent-string) str)
  1238. str))))
  1239. (define* (fill-paragraph str width #:optional (column 0))
  1240. "Fill STR such that each line contains at most WIDTH characters, assuming
  1241. that the first character is at COLUMN.
  1242. When STR contains a single line break surrounded by other characters, it is
  1243. converted to a space; sequences of more than one line break are preserved."
  1244. (define (maybe-break chr result)
  1245. (match result
  1246. ((column newlines chars)
  1247. (case chr
  1248. ((#\newline)
  1249. `(,column ,(+ 1 newlines) ,chars))
  1250. (else
  1251. (let* ((spaces (if (and (pair? chars) (eqv? (car chars) #\.)) 2 1))
  1252. (chars (case newlines
  1253. ((0) chars)
  1254. ((1)
  1255. (append (make-list spaces #\space) chars))
  1256. (else
  1257. (append (make-list newlines #\newline) chars))))
  1258. (column (case newlines
  1259. ((0) column)
  1260. ((1) (+ spaces column))
  1261. (else 0))))
  1262. (let ((chars (cons chr chars))
  1263. (column (+ 1 column)))
  1264. (if (> column width)
  1265. (let*-values (((before after)
  1266. (break (cut eqv? #\space <>) chars))
  1267. ((len)
  1268. (length before)))
  1269. (if (<= len width)
  1270. `(,len
  1271. 0
  1272. ,(if (null? after)
  1273. before
  1274. (append before
  1275. (cons #\newline
  1276. (drop-while (cut eqv? #\space <>)
  1277. after)))))
  1278. `(,column 0 ,chars))) ; unbreakable
  1279. `(,column 0 ,chars)))))))))
  1280. (match (string-fold maybe-break
  1281. `(,column 0 ())
  1282. str)
  1283. ((column newlines chars)
  1284. (list->string (reverse chars)))))
  1285. ;;;
  1286. ;;; Packages.
  1287. ;;;
  1288. (define %text-width
  1289. ;; '*line-width*' was introduced in Guile 2.2.7/3.0.1. On older versions of
  1290. ;; Guile, monkey-patch 'wrap*' below.
  1291. (if (defined? '*line-width*)
  1292. (let ((parameter (fluid->parameter *line-width*)))
  1293. (parameter (terminal-columns))
  1294. parameter)
  1295. (make-parameter (terminal-columns))))
  1296. (unless (defined? '*line-width*) ;Guile < 2.2.7
  1297. (set! (@@ (texinfo plain-text) wrap*)
  1298. ;; XXX: Monkey patch this private procedure to let 'package->recutils'
  1299. ;; parameterize the fill of description field correctly.
  1300. (lambda strings
  1301. (let ((indent (fluid-ref (@@ (texinfo plain-text) *indent*))))
  1302. (fill-string (string-concatenate strings)
  1303. #:line-width (%text-width) #:initial-indent indent
  1304. #:subsequent-indent indent)))))
  1305. (define (texi->plain-text str)
  1306. "Return a plain-text representation of texinfo fragment STR."
  1307. ;; 'texi-fragment->stexi' uses a string port so make sure it's a
  1308. ;; Unicode-capable one (see <http://bugs.gnu.org/11197>.)
  1309. (with-fluids ((%default-port-encoding "UTF-8"))
  1310. (stexi->plain-text (texi-fragment->stexi str))))
  1311. (define (package-field-string package field-accessor)
  1312. "Return a plain-text representation of PACKAGE field."
  1313. (and=> (field-accessor package)
  1314. (compose texi->plain-text P_)))
  1315. (define (package-description-string package)
  1316. "Return a plain-text representation of PACKAGE description field."
  1317. (package-field-string package package-description))
  1318. (define (package-synopsis-string package)
  1319. "Return a plain-text representation of PACKAGE synopsis field."
  1320. (package-field-string package package-synopsis))
  1321. (define (string->recutils str)
  1322. "Return a version of STR where newlines have been replaced by newlines
  1323. followed by \"+ \", which makes for a valid multi-line field value in the
  1324. `recutils' syntax."
  1325. (list->string
  1326. (string-fold-right (lambda (chr result)
  1327. (if (eqv? chr #\newline)
  1328. (cons* chr #\+ #\space result)
  1329. (cons chr result)))
  1330. '()
  1331. str)))
  1332. (define (hyperlink uri text)
  1333. "Return a string that denotes a hyperlink using an OSC escape sequence as
  1334. documented at
  1335. <https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda>."
  1336. (string-append "\x1b]8;;" uri "\x1b\\"
  1337. text "\x1b]8;;\x1b\\"))
  1338. (define* (supports-hyperlinks? #:optional (port (current-output-port)))
  1339. "Return true if PORT is a terminal that supports hyperlink escapes."
  1340. ;; Note that terminals are supposed to ignore OSC escapes they don't
  1341. ;; understand (this is the case of xterm as of version 349, for instance.)
  1342. ;; However, Emacs comint as of 26.3 does not ignore it and instead lets it
  1343. ;; through, hence the 'INSIDE_EMACS' special case below.
  1344. (and (isatty?* port)
  1345. (not (getenv "INSIDE_EMACS"))))
  1346. (define* (file-hyperlink file #:optional (text file))
  1347. "Return TEXT with escapes for a hyperlink to FILE."
  1348. (hyperlink (string-append "file://" (gethostname)
  1349. (encode-and-join-uri-path
  1350. (string-split file #\/)))
  1351. text))
  1352. (define (location->hyperlink location)
  1353. "Return a string corresponding to LOCATION, with escapes for a hyperlink."
  1354. (let ((str (location->string location))
  1355. (file (if (string-prefix? "/" (location-file location))
  1356. (location-file location)
  1357. (search-path %load-path (location-file location)))))
  1358. (if file
  1359. (file-hyperlink file str)
  1360. str)))
  1361. (define* (package->recutils p port #:optional (width (%text-width))
  1362. #:key
  1363. (hyperlinks? (supports-hyperlinks? port))
  1364. (extra-fields '()))
  1365. "Write to PORT a `recutils' record of package P, arranging to fit within
  1366. WIDTH columns. EXTRA-FIELDS is a list of symbol/value pairs to emit. When
  1367. HYPERLINKS? is true, emit hyperlink escape sequences when appropriate."
  1368. (define width*
  1369. ;; The available number of columns once we've taken into account space for
  1370. ;; the initial "+ " prefix.
  1371. (if (> width 2) (- width 2) width))
  1372. (define (dependencies->recutils packages)
  1373. (let ((list (string-join (delete-duplicates
  1374. (map package-full-name
  1375. (sort packages package<?))) " ")))
  1376. (string->recutils
  1377. (fill-paragraph list width*
  1378. (string-length "dependencies: ")))))
  1379. (define (package<? p1 p2)
  1380. (string<? (package-full-name p1) (package-full-name p2)))
  1381. ;; Note: Don't i18n field names so that people can post-process it.
  1382. (format port "name: ~a~%" (package-name p))
  1383. (format port "version: ~a~%" (package-version p))
  1384. (format port "outputs: ~a~%" (string-join (package-outputs p)))
  1385. (format port "systems: ~a~%"
  1386. (string-join (package-transitive-supported-systems p)))
  1387. (format port "dependencies: ~a~%"
  1388. (match (package-direct-inputs p)
  1389. (((labels inputs . _) ...)
  1390. (dependencies->recutils (filter package? inputs)))))
  1391. (format port "location: ~a~%"
  1392. (or (and=> (package-location p)
  1393. (if hyperlinks? location->hyperlink location->string))
  1394. (G_ "unknown")))
  1395. ;; Note: Starting from version 1.6 or recutils, hyphens are not allowed in
  1396. ;; field identifiers.
  1397. (format port "homepage: ~a~%" (package-home-page p))
  1398. (format port "license: ~a~%"
  1399. (match (package-license p)
  1400. (((? license? licenses) ...)
  1401. (string-join (map license-name licenses)
  1402. ", "))
  1403. ((? license? license)
  1404. (let ((text (license-name license))
  1405. (uri (license-uri license)))
  1406. (if (and hyperlinks? uri (string-prefix? "http" uri))
  1407. (hyperlink uri text)
  1408. text)))
  1409. (x
  1410. (G_ "unknown"))))
  1411. (format port "synopsis: ~a~%"
  1412. (string-map (match-lambda
  1413. (#\newline #\space)
  1414. (chr chr))
  1415. (or (package-synopsis-string p) "")))
  1416. (format port "~a~%"
  1417. (string->recutils
  1418. (string-trim-right
  1419. (parameterize ((%text-width width*))
  1420. ;; Call 'texi->plain-text' on the concatenated string to account
  1421. ;; for the width of "description:" in paragraph filling.
  1422. (texi->plain-text
  1423. (string-append "description: "
  1424. (or (and=> (package-description p) P_)
  1425. ""))))
  1426. #\newline)))
  1427. (for-each (match-lambda
  1428. ((field . value)
  1429. (let ((field (symbol->string field)))
  1430. (format port "~a: ~a~%"
  1431. field
  1432. (fill-paragraph (object->string value) width*
  1433. (string-length field))))))
  1434. extra-fields)
  1435. (newline port))
  1436. ;;;
  1437. ;;; Searching.
  1438. ;;;
  1439. (define (relevance obj regexps metrics)
  1440. "Compute a \"relevance score\" for OBJ as a function of its number of
  1441. matches of REGEXPS and accordingly to METRICS. METRICS is list of
  1442. field/weight pairs, where FIELD is a procedure that returns a string or list
  1443. of strings describing OBJ, and WEIGHT is a positive integer denoting the
  1444. weight of this field in the final score.
  1445. A score of zero means that OBJ does not match any of REGEXPS. The higher the
  1446. score, the more relevant OBJ is to REGEXPS."
  1447. (define (score regexp str)
  1448. (fold-matches regexp str 0
  1449. (lambda (m score)
  1450. (+ score
  1451. (if (string=? (match:substring m) str)
  1452. 5 ;exact match
  1453. 1)))))
  1454. (define (regexp->score regexp)
  1455. (let ((score-regexp (lambda (str) (score regexp str))))
  1456. (fold (lambda (metric relevance)
  1457. (match metric
  1458. ((field . weight)
  1459. (match (field obj)
  1460. (#f relevance)
  1461. ((? string? str)
  1462. (+ relevance (* (score-regexp str) weight)))
  1463. ((lst ...)
  1464. (+ relevance (* weight (apply + (map score-regexp lst)))))))))
  1465. 0 metrics)))
  1466. (let loop ((regexps regexps)
  1467. (total-score 0))
  1468. (match regexps
  1469. ((head . tail)
  1470. (let ((score (regexp->score head)))
  1471. ;; Return zero if one of PATTERNS doesn't match.
  1472. (if (zero? score)
  1473. 0
  1474. (loop tail (+ total-score score)))))
  1475. (() total-score))))
  1476. (define %package-metrics
  1477. ;; Metrics used to compute the "relevance score" of a package against a set
  1478. ;; of regexps.
  1479. `((,package-name . 4)
  1480. ;; Match against uncommon outputs.
  1481. (,(lambda (package)
  1482. (filter (lambda (output)
  1483. (not (member output
  1484. ;; Some common outputs shared by many packages.
  1485. '("out" "doc" "debug" "lib" "include" "bin"))))
  1486. (package-outputs package)))
  1487. . 1)
  1488. ;; Match regexps on the raw Texinfo since formatting it is quite expensive
  1489. ;; and doesn't have much of an effect on search results.
  1490. (,(lambda (package)
  1491. (and=> (package-synopsis package) P_)) . 3)
  1492. (,(lambda (package)
  1493. (and=> (package-description package) P_)) . 2)
  1494. (,(lambda (type)
  1495. (match (and=> (package-location type) location-file)
  1496. ((? string? file) (basename file ".scm"))
  1497. (#f "")))
  1498. . 1)))
  1499. (define (package-relevance package regexps)
  1500. "Return a score denoting the relevance of PACKAGE for REGEXPS. A score of
  1501. zero means that PACKAGE does not match any of REGEXPS."
  1502. (relevance package regexps %package-metrics))
  1503. (define* (call-with-paginated-output-port proc
  1504. #:key (less-options "FrX"))
  1505. (let ((pager-command-line (or (getenv "GUIX_PAGER")
  1506. (getenv "PAGER")
  1507. "less")))
  1508. ;; Setting PAGER to the empty string conventionally disables paging.
  1509. (if (and (not (string-null? pager-command-line))
  1510. (isatty?* (current-output-port)))
  1511. ;; Set 'LESS' so that 'less' exits if everything fits on the screen
  1512. ;; (F), lets ANSI escapes through (r), does not send the termcap
  1513. ;; initialization string (X). Set it unconditionally because some
  1514. ;; distros set it to something that doesn't work here.
  1515. ;;
  1516. ;; For things that produce long lines, such as 'guix processes', use
  1517. ;; 'R' instead of 'r': this strips hyperlinks but allows 'less' to
  1518. ;; make a good estimate of the line length.
  1519. (let* ((pager (with-environment-variables `(("LESS" ,less-options))
  1520. (apply open-pipe* OPEN_WRITE
  1521. ;; Split into arguments. Treat runs of multiple
  1522. ;; whitespace characters as one. libpipeline-
  1523. ;; style "cmd one\ arg" escaping is unsupported.
  1524. (remove (lambda (s) (string-null? s))
  1525. (string-split pager-command-line
  1526. char-set:whitespace))))))
  1527. (dynamic-wind
  1528. (const #t)
  1529. (lambda () (proc pager))
  1530. (lambda () (close-pipe pager))))
  1531. (proc (current-output-port)))))
  1532. (define-syntax with-paginated-output-port
  1533. (syntax-rules ()
  1534. "Evaluate EXP... with PORT bound to a port that talks to the pager if
  1535. standard output is a tty, or with PORT set to the current output port."
  1536. ((_ port exp ... #:less-options opts)
  1537. (call-with-paginated-output-port (lambda (port) exp ...)
  1538. #:less-options opts))
  1539. ((_ port exp ...)
  1540. (call-with-paginated-output-port (lambda (port) exp ...)))))
  1541. (define* (display-search-results matches port
  1542. #:key
  1543. (command "guix search")
  1544. (print package->recutils))
  1545. "Display MATCHES, a list of object/score pairs, by calling PRINT on each of
  1546. them. If PORT is a terminal, print at most a full screen of results."
  1547. (define first-line
  1548. (port-line port))
  1549. (define max-rows
  1550. (and first-line (isatty? port)
  1551. (terminal-rows port)))
  1552. (define (line-count str)
  1553. (string-count str #\newline))
  1554. (with-paginated-output-port paginated
  1555. (let loop ((matches matches))
  1556. (match matches
  1557. (((package . score) rest ...)
  1558. (let* ((links? (supports-hyperlinks? port)))
  1559. (print package paginated
  1560. #:hyperlinks? links?
  1561. #:extra-fields `((relevance . ,score)))
  1562. (loop rest)))
  1563. (()
  1564. #t)))))
  1565. (define (string->generations str)
  1566. "Return the list of generations matching a pattern in STR. This function
  1567. accepts the following patterns: \"1\", \"1,2,3\", \"1..9\", \"1..\", \"..9\"."
  1568. (define (maybe-integer)
  1569. (let ((x (string->number str)))
  1570. (and (integer? x)
  1571. x)))
  1572. (define (maybe-comma-separated-integers)
  1573. (let ((lst (delete-duplicates
  1574. (map string->number
  1575. (string-split str #\,)))))
  1576. (and (every integer? lst)
  1577. lst)))
  1578. (cond ((maybe-integer)
  1579. =>
  1580. list)
  1581. ((maybe-comma-separated-integers)
  1582. =>
  1583. identity)
  1584. ((string-match "^([0-9]+)\\.\\.([0-9]+)$" str)
  1585. =>
  1586. (lambda (match)
  1587. (let ((s (string->number (match:substring match 1)))
  1588. (e (string->number (match:substring match 2))))
  1589. (and (every integer? (list s e))
  1590. (<= s e)
  1591. (iota (1+ (- e s)) s)))))
  1592. ((string-match "^([0-9]+)\\.\\.$" str)
  1593. =>
  1594. (lambda (match)
  1595. (let ((s (string->number (match:substring match 1))))
  1596. (and (integer? s)
  1597. `(>= ,s)))))
  1598. ((string-match "^\\.\\.([0-9]+)$" str)
  1599. =>
  1600. (lambda (match)
  1601. (let ((e (string->number (match:substring match 1))))
  1602. (and (integer? e)
  1603. `(<= ,e)))))
  1604. (else #f)))
  1605. (define (string->duration str)
  1606. "Return the duration matching a pattern in STR. This function accepts the
  1607. following patterns: \"1d\", \"1w\", \"1m\"."
  1608. (define (hours->duration hours match)
  1609. (make-time time-duration 0
  1610. (* 3600 hours (string->number (match:substring match 1)))))
  1611. (cond ((string-match "^([0-9]+)s$" str)
  1612. =>
  1613. (lambda (match)
  1614. (make-time time-duration 0
  1615. (string->number (match:substring match 1)))))
  1616. ((string-match "^([0-9]+)h$" str)
  1617. =>
  1618. (lambda (match)
  1619. (hours->duration 1 match)))
  1620. ((string-match "^([0-9]+)d$" str)
  1621. =>
  1622. (lambda (match)
  1623. (hours->duration 24 match)))
  1624. ((string-match "^([0-9]+)w$" str)
  1625. =>
  1626. (lambda (match)
  1627. (hours->duration (* 24 7) match)))
  1628. ((string-match "^([0-9]+)m$" str)
  1629. =>
  1630. (lambda (match)
  1631. (hours->duration (* 24 30) match)))
  1632. (else #f)))
  1633. (define* (matching-generations str profile
  1634. #:key (duration-relation <=))
  1635. "Return the list of available generations matching a pattern in STR. See
  1636. 'string->generations' and 'string->duration' for the list of valid patterns.
  1637. When STR is a duration pattern, return all the generations whose ctime has
  1638. DURATION-RELATION with the current time."
  1639. (define (valid-generations lst)
  1640. (define (valid-generation? n)
  1641. (any (cut = n <>) (generation-numbers profile)))
  1642. (fold-right (lambda (x acc)
  1643. (if (valid-generation? x)
  1644. (cons x acc)
  1645. acc))
  1646. '()
  1647. lst))
  1648. (define (filter-generations generations)
  1649. (match generations
  1650. (() '())
  1651. (('>= n)
  1652. (drop-while (cut > n <>)
  1653. (generation-numbers profile)))
  1654. (('<= n)
  1655. (valid-generations (iota n 1)))
  1656. ((lst ..1)
  1657. (valid-generations lst))
  1658. (x #f)))
  1659. (define (filter-by-duration duration)
  1660. (define (time-at-midnight time)
  1661. ;; Return TIME at midnight by setting nanoseconds, seconds, minutes, and
  1662. ;; hours to zeros.
  1663. (let ((d (time-utc->date time)))
  1664. (date->time-utc
  1665. (make-date 0 0 0 0
  1666. (date-day d) (date-month d)
  1667. (date-year d) (date-zone-offset d)))))
  1668. (define generation-ctime-alist
  1669. (map (lambda (number)
  1670. (cons number
  1671. (time-second
  1672. (time-at-midnight
  1673. (generation-time profile number)))))
  1674. (generation-numbers profile)))
  1675. (match duration
  1676. (#f #f)
  1677. (res
  1678. (let ((s (time-second
  1679. (subtract-duration (time-at-midnight (current-time))
  1680. duration))))
  1681. (delete #f (map (lambda (x)
  1682. (and (duration-relation s (cdr x))
  1683. (first x)))
  1684. generation-ctime-alist))))))
  1685. (cond ((string->generations str)
  1686. =>
  1687. filter-generations)
  1688. ((string->duration str)
  1689. =>
  1690. filter-by-duration)
  1691. (else
  1692. (raise
  1693. (formatted-message (G_ "invalid syntax: ~a~%") str)))))
  1694. (define (display-generation profile number)
  1695. "Display a one-line summary of generation NUMBER of PROFILE."
  1696. (unless (zero? number)
  1697. (let* ((file (generation-file-name profile number))
  1698. (link (if (supports-hyperlinks?)
  1699. (cut file-hyperlink file <>)
  1700. identity))
  1701. (header (format #f (link (highlight (G_ "Generation ~a\t~a")))
  1702. number
  1703. (date->string
  1704. (time-utc->date
  1705. (generation-time profile number))
  1706. ;; TRANSLATORS: This is a format-string for date->string.
  1707. ;; Please choose a format that corresponds to the
  1708. ;; usual way of presenting dates in your locale.
  1709. ;; See https://www.gnu.org/software/guile/manual/html_node/SRFI_002d19-Date-to-string.html
  1710. ;; for details.
  1711. (G_ "~b ~d ~Y ~T"))))
  1712. (current (generation-number profile)))
  1713. (if (= number current)
  1714. ;; TRANSLATORS: The word "current" here is an adjective for
  1715. ;; "Generation", as in "current generation". Use the appropriate
  1716. ;; gender where applicable.
  1717. (format #t (G_ "~a\t(current)~%") header)
  1718. (format #t "~a~%" header)))))
  1719. (define (display-profile-content-diff profile gen1 gen2)
  1720. "Display the changed packages in PROFILE GEN2 compared to generation GEN1."
  1721. (define (equal-entry? first second)
  1722. (string= (manifest-entry-item first) (manifest-entry-item second)))
  1723. (define (display-entry entry prefix)
  1724. (match entry
  1725. (($ <manifest-entry> name version output location _)
  1726. (format #t " ~a ~a\t~a\t~a\t~a~%" prefix name version output location))))
  1727. (define (list-entries number)
  1728. (manifest-entries (profile-manifest (generation-file-name profile number))))
  1729. (define (display-diff profile old new)
  1730. (display-generation profile new)
  1731. (let ((added (lset-difference
  1732. equal-entry? (list-entries new) (list-entries old)))
  1733. (removed (lset-difference
  1734. equal-entry? (list-entries old) (list-entries new))))
  1735. (for-each (cut display-entry <> "+") added)
  1736. (for-each (cut display-entry <> "-") removed)
  1737. (newline)))
  1738. (display-diff profile gen1 gen2))
  1739. (define (profile-lock-handler profile errno . _)
  1740. "Handle failure to acquire PROFILE's lock."
  1741. ;; NFS mounts can return ENOLCK. When that happens, there's not much that
  1742. ;; can be done, so warn the user and keep going.
  1743. (if (= errno ENOLCK)
  1744. (warning (G_ "cannot lock profile ~a: ~a~%")
  1745. profile (strerror errno))
  1746. (leave (G_ "profile ~a is locked by another process~%")
  1747. profile)))
  1748. (define profile-lock-file
  1749. (cut string-append <> ".lock"))
  1750. (define-syntax-rule (with-profile-lock profile exp ...)
  1751. "Grab PROFILE's lock and evaluate EXP... Call 'leave' if the lock is
  1752. already taken."
  1753. (with-file-lock/no-wait (profile-lock-file profile)
  1754. (cut profile-lock-handler profile <...>)
  1755. exp ...))
  1756. (define (display-profile-content profile number)
  1757. "Display the packages in PROFILE, generation NUMBER, in a human-readable
  1758. way."
  1759. (for-each (match-lambda
  1760. (($ <manifest-entry> name version output location _)
  1761. (format #t " ~a\t~a\t~a\t~a~%"
  1762. name version output location)))
  1763. ;; Show most recently installed packages last.
  1764. (reverse
  1765. (manifest-entries
  1766. (profile-manifest (generation-file-name profile number))))))
  1767. (define (display-generation-change previous current)
  1768. (format #t (G_ "switched from generation ~a to ~a~%") previous current))
  1769. (define (roll-back* store profile)
  1770. "Like 'roll-back', but display what is happening."
  1771. (call-with-values
  1772. (lambda ()
  1773. (roll-back store profile))
  1774. display-generation-change))
  1775. (define (switch-to-generation* profile number)
  1776. "Like 'switch-to-generation', but display what is happening."
  1777. (let ((previous (switch-to-generation profile number)))
  1778. (display-generation-change previous number)))
  1779. (define (delete-generation* store profile generation)
  1780. "Like 'delete-generation', but display what is going on."
  1781. (format #t (G_ "deleting ~a~%")
  1782. (generation-file-name profile generation))
  1783. (delete-generation store profile generation))
  1784. (define* (package-specification->name+version+output spec
  1785. #:optional (output "out"))
  1786. "Parse package specification SPEC and return three value: the specified
  1787. package name, version number (or #f), and output name (or OUTPUT). SPEC may
  1788. optionally contain a version number and an output name, as in these examples:
  1789. guile
  1790. guile@2.0.9
  1791. guile:debug
  1792. guile@2.0.9:debug
  1793. "
  1794. (let*-values (((name sub-drv)
  1795. (match (string-rindex spec #\:)
  1796. (#f (values spec output))
  1797. (colon (values (substring spec 0 colon)
  1798. (substring spec (+ 1 colon))))))
  1799. ((name version)
  1800. (package-name->name+version name)))
  1801. (values name version sub-drv)))
  1802. ;;;
  1803. ;;; Command-line option processing.
  1804. ;;;
  1805. (define (show-guix-usage)
  1806. (format (current-error-port)
  1807. (G_ "Try `guix --help' for more information.~%"))
  1808. (exit 1))
  1809. ;; Representation of a 'guix' command.
  1810. (define-immutable-record-type <command>
  1811. (command name synopsis category)
  1812. command?
  1813. (name command-name)
  1814. (synopsis command-synopsis)
  1815. (category command-category))
  1816. (define (source-file-command file)
  1817. "Read FILE, a Scheme source file, and return either a <command> object based
  1818. on the 'define-command' top-level form found therein, or #f if FILE does not
  1819. contain a 'define-command' form."
  1820. (define command-name
  1821. (match (filter (negate string-null?)
  1822. (string-split file #\/))
  1823. ((_ ... "guix" (or "scripts" "extensions") name)
  1824. (list (file-sans-extension name)))
  1825. ((_ ... "guix" (or "scripts" "extensions") first second)
  1826. (list first (file-sans-extension second)))))
  1827. ;; The strategy here is to parse FILE. This is much cheaper than a
  1828. ;; technique based on run-time introspection where we'd load FILE and all
  1829. ;; the modules it depends on.
  1830. (call-with-input-file file
  1831. (lambda (port)
  1832. (let loop ()
  1833. (match (read port)
  1834. (('define-command _ ('synopsis synopsis)
  1835. _ ...)
  1836. (command command-name synopsis 'main))
  1837. (('define-command _
  1838. ('category category) ('synopsis synopsis)
  1839. _ ...)
  1840. (command command-name synopsis category))
  1841. ((? eof-object?)
  1842. #f)
  1843. (_
  1844. (loop)))))))
  1845. (define* (command-files #:optional directory)
  1846. "Return the list of source files that define Guix sub-commands."
  1847. (define directory*
  1848. (or directory
  1849. (and=> (search-path %load-path "guix.scm")
  1850. (compose (cut string-append <> "/guix/scripts")
  1851. dirname))))
  1852. (define dot-scm?
  1853. (cut string-suffix? ".scm" <>))
  1854. (if directory*
  1855. (map (cut string-append directory* "/" <>)
  1856. (scandir directory* dot-scm?))
  1857. '()))
  1858. (define (extension-directories)
  1859. "Return the list of directories containing Guix extensions."
  1860. (filter file-exists?
  1861. (parse-path
  1862. (getenv "GUIX_EXTENSIONS_PATH"))))
  1863. (define (commands)
  1864. "Return the list of commands, alphabetically sorted."
  1865. (filter-map source-file-command
  1866. (append (command-files)
  1867. (append-map command-files
  1868. (extension-directories)))))
  1869. (define (show-guix-help)
  1870. (define (internal? command)
  1871. (member command '("substitute" "authenticate" "offload"
  1872. "perform-download")))
  1873. (define (display-commands commands)
  1874. (let* ((names (map (lambda (command)
  1875. (string-join (command-name command)))
  1876. commands))
  1877. (max-width (reduce max 0 (map string-length names))))
  1878. (for-each (lambda (name command)
  1879. (format #t " ~a ~a~%"
  1880. (string-pad-right name max-width)
  1881. (G_ (command-synopsis command))))
  1882. names
  1883. commands)))
  1884. (define (category-predicate category)
  1885. (lambda (command)
  1886. (eq? category (command-category command))))
  1887. (format #t (G_ "Usage: guix COMMAND ARGS...
  1888. Run COMMAND with ARGS.\n"))
  1889. (newline)
  1890. (format #t (G_ "COMMAND must be one of the sub-commands listed below:\n"))
  1891. (let ((commands (commands))
  1892. (categories (module-ref (resolve-interface '(guix scripts))
  1893. '%command-categories)))
  1894. (for-each (match-lambda
  1895. (('internal . _)
  1896. #t) ;hide internal commands
  1897. ((category . synopsis)
  1898. (let ((relevant-commands (filter (category-predicate category)
  1899. commands)))
  1900. ;; Only print categories that contain commands.
  1901. (match relevant-commands
  1902. ((one . more)
  1903. (format #t "~% ~a~%" (G_ synopsis))
  1904. (display-commands relevant-commands))
  1905. (_ #f)))))
  1906. categories))
  1907. (show-bug-report-information))
  1908. (define (run-guix-command command . args)
  1909. "Run COMMAND with the given ARGS. Report an error when COMMAND is not
  1910. found."
  1911. (define (command-hint guess commands)
  1912. (define command-names
  1913. (map (lambda (command)
  1914. (match (command-name command)
  1915. ((head tail ...) head)))
  1916. commands))
  1917. (string-closest (symbol->string guess) command-names #:threshold 3))
  1918. (define module
  1919. ;; Check if there is a matching extension.
  1920. (match (search-path (extension-directories)
  1921. (format #f "~a.scm" command))
  1922. (#f
  1923. (catch 'misc-error
  1924. (lambda ()
  1925. (resolve-interface `(guix scripts ,command)))
  1926. (lambda _
  1927. (let ((hint (command-hint command (commands))))
  1928. (format (current-error-port)
  1929. (G_ "guix: ~a: command not found~%") command)
  1930. (when hint
  1931. (display-hint (format #f (G_ "Did you mean @code{~a}?")
  1932. hint)))
  1933. (show-guix-usage)))))
  1934. (file
  1935. (load file)
  1936. (resolve-interface `(guix extensions ,command)))))
  1937. (let ((command-main (module-ref module
  1938. (symbol-append 'guix- command))))
  1939. (parameterize ((program-name command))
  1940. ;; Disable canonicalization so we don't don't stat unreasonably.
  1941. (with-fluids ((%file-port-name-canonicalization #f))
  1942. (dynamic-wind
  1943. (const #f)
  1944. (lambda ()
  1945. (apply command-main args))
  1946. (lambda ()
  1947. ;; Abuse 'exit-hook' (which is normally meant to be used by the
  1948. ;; REPL) to run things like profiling hooks upon completion.
  1949. (run-hook exit-hook)))))))
  1950. (define (run-guix . args)
  1951. "Run the 'guix' command defined by command line ARGS.
  1952. Unlike 'guix-main', this procedure assumes that locale, i18n support,
  1953. and signal handling have already been set up."
  1954. (define option? (cut string-prefix? "-" <>))
  1955. ;; The default %LOAD-EXTENSIONS includes the empty string, which doubles the
  1956. ;; number of 'stat' calls per entry in %LOAD-PATH. Shamelessly remove it.
  1957. (set! %load-extensions '(".scm"))
  1958. (match args
  1959. (()
  1960. (format (current-error-port)
  1961. (G_ "guix: missing command name~%"))
  1962. (show-guix-usage))
  1963. ((or ("-h") ("--help"))
  1964. (leave-on-EPIPE (show-guix-help)))
  1965. ((or ("-V") ("--version"))
  1966. (show-version-and-exit "guix"))
  1967. (((? option? o) args ...)
  1968. (format (current-error-port)
  1969. (G_ "guix: unrecognized option '~a'~%") o)
  1970. (show-guix-usage))
  1971. (("help" command)
  1972. (apply run-guix-command (string->symbol command)
  1973. '("--help")))
  1974. (("help" args ...)
  1975. (leave-on-EPIPE (show-guix-help)))
  1976. ((command args ...)
  1977. (apply run-guix-command
  1978. (string->symbol command)
  1979. args))))
  1980. (define (guix-main arg0 . args)
  1981. (initialize-guix)
  1982. (apply run-guix args))
  1983. ;;; Local Variables:
  1984. ;;; eval: (put 'guard* 'scheme-indent-function 2)
  1985. ;;; End:
  1986. ;;; ui.scm ends here