@[has_globals] module main import nspkg import os import sync.stdatomic import v.profiler fn C._exit(status int) // set while this process has an open transaction: txn_locked when it holds // the db lock, txn_unlocked for a --print preview's, which takes none. it // makes trans_cleanup release once, however many paths reach it const txn_open = stdatomic.new_atomic(i64(0)) const txn_locked = i64(1) const txn_unlocked = i64(2) // interrupt_handle is the handle a transaction runs on, published for the // signal handler (as its address) from before nspkg takes the db lock // until after it let go of it. the handler calls its async unlock, which // removes the lock only while this handle holds it (its lockfd), as pacman's // soft_interrupt_handler does: there is no moment where the lock is taken // and the handler does not know it, and a lock held by someone else — or by // nobody, a --print preview's transaction — is never touched const interrupt_handle = stdatomic.new_atomic(u64(0)) // split_list reads a repeatable option the way pacman reads its lists: each // value may hold several, comma separated fn split_list(values []string) []string { mut out := []string{} for value in values { for item in value.split(',') { s := item.trim_space() if s != '' { out << s } } } return out } // dep_check_flag is pacman's -d: once (or --nodeps) skips the version checks // of the dependencies, twice (-dd, or --nodeps with -d) skips the // dependency checks altogether fn dep_check_flag(nodeps bool, level int) nspkg.TransFlag { n := level + if nodeps { 1 } else { 0 } return if n >= 2 { nspkg.TransFlag.no_deps } else if n == 1 { nspkg.TransFlag.no_depversion } else { nspkg.trans_flag_0 } } // TransOptions are the handle options a command line adds for one run, on // top of the config's: pacman's --overwrite, --ignore, --ignoregroup and // --assume-installed, every one a repeatable comma separated list struct TransOptions { overwrite []string ignore []string ignoregroup []string assume_installed []string } fn (o TransOptions) apply(handle &nspkg.Handle) ! { for glob in split_list(o.overwrite) { handle.option_add_overwrite_file(glob)! } for name in split_list(o.ignore) { handle.option_add_ignore_pkg(name)! } for group in split_list(o.ignoregroup) { handle.option_add_ignore_group(group)! } for spec in split_list(o.assume_installed) { // libalpm parses any text into a dependency, '=1' into one with no // name, which would assume nothing: a spec names its package dep := nspkg.dep_from_string(spec) if dep == unsafe { nil } || dep.get_name() == '' { if dep != unsafe { nil } { dep.free() } return error('--assume-installed: "${spec}" names no package, write it like name=version') } // libalpm keeps its own copy, as pacman relies on handle.option_add_assumeinstalled(dep) or { dep.free() return err } dep.free() } } // trans_begin initializes a transaction. pair it with // `defer { trans_cleanup(handle) }` so every exit path releases it fn trans_begin(handle &nspkg.Handle, flags nspkg.TransFlag) ! { // published first: trans_init takes the lock, and a signal right after // it must find the handle that holds it publish_for_interrupt(handle) handle.trans_init(flags) or { withdraw_from_interrupt() return err } mut open := txn_open open.store(if flags.has(.nolock) { txn_unlocked } else { txn_locked }) } // publish_for_interrupt makes handle the one the signal handler unlocks fn publish_for_interrupt(handle &nspkg.Handle) { mut published := interrupt_handle published.store(u64(voidptr(handle))) } // withdraw_from_interrupt leaves the signal handler no handle: the lock is // gone, and the handle may be released next fn withdraw_from_interrupt() { mut published := interrupt_handle published.store(0) } // print_flags are what a --print preview adds to its transaction, as // pacman's --print does: no db lock, so it needs no root and never waits on // a running transaction, and no conflict checks, so a preview lists the // packages even when a conflict question would come up fn print_flags(print_only bool) nspkg.TransFlag { return if print_only { nspkg.TransFlag.nolock | .no_conflicts } else { nspkg.trans_flag_0 } } // trans_cleanup releases an open transaction, which is what removes the db // lock. like pacman's cleanup: label, it runs on success, decline and error. // a release that does not go through is said (the lock and the transaction // state would hang behind it); it still counts as closed, or the defers of // a rollback would try again fn trans_cleanup(handle &nspkg.Handle) { mut open := txn_open if open.load() != 0 { handle.trans_release() or { warn('failed to release the transaction: ${err.msg()}') } open.store(0) } withdraw_from_interrupt() } // prepare_problem_lines words a failed prepare by what libalpm's errno says // its problems are, as pacman's sync_prepare_execute tells them apart: a // missing or broken dependency, a conflict between two packages, a package // of the wrong architecture, and anything else under libalpm's own text fn prepare_problem_lines(kind nspkg.Errno, problems []nspkg.DepProblem) []string { mut lines := []string{} match kind { .unsatisfied_deps { lines << 'could not satisfy dependencies:' for p in problems { lines << if p.causing == '' { " unable to satisfy dependency '${p.depend}' required by ${p.target}" } else { " ${p.causing} breaks dependency '${p.depend}' required by ${p.target}" } } } .conflicting_deps { lines << 'unresolvable package conflicts:' for p in problems { // the reason is only said when it is news: not one of the // two names again lines << if p.depend == '' || p.depend == p.target || p.depend == p.causing { ' ${p.target} and ${p.causing} are in conflict' } else { ' ${p.target} and ${p.causing} are in conflict (${p.depend})' } } } .pkg_invalid_arch { lines << '${kind.strerror()}:' for p in problems { lines << ' package ${p.target} does not have a valid architecture' } } else { lines << '${kind.strerror()}:' for p in problems { lines << ' ' + [p.target, p.depend, p.causing].filter(it != '').join(' ') } } } return lines } // trans_prepare_checked prepares a transaction. when packages would break it, // the error lists each problem the way pacman does fn trans_prepare_checked(handle &nspkg.Handle) ! { problems, failure := handle.trans_prepare_problems() if err := failure { if problems.len == 0 { return err } // copying conflict package names can reset the handle's mutable errno. kind := unsafe { nspkg.Errno(err.code()) } return error_with_code(prepare_problem_lines(kind, problems).join('\n'), err.code()) } } // runs the commit phase of a prepared transaction. the transaction must // already have been begun and prepared. fn trans_commit(handle &nspkg.Handle) ! { handle.trans_commit()! trans_cleanup(handle) } // on_interrupt is pacman's soft_interrupt_handler: a killed run removes the // db lock it holds, so it does not wedge the next run. unlock_async decides // whether it holds one, from the handle's own state, and does only close and // unlink — async-signal-safe, no allocation. the transaction is not // interrupted cleanly (no alpm_trans_interrupt here: the run ends at once), // but the lock is never left behind fn on_interrupt(sig os.Signal) { mut published := interrupt_handle h := published.load() if h != 0 { handle := unsafe { &nspkg.Handle(voidptr(h)) } handle.unlock_async() } C._exit(128 + int(sig)) } // install_interrupt_handlers runs after load_config, at which point db_path // is final: the handler gets the one path it may ever need, cut once here, // and never allocates fn install_interrupt_handlers() { for sig in [os.Signal.int, .hup, .term, .abrt] { os.signal_opt(sig, on_interrupt) or { went_on('install the handler of signal ${int(sig)}', err) } } } enum TransAction { remove install upgrade autoremove } // trans_listing collects what a prepared transaction does: every package, // with the installed version an install or upgrade replaces, and the sizes fn trans_listing(handle &nspkg.Handle, pkgs []&nspkg.Package, action TransAction) TransactionEvent { mut out := []TransPkg{} mut download := i64(0) mut install_size := i64(0) for pkg in pkgs { name := pkg.get_name() removing := action == .remove || action == .autoremove mut old := '' if !removing { if installed := handle.find_local_pkg(name) { old = installed.get_version() } } out << TransPkg{ name: name version: pkg.get_version() old_version: old download_size: if removing { 0 } else { pkg.download_size() } installed_size: pkg.get_isize() } download += out.last().download_size install_size += out.last().installed_size } return TransactionEvent{ action: action.str() packages: out download_size: download installed_size: install_size } } // print_trans_listing shows a transaction the way pkgin does, with the sizes // for anything that downloads fn print_trans_listing(t TransactionEvent) { header := match t.action { 'remove' { 'packages to delete' } 'install' { 'packages to be installed' } 'upgrade' { 'packages to be upgraded' } else { 'packages to be autoremoved' } } removing := t.action in ['remove', 'autoremove'] mut rows := []Row{} for p in t.packages { if removing { rows << row(name_style(p.name), version_style(p.version)) } else if p.old_version != '' { // old version, arrow, new version: a new dependency has no old one rows << row(name_style(p.name), old_style(p.old_version), '->', version_style(p.version)) } else { rows << row(name_style(p.name), '', '', version_style(p.version)) } } println(heading('${t.packages.len} ${header}:')) println(table_text(rows, ' ', ' ')) if !removing { sizes := [ row('to download', profiler.format_bytes(u64(t.download_size))), row('to install', profiler.format_bytes(u64(t.installed_size))), ] println(table_text(sizes, ' ', ' ')) } } // trans_confirm lists a prepared transaction and asks 'proceed? [Y/n]', // where enter is yes, as pacman's 'Proceed with installation?'. a frontend // gets the listing as a transaction event before the question fn trans_confirm(mut ui TransUI, handle &nspkg.Handle, pkgs []&nspkg.Package, action TransAction) bool { ui.pause() listing := trans_listing(handle, pkgs, action) if ipc_on() { emit(listing) } else { print_trans_listing(listing) } return ui.proceed('proceed?') }