ui.scm 72 KB

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