vpac / src / pkgbuild_install.v
639 lines · 601 sloc · 21.83 KB · 841315c100c81d9e6b14c4b55a25d4e3d12db762
Raw
1module main
2
3import nspkg
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 &nspkg.Handle
29 installed &nspkg.List
30 sync_dbs &nspkg.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 cd := 'cd ${vmakepkg.shell_quote(dir)} && '
127 if os.uname().sysname.to_lower() == 'vinix' {
128 return cd + 'export VPAC_MAKEPKG_EXE=${vmakepkg.shell_quote(os.executable())} VPAC_MAKEPKG_ROOT=${vmakepkg.shell_quote(root_path)} VPAC_MAKEPKG_DB=${vmakepkg.shell_quote(db_path)} && ' +
129 pkgbuild_makepkg
130 }
131 return cd + pkgbuild_makepkg
132}
133
134// makepkg's bash helpers open process substitutions through /dev/fd.
135// Vinix supplies the descriptors in procfs and recreates /dev at boot.
136fn run_makepkg(user string, dir string) ! {
137 if os.uname().sysname.to_lower() == 'vinix' {
138 // makepkg queries the local database as the builder, including on first use.
139 handle := nspkg.initialize(root_path, db_path)!
140 handle.release()!
141 if !os.is_dir('/dev/fd') {
142 os.symlink('/proc/self/fd', '/dev/fd') or {
143 if !os.is_dir('/dev/fd') {
144 return error('makepkg needs /dev/fd linked to /proc/self/fd: ${err}')
145 }
146 }
147 }
148 }
149 run_as_user(user, ['sh', '-c', makepkg_line(dir)])!
150}
151
152// makepkg reads these pacman queries to check dependencies and write .BUILDINFO.
153// use the same local package cache as the transaction that installs the build.
154fn makepkg_query(args []string) !int {
155 if args.len == 0 {
156 return error('makepkg did not specify a database query')
157 }
158 handle := nspkg.initialize(os.getenv('VPAC_MAKEPKG_ROOT'), os.getenv('VPAC_MAKEPKG_DB'))!
159 defer { handle.release() or { went_on('release the nspkg handle', err) } }
160 cache := local_pkgcache(handle)!
161 match args[0] {
162 '-T' {
163 missing := unsatisfied_deps(cache, args[1..])
164 for dep in missing {
165 println(dep)
166 }
167 if missing.len > 0 {
168 return 127
169 }
170 }
171 '-Qi', '-Qq' {
172 if args.len != 1 {
173 return error('makepkg expected a query for all installed packages')
174 }
175 for pkg in cache.pkgs() {
176 if args[0] == '-Qq' {
177 println(pkg.get_name())
178 } else {
179 println('Name : ${pkg.get_name()}\nVersion : ${pkg.get_version()}\nArchitecture : ${pkg.get_arch()}')
180 }
181 }
182 }
183 else { return error('unsupported makepkg database query: ${args[0]}') }
184 }
185 return 0
186}
187
188// run_process runs a command, its arguments reaching it one by one with no
189// shell in between to quote wrong, and answers its exit code. with capture
190// its stdout comes back as text, and its stderr is passed on as it arrives:
191// both pipes are drained while the child lives, so one that fills the
192// stderr pipe never waits on a reader that is itself waiting on stdout.
193// without capture the terminal is the child's own
194fn run_process(argv []string, capture bool) !(string, int) {
195 exe := os.find_abs_path_of_executable(argv[0]) or {
196 return error('${argv[0]} is needed, but it was not found')
197 }
198 mut process := os.new_process(exe)
199 process.set_args(argv[1..])
200 mut out := ''
201 if capture {
202 process.set_redirect_stdio()
203 process.run()
204 for process.is_alive() {
205 mut idle := true
206 if process.is_pending(.stdout) {
207 out += process.stdout_read()
208 idle = false
209 }
210 if process.is_pending(.stderr) {
211 eprint(process.stderr_read())
212 idle = false
213 }
214 if idle {
215 time.sleep(2 * time.millisecond)
216 }
217 }
218 out += process.stdout_slurp()
219 eprint(process.stderr_slurp())
220 }
221 process.wait()
222 code := process.code
223 process.close()
224 return out, code
225}
226
227// as_user runs a command as the invoking user, through runuser
228fn as_user(user string, args []string, capture bool) !string {
229 mut cmd := ['runuser', '-u', user, '--']
230 cmd << args
231 out, code := run_process(cmd, capture) or {
232 return error('${cmd[0]} is needed to run this as ${user}, but it was not found')
233 }
234 if code != 0 {
235 return error('${args[0]} failed as user ${user} (exit ${code})')
236 }
237 return out
238}
239
240// output_as_user runs a command as the invoking user, as run_as_user does,
241// and returns what it printed on stdout
242fn output_as_user(user string, args []string) !string {
243 return as_user(user, args, true)
244}
245
246// run_as_user runs a command as the invoking user, with the terminal passed on
247fn run_as_user(user string, args []string) ! {
248 as_user(user, args, false)!
249}
250
251// ReviewFile is one file a build runs, shown whole before it is built.
252// keep the generated field in the IPC review event for existing frontends.
253struct ReviewFile {
254 name string
255 text string
256 generated bool
257}
258
259// ReviewEvent is what a build runs, shown before the question that builds
260// it: the warnings about where it comes from, its files, and the names in
261// its dir
262struct ReviewEvent {
263 kind string = 'review' @[json: 'type']
264 package string
265mut:
266 files []ReviewFile
267 listing []string
268 warnings []string
269}
270
271// read_review collects a PKGBUILD dir's review: the PKGBUILD, every .install
272// script and the list of files that make up the package
273fn read_review(package string, dir string) !ReviewEvent {
274 mut parts := [ReviewFile{
275 name: 'PKGBUILD'
276 text: os.read_file('${dir}/PKGBUILD')!
277 }]
278 mut names := os.ls(dir)!
279 names.sort()
280 mut listing := []string{}
281 for f in names {
282 if f == '.git' {
283 continue
284 }
285 if f.ends_with('.install') {
286 parts << ReviewFile{
287 name: f
288 text: os.read_file('${dir}/${f}')!
289 }
290 }
291 listing << f
292 }
293 return ReviewEvent{
294 package: package
295 files: parts
296 listing: listing
297 }
298}
299
300// show_review shows a review: on a terminal the warnings, the title, every
301// file under its name and the files in the package; a frontend gets it as
302// one event
303fn show_review(r ReviewEvent, title string) {
304 if ipc_on() {
305 emit(ReviewEvent{
306 ...r
307 warnings: r.warnings.map(it.trim_space())
308 })
309 return
310 }
311 println(review_text(r, title))
312}
313
314// review_text is a review for the terminal: the warnings, the title, every
315// file under its name, and the files in the package
316fn review_text(r ReviewEvent, title string) string {
317 mut out := r.warnings.map(warning(it))
318 if title != '' {
319 out << heading(title)
320 }
321 for f in r.files {
322 out << heading(f.name)
323 out << f.text
324 }
325 if r.listing.len > 0 {
326 out << heading('files in the package')
327 out << r.listing.join(' ')
328 }
329 return out.join('\n')
330}
331
332// build_phase tells a frontend a build runs; a terminal sees makepkg's own
333// output, which goes to the frontend's log
334fn build_phase(name string, state string) {
335 if ipc_on() {
336 emit(PhaseEvent{
337 text: 'building ${name}'
338 state: state
339 })
340 }
341}
342
343// built_packages lists the archives a build produced, as makepkg names them
344// itself: the build command with --packagelist answers the files this
345// PKGBUILD's version packs to, wherever PKGDEST puts them and whatever PKGEXT
346// is. a name pattern over the build dir missed an uncompressed .pkg.tar and
347// another PKGDEST, and took an older build's archive a pulled checkout
348// carried — of two, the directory's order chose which was installed
349fn built_packages(user string, dir string) ![]string {
350 out := output_as_user(user, ['sh', '-c', '${makepkg_line(dir)} --packagelist'])!
351 return packagelist_files(out)
352}
353
354// packagelist_files are the paths --packagelist printed that the build did
355// produce: it names every package the PKGBUILD can make (a debug package
356// among them) whether built or not, so only the files that are there count
357fn packagelist_files(output string) []string {
358 return output.split_into_lines().map(it.trim_space()).filter(it.starts_with('/')
359 && os.is_file(it))
360}
361
362// archives_in lists the package archives a build dir holds, whatever version
363// or build made them: what clean asks of a build, to keep one that holds an
364// installed package's archive. an uncompressed .pkg.tar is one too
365fn archives_in(dir string) ![]string {
366 mut out := []string{}
367 for f in os.ls(dir)! {
368 if is_pkg_archive(f) {
369 out << '${dir}/${f}'
370 } else if f.starts_with('.vpac-') && os.is_dir('${dir}/${f}') && !os.is_link('${dir}/${f}') {
371 // completed native archives live beside this build's src and pkg directories.
372 for name in os.ls('${dir}/${f}')! {
373 if is_pkg_archive(name) { out << os.join_path(dir, f, name) }
374 }
375 }
376 }
377 return out
378}
379
380// pkgbuild_warnings are what the pkgbuild repo knows of a package that a
381// review wants beside the files: who keeps it, how many vouch for it, and
382// whether it was flagged
383fn pkgbuild_warnings(info PackagePkgbuild) []string {
384 maintainer := info.maintainer or { 'none (orphaned)' }
385 mut out := ['maintainer: ${maintainer}, votes: ${info.num_votes}']
386 if info.out_of_date != none {
387 out << 'flagged as out of date'
388 }
389 return out
390}
391
392// review_and_build asks its way to a build: whether the package is to come
393// from the pkgbuild repo at all (no by default), then whether its pkgbuild
394// is to be read first (yes by default), then the build's own question, asked
395// whether or not the review was read, so the build can still be declined.
396// the gate is the caller's to word: install asks the generic question, and
397// an upgrade names the versions it would go from and to. searched says the
398// repos were looked in before, which a -b target's never were. only then
399// does it install the repo packages the build needs, and build. returns the
400// archives; a no to a question is a BuildDeclined, which is the user's
401// answer and not a failure of the build
402fn review_and_build(mut ui TransUI, user string, node PkgbuildNode, config ConfigInstall, searched bool, gate string) ![]string {
403 name := node.info.name
404 base := node.info.package_base
405 dir := pkgbuild_build_dir(user, base)!
406 ask := !config.no_pkgbuild_confirm
407 // --noconfirm would take the first question's preset, which is no: the
408 // refusal says so before anything is cloned
409 if config.noconfirm && ask {
410 return error('pkgbuild packages are asked about: drop --noconfirm, or pass --nopkgbuildconfirm, to build ${name}')
411 }
412 ui.pause()
413 // the display is paused for the questions, the clone and the review; the
414 // run leaves it paused-through for the build, and syncs on the way out
415 defer { ui.sync() }
416 if searched {
417 warn('${name} was not found in the repos')
418 }
419 q := if gate != '' {
420 gate
421 } else {
422 'install ${name} from the pkgbuild repo (${node.repo})?'
423 }
424 if ask && !ui.noyes(q) {
425 return BuildDeclined{}
426 }
427 run_as_user(user, ['mkdir', '-p', pkgbuild_root(user)!])!
428 run_as_user(user, ['rm', '-rf', dir])!
429 run_as_user(user, ['git', 'clone', '--depth', '${pkgbuild_depth}', '${node.site}/${base}.git',
430 dir])!
431
432 // with --nopkgbuildconfirm nothing is asked, and the review is still
433 // shown: the record of what was built stays in the output
434 source_name := build_recipe_name(dir)!
435 if !ask || ui.yesno('review the pkgbuild?') {
436 mut review := recipe_review(user, name, dir, source_name)!
437 review.warnings = pkgbuild_warnings(node.info)
438 show_review(review, 'review ${name}')
439 }
440 prompt := if node.repo_deps.len > 0 {
441 'build and install ${name}, after installing its repo dependencies ${node.repo_deps.join(', ')}?'
442 } else {
443 'build and install ${name}?'
444 }
445 if ask && !ui.yesno(prompt) {
446 return BuildDeclined{}
447 }
448 if node.repo_deps.len > 0 {
449 install_repo_deps(node.repo_deps)!
450 ui.sync()
451 }
452 build_phase(name, 'start')
453 archives := build_archives(user, dir, source_name)!
454 build_phase(name, 'done')
455 return archives
456}
457
458// BuildDeclined is review_and_build's answer when the user said no
459struct BuildDeclined {
460 Error
461}
462
463fn (e BuildDeclined) msg() string {
464 return 'the build was declined'
465}
466
467// local_now opens the installed packages as they are at this moment, on a
468// handle of its own that the caller releases. the run's handle read the
469// local db when the run began, and every build since was installed through
470// another one (install's): its list is the past, and what is planned, asked
471// and skipped from here on is decided on the present
472fn local_now() !(&nspkg.Handle, &nspkg.List) {
473 handle := nspkg.initialize(root_path, db_path) or {
474 return error('could not read the local database: ${err.msg()}')
475 }
476 pkgs := local_pkgcache(handle) or {
477 handle.release() or { went_on('release the nspkg handle', err) }
478 return err
479 }
480 return handle, pkgs
481}
482
483// NodeStep is what is left to do for a node once the installed packages
484// are read again: nothing (skip, and why), or the build, with the repo
485// packages it still needs first
486struct NodeStep {
487 skip bool
488 why string
489 repo_deps []string
490}
491
492// node_step decides a node against the installed packages as they are now.
493// a dependency node is dropped when everything that wanted it is satisfied
494// by what is installed — an earlier build of this run that provides it, a
495// split package that came with its sibling — and never merely because a
496// package of its name is there at some version. the target is only ever
497// skipped by --needed, at the very version it would install. the repo
498// dependencies are the ones still missing
499fn node_step(installed &nspkg.List, node PkgbuildNode, needed bool, is_target bool) NodeStep {
500 name := node.info.name
501 if !is_target && node.wanted.len > 0
502 && node.wanted.all(installed.find_satisfier(it) != none) {
503 return NodeStep{
504 skip: true
505 why: '${name} is satisfied by what is installed now, not built'
506 }
507 }
508 if is_target && needed {
509 if local := installed.pkg_find(name) {
510 if nspkg.pkg_vercmp(local.get_version(), node.info.version) == 0 {
511 return NodeStep{
512 skip: true
513 why: '${name}-${node.info.version} is up to date, skipped'
514 }
515 }
516 }
517 }
518 return NodeStep{
519 repo_deps: node.repo_deps.filter(installed.pkg_find(it) == none)
520 }
521}
522
523// node_step_now is node_step on the local db read this moment
524fn node_step_now(node PkgbuildNode, needed bool, is_target bool) !NodeStep {
525 view, installed := local_now()!
526 defer { view.release() or { went_on('release the nspkg handle', err) } }
527 return node_step(installed, node, needed, is_target)
528}
529
530// install_repo_deps installs the repo packages a build needs, as
531// dependencies, through an install of its own: a fresh handle, so the
532// transaction is checked against the packages installed now and not against
533// what the run's handle read before the earlier builds went in. the
534// pkgbuild's questions were the go-ahead for the build and what it needs,
535// so the listing is shown and taken as --noconfirm takes it; nothing beyond
536// the named packages and what they depend on is upgraded along
537fn install_repo_deps(names []string) ! {
538 if names.len == 0 {
539 return
540 }
541 install(ConfigInstall{
542 query: names
543 noconfirm: true
544 asdeps: true
545 no_upgrade_deps: true
546 }) or { return error('the build dependencies ${names.join(', ')} were not installed: ${err.msg()}') }
547}
548
549// built_install_config is the install of what a pkgbuild built, as the outer
550// command line asked for it: the archives are the targets, a dependency
551// node is installed as a dependency whatever the target's reason is, and
552// what was said of the transaction (ignores, overwrites, the dependency
553// checks, the timeout) holds for this one as well. what belongs to the
554// outer run alone — the pkgbuild flags, --needed, --print, --download-only —
555// stays behind
556fn built_install_config(config ConfigInstall, archives []string, is_target bool) ConfigInstall {
557 return ConfigInstall{
558 query: archives
559 noconfirm: config.noconfirm
560 asdeps: if is_target { config.asdeps } else { true }
561 asexplicit: is_target && config.asexplicit
562 dbonly: config.dbonly
563 nodeps: config.nodeps
564 nodeps_level: config.nodeps_level
565 overwrite: config.overwrite
566 assume_installed: config.assume_installed
567 ignore: config.ignore
568 ignoregroup: config.ignoregroup
569 no_upgrade_deps: config.no_upgrade_deps
570 disable_timeout: config.disable_timeout
571 }
572}
573
574// pkgbuild_plan resolves target into its build plan, dependencies first,
575// against the local db read this moment and the handle's sync dbs
576fn pkgbuild_plan(handle &nspkg.Handle, target string) ![]PkgbuildNode {
577 view, installed := local_now()!
578 defer { view.release() or { went_on('release the nspkg handle', err) } }
579 mut r := PkgbuildResolver{
580 // the caller's handle outlives the plan: it is only read here
581 handle: unsafe { handle }
582 installed: installed
583 sync_dbs: handle.get_syncdbs()!
584 }
585 r.visit(target)!
586 return r.planned()
587}
588
589// pkgbuild_install builds an AUR package and the AUR packages it needs, reviewing
590// each one, then installs what was built. the gate is the first question's
591// word, the caller's to write — the generic install question when it is empty
592fn pkgbuild_install(mut ui TransUI, mut handle &nspkg.Handle, config ConfigInstall, target string, gate string) ! {
593 user := invoker_user()!
594 // the plan is resolved against the installed packages as they are now:
595 // an earlier target of this run may have been built and installed since
596 // the handle read them. the sync dbs are the handle's, which no install
597 // changes
598 nodes := pkgbuild_plan(handle, target)!
599
600 for i, planned in nodes {
601 // the nodes come dependencies first: the last one is the target
602 is_target := i == nodes.len - 1
603 // and each node is decided when its turn comes, after everything
604 // before it was installed
605 step := node_step_now(planned, config.needed, is_target)!
606 if step.skip {
607 // warn speaks both a terminal's and a frontend's language, the
608 // way an install's own --needed does
609 warn(step.why)
610 continue
611 }
612 node := PkgbuildNode{
613 ...planned
614 repo_deps: step.repo_deps
615 }
616 archives := review_and_build(mut ui, user, node, config, !(is_target
617 && config.pkgbuild), gate) or {
618 if err is BuildDeclined {
619 // a no is a quiet stop: nothing after this node can be built
620 // without it, and nothing went wrong
621 advise('${node.info.name} was declined, nothing more is built')
622 return
623 }
624 return err
625 }
626 if archives.len == 0 {
627 return error('${node.info.name} was not built')
628 }
629 // a pkgbuild dependency is installed as a dependency, the way the
630 // repo ones are; the target takes --asdeps or --asexplicit. the
631 // whole of what came out of the pkgbuild goes into one install, so a
632 // split package set lands as one transaction, with its ordering, its
633 // hooks and its prompt, instead of one apiece
634 install(built_install_config(config, archives, is_target))!
635 }
636 // everything built was installed by install() above, which already
637 // reports "installed: <package>"; provenance comes from the question
638 // asked before the build
639}
640