vpac / src / pkgbuild_install.v
570 lines · 534 sloc · 19.32 KB · 3609dfbd82867dc1034a443f8f9ced529ddbbedd
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// searched says the repos were looked in before, which a -b target's never
337// were. only then does it install the repo packages the build needs, and
338// build. returns the archives; a no to a question is a BuildDeclined, which
339// is the user's answer and not a failure of the build
340fn review_and_build(mut ui TransUI, user string, node PkgbuildNode, config ConfigInstall, searched bool) ![]string {
341 name := node.info.name
342 base := node.info.package_base
343 dir := pkgbuild_build_dir(user, base)!
344 ask := !config.no_pkgbuild_confirm
345 // --noconfirm would take the first question's preset, which is no: the
346 // refusal says so before anything is cloned
347 if config.noconfirm && ask {
348 return error('pkgbuild packages are asked about: drop --noconfirm, or pass --nopkgbuildconfirm, to build ${name}')
349 }
350 ui.pause()
351 // the display is paused for the questions, the clone and the review; the
352 // run leaves it paused-through for the build, and syncs on the way out
353 defer { ui.sync() }
354 if searched {
355 warn('${name} was not found in the repos')
356 }
357 if ask && !ui.noyes('install ${name} from the pkgbuild repo (${node.repo})?') {
358 return BuildDeclined{}
359 }
360 run_as_user(user, ['mkdir', '-p', pkgbuild_root(user)!])!
361 run_as_user(user, ['rm', '-rf', dir])!
362 run_as_user(user, ['git', 'clone', '--depth', '${pkgbuild_depth}', '${node.site}/${base}.git',
363 dir])!
364
365 // with --nopkgbuildconfirm nothing is asked, and the review is still
366 // shown: the record of what was built stays in the output
367 if !ask || ui.yesno('review the pkgbuild?') {
368 mut review := read_review(name, dir)!
369 review.warnings = pkgbuild_warnings(node.info)
370 show_review(review, 'review ${name}')
371 }
372 prompt := if node.repo_deps.len > 0 {
373 'build and install ${name}, after installing its repo dependencies ${node.repo_deps.join(', ')}?'
374 } else {
375 'build and install ${name}?'
376 }
377 if ask && !ui.yesno(prompt) {
378 return BuildDeclined{}
379 }
380 if node.repo_deps.len > 0 {
381 install_repo_deps(node.repo_deps)!
382 ui.sync()
383 }
384 build_phase(name, 'start')
385 run_as_user(user, ['sh', '-c', makepkg_line(dir)])!
386 build_phase(name, 'done')
387 return built_packages(user, dir)!
388}
389
390// BuildDeclined is review_and_build's answer when the user said no
391struct BuildDeclined {
392 Error
393}
394
395fn (e BuildDeclined) msg() string {
396 return 'the build was declined'
397}
398
399// local_now opens the installed packages as they are at this moment, on a
400// handle of its own that the caller releases. the run's handle read the
401// local db when the run began, and every build since was installed through
402// another one (install's): its list is the past, and what is planned, asked
403// and skipped from here on is decided on the present
404fn local_now() !(&alpm.Handle, &alpm.List) {
405 handle := alpm.initialize(root_path, db_path) or {
406 return error('could not read the local database: ${err.msg()}')
407 }
408 pkgs := local_pkgcache(handle) or {
409 handle.release() or { went_on('release the alpm handle', err) }
410 return err
411 }
412 return handle, pkgs
413}
414
415// NodeStep is what is left to do for a node once the installed packages
416// are read again: nothing (skip, and why), or the build, with the repo
417// packages it still needs first
418struct NodeStep {
419 skip bool
420 why string
421 repo_deps []string
422}
423
424// node_step decides a node against the installed packages as they are now.
425// a dependency node is dropped when everything that wanted it is satisfied
426// by what is installed — an earlier build of this run that provides it, a
427// split package that came with its sibling — and never merely because a
428// package of its name is there at some version. the target is only ever
429// skipped by --needed, at the very version it would install. the repo
430// dependencies are the ones still missing
431fn node_step(installed &alpm.List, node PkgbuildNode, needed bool, is_target bool) NodeStep {
432 name := node.info.name
433 if !is_target && node.wanted.len > 0
434 && node.wanted.all(installed.find_satisfier(it) != none) {
435 return NodeStep{
436 skip: true
437 why: '${name} is satisfied by what is installed now, not built'
438 }
439 }
440 if is_target && needed {
441 if local := installed.pkg_find(name) {
442 if alpm.pkg_vercmp(local.get_version(), node.info.version) == 0 {
443 return NodeStep{
444 skip: true
445 why: '${name}-${node.info.version} is up to date, skipped'
446 }
447 }
448 }
449 }
450 return NodeStep{
451 repo_deps: node.repo_deps.filter(installed.pkg_find(it) == none)
452 }
453}
454
455// node_step_now is node_step on the local db read this moment
456fn node_step_now(node PkgbuildNode, needed bool, is_target bool) !NodeStep {
457 view, installed := local_now()!
458 defer { view.release() or { went_on('release the alpm handle', err) } }
459 return node_step(installed, node, needed, is_target)
460}
461
462// install_repo_deps installs the repo packages a build needs, as
463// dependencies, through an install of its own: a fresh handle, so the
464// transaction is checked against the packages installed now and not against
465// what the run's handle read before the earlier builds went in. the
466// pkgbuild's questions were the go-ahead for the build and what it needs,
467// so the listing is shown and taken as --noconfirm takes it; nothing beyond
468// the named packages and what they depend on is upgraded along
469fn install_repo_deps(names []string) ! {
470 if names.len == 0 {
471 return
472 }
473 install(ConfigInstall{
474 query: names
475 noconfirm: true
476 asdeps: true
477 no_upgrade_deps: true
478 }) or { return error('the build dependencies ${names.join(', ')} were not installed: ${err.msg()}') }
479}
480
481// built_install_config is the install of what a pkgbuild built, as the outer
482// command line asked for it: the archives are the targets, a dependency
483// node is installed as a dependency whatever the target's reason is, and
484// what was said of the transaction (ignores, overwrites, the dependency
485// checks, the timeout) holds for this one as well. what belongs to the
486// outer run alone — the pkgbuild flags, --needed, --print, --download-only —
487// stays behind
488fn built_install_config(config ConfigInstall, archives []string, is_target bool) ConfigInstall {
489 return ConfigInstall{
490 query: archives
491 noconfirm: config.noconfirm
492 asdeps: if is_target { config.asdeps } else { true }
493 asexplicit: is_target && config.asexplicit
494 dbonly: config.dbonly
495 nodeps: config.nodeps
496 nodeps_level: config.nodeps_level
497 overwrite: config.overwrite
498 assume_installed: config.assume_installed
499 ignore: config.ignore
500 ignoregroup: config.ignoregroup
501 no_upgrade_deps: config.no_upgrade_deps
502 disable_timeout: config.disable_timeout
503 }
504}
505
506// pkgbuild_plan resolves target into its build plan, dependencies first,
507// against the local db read this moment and the handle's sync dbs
508fn pkgbuild_plan(handle &alpm.Handle, target string) ![]PkgbuildNode {
509 view, installed := local_now()!
510 defer { view.release() or { went_on('release the alpm handle', err) } }
511 mut r := PkgbuildResolver{
512 // the caller's handle outlives the plan: it is only read here
513 handle: unsafe { handle }
514 installed: installed
515 sync_dbs: handle.get_syncdbs()!
516 }
517 r.visit(target)!
518 return r.planned()
519}
520
521// pkgbuild_install builds an AUR package and the AUR packages it needs, reviewing
522// each one, then installs what was built
523fn pkgbuild_install(mut ui TransUI, mut handle &alpm.Handle, config ConfigInstall, target string) ! {
524 user := invoker_user()!
525 // the plan is resolved against the installed packages as they are now:
526 // an earlier target of this run may have been built and installed since
527 // the handle read them. the sync dbs are the handle's, which no install
528 // changes
529 nodes := pkgbuild_plan(handle, target)!
530
531 for i, planned in nodes {
532 // the nodes come dependencies first: the last one is the target
533 is_target := i == nodes.len - 1
534 // and each node is decided when its turn comes, after everything
535 // before it was installed
536 step := node_step_now(planned, config.needed, is_target)!
537 if step.skip {
538 // warn speaks both a terminal's and a frontend's language, the
539 // way an install's own --needed does
540 warn(step.why)
541 continue
542 }
543 node := PkgbuildNode{
544 ...planned
545 repo_deps: step.repo_deps
546 }
547 archives := review_and_build(mut ui, user, node, config, !(is_target
548 && config.pkgbuild)) or {
549 if err is BuildDeclined {
550 // a no is a quiet stop: nothing after this node can be built
551 // without it, and nothing went wrong
552 advise('${node.info.name} was declined, nothing more is built')
553 return
554 }
555 return err
556 }
557 if archives.len == 0 {
558 return error('${node.info.name} was not built')
559 }
560 // a pkgbuild dependency is installed as a dependency, the way the
561 // repo ones are; the target takes --asdeps or --asexplicit. the
562 // whole of what came out of the pkgbuild goes into one install, so a
563 // split package set lands as one transaction, with its ordering, its
564 // hooks and its prompt, instead of one apiece
565 install(built_install_config(config, archives, is_target))!
566 }
567 // everything built was installed by install() above, which already
568 // reports "installed: <package>"; provenance comes from the question
569 // asked before the build
570}
571