ui.scm 88 KB

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