ui.scm 88 KB

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