ui.scm 89 KB

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