ui.scm 89 KB

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