ui.scm 88 KB

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