ui.scm 86 KB

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