module main import alpm import os import time import vmakepkg // PkgbuildNode is one pkgbuild package in build order: the repo packages it needs first, // then itself. site is the pkgbuild repo the package came from, repo the // name the config gives it struct PkgbuildNode { info PackagePkgbuild site string repo string repo_deps []string // wanted are the dependency strings that put the node in the plan, as // the packages that need it spell them; the target has none. they are // what tells, once earlier builds are installed, whether this one is // still needed wanted []string } // PkgbuildResolver walks the dependencies of a pkgbuild package. a dependency that is // installed or in the repos is used as it is; one that is neither is looked up // in the pkgbuild repo and placed before the package that needs it struct PkgbuildResolver { mut: handle &alpm.Handle installed &alpm.List sync_dbs &alpm.List // visiting holds the names on the branch being walked, so a cycle is a // named error instead of a node silently skipped; done holds the ones // whose nodes are already in, so they are never built twice visiting map[string]bool done map[string]bool nodes []PkgbuildNode // wanted gathers, by node name, every dependency string that led to the // node, the later ones too: a node is planned once and wanted often wanted map[string][]string } // planned is the plan as it stands: the nodes in build order, each with // everything that wanted it fn (r &PkgbuildResolver) planned() []PkgbuildNode { return r.nodes.map(PkgbuildNode{ ...it wanted: r.wanted[it.info.name].clone() }) } fn (mut r PkgbuildResolver) visit(name string) ! { if r.done[name] { return } if r.visiting[name] { return error('circular pkgbuild dependency: ${name} is walked as its own dependency') } r.visiting[name] = true defer { r.visiting.delete(name) } pkg_info, site, from := pkgbuild_lookup(name)! if site == '' { return error('"${name}" is not in the repos or the pkgbuild repo') } mut repo := []string{} mut deps := []string{} deps << pkg_info.depends deps << pkg_info.make_depends // makepkg runs check() by default, so what it needs is needed before // the build is queued, not found missing inside it deps << pkg_info.check_depends for dep in deps { if p := r.handle.resolve_dep(r.installed, r.sync_dbs, dep) { if p.get_origin() == .syncdb { repo << p.get_name() } continue } if dep !in r.wanted[dep_name(dep)] { r.wanted[dep_name(dep)] << dep } r.visit(dep_name(dep))! } r.nodes << PkgbuildNode{ info: pkg_info site: site repo: from repo_deps: repo } // only a node that arrived in the plan counts as done: one whose walk // failed wants reporting when it is reached again r.done[name] = true } // dep_name strips a version constraint: 'glibc>=2.27' is 'glibc' fn dep_name(dep string) string { return dep.trim_space().all_before('<').all_before('>').all_before('=').trim_space() } // pkgbuild_root is the dir every build lives under. the configured dir is // taken under the invoking user's home when it is relative, because makepkg // runs as that user fn pkgbuild_root(user string) !string { if pkgbuild_dir.starts_with('/') { return pkgbuild_dir } return os.join_path(user_home(user)!, pkgbuild_dir) } // pkgbuild_build_dir is where a package is cloned and built fn pkgbuild_build_dir(user string, base string) !string { // the base is the rpc's answer, and the dir it names is removed before // the clone: only one plain path component may stand here if base == '' || base in ['.', '..'] || base.contains('/') || base.starts_with('-') { return error('the pkgbuild repo answered a package base that is not a plain name: "${base}"') } return '${pkgbuild_root(user)!}/${base}' } // makepkg_line is the shell line a build runs in its dir: the dir quoted as // one word, then the configured build command — config text passed through // the shell on purpose, trusted as far as the config it comes from, and // reviewed by the user beside everything else a pkgbuild runs fn makepkg_line(dir string) string { return 'cd ${vmakepkg.shell_quote(dir)} && ${pkgbuild_makepkg}' } // run_process runs a command, its arguments reaching it one by one with no // shell in between to quote wrong, and answers its exit code. with capture // its stdout comes back as text, and its stderr is passed on as it arrives: // both pipes are drained while the child lives, so one that fills the // stderr pipe never waits on a reader that is itself waiting on stdout. // without capture the terminal is the child's own fn run_process(argv []string, capture bool) !(string, int) { exe := os.find_abs_path_of_executable(argv[0]) or { return error('${argv[0]} is needed, but it was not found') } mut process := os.new_process(exe) process.set_args(argv[1..]) mut out := '' if capture { process.set_redirect_stdio() process.run() for process.is_alive() { mut idle := true if process.is_pending(.stdout) { out += process.stdout_read() idle = false } if process.is_pending(.stderr) { eprint(process.stderr_read()) idle = false } if idle { time.sleep(2 * time.millisecond) } } out += process.stdout_slurp() eprint(process.stderr_slurp()) } process.wait() code := process.code process.close() return out, code } // as_user runs a command as the invoking user, through runuser fn as_user(user string, args []string, capture bool) !string { mut cmd := ['runuser', '-u', user, '--'] cmd << args out, code := run_process(cmd, capture) or { return error('${cmd[0]} is needed to run this as ${user}, but it was not found') } if code != 0 { return error('${args[0]} failed as user ${user} (exit ${code})') } return out } // output_as_user runs a command as the invoking user, as run_as_user does, // and returns what it printed on stdout fn output_as_user(user string, args []string) !string { return as_user(user, args, true) } // run_as_user runs a command as the invoking user, with the terminal passed on fn run_as_user(user string, args []string) ! { as_user(user, args, false)! } // ReviewFile is one file a build runs, shown whole before it is built. // generated marks a file vpac wrote from a PKGBUILD.lip or a PKGBUILD.vsh struct ReviewFile { name string text string generated bool } // ReviewEvent is what a build runs, shown before the question that builds // it: the warnings about where it comes from, its files, and the names in // its dir struct ReviewEvent { kind string = 'review' @[json: 'type'] package string mut: files []ReviewFile listing []string warnings []string } // read_review collects a PKGBUILD dir's review: the PKGBUILD, every .install // script and the list of files that make up the package fn read_review(package string, dir string) !ReviewEvent { mut parts := [ReviewFile{ name: 'PKGBUILD' text: os.read_file('${dir}/PKGBUILD')! }] mut names := os.ls(dir)! names.sort() mut listing := []string{} for f in names { if f == '.git' { continue } if f.ends_with('.install') { parts << ReviewFile{ name: f text: os.read_file('${dir}/${f}')! } } listing << f } return ReviewEvent{ package: package files: parts listing: listing } } // show_review shows a review: on a terminal the warnings, the title, every // file under its name and the files in the package; a frontend gets it as // one event fn show_review(r ReviewEvent, title string) { if ipc_on() { emit(ReviewEvent{ ...r warnings: r.warnings.map(it.trim_space()) }) return } println(review_text(r, title)) } // review_text is a review for the terminal: the warnings, the title, every // file under its name, and the files in the package fn review_text(r ReviewEvent, title string) string { mut out := r.warnings.map(warning(it)) if title != '' { out << heading(title) } for f in r.files { out << heading(if f.generated && f.name == 'PKGBUILD' { 'PKGBUILD the build runs' } else { f.name }) out << f.text } if r.listing.len > 0 { out << heading('files in the package') out << r.listing.join(' ') } return out.join('\n') } // build_phase tells a frontend a build runs; a terminal sees makepkg's own // output, which goes to the frontend's log fn build_phase(name string, state string) { if ipc_on() { emit(PhaseEvent{ text: 'building ${name}' state: state }) } } // built_packages lists the archives a build produced, as makepkg names them // itself: the build command with --packagelist answers the files this // PKGBUILD's version packs to, wherever PKGDEST puts them and whatever PKGEXT // is. a name pattern over the build dir missed an uncompressed .pkg.tar and // another PKGDEST, and took an older build's archive a pulled checkout // carried — of two, the directory's order chose which was installed fn built_packages(user string, dir string) ![]string { out := output_as_user(user, ['sh', '-c', '${makepkg_line(dir)} --packagelist'])! return packagelist_files(out) } // packagelist_files are the paths --packagelist printed that the build did // produce: it names every package the PKGBUILD can make (a debug package // among them) whether built or not, so only the files that are there count fn packagelist_files(output string) []string { return output.split_into_lines().map(it.trim_space()).filter(it.starts_with('/') && os.is_file(it)) } // archives_in lists the package archives a build dir holds, whatever version // or build made them: what clean asks of a build, to keep one that holds an // installed package's archive. an uncompressed .pkg.tar is one too fn archives_in(dir string) ![]string { mut out := []string{} for f in os.ls(dir)! { if is_pkg_archive(f) { out << '${dir}/${f}' } } return out } // pkgbuild_warnings are what the pkgbuild repo knows of a package that a // review wants beside the files: who keeps it, how many vouch for it, and // whether it was flagged fn pkgbuild_warnings(info PackagePkgbuild) []string { maintainer := info.maintainer or { 'none (orphaned)' } mut out := ['maintainer: ${maintainer}, votes: ${info.num_votes}'] if info.out_of_date != none { out << 'flagged as out of date' } return out } // review_and_build asks its way to a build: whether the package is to come // from the pkgbuild repo at all (no by default), then whether its pkgbuild // is to be read first (yes by default), then the build's own question, asked // whether or not the review was read, so the build can still be declined. // the gate is the caller's to word: install asks the generic question, and // an upgrade names the versions it would go from and to. searched says the // repos were looked in before, which a -b target's never were. only then // does it install the repo packages the build needs, and build. returns the // archives; a no to a question is a BuildDeclined, which is the user's // answer and not a failure of the build fn review_and_build(mut ui TransUI, user string, node PkgbuildNode, config ConfigInstall, searched bool, gate string) ![]string { name := node.info.name base := node.info.package_base dir := pkgbuild_build_dir(user, base)! ask := !config.no_pkgbuild_confirm // --noconfirm would take the first question's preset, which is no: the // refusal says so before anything is cloned if config.noconfirm && ask { return error('pkgbuild packages are asked about: drop --noconfirm, or pass --nopkgbuildconfirm, to build ${name}') } ui.pause() // the display is paused for the questions, the clone and the review; the // run leaves it paused-through for the build, and syncs on the way out defer { ui.sync() } if searched { warn('${name} was not found in the repos') } q := if gate != '' { gate } else { 'install ${name} from the pkgbuild repo (${node.repo})?' } if ask && !ui.noyes(q) { return BuildDeclined{} } run_as_user(user, ['mkdir', '-p', pkgbuild_root(user)!])! run_as_user(user, ['rm', '-rf', dir])! run_as_user(user, ['git', 'clone', '--depth', '${pkgbuild_depth}', '${node.site}/${base}.git', dir])! // with --nopkgbuildconfirm nothing is asked, and the review is still // shown: the record of what was built stays in the output if !ask || ui.yesno('review the pkgbuild?') { mut review := read_review(name, dir)! review.warnings = pkgbuild_warnings(node.info) show_review(review, 'review ${name}') } prompt := if node.repo_deps.len > 0 { 'build and install ${name}, after installing its repo dependencies ${node.repo_deps.join(', ')}?' } else { 'build and install ${name}?' } if ask && !ui.yesno(prompt) { return BuildDeclined{} } if node.repo_deps.len > 0 { install_repo_deps(node.repo_deps)! ui.sync() } build_phase(name, 'start') run_as_user(user, ['sh', '-c', makepkg_line(dir)])! build_phase(name, 'done') return built_packages(user, dir)! } // BuildDeclined is review_and_build's answer when the user said no struct BuildDeclined { Error } fn (e BuildDeclined) msg() string { return 'the build was declined' } // local_now opens the installed packages as they are at this moment, on a // handle of its own that the caller releases. the run's handle read the // local db when the run began, and every build since was installed through // another one (install's): its list is the past, and what is planned, asked // and skipped from here on is decided on the present fn local_now() !(&alpm.Handle, &alpm.List) { handle := alpm.initialize(root_path, db_path) or { return error('could not read the local database: ${err.msg()}') } pkgs := local_pkgcache(handle) or { handle.release() or { went_on('release the alpm handle', err) } return err } return handle, pkgs } // NodeStep is what is left to do for a node once the installed packages // are read again: nothing (skip, and why), or the build, with the repo // packages it still needs first struct NodeStep { skip bool why string repo_deps []string } // node_step decides a node against the installed packages as they are now. // a dependency node is dropped when everything that wanted it is satisfied // by what is installed — an earlier build of this run that provides it, a // split package that came with its sibling — and never merely because a // package of its name is there at some version. the target is only ever // skipped by --needed, at the very version it would install. the repo // dependencies are the ones still missing fn node_step(installed &alpm.List, node PkgbuildNode, needed bool, is_target bool) NodeStep { name := node.info.name if !is_target && node.wanted.len > 0 && node.wanted.all(installed.find_satisfier(it) != none) { return NodeStep{ skip: true why: '${name} is satisfied by what is installed now, not built' } } if is_target && needed { if local := installed.pkg_find(name) { if alpm.pkg_vercmp(local.get_version(), node.info.version) == 0 { return NodeStep{ skip: true why: '${name}-${node.info.version} is up to date, skipped' } } } } return NodeStep{ repo_deps: node.repo_deps.filter(installed.pkg_find(it) == none) } } // node_step_now is node_step on the local db read this moment fn node_step_now(node PkgbuildNode, needed bool, is_target bool) !NodeStep { view, installed := local_now()! defer { view.release() or { went_on('release the alpm handle', err) } } return node_step(installed, node, needed, is_target) } // install_repo_deps installs the repo packages a build needs, as // dependencies, through an install of its own: a fresh handle, so the // transaction is checked against the packages installed now and not against // what the run's handle read before the earlier builds went in. the // pkgbuild's questions were the go-ahead for the build and what it needs, // so the listing is shown and taken as --noconfirm takes it; nothing beyond // the named packages and what they depend on is upgraded along fn install_repo_deps(names []string) ! { if names.len == 0 { return } install(ConfigInstall{ query: names noconfirm: true asdeps: true no_upgrade_deps: true }) or { return error('the build dependencies ${names.join(', ')} were not installed: ${err.msg()}') } } // built_install_config is the install of what a pkgbuild built, as the outer // command line asked for it: the archives are the targets, a dependency // node is installed as a dependency whatever the target's reason is, and // what was said of the transaction (ignores, overwrites, the dependency // checks, the timeout) holds for this one as well. what belongs to the // outer run alone — the pkgbuild flags, --needed, --print, --download-only — // stays behind fn built_install_config(config ConfigInstall, archives []string, is_target bool) ConfigInstall { return ConfigInstall{ query: archives noconfirm: config.noconfirm asdeps: if is_target { config.asdeps } else { true } asexplicit: is_target && config.asexplicit dbonly: config.dbonly nodeps: config.nodeps nodeps_level: config.nodeps_level overwrite: config.overwrite assume_installed: config.assume_installed ignore: config.ignore ignoregroup: config.ignoregroup no_upgrade_deps: config.no_upgrade_deps disable_timeout: config.disable_timeout } } // pkgbuild_plan resolves target into its build plan, dependencies first, // against the local db read this moment and the handle's sync dbs fn pkgbuild_plan(handle &alpm.Handle, target string) ![]PkgbuildNode { view, installed := local_now()! defer { view.release() or { went_on('release the alpm handle', err) } } mut r := PkgbuildResolver{ // the caller's handle outlives the plan: it is only read here handle: unsafe { handle } installed: installed sync_dbs: handle.get_syncdbs()! } r.visit(target)! return r.planned() } // pkgbuild_install builds an AUR package and the AUR packages it needs, reviewing // each one, then installs what was built. the gate is the first question's // word, the caller's to write — the generic install question when it is empty fn pkgbuild_install(mut ui TransUI, mut handle &alpm.Handle, config ConfigInstall, target string, gate string) ! { user := invoker_user()! // the plan is resolved against the installed packages as they are now: // an earlier target of this run may have been built and installed since // the handle read them. the sync dbs are the handle's, which no install // changes nodes := pkgbuild_plan(handle, target)! for i, planned in nodes { // the nodes come dependencies first: the last one is the target is_target := i == nodes.len - 1 // and each node is decided when its turn comes, after everything // before it was installed step := node_step_now(planned, config.needed, is_target)! if step.skip { // warn speaks both a terminal's and a frontend's language, the // way an install's own --needed does warn(step.why) continue } node := PkgbuildNode{ ...planned repo_deps: step.repo_deps } archives := review_and_build(mut ui, user, node, config, !(is_target && config.pkgbuild), gate) or { if err is BuildDeclined { // a no is a quiet stop: nothing after this node can be built // without it, and nothing went wrong advise('${node.info.name} was declined, nothing more is built') return } return err } if archives.len == 0 { return error('${node.info.name} was not built') } // a pkgbuild dependency is installed as a dependency, the way the // repo ones are; the target takes --asdeps or --asexplicit. the // whole of what came out of the pkgbuild goes into one install, so a // split package set lands as one transaction, with its ordering, its // hooks and its prompt, instead of one apiece install(built_install_config(config, archives, is_target))! } // everything built was installed by install() above, which already // reports "installed: "; provenance comes from the question // asked before the build }