vpac / src / pkgbuild_install.v
578 lines · 542 sloc · 19.64 KB · 6ecabf51a7e6b50dae0593172d6edd8378facdf3
Raw
1module main
2
3import alpm
4import os
5import time
6import vmakepkg
7
8// PkgbuildNode is one pkgbuild package in build order: the repo packages it needs first,
9// then itself. site is the pkgbuild repo the package came from, repo the
10// name the config gives it
11struct PkgbuildNode {
12 info PackagePkgbuild
13 site string
14 repo string
15 repo_deps []string
16 // wanted are the dependency strings that put the node in the plan, as
17 // the packages that need it spell them; the target has none. they are
18 // what tells, once earlier builds are installed, whether this one is
19 // still needed
20 wanted []string
21}
22
23// PkgbuildResolver walks the dependencies of a pkgbuild package. a dependency that is
24// installed or in the repos is used as it is; one that is neither is looked up
25// in the pkgbuild repo and placed before the package that needs it
26struct PkgbuildResolver {
27mut:
28 handle &alpm.Handle
29 installed &alpm.List
30 sync_dbs &alpm.List
31 // visiting holds the names on the branch being walked, so a cycle is a
32 // named error instead of a node silently skipped; done holds the ones
33 // whose nodes are already in, so they are never built twice
34 visiting map[string]bool
35 done map[string]bool
36 nodes []PkgbuildNode
37 // wanted gathers, by node name, every dependency string that led to the
38 // node, the later ones too: a node is planned once and wanted often
39 wanted map[string][]string
40}
41
42// planned is the plan as it stands: the nodes in build order, each with
43// everything that wanted it
44fn (r &PkgbuildResolver) planned() []PkgbuildNode {
45 return r.nodes.map(PkgbuildNode{
46 ...it
47 wanted: r.wanted[it.info.name].clone()
48 })
49}
50
51fn (mut r PkgbuildResolver) visit(name string) ! {
52 if r.done[name] {
53 return
54 }
55 if r.visiting[name] {
56 return error('circular pkgbuild dependency: ${name} is walked as its own dependency')
57 }
58 r.visiting[name] = true
59 defer {
60 r.visiting.delete(name)
61 }
62 pkg_info, site, from := pkgbuild_lookup(name)!
63 if site == '' {
64 return error('"${name}" is not in the repos or the pkgbuild repo')
65 }
66 mut repo := []string{}
67 mut deps := []string{}
68 deps << pkg_info.depends
69 deps << pkg_info.make_depends
70 // makepkg runs check() by default, so what it needs is needed before
71 // the build is queued, not found missing inside it
72 deps << pkg_info.check_depends
73 for dep in deps {
74 if p := r.handle.resolve_dep(r.installed, r.sync_dbs, dep) {
75 if p.get_origin() == .syncdb {
76 repo << p.get_name()
77 }
78 continue
79 }
80 if dep !in r.wanted[dep_name(dep)] {
81 r.wanted[dep_name(dep)] << dep
82 }
83 r.visit(dep_name(dep))!
84 }
85 r.nodes << PkgbuildNode{
86 info: pkg_info
87 site: site
88 repo: from
89 repo_deps: repo
90 }
91 // only a node that arrived in the plan counts as done: one whose walk
92 // failed wants reporting when it is reached again
93 r.done[name] = true
94}
95
96// dep_name strips a version constraint: 'glibc>=2.27' is 'glibc'
97fn dep_name(dep string) string {
98 return dep.trim_space().all_before('<').all_before('>').all_before('=').trim_space()
99}
100
101// pkgbuild_root is the dir every build lives under. the configured dir is
102// taken under the invoking user's home when it is relative, because makepkg
103// runs as that user
104fn pkgbuild_root(user string) !string {
105 if pkgbuild_dir.starts_with('/') {
106 return pkgbuild_dir
107 }
108 return os.join_path(user_home(user)!, pkgbuild_dir)
109}
110
111// pkgbuild_build_dir is where a package is cloned and built
112fn pkgbuild_build_dir(user string, base string) !string {
113 // the base is the rpc's answer, and the dir it names is removed before
114 // the clone: only one plain path component may stand here
115 if base == '' || base in ['.', '..'] || base.contains('/') || base.starts_with('-') {
116 return error('the pkgbuild repo answered a package base that is not a plain name: "${base}"')
117 }
118 return '${pkgbuild_root(user)!}/${base}'
119}
120
121// makepkg_line is the shell line a build runs in its dir: the dir quoted as
122// one word, then the configured build command — config text passed through
123// the shell on purpose, trusted as far as the config it comes from, and
124// reviewed by the user beside everything else a pkgbuild runs
125fn makepkg_line(dir string) string {
126 return 'cd ${vmakepkg.shell_quote(dir)} && ${pkgbuild_makepkg}'
127}
128
129// run_process runs a command, its arguments reaching it one by one with no
130// shell in between to quote wrong, and answers its exit code. with capture
131// its stdout comes back as text, and its stderr is passed on as it arrives:
132// both pipes are drained while the child lives, so one that fills the
133// stderr pipe never waits on a reader that is itself waiting on stdout.
134// without capture the terminal is the child's own
135fn run_process(argv []string, capture bool) !(string, int) {
136 exe := os.find_abs_path_of_executable(argv[0]) or {
137 return error('${argv[0]} is needed, but it was not found')
138 }
139 mut process := os.new_process(exe)
140 process.set_args(argv[1..])
141 mut out := ''
142 if capture {
143 process.set_redirect_stdio()
144 process.run()
145 for process.is_alive() {
146 mut idle := true
147 if process.is_pending(.stdout) {
148 out += process.stdout_read()
149 idle = false
150 }
151 if process.is_pending(.stderr) {
152 eprint(process.stderr_read())
153 idle = false
154 }
155 if idle {
156 time.sleep(2 * time.millisecond)
157 }
158 }
159 out += process.stdout_slurp()
160 eprint(process.stderr_slurp())
161 }
162 process.wait()
163 code := process.code
164 process.close()
165 return out, code
166}
167
168// as_user runs a command as the invoking user, through runuser
169fn as_user(user string, args []string, capture bool) !string {
170 mut cmd := ['runuser', '-u', user, '--']
171 cmd << args
172 out, code := run_process(cmd, capture) or {
173 return error('${cmd[0]} is needed to run this as ${user}, but it was not found')
174 }
175 if code != 0 {
176 return error('${args[0]} failed as user ${user} (exit ${code})')
177 }
178 return out
179}
180
181// output_as_user runs a command as the invoking user, as run_as_user does,
182// and returns what it printed on stdout
183fn output_as_user(user string, args []string) !string {
184 return as_user(user, args, true)
185}
186
187// run_as_user runs a command as the invoking user, with the terminal passed on
188fn run_as_user(user string, args []string) ! {
189 as_user(user, args, false)!
190}
191
192// ReviewFile is one file a build runs, shown whole before it is built.
193// generated marks a file vpac wrote from a PKGBUILD.lip or a PKGBUILD.vsh
194struct ReviewFile {
195 name string
196 text string
197 generated bool
198}
199
200// ReviewEvent is what a build runs, shown before the question that builds
201// it: the warnings about where it comes from, its files, and the names in
202// its dir
203struct ReviewEvent {
204 kind string = 'review' @[json: 'type']
205 package string
206mut:
207 files []ReviewFile
208 listing []string
209 warnings []string
210}
211
212// read_review collects a PKGBUILD dir's review: the PKGBUILD, every .install
213// script and the list of files that make up the package
214fn read_review(package string, dir string) !ReviewEvent {
215 mut parts := [ReviewFile{
216 name: 'PKGBUILD'
217 text: os.read_file('${dir}/PKGBUILD')!
218 }]
219 mut names := os.ls(dir)!
220 names.sort()
221 mut listing := []string{}
222 for f in names {
223 if f == '.git' {
224 continue
225 }
226 if f.ends_with('.install') {
227 parts << ReviewFile{
228 name: f
229 text: os.read_file('${dir}/${f}')!
230 }
231 }
232 listing << f
233 }
234 return ReviewEvent{
235 package: package
236 files: parts
237 listing: listing
238 }
239}
240
241// show_review shows a review: on a terminal the warnings, the title, every
242// file under its name and the files in the package; a frontend gets it as
243// one event
244fn show_review(r ReviewEvent, title string) {
245 if ipc_on() {
246 emit(ReviewEvent{
247 ...r
248 warnings: r.warnings.map(it.trim_space())
249 })
250 return
251 }
252 println(review_text(r, title))
253}
254
255// review_text is a review for the terminal: the warnings, the title, every
256// file under its name, and the files in the package
257fn review_text(r ReviewEvent, title string) string {
258 mut out := r.warnings.map(warning(it))
259 if title != '' {
260 out << heading(title)
261 }
262 for f in r.files {
263 out << heading(if f.generated && f.name == 'PKGBUILD' {
264 'PKGBUILD the build runs'
265 } else {
266 f.name
267 })
268 out << f.text
269 }
270 if r.listing.len > 0 {
271 out << heading('files in the package')
272 out << r.listing.join(' ')
273 }
274 return out.join('\n')
275}
276
277// build_phase tells a frontend a build runs; a terminal sees makepkg's own
278// output, which goes to the frontend's log
279fn build_phase(name string, state string) {
280 if ipc_on() {
281 emit(PhaseEvent{
282 text: 'building ${name}'
283 state: state
284 })
285 }
286}
287
288// built_packages lists the archives a build produced, as makepkg names them
289// itself: the build command with --packagelist answers the files this
290// PKGBUILD's version packs to, wherever PKGDEST puts them and whatever PKGEXT
291// is. a name pattern over the build dir missed an uncompressed .pkg.tar and
292// another PKGDEST, and took an older build's archive a pulled checkout
293// carried — of two, the directory's order chose which was installed
294fn built_packages(user string, dir string) ![]string {
295 out := output_as_user(user, ['sh', '-c', '${makepkg_line(dir)} --packagelist'])!
296 return packagelist_files(out)
297}
298
299// packagelist_files are the paths --packagelist printed that the build did
300// produce: it names every package the PKGBUILD can make (a debug package
301// among them) whether built or not, so only the files that are there count
302fn packagelist_files(output string) []string {
303 return output.split_into_lines().map(it.trim_space()).filter(it.starts_with('/')
304 && os.is_file(it))
305}
306
307// archives_in lists the package archives a build dir holds, whatever version
308// or build made them: what clean asks of a build, to keep one that holds an
309// installed package's archive. an uncompressed .pkg.tar is one too
310fn archives_in(dir string) ![]string {
311 mut out := []string{}
312 for f in os.ls(dir)! {
313 if is_pkg_archive(f) {
314 out << '${dir}/${f}'
315 }
316 }
317 return out
318}
319
320// pkgbuild_warnings are what the pkgbuild repo knows of a package that a
321// review wants beside the files: who keeps it, how many vouch for it, and
322// whether it was flagged
323fn pkgbuild_warnings(info PackagePkgbuild) []string {
324 maintainer := info.maintainer or { 'none (orphaned)' }
325 mut out := ['maintainer: ${maintainer}, votes: ${info.num_votes}']
326 if info.out_of_date != none {
327 out << 'flagged as out of date'
328 }
329 return out
330}
331
332// review_and_build asks its way to a build: whether the package is to come
333// from the pkgbuild repo at all (no by default), then whether its pkgbuild
334// is to be read first (yes by default), then the build's own question, asked
335// whether or not the review was read, so the build can still be declined.
336// the gate is the caller's to word: install asks the generic question, and
337// an upgrade names the versions it would go from and to. searched says the
338// repos were looked in before, which a -b target's never were. only then
339// does it install the repo packages the build needs, and build. returns the
340// archives; a no to a question is a BuildDeclined, which is the user's
341// answer and not a failure of the build
342fn review_and_build(mut ui TransUI, user string, node PkgbuildNode, config ConfigInstall, searched bool, gate string) ![]string {
343 name := node.info.name
344 base := node.info.package_base
345 dir := pkgbuild_build_dir(user, base)!
346 ask := !config.no_pkgbuild_confirm
347 // --noconfirm would take the first question's preset, which is no: the
348 // refusal says so before anything is cloned
349 if config.noconfirm && ask {
350 return error('pkgbuild packages are asked about: drop --noconfirm, or pass --nopkgbuildconfirm, to build ${name}')
351 }
352 ui.pause()
353 // the display is paused for the questions, the clone and the review; the
354 // run leaves it paused-through for the build, and syncs on the way out
355 defer { ui.sync() }
356 if searched {
357 warn('${name} was not found in the repos')
358 }
359 q := if gate != '' {
360 gate
361 } else {
362 'install ${name} from the pkgbuild repo (${node.repo})?'
363 }
364 if ask && !ui.noyes(q) {
365 return BuildDeclined{}
366 }
367 run_as_user(user, ['mkdir', '-p', pkgbuild_root(user)!])!
368 run_as_user(user, ['rm', '-rf', dir])!
369 run_as_user(user, ['git', 'clone', '--depth', '${pkgbuild_depth}', '${node.site}/${base}.git',
370 dir])!
371
372 // with --nopkgbuildconfirm nothing is asked, and the review is still
373 // shown: the record of what was built stays in the output
374 if !ask || ui.yesno('review the pkgbuild?') {
375 mut review := read_review(name, dir)!
376 review.warnings = pkgbuild_warnings(node.info)
377 show_review(review, 'review ${name}')
378 }
379 prompt := if node.repo_deps.len > 0 {
380 'build and install ${name}, after installing its repo dependencies ${node.repo_deps.join(', ')}?'
381 } else {
382 'build and install ${name}?'
383 }
384 if ask && !ui.yesno(prompt) {
385 return BuildDeclined{}
386 }
387 if node.repo_deps.len > 0 {
388 install_repo_deps(node.repo_deps)!
389 ui.sync()
390 }
391 build_phase(name, 'start')
392 run_as_user(user, ['sh', '-c', makepkg_line(dir)])!
393 build_phase(name, 'done')
394 return built_packages(user, dir)!
395}
396
397// BuildDeclined is review_and_build's answer when the user said no
398struct BuildDeclined {
399 Error
400}
401
402fn (e BuildDeclined) msg() string {
403 return 'the build was declined'
404}
405
406// local_now opens the installed packages as they are at this moment, on a
407// handle of its own that the caller releases. the run's handle read the
408// local db when the run began, and every build since was installed through
409// another one (install's): its list is the past, and what is planned, asked
410// and skipped from here on is decided on the present
411fn local_now() !(&alpm.Handle, &alpm.List) {
412 handle := alpm.initialize(root_path, db_path) or {
413 return error('could not read the local database: ${err.msg()}')
414 }
415 pkgs := local_pkgcache(handle) or {
416 handle.release() or { went_on('release the alpm handle', err) }
417 return err
418 }
419 return handle, pkgs
420}
421
422// NodeStep is what is left to do for a node once the installed packages
423// are read again: nothing (skip, and why), or the build, with the repo
424// packages it still needs first
425struct NodeStep {
426 skip bool
427 why string
428 repo_deps []string
429}
430
431// node_step decides a node against the installed packages as they are now.
432// a dependency node is dropped when everything that wanted it is satisfied
433// by what is installed — an earlier build of this run that provides it, a
434// split package that came with its sibling — and never merely because a
435// package of its name is there at some version. the target is only ever
436// skipped by --needed, at the very version it would install. the repo
437// dependencies are the ones still missing
438fn node_step(installed &alpm.List, node PkgbuildNode, needed bool, is_target bool) NodeStep {
439 name := node.info.name
440 if !is_target && node.wanted.len > 0
441 && node.wanted.all(installed.find_satisfier(it) != none) {
442 return NodeStep{
443 skip: true
444 why: '${name} is satisfied by what is installed now, not built'
445 }
446 }
447 if is_target && needed {
448 if local := installed.pkg_find(name) {
449 if alpm.pkg_vercmp(local.get_version(), node.info.version) == 0 {
450 return NodeStep{
451 skip: true
452 why: '${name}-${node.info.version} is up to date, skipped'
453 }
454 }
455 }
456 }
457 return NodeStep{
458 repo_deps: node.repo_deps.filter(installed.pkg_find(it) == none)
459 }
460}
461
462// node_step_now is node_step on the local db read this moment
463fn node_step_now(node PkgbuildNode, needed bool, is_target bool) !NodeStep {
464 view, installed := local_now()!
465 defer { view.release() or { went_on('release the alpm handle', err) } }
466 return node_step(installed, node, needed, is_target)
467}
468
469// install_repo_deps installs the repo packages a build needs, as
470// dependencies, through an install of its own: a fresh handle, so the
471// transaction is checked against the packages installed now and not against
472// what the run's handle read before the earlier builds went in. the
473// pkgbuild's questions were the go-ahead for the build and what it needs,
474// so the listing is shown and taken as --noconfirm takes it; nothing beyond
475// the named packages and what they depend on is upgraded along
476fn install_repo_deps(names []string) ! {
477 if names.len == 0 {
478 return
479 }
480 install(ConfigInstall{
481 query: names
482 noconfirm: true
483 asdeps: true
484 no_upgrade_deps: true
485 }) or { return error('the build dependencies ${names.join(', ')} were not installed: ${err.msg()}') }
486}
487
488// built_install_config is the install of what a pkgbuild built, as the outer
489// command line asked for it: the archives are the targets, a dependency
490// node is installed as a dependency whatever the target's reason is, and
491// what was said of the transaction (ignores, overwrites, the dependency
492// checks, the timeout) holds for this one as well. what belongs to the
493// outer run alone — the pkgbuild flags, --needed, --print, --download-only —
494// stays behind
495fn built_install_config(config ConfigInstall, archives []string, is_target bool) ConfigInstall {
496 return ConfigInstall{
497 query: archives
498 noconfirm: config.noconfirm
499 asdeps: if is_target { config.asdeps } else { true }
500 asexplicit: is_target && config.asexplicit
501 dbonly: config.dbonly
502 nodeps: config.nodeps
503 nodeps_level: config.nodeps_level
504 overwrite: config.overwrite
505 assume_installed: config.assume_installed
506 ignore: config.ignore
507 ignoregroup: config.ignoregroup
508 no_upgrade_deps: config.no_upgrade_deps
509 disable_timeout: config.disable_timeout
510 }
511}
512
513// pkgbuild_plan resolves target into its build plan, dependencies first,
514// against the local db read this moment and the handle's sync dbs
515fn pkgbuild_plan(handle &alpm.Handle, target string) ![]PkgbuildNode {
516 view, installed := local_now()!
517 defer { view.release() or { went_on('release the alpm handle', err) } }
518 mut r := PkgbuildResolver{
519 // the caller's handle outlives the plan: it is only read here
520 handle: unsafe { handle }
521 installed: installed
522 sync_dbs: handle.get_syncdbs()!
523 }
524 r.visit(target)!
525 return r.planned()
526}
527
528// pkgbuild_install builds an AUR package and the AUR packages it needs, reviewing
529// each one, then installs what was built. the gate is the first question's
530// word, the caller's to write — the generic install question when it is empty
531fn pkgbuild_install(mut ui TransUI, mut handle &alpm.Handle, config ConfigInstall, target string, gate string) ! {
532 user := invoker_user()!
533 // the plan is resolved against the installed packages as they are now:
534 // an earlier target of this run may have been built and installed since
535 // the handle read them. the sync dbs are the handle's, which no install
536 // changes
537 nodes := pkgbuild_plan(handle, target)!
538
539 for i, planned in nodes {
540 // the nodes come dependencies first: the last one is the target
541 is_target := i == nodes.len - 1
542 // and each node is decided when its turn comes, after everything
543 // before it was installed
544 step := node_step_now(planned, config.needed, is_target)!
545 if step.skip {
546 // warn speaks both a terminal's and a frontend's language, the
547 // way an install's own --needed does
548 warn(step.why)
549 continue
550 }
551 node := PkgbuildNode{
552 ...planned
553 repo_deps: step.repo_deps
554 }
555 archives := review_and_build(mut ui, user, node, config, !(is_target
556 && config.pkgbuild), gate) or {
557 if err is BuildDeclined {
558 // a no is a quiet stop: nothing after this node can be built
559 // without it, and nothing went wrong
560 advise('${node.info.name} was declined, nothing more is built')
561 return
562 }
563 return err
564 }
565 if archives.len == 0 {
566 return error('${node.info.name} was not built')
567 }
568 // a pkgbuild dependency is installed as a dependency, the way the
569 // repo ones are; the target takes --asdeps or --asexplicit. the
570 // whole of what came out of the pkgbuild goes into one install, so a
571 // split package set lands as one transaction, with its ordering, its
572 // hooks and its prompt, instead of one apiece
573 install(built_install_config(config, archives, is_target))!
574 }
575 // everything built was installed by install() above, which already
576 // reports "installed: <package>"; provenance comes from the question
577 // asked before the build
578}
579