From 3609dfbd82867dc1034a443f8f9ced529ddbbedd Mon Sep 17 00:00:00 2001 From: diviocity Date: Tue, 10 Nov 2026 20:19:42 +0100 Subject: [PATCH] ground zero --- .editorconfig | 8 + .gitattributes | 8 + .gitignore | 34 + AGENTS.md | 156 +++ README.md | 58 + install.vsh | 356 ++++++ pkgs/lipsmoke/PKGBUILD.lip | 35 + pkgs/lipsmoke/lipsmoke.sh | 2 + pkgs/lipsmoke/readme.txt | 1 + pkgs/lipsplit/PKGBUILD.lip | 15 + pkgs/lipsplit/shared.txt | 1 + pkgs/vshsmoke/PKGBUILD.vsh | 61 + pkgs/vshsmoke/readme.txt | 1 + pkgs/vshsmoke/vshsmoke.sh | 2 + src/alpm_log.h | 30 + src/autoremove.v | 72 ++ src/build_repo.v | 300 +++++ src/build_repo_test.v | 158 +++ src/clean.v | 436 +++++++ src/clean_test.v | 193 +++ src/cli.v | 753 +++++++++++ src/cli_test.v | 324 +++++ src/config.v | 1027 +++++++++++++++ src/config_test.v | 445 +++++++ src/db.v | 167 +++ src/db_check.v | 157 +++ src/db_check_test.v | 109 ++ src/db_test.v | 66 + src/deptest.v | 45 + src/deptest_test.v | 81 ++ src/deptree.v | 246 ++++ src/fields.v | 234 ++++ src/files.v | 221 ++++ src/files_test.v | 231 ++++ src/filter.v | 48 + src/find.v | 476 +++++++ src/format.v | 261 ++++ src/format_test.v | 93 ++ src/frontend_test.v | 2339 +++++++++++++++++++++++++++++++++++ src/help.v | 476 +++++++ src/help_test.v | 126 ++ src/info.v | 200 +++ src/ipc.v | 661 ++++++++++ src/ipc_test.v | 395 ++++++ src/mirrors.v | 554 +++++++++ src/mirrors_test.v | 314 +++++ src/modify.v | 88 ++ src/orphans.v | 74 ++ src/orphans_test.v | 100 ++ src/pkgbuild.v | 113 ++ src/pkgbuild_install.v | 570 +++++++++ src/pkgbuild_install_test.v | 339 +++++ src/privilege.v | 173 +++ src/privilege_test.v | 119 ++ src/prompt.v | 247 ++++ src/prompt_test.v | 512 ++++++++ src/remote.v | 454 +++++++ src/remote_test.v | 173 +++ src/remove.v | 172 +++ src/search.v | 363 ++++++ src/search_test.v | 38 + src/style.v | 140 +++ src/style_test.v | 24 + src/suggest.v | 72 ++ src/suggest_test.v | 20 + src/table.v | 123 ++ src/target.v | 178 +++ src/testdb/testdb.v | 60 + src/testdb/testdb_test.v | 56 + src/trans.v | 324 +++++ src/trans_test.v | 283 +++++ src/ui.v | 937 ++++++++++++++ src/ui_test.v | 120 ++ src/upgrade.v | 106 ++ src/upgrade_deps.v | 17 + src/url_install.v | 93 ++ src/url_install_test.v | 44 + src/verify.v | 201 +++ src/verify_full.v | 290 +++++ src/verify_full_test.v | 211 ++++ src/verify_test.v | 45 + v.mod | 8 + vmakepkg/lip.v | 939 ++++++++++++++ vmakepkg/lip_test.v | 396 ++++++ vmakepkg/vsh.v | 461 +++++++ vmakepkg/vsh_test.v | 358 ++++++ 86 files changed, 21017 insertions(+) create mode 100644 .editorconfig create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 AGENTS.md create mode 100644 README.md create mode 100755 install.vsh create mode 100644 pkgs/lipsmoke/PKGBUILD.lip create mode 100644 pkgs/lipsmoke/lipsmoke.sh create mode 100644 pkgs/lipsmoke/readme.txt create mode 100644 pkgs/lipsplit/PKGBUILD.lip create mode 100644 pkgs/lipsplit/shared.txt create mode 100644 pkgs/vshsmoke/PKGBUILD.vsh create mode 100644 pkgs/vshsmoke/readme.txt create mode 100644 pkgs/vshsmoke/vshsmoke.sh create mode 100644 src/alpm_log.h create mode 100644 src/autoremove.v create mode 100644 src/build_repo.v create mode 100644 src/build_repo_test.v create mode 100644 src/clean.v create mode 100644 src/clean_test.v create mode 100644 src/cli.v create mode 100644 src/cli_test.v create mode 100644 src/config.v create mode 100644 src/config_test.v create mode 100644 src/db.v create mode 100644 src/db_check.v create mode 100644 src/db_check_test.v create mode 100644 src/db_test.v create mode 100644 src/deptest.v create mode 100644 src/deptest_test.v create mode 100644 src/deptree.v create mode 100644 src/fields.v create mode 100644 src/files.v create mode 100644 src/files_test.v create mode 100644 src/filter.v create mode 100644 src/find.v create mode 100644 src/format.v create mode 100644 src/format_test.v create mode 100644 src/frontend_test.v create mode 100644 src/help.v create mode 100644 src/help_test.v create mode 100644 src/info.v create mode 100644 src/ipc.v create mode 100644 src/ipc_test.v create mode 100644 src/mirrors.v create mode 100644 src/mirrors_test.v create mode 100644 src/modify.v create mode 100644 src/orphans.v create mode 100644 src/orphans_test.v create mode 100644 src/pkgbuild.v create mode 100644 src/pkgbuild_install.v create mode 100644 src/pkgbuild_install_test.v create mode 100644 src/privilege.v create mode 100644 src/privilege_test.v create mode 100644 src/prompt.v create mode 100644 src/prompt_test.v create mode 100644 src/remote.v create mode 100644 src/remote_test.v create mode 100644 src/remove.v create mode 100644 src/search.v create mode 100644 src/search_test.v create mode 100644 src/style.v create mode 100644 src/style_test.v create mode 100644 src/suggest.v create mode 100644 src/suggest_test.v create mode 100644 src/table.v create mode 100644 src/target.v create mode 100644 src/testdb/testdb.v create mode 100644 src/testdb/testdb_test.v create mode 100644 src/trans.v create mode 100644 src/trans_test.v create mode 100644 src/ui.v create mode 100644 src/ui_test.v create mode 100644 src/upgrade.v create mode 100644 src/upgrade_deps.v create mode 100644 src/url_install.v create mode 100644 src/url_install_test.v create mode 100644 src/verify.v create mode 100644 src/verify_full.v create mode 100644 src/verify_full_test.v create mode 100644 src/verify_test.v create mode 100644 v.mod create mode 100644 vmakepkg/lip.v create mode 100644 vmakepkg/lip_test.v create mode 100644 vmakepkg/vsh.v create mode 100644 vmakepkg/vsh_test.v diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..01072ca --- /dev/null +++ b/.editorconfig @@ -0,0 +1,8 @@ +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[*.v] +indent_style = tab diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..9a98968 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,8 @@ +* text=auto eol=lf +*.bat eol=crlf + +*.v linguist-language=V +*.vv linguist-language=V +*.vsh linguist-language=V +v.mod linguist-language=V +.vdocignore linguist-language=ignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..671dbad --- /dev/null +++ b/.gitignore @@ -0,0 +1,34 @@ +# Binaries for programs and plugins +main +pacman +*.exe +*.exe~ +*.so +*.dylib +*.dll + +# Ignore binary output folders +bin/ + +# Ignore common editor/system specific metadata +.DS_Store +.idea/ +.vscode/ +*.iml + +# ENV +.env + +# Web assets and local databases +*.db +*.js + +# Modules installed with `v install --local` land beside this file, one +# directory per module. Add them here if they should stay out of the repo. + +# What `v . -o vpac` makes +/vpac + +# Editor swap files +*.swp +*.kate-swp diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..0a8817e --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,156 @@ +# AGENTS.md + +for agents landing in this repository cold. + +vpac is a package manager written in V on top of libalpm, the library that +backs pacman. it is a frontend of its own — its own listings, prompts, +progress drawing, and a json event protocol for other frontends — with a +config file of its own, and two package sources beyond the sync dbs: the +pkgbuild repos and arbitrary git repos built with vpac itself. + +## the repository + +``` +src/ module main: the frontend. one file per mode, plus the shared + parts every mode reaches for. +src/cli.v argument parsing and mode dispatch. modes: s q w n m b i r u + l o d c t a k v f (search info which deptest mark build + install remove upgrade files owner orphans clean tree + autoremove rank verify find). +src/config.v the configuration. the forms (path pkg network rank pkgbuild + options search clean tree color progress spinner + mirrorlist repo) are read from a blip file, /etc/vpac.d/config.lip by + default, and every setting keeps a __global here. +src/trans.v transaction begin/prepare/commit/cleanup and the interrupt + handler. src/db.v holds the db paths, repo registration and + freshness; src/db_check.v is verify's -D modes. +src/ipc.v --ui ipc: the event protocol (one json object per line) and + the prompter a frontend answers questions with. +src/ui.v the shared progress display and callback wiring for libalpm; + src/prompt.v the terminal's side of every question. +(the rest of src/) + one file per command. install is remote.v, and remove.v + autoremove.v upgrade.v modify.v write the db too; find.v + files.v orphans.v deptest.v are read-only; verify.v and + verify_full.v check the disk; pkgbuild.v pkgbuild_install.v + build_repo.v mirrors.v privilege.v are the network- and + privilege-flavored ones. +vmakepkg/ a library module of its own: PKGBUILD.lip (blip format; + lip.v) and PKGBUILD.vsh (a V script; vsh.v) both turn into a + real PKGBUILD (and a .install for hooks) whose phases makepkg + runs, delegating back into vpac or v. +pkgs/ two tiny packages vpac itself builds as smoke tests of the + vmakepkg formats. +src/*_test.v, vmakepkg/*_test.v the tests. +src/testdb/ a module only the tests import: the one writer of libalpm + local dbs they share. vpac never imports it, so it is in no + build of the program. +``` + +## the cross-references, and the rule about them + +the binary links libalpm through the V module `alpm` (a file that begins +`module alpm`), evaluates its config and lip files through the module +`blip.vlib.blip`, and reuses this repo's own `vmakepkg`. these dependencies +live outside the repository: on a machine, V finds them under its module +directory (typically ~/.vmodules), often as symlinks to checkouts beside vpac. + +- if a build cannot resolve `alpm`, `blip` or `vmakepkg`, find where those + checkouts are on this machine (ask, or look in V's module directory) — + never stub a missing module or patch a module cache to make it work. +- parity questions ("what does pacman do?", "is this libalpm behavior?") are + answered in the pacman C source — the checkout that holds + `lib/libalpm/*.c` — and in libalpm's headers, not guessed. vpac follows + pacman's defaults closely; a lot of what looks odd is pacman's own + behavior spelled out. cross-reference before you fix. +- signature and checksum semantics: libalpm distinguishes the default, local + file and remote file siglevels; pacman maps its config onto all three. + +## building and testing + +- the compiler is `v`. `v . -o vpac` compiles to ./vpac at the repo root. + `v test src` and `v test vmakepkg` run the two suites. + there is no install step: link or copy ./vpac where you want it. +- a change is finished when `v -check .` is clean, both test suites pass, + and every touched .v file has been through the formatter (`v fmt -w` on + the file; the formatter reflows — check the result). +- tests are hermetic: each src/*_test.v compiles as its own binary and + builds its own local dbs under V's temp dir. they need no network and no + root. globals a test touches (config, cache dirs, colors) are saved and + restored inside the test. +- smoke checks against a real system are read-only only unless you are + meant to change it: search, info, --print previews, verify, find, tree + are safe. installs, removals and rank -w are not. + +## house style + +- prose comments, lowercase, sparsely worded: they say why — the intent, the + pacman or posix cross-reference, the data's shape — not what the line does. + when you change behavior, move the comment with it. +- error discipline: no panics behind doors a user walks through; every + libalpm call's error is handled; a housekeeping failure the run goes on + from (a handle's release, a temp dir's removal) is not `or {}` but + `or { went_on('release the alpm handle', err) }`, which --verbose says; + ?T (may be none) and !T (may fail) are unwrapped with their own syntax + and are not interchangeable. +- identifiers snake_case, files named for their one concern. the formatter + is the arbiter of layout; do not hand-alignment what v fmt will rewrite. + +## gotchas learned the hard way (do not rediscover them) + +- os.File.read reports end of input as an os.Eof error: end a chunked read + with `err is os.Eof`, and treat anything else as failure (a truncated + digest must never pass as a whole one). +- dup(2) and dup2(2) answer their new descriptor on success — never 0 — so a + check against `!= 0` fires on every success; check `fd < 0`. +- `lock` is a V keyword. so a variable named it does not compile; spell the + lock's path `lpath` instead. +- the flag attributes read the field's long name with dashes: @[long: + no_upgrade_deps] accepts --no-upgrade-deps. spell help text with dashes. +- a `?T` if-guard cannot read `err` — only a `!T` call's `or {}` has one. + a `!` call cannot hide inside a function that returns ?T: either handle + the error inline or widen the return. +- defer always runs, including through `or { return err }`: pair + trans_begin with `defer { trans_cleanup(handle) }` at the moment of begin + and never also release by hand (alpm_release is not idempotent). +- assigning one array to another needs the checker's `.clone()`; a borrowed + &T passed to a mut method is the local copy, never a write to the C side. +- the repo's __global config values are the whole config surface: + load_config resets every one of them before reading the file, so a second + load in one process starts clean (tests depend on this). + +## conventions that hold the system together + +- every question goes through ui.yesno / ui.noyes / ui.proceed / ui.choose, + which pause the live display first. --noconfirm takes each preset printed; + --print answers silently; pkgbuild installs refuse --noconfirm unless + --nopkgbuildconfirm (the first question's preset is no). +- the ipc protocol is a versioned surface (const ipc_protocol in ipc.v): an + event whose shape a reader must know about bumps it. once ipc_start ran, + plain prints never touch stdout — they are led to stderr, so the channel + stays whole json lines. +- the config can hold packages (pkg :hold): the check runs on the targets + and again on the transaction's final victim set, after prepare. +- modes that change the system re-execute themselves as root through the + root provider (the config's options :root: sudo by default, any command + that runs its arguments as root; su and pkexec are known by name), + carrying the config and the invoker's name across (VPAC_INVOKER, VPAC_V). + pkgbuild builds and + the build mode run as that invoking user, never as root. --lip-run is vpac + internal: the entry generated PKGBUILDs call back through, not a mode. +- read-only modes may open a lean alpm.initialize handle; anything that + writes goes through init_handle so libalpm's callbacks and the + configured siglevel, cachedirs, ignores and parallelism attach. + +## the issue tracker + +there is no TODO file: the checklist of the 2026-11-09 review sweep +moved into the issue tracker — 140 issues, one per checklist id, and #2 +their index. tracker numbers do not match the ids; look an id up in the +index (#2) first. later sweeps filed some findings two or three times: +close the duplicates of an issue with it. work changes state in the +tracker, not in files: open an issue first (`fj issue create -R origin`), +push the fix, then close the issue with the resolution +(`fj issue close -R origin N -w "..."`). fj talks to +the origin host (git.vorelabs.dev) and needs a token such as configured +under `fj auth list` — user read, repository read, issue read/write. diff --git a/README.md b/README.md new file mode 100644 index 0000000..78968ad --- /dev/null +++ b/README.md @@ -0,0 +1,58 @@ +## introduction + +[vpac](https://vpac.vorelabs.dev/) is *versatile* package manager based on [libalpm](https://man.archlinux.org/man/libalpm.3) + +## features + +vpac not only posses full pacman parity, but also extends on top of it: + +- advanced orphan detection: `vpac d -tt` also lists the dependencies only an optdepends line keeps +- mirror ranking by latency and download speed (`vpac k`), written to the files the config requires +- pkgbuild repos, the AUR among them: search them, review a PKGBUILD, and build and install from them (`vpac b`, `vpac i -b`) +- verification against the package's mtree, not just its file list (`vpac v -kk`), and of the local db and the sync dependencies (`vpac v -D`, `vpac v -DD`) +- file lookup in the sync file dbs (`vpac f`), with regular expressions too +- a json event protocol for other frontends (`--ui ipc`) +- one config file, written in [blip](https://git.vorelabs.dev/vorelabs/blip), that can pull its mirror lists from files of their own + +## quick start + +Clone this repository, then: + +```sh +./install.vsh # asks a few questions, writes /etc/vpac.d/config.lip +v . -o vpac # builds vpac into ./vpac +ln -sf $PWD/vpac /usr/local/bin/vpac +vpac k -w # ranks the mirrors for your system into the config's mirror file +vpac s -r linux-lts # search the sync databases +``` + +`install.vsh` also asks whether to keep vpac's database, cache, keys and hooks +in pacman's directories, and whether to turn libalpm's download sandbox off. +Answer no to the first only if you mean to keep vpac's state apart from +pacman's: a separate database does not know the packages pacman installed. + +Building needs the V compiler, `v`. It also needs the `alpm` and `blip` +modules, which V finds under its module directory, and libalpm's headers and +library. + +`v test src` and `v test vmakepkg` run the test suites. + +## docs + +- [usage](docs/usage.md): the command line, every mode and its options +- [configuration](docs/configuration.md): every form and key in `config.lip`, with its default + +## coming soon + +- drop-in pacman shim +- configuration profils +- state snapshots +- extended flake-like makepkg + +## state + +an honest assessment of vpac's state: + +- [X] good enough to keep along pacman +- [ ] can fully replace pacman +- [ ] can be installed on any compatible OS diff --git a/install.vsh b/install.vsh new file mode 100755 index 0000000..dff5b27 --- /dev/null +++ b/install.vsh @@ -0,0 +1,356 @@ +#!/usr/bin/env v + +import os + +// install.vsh sets vpac's config up for a new user: it asks a few questions, +// then writes /etc/vpac.d/config.lip and the mirror file the config requires, +// /etc/vpac.d/mirrors/.lip. the config stays in /etc/vpac.d whatever the +// answers: the pacman choice only picks where the db, cache, keys, hooks and +// log live. VPAC_ETC writes the two files into another directory instead, a +// trial that needs no root and makes no directory outside it. the binary is +// built with `v . -o vpac`, which the installer's next steps name. + +const default_etc = '/etc/vpac.d' + +// distro is an os the config is written for: its name, which is also the rank +// name (mirrors/.lip defines mirrors-), its repos, and the url its +// mirrors start from, with the $repo and $arch placeholders left in it +struct Distro { + name string + repos []string + src string +} + +fn distros() []Distro { + return [ + Distro{ + name: 'arch' + repos: ['core', 'extra'] + src: 'https://geo.mirror.pkgbuild.com/\$repo/os/\$arch' + }, + Distro{ + name: 'artix' + repos: ['system', 'world', 'galaxy'] + src: 'https://mirror1.artixlinux.org/repos/\$repo/os/\$arch' + }, + Distro{ + name: 'cachyos' + repos: ['cachyos'] + src: 'https://mirror.cachyos.org/repo/\$arch/\$repo' + }, + ] +} + +// paths are where vpac keeps its db, cache, keyring and hooks, and its log +struct Paths { + db string + cache string + gpg string + hook string + log string +} + +// pacman_paths are the directories pacman itself uses, which libalpm defaults +// to. the local db is pacman's own, so vpac sees the packages pacman installed +fn pacman_paths() Paths { + return Paths{ + db: '/var/lib/pacman/' + cache: '/var/cache/pacman/pkg/' + gpg: '/etc/pacman.d/gnupg/' + hook: '/etc/pacman.d/hooks/' + log: '/var/log/pacman.log' + } +} + +// own_paths are vpac's own, apart from pacman's. the db starts empty: it does +// not know the packages pacman installed, and the keyring has no keys until +// they are imported into it +fn own_paths() Paths { + return Paths{ + db: '/var/lib/vpac/' + cache: '/var/cache/vpac/pkg/' + gpg: '/etc/vpac.d/gnupg/' + hook: '/etc/vpac.d/hooks/' + log: '/var/log/vpac.log' + } +} + +// answers are what the questions settled +struct Answers { + distro string + aur bool + root string + parallel int + color string + sandbox bool + arch string +} + +fn main() { + run() or { + eprintln('install: ${err}') + exit(1) + } +} + +fn run() ! { + trial := os.getenv('VPAC_ETC') != '' + etc := if trial { os.getenv('VPAC_ETC') } else { default_etc } + config := os.join_path(etc, 'config.lip') + mut replace := false + if os.exists(config) { + println('${config} exists.') + keep := ask_yes('replace it? the old file is kept as config.lip.old', false)! + if !keep { + println('kept ${config}: nothing changed') + return + } + replace = true + } + + mut paths := own_paths() + if found('pacman') { + if ask_yes("pacman is installed: keep vpac's db, cache, keys, hooks and log in pacman's directories?", true)! { + paths = pacman_paths() + } else { + println("note: vpac's own db starts empty and does not see the packages pacman installed") + } + } else { + println("pacman is not installed: vpac links libalpm, which the pacman package ships, so install pacman before vpac can run. the config uses vpac's own directories") + } + + distro := ask_choice('mirrors for which os', distros().map(it.name), detect_distro())! + aur := ask_yes('add the AUR as a pkgbuild repo', true)! + providers := ['doas', 'sudo', 'pkexec', 'su'] + root := ask_choice('the command vpac gets root with', providers, root_default())! + parallel := ask_count('parallel downloads', 3, 1)! + color := ask_choice('color output', ['auto', 'always', 'never'], 'auto')! + sandbox := ask_yes("turn libalpm's sandbox off for downloads and extraction (pacman's DisableSandbox)", false)! + + // the root command runs when the files are written to /etc: the same one + // the config names for vpac's own escalation + escalate := !trial && os.getuid() != 0 + if escalate && !found(root) { + return error('${root} is not installed: install it, or run install.vsh as root') + } + + a := Answers{ + distro: distro + aur: aur + root: root + parallel: parallel + color: color + sandbox: sandbox + arch: os.uname().machine + } + d := distro_named(distro) + mirror := os.join_path(etc, 'mirrors', '${d.name}.lip') + write_mirror := !os.exists(mirror) + + // the files are staged in a temp dir and then moved into place, so the + // root command only copies + stage := os.join_path(os.temp_dir(), 'vpac-install-${os.getpid()}') + os.mkdir_all(os.join_path(stage, 'mirrors'))! + defer { + os.rmdir_all(stage) or { eprintln('install: could not remove ${stage}: ${err}') } + } + staged_config := os.join_path(stage, 'config.lip') + staged_mirror := os.join_path(stage, 'mirrors', '${d.name}.lip') + os.write_file(staged_config, config_text(a, paths, d))! + os.write_file(staged_mirror, mirror_text(d))! + + mut cmds := ['mkdir -p ${sh_quote(etc)} ${sh_quote(os.join_path(etc, 'mirrors'))}'] + if !trial { + cmds << 'mkdir -p ${sh_quote(paths.db)} ${sh_quote(paths.cache)} ${sh_quote(paths.gpg)} ${sh_quote(paths.hook)}' + } + if replace { + cmds << 'cp -f ${sh_quote(config)} ${sh_quote(config + '.old')}' + } + cmds << 'install -m 644 ${sh_quote(staged_config)} ${sh_quote(config)}' + if write_mirror { + cmds << 'install -m 644 ${sh_quote(staged_mirror)} ${sh_quote(mirror)}' + } + line := cmds.join(' && ') + argv := if escalate { root_argv(root, line) } else { ['sh', '-c', line] } + code := os.system_args(argv) + if code != 0 { + return error('writing ${config} failed (exit ${code}): fix the cause and run install.vsh again') + } + + println('wrote ${config}') + if write_mirror { + println('wrote ${mirror}: one default url, which vpac k -w ranks') + } else { + println('kept ${mirror}: it is already there') + } + println('') + println('next:') + println(term.bold(' v . -o vpac ') + ' build vpac') + println(term.bold(' ln -sf $PWD/vpac /usr/local/bin') + ' symlink vpac to /usr/local/bin/vpac') + println(term.bold(' vpac k -w ') + ' rank the ${d.name} mirrors into ${mirror}') +} + +// distro_named is the distro with the name, or the first one when none has it +fn distro_named(name string) Distro { + for d in distros() { + if d.name == name { + return d + } + } + return distros()[0] +} + +// detect_distro reads /etc/os-release the way the ranker does: the ID, then the +// ID_LIKE, the first name that is one of the distros +fn detect_distro() string { + text := os.read_file('/etc/os-release') or { return 'arch' } + mut id := '' + mut like := '' + for line in text.split_into_lines() { + if line.starts_with('ID=') { + id = line[3..].trim('"\'') + } else if line.starts_with('ID_LIKE=') { + like = line[8..].trim('"\'') + } + } + for candidate in [id, ...like.split(' ')] { + for d in distros() { + if d.name == candidate { + return candidate + } + } + } + return 'arch' +} + +// found reports whether an executable is on the PATH +fn found(exe string) bool { + path := os.find_abs_path_of_executable(exe) or { '' } + return path != '' +} + +// root_default is the first root command on the machine, in the order the +// installer prefers them +fn root_default() string { + for p in ['doas', 'sudo', 'pkexec', 'su'] { + if found(p) { + return p + } + } + return 'su' +} + +// root_argv is the command that runs one shell line as root through the root +// command. su takes the line with -c, the others run it through sh +fn root_argv(provider string, line string) []string { + if provider == 'su' { + return ['su', '-c', line] + } + return [provider, 'sh', '-c', line] +} + +// sh_quote spells one word for a posix shell, in single quotes +fn sh_quote(s string) string { + return "'" + s.replace("'", "'\\''") + "'" +} + +// read_answer reads one line off stdin. the end of input is an error and not an +// answer, so a run with stdin closed stops before it writes anything +fn read_answer(prompt string) !string { + line := os.input_opt(prompt) or { + return error('stdin closed before the questions were answered: nothing was written') + } + return line.trim_space() +} + +// ask reads one answer: the default when it is left empty +fn ask(question string, default string) !string { + suffix := if default == '' { '' } else { ' [${default}]' } + answer := read_answer('${question}${suffix}: ')! + return if answer == '' { default } else { answer } +} + +fn ask_yes(question string, default bool) !bool { + hint := if default { 'Y/n' } else { 'y/N' } + for { + raw := read_answer('${question} [${hint}]: ')! + match raw.to_lower() { + '' { return default } + 'y', 'yes' { return true } + 'n', 'no' { return false } + else { println('answer y or n') } + } + } + return default +} + +fn ask_choice(question string, choices []string, default string) !string { + for { + answer := ask('${question} (${choices.join(' / ')})', default)! + if answer in choices { + return answer + } + println('answer one of: ${choices.join(', ')}') + } + return default +} + +fn ask_count(question string, default int, min int) !int { + for { + answer := ask(question, '${default}')! + if answer.len > 0 && answer.bytes().all(it.is_digit()) && answer.int() >= min { + return answer.int() + } + println('answer a whole number, ${min} or more') + } + return default +} + +// config_text is the one config file: every form a user is likely to want, +// with the mirror file of the distro required beside it +fn config_text(a Answers, p Paths, d Distro) string { + mut repos := []string{} + for name in d.repos { + repos << '(repo\n :name "${name}"\n :src mirrors-${d.name})' + } + if a.aur { + repos << '(repo\n :name "aur"\n :type "pkgbuild"\n :src "https://aur.archlinux.org")' + } + return '; vpac config, written by install.vsh: edit it by hand, or run install.vsh again. +(require "mirrors/${d.name}.lip") + +(path + :root "/" + :db "${p.db}" + :log "${p.log}" + :gpg "${p.gpg}" + :cache ["${p.cache}"] + :hook ["${p.hook}"]) + +(pkg + :arch "${a.arch}" + :hold ["pacman" "glibc"]) + +(network + :parallel ${a.parallel} + :protocols ["https"] + :user "alpm"' + + if a.sandbox if { ':disable-sandbox true' } else { '' } + +' + +(options + :root "${a.root}" + :color "${a.color}") + +${repos.join('\n\n')} +' +} + +// mirror_text is a mirror file as rank writes one: mirrors- is defined +// and holds the urls, here the distro's one url until the ranking replaces it +fn mirror_text(d Distro) string { + return '; mirrors for ${d.name}, the default until vpac k -w ranks them +(unless (defined? mirrors-${d.name}) (define mirrors-${d.name} [])) +(array-append! mirrors-${d.name} ["${d.src}"]) +' +} diff --git a/pkgs/lipsmoke/PKGBUILD.lip b/pkgs/lipsmoke/PKGBUILD.lip new file mode 100644 index 0000000..bcfdc1f --- /dev/null +++ b/pkgs/lipsmoke/PKGBUILD.lip @@ -0,0 +1,35 @@ +(defpkgbuild lipsmoke + ;; — identity — + :pkgname "lipsmoke" + :pkgver "1.0" + :pkgrel 1 + :pkgdesc "a tiny smoke test that a lip package builds end to end" + :arch '(:any) + :url "https://example.org/lipsmoke" + :license "MIT" + ;; — dependencies — + :depends '("bash") + ;; — sources & integrity — + :source '("lipsmoke.sh" "readme.txt") + :b2sums '("0d2649f267def0d9a231544898208afd025f675015b38ad05e3806c136ec8ecd176fe29f3988b4be078e08c63f34178e966e15bfc17c7f738e86db0fb4107276" + "5eae74e3630b54f9271b53c7a1ad8b665e687efe08ec193b730ff36dc69c171021b2ecedcc6658e462c9f7c513bc87a76e0faf49326d60eb04d3323b36e72da1") + ;; — phases: one of each, including the loop/glob payoff — + :build + (lambda () + (run "install -m755 lipsmoke.sh just") + (echo "lipsmoke: build finished")) + :package + (lambda () + (run "install -Dm755 just ~a/usr/bin/lipsmoke" (pkgdir)) + (for-each (lambda (doc) + (run "install -Dm644 ~a ~a/usr/share/doc/lipsmoke/~a" doc (pkgdir) doc)) + (glob "*.txt")) + (echo "lipsmoke: package finished")) + ;; — .install hooks, inline; pacman hands the versions as arguments — + :pre-install + (lambda (newver) + (echo (format "lipsmoke: pre-installing ~a" newver)) + (echo "lipsmoke: pre-done")) + :post-install + (lambda (newver) + (echo (format "lipsmoke: installed ~a, run lipsmoke for a hello" newver)))) diff --git a/pkgs/lipsmoke/lipsmoke.sh b/pkgs/lipsmoke/lipsmoke.sh new file mode 100644 index 0000000..908db40 --- /dev/null +++ b/pkgs/lipsmoke/lipsmoke.sh @@ -0,0 +1,2 @@ +#!/bin/bash +echo "just, from the lip pipeline" diff --git a/pkgs/lipsmoke/readme.txt b/pkgs/lipsmoke/readme.txt new file mode 100644 index 0000000..3d94a94 --- /dev/null +++ b/pkgs/lipsmoke/readme.txt @@ -0,0 +1 @@ +the lipsmoke readme diff --git a/pkgs/lipsplit/PKGBUILD.lip b/pkgs/lipsplit/PKGBUILD.lip new file mode 100644 index 0000000..a551d88 --- /dev/null +++ b/pkgs/lipsplit/PKGBUILD.lip @@ -0,0 +1,15 @@ +(defpkgbuild lipsplit + ;; two arch-independent splits from one tree, one shared :package lambda + :pkgname '("lipsplit" "lipsplit-doc") + :pkgver "3.2" + :pkgrel 1 + :pkgdesc "smoke test of split packages written in blip" + :arch '(:any) + :license "MIT" + :depends '("bash") + :source '("shared.txt") + :b2sums '("f7d65eb3c70eddb9257e9539ab502e85fa754f5a7389631fd3171d944dc6fa466f73f525feaa8e83f5126a29e77fdf4774b3e27f99c4da23a86e7bda5041b92f") + :package + (lambda () + ;; each split runs its own invocation: (this-pkg) says which + (run "install -Dm644 shared.txt ~a/root-of-~a" (pkgdir) (this-pkg)))) diff --git a/pkgs/lipsplit/shared.txt b/pkgs/lipsplit/shared.txt new file mode 100644 index 0000000..9d03c89 --- /dev/null +++ b/pkgs/lipsplit/shared.txt @@ -0,0 +1 @@ +the split readme diff --git a/pkgs/vshsmoke/PKGBUILD.vsh b/pkgs/vshsmoke/PKGBUILD.vsh new file mode 100644 index 0000000..5319d48 --- /dev/null +++ b/pkgs/vshsmoke/PKGBUILD.vsh @@ -0,0 +1,61 @@ +#!/usr/bin/env v + +// a package written as a V script: the spec is a struct, the phases are +// functions, and vsh_entry turns it into a makepkg package +import vmakepkg +import os + +fn spec() !vmakepkg.Spec { + return vmakepkg.Spec{ + pkgname: 'vshsmoke' + pkgver: '1.4' + pkgrel: 1 + pkgdesc: 'a smoke test that a PKGBUILD.vsh builds end to end' + arch: ['any'] + url: 'https://example.org/vshsmoke' + license: 'MIT' + depends: ['bash'] + source: ['vshsmoke.sh', 'readme.txt'] + b2sums: [ + '5395122afa0a2a2f169f4dbf6da935531a81c968adfc2e284f8cdeb36db10bd6966f679e5b6f768c1962b507dd1fe5973a0fe18ce77affc1064a0f8a8e4eca8b', + '1645d573e1441b363804b7f6e1bbd71b87ee87027d0110be97bc8de7e2682d391ae0812770de7c218d0018ee3f4ad6607039019ed7b3c814963ecae80b12f77d', + ] + hooks: ['post-install'] + } +} + +fn build() ! { + // the cwd is the sources makepkg unpacked; run shells out with makepkg's + // own spellings of its state restored + vmakepkg.run('install -m755 vshsmoke.sh vsh')! + println('vshsmoke: build finished') +} + +fn package() ! { + pd := vmakepkg.pkgdir()! + mut docs := []string{} + // the binary is the package whether or not a doc came beside it + vmakepkg.run('install -Dm755 vsh ${vmakepkg.shell_quote(pd)}/usr/bin/vshsmoke')! + for doc in vmakepkg.glob('*.txt')! { + name := os.base(doc) + vmakepkg.run('install -Dm644 ${vmakepkg.shell_quote(doc)} ${vmakepkg.shell_quote(pd)}/usr/share/doc/vshsmoke/${vmakepkg.shell_quote(name)}')! + docs << doc + } + println('vshsmoke: package finished (${docs.len} docs unpacked alongside)') +} + +fn post_install(_ []string) ! { + println('vshsmoke: installed, run vshsmoke for a hello') +} + +vmakepkg.vsh_entry( + spec: spec + build: build + package: package + hooks: { + 'post-install': post_install + } +) or { + eprintln(err) + exit(1) +} diff --git a/pkgs/vshsmoke/readme.txt b/pkgs/vshsmoke/readme.txt new file mode 100644 index 0000000..daa054f --- /dev/null +++ b/pkgs/vshsmoke/readme.txt @@ -0,0 +1 @@ +# the readme the vsh smoke ships diff --git a/pkgs/vshsmoke/vshsmoke.sh b/pkgs/vshsmoke/vshsmoke.sh new file mode 100644 index 0000000..b7c9903 --- /dev/null +++ b/pkgs/vshsmoke/vshsmoke.sh @@ -0,0 +1,2 @@ +#!/bin/bash +echo "vsh smoke ok" diff --git a/src/alpm_log.h b/src/alpm_log.h new file mode 100644 index 0000000..3eba4d2 --- /dev/null +++ b/src/alpm_log.h @@ -0,0 +1,30 @@ +// alpm_log.h is the C half of libalpm's log callback (ui.v holds the V +// half). the callback takes a va_list, which V cannot receive portably — +// a pointer on x86_64, a struct on aarch64 — so the line is formatted here, +// with vsnprintf, and handed over whole. only ERROR and WARNING pass, the +// levels pacman's cb_log prints by default: alpm_loglevel_t is bit flags +#ifndef VPAC_ALPM_LOG_H +#define VPAC_ALPM_LOG_H + +#include +#include +#include + +// vpac_log_line is exported by ui.v +void vpac_log_line(void *ctx, int level, char *text); + +static void vpac_alpm_log(void *ctx, alpm_loglevel_t level, const char *fmt, va_list args) { + if(!(level & (ALPM_LOG_ERROR | ALPM_LOG_WARNING)) || fmt == NULL || fmt[0] == '\0') { + return; + } + char line[4096]; + vsnprintf(line, sizeof line, fmt, args); + vpac_log_line(ctx, (int)level, line); +} + +// vpac_set_alpm_log installs the callback, ctx being the run's TransUI +static int vpac_set_alpm_log(alpm_handle_t *handle, void *ctx) { + return alpm_option_set_logcb(handle, vpac_alpm_log, ctx); +} + +#endif diff --git a/src/autoremove.v b/src/autoremove.v new file mode 100644 index 0000000..f3736c9 --- /dev/null +++ b/src/autoremove.v @@ -0,0 +1,72 @@ +module main + +import alpm + +// mirrors pacman's -Rns $(pacman -Qtdq) idiom: remove every orphaned +// package, letting the transaction pull in the dependencies that become +// unneeded along the way (recurse), dropping their config files (nosave) +fn autoremove(config ConfigAutoRemove) ! { + mut ui := new_trans_ui(noconfirm: config.noconfirm) + check_ask_db_lock(mut ui) + + mut handle := init_handle(ui)! + defer { handle.release() or { went_on('release the alpm handle', err) } } + defer { ui.stop() } + defer { trans_cleanup(handle) } + + mut s := ui.spinner(text: 'finding orphans') + s.start() + defer { stop_spinner(mut s) } + + mut pkgcache := local_pkgcache(handle)! + + orphs := orphan_pkgs(mut pkgcache, false) + if orphs.len == 0 { + stop_spinner(mut s) + ui.pause() + report('no orphans') + return + } + // the config can hold a package even when it is an orphan + check_hold(orphs.map(it.get_name()))! + + s.set_text('preparing removal') + trans_begin(handle, alpm.TransFlag.recurse | alpm.TransFlag.no_save)! + for pkg in orphs { + handle.remove_pkg(pkg)! + } + + trans_prepare_checked(handle)! + + // never empty: every orphan is a target, recurse only adds to them, and + // without the unneeded flag libalpm drops no target, it fails instead + victims := handle.trans_get_remove().pkgs() + + stop_spinner(mut s) + + // the transaction is the truth of what goes: a package held by the + // config that only the recurse would reach counts for the hold list too + check_hold(victims.map(it.get_name()))! + + if !trans_confirm(mut ui, handle, victims, .autoremove) { + return + } + + // the names are read before the commit, which frees the removed packages + names := victims.map(it.get_name()) + + mut s2 := ui.spinner(text: 'removing orphans') + s2.start() + defer { stop_spinner(mut s2) } + trans_commit(handle)! + stop_spinner(mut s2) + // a frontend learns what went as from every transaction: a done event + if ipc_on() { + emit(DoneEvent{ + action: 'removed' + packages: names + }) + return + } + ui.say('removed ${success(names.len.str())} orphaned packages') +} diff --git a/src/build_repo.v b/src/build_repo.v new file mode 100644 index 0000000..9aaabce --- /dev/null +++ b/src/build_repo.v @@ -0,0 +1,300 @@ +module main + +import crypto.sha256 +import vmakepkg +import os + +fn C.mkdtemp(template &char) &char + +// A package is pulled from an arbitrary repo — a directory or a git url — +// under the config's pkgbuild build dir, reviewed whole, built with the +// system's makepkg and installed. A bash PKGBUILD runs makepkg exactly as the +// original spells it; a PKGBUILD.lip gets a generated PKGBUILD whose phases +// run as blip through this very binary. +struct ConfigBuild { +pub mut: + show_help bool @[long: help; short: h] + noconfirm bool @[long: noconfirm] + no_pkgbuild_confirm bool @[long: nopkgbuildconfirm] + query []string @[tail] +} + +// generated_review is the review of a generated package: the source (the +// lip or the .vsh) and the PKGBUILD plus .install it produced, so the user +// agrees with everything makepkg will execute +fn generated_review(package string, source_name string, source_text string, pkg_text string, install_name string, install_text string) ReviewEvent { + mut parts := [ReviewFile{ + name: source_name + text: source_text + }, ReviewFile{ + name: 'PKGBUILD' + text: pkg_text + generated: true + }] + if install_text != '' { + parts << ReviewFile{ + name: install_name + text: install_text + generated: true + } + } + return ReviewEvent{ + package: package + files: parts + } +} + +// install_name_of reads the install file a generated PKGBUILD's head names, +// spelled the way makepkg accepts one: '=' with spaces, quotes of either +// kind; '' when it names none. it names a file beside the PKGBUILD: anything +// that leaves the build dir already (an absolute path, a '..' climb) is not a +// name this reader agrees to read. makepkg reads the line through bash, so a +// name spelled with a variable or followed by a comment comes back as +// written, naming no file here — review_the_rest covers that +fn install_name_of(pkg_text string) !string { + mut name := '' + for line in pkg_text.split('\n') { + s := line.trim_space() + if !s.starts_with('install') { + continue + } + rest := s[7..].trim_space() + if !rest.starts_with('=') { + continue + } + val := rest[1..].trim_space().trim('\'"') + if val == '' { + continue + } + if val.starts_with('/') || val in ['.', '..'] || val.starts_with('../') + || val.contains('/../') || val.ends_with('/..') { + return error('b: the install file name "${val}" is not a plain name beside the PKGBUILD') + } + name = val + } + return name +} + +// review_the_rest completes a generated PKGBUILD's review the way read_review +// shows a plain one's: every .install file of the build dir, not only the +// one install_name_of could resolve, and the build dir's files. the install +// scriptlet runs as root at install time, so one makepkg packs under a name +// this reader could not resolve must not get there unseen; such a name is +// said, beside the files that may be it +fn review_the_rest(mut review ReviewEvent, work_dir string, install_name string, resolved bool) ! { + mut names := os.ls(work_dir)! + names.sort() + on_view := review.files.map(it.name) + for f in names { + if f == '.git' { + continue + } + review.listing << f + if f.ends_with('.install') && f !in on_view && os.is_file('${work_dir}/${f}') { + review.files << ReviewFile{ + name: f + text: os.read_file('${work_dir}/${f}')! + } + } + } + if install_name != '' && !resolved { + review.warnings << 'the install file "${install_name}" could not be resolved: every .install file is shown' + } +} + +// pull_dir copies a local repo into its build dir as the building user: a +// root-owned copy would stop makepkg from touching anything +fn pull_dir(user string, src string, dst string) ! { + run_as_user(user, ['mkdir', '-p', os.dir(dst)])! + run_as_user(user, ['rm', '-rf', dst])! + run_as_user(user, ['cp', '-R', src, dst])! +} + +// write_as_user lays a generated file (a PKGBUILD or a .install out of a +// PKGBUILD.lip) into the work dir with the building user's ownership, the way +// pull_dir gives the clone theirs: a file that belongs to the root process +// would make makepkg's reads and the cleanups beside it trip. the text goes +// into a read-only temp file of the root process, and install copies it over. +// the temp file lives in a directory mkdtemp made for this one write: its +// name cannot be guessed and nobody else may write in it, so no link can be +// planted where the root process is about to write +fn write_as_user(user string, path string, text string) ! { + template := os.join_path(os.temp_dir(), 'vpac.XXXXXX').clone() + if C.mkdtemp(&char(template.str)) == unsafe { nil } { + return error('could not make a temp dir: ${os.posix_get_error_msg(C.errno)}') + } + defer { + os.rmdir_all(template) or { went_on('remove the temp dir ${template}', err) } + } + // the building user reads the file through it, and writes nothing in it + os.chmod(template, 0o755)! + tmp := os.join_path(template, 'text') + os.write_file(tmp, text)! + os.chmod(tmp, 0o444)! + run_as_user(user, ['install', '-m', '644', tmp, path])! +} + +// repo_name is the name a repo goes by: the last part of its path or url, +// without a .git suffix. an scp-style git address (user@host:path) counts +// from after the colon. empty when the target names nothing, like / or . +fn repo_name(source string) string { + name := os.base(source.trim_right('/')).all_after_last(':').trim_string_right('.git') + return if name in ['', '.', '..', '/'] { '' } else { name } +} + +// is_scp_remote reports scp-style git remotes (user@host:path): a colon that +// comes before the first slash, where the colon of a host:port transfer url +// or of a plain path with a colon in it would not. git itself accepts both +// spellings of that, so the clone does not need the target spelled further +fn is_scp_remote(target string) bool { + colon := target.index(':') or { return false } + // no slash: the colon splits the host from the path + slash := target.index('/') or { return true } + return colon < slash +} + +// is_git_url reports whether git clone can fetch the target: a transfer url, +// a name ending in .git, or an scp-style remote +fn is_git_url(target string) bool { + return target.ends_with('.git') || target.contains('://') || is_scp_remote(target) +} + +// repo_work_dir is where a b target is pulled and built, and the name the +// repo goes by. the dir is the name and a hash of the source, so two repos +// of one name (a fork, a mirror, two checkouts) and a pkgbuild package of +// that name never share it, and the same repo always lands in the same dir. +// a directory is keyed on its real path, so ./x and /abs/x are one repo +fn repo_work_dir(user string, target string) !(string, string) { + source := if os.is_dir(target) { os.real_path(target) } else { target.trim_right('/') } + name := repo_name(source) + if name == '' { + return error('b: "${target}" names no repo to build') + } + return name, pkgbuild_build_dir(user, '${name}-${sha256.hexhash(source)[..8]}')! +} + +// build_repo_target pulls one target, reviews it, builds and installs it. +// a target is an existing directory (a checkout, taken as the repo stands) +// or a git url to clone; bare names belong to the pkgbuild repos, which the +// --pkgbuild installs already cover, so the error points there +fn build_repo_target(config ConfigBuild, target string, mut ui TransUI) ! { + user := invoker_user()! + base, work_dir := repo_work_dir(user, target)! + // with --nopkgbuildconfirm nothing is asked, and the review is still + // shown: the record of what was built stays in the output + ask := !config.no_pkgbuild_confirm + ui.pause() + run_as_user(user, ['mkdir', '-p', os.dir(work_dir)])! + defer { ui.sync() } + if os.is_dir(target) { + pull_dir(user, target, work_dir)! + } else if is_git_url(target) { + // git is the one tool a clone cannot happen without: an absent one is + // said plainly, below user's name, before anything pulls + run_as_user(user, ['sh', '-c', 'git --version >/dev/null']) or { + return error('git is needed to clone ${target} as user ${user}, but it was not found (or failed): ${err.msg()}') + } + run_as_user(user, ['rm', '-rf', work_dir])! + run_as_user(user, ['git', 'clone', '--depth', '${pkgbuild_depth}', target, work_dir])! + } else { + return error('b: "${target}" is neither a directory nor a git url; pkgbuild repos are covered by vpac i --pkgbuild ${target}') + } + // makepkg builds either spelling; a bash PKGBUILD keeps the + // plain makepkg flow, the lip one generates its PKGBUILD through this + // binary's blip runner, and a PKGBUILD.vsh asks its own script to write + // the PKGBUILD through v + work_lip := '${work_dir}/PKGBUILD.lip' + mut work_vsh := '${work_dir}/PKGBUILD.vsh' + if os.exists(work_lip) { + bb := vmakepkg.lip_make(work_lip, os.executable())! + install_name := if bb.install != '' { '${bb.base}.install' } else { '' } + review := generated_review(base, os.base(work_lip), os.read_file(work_lip)!, + bb.text, install_name, bb.install) + show_review(review, '') + if ask && !ui.noyes('build and install ${base}?') { + return + } + write_as_user(user, '${work_dir}/PKGBUILD', bb.text)! + if bb.install != '' { + write_as_user(user, '${work_dir}/${bb.base}.install', bb.install)! + } + } else if os.exists(work_vsh) { + // v run compiles its temp to the script's own name inside the work + // dir, right on top of the PKGBUILD the script writes, so the script + // hides before anything runs + hsh := '${work_dir}/.vsh' + run_as_user(user, ['mv', work_vsh, hsh])! + work_vsh = hsh + // v lives where every tool of this project lives, and runuser's + // sanitized path may not carry it, so the script runs by full path + vbin := if os.getenv(env_v) != '' { + os.getenv(env_v) + } else { + os.find_abs_path_of_executable('v') or { + return error('the v compiler is not in the path; it is needed to run a PKGBUILD.vsh') + } + } + // the temp compile goes to the side of the PKGBUILD the script writes. + // the compiled runner is only for the generation: it is gone before + // the review lists the dir and before makepkg could pack it, whether + // the generation went through or not + generated := run_as_user(user, ['sh', '-c', + 'export VPAC_VSH_PATH=${vmakepkg.shell_quote(work_vsh)}; cd ${vmakepkg.shell_quote(work_dir)} && ${vmakepkg.shell_quote(vbin)} -o ${vmakepkg.shell_quote('${work_dir}/.vshgen')} run ${vmakepkg.shell_quote(work_vsh)} generate']) + run_as_user(user, ['rm', '-f', '${work_dir}/.vshgen']) or { + warn('could not remove the generator ${work_dir}/.vshgen: ${err.msg()}') + } + generated! + if !os.exists('${work_dir}/PKGBUILD') { + return error('${work_vsh} wrote no PKGBUILD') + } + pkg_text := os.read_file('${work_dir}/PKGBUILD')! + install_name := install_name_of(pkg_text)! + install_path := '${work_dir}/${install_name}' + resolved := install_name != '' && os.is_file(install_path) + install_text := if resolved { os.read_file(install_path)! } else { '' } + mut review := generated_review(base, 'PKGBUILD.vsh', os.read_file(work_vsh)!, pkg_text, + install_name, install_text) + review_the_rest(mut review, work_dir, install_name, resolved)! + show_review(review, '') + if ask && !ui.noyes('build and install ${base}?') { + return + } + } else if os.exists('${work_dir}/PKGBUILD') { + show_review(read_review(base, work_dir)!, 'review ${base}') + if ask && !ui.noyes('build and install ${base}?') { + return + } + } else { + return error('${work_dir} holds neither PKGBUILD, PKGBUILD.lip nor PKGBUILD.vsh') + } + build_phase(base, 'start') + run_as_user(user, ['sh', '-c', makepkg_line(work_dir)])! + build_phase(base, 'done') + // everything makepkg produced goes into one install: a split package's + // set lands with one transaction, one listing and one go-ahead, the way + // the pkgbuild installs batch their own + archives := built_packages(user, work_dir)! + if archives.len == 0 { + return error('b: makepkg built nothing for ${base} that its --packagelist names') + } + install(ConfigInstall{ + query: archives + noconfirm: config.noconfirm + })! +} + +// build_repo is the mode's entry: every query is one repo to build +fn build_repo(config ConfigBuild) ! { + need_query(config.query, 'repo (a directory or a git url)')! + // --noconfirm would take the build question's preset, which is no, and + // build nothing with a clean exit: the refusal says so first, as the + // pkgbuild installs' does + if config.noconfirm && !config.no_pkgbuild_confirm { + return error('a build is asked about: drop --noconfirm, or pass --nopkgbuildconfirm, to build ${config.query.join(', ')}') + } + mut ui := new_trans_ui(noconfirm: config.noconfirm) + defer { ui.stop() } + for target in config.query { + build_repo_target(config, target, mut ui)! + } +} diff --git a/src/build_repo_test.v b/src/build_repo_test.v new file mode 100644 index 0000000..4a1728d --- /dev/null +++ b/src/build_repo_test.v @@ -0,0 +1,158 @@ +module main + +import os + +fn test_repo_name() { + // the last part of the path or url, without a .git suffix. trim_right + // would have cut a set of characters: digit came out as d, gist as gis + cases := { + 'https://example.org/mything.git': 'mything' + 'https://example.org/mything': 'mything' + 'https://example.org/mything.git/': 'mything' + 'https://example.org/digit': 'digit' + 'https://example.org/gist.git': 'gist' + 'git@github.com:foo/bar.git': 'bar' + 'git@host:bar.git': 'bar' + '/home/u/src/thing': 'thing' + '/home/u/src/thing/': 'thing' + '/': '' + '.': '' + '': '' + } + for source, want in cases { + got := repo_name(source) + assert got == want, 'repo_name("${source}") is "${got}", not "${want}"' + } +} + +fn test_repo_work_dir_urls() ! { + old := pkgbuild_dir + pkgbuild_dir = '/builds' + defer { pkgbuild_dir = old } + + name, one := repo_work_dir('u', 'https://one.example/mything.git')! + _, two := repo_work_dir('u', 'https://two.example/mything.git')! + _, one_slash := repo_work_dir('u', 'https://one.example/mything.git/')! + assert name == 'mything' + hash := one.all_after('/builds/mything-') + assert one.starts_with('/builds/mything-') && hash.len == 8 + assert hash.bytes().all(it.is_hex_digit()) + // the same name from another source is another dir; a trailing slash is + // the same source + assert one != two + assert one == one_slash + // and a pkgbuild package of that name builds elsewhere + assert one != pkgbuild_build_dir('u', 'mything')! + if _, _ := repo_work_dir('u', '/') { + assert false, '/ names no repo' + } +} + +fn test_is_git_url() { + // the transfer urls and the .git names, as always + assert is_git_url('https://example.org/mything.git') + assert is_git_url('git://example.org/mything') + // scp-style: user@host:path — a colon before any slash, the way git + // spells a clone it will fetch over ssh + assert is_git_url('git@github.com:foo/bar') + assert is_git_url('git@host:bar.git') + assert is_scp_remote('git@host:bar.git') + // a path's slash comes first; a bare file with a colon in its name has + // no slash before it either, but hosts come before the colon in scp + for not in ['/home/u/mything', '/home/u/we:ird', '/dev/null:too'] { + assert !is_scp_remote(not), not + } +} + +fn test_repo_work_dir_directories() ! { + old := pkgbuild_dir + pkgbuild_dir = '/builds' + defer { pkgbuild_dir = old } + tmp := os.join_path(os.vtmp_dir(), 'vpac_test_build_repo_${os.getpid()}') + os.mkdir_all(os.join_path(tmp, 'a', 'mything'))! + os.mkdir_all(os.join_path(tmp, 'b', 'mything'))! + defer { os.rmdir_all(tmp) or {} } + cwd := os.getwd() + defer { os.chdir(cwd) or {} } + + _, a := repo_work_dir('u', os.join_path(tmp, 'a', 'mything'))! + _, b := repo_work_dir('u', os.join_path(tmp, 'b', 'mything'))! + assert a != b + // a directory is keyed on its real path: relative, trailing slash and . + // all name the same checkout + os.chdir(os.join_path(tmp, 'a'))! + _, rel := repo_work_dir('u', 'mything/')! + os.chdir(os.join_path(tmp, 'a', 'mything'))! + dot_name, dot := repo_work_dir('u', '.')! + assert rel == a + assert dot == a + assert dot_name == 'mything' +} + +fn test_install_name_of() ! { + for text, want in { + 'pkgname=x\ninstall=x.install\n': 'x.install' + 'install = "x.install"': 'x.install' + "install='x.install'": 'x.install' + // bash reads these; this reader takes them as written + 'install="\${pkgname}.install"': '\${pkgname}.install' + 'install=x.install # the hooks': 'x.install # the hooks' + // none named, or a command in a function body, which is no assignment + 'pkgname=x\n': '' + 'package() {\n install -Dm755 x "$pkgdir/x"\n}': '' + 'installdir=/opt': '' + // the last assignment is the one bash keeps + 'install=a.install\ninstall=b.install': 'b.install' + } { + assert install_name_of(text)! == want, text + } + for escape in ['install=/etc/x.install', 'install=../x.install', 'install=a/../../x.install', + 'install=..'] { + install_name_of(escape) or { + assert err.msg().contains('is not a plain name beside the PKGBUILD'), err.msg() + continue + } + assert false, '${escape} was taken' + } +} + +fn test_review_the_rest_shows_every_install_file() ! { + dir := os.join_path(os.vtmp_dir(), 'vpac_test_review_rest_${os.getpid()}') + os.rmdir_all(dir) or {} + os.mkdir_all(os.join_path(dir, '.git'))! + defer { os.rmdir_all(dir) or {} } + pkg_text := 'pkgname=x\ninstall="\${pkgname}.install"\n' + os.write_file(os.join_path(dir, 'PKGBUILD'), pkg_text)! + os.write_file(os.join_path(dir, 'x.install'), 'post_install() { rm -rf /; }')! + os.write_file(os.join_path(dir, 'other.install'), 'post_upgrade() { :; }')! + os.write_file(os.join_path(dir, 'x.patch'), 'patch')! + // the generated head spells its install file with a variable: the reader + // cannot resolve it, and the scriptlet makepkg packs must still be shown + name := install_name_of(pkg_text)! + mut review := generated_review('x', 'PKGBUILD.vsh', 'script', pkg_text, name, '') + review_the_rest(mut review, dir, name, false)! + files := review.files.map(it.name) + assert 'x.install' in files && 'other.install' in files, files.str() + assert review.files.filter(it.name == 'x.install')[0].text == 'post_install() { rm -rf /; }' + assert review.listing == ['PKGBUILD', 'other.install', 'x.install', 'x.patch'] + assert review.warnings.len == 1 + assert review.warnings[0].contains('"\${pkgname}.install"'), review.warnings[0] + + // a name the reader resolved is shown once, and nothing is warned of + mut plain := generated_review('x', 'PKGBUILD.vsh', 'script', 'install=x.install', 'x.install', + 'post_install() { rm -rf /; }') + review_the_rest(mut plain, dir, 'x.install', true)! + assert plain.files.filter(it.name == 'x.install').len == 1 + assert plain.files.any(it.name == 'other.install') + assert plain.warnings.len == 0 +} + +fn test_build_refuses_noconfirm_alone() { + // the build question's preset is no: --noconfirm alone would build + // nothing and exit clean, so it is refused before anything is pulled + build_repo(ConfigBuild{ noconfirm: true, query: ['/nonexistent/repo'] }) or { + assert err.msg().contains('--nopkgbuildconfirm'), err.msg() + return + } + assert false, 'built under --noconfirm' +} diff --git a/src/clean.v b/src/clean.v new file mode 100644 index 0000000..ad037f5 --- /dev/null +++ b/src/clean.v @@ -0,0 +1,436 @@ +module main + +import alpm +import os +import v.profiler + +// one archive file sitting in the cache, with its .sig companion removed +// alongside it, like pacman's cleancache does. the failures are collected and +// reported after: a clean that could not remove a file does not look +// successful, and the meter only moves past the files that went +fn cache_purge(mut ui TransUI, files []string) { + mut bar := ui.meter(files.len, 'removing cached packages') + bar.start() + mut failed := []string{} + for f in files { + os.rm(f) or { + failed << f + continue + } + // the sig goes only once its package did. one that was never signed + // has no companion to remove, so only a real failure is reported + if os.exists(f + '.sig') { + os.rm(f + '.sig') or { failed << f + '.sig' } + } + bar.add(1) + } + if failed.len > 0 { + warn('could not remove ${failed.len} of ${files.len} cached files: ${failed.map(os.base(it)).join(', ')}') + } +} + +// is_pkg_archive is whether a file name is a package archive's: compressed +// (.pkg.tar.zst and the like) or the plain .pkg.tar makepkg writes with no +// compression, as pacman's cache clean takes both; never a signature +fn is_pkg_archive(f string) bool { + return (f.contains('.pkg.tar.') || f.ends_with('.pkg.tar')) && !f.ends_with('.sig') +} + +fn cached_pkg_files() ![]string { + mut out := []string{} + for dir in cfg_cachedirs { + names := os.ls(dir) or { + // one unreadable cache dir does not take the others' cleaning + // down with it: the run cleans what it can see, and says so + warn('could not list the cache directory ${dir}: ${err.msg()}, cleaning the rest') + continue + } + // package archives only, with their directory prefixed; sigs go with + // their package, dbs stay + out << names.filter(|f| is_pkg_archive(f)).map(|f| os.join_path(dir, f)) + } + return out +} + +// sync_db_exts are the files a sync db is kept as, sigs and file dbs too +const sync_db_exts = ['.db.sig', '.files.sig', '.db', '.files'] + +// unused_sync_dbs are the sync db files of repos the config does not name +// any more, what pacman's -Sc asks about as 'unused repositories'. pacman +// clears everything else out of the sync dir with them; only what is +// plainly a db goes here, so the sync stamp and anything unknown stay +fn unused_sync_dbs() []string { + dir := db_path + 'sync/' + if !os.is_dir(dir) { + return []string{} + } + mut names := os.ls(dir) or { + warn('could not list the sync databases in ${dir}: ${err.msg()}, none is cleaned') + return []string{} + } + names.sort() + known := cfg_repos.filter(it.kind != 'pkgbuild').map(it.name) + mut out := []string{} + for f in names { + for ext in sync_db_exts { + if f.len > ext.len && f.ends_with(ext) { + if f[..f.len - ext.len] !in known { + out << dir + f + } + break + } + } + } + return out +} + +// a cached package archive: pkgname-pkgver-pkgrel-arch.pkg.tar[.*] +struct CacheFile { + name string + version string + file string +} + +// installed_file is whether a cached archive is the installed version of its +// package. the cache is listed as full paths and the prefixes are +// name-version-, so the file name is what they are matched against: its +// name and version read out whole, as pacman compares the archive's own, so +// a package whose name merely begins with another's name-version- is not +// taken for it. a name that does not read as an archive's is matched by its +// beginning, the careful way round: it is kept +fn installed_file(f string, keep_prefixes []string) bool { + if c := parse_cache_file(f) { + return '${c.name}-${c.version}-' in keep_prefixes + } + name := os.base(f) + return keep_prefixes.any(|k| name.starts_with(k)) +} + +fn parse_cache_file(f string) ?CacheFile { + base := os.base(f).all_before('.pkg.tar') + toks := base.split('-') + if toks.len < 4 { + return none + } + arch_t := toks.last() + rel := toks[toks.len - 2] + ver := toks[toks.len - 3] + name := toks[..toks.len - 3].join('-') + if arch_t == '' || rel == '' || ver == '' || name == '' { + return none + } + return CacheFile{ + name: name + version: ver + '-' + rel + file: f + } +} + +// paccache's KeepInstalled+KeepN: keep the newest `keep_n` versions of every +// package, plus whatever is currently installed. an installed version is +// kept once even though it also counts among the newest, so the answer is a +// set and the caller's filtering reads it straight +fn paccache_keep(keep_n int, files []string, keep_prefixes []string) map[string]bool { + mut groups := map[string][]CacheFile{} + mut kept := map[string]bool{} + for f in files { + // installed versions are always kept, and they still count among the + // newest: -k 2 keeps two versions, not the installed one and two more + if installed_file(f, keep_prefixes) { + kept[f] = true + } + cf := parse_cache_file(f) or { continue } + if cf.name !in groups { + groups[cf.name] = []CacheFile{} + } + groups[cf.name] << cf + } + for name in groups.keys() { + mut gg := groups[name] + // newest first, using the same vercmp as pacman + gg.sort_with_compare(fn (a &CacheFile, b &CacheFile) int { + return alpm.pkg_vercmp(b.version, a.version) + }) + for i, cf in gg { + if i < keep_n { + kept[cf.file] = true + } + } + } + return kept +} + +// BuildClean is what vpac c does with the pkgbuild build dirs: of the builds +// found under root, the ones it removes and their size +struct BuildClean { + user string + root string +mut: + found int + dirs []string + size u64 + // partial says the size is a floor: part of a build could not be read, + // and what is there is more than was counted + partial bool +} + +// build_dirs_to_clean picks the pkgbuild builds vpac c removes. like paru's +// and yay's clean, a build stays while its package is installed: its dir is +// named after an installed package base (vpac i --pkgbuild), or it holds a +// built archive of an installed package (vpac b, split packages). with all, +// every build goes. a build is pulled afresh each time, so nothing in a +// removed one is ever reused +fn build_dirs_to_clean(user string, all bool, bases []string, names []string) !BuildClean { + root := pkgbuild_root(user)! + mut bc := BuildClean{ + user: user + root: root + } + if !os.is_dir(root) { + return bc + } + for entry in os.ls(root)! { + dir := os.join_path(root, entry) + if os.is_link(dir) || !os.is_dir(dir) { + continue + } + bc.found++ + if !all && build_in_use(dir, entry, bases, names) { + continue + } + bc.dirs << dir + size, whole := tree_size(dir) + bc.size += size + if !whole { + bc.partial = true + } + } + return bc +} + +// build_in_use is whether a build dir belongs to an installed package +fn build_in_use(dir string, entry string, bases []string, names []string) bool { + if entry in bases { + return true + } + // fail closed: when the build cannot even be listed, it cannot be proven + // unused, and clean never deletes something it is not sure of. clean runs + // as root through run_as_user, so an unreadable dir is reported plainly + pkgs := archives_in(dir) or { + warn("could not list the built packages of '${dir}': ${err.msg()}, keeping the build") + return true + } + for archive in pkgs { + cf := parse_cache_file(os.base(archive)) or { continue } + if cf.name in names { + return true + } + } + return false +} + +// tree_size adds up the files under path, and says whether that is the +// whole of it: a directory that cannot be listed is warned about and +// counted as nothing, which makes the sum a floor and not the size. the +// rest of the tree is still counted. links are not followed: a build tree +// may point anywhere +fn tree_size(path string) (u64, bool) { + if os.is_link(path) { + return 0, true + } + if !os.is_dir(path) { + return os.file_size(path), true + } + names := os.ls(path) or { + warn('could not read ${path}: ${err.msg()}, its size is left out') + return 0, false + } + mut total := u64(0) + mut whole := true + for name in names { + size, sub_whole := tree_size(os.join_path(path, name)) + total += size + whole = whole && sub_whole + } + return total, whole +} + +// size_text spells a size for a person; one that is a floor says so +fn size_text(size u64, partial bool) string { + text := profiler.format_bytes(size) + return if partial { 'at least ${text}' } else { text } +} + +// clean_event is what a frontend is told before the proceed question. the +// build root goes out only when an invoker was known and its builds looked +// at; BuildClean{} is the unlooked-at one +fn clean_event(to_remove []string, total u64, builds BuildClean, dbs []string, preview bool) CleanEvent { + return CleanEvent{ + cache_dirs: cfg_cachedirs + build_root: if builds.user != '' { ?string(builds.root) } else { none } + files: to_remove + files_size: total + builds: builds.dirs + build_size: builds.size + build_size_partial: builds.partial + dbs: dbs + preview: preview + } +} + +fn clean(config ConfigClean) ! { + mut ui := new_trans_ui(noconfirm: config.noconfirm) + mut handle := init_handle(ui)! + defer { handle.release() or { went_on('release the alpm handle', err) } } + defer { ui.stop() } + + mut pkgcache := local_pkgcache(handle)! + installed := pkgcache.pkgs() + + // the package cache: everything with -a or -cc (pacman's -Scc), + // otherwise pacman's default KeepInstalled clean method, optionally + // paccache style with -k N: keep the newest N versions of every package + every := config.all || config.level >= 2 + pkg_files := cached_pkg_files()! + to_remove := if every { + pkg_files + } else { + mut keep_prefixes := installed.map(|pkg| '${pkg.get_name()}-${pkg.get_version()}-') + // pacman's KeepCurrent: a version a sync db still carries stays too + if config.keep_current { + for db in init_repos(mut handle)! { + // a sync db that cannot be read would keep nothing: what it + // carries would be cleaned as if no repo had it any more + mut cache := pkgcache_of(handle, db)! + keep_prefixes << cache.pkgs().map(|pkg| '${pkg.get_name()}-${pkg.get_version()}-') + } + } + to_keep := if config.keep > 0 { + // a set of paths, not a list: a cache of thousands of archives is + // filtered by map lookup per file, not a scan per file + paccache_keep(config.keep, pkg_files, keep_prefixes) + } else { + mut keep := map[string]bool{} + for f in pkg_files.filter(|f| installed_file(f, keep_prefixes)) { + keep[f] = true + } + keep + } + pkg_files.filter(|f| !to_keep[f]) + } + mut total := u64(0) + for f in to_remove { + total += os.file_size(f) + } + + // the pkgbuild builds are the invoker's: root running vpac c itself has + // none, since builds never run as root. a root session nobody asked for + // says so, instead of quietly leaving every build dir behind it + mut builds := BuildClean{} + if user := invoker_user() { + builds = build_dirs_to_clean(user, config.all, installed.map(it.get_base()), + installed.map(it.get_name()))! + } else { + warn('pkgbuild builds are not cleaned: run vpac as your own user') + } + + // the sync dbs of repos the config dropped go with any clean, as + // pacman's -Sc offers + dbs := unused_sync_dbs() + + // a frontend gets what would go as one event; the proceed question follows + // it unless this is a --print preview + if ipc_on() { + emit(clean_event(to_remove, total, builds, dbs, config.print_only)) + if config.print_only || (to_remove.len == 0 && builds.dirs.len == 0 && dbs.len == 0) { + return + } + } + // --print lists what would go, a path a line, and removes nothing + if config.print_only { + for f in to_remove { + println(f) + } + for dir in builds.dirs { + println(dir) + } + for f in dbs { + println(f) + } + return + } + + mut summary := [kv('cache directory', cfg_cachedirs.join(', '))] + if pkg_files.len > 0 { + if every { + summary << kv('remove', 'all ${pkg_files.len} files (${profiler.format_bytes(total)})') + } else { + summary << kv('keep', 'all locally installed packages') + if config.keep_current { + summary << row('', 'the versions the sync dbs carry') + } + if config.keep > 0 { + summary << row('', 'the ${config.keep} newest versions of every package') + } + summary << kv('remove', if to_remove.len == 0 { + 'nothing' + } else { + '${to_remove.len} files (${profiler.format_bytes(total)})' + }) + } + } + if builds.found > 0 { + summary << kv('build directory', builds.root) + if config.all { + summary << kv('remove', 'all ${builds.found} builds (${size_text(builds.size, builds.partial)})') + } else { + summary << kv('keep', 'the builds of installed packages') + summary << kv('remove', if builds.dirs.len == 0 { + 'nothing' + } else { + '${builds.dirs.len} builds (${size_text(builds.size, builds.partial)}): ${builds.dirs.map(os.base(it)).join(', ')}' + }) + } + } + if dbs.len > 0 { + summary << kv('database directory', db_path + 'sync/') + summary << kv('remove', '${dbs.len} files of unused repos: ${dbs.map(os.base(it)).join(', ')}') + } + if !ipc_on() { + println(table_text(summary, '', ' ')) + } + if to_remove.len == 0 && builds.dirs.len == 0 && dbs.len == 0 { + println(if pkg_files.len == 0 && builds.found == 0 { + 'cache is empty' + } else { + 'nothing to remove' + }) + return + } + if !ui.proceed('proceed?') { + return + } + if to_remove.len > 0 { + cache_purge(mut ui, to_remove) + } + if dbs.len > 0 { + mut failed := []string{} + for f in dbs { + os.rm(f) or { failed << os.base(f) } + } + if failed.len > 0 { + warn('could not remove ${failed.len} of ${dbs.len} unused sync database files: ${failed.join(', ')}') + } + } + if builds.dirs.len > 0 { + // removed as the user who built them, the way the builds clear their + // own dirs: root never deletes inside the user's tree + mut s := ui.spinner(text: 'removing pkgbuild builds') + s.start() + defer { stop_spinner(mut s) } + mut args := ['rm', '-rf', '--'] + args << builds.dirs + run_as_user(builds.user, args)! + stop_spinner(mut s) + } +} diff --git a/src/clean_test.v b/src/clean_test.v new file mode 100644 index 0000000..208fd01 --- /dev/null +++ b/src/clean_test.v @@ -0,0 +1,193 @@ +module main + +import json2 +import os + +fn test_parse_cache_file() { + cases := { + 'zsh-5.9.2-1-x86_64.pkg.tar.zst': 'zsh 5.9.2-1' + '/var/cache/pacman/pkg/zsh-5.9.2-1-x86_64.pkg.tar.zst': 'zsh 5.9.2-1' + 'gcc-libs-14.2.1+r1-1-x86_64.pkg.tar.zst': 'gcc-libs 14.2.1+r1-1' + 'vim-2:9.1.0-1-x86_64.pkg.tar.zst': 'vim 2:9.1.0-1' + 'python-3.12.7-1-x86_64.pkg.tar.xz': 'python 3.12.7-1' + // dashes in the cache dir are not part of the name + '/tmp/a-dir-with-dashes/foo-1.0-1-any.pkg.tar.zst': 'foo 1.0-1' + } + for file, want in cases { + cf := parse_cache_file(file) or { + assert false, '${file} did not parse' + continue + } + assert '${cf.name} ${cf.version}' == want, file + assert cf.file == file + } + for bad in ['broken.pkg.tar.zst', 'a-1-x.pkg.tar.zst', '-1-1-any.pkg.tar.zst'] { + if cf := parse_cache_file(bad) { + assert false, '${bad} parsed as ${cf.name} ${cf.version}' + } + } +} + +fn test_installed_file() { + prefixes := ['zsh-5.9.2-1-', 'gcc-libs-14.2.1-1-'] + // the cache is listed as full paths: the file name is what counts + assert installed_file('/var/cache/pacman/pkg/zsh-5.9.2-1-x86_64.pkg.tar.zst', prefixes) + assert installed_file('zsh-5.9.2-1-x86_64.pkg.tar.zst', prefixes) + assert installed_file('/c/gcc-libs-14.2.1-1-x86_64.pkg.tar.zst', prefixes) + assert !installed_file('/var/cache/pacman/pkg/zsh-5.9.1-1-x86_64.pkg.tar.zst', prefixes) + assert !installed_file('/c/zsh-completions-0.35-1-any.pkg.tar.zst', prefixes) + // a dir that looks like the prefix does not make its files installed + assert !installed_file('/c/zsh-5.9.2-1-x/foo-1.0-1-any.pkg.tar.zst', prefixes) + assert !installed_file('/c/zsh-5.9.2-1-x86_64.pkg.tar.zst', []) + // an uncompressed archive is one too + assert installed_file('/c/zsh-5.9.2-1-x86_64.pkg.tar', prefixes) + assert is_pkg_archive('zsh-5.9.2-1-x86_64.pkg.tar') && is_pkg_archive('a-1-1-any.pkg.tar.zst') + assert !is_pkg_archive('a-1-1-any.pkg.tar.zst.sig') && !is_pkg_archive('core.db') + // a package whose name begins with another's name-version- is its own: + // zsh-5.9.2-1-extras 2-1 is not zsh 5.9.2-1 + assert !installed_file('/c/zsh-5.9.2-1-extras-2-1-any.pkg.tar.zst', prefixes) +} + +// an unreadable cache dir does not stop the cleaning of the ones that read: +// the files of the rest come through, spelled out whole +fn test_cached_pkg_files_skips_a_lost_cache_dir() ! { + tmp := os.join_path(os.vtmp_dir(), 'vpac_test_cache_${os.getpid()}') + real := os.join_path(tmp, 'pkg') + '/' + os.mkdir_all(real)! + defer { + os.rmdir_all(tmp) or {} + } + os.write_file(os.join_path(real, 'zsh-5.9.2-1-x86_64.pkg.tar.zst'), '.')! + os.write_file(os.join_path(real, 'zsh-5.9.2-1-x86_64.pkg.tar.zst.sig'), '.')! + + mut old := cfg_cachedirs.clone() + defer { cfg_cachedirs = old.clone() } + cfg_cachedirs = [real, '/nonexistent-vpac-test/'] + files := cached_pkg_files()! + assert files == ['${real}zsh-5.9.2-1-x86_64.pkg.tar.zst'], files.str() + // the spelled-out path is a real one + assert os.exists(files[0]) +} + +// kept_names is the set paccache_keep keeps, as sorted file names +fn kept_names(kept map[string]bool) []string { + mut names := map[string]bool{} + for f, on in kept { + if !on { + continue + } + names[os.base(f).all_before('.pkg.tar.')] = true + } + mut out := names.keys() + out.sort() + return out +} + +fn test_paccache_keep() { + files := [ + '/c/foo-1.9-1-any.pkg.tar.zst', + '/c/foo-1.10-1-any.pkg.tar.zst', + '/c/zsh-5.9.1-1-x86_64.pkg.tar.zst', + '/c/zsh-5.9.2-1-x86_64.pkg.tar.zst', + '/c/zsh-6.0-1-x86_64.pkg.tar.zst', + ] + installed := ['zsh-5.9.2-1-'] + // newest by pacman's vercmp: 1.10 is newer than 1.9. the installed + // version is always kept, and it counts among the newest + assert kept_names(paccache_keep(1, files, installed)) == ['foo-1.10-1-any', 'zsh-5.9.2-1-x86_64', + 'zsh-6.0-1-x86_64'] + assert kept_names(paccache_keep(2, files, installed)) == ['foo-1.10-1-any', 'foo-1.9-1-any', + 'zsh-5.9.2-1-x86_64', 'zsh-6.0-1-x86_64'] + assert kept_names(paccache_keep(3, files, installed)).len == 5 + assert kept_names(paccache_keep(1, files, [])) == ['foo-1.10-1-any', 'zsh-6.0-1-x86_64'] +} + +fn test_clean_event_build_root() ! { + saved := cfg_cachedirs.clone() + defer { cfg_cachedirs = saved.clone() } + cfg_cachedirs = ['/cache/'] + // no invoker known: the builds were not looked at, and the event says so + // by leaving the root out, rather than an empty one beside no builds + unknown := clean_event(['/cache/a.pkg.tar.zst'], 10, BuildClean{}, []string{}, false) + assert unknown.build_root == none + text := json2.encode(unknown) + assert !text.contains('build_root'), text + assert text.contains('"files":["/cache/a.pkg.tar.zst"]') + // an invoker known, with no build found: the root goes out, the list is + // empty, and that does mean none + looked := clean_event([], 0, BuildClean{ + user: 'someone' + root: '/home/someone/.cache/vpac/pkgbuild' + }, ['/db/sync/gone.db'], true) + assert looked.build_root? == '/home/someone/.cache/vpac/pkgbuild' + doc := json2.decode[json2.Any](json2.encode(looked))!.as_map() + assert doc['build_root']!.str() == '/home/someone/.cache/vpac/pkgbuild' + assert doc['builds']!.as_array().len == 0 + assert doc['dbs']!.as_array().map(it.str()) == ['/db/sync/gone.db'] + assert doc['preview']!.bool() + assert doc['type']!.str() == 'clean' +} + +fn test_tree_size_says_when_it_is_a_floor() ! { + tmp := os.join_path(os.vtmp_dir(), 'vpac_test_tree_size_${os.getpid()}') + deep := os.join_path(tmp, 'a', 'closed') + os.mkdir_all(deep)! + os.mkdir_all(os.join_path(tmp, 'b', 'empty'))! + defer { + os.chmod(deep, 0o755) or {} + os.rmdir_all(tmp) or {} + } + os.write_file(os.join_path(tmp, 'top'), 'x'.repeat(10))! + os.write_file(os.join_path(tmp, 'a', 'file'), 'x'.repeat(100))! + os.write_file(os.join_path(deep, 'hidden'), 'x'.repeat(1000))! + os.write_file(os.join_path(tmp, 'b', 'file'), 'x'.repeat(5))! + // a link is not followed, whatever it points at, and is no gap + os.symlink(os.join_path(tmp, 'a'), os.join_path(tmp, 'b', 'link'))! + os.symlink('/nonexistent-vpac-test', os.join_path(tmp, 'b', 'dangling'))! + // everything readable: the whole size, said to be whole + size, whole := tree_size(tmp) + assert size == 1115 && whole + // a plain file, an empty dir and a link are each whole + fsize, fwhole := tree_size(os.join_path(tmp, 'top')) + assert fsize == 10 && fwhole + esize, ewhole := tree_size(os.join_path(tmp, 'b', 'empty')) + assert esize == 0 && ewhole + lsize, lwhole := tree_size(os.join_path(tmp, 'b', 'link')) + assert lsize == 0 && lwhole + // what is not there is nothing, and not a gap in something + gsize, gwhole := tree_size(os.join_path(tmp, 'gone')) + assert gsize == 0 && gwhole + if os.geteuid() == 0 { + // root reads a closed directory all the same + return + } + // a directory that cannot be listed, two levels down: the rest is + // still counted, and the sum is said to be a floor all the way up + os.chmod(deep, 0o000)! + psize, pwhole := tree_size(tmp) + assert psize == 115 && !pwhole + asize, awhole := tree_size(os.join_path(tmp, 'a')) + assert asize == 100 && !awhole + // its sibling is not tainted by it + bsize, bwhole := tree_size(os.join_path(tmp, 'b')) + assert bsize == 5 && bwhole + // the closed directory itself is nothing, and not whole + csize, cwhole := tree_size(deep) + assert csize == 0 && !cwhole + // the builds' sum carries the mark, and a person is told 'at least' + saved := pkgbuild_dir + defer { pkgbuild_dir = saved } + pkgbuild_dir = tmp + bc := build_dirs_to_clean('nobody', true, [], [])! + assert bc.dirs.len == 2 && bc.size == 105 && bc.partial + assert size_text(bc.size, bc.partial) == 'at least 105B' || size_text(bc.size, bc.partial).starts_with('at least 105') + assert !size_text(105, false).starts_with('at least') + ev := json2.decode[json2.Any](json2.encode(clean_event([], 0, bc, [], false)))!.as_map() + assert ev['build_size_partial']!.bool() && ev['build_size']!.i64() == 105 + // a build tree that is all readable leaves the mark off, and present + os.chmod(deep, 0o755)! + ok := build_dirs_to_clean('nobody', true, [], [])! + assert ok.size == 1105 && !ok.partial + whole_ev := json2.decode[json2.Any](json2.encode(clean_event([], 0, ok, [], false)))!.as_map() + assert !whole_ev['build_size_partial']!.bool() +} diff --git a/src/cli.v b/src/cli.v new file mode 100644 index 0000000..d2bd16d --- /dev/null +++ b/src/cli.v @@ -0,0 +1,753 @@ +@[has_globals] +module main + +import flag +import os +import vmakepkg + +struct ConfigSearch { +pub mut: + show_help bool @[long: help; short: h] + noconfirm bool @[long: noconfirm] + local bool @[long: local; short: l] + remote bool @[long: remote; short: r] + pkgbuild bool @[long: pkgbuild; short: b] + quiet bool @[long: quiet; short: q] + fuzzy bool @[long: fuzzy; short: f] + thold f64 = 0.9 @[long: thold; short: t] + sync_dbs bool @[long: sync; short: s] + deps bool @[long: deps; short: d] + explicit bool @[long: explicit; short: e] + foreign bool @[long: foreign; short: m] + native bool @[long: native; short: n] + unrequired bool @[long: unrequired] + // --unrequired given twice is pacman's -tt; the flag parser counts short + // flags only, so parse_mode counts the long one itself + unrequired_level int @[ignore] + upgrades bool @[long: upgrades; short: u] + groups bool @[long: groups] + groups_level int @[only: g; repeats] + installed bool @[long: installed; short: i] + fields string @[long: fields; short: F] + query []string @[tail] +} + +struct ConfigInstall { +pub mut: + show_help bool @[long: help; short: h] + noconfirm bool @[long: noconfirm] + no_upgrade_deps bool @[long: no_upgrade_deps] + pkgbuild bool @[long: pkgbuild; short: b] + no_pkgbuild_confirm bool @[long: nopkgbuildconfirm] + download_only bool @[long: download_only; short: w] + print_only bool @[long: print; short: p] + needed bool @[long: needed] + asdeps bool @[long: asdeps] + asexplicit bool @[long: asexplicit] + dbonly bool @[long: dbonly] + nodeps bool @[long: nodeps] + nodeps_level int @[only: d; repeats] + overwrite []string @[long: overwrite] + ignore []string @[long: ignore] + ignoregroup []string @[long: ignoregroup] + assume_installed []string @[long: assume_installed] + disable_timeout bool @[long: disable_timeout] + query []string @[tail] +} + +// trans_options are the transaction options a command line carries: +// install's and upgrade's are the same four flags, read through one body +fn trans_options[T](c T) TransOptions { + return TransOptions{ + overwrite: c.overwrite + ignore: c.ignore + ignoregroup: c.ignoregroup + assume_installed: c.assume_installed + } +} + +struct ConfigInfo { +pub mut: + show_help bool @[long: help; short: h] + noconfirm bool @[long: noconfirm] + fields string @[long: fields; short: F] + changelog bool @[long: changelog; short: c] + file bool @[long: file; short: p] + query []string @[tail] +} + +struct ConfigWhich { +pub mut: + show_help bool @[long: help; short: h] + query []string @[tail] +} + +struct ConfigRank { +pub mut: + show_help bool @[long: help; short: h] + stdin bool @[long: stdin] + top int = 10 @[long: top; short: n] + mirrorlist bool @[long: mirrorlist; short: m] + output string @[long: output; short: o] + path string @[long: path] + write bool @[long: write; short: w] + query []string @[tail] +} + +struct ConfigVerify { +pub mut: + show_help bool @[long: help; short: h] + checksums bool @[long: checksums] + checksums_level int @[only: k; repeats] + full bool @[long: full] + db bool @[long: db] + db_level int @[only: D; repeats] + query []string @[tail] +} + +struct ConfigFind { +pub mut: + show_help bool @[long: help; short: h] + noconfirm bool @[long: noconfirm] + refresh bool @[long: refresh; short: y] + list bool @[long: list; short: l] + quiet bool @[long: quiet; short: q] + regex bool @[long: regex; short: x] + machinereadable bool @[long: machinereadable] + repos string @[long: repos; short: r] + query []string @[tail] +} + +struct ConfigMark { +pub mut: + show_help bool @[long: help; short: h] + noconfirm bool @[long: noconfirm] + reason string @[long: reason; short: r] + query []string @[tail] +} + +struct ConfigRemove { +pub mut: + show_help bool @[long: help; short: h] + noconfirm bool @[long: noconfirm] + print_only bool @[long: print; short: p] + recursive bool @[long: recursive] + recursive_level int @[only: s; repeats] + unneeded bool @[long: unneeded; short: u] + cascade bool @[long: cascade; short: c] + nosave bool @[long: nosave; short: n] + dbonly bool @[long: dbonly] + nodeps bool @[long: nodeps] + nodeps_level int @[only: d; repeats] + assume_installed []string @[long: assume_installed] + query []string @[tail] +} + +struct ConfigUpgrade { +pub mut: + show_help bool @[long: help; short: h] + noconfirm bool @[long: noconfirm] + print_only bool @[long: print; short: p] + sync_dbs bool @[long: sync; short: s] + download_only bool @[long: download_only; short: w] + dbonly bool @[long: dbonly] + nodeps bool @[long: nodeps] + nodeps_level int @[only: d; repeats] + downgrade bool @[long: downgrade] + sysupgrade_level int @[only: u; repeats] + overwrite []string @[long: overwrite] + ignore []string @[long: ignore] + ignoregroup []string @[long: ignoregroup] + disable_timeout bool @[long: disable_timeout] + assume_installed []string @[long: assume_installed] +} + +struct ConfigFiles { +pub mut: + show_help bool @[long: help; short: h] + noconfirm bool @[long: noconfirm] + query []string @[tail] +} + +struct ConfigOwner { +pub mut: + show_help bool @[long: help; short: h] + quiet bool @[long: quiet; short: q] + query []string @[tail] +} + +struct ConfigOrphans { +pub mut: + show_help bool @[long: help; short: h] + // pacman's -Qdt and -Qdtt: twice lists the dependencies something still + // names as optional too + level int @[only: t; repeats] +} + +struct ConfigClean { +pub mut: + show_help bool @[long: help; short: h] + noconfirm bool @[long: noconfirm] + print_only bool @[long: print; short: p] + all bool @[long: all; short: a] + keep int @[long: keep; short: k] + keep_current bool @[long: keep_current] + // pacman's -Sc and -Scc: once is the default clean, twice every archive + level int @[only: c; repeats] +} + +struct ConfigTree { +pub mut: + show_help bool @[long: help; short: h] + noconfirm bool @[long: noconfirm] + reverse bool @[long: reverse; short: r] + optional bool @[long: optional; short: o] + depth int @[long: depth; short: d] + query []string @[tail] +} + +struct ConfigAutoRemove { +pub mut: + show_help bool @[long: help; short: h] + noconfirm bool @[long: noconfirm] +} + +@[noreturn] +fn print_err(e string) { + if ipc_on() { + // an error before the run started ends it all the same: the channel + // opens for it (once: ipc_start is guarded), so every stream starts + // with its hello and ends with its exit + ipc_start() + emit(ErrorEvent{ + msg: e + }) + } else { + eprintln(error_text(e)) + } + end_run(1) +} + +// error_text is an error line the way vpac prints them, 'error: ' in bold red +fn error_text(e string) string { + return erole('error', 'error: ') + e +} + +// failed_targets counts the targets a query reported bad and skipped. like +// pacman's queries, it goes on with the rest, and main exits 1 at the end +// when any failed +__global failed_targets = 0 + +// target_error reports one bad target of a query that goes on with the next +fn target_error(e string) { + failed_targets++ + if ipc_on() { + emit(ErrorEvent{ + msg: e + target: true + }) + return + } + os.flush() + eprintln(error_text(e)) +} + +// need_query stops a command that acts on targets when none were given +fn need_query(query []string, what string) ! { + if query.len == 0 { + return error('no ${what} given') + } +} + +// scan_globals collects vpac's own flags, wherever they stand in the command +// line: --config chooses the config file, --eval extends the config with blip +// code run after it. both repeatable, both also usable as --flag=value. the +// flags are stripped from the args (the program name stays first, the mode +// second), so a mode never sees them; escalation still gets the original +// args, so the root process reads the same config and evals +fn scan_globals(args []string) !(string, []string, []string) { + // the frontend is settled before any other flag can fail: an error is + // told over the channel whenever --ui ipc is on the command line, not + // only when it happens to come before the flag that is wrong + if kind := scan_ui(args) { + ui_kind = kind + } + mut chosen := '' + mut evals := []string{} + mut rest := [args[0]] + mut i := 1 + for i < args.len { + arg := args[i] + if arg == '--config' || arg == '--eval' { + if i + 1 >= args.len { + return error('${arg} needs a value') + } + value := args[i + 1] + if value == '' { + return error('${arg} needs a value') + } + if arg == '--config' { + chosen = value + } else { + evals << value + } + i += 2 + } else if arg.starts_with('--config=') { + chosen = arg.all_after('=') + if chosen == '' { + return error('--config needs a file') + } + i++ + } else if arg.starts_with('--eval=') { + expr := arg.all_after('=') + if expr == '' { + return error('--eval needs blip code') + } + evals << expr + i++ + } else if arg == '--color' || arg.starts_with('--color=') { + // pacman's --color: auto (the default) styles a terminal only + mut value := arg.all_after('=') + if arg == '--color' { + if i + 1 >= args.len { + return error('--color needs a value: auto, always or never') + } + i++ + value = args[i] + } + if value !in ['auto', 'always', 'never'] { + return error('--color takes auto, always or never, not "${value}"') + } + color_flag = value + color_given = true + i++ + } else if arg == '--verbose' { + // the verbose log: the housekeeping failures a run goes on from + verbose_flag = true + i++ + } else if arg == '--ui' || arg.starts_with('--ui=') { + // the frontend: tty, a person at a terminal, or ipc, a program + // speaking json lines (ipc.v) + mut value := arg.all_after('=') + if arg == '--ui' { + if i + 1 >= args.len { + return error('--ui needs a value: tty or ipc') + } + i++ + value = args[i] + } + if value !in ['tty', 'ipc'] { + return error('--ui takes tty or ipc, not "${value}"') + } + ui_kind = value + i++ + } else { + rest << arg + i++ + } + } + return chosen, evals, rest +} + +// global_value_flags are vpac's own flags that take the next argument as +// their value when spelled without '=' +const global_value_flags = ['--config', '--eval', '--color', '--ui'] + +// scan_ui finds the --ui the command line settles on — the last valid one, +// as scan_globals lets the last win — stepping over the values of the other +// globals the way scan_globals reads them, so an --eval whose code is the +// text '--ui' is not taken for the flag. none when there is no valid one: +// a bad value is scan_globals' error to give, on the terminal +fn scan_ui(args []string) ?string { + mut found := ?string(none) + mut i := 1 + for i < args.len { + arg := args[i] + if arg.starts_with('--ui=') { + value := arg.all_after('=') + if value in ['tty', 'ipc'] { + found = value + } + } else if arg == '--ui' && i + 1 < args.len && args[i + 1] in ['tty', 'ipc'] { + found = args[i + 1] + } + i += if arg in global_value_flags { 2 } else { 1 } + } + return found +} + +// ModeConfig is a mode's command line, parsed: which mode, with its flags +type ModeConfig = ConfigAutoRemove + | ConfigBuild + | ConfigClean + | ConfigDeptest + | ConfigFiles + | ConfigFind + | ConfigInfo + | ConfigInstall + | ConfigMark + | ConfigOrphans + | ConfigOwner + | ConfigRank + | ConfigRemove + | ConfigSearch + | ConfigTree + | ConfigUpgrade + | ConfigVerify + | ConfigWhich + +// mode_flags reads a mode's flags into its struct, then lays the config's +// options under them: a flag the config turns on (options :noconfirm true) +// is on for every mode that has it, as if it stood on the command line. +// the command line can only add to that; --eval turns one off for a run. +// an option the mode's struct has no field for is an error +fn mode_flags[T](args []string) !T { + mut c, unknown := flag.to_struct[T](args, skip: 2)! + // what the parser could not place is an option the mode does not have: + // said, as pacman says it, instead of a run that quietly leaves a + // mistyped flag out of a transaction + bad := unknown.filter(it.len > 1 && it.starts_with('-')) + if bad.len > 0 { + return error('unknown option: ${bad.map('"${it}"').join(', ')}') + } + // the rest of it are targets that stand before a flag: the parser's + // tail takes only the ones after the last flag, and these lead them + early := unknown.filter(!(it.len > 1 && it.starts_with('-'))) + if early.len > 0 { + mut placed := false + $for field in T.fields { + $if field.name == 'query' { + mut query := early.clone() + query << c.query + c.query = query + placed = true + } + } + if !placed { + return error('this mode takes no targets: ${early.map('"${it}"').join(', ')}') + } + } + $for field in T.fields { + $if field.typ is bool { + if opt_flags[field.name] { + c.$(field.name) = true + } + } + } + return c +} + +// flag_given is whether the command line spells a flag, by its long name or +// its short letter: what settles that a config default steps back. a letter +// is looked for in any bundle of short flags, so a doubt reads as given and +// leaves the mode's own default +fn flag_given(args []string, long string, short string) bool { + for a in args#[2..] { + if a == '--${long}' || a.starts_with('--${long}=') { + return true + } + if a.len > 1 && a[0] == `-` && a[1] != `-` && a.contains(short) { + return true + } + } + return false +} + +// parse_mode reads the mode and its flags. it runs before any escalation, so +// a flag that does not parse is an error the user sees before a root prompt +fn parse_mode(args []string) !ModeConfig { + return match args[1] { + 's', 'S', 'search' { + // a long flag given twice is the flag parser's error, so the + // repeats of --unrequired are counted and folded into one here + level := args.count(it == '--unrequired') + mut once := []string{cap: args.len} + for i, arg in args { + if arg == '--unrequired' && args[..i].contains(arg) { + continue + } + once << arg + } + mut c := mode_flags[ConfigSearch](once)! + if !flag_given(once, 'thold', 't') { + c.thold = cfg_search_thold + } else if c.thold < 0.0 || c.thold > 1.0 { + // the config's (search :thold) is held to the same range + return error('--thold must be between 0 and 1, not ${c.thold}') + } + c.unrequired_level = level + c.groups = c.groups || c.groups_level > 0 + if !c.local && !c.remote && !c.pkgbuild { + // the filters only work on the installed packages; the + // groups are the sync dbs' unless -l asks for the local ones + c.local = c.filtered() && !c.groups + c.remote = !c.filtered() || c.groups + } + ModeConfig(c) + } + 'q', 'Q', 'info' { + c := mode_flags[ConfigInfo](args)! + ModeConfig(c) + } + 'w', 'W', 'which' { + c := mode_flags[ConfigWhich](args)! + ModeConfig(c) + } + 'n', 'N', 'deptest' { + c := mode_flags[ConfigDeptest](args)! + ModeConfig(c) + } + 'm', 'M', 'mark' { + c := mode_flags[ConfigMark](args)! + ModeConfig(c) + } + 'b', 'B', 'build' { + c := mode_flags[ConfigBuild](args)! + ModeConfig(c) + } + 'i', 'I', 'install' { + c := mode_flags[ConfigInstall](args)! + ModeConfig(c) + } + 'r', 'R', 'remove' { + c := mode_flags[ConfigRemove](args)! + ModeConfig(c) + } + 'u', 'U', 'upgrade' { + c := mode_flags[ConfigUpgrade](args)! + ModeConfig(c) + } + 'l', 'L', 'files' { + c := mode_flags[ConfigFiles](args)! + ModeConfig(c) + } + 'o', 'O', 'owner' { + c := mode_flags[ConfigOwner](args)! + ModeConfig(c) + } + 'd', 'D', 'orphans' { + c := mode_flags[ConfigOrphans](args)! + ModeConfig(c) + } + 'c', 'C', 'clean' { + mut c := mode_flags[ConfigClean](args)! + if !flag_given(args, 'keep', 'k') { + c.keep = cfg_clean_keep + } + ModeConfig(c) + } + 't', 'T', 'tree' { + mut c := mode_flags[ConfigTree](args)! + if !flag_given(args, 'depth', 'd') { + c.depth = cfg_tree_depth + } + ModeConfig(c) + } + 'a', 'A', 'autoremove' { + c := mode_flags[ConfigAutoRemove](args)! + ModeConfig(c) + } + 'k', 'K', 'rank' { + mut c := mode_flags[ConfigRank](args)! + if !flag_given(args, 'top', 'n') { + c.top = rank_top + } else if c.top < 1 { + // the config's (rank :top) is held to the same floor + return error('--top must be at least 1, not ${c.top}') + } + ModeConfig(c) + } + 'v', 'V', 'verify' { + c := mode_flags[ConfigVerify](args)! + ModeConfig(c) + } + 'f', 'F', 'find' { + c := mode_flags[ConfigFind](args)! + ModeConfig(c) + } + else { + error('unknown subcommand: "${args[1]}"') + } + } +} + +// needs_root is whether a mode runs as root: the ones that change the +// system, except a --print preview, which changes nothing and stays the +// user's as pacman's --print does; find -y, which writes the file dbs; and +// rank when the file it writes is not the user's to write. rank -w writes +// the config's mirror file under /etc, so that is known before any ranking +fn needs_root(c ModeConfig) !bool { + return match c { + ConfigInstall { !c.print_only } + ConfigRemove { !c.print_only } + ConfigUpgrade { !c.print_only } + ConfigClean { !c.print_only } + ConfigBuild, ConfigMark, ConfigAutoRemove { true } + ConfigFind { c.refresh } + ConfigRank { + mut target := c.output + if target == '' && c.write { + target = rank_write_target(rank_os_name(c.query)!) + } + target != '' && !can_write(target) + } + else { false } + } +} + +// run_mode runs a parsed mode and returns its exit status: 0, or what the +// mode's outcome asks for +fn run_mode(c ModeConfig) !int { + match c { + ConfigSearch { + search(c)! + } + ConfigInfo { + info(c)! + } + ConfigWhich { + which(c)! + } + ConfigDeptest { + // pacman's -T: 127 tells makepkg a dependency is missing + if deptest(c)!.len > 0 { + return 127 + } + } + ConfigMark { + mark(c)! + } + ConfigBuild { + build_repo(c)! + } + ConfigInstall { + install(c)! + } + ConfigRemove { + remove(c)! + } + ConfigUpgrade { + upgrade(c)! + } + ConfigFiles { + files(c)! + } + ConfigOwner { + owner(c)! + } + ConfigOrphans { + orphans(c)! + } + ConfigClean { + clean(c)! + } + ConfigTree { + tree(c)! + } + ConfigAutoRemove { + autoremove(c)! + } + ConfigRank { + rank(c)! + } + ConfigVerify { + if verify(c)! > 0 { + return 1 + } + } + ConfigFind { + find(c)! + } + } + return 0 +} + +fn main() { + // --lip-run [args...] is what a PKGBUILD generated from a + // PKGBUILD.lip calls back (vpac b): it runs one phase of the lip. it is no + // mode, reads no config and never needs root + if os.args.len > 3 && os.args[1] == '--lip-run' { + vmakepkg.lip_run_phase(os.args[2], os.args[3], os.args[4..]) or { + eprintln(error_text('lip: ${err.msg()}')) + exit(1) + } + exit(0) + } + chosen, evals, args := scan_globals(os.args) or { print_err(err.msg()) } + // the config comes first: it is required, and everything downstream reads + // it, including the escalation to root + load_config(chosen, evals) or { print_err(err.msg()) } + // the config's color is the default a --color on the command line beats + if !color_given && opt_color != '' { + color_flag = opt_color + } + // a killed run lets go of the db lock it holds (on_interrupt) + install_interrupt_handlers() + // no mode, or help: the overview. an option where the mode belongs is + // one no global scan took, and an error as pacman's unknown options are + if args.len < 2 || args[1] in ['h', 'help', '-h', '--help'] { + if ipc_on() { + ipc_start() + } + show_help(help_text()) + end_run(0) + } + if args[1].starts_with('-') { + print_err('unknown option "${args[1]}" before the mode (vpac --help lists the modes)') + } + // the mode is parsed before anything else happens: a bad flag is an error + // here, not a panic in a root process. 'vpac -h' prints that + // mode's options and never runs the command; the flag parser reads the + // -h, so one bundled with others (-lh) counts and one that is another + // flag's value does not. a help request beside flags that do not parse + // is still answered with the help + config := parse_mode(args) or { + if args[2..].any(it == '-h' || it == '--help') { + mode_help(args[1]) + } + print_err(err.msg()) + } + if config.show_help { + mode_help(args[1]) + } + // a mode that changes the system runs as root, through the root + // provider; the original command line is passed, globals included, so + // the root process reads the same config and evals + root := needs_root(config) or { print_err(err.msg()) } + if root { + reexec_as_root(os.args[1..]) or { print_err(err.msg()) } + } + // this is the process that does the work: a frontend's channel opens here + if ipc_on() { + ipc_start() + } + mut status := run_mode(config) or { print_err(err.msg()) } + // a query that skipped bad targets still fails, after showing the rest + if failed_targets > 0 && status == 0 { + status = 1 + } + end_run(status) +} + +// mode_help prints one mode's options and ends the run +@[noreturn] +fn mode_help(name string) { + if ipc_on() { + ipc_start() + } + mode := find_mode(name) or { print_err('unknown subcommand: "${name}"') } + show_help(mode_help_text(mode)) + end_run(0) +} + +// end_run is the one exit of a run, an error's included: the status, told +// to a frontend first as the exit event that closes every stream +@[noreturn] +fn end_run(status int) { + if ipc_on() { + emit(ExitEvent{ + status: status + }) + } + exit(status) +} diff --git a/src/cli_test.v b/src/cli_test.v new file mode 100644 index 0000000..a477bce --- /dev/null +++ b/src/cli_test.v @@ -0,0 +1,324 @@ +module main + +import alpm +import os + +// --eval takes its blip from the next argument or from =; an empty one is +// refused like an empty --config or --color value is +fn test_scan_globals_eval() ! { + mut chosen := '' + mut evals := []string{} + mut rest := []string{} + chosen, evals, rest = scan_globals(['vpac', '--eval', '(define x 1)', 's', 'zsh'])! + assert chosen == '' + assert evals == ['(define x 1)'] + assert rest == ['vpac', 's', 'zsh'] + + chosen, evals, rest = scan_globals(['vpac', '--eval=(define x 2)', '--config=other.lip', 's'])! + assert chosen == 'other.lip' + assert evals == ['(define x 2)'] + assert rest == ['vpac', 's'] + + for arg in ['--eval=', '--eval', '--config=', '--config'] { + if _, _, _ := scan_globals(['vpac', arg]) { + assert false, '"${arg}" was taken without its value' + } else { + assert err.msg().contains('needs'), '"${arg}": ${err.msg()}' + } + } +} + +// the global flags parse wherever they stand, and none of them bleeds into +// the rest the mode sees +fn test_scan_globals_mixed() ! { + saved_kind, saved_color := ui_kind, color_flag + defer { + ui_kind, color_flag = saved_kind, saved_color + } + _, _, rest := scan_globals(['vpac', 'i', '--color=never', 'zsh', '--ui', 'ipc'])! + assert rest == ['vpac', 'i', 'zsh'] +} + +fn test_scan_ui() { + for args, want in { + 'vpac s --ui ipc': 'ipc' + 'vpac --ui=ipc s': 'ipc' + 'vpac --ui tty s': 'tty' + // the last valid one wins, as in scan_globals + 'vpac --ui tty s --ui ipc': 'ipc' + 'vpac --ui=ipc --ui=tty': 'tty' + // another global's value is stepped over, not read as a flag + 'vpac --eval --ui ipc': '' + 'vpac --config --ui --ui ipc': 'ipc' + // no valid one: none, and scan_globals says why on the terminal + 'vpac s zsh': '' + 'vpac --ui bogus s': '' + 'vpac --ui': '' + 'vpac --ui=': '' + } { + got := scan_ui(args.split(' ')) or { '' } + assert got == want, args + } +} + +// an error in any global is told the frontend's way when --ui ipc is on the +// command line, wherever it stands: the ui is settled before the error +fn test_scan_globals_settles_the_ui_before_failing() { + saved_kind := ui_kind + defer { ui_kind = saved_kind } + for args in ['vpac --color sometimes --ui ipc s', 'vpac --color sometimes s --ui=ipc', + 'vpac --ui ipc --color sometimes s'] { + ui_kind = 'tty' + if _, _, _ := scan_globals(args.split(' ')) { + assert false, '${args} was accepted' + } + assert ui_kind == 'ipc', args + } + // a bad --ui itself names no frontend: the terminal tells it + ui_kind = 'tty' + if _, _, _ := scan_globals('vpac --color sometimes --ui bogus s'.split(' ')) { + assert false + } + assert ui_kind == 'tty' +} + +// the doubled flags are counts, as pacman reads -ss, -cc, -gg, -tt and -uu +fn test_doubled_flags_count() ! { + r := parse_mode(['vpac', 'r', '-ss', '-u', 'foo'])! as ConfigRemove + assert r.recursive_level == 2 && r.unneeded && r.query == ['foo'] + assert recurse_flags(r.recursive, r.recursive_level) == alpm.TransFlag.recurse | .recurse_all + one := parse_mode(['vpac', 'r', '--recursive', 'foo'])! as ConfigRemove + assert recurse_flags(one.recursive, one.recursive_level) == alpm.TransFlag.recurse + + c := parse_mode(['vpac', 'c', '-cc'])! as ConfigClean + assert c.level == 2 && !c.keep_current + kc := parse_mode(['vpac', 'c', '--keep-current'])! as ConfigClean + assert kc.keep_current && kc.level == 0 + + u := parse_mode(['vpac', 'u', '-uu'])! as ConfigUpgrade + assert u.sysupgrade_level == 2 + d := parse_mode(['vpac', 'd', '-tt'])! as ConfigOrphans + assert d.level == 2 +} + +fn test_search_group_and_unrequired_counts() ! { + g := parse_mode(['vpac', 's', '-gg'])! as ConfigSearch + assert g.groups && g.groups_level == 2 + // groups are the sync dbs' unless -l asks for the installed ones + assert g.remote && !g.local + lg := parse_mode(['vpac', 's', '-l', '-g', 'base'])! as ConfigSearch + assert lg.groups && lg.local && !lg.remote && lg.query == ['base'] + long := parse_mode(['vpac', 's', '--groups'])! as ConfigSearch + assert long.groups + + t := parse_mode(['vpac', 's', '--unrequired'])! as ConfigSearch + assert t.unrequired && t.unrequired_level == 1 && t.local + tt := parse_mode(['vpac', 's', '--unrequired', '-d', '--unrequired'])! as ConfigSearch + assert tt.unrequired && tt.unrequired_level == 2 && tt.deps +} + +fn test_new_query_flags_parse() ! { + q := parse_mode(['vpac', 'q', '-c', '-p', 'a.pkg.tar', 'b.pkg.tar'])! as ConfigInfo + assert q.changelog && q.file && q.query == ['a.pkg.tar', 'b.pkg.tar'] + o := parse_mode(['vpac', 'o', '-q', '/usr/bin/ls'])! as ConfigOwner + assert o.quiet + f := parse_mode(['vpac', 'f', '-x', '--machinereadable', 'ls$'])! as ConfigFind + assert f.regex && f.machinereadable && f.query == ['ls$'] +} + +fn test_ranged_flags_are_checked() ! { + // the flags are held to the ranges the config's forms are + for bad in [['vpac', 's', '--thold', '2', 'x'], ['vpac', 's', '-t', '1.5', 'x'], + ['vpac', 's', '--thold', '-1', 'x'], ['vpac', 'k', '--top', '0'], ['vpac', 'k', '--top', + '-2']] { + if _ := parse_mode(bad) { + assert false, 'parsed ${bad}' + } + } + s := parse_mode(['vpac', 's', '--thold', '0.5', 'x'])! as ConfigSearch + assert s.thold == 0.5 + k := parse_mode(['vpac', 'k', '--top', '3'])! as ConfigRank + assert k.top == 3 +} + +fn test_help_flag_is_the_parsers() ! { + // bundled with other flags it still asks for help; as another flag's + // value it does not + s := parse_mode(['vpac', 's', '-lh'])! as ConfigSearch + assert s.show_help && s.local + q := parse_mode(['vpac', 'q', '--fields', '-h', 'x'])! as ConfigInfo + assert !q.show_help && q.fields == '-h' +} + +fn test_parse_target() { + assert parse_target('bash') == Target{ + name: 'bash' + } + assert parse_target('core/bash') == Target{'core', 'bash'} + assert parse_target('local/bash>=5') == Target{'local', 'bash>=5'} + // a leading slash is no db prefix + assert parse_target('/bash').repo == '' + assert local_target_name('local/bash') == 'bash' + assert local_target_name('core/bash') == 'core/bash' + assert has_constraint('bash>=5') && has_constraint('sh=1') && !has_constraint('bash') +} + +fn test_flags_nothing_read_are_gone() ! { + // install's -u, -s and -v and search's -v parsed into fields no code + // read: a flag that does nothing is refused instead of taken + for dead in [['vpac', 'i', '-u', 'x'], ['vpac', 'i', '--upgrade-deps', 'x'], + ['vpac', 'i', '-s', 'x'], ['vpac', 'i', '--sync', 'x'], ['vpac', 'i', '-v', 'x'], + ['vpac', 's', '-v', 'x']] { + if _ := parse_mode(dead) { + assert false, 'parsed ${dead}' + } + } + // the ones that do something still parse, bundled too + w := parse_mode(['vpac', 'i', '-w', 'x'])! as ConfigInstall + assert w.download_only && w.query == ['x'] + wp := parse_mode(['vpac', 'i', '-wp', '--no-upgrade-deps', 'x'])! as ConfigInstall + assert wp.download_only && wp.print_only && wp.no_upgrade_deps + s := parse_mode(['vpac', 's', '-s', 'x'])! as ConfigSearch + assert s.sync_dbs +} + +fn test_unknown_mode_flags_are_errors() ! { + // a flag the mode has no field for is named, not dropped: long, short, + // bundled with known ones, before or after the targets, and a mistyped + // spelling of a real one + for bad in [['vpac', 'q', '--bogus', 'bash'], ['vpac', 'q', '-Z', 'bash'], + ['vpac', 'q', 'bash', '--bogus'], ['vpac', 'i', '--noconfrim', 'x'], + ['vpac', 'i', '--asdep', 'x'], ['vpac', 'r', '--print', '--bogus', 'x'], + ['vpac', 's', '-t', '-1', 'x']] { + if c := parse_mode(bad) { + assert false, 'parsed ${bad} as ${c}' + } else { + assert err.msg().contains('unknown option') || err.msg().contains('--thold'), err.msg() + } + } + named := parse_mode(['vpac', 'q', '--bogus', '-Z', 'bash']) or { + assert err.msg() == 'unknown option: "--bogus", "-Z"', err.msg() + ModeConfig(ConfigInfo{}) + } + assert (named as ConfigInfo).query.len == 0 + // what is known still parses in every position, and a mode with no + // flags given at all is not an error + q := parse_mode(['vpac', 'q', 'bash', '-c', 'zsh'])! as ConfigInfo + assert q.changelog && q.query == ['bash', 'zsh'] + bare := parse_mode(['vpac', 'd'])! as ConfigOrphans + assert bare.level == 0 + // targets that stand before a flag are targets all the same, in the + // order given, with the ones after it + mixed := parse_mode(['vpac', 'i', 'a', '--needed', 'b', '-w', 'c', 'd'])! as ConfigInstall + assert mixed.query == ['a', 'b', 'c', 'd'] && mixed.needed && mixed.download_only + lead := parse_mode(['vpac', 'r', 'a', 'b', '--print'])! as ConfigRemove + assert lead.query == ['a', 'b'] && lead.print_only + // a lone dash names neither a flag nor a target: the parser's error + if d := parse_mode(['vpac', 'q', '-', '-c']) { + assert false, 'a lone dash parsed: ${d}' + } + // a mode with no targets says so of one given before a flag + if o := parse_mode(['vpac', 'd', 'stray', '-t']) { + assert false, 'orphans took a target: ${o}' + } else { + assert err.msg().contains('takes no targets'), err.msg() + } +} + +fn test_needs_root_by_mode() ! { + root := fn (args []string) !bool { + return needs_root(parse_mode(args)!)! + } + // what changes the system runs as root + for args in [['vpac', 'i', 'x'], ['vpac', 'r', 'x'], ['vpac', 'u'], ['vpac', 'c'], + ['vpac', 'm', '-r', 'd', 'x'], ['vpac', 'a'], ['vpac', 'b', '/x'], ['vpac', 'f', '-y', + '/x'], ['vpac', 'i', '-w', 'x'], ['vpac', 'u', '-w'], ['vpac', 'i', '--dbonly', 'x']] { + assert root(args)!, '${args} runs as the user' + } + // a --print preview changes nothing and stays the user's, whatever + // else is asked beside it + for args in [['vpac', 'i', '-p', 'x'], ['vpac', 'r', '--print', 'x'], ['vpac', 'u', '-p'], + ['vpac', 'c', '-p'], ['vpac', 'i', '-p', '--dbonly', '--noconfirm', 'x'], + ['vpac', 'c', '-p', '-a']] { + assert !root(args)!, '${args} asks for root' + } + // what only reads never asks for root + for args in [['vpac', 's', 'x'], ['vpac', 'q', 'x'], ['vpac', 'w', 'x'], ['vpac', 'n', 'x'], + ['vpac', 'l', 'x'], ['vpac', 'o', '/x'], ['vpac', 'd'], ['vpac', 't', 'x'], ['vpac', 'v'], + ['vpac', 'f', '/x'], ['vpac', 'f', '-l', 'x'], ['vpac', 'k', 'arch']] { + assert !root(args)!, '${args} asks for root' + } +} + +fn test_needs_root_for_rank_follows_the_file() ! { + if os.geteuid() == 0 { + // root may write anywhere: there is no 'not the user's' to tell + return + } + tmp := os.join_path(os.vtmp_dir(), 'vpac_test_needs_root_${os.getpid()}') + os.mkdir_all(os.join_path(tmp, 'ro'))! + saved_dir := rank_dir + defer { + rank_dir = saved_dir + os.chmod(os.join_path(tmp, 'ro'), 0o755) or {} + os.rmdir_all(tmp) or {} + } + os.chmod(os.join_path(tmp, 'ro'), 0o555)! + os_name := rank_oses.keys()[0] + // printing a ranking writes nothing + assert !needs_root(ConfigRank{ query: [os_name] })! + // -o: a file the user may write, or may create, is the user's + assert !needs_root(ConfigRank{ output: os.join_path(tmp, 'new.lip'), query: [os_name] })! + os.write_file(os.join_path(tmp, 'there.lip'), '')! + assert !needs_root(ConfigRank{ output: os.join_path(tmp, 'there.lip'), query: [os_name] })! + // one it may not is root's: an existing read-only file, a new file in + // a read-only dir, and a path under a dir that is not there + os.chmod(os.join_path(tmp, 'there.lip'), 0o444)! + assert needs_root(ConfigRank{ output: os.join_path(tmp, 'there.lip'), query: [os_name] })! + assert needs_root(ConfigRank{ output: os.join_path(tmp, 'ro', 'new.lip'), query: [os_name] })! + assert needs_root(ConfigRank{ output: os.join_path(tmp, 'gone', 'new.lip'), query: [os_name] })! + // -w writes the config's mirror file: the rank dir decides, and -o, + // when both are given, is the file that is written + rank_dir = tmp + assert !needs_root(ConfigRank{ write: true, query: [os_name] })! + rank_dir = os.join_path(tmp, 'ro') + assert needs_root(ConfigRank{ write: true, query: [os_name] })! + assert !needs_root(ConfigRank{ + write: true + output: os.join_path(tmp, 'new.lip') + query: [os_name] + })! + // an os the ranker does not know is an error before any escalation + if _ := needs_root(ConfigRank{ write: true, query: ['no-such-os'] }) { + assert false, 'an unknown os was ranked' + } +} + +fn test_verbose_is_a_global_flag() ! { + saved := verbose_flag + defer { verbose_flag = saved } + // wherever it stands, it is taken off the mode's arguments and turns + // the verbose log on; without it the log stays off + for args in [['vpac', '--verbose', 'i', 'x'], ['vpac', 'i', '--verbose', 'x'], + ['vpac', 'i', 'x', '--verbose'], ['vpac', '--verbose', '--verbose', 'i', 'x']] { + verbose_flag = false + _, _, rest := scan_globals(args)! + assert rest == ['vpac', 'i', 'x'], '${args}' + assert verbose_flag, '${args}' + } + verbose_flag = false + _, _, plain := scan_globals(['vpac', 'i', 'x'])! + assert plain == ['vpac', 'i', 'x'] && !verbose_flag + // as the value of another global it is that flag's value, not the flag + _, evals, rest := scan_globals(['vpac', '--eval', '--verbose', 's'])! + assert evals == ['--verbose'] && rest == ['vpac', 's'] && !verbose_flag + // the short letter is not it: -v stays the mode's to refuse or to take + _, _, short := scan_globals(['vpac', 'i', '-v', 'x'])! + assert short == ['vpac', 'i', '-v', 'x'] && !verbose_flag + // and it takes no value + _, _, eq := scan_globals(['vpac', 'i', '--verbose=yes', 'x'])! + assert eq == ['vpac', 'i', '--verbose=yes', 'x'] && !verbose_flag + if _ := parse_mode(eq) { + assert false, '--verbose=yes parsed as a mode flag' + } +} diff --git a/src/config.v b/src/config.v new file mode 100644 index 0000000..32b4b1a --- /dev/null +++ b/src/config.v @@ -0,0 +1,1027 @@ +@[has_globals] +module main + +import os +import blip.vlib.blip +import blip.vlib.blip.machine +import alpm + +// config_path is the file read at startup, written in blip: a lisp dialect +// embedded from V. the file is required, since the config carries parts of +// vpac (the repos, for one); a setting no form of it names keeps the +// default its __global is declared with below, which reset_config puts +// back before every load +pub const config_path = '/etc/vpac.d/config.lip' + +// the settings below were consts until the config existed. root_path and +// db_path are joined onto file names directly, so they keep a trailing slash +__global root_path = '/' +__global db_path = '/var/lib/pacman/' +__global arch = 'x86_64' +__global parallel_downloads = 3 +// the rank form: how many mirrors to probe at once (0 = unset, so the rank +// parallelism falls back to the network's parallel) and how long one probe +// may take +__global rank_parallel = 0 +__global rank_timeout = 10 +// the pkgbuild form: the command that builds and how deep the clone is. +// where it builds is path :dir. the build command is the system's makepkg, +// which ships in the pacman package with the libalpm vpac runs on; :makepkg +// names another +// the build command is trusted text: it is spelled whole into a shell that +// runs it in the cloned dir, first as the building user and through the +// reviews of the pkgbuild for its content. vpac does not vet it — the config +// is code the machine's user writes (like pacman.conf no more and no less), +// and whoever controls a user's config already controls their shell +__global pkgbuild_makepkg = 'makepkg -f' +__global pkgbuild_depth = 1 +// the unprivileged user libalpm downloads as, like DownloadUser in pacman.conf +__global download_user = 'alpm' +// the configured directories and lists. the defaults are the values the +// hardcoded vpac used +__global cfg_cachedirs = ['/var/cache/pacman/pkg/'] +// pacman's default HookDir, beside the system one libalpm adds by itself +__global cfg_hookdirs = ['/etc/pacman.d/hooks/'] +// where pkgbuild packages are cloned and built (path :build): a relative +// dir is taken under the invoking user's home, because makepkg runs as that user +__global pkgbuild_dir = '.cache/vpac/pkgbuild' +__global cfg_logfile = '' +// the keyring signatures are checked against: pacman's GPGDir default, not +// moved under a fake root (pacman keeps it as configuration). libalpm has +// no default of its own, and without one gpgme falls back on root's own +// ~/.gnupg, where no packager's key is +__global cfg_gpgdir = '/etc/pacman.d/gnupg/' +__global cfg_protocols = ['https'] +// the signature level every sync db is registered with and packages are +// checked against. libalpm's freshly calloc'd handle verifies nothing, so +// vpac defaults to pacman's shipped SigLevel: a package and a database +// signature are both verified when they are present, and a mismatching one +// fails. override with (network :siglevel [...]) +__global cfg_siglevel = alpm.SigLevel.package | .package_optional | .database | .database_optional +__global cfg_hold = []string{} +__global cfg_ignore = []string{} +// the rest of pacman.conf's [options]: groups ignored as cfg_ignore's packages +// are, files an upgrade or an install leaves alone, and the download timeout +__global cfg_ignore_groups = []string{} +__global cfg_noupgrade = []string{} +__global cfg_noextract = []string{} +__global cfg_disable_timeout = false +// pacman.conf's DisableSandboxFilesystem and DisableSandboxSyscalls: libalpm +// sandboxes its downloads and extracts, and this turns both parts off +__global cfg_disable_sandbox = false +// pacman.conf's UseSyslog: libalpm logs to syslog too, (path :syslog true) +__global cfg_syslog = false +// cfg_repos holds the repos the config defines +__global cfg_repos = []CfgRepo{} + +// CfgRepo is one registered repo: a name, a kind ('sync', or 'pkgbuild' for +// a site to build from), and the urls to fetch it from, where a url keeps +// the $repo and $arch placeholders +struct CfgRepo { + name string + kind string + servers []string + // what the db is used for, as pacman.conf's Usage; every use by default + usage alpm.DBUsage = alpm.db_usage_all +} + +// QuietConfigHost reads the config file from the real filesystem and throws +// away anything it prints: a config is read for its definitions, and its +// output has no place in vpac's own. it never reads stdin +struct QuietConfigHost {} + +fn (h &QuietConfigHost) host_print(_ string) {} + +fn (h &QuietConfigHost) host_write(_ string) {} + +fn (h &QuietConfigHost) host_read_line() ?string { + return none +} + +fn (h &QuietConfigHost) host_load(path string) !string { + return os.read_file(path) +} + +// str_of reads one quoted string out of a config value +// usage_of reads a repo's :usage, pacman.conf's Usage: one or more of sync, +// search, install, upgrade and all +fn usage_of(v blip.Value, what string) !alpm.DBUsage { + names := match v.tag { + .string { [v.as_string()] } + else { strs_of(v, what)! } + } + if names.len == 0 { + return error('config: ${what} needs at least one of sync, search, install, upgrade, all') + } + mut usage := unsafe { alpm.DBUsage(0) } + for name in names { + usage |= match name.to_lower() { + 'sync' { alpm.DBUsage.sync } + 'search' { alpm.DBUsage.search } + 'install' { alpm.DBUsage.install } + 'upgrade' { alpm.DBUsage.upgrade } + 'all' { alpm.db_usage_all } + else { + return error('config: ${what} takes sync, search, install, upgrade and all, not "${name}"') + } + } + } + return usage +} + +fn bool_of(v blip.Value, what string) !bool { + if v.tag != .boolean { + return error('config: ${what} must be true or false') + } + return v.as_bool() +} + +fn str_of(v blip.Value, what string) !string { + if v.tag != .string { + return error('config: ${what} must be a quoted string') + } + return v.as_string() +} + +// strs_of reads a string or an array of strings out of a config value +fn strs_of(v blip.Value, what string) ![]string { + mut out := []string{} + match v.tag { + .emptylist {} + .string { + out << v.as_string() + } + .vector, .array { + for item in v.as_vector().data { + out << str_of(item, what)! + } + } + else { + return error('config: ${what} must be a string or an array of strings') + } + } + return out +} + +// int_of reads one integer out of a config value +fn int_of(v blip.Value, what string) !int { + if v.tag != .integer { + return error('config: ${what} must be an integer') + } + return int(v.as_int()) +} + +// float_of reads a number out of a config value, an integer taken as one +fn float_of(v blip.Value, what string) !f64 { + return match v.tag { + .float { v.as_float() } + .integer { f64(v.as_int()) } + else { error('config: ${what} must be a number') } + } +} + +// ratio_of reads a number between 0 and 1: a threshold, a completion +fn ratio_of(v blip.Value, what string) !f64 { + f := float_of(v, what)! + if f < 0.0 || f > 1.0 { + return error('config: ${what} must be between 0 and 1') + } + return f +} + +// count_of reads an integer no smaller than min +fn count_of(v blip.Value, what string, min int) !int { + n := int_of(v, what)! + if n < min { + return error('config: ${what} must be at least ${min}') + } + return n +} + +// siglevel_names are the names (network :siglevel) accepts, mapped onto +// libalpm's SigLevel bits, plus what each one means +const siglevel_names = { + 'package': alpm.SigLevel.package + 'package_optional': alpm.SigLevel.package_optional + 'package_marginal_ok': alpm.SigLevel.package_marginal_ok + 'package_unknown_ok': alpm.SigLevel.package_unknown_ok + 'database': alpm.SigLevel.database + 'database_optional': alpm.SigLevel.database_optional + 'database_marginal_ok': alpm.SigLevel.database_marginal_ok + 'database_unknown_ok': alpm.SigLevel.database_unknown_ok +} + +// siglevel_of reads a SigLevel out of a config value: one name or an array +// of names, e.g. (network :siglevel ['package' 'database_optional']) +fn siglevel_of(v blip.Value, what string) !alpm.SigLevel { + names := match v.tag { + .string { [v.as_string()] } + else { strs_of(v, what)! } + } + // an empty one verifies nothing: libalpm would take the silent answer + // as handing everything over unsigned, which nobody ever means + if names.len == 0 { + return error('config: ${what} needs at least one of: ${siglevel_names.keys().join(', ')}') + } + mut level := unsafe { alpm.SigLevel(0) } + for name in names { + key := name.to_lower() + bit := siglevel_names[key] or { + return error('config: ${what} must be one or more of: ${siglevel_names.keys().join(', ')}') + } + level |= bit + } + return level +} + +// dir_path checks a configured directory: names are joined onto it directly, +// so it must not be empty and it has to end with a slash +fn dir_path(what string, value string) !string { + if value == '' { + return error('config: ${what} must not be empty') + } + return if value.ends_with('/') { value } else { value + '/' } +} + +// keyword_of reads the :key a config form applies to +fn keyword_of(v blip.Value, form string) !string { + if v.tag != .keyword { + return error('config: ${form} expected a :key') + } + return v.as_string() +} + +// keyword_args walks a config form's arguments as keyword, value pairs +fn keyword_args(form string, args []blip.Value) !([]string, []blip.Value) { + if args.len % 2 != 0 { + return error('config: ${form} keys and values come in pairs') + } + mut keys := []string{} + mut values := []blip.Value{} + mut i := 0 + for i < args.len { + keys << keyword_of(args[i], form)! + values << args[i + 1] + i += 2 + } + return keys, values +} + +// prim_path is the config's (path ...) form: root, db, log, gpg, cache, hook, +// and :syslog true for pacman.conf's UseSyslog +fn prim_path(args []blip.Value) !blip.Value { + keys, values := keyword_args('path', args)! + mut i := 0 + for i < keys.len { + match keys[i] { + 'root' { + root_path = dir_path('path :root', str_of(values[i], 'path :root')!)! + } + 'db' { + db_path = dir_path('path :db', str_of(values[i], 'path :db')!)! + } + 'log' { + cfg_logfile = str_of(values[i], 'path :log')! + } + 'syslog' { + cfg_syslog = bool_of(values[i], 'path :syslog')! + } + 'gpg' { + cfg_gpgdir = dir_path('path :gpg', str_of(values[i], 'path :gpg')!)! + } + 'cache' { + dirs := strs_of(values[i], 'path :cache')! + cfg_cachedirs = []string{} + for dir in dirs { + cfg_cachedirs << dir_path('path :cache', dir)! + } + } + 'hook' { + dirs := strs_of(values[i], 'path :hook')! + cfg_hookdirs = []string{} + for dir in dirs { + cfg_hookdirs << dir_path('path :hook', dir)! + } + } + 'build' { + d := str_of(values[i], 'path :build')! + if d == '' { + return error('config: path :build must not be empty') + } + pkgbuild_dir = d + } + else { + return error('config: path has no key :${keys[i]}') + } + } + i++ + } + return blip.nil_value() +} + +// prim_pkg is the config's (pkg ...) form: arch, hold, ignore, and pacman.conf's +// IgnoreGroup, NoUpgrade and NoExtract as :ignoregroup, :noupgrade and +// :noextract, each a list, e.g. (pkg :noextract ["usr/share/doc/*"]) +fn prim_pkg(args []blip.Value) !blip.Value { + keys, values := keyword_args('pkg', args)! + mut i := 0 + for i < keys.len { + match keys[i] { + 'arch' { + a := str_of(values[i], 'pkg :arch')! + // it fills the $arch of every server url and is the one + // architecture libalpm installs for: one plain word + if a == '' || a.contains('/') || a.fields().len != 1 || a.fields()[0] != a { + return error('config: pkg :arch must be one plain word, such as x86_64') + } + arch = a + } + 'hold' { + cfg_hold = strs_of(values[i], 'pkg :hold')! + } + 'ignore' { + cfg_ignore = strs_of(values[i], 'pkg :ignore')! + } + 'ignoregroup' { + cfg_ignore_groups = strs_of(values[i], 'pkg :ignoregroup')! + } + 'noupgrade' { + cfg_noupgrade = strs_of(values[i], 'pkg :noupgrade')! + } + 'noextract' { + cfg_noextract = strs_of(values[i], 'pkg :noextract')! + } + else { + return error('config: pkg has no key :${keys[i]}') + } + } + i++ + } + return blip.nil_value() +} + +// prim_network is the config's (network ...) form: parallel, protocols, user, +// siglevel, :disable-timeout true for pacman.conf's DisableDownloadTimeout, and +// :disable-sandbox true for its DisableSandbox +fn prim_network(args []blip.Value) !blip.Value { + keys, values := keyword_args('network', args)! + mut i := 0 + for i < keys.len { + match keys[i] { + 'parallel' { + n := int_of(values[i], 'network :parallel')! + if n < 1 { + return error('config: network :parallel must be at least 1') + } + parallel_downloads = n + } + 'protocols' { + protos := strs_of(values[i], 'network :protocols')! + if protos.len == 0 { + return error('config: network :protocols needs at least one, https or http') + } + // a scheme no mirror is listed under would filter every + // mirror out without a word + for proto in protos { + if proto !in ['https', 'http'] { + return error('config: network :protocols takes https and http, not "${proto}"') + } + } + cfg_protocols = protos.clone() + } + 'user' { + download_user = str_of(values[i], 'network :user')! + } + 'siglevel' { + cfg_siglevel = siglevel_of(values[i], 'network :siglevel')! + } + 'disable-timeout' { + cfg_disable_timeout = bool_of(values[i], 'network :disable-timeout')! + } + 'disable-sandbox' { + cfg_disable_sandbox = bool_of(values[i], 'network :disable-sandbox')! + } + else { + return error('config: network has no key :${keys[i]}') + } + } + i++ + } + return blip.nil_value() +} + +// prim_rank is the config's (rank ...) form: parallel and timeout for the +// mirror ranking. the parallelism falls back to the network's parallel when +// the rank form does not set its own. :top is how many mirrors are answered, +// :completion (0 to 1) and :max-delay (seconds) what a mirror must report to +// be probed, :candidates how many get the speed test, :retest how many of +// the fastest are timed twice, :dir where rank -w writes +fn prim_rank(args []blip.Value) !blip.Value { + keys, values := keyword_args('rank', args)! + mut i := 0 + for i < keys.len { + match keys[i] { + 'parallel' { + n := int_of(values[i], 'rank :parallel')! + if n < 1 { + return error('config: rank :parallel must be at least 1') + } + rank_parallel = n + } + 'timeout' { + n := int_of(values[i], 'rank :timeout')! + if n < 1 { + return error('config: rank :timeout must be at least 1') + } + rank_timeout = n + } + 'top' { + rank_top = count_of(values[i], 'rank :top', 1)! + } + 'dir' { + d := str_of(values[i], 'rank :dir')! + if !d.starts_with('/') { + return error('config: rank :dir must be an absolute path') + } + rank_dir = d.trim_right('/') + } + 'candidates' { + rank_speed_candidates = count_of(values[i], 'rank :candidates', 1)! + } + 'retest' { + rank_retest = count_of(values[i], 'rank :retest', 0)! + } + 'completion' { + rank_min_completion = ratio_of(values[i], 'rank :completion')! + } + 'max-delay' { + rank_max_delay = i64(count_of(values[i], 'rank :max-delay', 0)!) + } + else { + return error('config: rank has no key :${keys[i]}') + } + } + i++ + } + return blip.nil_value() +} + +// prim_repo is the config's (repo ...) form: a repo's name, its type ('sync', +// or 'pkgbuild', a site to build from) and the mirrors it is fetched +// from, with $repo and $arch left as placeholders +// :usage is pacman.conf's Usage: a list of sync, search, install, upgrade +// and all; every use when it is left out +fn prim_repo(args []blip.Value) !blip.Value { + keys, values := keyword_args('repo', args)! + mut repo := CfgRepo{ + kind: 'sync' + } + mut i := 0 + for i < keys.len { + match keys[i] { + 'name' { + rname := str_of(values[i], 'repo :name')! + repo = CfgRepo{ + ...repo + name: rname + } + } + 'type' { + rkind := str_of(values[i], 'repo :type')! + if rkind !in ['sync', 'pkgbuild'] { + return error("config: repo :type is 'sync' or 'pkgbuild', not '${rkind}'") + } + repo = CfgRepo{ + ...repo + kind: rkind + } + } + 'src' { + rservers := strs_of(values[i], 'repo :src')! + if rservers.len == 0 { + return error('config: repo :src needs at least one url') + } + for server in rservers { + if server == '' { + return error('config: repo :src has an empty url in it') + } + } + repo = CfgRepo{ + ...repo + servers: rservers + } + } + 'usage' { + rusage := usage_of(values[i], 'repo :usage')! + repo = CfgRepo{ + ...repo + usage: rusage + } + } + else { + return error('config: repo has no key :${keys[i]}') + } + } + i++ + } + if repo.name == '' { + return error('config: repo needs a :name') + } + // libalpm refuses a second db of a name, and 'local' is its own db's: + // said here, by name, instead of late and from inside a mode + if repo.name == 'local' { + return error('config: a repo cannot be named local, the installed packages are') + } + if cfg_repos.any(it.name == repo.name) { + return error('config: repo ${repo.name} is defined twice') + } + if repo.kind == 'sync' && repo.servers.len == 0 { + return error('config: a sync repo takes at least one :src') + } + if repo.kind == 'pkgbuild' && repo.servers.len != 1 { + return error('config: a pkgbuild repo takes one :src, the site to build from') + } + cfg_repos << repo + return blip.nil_value() +} + +// pkgbuild_repos are the configured pkgbuild repos, in config order. the +// --pkgbuild flags search and build from all of them, each under its own name +fn pkgbuild_repos() []CfgRepo { + return cfg_repos.filter(it.kind == 'pkgbuild') +} + +// prim_pkgbuild is the config's (pkgbuild ...) form: makepkg, depth, and +// timeout, the seconds one lookup of a pkgbuild repo may take. where the +// build happens is path :build +fn prim_pkgbuild(args []blip.Value) !blip.Value { + keys, values := keyword_args('pkgbuild', args)! + mut i := 0 + for i < keys.len { + match keys[i] { + 'makepkg' { + m := str_of(values[i], 'pkgbuild :makepkg')! + if m == '' { + return error('config: pkgbuild :makepkg must not be empty') + } + pkgbuild_makepkg = m + } + 'depth' { + n := int_of(values[i], 'pkgbuild :depth')! + if n < 1 { + return error('config: pkgbuild :depth must be at least 1') + } + pkgbuild_depth = n + } + 'timeout' { + pkgbuild_rpc_timeout = count_of(values[i], 'pkgbuild :timeout', 1)! + } + else { + return error('config: pkgbuild has no key :${keys[i]}') + } + } + i++ + } + return blip.nil_value() +} + +// option_flags are the mode flags (options ...) can turn on for every run, +// by the config's key: each names the field the modes' flag structs keep it +// in, so a mode that has no such flag is simply not touched +const option_flags = { + 'noconfirm': 'noconfirm' + 'nopkgbuildconfirm': 'no_pkgbuild_confirm' + 'needed': 'needed' + 'no-upgrade-deps': 'no_upgrade_deps' + 'quiet': 'quiet' + 'keep-current': 'keep_current' + 'fuzzy': 'fuzzy' + 'disable-timeout': 'disable_timeout' +} + +// opt_flags holds the fields of option_flags the config turned on; +// opt_color is options :color, empty when the config names none +__global opt_flags = map[string]bool{} +__global opt_color = '' + +// prim_options is the config's (options ...) form: root, the command vpac +// gets root with (privilege.v); color, the --color a run starts from; +// verbose, the verbose log of a run's housekeeping failures (--verbose); +// sync-age, the hours after which the sync dbs are called stale (0: never); +// suggest, how close (0 to 1) a name must be to be offered for a typo; and +// the mode flags of option_flags, true or false +fn prim_options(args []blip.Value) !blip.Value { + keys, values := keyword_args('options', args)! + mut i := 0 + for i < keys.len { + match keys[i] { + 'root' { + r := str_of(values[i], 'options :root')! + if r.trim_space() == '' { + return error('config: options :root must not be empty') + } + root_provider = r + } + 'color' { + c := str_of(values[i], 'options :color')! + if c !in ['auto', 'always', 'never'] { + return error('config: options :color takes auto, always or never, not "${c}"') + } + opt_color = c + } + 'sync-age' { + // hours; 0 never warns + sync_max_age = i64(count_of(values[i], 'options :sync-age', 0)!) * 3600 + } + 'suggest' { + suggest_thold = ratio_of(values[i], 'options :suggest')! + } + 'verbose' { + // the verbose log for every run, as --verbose for one + cfg_verbose = bool_of(values[i], 'options :verbose')! + } + else { + field := option_flags[keys[i]] or { + return error('config: options has no key :${keys[i]}') + } + // only what is on is held: a false takes back an earlier + // true (an --eval over the file) and leaves no entry behind + if bool_of(values[i], 'options :${keys[i]}')! { + opt_flags[field] = true + } else { + opt_flags.delete(field) + } + } + } + i++ + } + return blip.nil_value() +} + +// prim_search is the config's (search ...) form: fields, the columns of a +// listing when --fields names none, and thold, the fuzzy threshold +fn prim_search(args []blip.Value) !blip.Value { + keys, values := keyword_args('search', args)! + mut i := 0 + for i < keys.len { + match keys[i] { + 'fields' { + names := strs_of(values[i], 'search :fields')! + if names.len == 0 { + return error('config: search :fields needs at least one field') + } + cfg_search_fields = parse_fields(names.join(','), []string{}) or { + return error('config: search :fields: ${err.msg()}') + } + } + 'thold' { + cfg_search_thold = ratio_of(values[i], 'search :thold')! + } + else { + return error('config: search has no key :${keys[i]}') + } + } + i++ + } + return blip.nil_value() +} + +// prim_clean is the config's (clean ...) form: keep, the versions of every +// package the cache keeps when -k names none +fn prim_clean(args []blip.Value) !blip.Value { + keys, values := keyword_args('clean', args)! + mut i := 0 + for i < keys.len { + match keys[i] { + 'keep' { + cfg_clean_keep = count_of(values[i], 'clean :keep', 0)! + } + else { + return error('config: clean has no key :${keys[i]}') + } + } + i++ + } + return blip.nil_value() +} + +// prim_tree is the config's (tree ...) form: depth, how deep a tree is +// drawn when -d names none +fn prim_tree(args []blip.Value) !blip.Value { + keys, values := keyword_args('tree', args)! + mut i := 0 + for i < keys.len { + match keys[i] { + 'depth' { + cfg_tree_depth = count_of(values[i], 'tree :depth', 0)! + } + else { + return error('config: tree has no key :${keys[i]}') + } + } + i++ + } + return blip.nil_value() +} + +// prim_color is the config's (color ...) form, the theme: each key is a role +// of default_theme, each value one style or a list of them out of +// style_names, e.g. (color :version "cyan" :warning ["bold" "magenta"]) +fn prim_color(args []blip.Value) !blip.Value { + keys, values := keyword_args('color', args)! + mut i := 0 + for i < keys.len { + if keys[i] !in theme { + return error('config: color has no role :${keys[i]}, the roles are: ${default_theme().keys().join(', ')}') + } + styles := strs_of(values[i], 'color :${keys[i]}')! + for style in styles { + if style !in style_names { + return error('config: color :${keys[i]} takes ${style_names.join(', ')}, not "${style}"') + } + } + theme[keys[i]] = styles.clone() + i++ + } + return blip.nil_value() +} + +// prim_mirrorlist is the config's (mirrorlist ...) form: an os for the +// ranker, new or one of its own redefined. :name is what rank is asked for +// (and what /etc/os-release is matched against), :repo the repo whose db the +// speed test pulls, and the mirrors come from one of :status, a mirror +// status json api as arch publishes, or :list, a Server = mirrorlist at a +// url or an absolute path +fn prim_mirrorlist(args []blip.Value) !blip.Value { + keys, values := keyword_args('mirrorlist', args)! + mut name := '' + mut status := '' + mut list := '' + mut repo := '' + mut i := 0 + for i < keys.len { + match keys[i] { + 'name' { name = str_of(values[i], 'mirrorlist :name')! } + 'status' { status = str_of(values[i], 'mirrorlist :status')! } + 'list' { list = str_of(values[i], 'mirrorlist :list')! } + 'repo' { repo = str_of(values[i], 'mirrorlist :repo')! } + else { return error('config: mirrorlist has no key :${keys[i]}') } + } + i++ + } + if name == '' || name.contains('/') || name.starts_with('.') || name.starts_with('-') + || name.fields().len != 1 || name.fields()[0] != name { + return error('config: mirrorlist needs a :name, one plain word') + } + if repo == '' { + return error('config: mirrorlist ${name} needs a :repo, the repo whose db is timed') + } + if (status == '') == (list == '') { + return error('config: mirrorlist ${name} takes one of :status and :list') + } + if status != '' && !status.starts_with('https://') && !status.starts_with('http://') { + return error('config: mirrorlist ${name} :status must be an http or https url') + } + if list != '' && !list.starts_with('https://') && !list.starts_with('http://') + && !list.starts_with('/') { + return error('config: mirrorlist ${name} :list must be a url or an absolute path') + } + rank_oses[name] = RankOs{ + status_json: status + mirrorlist: list + repo: repo + } + return blip.nil_value() +} + +// cell_of reads one piece of a bar graphic: text of exactly one rune, or of +// at most one when it may be left out +fn cell_of(v blip.Value, what string, may_be_empty bool) !string { + text := str_of(v, what)! + n := text.runes().len + if n > 1 || (n == 0 && !may_be_empty) { + return error('config: ${what} must be one character') + } + return text +} + +// prim_progress is the config's (progress ...) form, the bars: style +// ('classic' or 'block'); the graphic's pieces start, end, fill, head and +// empty; length in cells (0 fills the terminal); percent, eta, elapsed and +// rate, true or false; delay, the milliseconds between redraws +fn prim_progress(args []blip.Value) !blip.Value { + keys, values := keyword_args('progress', args)! + mut i := 0 + for i < keys.len { + what := 'progress :${keys[i]}' + match keys[i] { + 'style' { + s := str_of(values[i], what)! + if s !in ['classic', 'block'] { + return error('config: ${what} is classic or block, not "${s}"') + } + cfg_progress.style = s + } + 'start', 'end' { + cfg_progress.parts[keys[i]] = str_of(values[i], what)! + } + 'fill', 'empty' { + cfg_progress.parts[keys[i]] = cell_of(values[i], what, false)! + } + 'head' { + cfg_progress.parts[keys[i]] = cell_of(values[i], what, true)! + } + 'length' { + cfg_progress.length = count_of(values[i], what, 0)! + } + 'percent' { + cfg_progress.percent = bool_of(values[i], what)! + } + 'eta' { + cfg_progress.eta = bool_of(values[i], what)! + } + 'elapsed' { + cfg_progress.elapsed = bool_of(values[i], what)! + } + 'rate' { + cfg_progress.rate = bool_of(values[i], what)! + } + 'delay' { + cfg_progress.delay = count_of(values[i], what, 1)! + } + else { + return error('config: progress has no key :${keys[i]}') + } + } + i++ + } + return blip.nil_value() +} + +// prim_spinner is the config's (spinner ...) form: frames, a set by name +// (spinner_sets) or a list of frames of one's own; interval, the +// milliseconds a frame stays; done, what a finished step shows in place of +// the animation; elapsed, whether the time taken is shown +fn prim_spinner(args []blip.Value) !blip.Value { + keys, values := keyword_args('spinner', args)! + mut i := 0 + for i < keys.len { + what := 'spinner :${keys[i]}' + match keys[i] { + 'frames' { + if values[i].tag == .string { + name := values[i].as_string() + cfg_progress.frames = spinner_frames_named(name) or { + return error('config: ${what} knows ${spinner_sets.join(', ')}, not "${name}"; a list gives frames of your own') + } + } else { + frames := strs_of(values[i], what)! + if frames.len == 0 { + return error('config: ${what} needs at least one frame') + } + cfg_progress.frames = frames.clone() + } + } + 'interval' { + cfg_progress.interval = count_of(values[i], what, 1)! + } + 'done' { + cfg_progress.done = str_of(values[i], what)! + } + 'elapsed' { + cfg_progress.timed = bool_of(values[i], what)! + } + else { + return error('config: spinner has no key :${keys[i]}') + } + } + i++ + } + return blip.nil_value() +} + +// prim_array_append is (array-append! dst src): every element of src pushed +// onto dst. it is std.lip's, provided by the host so the config's mirror lists +// are fillable without vpac loading std.lip +fn prim_array_append(args []blip.Value) !blip.Value { + if args.len != 2 { + return error('config: array-append! needs an array and an array of values') + } + if args[0].tag !in [.vector, .array] { + return error('config: array-append! the first argument must be an array') + } + match args[1].tag { + .vector, .array { + for item in args[1].as_vector().data { + args[0].as_vector().push(item) + } + } + .emptylist {} + else { + return error('config: array-append! the second argument must be an array') + } + } + return args[0] +} + +// reset_config puts every config global back at its declared default, the +// values the hardcoded vpac used. load_config runs it first, so a second +// load in one process neither duplicates the repos nor keeps settings the +// new file does not name; a failed load can leave values behind, and the +// next load starts clean again +fn reset_config() { + root_path = '/' + root_provider = 'sudo' + opt_flags = map[string]bool{} + opt_color = '' + cfg_verbose = false + sync_max_age = i64(24 * 60 * 60) + suggest_thold = 0.85 + pkgbuild_rpc_timeout = 10 + rank_min_completion = 1.0 + rank_max_delay = i64(86400) + rank_speed_candidates = 40 + rank_retest = 5 + rank_top = 10 + cfg_search_fields = search_default_fields.clone() + cfg_search_thold = 0.9 + cfg_clean_keep = 0 + cfg_tree_depth = 0 + theme = default_theme() + rank_oses = default_rank_oses() + rank_dir = '/etc/vpac.d/mirrors' + cfg_progress = ProgressCfg{} + db_path = '/var/lib/pacman/' + arch = 'x86_64' + parallel_downloads = 3 + rank_parallel = 0 + rank_timeout = 10 + pkgbuild_makepkg = 'makepkg -f' + pkgbuild_depth = 1 + download_user = 'alpm' + pkgbuild_dir = '.cache/vpac/pkgbuild' + cfg_cachedirs = ['/var/cache/pacman/pkg/'] + cfg_hookdirs = ['/etc/pacman.d/hooks/'] + cfg_logfile = '' + cfg_gpgdir = '/etc/pacman.d/gnupg/' + cfg_protocols = ['https'] + cfg_siglevel = alpm.SigLevel.package | .package_optional | .database | .database_optional + cfg_hold = []string{} + cfg_ignore = []string{} + cfg_ignore_groups = []string{} + cfg_noupgrade = []string{} + cfg_noextract = []string{} + cfg_disable_timeout = false + cfg_disable_sandbox = false + cfg_syslog = false + cfg_repos = []CfgRepo{} +} + +// load_config reads the config file -- the one --config names, else +// config_path -- and evaluates it in a machine that provides the config +// forms. the file is required: vpac has no defaults to fall back to once its +// repos, paths and mirror lists live in the config. the --eval snippets run +// after it, in the same machine, so they can extend or override the file for +// this run. a file that does not parse, or a form with the wrong keys, stops +// vpac, because running on silently could act on the wrong database +fn load_config(chosen string, evals []string) ! { + reset_config() + path := if chosen != '' { chosen } else { config_path } + if !os.exists(path) { + return error('${path} is required: write it, starting with (require ...) for each part') + } + mut m := machine.new_standalone(&QuietConfigHost{}) + m.prims['path'] = prim_path + m.prims['pkg'] = prim_pkg + m.prims['network'] = prim_network + m.prims['rank'] = prim_rank + m.prims['pkgbuild'] = prim_pkgbuild + m.prims['options'] = prim_options + m.prims['search'] = prim_search + m.prims['clean'] = prim_clean + m.prims['tree'] = prim_tree + m.prims['color'] = prim_color + m.prims['mirrorlist'] = prim_mirrorlist + m.prims['progress'] = prim_progress + m.prims['spinner'] = prim_spinner + m.prims['repo'] = prim_repo + m.prims['array-append!'] = prim_array_append + m.load(path) or { + return error('config: ${err.msg()}') + } + for code in evals { + m.run_str(code) or { + return error('config --eval: ${err.msg()}') + } + } +} + +// check_hold refuses to remove a package the config holds, as pacman does for +// HoldPkg. libalpm has no option for it, so it is a frontend check +fn check_hold(names []string) ! { + for name in names { + if name in cfg_hold { + return error('${name} is held by the config: remove it from pkg :hold first') + } + } +} diff --git a/src/config_test.v b/src/config_test.v new file mode 100644 index 0000000..6568a29 --- /dev/null +++ b/src/config_test.v @@ -0,0 +1,445 @@ +module main + +import os +import time +import x.progress + +fn config_tmp(name string) !string { + tmp := os.join_path(os.vtmp_dir(), 'vpac_test_config_${name}_${os.getpid()}') + os.mkdir_all(os.join_path(tmp, 'db', 'local'))! + os.write_file(os.join_path(tmp, 'db', 'local', 'ALPM_DB_VERSION'), '9\n')! + return tmp +} + +fn test_config_options() ! { + tmp := config_tmp('options')! + defer { os.rmdir_all(tmp) or {} } + cfg := os.join_path(tmp, 'config.lip') + os.write_file(cfg, '(path :db "${tmp}/db/")\n' + + '(pkg :ignoregroup ["kde-applications"] :noupgrade ["etc/foo.conf"] :noextract ["usr/share/doc/*" "usr/share/man/*"])\n' + + '(path :syslog true)\n' + '(network :disable-timeout true :disable-sandbox true)\n' + r'(repo :name "core" :src ["https://example.org/$repo"] :usage ["sync" "Search"])' + + '\n' + r'(repo :name "extra" :src ["https://example.org/$repo"])' + '\n')! + load_config(cfg, [])! + + assert cfg_ignore_groups == ['kde-applications'] + assert cfg_noupgrade == ['etc/foo.conf'] + assert cfg_noextract == ['usr/share/doc/*', 'usr/share/man/*'] + assert cfg_disable_timeout + assert cfg_disable_sandbox + assert cfg_syslog + core := cfg_repos.filter(it.name == 'core')[0] + extra := cfg_repos.filter(it.name == 'extra')[0] + // pacman's Usage bits: Sync 1, Search 2; every use when none is given + assert int(core.usage) == 1 | 2 + assert int(extra.usage) == 15 + + // and libalpm gets them from init_handle + ui := new_trans_ui() + mut handle := init_handle(ui)! + defer { handle.release() or {} } + mut groups := handle.option_get_ignore_groups() + assert groups.strs() == ['kde-applications'] + mut noupgrade := handle.option_get_noupgrades() + assert noupgrade.strs() == ['etc/foo.conf'] + mut noextract := handle.option_get_no_extracts() + assert noextract.strs() == ['usr/share/doc/*', 'usr/share/man/*'] + assert handle.option_match_no_extract('usr/share/doc/zsh/README') + assert !handle.option_match_no_extract('usr/bin/zsh') + assert handle.option_get_disable_sandbox_filesystem() + assert handle.option_get_disable_sandbox_syscalls() +} + +// the sandbox stays on unless the config turns it off: a config that does not +// name it, or names it false, leaves libalpm's sandbox on for the handle +fn test_config_disable_sandbox_defaults_on() ! { + tmp := config_tmp('sandbox')! + defer { + os.rmdir_all(tmp) or {} + reset_config() + } + cfg := os.join_path(tmp, 'config.lip') + os.write_file(cfg, '(network :parallel 2)\n')! + load_config(cfg, [])! + assert !cfg_disable_sandbox + ui := new_trans_ui() + mut handle := init_handle(ui)! + defer { handle.release() or {} } + assert !handle.option_get_disable_sandbox_filesystem() + assert !handle.option_get_disable_sandbox_syscalls() + // a false written out is the same as leaving it out + os.write_file(cfg, '(network :disable-sandbox false)\n')! + load_config(cfg, [])! + assert !cfg_disable_sandbox +} + +fn test_config_rejects_bad_values() ! { + tmp := config_tmp('bad')! + defer { os.rmdir_all(tmp) or {} } + cfg := os.join_path(tmp, 'config.lip') + for form, says in { + '(repo :name "x" :usage ["sometimes"])': 'takes sync, search, install, upgrade and all' + '(repo :name "x" :usage [])': 'needs at least one' + '(network :disable-timeout "yes")': 'must be true or false' + '(network :disable-sandbox "yes")': 'must be true or false' + // an empty one verifies nothing, and a list of no protocols accepts + // no transfers; a repo that names no servers has nothing to fetch + '(network :siglevel [])': 'needs at least one of' + '(network :protocols [])': 'needs at least one' + '(network :protocols ["ftp"])': 'takes https and http' + '(network :protocols ["https" "HTTPS"])': 'takes https and http' + '(pkg :arch "")': 'must be one plain word' + '(pkg :arch "x86 64")': 'must be one plain word' + '(pkg :arch " x86_64")': 'must be one plain word' + '(pkg :arch "a/b")': 'must be one plain word' + '(repo :name "local" :src ["http://x"])': 'cannot be named local' + '(repo :name "x" :src ["http://x"]) (repo :name "x" :src ["http://y"])': 'is defined twice' + '(repo :name "x" :src ["http://x"]) (repo :name "x" :type "pkgbuild" :src ["http://y"])': 'is defined twice' + '(mirrorlist :name "my os" :repo "core" :status "https://x")': 'one plain word' + '(mirrorlist :name "os\t" :repo "core" :status "https://x")': 'one plain word' + '(repo :name "x" :src [])': 'needs at least one url' + '(repo :name "x" :src "")': 'has an empty url in it' + '(repo :name "x" :type "sync")': 'takes at least one :src' + '(options :root " ")': 'must not be empty' + '(options :colour "always")': 'has no key :colour' + '(options :color "sometimes")': 'takes auto, always or never' + '(options :noconfirm "yes")': 'must be true or false' + '(options :suggest 2)': 'between 0 and 1' + '(options :sync-age -1)': 'at least 0' + '(search :fields ["nope"])': 'unknown field' + '(search :thold "high")': 'must be a number' + '(rank :top 0)': 'at least 1' + '(pkgbuild :timeout 0)': 'at least 1' + '(color :nope "red")': 'has no role :nope' + '(progress :style "round")': 'classic or block' + '(progress :fill "==")': 'must be one character' + '(progress :empty "")': 'must be one character' + '(spinner :frames "nope")': 'not "nope"' + '(spinner :frames [])': 'at least one frame' + '(mirrorlist :name "x" :repo "core")': 'one of :status and :list' + '(mirrorlist :name "x" :list "/m")': 'needs a :repo' + '(mirrorlist :name "a/b" :list "/m" :repo "c")': 'one plain word' + '(mirrorlist :name "x" :status "/m" :repo "c")': 'http or https url' + '(rank :dir "mirrors")': 'absolute path' + '(color :name "pink")': 'not "pink"' + } { + os.write_file(cfg, form + '\n')! + if _ := load_config(cfg, []) { + assert false, '${form} was accepted' + } else { + assert err.msg().contains(says), '${form}: ${err.msg()}' + } + } + // a list may be a single string, as everywhere in the config + os.write_file(cfg, '(pkg :noupgrade "etc/foo.conf")\n')! + load_config(cfg, [])! + assert cfg_noupgrade == ['etc/foo.conf'] +} + +// a second load answers nothing of the first's: every global is back at its +// default before the file is read, so nothing is kept that the new file does +// not name, and no repo of the old load survives +fn test_config_resets_between_loads() ! { + tmp := config_tmp('reset')! + defer { os.rmdir_all(tmp) or {} } + cfg := os.join_path(tmp, 'config.lip') + os.write_file(cfg, '(repo :name "one" :src ["https://one.example/$repo"])\n +(network :parallel 5 :siglevel ["package" "database"])\n(pkg :hold ["glibc"] :ignore ["flatpak"])\n(options :root "doas -n")\n')! + load_config(cfg, [])! + assert root_provider == 'doas -n' + assert cfg_repos.map(it.name) == ['one'] + assert cfg_repos.len == 1 + assert parallel_downloads == 5 + assert cfg_hold == ['glibc'] + assert cfg_ignore == ['flatpak'] + assert cfg_disable_timeout == false + + os.write_file(cfg, '(repo :name "two" :src "https://two.example/$repo")\n')! + load_config(cfg, [])! + assert cfg_repos.map(it.name) == ['two'] + assert cfg_repos.len == 1 + assert parallel_downloads == 3 + assert root_provider == 'sudo' + assert opt_color == '' + assert opt_flags.len == 0 + assert cfg_hold == []string{} + assert cfg_ignore == []string{} +} + +// check_hold refuses a name on the hold list, the targets of a removal as +// well as whatever a transaction pulls in beyond them +fn test_check_hold() { + mut old := cfg_hold.clone() + defer { cfg_hold = old.clone() } + cfg_hold = ['held', 'base'] + check_hold(['other', 'more']) or { + assert false, 'a name off the hold list was refused' + } + if _ := check_hold(['fine', 'held']) { + assert false, 'a held package was let through' + } else { + assert err.msg().contains('held'), err.msg() + } +} + +// the keyring dir defaults to pacman's GPGDir, so a config that names no +// :gpg checks signatures against the system keyring, not root's ~/.gnupg; +// a named one overrides it for its load only +fn test_config_gpgdir_default() ! { + tmp := config_tmp('gpgdir')! + defer { os.rmdir_all(tmp) or {} } + cfg := os.join_path(tmp, 'config.lip') + saved := cfg_gpgdir + defer { cfg_gpgdir = saved } + + os.write_file(cfg, '(network :parallel 2)\n')! + load_config(cfg, [])! + assert cfg_gpgdir == '/etc/pacman.d/gnupg/' + + os.write_file(cfg, '(path :gpg "${tmp}/keys")\n')! + load_config(cfg, [])! + assert cfg_gpgdir == '${tmp}/keys/' + + os.write_file(cfg, '(network :parallel 2)\n')! + load_config(cfg, [])! + assert cfg_gpgdir == '/etc/pacman.d/gnupg/' +} + +// the default reaches the handle every writing mode opens +fn test_init_handle_sets_the_default_gpgdir() ! { + tmp := config_tmp('gpghandle')! + defer { os.rmdir_all(tmp) or {} } + os.mkdir_all(os.join_path(tmp, 'root'))! + saved_root, saved_db, saved_user := root_path, db_path, download_user + defer { + reset_config() + root_path, db_path, download_user = saved_root, saved_db, saved_user + } + reset_config() + root_path = os.join_path(tmp, 'root') + '/' + db_path = os.join_path(tmp, 'db') + '/' + // the sandbox user need not exist where the tests run + download_user = '' + ui := new_trans_ui() + handle := init_handle(ui)! + defer { handle.release() or {} } + assert handle.option_get_gpgdir() == '/etc/pacman.d/gnupg/' +} + +// the config's options are the flags a run starts with: on for every mode +// that has the flag, untouched where it has none, and off again by --eval +fn test_config_options_set_mode_flags() ! { + tmp := config_tmp('flags')! + defer { + os.rmdir_all(tmp) or {} + reset_config() + } + cfg := os.join_path(tmp, 'config.lip') + os.write_file(cfg, '(options :noconfirm true :needed true :nopkgbuildconfirm true :no-upgrade-deps true :color "never")\n')! + load_config(cfg, [])! + assert opt_color == 'never' + install_mode := parse_mode(['vpac', 'i', 'foo'])! + if install_mode is ConfigInstall { + assert install_mode.noconfirm && install_mode.needed + assert install_mode.no_pkgbuild_confirm && install_mode.no_upgrade_deps + assert install_mode.query == ['foo'] + } else { + assert false + } + remove_mode := parse_mode(['vpac', 'r', 'foo'])! + if remove_mode is ConfigRemove { + assert remove_mode.noconfirm + } else { + assert false + } + load_config(cfg, ['(options :noconfirm false)'])! + again := parse_mode(['vpac', 'i', 'foo'])! + if again is ConfigInstall { + assert !again.noconfirm && again.needed + } else { + assert false + } +} + +// the tunables the modes read are the config's: thresholds, sizes, the +// defaults a flag would otherwise carry, and the theme. a flag on the +// command line still wins, and the next load puts every one back +fn test_config_tunables() ! { + tmp := config_tmp('tunables')! + old_color := color_flag + defer { + os.rmdir_all(tmp) or {} + color_flag = old_color + reset_config() + } + cfg := os.join_path(tmp, 'config.lip') + os.write_file(cfg, '(options :sync-age 0 :suggest 0.5 :fuzzy true)\n' + + '(search :fields ["name" "version"] :thold 0.7)\n' + + '(rank :top 3 :candidates 12 :retest 0 :completion 0.9 :max-delay 3600)\n' + + '(pkgbuild :timeout 30)\n(clean :keep 2)\n(tree :depth 4)\n' + + '(color :version "cyan" :warning ["bold" "magenta"] :name "none")\n')! + load_config(cfg, [])! + assert sync_max_age == 0 + assert suggest_thold == 0.5 + assert cfg_search_fields == ['name', 'version'] + assert rank_speed_candidates == 12 && rank_retest == 0 + assert rank_min_completion == 0.9 && rank_max_delay == 3600 + assert pkgbuild_rpc_timeout == 30 + + search_mode := parse_mode(['vpac', 's', 'foo'])! + if search_mode is ConfigSearch { + assert search_mode.thold == 0.7 && search_mode.fuzzy + } else { + assert false + } + given := parse_mode(['vpac', 's', '--thold', '0.95', 'foo'])! + if given is ConfigSearch { + assert given.thold == 0.95 + } else { + assert false + } + rank_mode := parse_mode(['vpac', 'k', 'arch'])! + if rank_mode is ConfigRank { + assert rank_mode.top == 3 + } else { + assert false + } + rank_given := parse_mode(['vpac', 'k', '-n', '7', 'arch'])! + if rank_given is ConfigRank { + assert rank_given.top == 7 + } else { + assert false + } + clean_mode := parse_mode(['vpac', 'c'])! + if clean_mode is ConfigClean { + assert clean_mode.keep == 2 + } else { + assert false + } + tree_mode := parse_mode(['vpac', 't', 'foo'])! + if tree_mode is ConfigTree { + assert tree_mode.depth == 4 + } else { + assert false + } + + color_flag = 'always' + assert version_style('1') == '\x1b[36m1\x1b[39m' + assert name_style('n') == 'n' + assert warning('w').starts_with('\x1b[') + + os.write_file(cfg, '(path :db "${tmp}/db/")\n')! + load_config(cfg, [])! + assert sync_max_age == 24 * 60 * 60 + assert cfg_search_fields == search_default_fields + assert rank_top == 10 && cfg_clean_keep == 0 && cfg_tree_depth == 0 + assert theme == default_theme() +} + +// the live display and the ranker's oses are the config's too: a bar's +// graphic and columns, a spinner's frames, and an os defined beside the +// ranker's own, which a mirrorlist on the disk is enough for +fn test_config_display_and_mirrorlists() ! { + tmp := config_tmp('display')! + defer { + os.rmdir_all(tmp) or {} + reset_config() + } + list := os.join_path(tmp, 'mirrorlist') + os.write_file(list, 'Server = https://one.example/\$repo/os/\$arch\n# a comment\nServer = https://two.example/\$repo/os/\$arch\n')! + cfg := os.join_path(tmp, 'config.lip') + os.write_file(cfg, '(progress :style "classic" :start "|" :end "|" :fill "#" :head "" :empty "." :length 12 :percent false :eta false :elapsed true :rate false :delay 100)\n' + + '(spinner :frames ["a" "b"] :interval 200 :done "ok" :elapsed true)\n' + + '(mirrorlist :name "myos" :list "${list}" :repo "main")\n' + + '(mirrorlist :name "arch" :status "https://example.org/status.json" :repo "core")\n' + + '(rank :dir "${tmp}/ranked/")\n')! + load_config(cfg, [])! + + bar := bar_opts(text: 'x', show_rate: true) + assert bar.text == 'x' && bar.length == 12 + assert !bar.show_percent && !bar.show_left && bar.show_elapsed && !bar.show_rate + style := bar.style + if style is progress.ClassicStyle { + assert style.start == '|' && style.end == '|' + assert style.fill == `#` && style.empty == `.` && style.head == 0 + } else { + assert false, 'the bar is not the classic one' + } + spin := spinner_opts(text: 'working') + assert spin.text == 'working' && spin.frames == ['a', 'b'] + assert spin.interval == 200 * time.millisecond + assert spin.done_frame == 'ok' && spin.show_elapsed + + assert rank_os_name(['myos'])! == 'myos' + assert rank_oses['arch'].status_json == 'https://example.org/status.json' + assert 'artix' in rank_oses + mirrors := fetch_mirrorlist(rank_oses['myos'])! + assert mirrors.len == 2, mirrors.str() + assert rank_write_target('myos') == '${tmp}/ranked/myos.lip' + + os.write_file(cfg, '(spinner :frames "line")\n(progress :style "block")\n')! + load_config(cfg, [])! + assert cfg_progress.frames == progress.spinner_line() + assert bar_opts(text: 'x').style is progress.BlockStyle + assert bar_opts(text: 'x').length == 30 + assert 'myos' !in rank_oses + assert rank_write_target('arch') == '/etc/vpac.d/mirrors/arch.lip' +} + +// an option the config turns off holds no entry: only what is on is kept, +// and a false after a true takes the true back +fn test_config_options_hold_only_what_is_on() ! { + tmp := config_tmp('optflags')! + defer { + os.rmdir_all(tmp) or {} + reset_config() + } + cfg := os.join_path(tmp, 'config.lip') + os.write_file(cfg, '(options :noconfirm false :needed true)\n')! + load_config(cfg, [])! + assert 'noconfirm' !in opt_flags + assert opt_flags == { + 'needed': true + } + // a later form, as an --eval is, turns it off again and leaves nothing + load_config(cfg, ['(options :needed false)'])! + assert opt_flags.len == 0 + mode := parse_mode(['vpac', 'i', 'foo'])! as ConfigInstall + assert !mode.needed && !mode.noconfirm + // the key of the flag nothing read is gone with the flag + for form in ['(options :upgrade-deps true)', '(options :verbose "yes")'] { + os.write_file(cfg, form + '\n')! + if _ := load_config(cfg, []) { + assert false, '${form} was accepted' + } + } +} + +// options :verbose turns the verbose log on for every run, and a load that +// does not name it turns it off again: it is the config's, reset with it +fn test_config_verbose_is_reset_with_the_config() ! { + tmp := config_tmp('verbose')! + saved_flag := verbose_flag + defer { + verbose_flag = saved_flag + os.rmdir_all(tmp) or {} + reset_config() + } + verbose_flag = false + cfg := os.join_path(tmp, 'config.lip') + os.write_file(cfg, '(options :verbose true)\n')! + load_config(cfg, [])! + assert cfg_verbose && verbose_on() + // an --eval after the file takes it back for a run + load_config(cfg, ['(options :verbose false)'])! + assert !cfg_verbose && !verbose_on() + os.write_file(cfg, '(options :color "never")\n')! + load_config(cfg, [])! + assert !cfg_verbose + // the command line's flag is not the config's to reset + verbose_flag = true + load_config(cfg, [])! + assert verbose_on() && !cfg_verbose + // and it is no mode flag: no mode's struct grows a field from it + mode := parse_mode(['vpac', 'i', 'foo'])! as ConfigInstall + assert mode.query == ['foo'] +} diff --git a/src/db.v b/src/db.v new file mode 100644 index 0000000..ffdf573 --- /dev/null +++ b/src/db.v @@ -0,0 +1,167 @@ +@[has_globals] +module main + +import alpm +import os +import time + +// arch and the download user are configurable through config.lip + +// pkgcache_of is a db's package list. libalpm hands an empty db's list over +// as NULL, the NULL it answers an error with too: alpm_db_get_pkgcache +// clears the error first, so alpm_errno tells the two apart. an empty db is +// an empty list here — a nil one, which every list reader takes as such +// (pkgs, pkg_find, find_satisfier) — never a failure: a fresh root has no +// package installed, and pacman finds nothing in it rather than failing +fn pkgcache_of(handle &alpm.Handle, db &alpm.DB) !&alpm.List { + return db.get_pkgcache() or { + e := handle.errno() + if e != .ok { + return error('could not read the packages of ${db.get_name()}: ${e.strerror()}') + } + unsafe { &alpm.List(nil) } + } +} + +// local_pkgcache is the installed packages' list, as pkgcache_of reads one +fn local_pkgcache(handle &alpm.Handle) !&alpm.List { + localdb := handle.get_localdb() or { return error('could not open the local database: ${err.msg()}') } + return pkgcache_of(handle, localdb) +} + +// lock_path is a function because db_path is configurable +fn lock_path() string { + return db_path + 'db.lck' +} + +fn check_db_lock() bool { + return os.exists(lock_path()) +} + +// check_ask_db_lock warns about a db lock left behind and offers to remove it. +// it goes right before vpac takes the lock: a transaction or a db update. +// reading the dbs takes no lock, as pacman's -Ss and -Si take none, so a +// read-only command checks only when it is about to update them. only root +// can remove the lock, so anyone else gets the warning alone. the warning +// goes to stderr with the prompt it leads into +fn check_ask_db_lock(mut ui TransUI) { + if !check_db_lock() { + return + } + // one path, spelled once: the warning, the advice and the removal read + // the same path, and the removal says exactly what went wrong with it + lpath := lock_path() + warn('database lock already exists (${lpath})') + advise("if you're sure a package manager is not already running, you can remove it") + if os.geteuid() != 0 { + advise('run as root to remove it') + return + } + if ui.noyes('do you want to remove ${lpath}?') { + os.rm(lpath) or { report('failed to remove ${lpath}: ${err.msg()}') } + } +} + +// init_repo registers one sync db under its name and mirrors; the arch comes +// from the config, so the parameter is named a to keep the global visible +// the handle parameter of the three functions here is spelled +// `mut handle alpm.Handle`, which is already the caller's pointer: spelled +// `mut handle &alpm.Handle` the same body hands libalpm a pointer one level +// off, and alpm_db_update crashes on it (tried for the review's sake, and +// caught by test_sync_stamp_keeps_an_old_server_time_fresh). leave it +fn init_repo(mut handle alpm.Handle, repo string, servers []string, a string, usage alpm.DBUsage) !&alpm.DB { + // the siglevel is the configured one (pacman's default without config): + // libalpm's own default is 0, which verifies nothing + db := handle.register_syncdb(repo, int(cfg_siglevel))! + for server in servers { + db.add_server(server.replace('$repo', repo).replace('$arch', a))! + } + db.set_usage(usage)! + return db +} + +// a sync db counts as synced if its file is this recent, or if vpac updated +// the dbs this recently. libalpm sets the file time from the mirror, so an +// unchanged db keeps an old time, and the stamp covers that case +// (options :sync-age hours) sets it; 0 never calls a db stale +__global sync_max_age = i64(24 * 60 * 60) + +// sync_stamp is a function because db_path is configurable +fn sync_stamp() string { + return db_path + 'sync/vpac.synced' +} + +fn update_repos(mut handle alpm.Handle, force bool) ! { + // one db_update call: libalpm itself updates only the stale dbs, and + // "up to date" (returned as 1) is an answer, not an error. whatever it + // did, the dbs are known current now, so the stamp is written + handle.db_update(handle.get_syncdbs()!, force)! + // the stamp is what every later freshness check reads: when it cannot + // be written, the dbs count stale again next time — said, not hidden + os.write_file(sync_stamp(), '') or { + warn('could not write the sync stamp ${sync_stamp()}: ${err.msg()}') + } +} + +// stale_sync_dbs lists the sync dbs not synced within sync_max_age. a sync +// db listing that fails is said: an empty answer would read as 'fresh +// enough', and it never was +fn stale_sync_dbs(handle &alpm.Handle) []string { + dbs := handle.get_syncdbs() or { + warn('could not list the sync databases: ${err.msg()}') + return []string{} + } + stamp := if os.exists(sync_stamp()) { os.file_last_mod_unix(sync_stamp()) } else { i64(0) } + now := time.now().unix() + mut stale := []string{} + for db in dbs.dbs() { + name := db.get_name() + file := '${db_path}sync/${name}.db' + file_time := if os.exists(file) { os.file_last_mod_unix(file) } else { i64(0) } + newest := if stamp > file_time { stamp } else { file_time } + if sync_max_age > 0 && now - newest > sync_max_age { + stale << name + } + } + return stale +} + +// check_sync_fresh asks whether to update the sync dbs when any are stale. +// only root can update them, so anyone else gets the warning and carries on, +// and so does a --print preview, which changes nothing. the warning goes to +// stderr, so it stays out of piped results +fn check_sync_fresh(mut ui TransUI, mut handle &alpm.Handle) ! { + stale := stale_sync_dbs(handle) + if stale.len == 0 { + return + } + ui.pause() + warn('sync databases not synced in the last day: ${stale.join(', ')}') + if ui.print_only { + return + } + if os.geteuid() != 0 { + advise('run as root to update them') + return + } + if !ui.yesno('update them now?') { + return + } + check_ask_db_lock(mut ui) + update_repos(mut handle, false)! +} + +// init_repos registers the sync dbs the config defines, in the order the +// config lists them. the pkgbuild repo is not a sync db: it is built from, +// not downloaded. urls keep the $repo and $arch placeholders for libalpm to +// substitute +fn init_repos(mut handle alpm.Handle) ![]&alpm.DB { + mut dbs := []&alpm.DB{} + for repo in cfg_repos { + if repo.kind == 'pkgbuild' { + continue + } + dbs << init_repo(mut handle, repo.name, repo.servers, arch, repo.usage)! + } + return dbs +} diff --git a/src/db_check.v b/src/db_check.v new file mode 100644 index 0000000..4bacaaa --- /dev/null +++ b/src/db_check.v @@ -0,0 +1,157 @@ +module main + +import alpm +import os + +// pacman's -Dk and -Dkk, as vpac v -D and -DD. every check returns the +// errors it found, as pacman words them + +// db_local_files: every entry of the local db has its description and its +// file list. the other checks read both, so they wait for this one +fn db_local_files(dbpath string) ![]string { + local := '${dbpath}local' + mut out := []string{} + mut entries := os.ls(local) or { return error('could not open the local database ${local}: ${err.msg()}') } + entries.sort() + for entry in entries { + if entry == 'ALPM_DB_VERSION' { + continue + } + if !os.exists(os.join_path(local, entry, 'desc')) { + out << "'${entry}': description file is missing" + } + if !os.exists(os.join_path(local, entry, 'files')) { + out << "'${entry}': file list is missing" + } + } + return out +} + +// db_missing_deps: every dependency of the packages, satisfied among the +// packages themselves +fn db_missing_deps(handle &alpm.Handle, pkgs &alpm.List) []string { + mut out := []string{} + mut head := handle.checkdeps(unsafe { nil }, unsafe { nil }, pkgs, 0) + defer { + // the misses and the depends inside them are libalpm's to free; + // inner first, then the list, as pacman's check_db_missing_deps does + head.free_inner(fn (p voidptr) { + unsafe { + miss := &alpm.DepMissing(p) + miss.free() + } + }) + head.free() + } + // node walks to nil; the head is what lives + mut node := head + for node != unsafe { nil } { + miss := unsafe { &alpm.DepMissing(node.data) } + target := unsafe { cstring_to_vstring(miss.target) } + out << "missing '${miss.depend.compute_string()}' dependency for '${target}'" + node = node.next + } + return out +} + +// db_package_conflicts: no two installed packages conflict +fn db_package_conflicts(handle &alpm.Handle, pkgs &alpm.List) []string { + mut out := []string{} + mut head := handle.checkconflicts(pkgs) + defer { + // the conflicts are libalpm's to free, as pacman's + // check_db_local_package_conflicts does: inner, then the list + head.free_inner(fn (p voidptr) { + unsafe { + conf := &alpm.Conflict(p) + conf.free() + } + }) + head.free() + } + // node walks to nil; the head is what lives + mut node := head + for node != unsafe { nil } { + c := unsafe { &alpm.Conflict(node.data) } + out << "'${c.package1.get_name()}' conflicts with '${c.package2.get_name()}'" + node = node.next + } + return out +} + +// db_filelist_conflicts: no file, directories aside, belongs to two +// packages. every pair of owners is reported, in file order +fn db_filelist_conflicts(pkgs []&alpm.Package) []string { + // the owners of every file seen so far, so a third package that shares + // one clashes with both of the ones before it + mut owners := map[string][]string{} + mut clashes := map[string][]string{} + for pkg in pkgs { + for name in pkg.get_files().names() { + if name.ends_with('/') { + continue + } + for other in owners[name] { + clashes[name] << "file owned by '${other}' and '${pkg.get_name()}': '${name}'" + } + owners[name] << pkg.get_name() + } + } + mut names := clashes.keys() + names.sort() + mut out := []string{} + for name in names { + out << clashes[name] + } + return out +} + +// check_db_local is -Dk: the local db's files, then its packages' +// dependencies, conflicts and shared files. the checks accumulate: each one +// speaks for itself, and none hides the later ones behind an early return +fn check_db_local(handle &alpm.Handle, dbpath string) ![]string { + mut out := db_local_files(dbpath)! + mut pkgcache := local_pkgcache(handle)! + out << db_missing_deps(handle, pkgcache) + out << db_package_conflicts(handle, pkgcache) + out << db_filelist_conflicts(pkgcache.pkgs()) + return out +} + +// check_db_sync is -Dkk: every sync package's dependencies, satisfied +// across all the sync dbs. a cache that cannot be read has the db say so; +// the check does not quietly pretend that db has no packages +fn check_db_sync(handle &alpm.Handle) ![]string { + mut all := &alpm.List(unsafe { nil }) + mut syncdbs := handle.get_syncdbs()! + for db in syncdbs.dbs() { + // a cache that cannot be read is named, so its unchecked packages + // are not read as an empty db; an empty db is one, and checks fine + mut cache := pkgcache_of(handle, db) or { + warn('${err.msg()}: its packages are not checked') + continue + } + for pkg in cache.pkgs() { + all = all.add(pkg) + } + } + defer { all.free() } + return db_missing_deps(handle, all) +} + +// verify_db is vpac v -D (level 1) and -DD (level 2). each error is a failed +// target, so vpac exits 1 when there is any +fn verify_db(mut handle &alpm.Handle, level int) ! { + errors := if level >= 2 { + init_repos(mut handle)! + check_db_sync(handle)! + } else { + check_db_local(handle, db_path)! + } + for e in errors { + target_error(e) + } + if errors.len == 0 { + report('no database errors found') + } +} diff --git a/src/db_check_test.v b/src/db_check_test.v new file mode 100644 index 0000000..4af56e2 --- /dev/null +++ b/src/db_check_test.v @@ -0,0 +1,109 @@ +module main + +import alpm +import os +import testdb + +fn check_tmp(name string) !(string, string) { + tmp := os.join_path(os.vtmp_dir(), 'vpac_test_dbcheck_${name}_${os.getpid()}') + os.mkdir_all(os.join_path(tmp, 'root'))! + return tmp, os.join_path(tmp, 'db') + '/' +} + +fn test_db_local_files() ! { + tmp, dbpath := check_tmp('files')! + defer { os.rmdir_all(tmp) or {} } + testdb.write_local(dbpath, [testdb.Pkg{ + name: 'whole' + }])! + os.mkdir_all(os.join_path(dbpath, 'local', 'nodesc-1.0-1'))! + os.write_file(os.join_path(dbpath, 'local', 'nodesc-1.0-1', 'files'), '%FILES%\n\n')! + os.mkdir_all(os.join_path(dbpath, 'local', 'nofiles-1.0-1'))! + os.write_file(os.join_path(dbpath, 'local', 'nofiles-1.0-1', 'desc'), '%NAME%\nnofiles\n\n')! + assert db_local_files(dbpath)! == ["'nodesc-1.0-1': description file is missing", + "'nofiles-1.0-1': file list is missing"] +} + +fn test_check_db_local() ! { + tmp, dbpath := check_tmp('local')! + defer { os.rmdir_all(tmp) or {} } + testdb.write_local(dbpath, [ + testdb.Pkg{ + name: 'app' + depends: ['lib>=1.0', 'gone', 'old<1.0'] + files: ['usr/', 'usr/bin/', 'usr/bin/app', 'usr/share/shared'] + }, + testdb.Pkg{ + name: 'lib' + files: ['usr/', 'usr/lib/libx.so'] + }, + testdb.Pkg{ + name: 'old' + }, + testdb.Pkg{ + name: 'rival' + conflicts: ['app'] + files: ['usr/', 'usr/share/shared'] + }, + ])! + handle := alpm.initialize(os.join_path(tmp, 'root') + '/', dbpath)! + defer { handle.release() or {} } + errors := check_db_local(handle, dbpath)! + // a dependency nothing provides, one whose version does not match, two + // packages in conflict, and a file two packages own. the shared usr/ + // directory is no clash + assert "missing 'gone' dependency for 'app'" in errors + assert "missing 'old<1.0' dependency for 'app'" in errors + assert errors.any(it.contains('conflicts with') && it.contains("'app'") + && it.contains("'rival'")) + assert "file owned by 'app' and 'rival': 'usr/share/shared'" in errors + assert errors.len == 4, errors.str() +} + +fn test_check_db_local_clean() ! { + tmp, dbpath := check_tmp('clean')! + defer { os.rmdir_all(tmp) or {} } + testdb.write_local(dbpath, [ + testdb.Pkg{ + name: 'app' + depends: ['lib'] + files: ['usr/', 'usr/bin/app'] + }, + testdb.Pkg{ + name: 'lib' + files: ['usr/', 'usr/lib/lib.so'] + }, + ])! + handle := alpm.initialize(os.join_path(tmp, 'root') + '/', dbpath)! + defer { handle.release() or {} } + assert check_db_local(handle, dbpath)! == [] +} + +fn test_db_local_files_edges() ! { + tmp, dbpath := check_tmp('fileedges')! + defer { os.rmdir_all(tmp) or {} } + // a local db that is not there cannot be checked, which is an error + if got := db_local_files(dbpath) { + assert false, 'a missing local db checked clean: ${got}' + } else { + assert err.msg().contains('could not open the local database'), err.msg() + } + // the version file alone is an empty db: it is no package entry, and + // nothing is missing from it + testdb.write_local(dbpath, [])! + assert os.exists(os.join_path(dbpath, 'local', 'ALPM_DB_VERSION')) + assert db_local_files(dbpath)! == [] + // an entry with neither file is named for both, in order + os.mkdir_all(os.join_path(dbpath, 'local', 'bare-1.0-1'))! + assert db_local_files(dbpath)! == ["'bare-1.0-1': description file is missing", + "'bare-1.0-1': file list is missing"] + // whole entries beside it stay unnamed, and the order is the names' + testdb.write_local(dbpath, [testdb.Pkg{ + name: 'aaa' + }, testdb.Pkg{ + name: 'zzz' + }])! + os.rm(os.join_path(dbpath, 'local', 'zzz-1.0-1', 'files'))! + assert db_local_files(dbpath)! == ["'bare-1.0-1': description file is missing", + "'bare-1.0-1': file list is missing", "'zzz-1.0-1': file list is missing"] +} diff --git a/src/db_test.v b/src/db_test.v new file mode 100644 index 0000000..ceb225a --- /dev/null +++ b/src/db_test.v @@ -0,0 +1,66 @@ +module main + +import os + +// the signature level libalpm ends up with, read back through vpac's own +// setup. the alpm binding once wrote its SigLevel bits as masks where a V +// flag enum takes positions, and libalpm got 6 instead of 3075: no package +// or database signature was ever checked +fn test_default_siglevel_reaches_libalpm() ! { + // package | package_optional | database | database_optional + want := 1 | 2 | 1024 | 2048 + assert int(cfg_siglevel) == want + + old_db := db_path + tmp := os.join_path(os.vtmp_dir(), 'vpac_test_db_${os.getpid()}') + os.mkdir_all(os.join_path(tmp, 'local'))! + os.write_file(os.join_path(tmp, 'local', 'ALPM_DB_VERSION'), '9\n')! + db_path = tmp + '/' + defer { + db_path = old_db + os.rmdir_all(tmp) or {} + } + + ui := new_trans_ui() + mut handle := init_handle(ui)! + defer { handle.release() or {} } + default := handle.option_get_default_siglevel() or { return error('no default siglevel') } + local_file := handle.option_get_local_file_siglevel() or { return error('no local file siglevel') } + remote_file := handle.option_get_remote_file_siglevel() or { + return error('no remote file siglevel') + } + assert int(default) == want + assert int(local_file) == want + assert int(remote_file) == want + // the configured architecture is on the handle, so check_arch has one + // to compare a package's with + arches := handle.option_get_architectures() or { return error('no architectures') } + assert arches.count() == 1 + assert arches.get_str() or { '' } == arch + // and pacman's default hook dir, after libalpm's own + hooks := handle.option_get_hookdirs() or { return error('no hookdirs') } + assert hooks.count() == 2 + db := init_repo(mut handle, 'core', [], arch, .sync | .search)! + assert int(db.get_siglevel()) == want + // the usage the repo form gives reaches libalpm the same way + usage := db.get_usage() or { return error('no usage') } + assert int(usage) == 1 | 2 +} + +// every name the config's (network :siglevel ...) takes is libalpm's bit +fn test_siglevel_names() { + want := { + 'package': 1 << 0 + 'package_optional': 1 << 1 + 'package_marginal_ok': 1 << 2 + 'package_unknown_ok': 1 << 3 + 'database': 1 << 10 + 'database_optional': 1 << 11 + 'database_marginal_ok': 1 << 12 + 'database_unknown_ok': 1 << 13 + } + assert siglevel_names.len == want.len + for name, bit in want { + assert int(siglevel_names[name] or { panic(name) }) == bit, name + } +} diff --git a/src/deptest.v b/src/deptest.v new file mode 100644 index 0000000..4803879 --- /dev/null +++ b/src/deptest.v @@ -0,0 +1,45 @@ +module main + +import alpm + +struct ConfigDeptest { +pub mut: + show_help bool @[long: help; short: h] + query []string @[tail] +} + +// unsatisfied_deps are the dependencies no installed package satisfies, in +// the order and the spelling they were given +fn unsatisfied_deps(pkgcache &alpm.List, deps []string) []string { + mut out := []string{} + for dep in deps { + if _ := pkgcache.find_satisfier(dep) { + continue + } + out << dep + } + return out +} + +// deptest is pacman's -T: it prints every dependency no installed package +// satisfies and returns them; main exits 127 when there is one, the code +// makepkg tells apart from a failure. it changes nothing, so it needs no root +fn deptest(config ConfigDeptest) ![]string { + need_query(config.query, 'dependency')! + handle := alpm.initialize(root_path, db_path) or { return err } + defer { handle.release() or { went_on('release the alpm handle', err) } } + pkgcache := local_pkgcache(handle)! + missing := unsatisfied_deps(pkgcache, config.query) + if ipc_on() { + emit(UnsatisfiedEvent{ + deps: missing + }) + } else { + for dep in missing { + println(dep) + } + } + // the defer above releases the handle; a second release here would free + // it twice + return missing +} diff --git a/src/deptest_test.v b/src/deptest_test.v new file mode 100644 index 0000000..6c0b2dc --- /dev/null +++ b/src/deptest_test.v @@ -0,0 +1,81 @@ +module main + +import alpm +import os + +fn test_unsatisfied_deps() ! { + tmp := os.join_path(os.vtmp_dir(), 'vpac_test_deptest_${os.getpid()}') + local := os.join_path(tmp, 'db', 'local') + os.mkdir_all(os.join_path(tmp, 'root'))! + os.mkdir_all(local)! + defer { os.rmdir_all(tmp) or {} } + os.write_file(os.join_path(local, 'ALPM_DB_VERSION'), '9\n')! + for name, extra in { + 'zsh': '' + 'impl': '%PROVIDES%\nlibfoo.so=1-64\nvirtual\n\n' + } { + dir := os.join_path(local, '${name}-5.9-1') + os.mkdir_all(dir)! + os.write_file(os.join_path(dir, 'desc'), '%NAME%\n${name}\n\n%VERSION%\n5.9-1\n\n${extra}')! + } + handle := alpm.initialize(os.join_path(tmp, 'root') + '/', os.join_path(tmp, 'db') + '/')! + defer { handle.release() or {} } + pkgcache := handle.get_localdb()!.get_pkgcache() or { return error('empty db') } + + // names, versions and provisions, kept in the order and spelling given + assert unsatisfied_deps(pkgcache, ['zsh', 'zsh>=5', 'zsh=5.9-1', 'virtual', 'libfoo.so=1-64']) == [] + assert unsatisfied_deps(pkgcache, ['zsh<5', 'gone', 'zsh', 'zsh>6', 'libfoo.so=2']) == [ + 'zsh<5', + 'gone', + 'zsh>6', + 'libfoo.so=2', + ] + assert unsatisfied_deps(pkgcache, []) == [] +} + +// no dependency, no run: pacman's -T speaks up as well +fn test_deptest_needs_a_query() ! { + if _ := deptest(ConfigDeptest{}) { + assert false, 'an empty query ran' + } else { + assert err.msg().contains('no dependency'), err.msg() + } +} + +// deptest itself, against a db on disk: what it answers is what is missing, +// in the order asked, and the db is only read +fn test_deptest_reads_the_configured_db() ! { + tmp := os.join_path(os.vtmp_dir(), 'vpac_test_deptest_run_${os.getpid()}') + local := os.join_path(tmp, 'db', 'local') + os.mkdir_all(os.join_path(tmp, 'root'))! + os.mkdir_all(local)! + saved_root, saved_db := root_path, db_path + defer { + root_path, db_path = saved_root, saved_db + os.rmdir_all(tmp) or {} + } + root_path = os.join_path(tmp, 'root') + '/' + db_path = os.join_path(tmp, 'db') + '/' + os.write_file(os.join_path(local, 'ALPM_DB_VERSION'), '9\n')! + // nothing installed: every dependency is missing, and that is an + // answer, not an error + assert deptest(ConfigDeptest{ query: ['zsh', 'sh'] })! == ['zsh', 'sh'] + dir := os.join_path(local, 'zsh-5.9-1') + os.mkdir_all(dir)! + os.write_file(os.join_path(dir, 'desc'), '%NAME%\nzsh\n\n%VERSION%\n5.9-1\n\n%PROVIDES%\nsh\n\n')! + assert deptest(ConfigDeptest{ query: ['zsh', 'sh'] })! == [] + assert deptest(ConfigDeptest{ query: ['zsh>=6', 'sh', 'zsh=5.9-1', 'bash'] })! == [ + 'zsh>=6', + 'bash', + ] + // the same dependency asked twice is answered twice + assert deptest(ConfigDeptest{ query: ['bash', 'bash'] })! == ['bash', 'bash'] + // the run took no lock and left the db as it was + assert !os.exists(os.join_path(tmp, 'db', 'db.lck')) + assert os.ls(local)!.len == 2 + // a db that is not there is an error, not 'everything is missing' + db_path = os.join_path(tmp, 'nowhere') + '/' + if got := deptest(ConfigDeptest{ query: ['zsh'] }) { + assert false, 'a missing db answered ${got}' + } +} diff --git a/src/deptree.v b/src/deptree.v new file mode 100644 index 0000000..118f106 --- /dev/null +++ b/src/deptree.v @@ -0,0 +1,246 @@ +module main + +import alpm +import v.profiler + +// DepTracer walks the dependency graph straight from libalpm: the local db +// answers for installed packages and the sync dbs for everything else, so a +// package that is not installed can be traced too. the sync dbs are the +// lookup's: set up, and asked about their freshness, by the first target or +// dependency the installed packages do not answer, so a tree that stays +// among them never touches the sync dbs +struct DepTracer { +mut: + handle &alpm.Handle + ui &TransUI + lookup &InfoLookup + installed &alpm.List + sync_lost bool + reverse bool + optional bool + max_depth int + seen map[string]bool +} + +// TreeNode is one node of the tree: a resolved package, or a dependency that +// nothing provides (pkg is nil then, and dep is how it was asked for). tag +// marks an optional dependency +struct TreeNode { + pkg &alpm.Package = unsafe { nil } + dep string + tag string +} + +// TreeBranch is a node with the branches below it, as the tracer collects +// them. a package already expanded higher up is seen, and is not expanded +// again, which also stops cycles +struct TreeBranch { + node TreeNode + seen bool + children []TreeBranch +} + +// tree_label is the name and version, then the size: what the package takes +// on disk when installed, or what it downloads when it is only in the repos +fn tree_label(pkg &alpm.Package) string { + label := '${name_style(pkg.get_name())} ${version_style(pkg.get_version())}' + if pkg.get_origin() == .syncdb { + return '${label} (${profiler.format_bytes(u64(pkg.download_size()))} to download)' + } + return '${label} (${profiler.format_bytes(u64(pkg.get_isize()))})' +} + +// node_label is the line a node draws: the package's label, or the +// dependency nothing provides +fn node_label(node TreeNode) string { + if node.pkg == unsafe { nil } { + return old_style('${node.dep} (not found)') + node.tag + } + return tree_label(node.pkg) + node.tag +} + +fn (mut t DepTracer) dep_node(depstring string, tag string) TreeNode { + if pkg := t.installed.find_satisfier(depstring) { + return TreeNode{ + pkg: pkg + tag: tag + } + } + // sync dbs that cannot be set up are said once; the tree goes on with + // what is installed, and the dependency draws as not found + if !t.sync_lost { + t.lookup.sync_dbs(mut t.ui, mut t.handle) or { + warn('the sync databases are left out of the tree: ${err.msg()}') + t.sync_lost = true + } + } + if dbs := t.handle.get_syncdbs() { + if pkg := t.handle.find_dbs_satisfier(dbs, depstring) { + return TreeNode{ + pkg: pkg + tag: tag + } + } + } + return TreeNode{ + dep: depstring + tag: tag + } +} + +// children are what the package depends on, or with -r what requires it +fn (mut t DepTracer) children(pkg &alpm.Package) []TreeNode { + mut nodes := []TreeNode{} + if t.reverse { + for name in pkg.compute_required_by() { + if p := t.installed.pkg_find(name) { + nodes << TreeNode{ + pkg: p + } + } + } + return nodes + } + for dep in pkg.get_depends().depends() { + nodes << t.dep_node(dep.compute_string(), '') + } + if t.optional { + for dep in pkg.get_opt_depends().depends() { + nodes << t.dep_node(dep.compute_string(), ' (optional)') + } + } + return nodes +} + +// branches collects the tree below nodes, depth first: a package is +// expanded the first time it appears, down to the max depth, and later +// appearances are marked seen +fn (mut t DepTracer) branches(nodes []TreeNode, depth int) []TreeBranch { + mut out := []TreeBranch{} + for node in nodes { + if node.pkg == unsafe { nil } { + out << TreeBranch{ + node: node + } + continue + } + name := node.pkg.get_name() + if t.seen[name] { + out << TreeBranch{ + node: node + seen: true + } + continue + } + t.seen[name] = true + out << TreeBranch{ + node: node + children: if t.max_depth == 0 || depth < t.max_depth { + t.branches(t.children(node.pkg), depth + 1) + } else { + []TreeBranch{} + } + } + } + return out +} + +// tree_item is a branch as a frontend gets it, plain +fn tree_item(b TreeBranch) TreeItem { + optional := b.node.tag != '' + if b.node.pkg == unsafe { nil } { + return TreeItem{ + name: b.node.dep + optional: optional + } + } + return TreeItem{ + name: b.node.pkg.get_name() + version: b.node.pkg.get_version() + found: true + optional: optional + seen: b.seen + children: b.children.map(tree_item(it)) + } +} + +// print_branches draws the branch for each node, then the ones below it +fn print_branches(branches []TreeBranch, prefix string) { + for i, b in branches { + last := i == branches.len - 1 + branch := branch_style(if last { '└── ' } else { '├── ' }) + println(prefix + branch + node_label(b.node) + if b.seen { ' (seen)' } else { '' }) + print_branches(b.children, prefix + branch_style(if last { ' ' } else { '│ ' })) + } +} + +fn tree(config ConfigTree) ! { + need_query(config.query, 'package')! + mut ui := new_trans_ui(noconfirm: config.noconfirm) + mut handle := init_handle(ui)! + defer { handle.release() or { went_on('release the alpm handle', err) } } + defer { ui.stop() } + + // the roots are found as info finds its targets: installed first, then + // the sync dbs, a repo/ prefix scoping the search. the lookup sets the + // sync dbs up when a target or a dependency first needs them + mut lookup := InfoLookup{ + installed: local_pkgcache(handle)! + } + // a dependency several sync packages provide is drawn with the first, as + // pactree draws it: libalpm's provider question is answered silently + // there. the flag rides the whole walk, and lands false again on the way + // out, the scope the way walk_upgrade_deps keeps its own + ui.walking = true + defer { ui.walking = false } + mut installed := local_pkgcache(handle)! + + for i, target in config.query { + // one target that resolves to nothing does not take the rest of + // them down with it + root := lookup.find(mut ui, mut handle, target) or { + target_error(err.msg()) + continue + } + + // the blank line between trees is a terminal's frame; under ipc each + // tree leaves as its own event, and a stray line on stdout is not + // something a structured reader asked for + if i > 0 && !ipc_on() { + println('') + } + mut t := DepTracer{ + handle: handle + ui: ui + lookup: &lookup + installed: installed + reverse: config.reverse + optional: config.optional + max_depth: config.depth + } + t.seen[root.get_name()] = true + branches := t.branches(t.children(root), 1) + if ipc_on() { + emit(TreeEvent{ + reverse: config.reverse + root: TreeItem{ + name: root.get_name() + version: root.get_version() + found: true + children: branches.map(tree_item(it)) + } + }) + continue + } + println(tree_label(root)) + if branches.len == 0 { + if config.reverse { + println('nothing requires it') + } else { + println('no dependencies') + } + continue + } + print_branches(branches, '') + } +} diff --git a/src/fields.v b/src/fields.v new file mode 100644 index 0000000..88d0fec --- /dev/null +++ b/src/fields.v @@ -0,0 +1,234 @@ +@[has_globals] +module main + +import alpm +import time +import v.profiler + +// pkg_field_names are the fields info and search can show. both take the same +// names through --fields, so a field means the same thing in either command +const pkg_field_names = ['source', 'name', 'version', 'description', 'arch', 'url', 'licenses', + 'groups', 'provides', 'depends', 'optdepends', 'required_by', 'optional_for', 'conflicts', + 'replaces', 'size', 'packager', 'build_date', 'install_date', 'install_reason', 'install_script', + 'validation'] + +// search_default_fields are the columns of a search unless --fields says otherwise +const search_default_fields = ['source', 'name', 'version', 'description'] + +// cfg_search_fields are the columns the config asks for, (search :fields): +// search_default_fields unless it says otherwise. cfg_search_thold is the +// fuzzy search's threshold when --thold names none, (search :thold) +__global cfg_search_fields = ['source', 'name', 'version', 'description'] +__global cfg_search_thold = 0.9 +// what a mode starts from when its flag names nothing: (clean :keep), the +// versions of a package the cache keeps, and (tree :depth), how deep a tree +// is drawn; 0 leaves each to the mode +__global cfg_clean_keep = 0 +__global cfg_tree_depth = 0 + +// parse_fields reads --fields: nothing gives the defaults, 'all' every field, +// and anything else a comma separated list of field names +fn parse_fields(spec string, defaults []string) ![]string { + if spec == '' { + return defaults + } + if spec == 'all' { + return pkg_field_names + } + mut out := []string{} + for f in spec.split(',') { + name := f.trim_space() + if name !in pkg_field_names { + return error('unknown field "${name}", the fields are: ${pkg_field_names.join(', ')}') + } + out << name + } + return out +} + +// strs_text is a list of strings as one value: 'a, b'. the list arrives as a +// borrowed pointer, and strs() walks it without writing to it — the mut +// binding is only the mutable receiver the method spells, never a write to +// the C list +fn strs_text(list &alpm.List) string { + mut l := unsafe { list } + return l.strs().join(', ') +} + +// pkg_source is where an alpm package comes from: 'local', or the sync repo +fn pkg_source(pkg &alpm.Package) string { + origin := pkg.get_origin() + if origin == .file { + return 'file' + } + if origin != .syncdb { + return 'local' + } + db := pkg.get_db() or { return 'remote' } + return db.get_name() +} + +// pkg_field_items gives a field's value as separate items, for the fields that +// wrap their lists across lines. none for the fields whose value is one piece +// of text +fn pkg_field_items(pkg &alpm.Package, field string) ?[]string { + return match field { + 'licenses' { + pkg.get_licenses().strs() + } + 'groups' { + pkg.get_groups().strs() + } + 'provides' { + pkg.get_provides().depends().map(|d| d.compute_string()) + } + 'depends' { + pkg.get_depends().depends().map(|d| d.compute_string()) + } + // for a sync package libalpm looks through every sync db, as pacman -Sii + 'required_by' { + pkg.compute_required_by() + } + 'optional_for' { + pkg.compute_optional_for() + } + 'conflicts' { + pkg.get_conflicts().depends().map(|d| d.compute_string()) + } + 'replaces' { + pkg.get_replaces().depends().map(|d| d.compute_string()) + } + // every optional dependency of its own line: name, then its reason. + // an installed one carries pacman's [installed] mark + 'optdepends' { + pkg.get_opt_depends().depends().map(|d| optdepend_text(d, pkg)) + } + else { + none + } + } +} + +// optdepend_text is one line of the optional deps: name, then its reason. an +// installed package marks the deps the local db satisfies, as pacman's -Qi +// does; a sync package's list stays bare, like pacman's -Si +fn optdepend_text(d alpm.Depend, pkg &alpm.Package) string { + name := d.get_name() + desc := d.get_desc() + text := if desc == '' { name } else { '${name}: ${desc}' } + // the local cache hangs off the package's own db, no separate lookup + if pkg.get_origin() != .localdb { + return text + } + if db := pkg.get_db() { + if cache := db.get_pkgcache() { + if _ := cache.find_satisfier(d.compute_string()) { + return text + ' [installed]' + } + } + } + return text +} + +// pkg_field is one field of an alpm package. '' when the field does not apply, +// such as the install fields of a package that is not installed +fn pkg_field(pkg &alpm.Package, source string, field string) string { + sync := pkg.get_origin() == .syncdb + return match field { + 'source' { + source + } + 'name' { + pkg.get_name() + } + 'version' { + pkg.get_version() + } + 'description' { + pkg.get_desc() + } + 'arch' { + pkg.get_arch() + } + 'url' { + pkg.get_url() + } + 'licenses' { + strs_text(pkg.get_licenses()) + } + 'groups' { + strs_text(pkg.get_groups()) + } + 'provides' { + depends_text(pkg.get_provides()) + } + 'depends' { + depends_text(pkg.get_depends()) + } + // the mark rides along here too, since info's one-value fields and + // the listing columns of search read the same sense from the field: + // an installed package marks the deps the local db satisfies, as + // pacman's -Qi and -Ss listings do + 'optdepends' { + pkg.get_opt_depends().depends().map(|d| optdepend_text(d, pkg)).join(', ') + } + 'required_by' { + pkg.compute_required_by().join(', ') + } + 'optional_for' { + pkg.compute_optional_for().join(', ') + } + 'conflicts' { + depends_text(pkg.get_conflicts()) + } + 'replaces' { + depends_text(pkg.get_replaces()) + } + 'size' { + if sync { + profiler.format_bytes(u64(pkg.download_size())) + ' to download' + } else { + profiler.format_bytes(u64(pkg.get_isize())) + } + } + 'packager' { + pkg.get_packager() + } + 'build_date' { + time.unix(pkg.get_build_date()).format_ss() + } + 'install_date' { + if sync { '' } else { time.unix(pkg.get_install_date()).format_ss() } + } + 'install_reason' { + if sync { '' } else { reason_to_str(pkg.get_reason()) } + } + 'install_script' { + if sync { + '' + } else { + if pkg.has_scriptlet() { 'yes' } else { 'no' } + } + } + 'validation' { + validation_to_str(pkg.get_validation()) + } + else { + '' + } + } +} + +// pkgbuild_field is one field of a pkgbuild result. the rpc only knows some of +// them; the source is the repo's own name +fn pkgbuild_field(info PackagePkgbuild, field string, source string) string { + return match field { + 'source' { source } + 'name' { info.name } + 'version' { info.version } + 'description' { info.description } + 'url' { info.url } + 'packager' { info.maintainer or { '' } } + else { '' } + } +} diff --git a/src/files.v b/src/files.v new file mode 100644 index 0000000..44a9113 --- /dev/null +++ b/src/files.v @@ -0,0 +1,221 @@ +module main + +import alpm +import os + +fn files(config ConfigFiles) ! { + need_query(config.query, 'package')! + // no display: the ui is there for the did-you-mean question + mut ui := new_trans_ui(noconfirm: config.noconfirm) + defer { ui.stop() } + mut handle := alpm.initialize(root_path, db_path) or { return err } + defer { handle.release() or { went_on('release the alpm handle', err) } } + + mut pkgcache := local_pkgcache(handle)! + + for target in config.query { + mut name := local_target_name(target) + pkg := find_local_target(pkgcache, name, true) or { + name = did_you_mean(mut ui, name, pkg_names(pkgcache.pkgs())) or { + target_error(err.msg()) + continue + } + pkgcache.pkg_find(name) or { + target_error('unknown package: "${name}"') + continue + } + } + + paths := pkg_paths(pkg) + if ipc_on() { + emit(FilesEvent{ + package: pkg.get_name() + paths: paths + }) + continue + } + println(table_text(paths.map(row(name_style(pkg.get_name()), it)), '', ' ')) + } +} + +// pkg_paths are the files of an installed package, as paths under the root +fn pkg_paths(pkg &alpm.Package) []string { + return pkg.get_files().names().map('${root_path}${it}') +} + +// OwnerQuery is one target of owner mode, the way pacman's query_fileowner +// shapes it: rel is what the filelists are searched for, relative to the +// root — a directory spelled with its trailing slash, as filelists spell +// one — and dir says a directory is asked for +struct OwnerQuery { + rel string + dir bool +} + +// file_owners are the installed packages whose filelists hold q.rel, an +// exact match as alpm_filelist_contains makes it. a file has one owner and +// the walk stops there; a directory is shared, and every owner answers, as +// in pacman +fn file_owners(pkgs []&alpm.Package, q OwnerQuery) []&alpm.Package { + mut out := []&alpm.Package{} + for pkg in pkgs { + if pkg.get_files().contains(q.rel) != none { + out << pkg + if !q.dir { + break + } + } + } + return out +} + +// owner_query makes a target into the path the filelists are searched for, +// step for step as pacman's query_fileowner does: trailing slashes go, a +// missing bare name is looked up in PATH, the directory the name sits in is +// canonicalized while the name itself is not (a symlink is owned as the +// link, the way a filelist lists it), and a directory takes its slash back +fn owner_query(target string) !OwnerQuery { + if target == '' { + return error('empty path') + } + // a trailing slash would make lstat follow a directory symlink; it still + // asks for a directory, unless what is there says otherwise. / stays + mut p := target + mut dir := false + for p.len > 1 && p.ends_with('/') { + p = p[..p.len - 1] + dir = true + } + mut missing := false + mut kind := os.FileType.unknown + if st := os.lstat(p) { + kind = st.get_filetype() + } else { + missing = true + // not a path but a program name: the first PATH entry that holds it + if !p.contains('/') { + if found := search_path(p) { + p = found + missing = false + kind = (os.lstat(p) or { os.Stat{} }).get_filetype() + } + } + } + // a directory that cannot be resolved (it does not exist) leaves the + // path as named. pacman proceeds with it verbatim, which drops a relative + // one as outside the root; it is made absolute here instead, so a file a + // package lists under a since deleted directory still finds its owner + mut path := lrealpath(p) or { os.abs_path(p) } + // an existing path is a directory by what it is, a missing one by the + // slash it was given + dir = if missing { dir } else { kind == .directory } + if dir && !path.ends_with('/') { + path += '/' + } + // the root itself is the empty relative path: no package lists it, so it + // gets the plain no-owner answer, not the outside-root one. the real + // filespace '/' and a fake root '/x/' both end in their slash, which a + // missing root (no directory to say so) can lack + if path == root_path || path + '/' == root_path { + return OwnerQuery{ + dir: true + } + } + if !path.starts_with(root_path) { + return error('file is outside of root (${root_path}): ${path}') + } + return OwnerQuery{ + rel: path[root_path.len..] + dir: dir + } +} + +// search_path is pacman's own PATH search for a bare name: the first entry +// where the name exists at all, as lstat sees it — a link or a file that is +// not executable counts, as in pacman. an empty entry would be the working +// directory, which the caller has looked in already +fn search_path(name string) ?string { + for entry in os.getenv('PATH').split(':') { + if entry == '' { + continue + } + candidate := '${entry.trim_right('/')}/${name}' + if _ := os.lstat(candidate) { + return candidate + } + } + return none +} + +// lrealpath is pacman's: the directory a path names its file in is resolved +// (links, '.' and '..'), and the file itself is kept as named, so a link +// stays the link. a path ending in '.' or '..' names a directory, which is +// resolved whole. none when the directory does not resolve +fn lrealpath(path string) ?string { + base := path.all_after_last('/') + if base in ['.', '..'] { + return realpath(path) + } + slash := path.last_index('/') or { -1 } + dname := match slash { + -1 { '.' } + 0 { '/' } + else { path[..slash] } + } + resolved := realpath(dname)? + return if resolved.ends_with('/') { resolved + base } else { '${resolved}/${base}' } +} + +// realpath is realpath(3), none when it fails: os.real_path hands back its +// input on failure, which here must tell a resolved path from an unresolved +fn realpath(path string) ?string { + res := C.realpath(&char(path.str), unsafe { nil }) + if res == unsafe { nil } { + return none + } + out := unsafe { cstring_to_vstring(res) } + unsafe { C.free(res) } + return out +} + +fn owner(config ConfigOwner) ! { + need_query(config.query, 'file')! + mut handle := alpm.initialize(root_path, db_path) or { return err } + defer { handle.release() or { went_on('release the alpm handle', err) } } + + mut pkgcache := local_pkgcache(handle)! + + installed := pkgcache.pkgs() + for target in config.query { + q := owner_query(target) or { + target_error(err.msg()) + continue + } + path := '${root_path}${q.rel}' + owners := file_owners(installed, q) + if owners.len == 0 { + target_error('no package owns ${path}') + continue + } + // a directory's owners are one event each, the path repeated + if ipc_on() { + for pkg in owners { + emit(OwnerEvent{ + path: path + package: pkg.get_name() + version: pkg.get_version() + }) + } + continue + } + // pacman's -Qqo: the owners' names alone + if config.quiet { + for pkg in owners { + println(pkg.get_name()) + } + continue + } + println(table_text(owners.map(row(name_style(path), name_style(it.get_name()), + version_style(it.get_version()))), '', ' ')) + } +} diff --git a/src/files_test.v b/src/files_test.v new file mode 100644 index 0000000..4b1bc55 --- /dev/null +++ b/src/files_test.v @@ -0,0 +1,231 @@ +module main + +import alpm +import os +import testdb + +// OwnerFixture is a small filespace laid out the way a merged-/usr system +// lays one out, with the links pacman's owner query has to see through or +// keep: bin is a link to usr/bin, usr/bin/alias a link to a file beside it +struct OwnerFixture { + tmp string + real string // tmp with its own links resolved: what canonical paths start with +} + +fn owner_fixture(name string) !OwnerFixture { + tmp := os.join_path(os.vtmp_dir(), 'vpac_test_files_${name}_${os.getpid()}') + os.rmdir_all(tmp) or {} + for d in ['usr/bin', 'usr/share/doc', 'etc', 'nopath'] { + os.mkdir_all(os.join_path(tmp, d))! + } + os.write_file(os.join_path(tmp, 'usr/bin/tool'), '#!/bin/sh\n')! + os.chmod(os.join_path(tmp, 'usr/bin/tool'), 0o755)! + // pacman's PATH search takes any name that exists, executable or not + os.write_file(os.join_path(tmp, 'usr/bin/plain'), '')! + os.write_file(os.join_path(tmp, 'etc/fstab'), '')! + os.symlink('usr/bin', os.join_path(tmp, 'bin'))! + os.symlink('tool', os.join_path(tmp, 'usr/bin/alias'))! + os.symlink('nowhere', os.join_path(tmp, 'dangling'))! + return OwnerFixture{ + tmp: tmp + real: os.real_path(tmp) + } +} + +// in_fixture runs f with the root at the fixture, the working directory in +// it and PATH set; the globals and the process state are put back after +fn in_fixture(fx OwnerFixture, cwd string, path string, f fn () !) ! { + old_root := root_path + old_path := os.getenv('PATH') + old_cwd := os.getwd() + defer { + root_path = old_root + os.setenv('PATH', old_path, true) + os.chdir(old_cwd) or {} + } + root_path = fx.real + '/' + os.setenv('PATH', path, true) + os.chdir(os.join_path(fx.tmp, cwd))! + f()! +} + +fn oq(target string) !OwnerQuery { + return owner_query(target)! +} + +fn test_owner_query_resolves_the_directory_not_the_name() ! { + fx := owner_fixture('resolve')! + defer { os.rmdir_all(fx.tmp) or {} } + in_fixture(fx, '', '/nonexistent', fn [fx] () ! { + // a merged-/usr link in the directory part is seen through: pacman + // answers /bin/ls as /usr/bin/ls + assert oq('${fx.tmp}/bin/tool')! == OwnerQuery{'usr/bin/tool', false} + // '..' and '.' in the directory part are resolved too + assert oq('${fx.tmp}/usr/../usr/bin/tool')! == OwnerQuery{'usr/bin/tool', false} + assert oq('${fx.tmp}/usr/./bin/tool')! == OwnerQuery{'usr/bin/tool', false} + // the name itself stays the link: a filelist lists the link, and its + // owner is the answer, not the target's + assert oq('${fx.tmp}/usr/bin/alias')! == OwnerQuery{'usr/bin/alias', false} + assert oq('./usr/bin/alias')! == OwnerQuery{'usr/bin/alias', false} + assert oq('${fx.tmp}/bin/alias')! == OwnerQuery{'usr/bin/alias', false} + // a dangling link exists as itself + assert oq('dangling')! == OwnerQuery{'dangling', false} + // a relative path, through a link + assert oq('bin/tool')! == OwnerQuery{'usr/bin/tool', false} + })! +} + +fn test_owner_query_directories() ! { + fx := owner_fixture('dirs')! + defer { os.rmdir_all(fx.tmp) or {} } + in_fixture(fx, '', '/nonexistent', fn [fx] () ! { + // a directory is asked for with its trailing slash, as filelists + // spell one, given with slashes or not + assert oq('${fx.tmp}/usr/share/doc')! == OwnerQuery{'usr/share/doc/', true} + assert oq('${fx.tmp}/usr/share/doc///')! == OwnerQuery{'usr/share/doc/', true} + // a link to a directory is the link, even with a slash after it: the + // slash is dropped so lstat does not follow it, and what is there, + // a link, says it is no directory + assert oq('${fx.tmp}/bin')! == OwnerQuery{'bin', false} + assert oq('${fx.tmp}/bin/')! == OwnerQuery{'bin', false} + // a missing path is a directory by its slash alone + assert oq('${fx.tmp}/usr/share/gone/')! == OwnerQuery{'usr/share/gone/', true} + assert oq('${fx.tmp}/usr/share/gone')! == OwnerQuery{'usr/share/gone', false} + // a path ending in '.' or '..' is resolved whole + os.chdir(os.join_path(fx.tmp, 'usr/bin'))! + assert oq('.')! == OwnerQuery{'usr/bin/', true} + assert oq('..')! == OwnerQuery{'usr/', true} + assert oq('../bin/..')! == OwnerQuery{'usr/', true} + })! +} + +fn test_owner_query_bare_names() ! { + fx := owner_fixture('names')! + defer { os.rmdir_all(fx.tmp) or {} } + in_fixture(fx, 'etc', '/nonexistent::${fx.tmp}/bin/', fn [fx] () ! { + // a name the working directory holds is that file, not a command + assert oq('fstab')! == OwnerQuery{'etc/fstab', false} + // a name it lacks is looked up in PATH, empty entries and trailing + // slashes and all; the PATH entry's link is seen through + assert oq('tool')! == OwnerQuery{'usr/bin/tool', false} + // a PATH hit need not be executable, and a link found there stays + // the link + assert oq('plain')! == OwnerQuery{'usr/bin/plain', false} + assert oq('alias')! == OwnerQuery{'usr/bin/alias', false} + // a name found nowhere is the working directory's missing file, as + // in pacman, so a deleted file still finds the package that listed it + assert oq('nosuch')! == OwnerQuery{'etc/nosuch', false} + })! + in_fixture(fx, 'nopath', '', fn [fx] () ! { + // no PATH at all: the name stays in the working directory + assert oq('tool')! == OwnerQuery{'nopath/tool', false} + })! +} + +fn test_owner_query_unresolvable_directory() ! { + fx := owner_fixture('missing')! + defer { os.rmdir_all(fx.tmp) or {} } + in_fixture(fx, '', '/nonexistent', fn [fx] () ! { + // a directory that does not exist cannot be resolved: the path is + // made absolute as named, so it still answers inside the root + assert oq('${fx.tmp}/gone/dir/file')! == OwnerQuery{'gone/dir/file', false} + assert oq('gone/dir/file')! == OwnerQuery{'gone/dir/file', false} + assert oq('gone/../usr/bin/tool')! == OwnerQuery{'usr/bin/tool', false} + })! +} + +fn test_owner_query_root_and_outside() ! { + old := root_path + defer { root_path = old } + + root_path = '/' + // the root itself: no package lists it, but it is not outside the root + assert owner_query('/')!.rel == '' + assert owner_query('///')!.rel == '' + + fx := owner_fixture('root')! + defer { os.rmdir_all(fx.tmp) or {} } + root_path = fx.real + '/' + assert owner_query(fx.real)!.rel == '' + assert owner_query(fx.real + '/')!.rel == '' + // a fake root that does not exist (yet) is still the root itself + root_path = '/vpac-no-such-root-${os.getpid()}/sys/' + assert owner_query(root_path)!.rel == '' + assert owner_query(root_path.trim_right('/'))!.rel == '' + for outside in ['/vpac-no-such-root-${os.getpid()}/sysfoo', '/etc', '/'] { + if got := owner_query(outside) { + assert false, '${outside} is outside ${root_path}, yet gave "${got.rel}"' + } else { + assert err.msg().starts_with('file is outside of root') + } + } + + if _ := owner_query('') { + assert false, 'an empty path has no owner query' + } +} + +fn test_lrealpath() ! { + fx := owner_fixture('lrealpath')! + defer { os.rmdir_all(fx.tmp) or {} } + assert lrealpath('${fx.tmp}/bin/alias')? == '${fx.real}/usr/bin/alias' + // '..' after a link climbs from the link's target, as the kernel does: + // bin is usr/bin, so bin/.. is usr, not the fixture's top + assert lrealpath('${fx.tmp}/bin/..')? == '${fx.real}/usr' + assert lrealpath('/')? == '/' + assert lrealpath('/usr')? == '/usr' + if got := lrealpath('${fx.tmp}/gone/file') { + assert false, 'an unresolvable directory gave ${got}' + } + assert realpath(fx.tmp + '/bin')? == fx.real + '/usr/bin' + if got := realpath(fx.tmp + '/dangling') { + assert false, 'a dangling link resolved to ${got}' + } +} + +// write_owner_db lays out a local db whose packages own files +fn write_owner_db(dbpath string, pkgs map[string][]string) ! { + mut out := []testdb.Pkg{} + for name, files in pkgs { + out << testdb.Pkg{ + name: name + files: files + } + } + testdb.write_local(dbpath, out)! +} + +fn test_file_owners() ! { + tmp := os.join_path(os.vtmp_dir(), 'vpac_test_files_owners_${os.getpid()}') + os.mkdir_all(os.join_path(tmp, 'root'))! + defer { os.rmdir_all(tmp) or {} } + write_owner_db(os.join_path(tmp, 'db'), { + 'filesystem': ['bin', 'usr/', 'usr/bin/', 'usr/share/'] + 'coreutils': ['usr/', 'usr/bin/', 'usr/bin/ls', 'usr/share/', 'usr/share/man/'] + 'zsh': ['usr/', 'usr/bin/', 'usr/bin/zsh', 'usr/share/', 'usr/share/man/'] + })! + handle := alpm.initialize(os.join_path(tmp, 'root') + '/', os.join_path(tmp, 'db') + '/')! + defer { handle.release() or {} } + mut localdb := handle.get_localdb()! + mut pkgcache := localdb.get_pkgcache() or { return error('the test db has no pkgcache') } + pkgs := pkgcache.pkgs() + owners := fn [pkgs] (rel string, dir bool) []string { + mut names := file_owners(pkgs, OwnerQuery{rel, dir}).map(it.get_name()) + names.sort() + return names + } + + // a file has its one owner + assert owners('usr/bin/ls', false) == ['coreutils'] + // a directory answers every package that lists it + assert owners('usr/share/man/', true) == ['coreutils', 'zsh'] + assert owners('usr/bin/', true) == ['coreutils', 'filesystem', 'zsh'] + // the match is exact: a directory is not found without its slash, a file + // not with one, and a link is owned as itself + assert owners('usr/bin', false) == [] + assert owners('usr/bin/ls/', true) == [] + assert owners('bin', false) == ['filesystem'] + assert owners('usr/bin/nope', false) == [] + // the root itself is listed by nobody + assert owners('', true) == [] +} diff --git a/src/filter.v b/src/filter.v new file mode 100644 index 0000000..1868470 --- /dev/null +++ b/src/filter.v @@ -0,0 +1,48 @@ +module main + +import alpm + +// filter_sync_dbs loads the sync dbs when a filter compares the installed +// packages with them. the other filters need no sync data +fn filter_sync_dbs(mut ui TransUI, mut handle &alpm.Handle, config ConfigSearch) ![]&alpm.DB { + if !(config.foreign || config.native || config.upgrades) { + return []&alpm.DB{} + } + dbs := init_repos(mut handle)! + check_sync_fresh(mut ui, mut handle)! + return dbs +} + +// pkg_matches_filter is true when an installed package passes every filter +// given, the way pacman's -Q filters combine +fn pkg_matches_filter(pkg &alpm.Package, config ConfigSearch, sync_dbs []&alpm.DB) bool { + reason := pkg.get_reason() + if config.deps && reason != .depend { + return false + } + if config.explicit && reason != .explicit { + return false + } + // pacman's -Qt: required by nothing, and optional for nothing either; + // twice (-Qtt) what is only optionally required passes too + if config.unrequired && (pkg.compute_required_by().len > 0 + || (config.unrequired_level < 2 && pkg.compute_optional_for().len > 0)) { + return false + } + if config.foreign || config.native || config.upgrades { + sync_pkg := find_repo_pkg(sync_dbs, pkg.get_name()) + if config.foreign && sync_pkg != none { + return false + } + if config.native && sync_pkg == none { + return false + } + if config.upgrades { + newer := sync_pkg or { return false } + if alpm.pkg_vercmp(pkg.get_version(), newer.get_version()) >= 0 { + return false + } + } + } + return true +} diff --git a/src/find.v b/src/find.v new file mode 100644 index 0000000..d45d9a7 --- /dev/null +++ b/src/find.v @@ -0,0 +1,476 @@ +module main + +import alpm + +#include + +@[typedef] +struct C.regex_t {} + +fn C.regcomp(preg &C.regex_t, pattern &char, cflags int) int + +fn C.regexec(preg &C.regex_t, text &char, nmatch uint, pmatch voidptr, eflags int) int + +fn C.regfree(preg &C.regex_t) + +// FilePattern is one -x target, compiled as pacman's files_search compiles +// it: a posix extended expression, case ignored. a target with a slash is +// matched against whole paths, one without against file names alone +struct FilePattern { + re &C.regex_t + whole bool +} + +// find_rel is a target as the filelists spell paths, with no leading slash. +// as in pacman's files_search the slashes go while more than one byte is +// left, so a target of slashes alone stays '/' instead of becoming the empty +// expression that matches everything +fn find_rel(target string) string { + mut rel := target + for rel.len > 1 && rel[0] == `/` { + rel = rel[1..] + } + return rel +} + +fn file_pattern(target string) !FilePattern { + whole := target.contains('/') + text := if whole { find_rel(target) } else { target } + re := &C.regex_t{} + if C.regcomp(re, &char(text.str), C.REG_EXTENDED | C.REG_NOSUB | C.REG_ICASE | C.REG_NEWLINE) != 0 { + return error("invalid regular expression '${target}'") + } + return FilePattern{ + re: re + whole: whole + } +} + +// matches is whether a filelist entry answers the pattern. a file name is +// what follows the last slash: a directory has none, and is no match +fn (p FilePattern) matches(file string) bool { + text := if p.whole { file } else { file.all_after_last('/') } + if text == '' || (!p.whole && !file.contains('/')) { + return false + } + return C.regexec(p.re, &char(text.str), 0, unsafe { nil }, 0) == 0 +} + +// find is pacman's -F: the sync file databases, one .files file per repo. +// a path asks which repo package provides it, -l lists the files of a sync +// package, and -y refreshes the file dbs. the file dbs are the sync dbs read +// with a .files extension, so they live in their own handle. -r narrows the +// repos searched, while -y still refreshes all of them +fn find(config ConfigFind) ! { + need_query(config.query, 'a file path, or a package name with -l')! + + mut ui := new_trans_ui(noconfirm: config.noconfirm) + mut handle := find_handle(mut ui, config.refresh)! + defer { handle.release() or { went_on('release the alpm handle', err) } } + defer { ui.stop() } + + dbs := init_repos(mut handle)! + mut filter := []string{} + if config.repos != '' { + filter = config.repos.split(',').map(it.trim_space()).filter(it != '') + known := dbs.map(it.get_name()) + for name in filter { + if name !in known { + return error('not a sync repo: ${name} (these are: ${known.join(', ')})') + } + } + } + + if config.refresh { + check_ask_db_lock(mut ui) + mut s := ui.spinner(text: 'refreshing file databases') + s.start() + defer { stop_spinner(mut s) } + // "up to date" is libalpm saying nothing needed fetching: success + handle.db_update(handle.get_syncdbs()!, false) or { + return error('could not refresh the file databases: ${err.msg()}') + } + stop_spinner(mut s) + } + + if config.list { + find_list(mut ui, dbs, filter, config)! + return + } + find_owner(mut ui, dbs, filter, config)! +} + +// find_handle opens the handle the file dbs are read through, with their +// .files extension. a refresh downloads, as root: it takes the full handle, +// so the download runs as the sandbox user with the configured keyring, +// timeout and progress, as pacman -Fy's does. reading needs none of that, +// and keeps the lean handle of the read-only modes +fn find_handle(mut ui TransUI, refresh bool) !&alpm.Handle { + handle := if refresh { + init_handle(ui)! + } else { + alpm.initialize(root_path, db_path) or { return err } + } + handle.option_set_dbext('.files') or { + handle.release() or { went_on('release the alpm handle', err) } + return err + } + return handle +} + +// FileCache is one file db loaded: the db, for its name, and its package cache +struct FileCache { + db &alpm.DB + cache &alpm.List +} + +// find_caches loads the file db package caches the named repos ask for, with +// a name in the error, because a missing .files file is the one thing a first +// run trips over. an empty filter loads them all +fn find_caches(dbs []&alpm.DB, filter []string) ![]FileCache { + mut out := []FileCache{} + for db in dbs { + if filter.len > 0 && db.get_name() !in filter { + continue + } + // a db with no packages is an empty one, not a broken one + cache := pkgcache_of(db.get_handle(), db) or { + return error('the file database of ${db.get_name()} is missing or broken (${err.msg()}): refresh it with vpac f -y') + } + out << FileCache{ + db: db + cache: cache + } + } + return out +} + +// OwnerRef is one claim in the inverted file index: the repo whose file db +// listed the package, and the package by its place in the pkgs list the +// index walks (the list of packages itself is kept beside the index, so no +// pointer-bearing struct has to live in the map's cells) +struct OwnerRef { + repo string + pkg_i int +} + +// owner_index is the inverted file index of the caches: every file and +// directory the file dbs hold, naming the packages that carry them. each +// query path would otherwise walk every package and its C-side filelist +// once, which is what makes an owner search over a full file db crawl +// (alpm_filelist_contains is a scan per path). the keys carry no trailing +// slash — a directory entry and a file land under the same key — and the +// entries are ordered as the dbs and their packages come, the same order +// the walk reports them in +fn owner_index(caches []FileCache) OwnerIndex { + mut index := OwnerIndex{} + for fc in caches { + for pkg in fc.cache.pkgs() { + pkg_i := index.pkgs.len + index.pkgs << pkg + for name in pkg.get_files().names() { + key := name.trim_right('/') + if key == '' { + continue + } + index.refs[key] << OwnerRef{ + repo: fc.db.get_name() + pkg_i: pkg_i + } + } + } + } + return index +} + +// OwnerIndex is owner_index's answer, one value: a multi-path search takes it +// as it is built, where two variables filled after the fact would each be a +// copy of an index as large as every filelist of the dbs +struct OwnerIndex { +mut: + refs map[string][]OwnerRef + pkgs []&alpm.Package +} + +// owner_matches answers whether a file db entry provides the path. directories +// in a filelist carry a trailing slash, so the query, given without its own, +// is tried both ways +fn owner_matches(pkg &alpm.Package, rel string) bool { + return pkg.get_files().contains(rel) != none + || pkg.get_files().contains(rel + '/') != none +} + +// OwnerHit is one path's matches, kept so the results print only after the +// spinner stops. files are the paths that matched in each package: the path +// asked for, or every file an expression or a bare file name found — listed +// is set for those two, whose answer is the files and not only the packages +struct OwnerHit { + path string + listed bool +mut: + repos []string + pkgs []&alpm.Package + files [][]string +} + +// machine_line is pacman's --machinereadable line: repo, package, version +// and path, parted by NUL bytes +fn machine_line(repo string, pkg &alpm.Package, file string) string { + return [repo, pkg.get_name(), pkg.get_version(), file].join('\0') +} + +// find_owner answers which repo package provides a path, pacman's -Fo. the +// paths are relative to root, with or without the leading slash, and every +// path given is searched +fn find_owner(mut ui TransUI, dbs []&alpm.DB, filter []string, config ConfigFind) ! { + // -x: every expression compiles before anything is searched, and a bad + // one stops the run once all of them are named, as in pacman + mut patterns := []FilePattern{} + defer { + for p in patterns { + C.regfree(p.re) + } + } + if config.regex { + mut bad := 0 + for target in config.query { + patterns << file_pattern(target) or { + target_error(err.msg()) + bad++ + continue + } + } + if bad > 0 { + return + } + } + mut s := ui.spinner(text: 'searching file databases') + // quiet pipes its results: no spinner to glue a finished line onto them + spun := !config.quiet && !config.machinereadable + if spun { + s.start() + } + defer { stop_spinner(mut s) } + + caches := find_caches(dbs, filter)! + // many paths or one: building the index costs about one walk of every + // filelist, so a single-path search keeps its own walk, and a multi-path + // one pays once and does every later path by lookup. an expression is + // no key to look up: it walks + index := if config.query.len > 1 && !config.regex { + owner_index(caches) + } else { + OwnerIndex{} + } + mut hits := []OwnerHit{} + for qi, path in config.query { + // a target with no slash is a file name, looked for in every + // directory, as pacman's files_search does without -x too + by_name := !path.contains('/') + mut hit := OwnerHit{ + path: path + listed: config.regex || by_name + } + // the keys of the index and the entries of a filelist are matched + // without the query's trailing slash, the same in both branches below + rel := find_rel(path).trim_right('/') + if hit.listed { + for fc in caches { + for pkg in fc.cache.pkgs() { + names := pkg.get_files().names() + matched := if config.regex { + names.filter(patterns[qi].matches(it)) + } else { + // a directory entry ends in its slash and has no + // file name; an entry with no slash has no directory + names.filter(it.contains('/') && it.all_after_last('/') == path) + } + if matched.len > 0 { + hit.repos << fc.db.get_name() + hit.pkgs << pkg + hit.files << matched + } + } + } + hits << hit + continue + } + if rel == '' { + // reported with the misses, once the spinner is gone + hits << hit + continue + } + if config.query.len > 1 { + // alpm's own lookup matches the file and every directory on + // the way to it, which is what pacman's -Fo does; the index + // answers in the same order the walk would + for ref in index.refs[rel] { + hit.repos << ref.repo + hit.pkgs << index.pkgs[ref.pkg_i] + hit.files << [rel] + } + } else { + for fc in caches { + for pkg in fc.cache.pkgs() { + // alpm's own lookup matches the file and every directory + // on the way to it, which is what pacman's -Fo does + if owner_matches(pkg, rel) { + hit.repos << fc.db.get_name() + hit.pkgs << pkg + hit.files << [rel] + } + } + } + } + // a miss is kept too: it is reported in its place among the results + hits << hit + } + if spun { + end_frame(mut ui, mut s) + } + + for hit in hits { + if hit.pkgs.len == 0 { + if hit.path.trim_left('/') == '' && !hit.listed { + target_error('a file path is needed, not "${hit.path}"') + } else { + target_error('no package provides ${hit.path}') + } + } else if ipc_on() { + mut listing := Listing{ + fields: ['source', 'name', 'version', 'description'] + } + for i, pkg in hit.pkgs { + listing.add_pkg(pkg, hit.repos[i]) + } + emit(ProvidesEvent{ + path: hit.path + fields: listing.fields + entries: listing.entries + files: if hit.listed { hit.files } else { [][]string{} } + }) + } else if config.machinereadable { + // one line a matched path, for a program to split + for i, pkg in hit.pkgs { + for file in hit.files[i] { + println(machine_line(hit.repos[i], pkg, file)) + } + } + } else if config.quiet { + for i, pkg in hit.pkgs { + // pacman's -Fq prints repo/pkg, which is what tells packages + // that share a name apart + println('${hit.repos[i]}/${pkg.get_name()}') + } + } else if hit.listed { + // an expression or a file name finds many files: each is listed + // with its package + if config.query.len > 1 { + println(heading(hit.path)) + } + mut rows := []Row{} + for i, pkg in hit.pkgs { + for file in hit.files[i] { + rows << row(file, source_style(hit.repos[i]), name_style(pkg.get_name()), + version_style(pkg.get_version())) + } + } + println(table_text(rows, '', ' ')) + } else { + if config.query.len > 1 { + println(heading(hit.path)) + } + mut listing := Listing{ + fields: ['source', 'name', 'version', 'description'] + } + for i, pkg in hit.pkgs { + listing.add_pkg(pkg, hit.repos[i]) + } + listing.print() + } + } +} + +// find_list lists the files of a sync package from the file dbs, pacman's -Fl +fn find_list(mut ui TransUI, dbs []&alpm.DB, filter []string, config ConfigFind) ! { + mut s := ui.spinner(text: 'searching file databases') + // quiet pipes its results: no spinner to glue a finished line onto them + plain := config.quiet || config.machinereadable + spun := !plain + if spun { + s.start() + } + defer { stop_spinner(mut s) } + + caches := find_caches(dbs, filter)! + mut lines := []string{} + mut rows := []Row{} + mut missing := []string{} + for target in config.query { + // a target may name its repo, repo/package, as pacman's -Fl takes it + want_repo, name := if target.contains('/') { + target.all_before('/'), target.all_after('/') + } else { + '', target + } + if name == '' { + missing << target + continue + } + // the package the caches hold, or the miss it is: pkg keeps the nil + // answer as none instead of a sentinel &alpm.Package + mut pkg := ?&alpm.Package(none) + mut repo := '' + for fc in caches { + if want_repo != '' && fc.db.get_name() != want_repo { + continue + } + if p := fc.cache.pkg_find(name) { + pkg = ?&alpm.Package(p) + repo = fc.db.get_name() + break + } + } + if p := pkg { + // the miss is counted, the hit is listed; under ipc it leaves as + // soon as it is collected, like find_owner's answers do + if ipc_on() { + emit(FilesEvent{ + package: p.get_name() + repo: repo + paths: p.get_files().names() + }) + continue + } + for file in p.get_files().names() { + // quiet is pacman's -Flq: the file paths alone, with no package + // name, so a file two packages hold is listed twice; the form's + // help says 'repo/pkg for paths, file paths for -l' + if config.machinereadable { + lines << machine_line(repo, p, file) + } else if config.quiet { + lines << file + } else { + // pacman's dump_file_list: the package, then the path + rows << row(name_style(p.get_name()), file) + } + } + } else { + // no cache holds it: the miss is named once the listing is out + missing << target + } + } + if spun { + end_frame(mut ui, mut s) + } + if plain && lines.len > 0 { + println(lines.join('\n')) + } else if !plain && rows.len > 0 { + println(table_text(rows, ' ', ' ')) + } + // the misses follow the listing: written while the spinner ran, they + // would be drawn over + for name in missing { + target_error('"${name}" is not in the file databases: refresh them with vpac f -y') + } +} diff --git a/src/format.v b/src/format.v new file mode 100644 index 0000000..6f1606b --- /dev/null +++ b/src/format.v @@ -0,0 +1,261 @@ +module main + +import alpm +import term + +enum PrintMode { + default + minimal +} + +// Listing is a package list as search and orphans collect it: the fields +// asked for, and one entry per package with its values as plain text. print +// is the terminal's rendering of it +struct Listing { +pub mut: + mode PrintMode + fields []string + entries []ListEntry +} + +// ListEntry is one package of a listing: its name, and its value of every +// field of the listing, in their order. the quiet mode collects the name +// alone. group is the group a search -g member was listed for +struct ListEntry { + name string + values []string + group string @[omitempty] +} + +fn shown(value string) string { + return if value == '' { '-' } else { value } +} + +fn field_cell(field string, value string) Cell { + text := shown(value) + return match field { + 'name' { cell(name_style(text)) } + 'version' { cell(version_style(text)) } + 'source' { cell(source_style(text)) } + else { cell(text) } + } +} + +fn (mut l Listing) add_pkg(pkg &alpm.Package, source string) { + l.entries << ListEntry{ + name: pkg.get_name() + values: if l.mode == .minimal { + []string{} + } else { + l.fields.map(pkg_field(pkg, source, it)) + } + } +} + +// add_member adds a member of a group, search -g's +fn (mut l Listing) add_member(pkg &alpm.Package, source string, group string) { + l.add_pkg(pkg, source) + last := l.entries.pop() + l.entries << ListEntry{ + ...last + group: group + } +} + +fn (mut l Listing) add_pkgbuild(info PackagePkgbuild, source string) { + l.entries << ListEntry{ + name: info.name + values: if l.mode == .minimal { + []string{} + } else { + l.fields.map(pkgbuild_field(info, it, source)) + } + } +} + +// print renders the listing: the quiet mode one name a line, the default a +// table with every value styled by its field +fn (l Listing) print() { + if ipc_on() { + emit(ListingEvent{ + fields: if l.mode == .minimal { []string{} } else { l.fields } + entries: l.entries + }) + return + } + if l.mode == .minimal { + for e in l.entries { + println(e.name) + } + return + } + if l.entries.len > 0 { + // a listing of group members leads each row with its group, as + // pacman's -Sg does and as the ipc entries carry it + grouped := l.entries.any(it.group != '') + mut rows := []Row{} + for e in l.entries { + mut r := listing_row(l.fields, e) + if grouped { + r.cols.insert(0, cell(shown(e.group))) + } + rows << r + } + println(table_text(rows, '', ' ')) + } +} + +// print_found is the output of a listing whose collection failed part way: +// the quiet mode names what was found, the default prints nothing +fn (l Listing) print_found() { + if l.mode == .minimal { + l.print() + } +} + +fn listing_row(fields []string, e ListEntry) Row { + mut cols := []Cell{} + // an entry always carries one value per field of its listing; a mismatch + // shortens the row instead of tripping a bounds panic mid-render + for i, f in fields { + value := if i < e.values.len { e.values[i] } else { '' } + cols << field_cell(f, value) + } + return Row{ + cols: cols + } +} + +// reason_to_str is an install reason as a person reads it; reason_key is +// the same reason as a frontend reads it. every reason is named in both, no +// else: one libalpm adds fails the build here, rather than reading as +// 'unknown' in one spelling and something else in the other +pub fn reason_to_str(reason alpm.PackageReason) string { + return match reason { + .explicit { 'explicitly installed' } + .depend { 'installed as a dependency' } + .unknown { 'unknown' } + } +} + +pub fn validation_to_str(validation alpm.PkgValidation) string { + if validation == .unknown { + return 'unknown' + } + if validation == .none { + return 'none' + } + mut parts := []string{} + if int(validation) & int(alpm.PkgValidation.md5sum) != 0 { + parts << 'MD5 checksum' + } + if int(validation) & int(alpm.PkgValidation.sha256sum) != 0 { + parts << 'SHA-256 checksum' + } + if int(validation) & int(alpm.PkgValidation.signature) != 0 { + parts << 'signature' + } + return parts.join(', ') +} + +fn depends_text(deps &alpm.List) string { + mut d := unsafe { deps } + return d.depends().map(|dep| dep.compute_string()).join(', ') +} + +// InfoField is one field of a package as info collects it: the field's name, +// its value as one piece of text, and for the list fields the items that the +// terminal fills into lines +struct InfoField { + field string + value string + items []string +} + +// wrap_items fills as many items into one line as the width allows, joining +// with ', '. the cells are measured the way the table prints them, so styled +// and wide text wrap right +fn wrap_items(items []string, avail int) []string { + mut wide := avail + if wide < 1 { + wide = 1 + } + mut out := []string{} + mut line := '' + for item in items { + cand := if line == '' { item } else { '${line}, ${item}' } + if line != '' && visible_width(cand) > wide { + out << line + line = item + } else { + line = cand + } + } + if line != '' { + out << line + } + return if out.len == 0 { [''] } else { out } +} + +// info_fields collects what info shows of a package: the fields asked for, +// in order. an empty one is left out unless the fields were named on the +// command line (explicit) +fn info_fields(pkg &alpm.Package, fields []string, explicit bool) []InfoField { + source := pkg_source(pkg) + mut out := []InfoField{} + for f in fields { + value := pkg_field(pkg, source, f) + if value == '' && !explicit { + continue + } + out << InfoField{ + field: f + value: value + items: pkg_field_items(pkg, f) or { []string{} }.filter(it != '') + } + } + return out +} + +// the width info wraps to when the terminal tells none (output into a pipe +// or a file answers 0), and the narrowest a terminal may answer before its +// answer is taken for none: a column count that small is no real terminal +const info_fallback_cols = 80 +const info_min_cols = 9 + +// info_width is the width the info table wraps to for a terminal's columns +fn info_width(cols int) int { + return if cols >= info_min_cols { cols } else { info_fallback_cols } +} + +// info_table renders a package's fields. the list fields fill as many items +// per line as the terminal lets them, opt depends give every line its own, +// and the continuation lines are padded from the start to the value column +fn info_table(fields []InfoField) string { + if fields.len == 0 { + // the fields list is empty: nothing to show + return '' + } + cols, _ := term.get_terminal_size() + width := info_width(cols) + labels := fields.map(it.field.replace('_', ' ')) + mut label_w := 0 + for l in labels { + if l.len > label_w { + label_w = l.len + } + } + pad := ' '.repeat(label_w + 2) + avail := width - label_w - 2 + mut text := []string{} + for i, f in fields { + lines := if f.field == 'optdepends' { f.items } else { wrap_items(f.items, avail) } + first := if f.items.len == 0 { f.value } else { lines[0] } + text << '${heading(labels[i])}${' '.repeat(label_w - labels[i].len + 2)}${shown(first)}' + // an empty optdepends has no lines at all: -F all shows it as '-' + for line in lines#[1..] { + text << '${pad}${line}' + } + } + return text.join('\n') +} diff --git a/src/format_test.v b/src/format_test.v new file mode 100644 index 0000000..1501583 --- /dev/null +++ b/src/format_test.v @@ -0,0 +1,93 @@ +module main + +fn test_listing_renders_plain_entries() { + old := color_flag + defer { color_flag = old } + color_flag = 'never' + + // the entries are plain values; the render styles them, and shows an + // empty one as '-' + l := Listing{ + fields: ['name', 'version', 'description'] + entries: [ListEntry{ + name: 'zsh' + values: ['zsh', '5.9-1', ''] + }, ListEntry{ + name: 'bash' + values: ['bash', '5.2-1', 'shell'] + }] + } + assert table_text(l.entries.map(listing_row(l.fields, it)), '', ' ') == 'zsh 5.9-1 -\nbash 5.2-1 shell' +} + +// a row built against another listing's fields is shortened, not tripped +// over: an entry always carries one value per field, but a mismatched one +// fills its tail with empties and renders as '-' instead of panicking +fn test_listing_row_survives_a_short_entry() { + old := color_flag + defer { color_flag = old } + color_flag = 'never' + + r := listing_row(['name', 'version', 'description'], ListEntry{ + name: 'zsh' + values: ['zsh'] + }) + assert r.cols.len == 3 + assert table_text([r], '', ' ') == 'zsh - -' +} + +fn test_info_table() { + old := color_flag + defer { color_flag = old } + color_flag = 'never' + + assert info_table([]) == '' + // -F all on a package without optional deps: an optdepends with no + // items shows '-' and draws no continuation line + assert info_table([InfoField{ + field: 'optdepends' + }, InfoField{ + field: 'install_reason' + value: 'explicitly installed' + }]) == 'optdepends -\ninstall reason explicitly installed' + // optdepends puts each item on its own line, padded to the value column + assert info_table([InfoField{ + field: 'optdepends' + value: 'a, b' + items: ['a: x', 'b'] + }]) == 'optdepends a: x\n b' +} + +fn test_reason_spellings() ! { + // every reason in both spellings, and the frontend's key is a word mark + // reads back as that reason + for reason, want in { + alpm.PackageReason.explicit: ['explicit', 'explicitly installed'] + alpm.PackageReason.depend: ['depend', 'installed as a dependency'] + alpm.PackageReason.unknown: ['unknown', 'unknown'] + } { + assert [reason_key(reason), reason_to_str(reason)] == want + assert parse_reason(reason_key(reason))! == reason + } + for short, reason in { + 'e': alpm.PackageReason.explicit + 'dep': alpm.PackageReason.depend + 'dependency': alpm.PackageReason.depend + 'u': alpm.PackageReason.unknown + } { + assert parse_reason(short)! == reason + } + if _ := parse_reason('optional') { + assert false, 'an unknown reason was read' + } +} + +fn test_info_width() { + // no terminal (a pipe answers 0), or a size no terminal has: the fallback + assert info_width(0) == info_fallback_cols + assert info_width(-1) == info_fallback_cols + assert info_width(info_min_cols - 1) == info_fallback_cols + // a terminal's own width, from the narrowest one taken on + assert info_width(info_min_cols) == info_min_cols + assert info_width(132) == 132 +} diff --git a/src/frontend_test.v b/src/frontend_test.v new file mode 100644 index 0000000..010b9cc --- /dev/null +++ b/src/frontend_test.v @@ -0,0 +1,2339 @@ +module main + +import alpm +import crypto.sha256 +import json2 +import net.http +import net.urllib +import os +import testdb +import time + +#include + +fn C.__fpurge(stream &C.FILE) + +fn C.clearerr(stream &C.FILE) + +// the modes that commit a transaction, run whole under --ui ipc against a +// system that lives in a temp dir: a root, a local db, a sync repo served +// over file:// with real package archives, and a cache. libalpm does every +// step for real — download, validation, extraction, db writes — and the +// events the mode sends are read back line by line, as a frontend reads them + +// FakePkg is a package of the fake system: its files are paths under the +// root with their content +struct FakePkg { + name string + version string = '1.0-1' + reason int // installed ones: 0 explicit, 1 a dependency + depends []string + provides []string + groups []string + desc string + // changelog is the text the package carries as its changelog, if any + changelog string + files map[string]string +} + +// FakeSystem is the temp dir a run's whole system lives in +struct FakeSystem { + tmp string +} + +fn fake_system(name string) !FakeSystem { + tmp := os.join_path(os.vtmp_dir(), 'vpac_test_frontend_${name}_${os.getpid()}') + os.rmdir_all(tmp) or {} + // pkgbuild is the build dir the runs point pkgbuild_dir at: it is there, + // empty, so a mode that lists the builds reads a dir and not an error + for d in ['root', 'db/local', 'db/sync', 'cache', 'repo', 'gpg', 'build', 'dbsrc', 'pkgbuild'] { + os.mkdir_all(os.join_path(tmp, d))! + } + os.write_file(os.join_path(tmp, 'db/local/ALPM_DB_VERSION'), '9\n')! + return FakeSystem{ + tmp: tmp + } +} + +fn (s FakeSystem) path(rel string) string { + return os.join_path(s.tmp, rel) +} + +// file_list is a package's filelist the way libalpm keeps one: every +// directory on the way, with its slash, then the files, sorted +fn file_list(files map[string]string) []string { + mut set := map[string]bool{} + for f, _ in files { + parts := f.split('/') + for i in 1 .. parts.len { + set[parts[..i].join('/') + '/'] = true + } + set[f] = true + } + mut out := set.keys() + out.sort() + return out +} + +// install_local puts p in the local db as installed, its files on the root +fn (s FakeSystem) install_local(p FakePkg) ! { + // the db entry is the shared writer's; the changelog and the files on + // the root are this fake system's own + testdb.write_local(s.path('db'), [ + testdb.Pkg{ + name: p.name + version: p.version + reason: p.reason + depends: p.depends + provides: p.provides + groups: p.groups + files: file_list(p.files) + }, + ])! + if p.changelog != '' { + os.write_file(s.path('db/local/${p.name}-${p.version}/changelog'), p.changelog)! + } + for f, content in p.files { + os.mkdir_all(os.dir(s.path('root/${f}')))! + os.write_file(s.path('root/${f}'), content)! + } +} + +// publish builds an archive of each package into the repo, writes the repo's +// core.db naming them with their checksums, and puts that db in the sync dir +// fresh, so no mode asks to update it +fn (s FakeSystem) publish(pkgs []FakePkg) ! { + for p in pkgs { + src := s.path('build/${p.name}-${p.version}') + os.mkdir_all(src)! + mut info := 'pkgname = ${p.name}\npkgbase = ${p.name}\npkgver = ${p.version}\npkgdesc = ${p.name} for a test\narch = any\nsize = 0\n' + for d in p.depends { + info += 'depend = ${d}\n' + } + for v in p.provides { + info += 'provides = ${v}\n' + } + for g in p.groups { + info += 'group = ${g}\n' + } + if p.changelog != '' { + os.write_file(os.join_path(src, '.CHANGELOG'), p.changelog)! + } + os.write_file(os.join_path(src, '.PKGINFO'), info)! + for f, content in p.files { + os.mkdir_all(os.dir(os.join_path(src, f)))! + os.write_file(os.join_path(src, f), content)! + } + file := '${p.name}-${p.version}-any.pkg.tar' + tar(s.path('repo/${file}'), src, os.ls(src)!)! + text := if p.desc != '' { p.desc } else { '${p.name} for a test' } + mut desc := '%FILENAME%\n${file}\n\n%NAME%\n${p.name}\n\n%VERSION%\n${p.version}\n\n%DESC%\n${text}\n\n' + desc += '%CSIZE%\n${os.file_size(s.path('repo/${file}'))}\n\n%ISIZE%\n0\n\n' + desc += '%SHA256SUM%\n${sha256.hexhash(os.read_file(s.path('repo/${file}'))!)}\n\n%ARCH%\nany\n\n' + if p.depends.len > 0 { + desc += '%DEPENDS%\n${p.depends.join('\n')}\n\n' + } + if p.provides.len > 0 { + desc += '%PROVIDES%\n${p.provides.join('\n')}\n\n' + } + if p.groups.len > 0 { + desc += '%GROUPS%\n${p.groups.join('\n')}\n\n' + } + os.mkdir_all(s.path('dbsrc/${p.name}-${p.version}'))! + os.write_file(s.path('dbsrc/${p.name}-${p.version}/desc'), desc)! + } + tar(s.path('repo/core.db'), s.path('dbsrc'), os.ls(s.path('dbsrc'))!)! + os.cp(s.path('repo/core.db'), s.path('db/sync/core.db'))! + // the file db beside it, the way a repo serves one: each entry's desc and + // its file list. it stays on the server until a find -y fetches it + for p in pkgs { + entry := s.path('filessrc/${p.name}-${p.version}') + os.mkdir_all(entry)! + os.cp(s.path('dbsrc/${p.name}-${p.version}/desc'), os.join_path(entry, 'desc'))! + os.write_file(os.join_path(entry, 'files'), '%FILES%\n${file_list(p.files).join('\n')}\n\n')! + } + tar(s.path('repo/core.files'), s.path('filessrc'), os.ls(s.path('filessrc'))!)! +} + +fn tar(out string, dir string, entries []string) ! { + mut args := ['tar', '-cf', out, '-C', dir] + args << entries + res := os.exec(args) + if res.exit_code != 0 { + return error('tar failed: ${res.output}') + } +} + +// installed is the local db's name to version, read the way the next +// command would read it: a fresh handle +fn (s FakeSystem) installed() !map[string]string { + handle := alpm.initialize(s.path('root') + '/', s.path('db') + '/')! + defer { handle.release() or {} } + // an empty db is no packages; one that cannot be read is an error, not + // 'nothing installed' (pkgcache_of tells the two apart by libalpm's errno) + mut cache := local_pkgcache(handle)! + mut out := map[string]string{} + for p in cache.pkgs() { + out[p.get_name()] = p.get_version() + } + return out +} + +fn (s FakeSystem) reason_of(name string) !alpm.PackageReason { + handle := alpm.initialize(s.path('root') + '/', s.path('db') + '/')! + defer { handle.release() or {} } + return (handle.find_local_pkg(name) or { return error('${name} is not installed') }).get_reason() +} + +// FrontendRun is what a mode sent on the channel, decoded, and the error it +// returned ('' when it returned none) +struct FrontendRun { + events []map[string]json2.Any + err string + // stdout is what reached fd 1 itself, beside the channel + stdout string + // failed is how many targets this run reported bad, main's exit status + // counting them + failed int +} + +fn (r FrontendRun) of(kind string) []map[string]json2.Any { + return r.events.filter(it['type'] or { json2.Any('') }.str() == kind) +} + +// done is the run's one done event; it fails when there is not exactly one +fn (r FrontendRun) done() !map[string]json2.Any { + dones := r.of('done') + if dones.len != 1 { + return error('${dones.len} done events in ${r.events.map(it['type'] or { json2.Any('') }.str())}') + } + return dones[0] +} + +fn sorted_strs(v json2.Any) []string { + mut out := v.as_array().map(it.str()) + out.sort() + return out +} + +// run runs a mode on the system the way a frontend runs vpac: --ui ipc, the +// events on a channel (a file here), the answers on stdin. the config is +// aimed at the system — its root and dbs, its cache, its keyring dir, its +// repo over file:// — and put back at its defaults after, with the ui +fn (s FakeSystem) run(stdin string, mode fn () !) !FrontendRun { + return s.run_ui('ipc', stdin, mode) +} + +// run_ui is run with the ui kind given: 'tty' runs the mode as a terminal +// sees it, with no channel, its output read back from fd 1 +fn (s FakeSystem) run_ui(kind string, stdin string, mode fn () !) !FrontendRun { + chan_path := s.path('channel') + out_path := s.path('stdout') + mut out_file := os.create(out_path)! + saved_out := C.dup(1) + if saved_out < 0 { + return error('could not save stdout') + } + in_path := s.path('stdin') + os.write_file(in_path, stdin)! + mut chan_file := os.create(chan_path)! + mut in_file := os.open(in_path)! + saved_in := C.dup(0) + if saved_in < 0 { + return error('could not save stdin') + } + saved_kind, saved_color, saved_fd := ui_kind, color_flag, ipc_fd + // a process-wide count, as main reads it at the end of its one run: each + // run here starts from none, and puts the count back after + saved_failed := failed_targets + failed_targets = 0 + defer { + failed_targets = saved_failed + } + reset_config() + root_path = s.path('root') + '/' + db_path = s.path('db') + '/' + cfg_cachedirs = [s.path('cache') + '/'] + cfg_gpgdir = s.path('gpg') + '/' + // the machine's own hooks stay out of a fake system's transactions + cfg_hookdirs = []string{} + // the sandbox user need not exist where the tests run + download_user = '' + // the pkgbuild builds are the system's own too: never the ones in the + // home of whoever runs the tests, which a clean would otherwise look at + pkgbuild_dir = s.path('pkgbuild') + cfg_repos = [CfgRepo{ + name: 'core' + kind: 'sync' + servers: ['file://' + s.path('repo')] + }] + ui_kind = kind + color_flag = 'never' + ipc_fd = chan_file.fd + C.__fpurge(C.stdin) + C.clearerr(C.stdin) + C.dup2(in_file.fd, 0) + C.fflush(C.stdout) + C.dup2(out_file.fd, 1) + + mut msg := '' + mode() or { msg = err.msg() } + + C.fflush(C.stdout) + C.dup2(saved_out, 1) + C.close(saved_out) + out_file.close() + C.dup2(saved_in, 0) + C.close(saved_in) + C.__fpurge(C.stdin) + C.clearerr(C.stdin) + ui_kind, color_flag, ipc_fd = saved_kind, saved_color, saved_fd + reset_config() + in_file.close() + chan_file.close() + mut events := []map[string]json2.Any{} + for line in os.read_lines(chan_path)! { + // every line is one whole json object, or the channel is broken + events << json2.decode[json2.Any](line)!.as_map() + } + return FrontendRun{ + events: events + err: msg + stdout: os.read_file(out_path)! + failed: failed_targets + } +} + +fn (s FakeSystem) lock_left() bool { + return os.exists(s.path('db/db.lck')) +} + +fn foo(version string, content string) FakePkg { + return FakePkg{ + name: 'foo' + version: version + files: { + 'usr/share/foo/hello': content + } + } +} + +fn test_upgrade_ends_with_a_done_event() ! { + s := fake_system('upgrade')! + defer { os.rmdir_all(s.tmp) or {} } + s.install_local(foo('1.0-1', 'one'))! + s.publish([foo('2.0-1', 'two')])! + + run := s.run('', fn () ! { + upgrade(ConfigUpgrade{ noconfirm: true })! + })! + assert run.err == '' + done := run.done()! + assert done['action']!.str() == 'upgraded' + assert sorted_strs(done['packages']!) == ['foo'] + // the listing and the go-ahead came first, the done last of them + assert run.of('transaction').len == 1 + assert run.of('question').len == 1 + // and it happened: the new version is on the root and in the local db + assert os.read_file(s.path('root/usr/share/foo/hello'))! == 'two' + assert s.installed()! == { + 'foo': '2.0-1' + } + assert !s.lock_left() +} + +fn test_upgrade_with_nothing_to_do_sends_no_done() ! { + s := fake_system('uptodate')! + defer { os.rmdir_all(s.tmp) or {} } + s.install_local(foo('1.0-1', 'one'))! + s.publish([foo('1.0-1', 'one')])! + run := s.run('', fn () ! { + upgrade(ConfigUpgrade{ noconfirm: true })! + })! + assert run.err == '' + assert run.of('done').len == 0 + assert run.of('message').any(it['text']!.str() == 'nothing to upgrade.') +} + +fn test_install_ends_with_a_done_event() ! { + s := fake_system('install')! + defer { os.rmdir_all(s.tmp) or {} } + s.publish([ + FakePkg{ + name: 'bar' + depends: ['baz'] + files: { + 'usr/bin/bar': 'bar' + } + }, + FakePkg{ + name: 'baz' + files: { + 'usr/lib/libbaz': 'baz' + } + }, + ])! + run := s.run('', fn () ! { + install(ConfigInstall{ noconfirm: true, query: ['bar'] })! + })! + assert run.err == '' + done := run.done()! + assert done['action']!.str() == 'installed' + // the targets: the dependency comes along, but is not one + assert sorted_strs(done['packages']!) == ['bar'] + assert s.installed()! == { + 'bar': '1.0-1' + 'baz': '1.0-1' + } + assert s.reason_of('bar')! == .explicit + assert s.reason_of('baz')! == .depend + assert os.read_file(s.path('root/usr/bin/bar'))! == 'bar' + assert !s.lock_left() +} + +fn test_remove_ends_with_a_done_event() ! { + s := fake_system('remove')! + defer { os.rmdir_all(s.tmp) or {} } + s.install_local(foo('1.0-1', 'one'))! + run := s.run('', fn () ! { + remove(ConfigRemove{ noconfirm: true, query: ['foo'] })! + })! + assert run.err == '' + done := run.done()! + assert done['action']!.str() == 'removed' + assert sorted_strs(done['packages']!) == ['foo'] + assert s.installed()!.len == 0 + assert !os.exists(s.path('root/usr/share/foo/hello')) + assert !s.lock_left() +} + +fn test_autoremove_ends_with_a_done_event() ! { + s := fake_system('autoremove')! + defer { os.rmdir_all(s.tmp) or {} } + s.install_local(FakePkg{ + name: 'app' + depends: ['lib'] + })! + s.install_local(FakePkg{ + name: 'lib' + reason: 1 + })! + s.install_local(FakePkg{ + name: 'orphan' + reason: 1 + })! + // an orphan whose own dependency becomes unneeded with it: the recurse + // takes it along, and the done event names it with the rest + s.install_local(FakePkg{ + name: 'stray' + reason: 1 + depends: ['leaf'] + })! + s.install_local(FakePkg{ + name: 'leaf' + reason: 1 + })! + run := s.run('', fn () ! { + autoremove(ConfigAutoRemove{ noconfirm: true })! + })! + assert run.err == '' + done := run.done()! + assert done['action']!.str() == 'removed' + assert sorted_strs(done['packages']!) == ['leaf', 'orphan', 'stray'] + // the text line of a terminal is not sent beside it + assert !run.of('message').any(it['text']!.str().contains('orphaned packages')) + mut left := s.installed()!.keys() + left.sort() + assert left == ['app', 'lib'] + assert !s.lock_left() +} + +fn test_mark_ends_with_a_done_event() ! { + s := fake_system('mark')! + defer { os.rmdir_all(s.tmp) or {} } + s.install_local(foo('1.0-1', 'one'))! + run := s.run('', fn () ! { + mark(ConfigMark{ reason: 'd', query: ['foo'] })! + })! + assert run.err == '' + done := run.done()! + assert done['action']!.str() == 'marked' + assert done['reason']!.str() == 'depend' + assert sorted_strs(done['packages']!) == ['foo'] + assert s.reason_of('foo')! == .depend + assert !s.lock_left() +} + +fn test_declined_transaction_sends_no_done() ! { + s := fake_system('decline')! + defer { os.rmdir_all(s.tmp) or {} } + s.install_local(foo('1.0-1', 'one'))! + // the frontend says no to the go-ahead, question 1 + run := s.run('{"id": 1, "answer": false}\n', fn () ! { + remove(ConfigRemove{ query: ['foo'] })! + })! + assert run.err == '' + questions := run.of('question') + assert questions.len == 1 + assert questions[0]['question']!.str() == 'proceed' + assert run.of('done').len == 0 + // nothing changed, and the transaction let go of the lock + assert s.installed()! == { + 'foo': '1.0-1' + } + assert os.exists(s.path('root/usr/share/foo/hello')) + assert !s.lock_left() +} + +fn test_print_preview_sends_no_done() ! { + s := fake_system('preview')! + defer { os.rmdir_all(s.tmp) or {} } + s.install_local(foo('1.0-1', 'one'))! + s.publish([foo('2.0-1', 'two')])! + run := s.run('', fn () ! { + upgrade(ConfigUpgrade{ print_only: true })! + })! + assert run.err == '' + listing := run.of('transaction') + assert listing.len == 1 + assert listing[0]['preview']!.bool() + assert run.of('done').len == 0 + assert run.of('question').len == 0 + assert s.installed()! == { + 'foo': '1.0-1' + } + assert !s.lock_left() +} + +fn test_prepare_failure_sends_no_done_and_lets_go_of_the_lock() ! { + s := fake_system('prepare')! + defer { os.rmdir_all(s.tmp) or {} } + // a dependency no repo has: prepare fails, and says on what + s.publish([FakePkg{ + name: 'needy' + depends: ['nowhere'] + }])! + run := s.run('', fn () ! { + install(ConfigInstall{ noconfirm: true, query: ['needy'] })! + })! + assert run.err != '' + assert run.err.contains('nowhere'), run.err + assert run.of('done').len == 0 + assert s.installed()!.len == 0 + assert !s.lock_left() +} + +// an empty local db is a db with no packages, not a broken one: the modes +// that read it answer nothing found, as pacman does on a fresh root (the +// install above runs on one too) +fn test_an_empty_system_is_no_error() ! { + s := fake_system('empty')! + defer { os.rmdir_all(s.tmp) or {} } + s.publish([foo('1.0-1', 'one')])! + orphaned := s.run('', fn () ! { + orphans(ConfigOrphans{})! + })! + assert orphaned.err == '' + verified := s.run('', fn () ! { + verify(ConfigVerify{})! + })! + assert verified.err == '' + searched := s.run('', fn () ! { + search(ConfigSearch{ local: true, query: ['foo'] })! + })! + assert searched.err == '' + // a name to act on is unknown, said so, not a database failure: mark + // and remove report it as the bad target it is + marked := s.run('', fn () ! { + mark(ConfigMark{ reason: 'd', query: ['foo'] })! + })! + assert marked.err == '' && marked.failed == 1 + assert marked.of('error')[0]['msg']!.str().contains('unknown package') + assert !s.lock_left() + removed := s.run('', fn () ! { + remove(ConfigRemove{ noconfirm: true, query: ['foo'] })! + })! + assert removed.err == '' && removed.failed == 1 + assert removed.of('error')[0]['msg']!.str().contains('unknown package') + assert !s.lock_left() +} + +fn test_pkgcache_of() ! { + s := fake_system('pkgcache')! + defer { os.rmdir_all(s.tmp) or {} } + handle := alpm.initialize(s.path('root') + '/', s.path('db') + '/')! + // empty: a nil list, which reads as no packages + mut empty := local_pkgcache(handle)! + assert empty == unsafe { nil } + assert empty.pkgs().len == 0 + assert empty.pkg_find('foo') == none + handle.release()! + + s.install_local(foo('1.0-1', 'one'))! + full_handle := alpm.initialize(s.path('root') + '/', s.path('db') + '/')! + mut full := local_pkgcache(full_handle)! + assert full.pkgs().map(it.get_name()) == ['foo'] + full_handle.release()! + + if os.geteuid() == 0 { + // root reads the unreadable dir below anyway + return + } + // a db libalpm cannot read is still an error, with libalpm's reason. the + // handle opens first: libalpm reads the packages only when asked + broken := alpm.initialize(s.path('root') + '/', s.path('db') + '/')! + defer { broken.release() or {} } + os.chmod(s.path('db/local'), 0)! + defer { os.chmod(s.path('db/local'), 0o755) or {} } + if mut got := local_pkgcache(broken) { + assert false, 'an unreadable local db read as ${got.pkgs().len} packages' + } else { + assert err.msg().starts_with('could not read the packages of local: '), err.msg() + } +} + +fn test_url_install_through_the_install_handle() ! { + s := fake_system('url')! + defer { os.rmdir_all(s.tmp) or {} } + s.publish([foo('1.0-1', 'one')])! + url := 'file://' + s.path('repo/foo-1.0-1-any.pkg.tar') + run := s.run('', fn [url] () ! { + install(ConfigInstall{ noconfirm: true, query: [url] })! + })! + assert run.err == '' + done := run.done()! + assert done['action']!.str() == 'installed' + assert sorted_strs(done['packages']!) == ['foo'] + assert os.read_file(s.path('root/usr/share/foo/hello'))! == 'one' + // the trust warning is a warning to a frontend, and comes before the + // download it is about, which comes before the transaction + kinds := run.events.map(it['type']!.str()) + warned := run.events.filter(it['type']!.str() == 'message' + && it['text']!.str().contains('signature')) + assert warned.len == 1 + assert warned[0]['warning']!.bool() + first_warning := run.events.index(warned[0]) + first_download := kinds.index('download') + assert first_download > first_warning + assert kinds.index('transaction') > first_download + assert run.of('download').any(it['file']!.str().starts_with('foo-1.0-1-any.pkg.tar')) + // the archive was fetched into the cache, as libalpm fetches one + assert os.exists(s.path('cache/foo-1.0-1-any.pkg.tar')) + assert !s.lock_left() +} + +fn test_url_install_refuses_a_bad_signature_beside_it() ! { + s := fake_system('urlsig')! + defer { os.rmdir_all(s.tmp) or {} } + s.publish([foo('1.0-1', 'one')])! + // the server offers a signature that does not hold: libalpm fetches it + // with the archive, and the load at the remote level reads it + os.write_file(s.path('repo/foo-1.0-1-any.pkg.tar.sig'), 'not a signature')! + url := 'file://' + s.path('repo/foo-1.0-1-any.pkg.tar') + run := s.run('', fn [url] () ! { + install(ConfigInstall{ noconfirm: true, query: [url] })! + })! + assert run.err.contains('signature'), run.err + assert run.of('done').len == 0 + assert s.installed()!.len == 0 + assert !os.exists(s.path('root/usr/share/foo/hello')) + assert !s.lock_left() +} + +fn test_find_refresh_takes_the_full_handle() ! { + s := fake_system('findhandle')! + defer { os.rmdir_all(s.tmp) or {} } + run := s.run('', fn () ! { + // a sandbox user that exists wherever the test runs: this one + download_user = current_user()! + mut ui := new_trans_ui() + refresh := find_handle(mut ui, true)! + defer { refresh.release() or {} } + // the refresh downloads as the sandbox user, from the file dbs + if refresh.option_get_sandboxuser() != download_user { + return error('a refresh downloads as "${refresh.option_get_sandboxuser()}"') + } + if refresh.option_get_dbext() != '.files' { + return error('a refresh reads ${refresh.option_get_dbext()}') + } + read := find_handle(mut ui, false)! + defer { read.release() or {} } + if read.option_get_dbext() != '.files' { + return error('a lookup reads ${read.option_get_dbext()}') + } + })! + assert run.err == '' +} + +fn test_find_refresh_fetches_the_file_dbs() ! { + s := fake_system('findrefresh')! + defer { os.rmdir_all(s.tmp) or {} } + s.publish([FakePkg{ + name: 'bar' + files: { + 'usr/bin/bar': 'bar' + } + }])! + assert !os.exists(s.path('db/sync/core.files')) + run := s.run('', fn () ! { + find(ConfigFind{ refresh: true, query: ['/usr/bin/bar'] })! + })! + assert run.err == '' + // fetched through the full handle: its progress reached the frontend + assert run.of('download').any(it['file']!.str().starts_with('core.files')) + assert os.exists(s.path('db/sync/core.files')) + // and read: the repo package that provides the path + provides := run.of('provides') + assert provides.len == 1 + entries := provides[0]['entries']!.as_array() + assert entries.len == 1 + assert entries[0].as_map()['name']!.str() == 'bar' +} + +// verify_lines runs the fast check on the system, with the NoExtract globs +// given, and returns its report: the lines, and how many packages are bad +fn (s FakeSystem) verify_lines(noextract []string) !([]string, int) { + run := s.run('', fn [noextract] () ! { + cfg_noextract = noextract.clone() + verify(ConfigVerify{})! + })! + if run.err != '' { + return error(run.err) + } + events := run.of('verify') + if events.len != 1 { + return error('${events.len} verify events') + } + lines := events[0]['lines']!.as_array().map(it.as_map()['text']!.str()) + return lines, events[0]['bad']!.int() +} + +fn test_verify_fast_check_as_pacman() ! { + s := fake_system('verify')! + defer { os.rmdir_all(s.tmp) or {} } + s.install_local(FakePkg{ + name: 'docs' + files: { + 'usr/bin/docs': 'docs' + 'usr/share/man/man1/docs.1': 'man' + 'usr/share/doc/docs/README.md': 'readme' + } + })! + s.install_local(FakePkg{ + name: 'dirs' + files: { + 'usr/share/dirs/a': 'a' + } + })! + s.install_local(FakePkg{ + name: 'intact' + files: { + 'usr/lib/intact': 'ok' + } + })! + // a man page NoExtract kept off the disk, and a binary that is gone + os.rm(s.path('root/usr/share/man/man1/docs.1'))! + os.rm(s.path('root/usr/bin/docs'))! + // a directory the db lists, now a link to one elsewhere: the file in it + // is still reached through the link + os.mkdir_all(s.path('root/usr/share/elsewhere'))! + os.write_file(s.path('root/usr/share/elsewhere/a'), 'a')! + os.rmdir_all(s.path('root/usr/share/dirs'))! + os.symlink('elsewhere', s.path('root/usr/share/dirs'))! + + lines, bad := s.verify_lines(['usr/share/man/*'])! + root := s.path('root') + assert bad == 2, lines.str() + assert 'docs: missing ${root}/usr/bin/docs' in lines + assert 'dirs: ${root}/usr/share/dirs/ is a link, the db says a directory' in lines + // NoExtract's file is not missing, and not said at all, as in pacman + assert !lines.any(it.contains('docs.1')), lines.str() + assert !lines.any(it.starts_with('intact')), lines.str() + assert lines.len == 2, lines.str() + + // without the NoExtract glob, the man page is missing like any file + lines2, bad2 := s.verify_lines([])! + assert bad2 == 2 + assert 'docs: missing ${root}/usr/share/man/man1/docs.1' in lines2 +} + +fn test_verify_fast_check_lets_links_be() ! { + s := fake_system('verifylinks')! + defer { os.rmdir_all(s.tmp) or {} } + s.install_local(FakePkg{ + name: 'linked' + files: { + 'usr/lib/libx.so.1': 'lib' + 'usr/lib/libx.so': '' + 'usr/lib/dangling': '' + } + })! + // a package's file may be a link, to its neighbour or to nothing at all + os.rm(s.path('root/usr/lib/libx.so'))! + os.symlink('libx.so.1', s.path('root/usr/lib/libx.so'))! + os.rm(s.path('root/usr/lib/dangling'))! + os.symlink('nowhere', s.path('root/usr/lib/dangling'))! + lines, bad := s.verify_lines([])! + assert bad == 0, lines.str() + assert lines.len == 0 +} + +// fake_pkg is a FakePkg with no files, at a version, with its dependencies +fn fake_pkg(name string, version string, depends []string) FakePkg { + return FakePkg{ + name: name + version: version + depends: depends + } +} + +fn test_install_upgrades_the_whole_outdated_closure() ! { + // app needs mid, mid needs low: both installed, both outdated. the walk + // is the dependency closure, not one level of it + s := fake_system('closure')! + defer { os.rmdir_all(s.tmp) or {} } + s.install_local(FakePkg{ ...fake_pkg('mid', '1.0-1', ['low']), reason: 1 })! + s.install_local(FakePkg{ ...fake_pkg('low', '1.0-1', []), reason: 1 })! + s.publish([fake_pkg('app', '1.0-1', ['mid']), fake_pkg('mid', '2.0-1', ['low']), + fake_pkg('low', '2.0-1', [])])! + run := s.run('', fn () ! { + install(ConfigInstall{ noconfirm: true, query: ['app'] })! + })! + assert run.err == '' + assert s.installed()! == { + 'app': '1.0-1' + 'mid': '2.0-1' + 'low': '2.0-1' + } + // what came along is still a dependency + assert s.reason_of('mid')! == .depend +} + +fn test_install_no_upgrade_deps_leaves_the_closure() ! { + s := fake_system('noclosure')! + defer { os.rmdir_all(s.tmp) or {} } + s.install_local(FakePkg{ ...fake_pkg('mid', '1.0-1', ['low']), reason: 1 })! + s.install_local(FakePkg{ ...fake_pkg('low', '1.0-1', []), reason: 1 })! + s.publish([fake_pkg('app', '1.0-1', ['mid']), fake_pkg('mid', '2.0-1', ['low']), + fake_pkg('low', '2.0-1', [])])! + run := s.run('', fn () ! { + install(ConfigInstall{ noconfirm: true, no_upgrade_deps: true, query: ['app'] })! + })! + assert run.err == '' + assert s.installed()! == { + 'app': '1.0-1' + 'mid': '1.0-1' + 'low': '1.0-1' + } +} + +fn test_install_brings_along_what_it_would_break() ! { + // user needs lib below 2.0; installing lib 2.0 breaks it, so the repo's + // user, which takes the new lib, comes along in the same transaction + s := fake_system('broken')! + defer { os.rmdir_all(s.tmp) or {} } + s.install_local(fake_pkg('user', '1.0-1', ['lib<2.0']))! + s.install_local(FakePkg{ ...fake_pkg('lib', '1.0-1', []), reason: 1 })! + s.publish([fake_pkg('lib', '2.0-1', []), fake_pkg('user', '2.0-1', ['lib>=2.0'])])! + run := s.run('', fn () ! { + install(ConfigInstall{ noconfirm: true, query: ['lib'] })! + })! + assert run.err == '' + assert s.installed()! == { + 'lib': '2.0-1' + 'user': '2.0-1' + } + // the transaction listed it before the go-ahead + listing := run.of('transaction') + assert listing.len == 1 +} + +fn test_no_upgrade_deps_failure_says_what_breaks() ! { + // --no-upgrade-deps keeps an installed package that needs the old lib at + // its version: prepare fails on it, and the hint names the cause + s := fake_system('noupbreak')! + defer { os.rmdir_all(s.tmp) or {} } + s.install_local(fake_pkg('user', '1.0-1', ['lib<2.0']))! + s.install_local(FakePkg{ ...fake_pkg('lib', '1.0-1', []), reason: 1 })! + s.publish([fake_pkg('lib', '2.0-1', []), fake_pkg('user', '2.0-1', ['lib>=2.0'])])! + run := s.run('', fn () ! { + install(ConfigInstall{ noconfirm: true, no_upgrade_deps: true, query: ['lib'] })! + })! + lines := run.err.split('\n') + assert lines[0] == 'could not satisfy dependencies:', run.err + assert lines[1] == " lib breaks dependency 'lib<2.0' required by user", run.err + assert lines[2].starts_with('without --no-upgrade-deps, the installed packages this breaks are upgraded along'), run.err + assert s.installed()!['lib']! == '1.0-1' + assert !s.lock_left() +} + +fn test_no_upgrade_deps_still_takes_a_newer_dependency() ! { + // a target that needs a newer dependency than is installed gets it even + // under --no-upgrade-deps: libalpm's prepare pulls it in, which is why + // the hint never blames this case + s := fake_system('noupnewer')! + defer { os.rmdir_all(s.tmp) or {} } + s.install_local(FakePkg{ ...fake_pkg('lib', '1.0-1', []), reason: 1 })! + s.publish([fake_pkg('lib', '2.0-1', []), fake_pkg('app', '1.0-1', ['lib>=2.0'])])! + run := s.run('', fn () ! { + install(ConfigInstall{ noconfirm: true, no_upgrade_deps: true, query: ['app'] })! + })! + assert run.err == '' + assert s.installed()! == { + 'app': '1.0-1' + 'lib': '2.0-1' + } +} + +fn test_mark_failure_names_what_was_set() ! { + if os.geteuid() == 0 { + // root writes the read-only desc below anyway + return + } + s := fake_system('markfail')! + defer { os.rmdir_all(s.tmp) or {} } + for name in ['aa', 'bb', 'cc'] { + s.install_local(fake_pkg(name, '1.0-1', []))! + } + // bb's db entry cannot be written: its reason cannot change + os.chmod(s.path('db/local/bb-1.0-1/desc'), 0o444)! + run := s.run('', fn () ! { + mark(ConfigMark{ reason: 'd', query: ['aa', 'bb', 'cc'] })! + })! + assert run.err.starts_with('could not set the install reason of bb: '), run.err + assert run.err.ends_with(' (already set: aa)'), run.err + assert run.of('done').len == 0 + // what the error says is what the db holds + assert s.reason_of('aa')! == .depend + assert s.reason_of('bb')! == .explicit + assert s.reason_of('cc')! == .explicit + assert !s.lock_left() +} + +fn test_provider_question_under_a_frontend() ! { + // app needs a shell two repo packages provide: libalpm asks which, the + // frontend gets the providers as the choices, and the answer is what is + // installed + s := fake_system('provider')! + defer { os.rmdir_all(s.tmp) or {} } + s.publish([fake_pkg('app', '1.0-1', ['shell']), + FakePkg{ ...fake_pkg('bash', '1.0-1', []), provides: ['shell'] }, + FakePkg{ ...fake_pkg('dash', '1.0-1', []), provides: ['shell'] }])! + // the frontend picks the second provider of question 1 + run := s.run('{"id": 1, "answer": 1}\n{"id": 2, "answer": true}\n', fn () ! { + install(ConfigInstall{ query: ['app'] })! + })! + assert run.err == '' + questions := run.of('question') + assert questions.len == 2 + assert questions[0]['question']!.str() == 'choose' + assert questions[0]['msg']!.str() == '2 providers for shell' + choices := questions[0]['choices']!.as_array().map(it.str()) + assert choices.len == 2 + assert choices.all(it.starts_with('core/') && it.ends_with(' 1.0-1')) + chosen := choices[1].all_after('/').all_before(' ') + assert questions[1]['question']!.str() == 'proceed' + installed := s.installed()! + assert chosen in installed && installed.len == 2, installed.str() + assert 'app' in installed +} + +fn test_provider_rows_number_the_choices() ! { + s := fake_system('providerrows')! + defer { os.rmdir_all(s.tmp) or {} } + s.publish([fake_pkg('bash', '1.0-1', []), fake_pkg('dash', '2.0-1', [])])! + run := s.run('', fn () ! { + mut handle := init_handle(new_trans_ui())! + defer { handle.release() or {} } + dbs := init_repos(mut handle)! + bash := dbs[0].get_pkg('bash') or { return error('no bash') } + dash := dbs[0].get_pkg('dash') or { return error('no dash') } + if provider_choice(dash) != 'core/dash 2.0-1' { + return error('choice ${provider_choice(dash)}') + } + text := table_text(provider_rows([bash, dash]), '', ' ') + if text.split('\n').map(it.trim_space()) != ['1) core/bash 1.0-1', '2) core/dash 2.0-1'] { + return error('rows ${text}') + } + })! + assert run.err == '' +} + +fn test_fuzzy_search_lists_name_matches_then_desc_matches_once() ! { + s := fake_system('fuzzy')! + defer { os.rmdir_all(s.tmp) or {} } + s.publish([FakePkg{ + ...fake_pkg('zsh', '1.0-1', []) + desc: 'zsh is the z shell' + }, FakePkg{ + ...fake_pkg('fish', '1.0-1', []) + desc: 'a friendly shell, much like zsh' + }, FakePkg{ + ...fake_pkg('bash', '1.0-1', []) + desc: 'the gnu bourne again shell' + }, FakePkg{ + ...fake_pkg('zsh-doc', '1.0-1', []) + desc: 'documentation' + }])! + run := s.run('', fn () ! { + mut handle := init_handle(new_trans_ui())! + defer { handle.release() or {} } + dbs := init_repos(mut handle)! + mut cache := pkgcache_of(handle, dbs[0])! + got := build_matches(cache.pkgs(), ConfigSearch{ + fuzzy: true + thold: 0.9 + query: ['zsh'] + }).map(it.get_name()) + // zsh by its name (and not again for its desc), then fish by its desc; + // bash matches neither, and zsh-doc's name is too far at this threshold + if got != ['zsh', 'fish'] { + return error('matched ${got}') + } + })! + assert run.err == '' +} + +// with_file_dbs publishes the packages with their file db already synced, +// as a find without -y reads it +fn with_file_dbs(name string, pkgs []FakePkg) !FakeSystem { + s := fake_system(name)! + s.publish(pkgs)! + os.cp(s.path('repo/core.files'), s.path('db/sync/core.files'))! + return s +} + +// providers_of maps each path a find answered to the packages it named +fn providers_of(run FrontendRun) map[string][]string { + mut out := map[string][]string{} + for e in run.of('provides') { + mut names := e['entries']!.as_array().map(it.as_map()['name']!.str()) + names.sort() + out[e['path']!.str()] = names + } + return out +} + +fn test_find_owner_index_answers_as_the_walk() ! { + s := with_file_dbs('findowner', [ + FakePkg{ + name: 'bar' + files: { + 'usr/bin/bar': 'bar' + } + }, + FakePkg{ + name: 'baz' + files: { + 'usr/bin/baz': 'baz' + 'usr/lib/libbaz': 'lib' + } + }, + ])! + defer { os.rmdir_all(s.tmp) or {} } + paths := ['/usr/bin/bar', 'usr/lib/libbaz', '/usr/bin/', '/usr/bin', '/nope'] + // several paths at once go through the index + many := s.run('', fn [paths] () ! { + find(ConfigFind{ query: paths })! + })! + got := providers_of(many) + assert got['/usr/bin/bar']! == ['bar'] + assert got['usr/lib/libbaz']! == ['baz'] + // a directory is every package's that carries it, with or without its slash + assert got['/usr/bin/']! == ['bar', 'baz'] + assert got['/usr/bin']! == ['bar', 'baz'] + // the miss is named, as a target error, and counted + misses := many.of('error').filter(it['target']!.bool()) + assert misses.len == 1 + assert misses[0]['msg']!.str() == 'no package provides /nope' + // one path at a time walks the filelists: the same answers + for p in paths { + one := s.run('', fn [p] () ! { + find(ConfigFind{ query: [p] })! + })! + assert providers_of(one)[p] or { []string{} } == got[p] or { []string{} }, p + } +} + +fn test_find_list_names_its_misses() ! { + s := with_file_dbs('findlist', [FakePkg{ + name: 'bar' + files: { + 'usr/bin/bar': 'bar' + } + }])! + defer { os.rmdir_all(s.tmp) or {} } + run := s.run('', fn () ! { + find(ConfigFind{ list: true, query: ['bar', 'nothere'] })! + })! + lists := run.of('files') + assert lists.len == 1 + assert lists[0]['package']!.str() == 'bar' + assert lists[0]['repo']!.str() == 'core' + assert lists[0]['paths']!.as_array().map(it.str()) == ['usr/', 'usr/bin/', 'usr/bin/bar'] + misses := run.of('error').filter(it['target']!.bool()) + assert misses.len == 1 + assert misses[0]['msg']!.str().contains('nothere') +} + +// stale_after_update updates the sync dbs over file:// and answers what +// the freshness check then calls stale +fn (s FakeSystem) stale_after_update() !FrontendRun { + return s.run('', fn () ! { + mut handle := init_handle(new_trans_ui())! + defer { handle.release() or {} } + init_repos(mut handle)! + update_repos(mut handle, false)! + stale := stale_sync_dbs(handle) + report('stale: ${stale.join(',')}') + })! +} + +fn test_sync_stamp_keeps_an_old_server_time_fresh() ! { + s := fake_system('stamp')! + defer { os.rmdir_all(s.tmp) or {} } + s.publish([foo('1.0-1', 'one')])! + // the server's db has not changed in two days: libalpm gives the copy + // it downloads the server's time, so only vpac's stamp says it is current + two_days_ago := time.now().unix() - 2 * sync_max_age + os.utime(s.path('repo/core.db'), two_days_ago, two_days_ago)! + os.rm(s.path('db/sync/core.db'))! + run := s.stale_after_update()! + assert run.err == '' + assert os.file_last_mod_unix(s.path('db/sync/core.db')) <= two_days_ago + 1 + assert os.exists(s.path('db/sync/vpac.synced')) + assert run.of('message').any(it['text']!.str() == 'stale: ') +} + +fn test_sync_stamp_that_cannot_be_written_is_said() ! { + s := fake_system('stampfail')! + defer { os.rmdir_all(s.tmp) or {} } + s.publish([foo('1.0-1', 'one')])! + two_days_ago := time.now().unix() - 2 * sync_max_age + os.utime(s.path('repo/core.db'), two_days_ago, two_days_ago)! + os.rm(s.path('db/sync/core.db'))! + // the stamp's path leads nowhere writable: its write fails, and no stamp + // is there after it (a link into a directory that does not exist) + os.symlink(s.path('nowhere/vpac.synced'), s.path('db/sync/vpac.synced'))! + run := s.stale_after_update()! + assert run.err == '' + // said, as a warning naming the stamp, and the db counts stale again — + // touching the db instead would feed libalpm's If-Modified-Since a lie + warned := run.of('message').filter(it['warning'] or { json2.Any(false) }.bool()) + assert warned.len == 1 + assert warned[0]['text']!.str().starts_with('could not write the sync stamp ${s.path('db/sync/vpac.synced')}') + assert run.of('message').any(it['text']!.str() == 'stale: core') +} + +fn test_libalpm_warnings_reach_the_frontend() ! { + // installing what is installed already: libalpm says so at warning level, + // through its log callback alone, as pacman prints it + s := fake_system('alpmwarn')! + defer { os.rmdir_all(s.tmp) or {} } + s.install_local(foo('1.0-1', 'one'))! + s.publish([foo('1.0-1', 'one')])! + run := s.run('', fn () ! { + install(ConfigInstall{ noconfirm: true, query: ['foo'] })! + })! + assert run.err == '' + said := run.of('message').filter(it['text']!.str() == 'foo-1.0-1 is up to date -- reinstalling') + assert said.len == 1, run.of('message').str() + assert said[0]['warning']!.bool() + assert 'error' !in said[0] +} + +fn test_libalpm_errors_reach_the_frontend() ! { + // a corrupt mtree: libalpm's error names the file and libarchive's reason + s := fake_system('alpmerror')! + defer { os.rmdir_all(s.tmp) or {} } + s.install_local(foo('1.0-1', 'one'))! + res := os.exec(['sh', '-c', 'printf "#mtree\\n./a type=file\\n" | gzip | head -c 15 > "\$0"', + s.path('db/local/foo-1.0-1/mtree')]) + assert res.exit_code == 0, res.output + run := s.run('', fn () ! { + verify(ConfigVerify{ + checksums_level: 2 + })! + })! + assert run.err == '' + errors := run.of('message').filter(it['error'] or { json2.Any(false) }.bool()) + assert errors.len == 1, run.of('message').str() + assert errors[0]['text']!.str() == 'error while reading file ${s.path('db/local/foo-1.0-1/mtree')}: truncated gzip input' + assert errors[0]['warning']!.bool() +} + +fn test_mark_and_verify_skip_what_names_nothing() ! { + s := fake_system('skiptargets')! + defer { os.rmdir_all(s.tmp) or {} } + s.install_local(foo('1.0-1', 'one'))! + s.install_local(FakePkg{ + ...fake_pkg('impl', '1.0-1', []) + provides: ['virt=2'] + })! + // a bad target is reported and counted; the good ones are still marked + marked := s.run('', fn () ! { + mark(ConfigMark{ reason: 'd', query: ['nope', 'foo'] })! + })! + assert marked.err == '' && marked.failed == 1 + assert marked.of('done')[0]['packages']!.as_array().map(it.str()) == ['foo'] + // verify resolves a versioned name and a provision, as pacman's -Qk + // does, and names the target nothing answers + checked := s.run('', fn () ! { + verify(ConfigVerify{ query: ['foo>=1.0', 'virt', 'ghost'] })! + })! + assert checked.err == '', checked.err + assert checked.failed == 1 + assert target_errors(checked) == ['package "ghost" was not found'] + none_there := s.run('', fn () ! { + verify(ConfigVerify{ query: ['ghost'] })! + })! + assert none_there.err.contains('no one of the named packages'), none_there.err +} + +fn test_tree_of_several_targets_under_a_frontend() ! { + s := fake_system('tree')! + defer { os.rmdir_all(s.tmp) or {} } + s.publish([fake_pkg('app', '1.0-1', ['lib']), fake_pkg('lib', '1.0-1', [])])! + run := s.run('', fn () ! { + tree(ConfigTree{ query: ['app', 'lib', 'nope'] })! + })! + assert run.err == '' + // each tree is its own event, every channel line one json object, and + // nothing at all reaches stdout — the blank line between trees is a + // terminal's frame + trees := run.of('tree') + assert trees.len == 2 + assert trees[0]['root']!.as_map()['name']!.str() == 'app' + children := trees[0]['root']!.as_map()['children']!.as_array() + assert children.len == 1 && children[0].as_map()['name']!.str() == 'lib' + assert trees[1]['root']!.as_map()['name']!.str() == 'lib' + assert run.of('error').filter(it['target']!.bool()).len == 1 + assert run.stdout == '', run.stdout +} + +fn test_tree_leaves_the_sync_dbs_alone_until_needed() ! { + // no sync db was ever fetched here, so setting them up warns that they + // are not synced: a tree among installed packages never gets that far, + // one that has to look past them does + s := fake_system('treelazy')! + defer { os.rmdir_all(s.tmp) or {} } + s.install_local(fake_pkg('app', '1.0-1', ['lib']))! + s.install_local(fake_pkg('lib', '1.0-1', []))! + s.install_local(fake_pkg('broken', '1.0-1', ['gone']))! + stale := fn (run FrontendRun) int { + return run.of('message').filter(it['text'] or { json2.Any('') }.str().contains('not synced')).len + } + for query in [['app'], ['local/app', 'lib'], ['lib']] { + local := s.run('', fn [query] () ! { + tree(ConfigTree{ query: query })! + })! + assert local.err == '', local.err + assert local.of('tree').len == query.len + assert stale(local) == 0, '${query}: ${local.of('message')}' + } + // the reverse tree reads the installed packages alone, too + reverse := s.run('', fn () ! { + tree(ConfigTree{ reverse: true, query: ['lib'] })! + })! + assert reverse.of('tree').len == 1 && stale(reverse) == 0 + // a target that is not installed, and a dependency nothing installed + // answers, each reach for the sync dbs — once, however many ask + for query in [['nowhere'], ['broken'], ['broken', 'nowhere', 'core/x']] { + past := s.run('', fn [query] () ! { + tree(ConfigTree{ query: query })! + })! + assert stale(past) == 1, '${query}: ${past.of('message')}' + } + // what nothing provides is still drawn, as not found + broken := s.run('', fn () ! { + tree(ConfigTree{ query: ['broken'] })! + })! + child := broken.of('tree')[0]['root']!.as_map()['children']!.as_array()[0].as_map() + assert child['name']!.str() == 'gone' && !(child['found'] or { json2.Any(false) }.bool()) +} + +fn test_tree_of_several_targets_on_a_terminal() ! { + s := fake_system('treetty')! + defer { os.rmdir_all(s.tmp) or {} } + s.publish([fake_pkg('app', '1.0-1', ['lib']), fake_pkg('lib', '1.0-1', [])])! + run := s.run_ui('tty', '', fn () ! { + tree(ConfigTree{ query: ['app', 'lib'] })! + })! + assert run.err == '' + // the terminal gets the trees on stdout, a blank line between them + trees := run.stdout.split('\n\n') + assert trees.len == 2, run.stdout + assert trees[0].starts_with('app'), run.stdout + assert trees[1].starts_with('lib'), run.stdout + assert run.events.len == 0 +} + +fn test_failed_targets_count_per_run() ! { + // one run's bad targets are its own: the next run in the same process + // starts from none, as each vpac process does + s := with_file_dbs('failedcount', [FakePkg{ + name: 'bar' + files: { + 'usr/bin/bar': 'bar' + } + }])! + defer { os.rmdir_all(s.tmp) or {} } + misses := s.run('', fn () ! { + find(ConfigFind{ query: ['/nope', '/usr/bin/bar', '/neither'] })! + })! + assert misses.failed == 2 + clean := s.run('', fn () ! { + find(ConfigFind{ query: ['/usr/bin/bar'] })! + })! + assert clean.failed == 0 + // and a run leaves the count of whoever called it as it found it: the + // run's own is in its result, not in the global after it + failed_targets = 7 + defer { failed_targets = 0 } + again := s.run('', fn () ! { + find(ConfigFind{ query: ['/nope'] })! + })! + assert again.failed == 1 + assert failed_targets == 7 +} + +fn test_install_of_several_archives_is_one_transaction() ! { + // what a split build hands install: its archives, as local files, which + // go in together — one listing, one go-ahead, one done event + s := fake_system('archives')! + defer { os.rmdir_all(s.tmp) or {} } + s.publish([FakePkg{ + name: 'split-a' + files: { + 'usr/share/split/a': 'a' + } + }, FakePkg{ + name: 'split-b' + files: { + 'usr/share/split/b': 'b' + } + }])! + archives := ['split-a', 'split-b'].map(s.path('repo/${it}-1.0-1-any.pkg.tar')) + run := s.run('', fn [archives] () ! { + install(ConfigInstall{ noconfirm: true, query: archives })! + })! + assert run.err == '' + assert run.of('transaction').len == 1 + assert run.of('question').len == 1 + done := run.done()! + assert sorted_strs(done['packages']!) == ['split-a', 'split-b'] + assert s.installed()! == { + 'split-a': '1.0-1' + 'split-b': '1.0-1' + } + assert os.read_file(s.path('root/usr/share/split/b'))! == 'b' +} + +// FakeRpc answers the pkgbuild rpc's info and search requests from a set of +// packages, or every request with raw when it is set +struct FakeRpc { + pkgs map[string]PackagePkgbuild + raw string +} + +fn (mut h FakeRpc) handle(req http.Request) http.Response { + if h.raw != '' { + return http.new_response(body: h.raw) + } + u := urllib.parse(req.url) or { return http.new_response(status: .bad_request) } + mut results := []PackagePkgbuild{} + if u.path == '/rpc/v5/info' { + q := urllib.parse_query(u.raw_query) or { urllib.new_values() } + for name in q.get_all('arg[]') { + if p := h.pkgs[name] { + results << p + } + } + } else if u.path.starts_with('/rpc/v5/search/') { + needle := u.path.all_after('/rpc/v5/search/') + // by name, so several results come in an order a test can name + mut names := h.pkgs.keys().filter(it.contains(needle)) + names.sort() + for name in names { + results << h.pkgs[name] + } + } + return http.new_response( + body: json2.encode(PackagesPkgbuild{ + count: results.len + results: results + type: 'multiinfo' + version: 5 + }) + ) +} + +// aur_pkg is a pkgbuild repo package of the fake rpc +fn aur_pkg(name string, depends []string, make_depends []string) PackagePkgbuild { + return PackagePkgbuild{ + name: name + package_base: name + version: '1.0-1' + depends: depends + make_depends: make_depends + } +} + +// fake_rpc serves h on a free localhost port until the returned server is +// stopped, and answers its base url +fn fake_rpc(h FakeRpc) !(&http.Server, string) { + mut server := &http.Server{ + addr: '127.0.0.1:0' + handler: h + show_startup_message: false + worker_num: 1 + } + spawn server.listen_and_serve() + server.wait_till_running()! + return server, 'http://${server.addr}' +} + +fn test_pkgbuild_info_from_the_rpc() ! { + mut server, base := fake_rpc(FakeRpc{ + pkgs: { + 'yay-bin': aur_pkg('yay-bin', ['pacman'], []) + } + })! + defer { server.stop() } + got := get_pkgbuild_info(base, ['yay-bin', 'nothere'])! + assert got.map(it.name) == ['yay-bin'] + assert got[0].depends == ['pacman'] + found := get_pkgbuild_packages(base, 'yay')! + assert found.map(it.name) == ['yay-bin'] + // no names asks for nothing, without a request + assert get_pkgbuild_info(base, [])!.len == 0 +} + +fn test_pkgbuild_rpc_short_garbage_is_an_error() ! { + // a 200 whose body is no json and shorter than the quote of it: an error + // naming what came, not a panic + mut server, base := fake_rpc(FakeRpc{ + raw: 'oops' + })! + defer { server.stop() } + get_pkgbuild_info(base, ['x']) or { + assert err.msg().starts_with('failed to decode package info'), err.msg() + assert err.msg().ends_with('(the answer begins: oops)'), err.msg() + get_pkgbuild_packages(base, 'x') or { + assert err.msg().ends_with('(the answer begins: oops)'), err.msg() + return + } + assert false, 'the search took garbage' + } + assert false, 'the info lookup took garbage' +} + +// resolve walks name through the fake system's local and sync dbs and the +// fake rpc, as pkgbuild_install does, and answers the build plan +fn resolve(s FakeSystem, base string, name string) ![]PkgbuildNode { + // the closure captures by value: the plan comes out through the heap + mut plan := &Plan{} + run := s.run('', fn [base, name, mut plan] () ! { + cfg_repos << CfgRepo{ + name: 'aur' + kind: 'pkgbuild' + servers: [base] + } + mut handle := init_handle(new_trans_ui())! + defer { handle.release() or {} } + init_repos(mut handle)! + plan.nodes << pkgbuild_plan(handle, name)! + })! + if run.err != '' { + return error(run.err) + } + return plan.nodes +} + +@[heap] +struct Plan { +mut: + nodes []PkgbuildNode +} + +fn test_pkgbuild_resolver_orders_the_build() ! { + s := fake_system('resolver')! + defer { os.rmdir_all(s.tmp) or {} } + // glibc installed, lib in the repos, the rest only in the pkgbuild repo + s.install_local(fake_pkg('glibc', '1.0-1', []))! + s.publish([fake_pkg('lib', '1.0-1', [])])! + mut server, base := fake_rpc(FakeRpc{ + pkgs: { + 'top': PackagePkgbuild{ + ...aur_pkg('top', ['mid', 'lib', 'glibc>=1.0', 'shared'], ['tool']) + check_depends: ['checker'] + } + 'checker': aur_pkg('checker', [], []) + 'mid': aur_pkg('mid', ['leaf', 'shared'], []) + 'leaf': aur_pkg('leaf', [], []) + 'shared': aur_pkg('shared', [], []) + 'tool': aur_pkg('tool', [], []) + } + })! + defer { server.stop() } + plan := resolve(s, base, 'top')! + // dependencies first, each once (shared is reached twice), the target last + // what check() needs is planned as what the build needs is + assert plan.map(it.info.name) == ['leaf', 'shared', 'mid', 'tool', 'checker', 'top'] + // a repo package is installed before the build that needs it; an + // installed one is not touched; the site is the pkgbuild repo it came from + top := plan.last() + assert top.repo_deps == ['lib'] + assert plan.all(it.site == base) + assert plan.filter(it.info.name != 'top').all(it.repo_deps.len == 0) + // every node carries what wanted it, as the dependents spelled it: the + // target nothing, a node wanted twice both spellings once each + wanted := fn [plan] (name string) []string { + return plan.filter(it.info.name == name)[0].wanted + } + assert wanted('top') == [] + assert wanted('mid') == ['mid'] && wanted('leaf') == ['leaf'] + assert wanted('shared') == ['shared'] + assert wanted('checker') == ['checker'] + // a site the config spells with a trailing slash joins a clone url with + // one slash all the same + slashed := resolve(s, base + '/', 'leaf')! + assert slashed[0].site == base +} + +fn test_pkgbuild_resolver_refuses_cycles_and_unknowns() ! { + s := fake_system('resolverbad')! + defer { os.rmdir_all(s.tmp) or {} } + s.publish([fake_pkg('lib', '1.0-1', [])])! + mut server, base := fake_rpc(FakeRpc{ + pkgs: { + 'c1': aur_pkg('c1', ['c2'], []) + 'c2': aur_pkg('c2', ['c1'], []) + 'needy': aur_pkg('needy', ['ghost>=2'], []) + } + })! + defer { server.stop() } + resolve(s, base, 'c1') or { + assert err.msg() == 'circular pkgbuild dependency: c1 is walked as its own dependency', err.msg() + resolve(s, base, 'needy') or { + assert err.msg() == '"ghost" is not in the repos or the pkgbuild repo', err.msg() + return + } + assert false, 'a dependency nowhere was planned' + } + assert false, 'a cycle was planned' +} + +// target_errors are the messages of the target errors a run reported +fn target_errors(run FrontendRun) []string { + return run.of('error').filter(it['target'] or { json2.Any(false) }.bool()).map(it['msg'] or { + json2.Any('') + }.str()) +} + +fn test_install_scopes_a_target_to_its_repo() ! { + s := fake_system('scope')! + defer { os.rmdir_all(s.tmp) or {} } + s.publish([fake_pkg('foo', '1.0-1', [])])! + // a repo the config does not carry is an error, not a prefix to drop + bad := s.run('', fn () ! { + install(ConfigInstall{ noconfirm: true, query: ['nope/foo'] })! + })! + assert target_errors(bad) == ['database not found: nope'] + assert s.installed()!.len == 0 + // a name the repo named does not hold is not looked up anywhere else + miss := s.run('', fn () ! { + install(ConfigInstall{ noconfirm: true, query: ['core/nothere'] })! + })! + assert target_errors(miss) == ['target not found in core: nothere'] + good := s.run('', fn () ! { + install(ConfigInstall{ noconfirm: true, query: ['core/foo'] })! + })! + assert good.err == '' && good.failed == 0 + assert s.installed()! == { + 'foo': '1.0-1' + } +} + +fn test_install_resolves_constraints_and_providers() ! { + s := fake_system('satisfier')! + defer { os.rmdir_all(s.tmp) or {} } + s.publish([fake_pkg('foo', '2.0-1', []), + FakePkg{ ...fake_pkg('bash', '1.0-1', []), provides: ['sh'] }])! + run := s.run('', fn () ! { + install(ConfigInstall{ noconfirm: true, query: ['foo>=2', 'sh'] })! + })! + assert run.err == '' && run.failed == 0, run.err + assert s.installed()! == { + 'foo': '2.0-1' + 'bash': '1.0-1' + } + // a version nothing has is a miss like any other + old := s.run('', fn () ! { + install(ConfigInstall{ noconfirm: true, query: ['core/foo>=3'] })! + })! + assert target_errors(old) == ['target not found in core: foo>=3'] +} + +fn test_install_names_every_bad_target_and_installs_nothing() ! { + s := fake_system('badtargets')! + defer { os.rmdir_all(s.tmp) or {} } + s.publish([fake_pkg('foo', '1.0-1', [])])! + run := s.run('', fn () ! { + install(ConfigInstall{ noconfirm: true, query: ['zzzzzz', 'foo', 'qqqqqq'] })! + })! + // both misses are told, not only the first, and the good one waits + assert run.err == '' + assert run.failed == 2 + assert target_errors(run).len == 2 + assert run.of('done').len == 0 + assert s.installed()!.len == 0 + assert !s.lock_left() +} + +fn tool(name string) FakePkg { + return FakePkg{ + ...fake_pkg(name, '1.0-1', []) + groups: ['tools'] + } +} + +fn test_install_asks_which_members_of_a_group() ! { + s := fake_system('groupselect')! + defer { os.rmdir_all(s.tmp) or {} } + s.publish([tool('aa'), tool('bb'), tool('cc')])! + // the frontend picks the first and the third, then lets it go + run := s.run('{"id": 1, "answer": [0, 2]}\n{"id": 2, "answer": true}\n', fn () ! { + install(ConfigInstall{ query: ['tools'] })! + })! + assert run.err == '', run.err + // the members go out as a listing, each naming its group, then the question + lists := run.of('listing') + assert lists.len == 1 + members := lists[0]['entries']!.as_array().map(it.as_map()) + assert members.map(it['name'] or { json2.Any('') }.str()) == ['aa', 'bb', 'cc'] + assert members.all(it['group'] or { json2.Any('') }.str() == 'tools') + questions := run.of('question') + assert questions[0]['question']!.str() == 'select' + assert questions[0]['preset']!.as_array().len == 3 + assert s.installed()! == { + 'aa': '1.0-1' + 'cc': '1.0-1' + } + // --noconfirm takes every member left; the installed ones are not offered + rest := s.run('', fn () ! { + install(ConfigInstall{ noconfirm: true, query: ['tools'] })! + })! + assert rest.err == '' + assert rest.of('listing')[0]['entries']!.as_array().len == 1 + assert s.installed()!.len == 3 + // nothing left: said, and no failure + done := s.run('', fn () ! { + install(ConfigInstall{ noconfirm: true, query: ['tools'] })! + })! + assert done.err == '' && done.failed == 0 + assert done.of('message').any(it['text'] or { json2.Any('') }.str().contains('every member')) +} + +fn test_group_selection_on_a_terminal() ! { + s := fake_system('groupselecttty')! + defer { os.rmdir_all(s.tmp) or {} } + s.publish([tool('aa'), tool('bb'), tool('cc')])! + // all but the second, then the go-ahead + run := s.run_ui('tty', '^2\ny\n', fn () ! { + install(ConfigInstall{ query: ['tools'] })! + })! + assert run.err == '', run.err + assert s.installed()! == { + 'aa': '1.0-1' + 'cc': '1.0-1' + } + // --print lists every member and asks nothing + preview := s.run_ui('tty', '', fn () ! { + install(ConfigInstall{ print_only: true, query: ['tools'] })! + })! + assert preview.stdout.trim_space() == 'bb-1.0-1-any.pkg.tar', preview.stdout +} + +fn test_remove_takes_a_group_and_names_every_bad_target() ! { + s := fake_system('removegroup')! + defer { os.rmdir_all(s.tmp) or {} } + s.install_local(tool('aa'))! + s.install_local(tool('bb'))! + s.install_local(fake_pkg('keep', '1.0-1', []))! + // one unknown target stops the removal, after every one is named + bad := s.run('', fn () ! { + remove(ConfigRemove{ noconfirm: true, query: ['zzzzzz', 'tools', 'qqqqqq'] })! + })! + assert bad.failed == 2 + assert s.installed()!.len == 3 + assert !s.lock_left() + run := s.run('', fn () ! { + remove(ConfigRemove{ noconfirm: true, query: ['tools'] })! + })! + assert run.err == '', run.err + assert sorted_strs(run.done()!['packages']!) == ['aa', 'bb'] + assert s.installed()! == { + 'keep': '1.0-1' + } +} + +fn test_remove_unneeded_and_recursive_levels() ! { + s := fake_system('removelevels')! + defer { os.rmdir_all(s.tmp) or {} } + s.install_local(fake_pkg('app', '1.0-1', ['lib', 'tool']))! + s.install_local(FakePkg{ ...fake_pkg('lib', '1.0-1', []), reason: 1 })! + // tool was installed explicitly, though app needs it + s.install_local(fake_pkg('tool', '1.0-1', []))! + s.install_local(fake_pkg('other', '1.0-1', []))! + // -u: lib stays where app needs it, other goes, and that is no failure + u := s.run('', fn () ! { + remove(ConfigRemove{ noconfirm: true, unneeded: true, query: ['lib', 'other'] })! + })! + assert u.err == '', u.err + assert sorted_strs(u.done()!['packages']!) == ['other'] + assert 'lib' in s.installed()! + none_left := s.run('', fn () ! { + remove(ConfigRemove{ noconfirm: true, unneeded: true, query: ['lib'] })! + })! + assert none_left.err == '' && none_left.of('done').len == 0 + // a version constraint names what satisfies it + // -s takes lib, a dependency; tool was asked for by name and stays + one := s.run('', fn () ! { + remove(ConfigRemove{ print_only: true, recursive_level: 1, query: ['app>=1'] })! + })! + assert one.err == '', one.err + assert sorted_strs(one.of('transaction')[0]['packages']!.as_array().map(it.as_map()['name'] or { + json2.Any('') + })) == ['app', 'lib'] + // -ss takes the explicitly installed dependency too + two := s.run('', fn () ! { + remove(ConfigRemove{ print_only: true, recursive_level: 2, query: ['app'] })! + })! + assert sorted_strs(two.of('transaction')[0]['packages']!.as_array().map(it.as_map()['name'] or { + json2.Any('') + })) == ['app', 'lib', 'tool'] +} + +fn test_upgrade_downgrades_only_when_asked() ! { + s := fake_system('downgrade')! + defer { os.rmdir_all(s.tmp) or {} } + s.install_local(foo('2.0-1', 'two'))! + s.publish([foo('1.0-1', 'one')])! + plain := s.run('', fn () ! { + upgrade(ConfigUpgrade{ noconfirm: true })! + })! + assert plain.err == '' + assert s.installed()!['foo']! == '2.0-1' + down := s.run('', fn () ! { + upgrade(ConfigUpgrade{ noconfirm: true, sysupgrade_level: 2 })! + })! + assert down.err == '', down.err + assert s.installed()!['foo']! == '1.0-1' +} + +fn test_info_changelog_and_package_files() ! { + s := fake_system('changelog')! + defer { os.rmdir_all(s.tmp) or {} } + s.install_local(FakePkg{ ...fake_pkg('logged', '1.0-1', []), changelog: 'first release\n' })! + s.install_local(fake_pkg('silent', '1.0-1', []))! + s.publish([ + FakePkg{ ...fake_pkg('filed', '1.0-1', []), changelog: 'from the archive\n' }, + fake_pkg('other', '2.0-1', []), + ])! + run := s.run('', fn () ! { + info(ConfigInfo{ changelog: true, query: ['logged', 'silent'] })! + })! + assert run.err == '' && run.failed == 0 + logs := run.of('changelog') + assert logs.len == 1 + assert logs[0]['package']!.str() == 'logged' + assert logs[0]['text']!.str() == 'first release\n' + // the one without is said, and is no failure, as in pacman + assert run.of('message').any(it['text'] or { json2.Any('') }.str().contains('no changelog available for silent')) + + // -p: every target is a package file, and one that does not load is its + // own error + archives := ['filed-1.0-1', 'other-2.0-1'].map(s.path('repo/${it}-any.pkg.tar')) + mut targets := archives.clone() + targets << s.path('repo/nothere.pkg.tar') + files := s.run('', fn [targets] () ! { + info(ConfigInfo{ file: true, fields: 'name,version', query: targets })! + })! + infos := files.of('info') + assert infos.len == 2 + assert files.failed == 1 + first := archives[0] + log := s.run('', fn [first] () ! { + info(ConfigInfo{ file: true, changelog: true, query: [first] })! + })! + assert log.of('changelog')[0]['text']!.str() == 'from the archive\n' + tty := s.run_ui('tty', '', fn () ! { + info(ConfigInfo{ changelog: true, query: ['logged'] })! + })! + assert tty.stdout == 'changelog for logged:\nfirst release\n', tty.stdout +} + +fn test_info_scopes_and_satisfiers() ! { + s := fake_system('infoscope')! + defer { os.rmdir_all(s.tmp) or {} } + s.install_local(FakePkg{ ...fake_pkg('bash', '1.0-1', []), provides: ['sh'] })! + s.publish([fake_pkg('bash', '2.0-1', []), fake_pkg('zsh', '1.0-1', [])])! + version_of := fn (run FrontendRun) string { + for f in run.of('info')[0]['fields'] or { json2.Any([]json2.Any{}) }.as_array() { + m := f.as_map() + if m['field'] or { json2.Any('') }.str() == 'version' { + return m['value'] or { json2.Any('') }.str() + } + } + return '' + } + // bare: the installed one; core/: the repo's; a provider resolves + for target, version in { + 'bash': '1.0-1' + 'local/bash': '1.0-1' + 'core/bash': '2.0-1' + 'sh': '1.0-1' + 'bash>=2': '2.0-1' + } { + run := s.run('', fn [target] () ! { + info(ConfigInfo{ noconfirm: true, query: [target] })! + })! + assert run.failed == 0, target + assert version_of(run) == version, target + } + // local/ never reaches the sync dbs, and an unknown repo is an error + for target, msg in { + 'local/zsh': 'unknown package: "zsh"' + 'nope/bash': 'database not found: nope' + } { + run := s.run('', fn [target] () ! { + info(ConfigInfo{ noconfirm: true, query: [target] })! + })! + assert target_errors(run) == [msg], target + } +} + +fn test_search_local_groups_and_all_members() ! { + s := fake_system('localgroups')! + defer { os.rmdir_all(s.tmp) or {} } + s.install_local(tool('aa'))! + s.install_local(fake_pkg('plain', '1.0-1', []))! + s.publish([tool('aa'), tool('bb'), FakePkg{ + ...fake_pkg('cc', '1.0-1', []) + groups: [ + 'extras', + ] + }])! + names := fn (run FrontendRun) []string { + return run.of('listing')[0]['entries'] or { json2.Any([]json2.Any{}) }.as_array().map('${it.as_map()['group'] or { + json2.Any('') + }.str()} ${it.as_map()['name'] or { json2.Any('') }.str()}') + } + // -l -g: the local db's groups, the installed members alone + local := s.run('', fn () ! { + search(ConfigSearch{ local: true, groups: true, query: ['tools'] })! + })! + assert local.err == '', local.err + assert names(local) == ['tools aa'] + bare := s.run('', fn () ! { + search(ConfigSearch{ local: true, groups: true })! + })! + groups := bare.of('groups')[0]['groups']!.as_array().map(it.as_map()) + assert groups.len == 1 + assert groups[0]['repo']!.str() == 'local' && groups[0]['name']!.str() == 'tools' + // -gg: every group of the sync dbs with its members + all := s.run('', fn () ! { + search(ConfigSearch{ remote: true, groups: true, groups_level: 2 })! + })! + mut got := names(all) + got.sort() + assert got == ['extras cc', 'tools aa', 'tools bb'] + tty := s.run_ui('tty', '', fn () ! { + search(ConfigSearch{ local: true, groups: true, groups_level: 2 })! + })! + assert tty.stdout == 'tools aa\n', tty.stdout + // a sync-comparing filter on the sync groups: the dbs are registered + // once, and only the installed member can pass + native := s.run('', fn () ! { + search(ConfigSearch{ remote: true, groups: true, native: true, query: ['tools'] })! + })! + assert native.err == '', native.err + assert names(native) == ['tools aa'] + // the terminal's table leads with the group, as the ipc entries carry it + named := s.run_ui('tty', '', fn () ! { + search(ConfigSearch{ remote: true, groups: true, fields: 'name', query: ['tools'] })! + })! + assert named.err == '', named.err + assert named.stdout.split_into_lines().map(it.fields().join(' ')) == ['tools aa', 'tools bb'], named.stdout +} + +fn test_owner_quiet_names_the_package_alone() ! { + s := fake_system('ownerquiet')! + defer { os.rmdir_all(s.tmp) or {} } + s.install_local(foo('1.0-1', 'one'))! + path := s.path('root/usr/share/foo/hello') + run := s.run_ui('tty', '', fn [path] () ! { + owner(ConfigOwner{ quiet: true, query: [path] })! + })! + assert run.err == '' + assert run.stdout == 'foo\n', run.stdout +} + +fn test_find_regex_and_machinereadable() ! { + s := with_file_dbs('findregex', [ + FakePkg{ + name: 'bar' + files: { + 'usr/bin/bar': 'bar' + 'usr/share/bar/x': 'x' + } + }, + FakePkg{ + name: 'baz' + files: { + 'usr/bin/baz': 'baz' + } + }, + ])! + defer { os.rmdir_all(s.tmp) or {} } + // without a slash the expression is tried on file names, case ignored + names := s.run('', fn () ! { + find(ConfigFind{ regex: true, query: ['^BA.$'] })! + })! + assert providers_of(names)['^BA.$']! == ['bar', 'baz'] + // with one, on whole paths + paths := s.run('', fn () ! { + find(ConfigFind{ regex: true, query: ['share/.*x$', '/usr/bin/ba[rz]'] })! + })! + got := providers_of(paths) + assert got['share/.*x$']! == ['bar'] + assert got['/usr/bin/ba[rz]']! == ['bar', 'baz'] + // a bad expression is named and nothing is searched + bad := s.run('', fn () ! { + find(ConfigFind{ regex: true, query: ['(', 'bar'] })! + })! + assert target_errors(bad) == ["invalid regular expression '('"] + assert bad.of('provides').len == 0 + // pacman's --machinereadable: repo, package, version, path, NUL parted + machine := s.run_ui('tty', '', fn () ! { + find(ConfigFind{ regex: true, machinereadable: true, query: ['usr/bin/ba.'] })! + })! + assert machine.stdout == 'core\0bar\x001.0-1\0usr/bin/bar\ncore\0baz\x001.0-1\0usr/bin/baz\n', machine.stdout.bytes().str() + exact := s.run_ui('tty', '', fn () ! { + find(ConfigFind{ machinereadable: true, query: ['/usr/bin/bar'] })! + })! + assert exact.stdout == 'core\0bar\x001.0-1\0usr/bin/bar\n', exact.stdout.bytes().str() + list := s.run_ui('tty', '', fn () ! { + find(ConfigFind{ list: true, machinereadable: true, query: ['baz'] })! + })! + assert list.stdout.split('\n')[2] == 'core\0baz\x001.0-1\0usr/bin/baz', list.stdout.bytes().str() + // an expression's event names the files it matched, one list a package + matched := paths.of('provides').filter(it['path']!.str() == 'share/.*x$') + assert matched[0]['files']!.as_array().map(it.as_array().map(it.str())) == [ + ['usr/share/bar/x'], + ] +} + +fn test_find_names_slashes_and_scoped_lists() ! { + s := with_file_dbs('findnames', [ + FakePkg{ + name: 'bar' + files: { + 'usr/bin/bar': 'bar' + 'usr/share/bar/x': 'x' + } + }, + FakePkg{ + name: 'baz' + files: { + 'usr/bin/baz': 'baz' + } + }, + ])! + defer { os.rmdir_all(s.tmp) or {} } + // a target with no slash is a file name: the directory usr/share/bar/ + // has none, the file usr/bin/bar does + name := s.run('', fn () ! { + find(ConfigFind{ query: ['bar'] })! + })! + assert providers_of(name)['bar']! == ['bar'] + assert name.of('provides')[0]['files']!.as_array().map(it.as_array().map(it.str())) == [ + ['usr/bin/bar'], + ] + // a trailing slash on a file's path answers the same alone as among + // others: the walk and the index match it the same way + alone := s.run('', fn () ! { + find(ConfigFind{ query: ['/usr/bin/bar/'] })! + })! + among := s.run('', fn () ! { + find(ConfigFind{ query: ['/usr/bin/bar/', '/usr/bin/baz'] })! + })! + assert providers_of(alone)['/usr/bin/bar/']! == ['bar'] + assert providers_of(among)['/usr/bin/bar/']! == ['bar'] + // slashes alone never become the empty expression + assert find_rel('//') == '/' && find_rel('/usr/bin') == 'usr/bin' && find_rel('x') == 'x' + // -l takes repo/package, and lists the package before the path + scoped := s.run_ui('tty', '', fn () ! { + find(ConfigFind{ list: true, query: ['core/baz'] })! + })! + assert scoped.err == '', scoped.err + assert scoped.stdout.split_into_lines().map(it.fields().join(' ')) == ['baz usr/', 'baz usr/bin/', + 'baz usr/bin/baz'], scoped.stdout + other := s.run('', fn () ! { + find(ConfigFind{ list: true, query: ['nope/baz', 'core/'] })! + })! + assert other.of('files').len == 0 + assert target_errors(other).len == 2 +} + +fn test_clean_levels_and_unused_sync_dbs() ! { + s := fake_system('cleandbs')! + defer { os.rmdir_all(s.tmp) or {} } + s.install_local(foo('1.0-1', 'one'))! + for f in ['foo-1.0-1-any.pkg.tar.zst', 'gone-1.0-1-any.pkg.tar.zst'] { + os.write_file(s.path('cache/${f}'), 'x')! + } + // core is configured; old is a repo the config dropped + for f in ['core.db', 'core.files', 'old.db', 'old.db.sig', 'old.files', 'vpac.synced'] { + os.write_file(s.path('db/sync/${f}'), 'x')! + } + preview := s.run('', fn () ! { + clean(ConfigClean{ print_only: true })! + })! + assert preview.err == '', preview.err + ev := preview.of('clean')[0].clone() + assert ev['files']!.as_array().map(os.base(it.str())) == ['gone-1.0-1-any.pkg.tar.zst'] + assert ev['dbs']!.as_array().map(os.base(it.str())) == ['old.db', 'old.db.sig', 'old.files'] + // -cc is every cached package, the installed one too + all := s.run('', fn () ! { + clean(ConfigClean{ print_only: true, level: 2 })! + })! + assert all.of('clean')[0]['files']!.as_array().len == 2 + run := s.run('', fn () ! { + clean(ConfigClean{ noconfirm: true, level: 1 })! + })! + assert run.err == '', run.err + mut left := os.ls(s.path('db/sync'))! + left.sort() + assert left == ['core.db', 'core.files', 'vpac.synced'] + assert os.ls(s.path('cache'))! == ['foo-1.0-1-any.pkg.tar.zst'] +} + +// dead_mirror aims the repo at a server that has nothing: every refresh +// against it fails +fn (s FakeSystem) dead_mirror() { + cfg_repos = [CfgRepo{ + name: 'core' + kind: 'sync' + servers: ['file://' + s.path('nowhere')] + }] +} + +fn test_a_failed_refresh_is_an_error() ! { + s := fake_system('deadmirror')! + defer { os.rmdir_all(s.tmp) or {} } + s.install_local(foo('1.0-1', 'one'))! + s.publish([foo('2.0-1', 'two')])! + up := s.run_ui('tty', '', fn [s] () ! { + s.dead_mirror() + upgrade(ConfigUpgrade{ noconfirm: true, sync_dbs: true })! + })! + se := s.run('', fn [s] () ! { + s.dead_mirror() + search(ConfigSearch{ remote: true, sync_dbs: true, query: ['foo'] })! + })! + fy := s.run('', fn [s] () ! { + s.dead_mirror() + find(ConfigFind{ refresh: true, query: ['/usr/share/foo/hello'] })! + })! + assert up.err != '' + assert se.err != '' + assert fy.err != '' + assert s.installed()!['foo']! == '1.0-1' +} + +// check is an assertion inside a run's closure, where a failed assert would +// leave the fake system's redirected fds behind: it fails the run instead +fn check(ok bool, what string) ! { + if !ok { + return error('check failed: ${what}') + } +} + +fn test_targets_resolve_by_scope_version_and_provision() ! { + s := fake_system('targets')! + defer { os.rmdir_all(s.tmp) or {} } + s.install_local(fake_pkg('app', '1.0-1', ['lib']))! + s.install_local(FakePkg{ + ...fake_pkg('impl', '1.0-1', []) + provides: ['virt=2'] + })! + s.publish([fake_pkg('app', '2.0-1', ['lib']), fake_pkg('lib', '1.0-1', []), FakePkg{ + ...fake_pkg('simpl', '1.0-1', []) + provides: ['svirt=3'] + }])! + run := s.run('', fn () ! { + mut ui := new_trans_ui() + mut handle := init_handle(ui)! + defer { handle.release() or {} } + dbs := init_repos(mut handle)! + local := local_pkgcache(handle)! + // the scope is all the dbs, or the one named; an unknown name is an + // error and never a search of everything + check(scope_dbs(dbs, '')!.len == 1, 'no scope keeps every db')! + check(scope_dbs(dbs, 'core')!.map(it.get_name()) == ['core'], 'core scopes to core')! + if _ := scope_dbs(dbs, 'extra') { + return error('an unknown repo scoped') + } else { + check(err.msg() == 'database not found: extra', err.msg())! + } + if _ := scope_dbs([], 'core') { + return error('a repo was found among no dbs') + } + // installed: by name, by a constraint it meets, and by provision + // only where the caller takes providers + check(find_local_target(local, 'app', false) != none, 'app by name')! + check(find_local_target(local, 'app>=1.0', false) != none, 'app by a met constraint')! + check(find_local_target(local, 'app>=2', false) == none, 'app by an unmet constraint')! + check(find_local_target(local, 'virt', false) == none, 'a provision without providers')! + check(find_local_target(local, 'virt', true) != none, 'a provision with providers')! + check(find_local_target(local, 'virt>=3', true) == none, 'a provision too old')! + check(find_local_target(local, '', true) == none, 'the empty name')! + check(find_local_target(local, 'ap', true) == none, 'a prefix of a name')! + // sync: by name, constraint and provision; the empty name is nothing + check(find_sync_target(handle, dbs, 'app', false) != none, 'sync app')! + check(find_sync_target(handle, dbs, 'app>=2.0', false) != none, 'sync app>=2.0')! + check(find_sync_target(handle, dbs, 'app>2.0', false) == none, 'sync app>2.0')! + check(find_sync_target(handle, dbs, 'svirt', false) != none, 'sync provision')! + check(find_sync_target(handle, dbs, 'svirt=4', false) == none, 'sync provision, wrong version')! + check(find_sync_target(handle, dbs, '', false) == none, 'sync empty name')! + check(find_sync_target(handle, []&alpm.DB{}, 'app', false) == none, 'no dbs')! + // a db not for installing answers a provision only when it was + // named with the target, and its usage is put back after + dbs[0].set_usage(.sync | .search)! + check(find_sync_target(handle, dbs, 'svirt', false) == none, 'usage without install')! + check(find_sync_target(handle, dbs, 'svirt', true) != none, 'named db, usage lifted')! + usage := dbs[0].get_usage() or { return error('no usage') } + check(!usage.has(.install), 'the usage was put back')! + // by name it is found either way: the name is asked of the db itself + check(find_sync_target(handle, dbs, 'app', false) != none, 'by name whatever the usage')! + })! + assert run.err == '', run.err +} + +fn test_filters_combine_as_pacmans_query_filters() ! { + s := fake_system('filters')! + defer { os.rmdir_all(s.tmp) or {} } + // app: explicit, in the repos, newer there. lib: a dependency app needs. + // own: explicit, in no repo. loose: a dependency nothing needs, older in + // the repos than installed. opt-only would need optdepends, which the + // level-2 unrequired check is covered with in orphans_test + s.install_local(fake_pkg('app', '1.0-1', ['lib']))! + s.install_local(FakePkg{ + ...fake_pkg('lib', '1.0-1', []) + reason: 1 + })! + s.install_local(fake_pkg('own', '1.0-1', []))! + s.install_local(FakePkg{ + ...fake_pkg('loose', '2.0-1', []) + reason: 1 + })! + s.publish([fake_pkg('app', '2.0-1', ['lib']), fake_pkg('lib', '1.0-1', []), + fake_pkg('loose', '1.0-1', [])])! + run := s.run('', fn () ! { + mut ui := new_trans_ui() + mut handle := init_handle(ui)! + defer { handle.release() or {} } + dbs := init_repos(mut handle)! + mut local := local_pkgcache(handle)! + pass := fn [mut local, dbs] (c ConfigSearch) []string { + mut names := local.pkgs().filter(pkg_matches_filter(it, c, dbs)).map(it.get_name()) + names.sort() + return names + } + check(pass(ConfigSearch{}) == ['app', 'lib', 'loose', 'own'], 'no filter passes all')! + check(pass(ConfigSearch{ explicit: true }) == ['app', 'own'], 'explicit')! + check(pass(ConfigSearch{ deps: true }) == ['lib', 'loose'], 'deps')! + // the two reasons together pass nothing: no package is both + check(pass(ConfigSearch{ deps: true, explicit: true }) == [], 'deps and explicit')! + check(pass(ConfigSearch{ unrequired: true, unrequired_level: 1 }) == ['app', 'loose', 'own'], 'unrequired')! + check(pass(ConfigSearch{ deps: true, unrequired: true, unrequired_level: 1 }) == ['loose'], 'unrequired deps')! + check(pass(ConfigSearch{ foreign: true }) == ['own'], 'foreign')! + check(pass(ConfigSearch{ native: true }) == ['app', 'lib', 'loose'], 'native')! + check(pass(ConfigSearch{ native: true, foreign: true }) == [], 'native and foreign')! + // an upgrade is a strictly newer sync version: an equal one, an + // older one (loose) and a package in no repo are not + check(pass(ConfigSearch{ upgrades: true }) == ['app'], 'upgrades')! + check(pass(ConfigSearch{ upgrades: true, deps: true }) == [], 'upgrades among deps')! + check(pass(ConfigSearch{ upgrades: true, foreign: true }) == [], 'upgrades of foreign')! + // with no sync dbs to compare with, everything is foreign + none_synced := local.pkgs().filter(pkg_matches_filter(it, ConfigSearch{ native: true }, + []&alpm.DB{})) + check(none_synced.len == 0, 'native with no sync dbs')! + // the filters that need no sync data never load it + check(filter_sync_dbs(mut ui, mut handle, ConfigSearch{ explicit: true, unrequired: true })!.len == 0, + 'no sync dbs for local-only filters')! + })! + assert run.err == '', run.err +} + +fn test_search_groups_take_one_side_and_fuzzy_keeps_its_order() ! { + s := fake_system('searchedges')! + defer { os.rmdir_all(s.tmp) or {} } + s.install_local(tool('aa'))! + s.publish([tool('aa'), FakePkg{ + ...fake_pkg('zeditor', '1.0-1', []) + desc: 'an editor' + }, FakePkg{ + ...fake_pkg('notes', '1.0-1', []) + desc: 'a small editor for notes' + }, FakePkg{ + ...fake_pkg('editor', '1.0-1', []) + desc: 'the editor' + }])! + // -g with both sides named would drop one of them: refused, before any + // db is opened, with or without a group named + for query in [[]string{}, ['tools']] { + both := s.run('', fn [query] () ! { + search(ConfigSearch{ local: true, remote: true, groups: true, query: query })! + })! + assert both.err.contains('not both at once'), both.err + assert both.of('listing').len == 0 && both.of('groups').len == 0 + } + // each side alone still answers + for local in [true, false] { + one := s.run('', fn [local] () ! { + search(ConfigSearch{ local: local, remote: !local, groups: true, query: ['tools'] })! + })! + assert one.err == '', one.err + assert one.of('listing').len == 1 + } + // fuzzy: the names that match lead, best first, and a package matched + // by its description alone trails them, listed once + fuzzy := s.run('', fn () ! { + search(ConfigSearch{ remote: true, fuzzy: true, thold: 0.8, fields: 'name', query: ['editor'] })! + })! + assert fuzzy.err == '', fuzzy.err + names := fuzzy.of('listing')[0]['entries']!.as_array().map(it.as_map()['name']!.str()) + assert names == ['editor', 'zeditor', 'notes'], names.str() + // a term nothing is near matches nothing, and is no error + none_near := s.run('', fn () ! { + search(ConfigSearch{ remote: true, fuzzy: true, thold: 0.8, query: ['qqqqqqqq'] })! + })! + assert none_near.err == '' + assert none_near.of('listing')[0]['entries'] or { json2.Any([]json2.Any{}) }.as_array().len == 0 +} + +fn test_info_fields_and_listing_on_real_packages() ! { + s := fake_system('formatreal')! + defer { os.rmdir_all(s.tmp) or {} } + s.install_local(FakePkg{ + ...fake_pkg('app', '1.0-1', ['lib>=1', 'glibc']) + provides: ['virt=2'] + groups: ['tools'] + })! + s.install_local(fake_pkg('bare', '2.0-1', []))! + run := s.run_ui('tty', '', fn () ! { + mut ui := new_trans_ui() + mut handle := init_handle(ui)! + defer { handle.release() or {} } + local := local_pkgcache(handle)! + app := local.pkg_find('app') or { return error('no app') } + bare := local.pkg_find('bare') or { return error('no bare') } + // asked for by default, an empty field is left out; named on the + // command line it is shown, empty + fields := ['name', 'version', 'depends', 'provides', 'groups', 'url'] + quiet := info_fields(bare, fields, false) + check(quiet.map(it.field) == ['name', 'version'], 'empty fields left out: ${quiet.map(it.field)}')! + named := info_fields(bare, fields, true) + check(named.map(it.field) == fields, 'named fields all shown')! + check(named.filter(it.field == 'depends')[0].value == '', 'an empty value stays empty')! + check(named.filter(it.field == 'depends')[0].items.len == 0, 'and has no items')! + // a list field carries its items one by one, a plain one none + full := info_fields(app, fields, false) + check(full.map(it.field) == ['name', 'version', 'depends', 'provides', 'groups'], 'app fields: ${full.map(it.field)}')! + deps := full.filter(it.field == 'depends')[0] + check(deps.items == ['lib>=1', 'glibc'] && deps.value == 'lib>=1, glibc', 'depends items: ${deps}')! + check(full.filter(it.field == 'name')[0].items.len == 0, 'a plain field has no items')! + check(full.filter(it.field == 'provides')[0].items == ['virt=2'], 'provides items')! + // no fields asked for is nothing to show, not a crash + check(info_fields(app, [], true).len == 0, 'no fields')! + check(info_table([]) == '', 'an empty table is no text')! + // a listing: the default mode holds a value per field, the quiet one + // the name alone, and a member carries its group + mut l := Listing{ + fields: ['name', 'version', 'groups'] + } + l.add_pkg(app, 'local') + l.add_pkg(bare, 'local') + check(l.entries[0].values == ['app', '1.0-1', 'tools'], 'values: ${l.entries[0].values}')! + check(l.entries[1].values == ['bare', '2.0-1', ''], 'an empty value is kept in its place')! + mut q := Listing{ + mode: .minimal + fields: ['name', 'version'] + } + q.add_pkg(app, 'local') + q.add_member(bare, 'local', 'tools') + check(q.entries.all(it.values.len == 0), 'quiet entries hold no values')! + check(q.entries[1].group == 'tools' && q.entries[0].group == '', 'the member has its group')! + // what the terminal gets: a table with '-' for the empty value, the + // names alone for the quiet one, nothing at all for an empty listing + l.print() + println('--') + q.print() + println('--') + Listing{ + fields: ['name'] + }.print() + println('--') + // a collection that failed part way shows what a quiet listing + // found, and nothing of a table + l.print_found() + q.print_found() + })! + assert run.err == '', run.err + parts := run.stdout.split('--\n') + assert parts.len == 4, run.stdout + assert parts[0].split_into_lines().map(it.fields().join(' ')) == ['app 1.0-1 tools', 'bare 2.0-1 -'], parts[0] + assert parts[1] == 'app\nbare\n' + assert parts[2] == '' + assert parts[3] == 'app\nbare\n' +} + +fn test_pkgbuild_plan_gathers_every_spelling_that_wanted_a_node() ! { + s := fake_system('wanted')! + defer { os.rmdir_all(s.tmp) or {} } + // dep 1.0 is installed, and too old for everything that asks for it + s.install_local(fake_pkg('dep', '1.0-1', []))! + s.publish([fake_pkg('lib', '1.0-1', [])])! + mut server, base := fake_rpc(FakeRpc{ + pkgs: { + 'top': aur_pkg('top', ['a', 'b', 'dep>=2'], []) + 'a': aur_pkg('a', ['dep>=2', 'dep>=3'], []) + 'b': aur_pkg('b', ['dep>=3'], ['dep>=2']) + 'dep': aur_pkg('dep', [], []) + } + })! + defer { server.stop() } + plan := resolve(s, base, 'top')! + assert plan.map(it.info.name) == ['dep', 'a', 'b', 'top'] + // the node is planned once, and holds each spelling once, in the order + // they were met, those that came after it was planned too + assert plan[0].wanted == ['dep>=2', 'dep>=3'] + assert plan[1].wanted == ['a'] && plan[2].wanted == ['b'] && plan[3].wanted == [] + // the plan is made on the local db of this moment: with dep new enough + // for everyone installed since, it is planned by nobody + os.rmdir_all(s.path('db/local/dep-1.0-1'))! + s.install_local(fake_pkg('dep', '3.0-1', []))! + again := resolve(s, base, 'top')! + assert again.map(it.info.name) == ['a', 'b', 'top'] + // new enough for some and not for all, it is still planned, and wanted + // by the one spelling it does not meet: a spelling that is met already + // plans nothing and is not held + os.rmdir_all(s.path('db/local/dep-3.0-1'))! + s.install_local(fake_pkg('dep', '2.0-1', []))! + partly := resolve(s, base, 'top')! + assert partly.map(it.info.name) == ['dep', 'a', 'b', 'top'] + assert partly[0].wanted == ['dep>=3'] +} diff --git a/src/help.v b/src/help.v new file mode 100644 index 0000000..67ab4af --- /dev/null +++ b/src/help.v @@ -0,0 +1,476 @@ +module main + +import term + +struct HelpFlag { + name string + desc string +} + +struct HelpExample { + cmd string + desc string +} + +struct HelpMode { + key string + name string + desc string + usage string + options []HelpFlag + examples []HelpExample +} + +const help_modes = [ + HelpMode{ + key: 's' + name: 'search' + desc: 'search packages in the local, sync and pkgbuild databases' + usage: '[options] ' + options: [ + HelpFlag{'-l, --local', 'search the installed packages'}, + HelpFlag{'-r, --remote', 'search the sync databases (the default)'}, + HelpFlag{'-b, --pkgbuild', 'search the pkgbuild repo'}, + HelpFlag{'-f, --fuzzy', 'fuzzy matching instead of substring matching'}, + HelpFlag{'-t, --thold <0-1>', 'fuzzy match threshold (default 0.9)'}, + HelpFlag{'-q, --quiet', 'print package names only'}, + HelpFlag{'-s, --sync', 'refresh the sync databases first'}, + HelpFlag{'-F, --fields ', 'columns to show: all, or a comma list (see fields)'}, + HelpFlag{'-d, --deps', 'installed packages installed as dependencies [filter]'}, + HelpFlag{'-e, --explicit', 'installed packages installed explicitly [filter]'}, + HelpFlag{'-m, --foreign', 'installed packages not in the sync dbs [filter]'}, + HelpFlag{'-n, --native', 'installed packages found in the sync dbs [filter]'}, + HelpFlag{'--unrequired', 'installed packages nothing requires [filter]'}, + HelpFlag{'', 'twice keeps the ones only optionally required'}, + HelpFlag{'-u, --upgrades', 'installed packages with a newer version in the sync dbs [filter]'}, + HelpFlag{'-g, --groups', 'list the groups, or the members of the groups named'}, + HelpFlag{'', 'with -gg every group with its members'}, + HelpFlag{'', 'with -l the installed groups'}, + HelpFlag{'--noconfirm', 'take the default at every prompt, never read stdin'}, + HelpFlag{'-i, --installed', 'keep only packages that are installed locally'}, + ] + examples: [ + HelpExample{'vpac s -r linux-lts', 'search the sync databases for linux-lts'}, + HelpExample{'vpac s -l -F name,version,size', 'installed packages with their sizes'}, + HelpExample{'vpac s -l -e', 'installed packages installed explicitly'}, + HelpExample{'vpac s -l -u', 'installed packages with an update available'}, + HelpExample{'vpac s -r visual code', 'packages with both words in the name or description'}, + HelpExample{'vpac s -l -f -t 0.8 patchelv', 'fuzzy search the installed packages'}, + HelpExample{'vpac s -g base-devel', 'the members of a sync group'}, + HelpExample{'vpac s -l -gg', 'every installed group with its members'}, + ] + }, + HelpMode{ + key: 'q' + name: 'info' + desc: 'show package information, falling back to the sync databases' + usage: '[options] ' + options: [ + HelpFlag{'-F, --fields ', 'fields to show: all, or a comma list (see fields)'}, + HelpFlag{'-c, --changelog', 'show the changelog of the package instead'}, + HelpFlag{'-p, --file', 'the targets are package files, not installed or sync packages'}, + HelpFlag{'--noconfirm', 'take the default at every prompt, never read stdin'}, + ] + examples: [ + HelpExample{'vpac q patchelf', 'show what is installed for patchelf'}, + HelpExample{'vpac q -F name,version,depends bash', 'only those three fields'}, + HelpExample{'vpac q extra/bash', 'the bash of one repo; local/bash is the installed one'}, + HelpExample{"vpac q 'sh>=5'", 'whatever satisfies a dependency'}, + HelpExample{'vpac q -c bash', 'the changelog bash was packaged with'}, + HelpExample{'vpac q -p ./a.pkg.tar.zst ./b.pkg.tar.zst', 'package files on disk'}, + ] + }, + HelpMode{ + key: 'w' + name: 'which' + desc: 'find the installed package that provides a dependency' + usage: '' + examples: [ + HelpExample{'vpac w libpng.so', 'which package provides libpng.so'}, + ] + }, + HelpMode{ + key: 'n' + name: 'deptest' + desc: 'print the dependencies no installed package satisfies, exit 127 if any' + usage: '' + examples: [ + HelpExample{"vpac n 'glibc>=2.40' cowsay", 'print whichever of the two is not satisfied'}, + ] + }, + HelpMode{ + key: 'm' + name: 'mark' + desc: 'change why an installed package is installed' + usage: '-r ' + options: [ + HelpFlag{'-r, --reason ', 'explicit, depend or unknown'}, + HelpFlag{'--noconfirm', 'take the default at every prompt, never read stdin'}, + ] + examples: [ + HelpExample{'vpac m -r depend patchelf', 'mark patchelf as installed as a dependency'}, + ] + }, + HelpMode{ + key: 'i' + name: 'install' + desc: 'install from the repos, a local file or the pkgbuild repo (asked first)' + usage: '[options] ' + options: [ + HelpFlag{'--no-upgrade-deps', 'leave outdated dependencies and their dependents alone'}, + HelpFlag{'--needed', 'skip the targets installed at the version they would install'}, + HelpFlag{'--asdeps', 'mark the targets as installed as dependencies'}, + HelpFlag{'--asexplicit', 'mark the targets as explicitly installed'}, + HelpFlag{'-d, --nodeps', 'skip the dependency version checks'}, + HelpFlag{'-dd', 'skips the dependency checks'}, + HelpFlag{'--assume-installed ', 'count a dependency as installed (repeatable, comma separated)'}, + HelpFlag{'--overwrite ', 'overwrite conflicting files that match (repeatable, comma separated)'}, + HelpFlag{'--ignore ', 'leave a package out of this run (repeatable, comma separated)'}, + HelpFlag{'--ignoregroup ', 'leave a group out of this run (repeatable, comma separated)'}, + HelpFlag{'--dbonly', 'change the database only, not the files on disk'}, + HelpFlag{'--disable-timeout', 'let slow downloads take their time'}, + HelpFlag{'-b, --pkgbuild', 'build from the pkgbuild repo only, offering the PKGBUILD for review first'}, + HelpFlag{'--nopkgbuildconfirm', 'skip the questions asked while installing from the pkgbuild repo'}, + HelpFlag{'-w, --download-only', 'download the packages into the cache, and install nothing'}, + HelpFlag{'-p, --print', 'list the archives the transaction would install, and install nothing'}, + HelpFlag{'--noconfirm', 'answer yes to repo prompts, and refuse pkgbuild builds unless --nopkgbuildconfirm'}, + ] + examples: [ + HelpExample{'vpac i patchelf', 'install patchelf, upgrading its outdated dependencies'}, + HelpExample{'vpac i ./foo-1.0-1-x86_64.pkg.tar.zst', 'install a local package file'}, + HelpExample{'vpac i patchelf bash', 'install both in one transaction, confirmed once'}, + HelpExample{'vpac i --needed --asdeps patchelf', 'install patchelf as a dependency, unless it is up to date'}, + HelpExample{'vpac i extra/patchelf', 'install it from that repo and no other'}, + HelpExample{"vpac i 'bash>=5' sh", 'install what satisfies a version, or provides a name'}, + HelpExample{'vpac i base-devel', 'install a group: its members are listed, to pick from'}, + ] + }, + HelpMode{ + key: 'r' + name: 'remove' + desc: 'remove an installed package' + usage: '[options] ' + options: [ + HelpFlag{'-s, --recursive', 'also remove the dependencies the removal leaves unneeded'}, + HelpFlag{'-ss', 'the explicitly installed ones too'}, + HelpFlag{'-u, --unneeded', 'leave the targets something still requires, instead of failing'}, + HelpFlag{'-c, --cascade', 'also remove the packages that depend on the targets'}, + HelpFlag{'-n, --nosave', 'remove changed config files too, instead of keeping .pacsave copies'}, + HelpFlag{'-d, --nodeps', 'skip the dependency version checks'}, + HelpFlag{'-dd', 'skips the dependency checks'}, + HelpFlag{'--assume-installed ', 'count a dependency as installed (repeatable, comma separated)'}, + HelpFlag{'--dbonly', 'change the database only, not the files on disk'}, + HelpFlag{'-p, --print', 'list the packages the removal would take, as name-version, and remove nothing'}, + HelpFlag{'--noconfirm', 'take the default at every prompt, never read stdin'}, + ] + examples: [ + HelpExample{'vpac r patchelf', 'remove patchelf'}, + HelpExample{'vpac r -s patchelf', 'remove patchelf and the dependencies only it needed'}, + HelpExample{'vpac r -c libfoo', 'remove libfoo and every package that needs it'}, + HelpExample{'vpac r -ss patchelf', 'also the dependencies that were installed explicitly'}, + HelpExample{'vpac r -u libfoo libbar', 'remove whichever of them nothing needs'}, + HelpExample{'vpac r xorg-apps', 'remove the installed members of a group'}, + ] + }, + HelpMode{ + key: 'u' + name: 'upgrade' + desc: 'upgrade the whole system' + usage: '[options]' + options: [ + HelpFlag{'-s, --sync', 'refresh the sync databases first'}, + HelpFlag{'-w, --download-only', 'download the upgrades without installing them'}, + HelpFlag{'-uu, --downgrade', 'also downgrade packages newer than the sync dbs carry'}, + HelpFlag{'--ignore ', 'hold a package back this time (repeatable, comma separated)'}, + HelpFlag{'--ignoregroup ', 'hold a group back this time (repeatable, comma separated)'}, + HelpFlag{'-d, --nodeps', 'skip the dependency version checks'}, + HelpFlag{'-dd', 'skips the dependency checks'}, + HelpFlag{'--assume-installed ', 'count a dependency as installed (repeatable, comma separated)'}, + HelpFlag{'--overwrite ', 'overwrite conflicting files that match (repeatable, comma separated)'}, + HelpFlag{'--dbonly', 'change the database only, not the files on disk'}, + HelpFlag{'--disable-timeout', 'let slow downloads take their time'}, + HelpFlag{'-p, --print', 'list the archives the upgrade would install, and upgrade nothing'}, + HelpFlag{'--noconfirm', 'take the default at every prompt, never read stdin'}, + ] + examples: [ + HelpExample{'vpac u -s', 'refresh the databases and upgrade the system'}, + HelpExample{'vpac u --ignore linux', 'upgrade everything but linux'}, + HelpExample{'vpac u -s -w', 'refresh, then only download what the upgrade needs'}, + HelpExample{'vpac u -uu', 'bring packages newer than the repos back down to them'}, + ] + }, + HelpMode{ + key: 'l' + name: 'files' + desc: 'list the files of an installed package' + usage: '[options] ' + options: [ + HelpFlag{'--noconfirm', 'take the default at every prompt, never read stdin'}, + ] + examples: [ + HelpExample{'vpac l bash', 'list the files bash installed'}, + ] + }, + HelpMode{ + key: 'o' + name: 'owner' + desc: 'find the installed package that owns a file, or every one that owns a directory' + usage: '[options] ' + options: [ + HelpFlag{'-q, --quiet', 'print the package names only'}, + ] + examples: [ + HelpExample{'vpac o /usr/bin/ls', 'which package owns /usr/bin/ls'}, + HelpExample{'vpac o -q /usr/bin/ls', 'only its name'}, + HelpExample{'vpac o ls', 'a bare name the current directory lacks is looked up in PATH'}, + ] + }, + HelpMode{ + key: 'd' + name: 'orphans' + desc: 'list packages installed as dependencies that nothing requires' + usage: '[options]' + options: [ + HelpFlag{'-t', '-tt also lists the ones something names as an optional dependency'}, + ] + examples: [ + HelpExample{'vpac d', 'list the orphans'}, + HelpExample{'vpac d -tt', 'and the dependencies only an optdepends line keeps'}, + ] + }, + HelpMode{ + key: 'b' + name: 'build' + desc: 'build and install a package from an arbitrary repo' + usage: '[options] ' + options: [ + HelpFlag{'--nopkgbuildconfirm', 'skip the build question; the review is still shown'}, + HelpFlag{'--noconfirm', 'answer yes to the install prompts, and refuse to build unless --nopkgbuildconfirm'}, + ] + examples: [ + HelpExample{'vpac b ~/src/mything', 'build a local checkout, review included, and install it'}, + HelpExample{'vpac b https://example.org/mything.git', 'clone the repo under the pkgbuild build dir and install'}, + HelpExample{'vpac b -h', 'show the options of the mode'}, + ] + }, + HelpMode{ + key: 'c' + name: 'clean' + desc: 'clean the package cache and the pkgbuild builds' + usage: '[options]' + options: [ + HelpFlag{'-c', 'the default clean'}, + HelpFlag{'-cc', 'removes every cached package'}, + HelpFlag{'-a, --all', 'remove every cached file and every pkgbuild build'}, + HelpFlag{'-k, --keep ', 'keep the n newest versions of every package'}, + HelpFlag{'--keep-current', 'also keep the versions the sync dbs carry'}, + HelpFlag{'-p, --print', 'list the files and builds the clean would remove, and remove nothing'}, + HelpFlag{'--noconfirm', 'take the default at every prompt, never read stdin'}, + ] + examples: [ + HelpExample{'vpac c', 'remove cached packages that are not installed or are old, the builds of packages that are not installed, and the sync dbs of repos the config dropped'}, + HelpExample{'vpac c -cc', 'remove every cached package'}, + HelpExample{'vpac c -k 2', 'keep the two newest versions of every cached package'}, + ] + }, + HelpMode{ + key: 'a' + name: 'autoremove' + desc: 'remove every orphan, and the dependencies that become unneeded' + usage: '[options]' + options: [ + HelpFlag{'--noconfirm', 'take the default at every prompt, never read stdin'}, + ] + examples: [ + HelpExample{'vpac a', 'remove all orphans'}, + ] + }, + HelpMode{ + key: 'k' + name: 'rank' + desc: 'rank mirrors by latency and download speed' + usage: '[options] [os]' + options: [ + HelpFlag{'-n, --top ', 'show the n fastest mirrors (default 10)'}, + HelpFlag{'-w, --write', 'write the ranking to .lip in the mirrors dir (/etc/vpac.d/mirrors), as root if needed'}, + HelpFlag{'-m, --mirrorlist', 'print the result as mirrorlist Server lines'}, + HelpFlag{'-o, --output ', 'write the Server lines to a file, as root if needed'}, + HelpFlag{'--stdin', 'rank the mirrors listed on stdin, instead of the os mirror list'}, + HelpFlag{'--path ', 'file to time for speed, under the mirror root'}, + ] + examples: [ + HelpExample{'vpac k -n 5', 'the five fastest mirrors of this system'}, + HelpExample{'vpac k -w', 'rank and write the config mirror file for this system'}, + HelpExample{'vpac k -n 5 cachyos', 'the five fastest CachyOS mirrors'}, + HelpExample{'vpac k -m -o /tmp/mirrorlist arch', 'write the fastest Arch mirrors to a file'}, + HelpExample{'cat list.txt | vpac k --stdin', 'rank the mirrors in a list, one url per line'}, + ] + }, + HelpMode{ + key: 't' + name: 'tree' + desc: 'show the dependency tree of a package' + usage: '[options] ' + options: [ + HelpFlag{'-r, --reverse', 'show what requires the package instead'}, + HelpFlag{'-o, --optional', 'include optional dependencies'}, + HelpFlag{'-d, --depth ', 'show n levels only (default: all)'}, + HelpFlag{'--noconfirm', 'take the default at every prompt, never read stdin'}, + ] + examples: [ + HelpExample{'vpac t -d 2 bash', 'dependencies of bash, two levels deep'}, + HelpExample{'vpac t -r glibc', 'packages that require glibc'}, + ] + }, + HelpMode{ + key: 'v' + name: 'verify' + desc: 'check the files of installed packages' + usage: '[options] [package...]' + options: [ + HelpFlag{'-k, --checksums', 'also check that backed up config files are unmodified'}, + HelpFlag{'-kk, --full', "check every file against the package's mtree: type, owner, mode, link, time, size, sha256"}, + HelpFlag{'-D, --db', 'check the local db instead: its files, dependencies, conflicts, shared files'}, + HelpFlag{'-DD', "check that every sync package's dependencies resolve"}, + ] + examples: [ + HelpExample{'vpac v', 'check every installed package'}, + HelpExample{'vpac v glibc', 'check one package'}, + HelpExample{'vpac v -k', 'also check the backup files'}, + HelpExample{'vpac v -kk glibc', 'check every file of glibc; run as root to read root-only files'}, + HelpExample{'vpac v -D', 'check the local package database for consistency'}, + ] + }, + HelpMode{ + key: 'f' + name: 'find' + desc: 'find the sync package that provides a file, from the file dbs' + usage: '[options] | -l ' + options: [ + HelpFlag{'-l, --list', 'list the files of a sync package instead'}, + HelpFlag{'-y, --refresh', 'refresh the file dbs first (as root)'}, + HelpFlag{'-r, --repos ', 'comma separated repos to search (default: all)'}, + HelpFlag{'-q, --quiet', 'repo/pkg for paths, file paths for -l'}, + HelpFlag{'-x, --regex', 'the targets are regular expressions: with a slash matched against paths, without against file names'}, + HelpFlag{'--machinereadable', 'one line a file, its repo, package, version and path parted by NUL bytes'}, + HelpFlag{'--noconfirm', 'take the default at every prompt, never read stdin'}, + ] + examples: [ + HelpExample{'vpac f /usr/bin/vlc', 'which sync package provides /usr/bin/vlc'}, + HelpExample{'vpac f -l dolphin', 'the files of an uninstalled package'}, + HelpExample{"vpac f -x '^usr/bin/vl.*'", 'every package with a file the expression matches'}, + HelpExample{'vpac f -y', 'refresh the file dbs first'}, + ] + }, +] + +// find_mode matches a mode by its short key or its name +fn find_mode(name string) ?HelpMode { + for m in help_modes { + if m.key == name || m.name == name { + return m + } + } + return none +} + +// show_help prints a help text, or sends it as a help event +fn show_help(text string) { + if ipc_on() { + emit(HelpEvent{ + text: text + }) + return + } + println(text) +} + +// overview_examples are the overview's examples: some of the modes' own, +// named by their command, so each is written once, in its mode +const overview_examples = ['vpac s -r linux-lts', 'vpac i patchelf', 'vpac c -k 2', 'vpac t -d 2 bash'] + +// overview_example_rows finds the overview's examples in the modes +fn overview_example_rows() []Row { + mut rows := []Row{} + for cmd in overview_examples { + for m in help_modes { + for e in m.examples { + if e.cmd == cmd { + rows << row(e.cmd, e.desc) + } + } + } + } + return rows +} + +fn help_text() string { + mut modes := []Row{} + for m in help_modes { + modes << row(heading(m.key), m.name, m.desc) + } + examples := overview_example_rows() + + mut out := []string{} + out << bold_heading('usage') + ' vpac [flags] [options] [args]' + out << ' --config read this config instead of ${config_path}' + out << ' --eval run blip after the config, extending it for this run' + out << ' --color auto, always or never: auto styles a terminal only' + out << ' --ui tty, or ipc: json lines on stdout, answers on stdin' + out << ' --verbose say the housekeeping failures a run otherwise goes on from' + out << ' vpac -h show the options of a mode' + out << '' + out << bold_heading('modes') + out << table_text(modes, ' ', ' ') + out << '' + out << bold_heading('examples') + out << table_text(examples, ' ', ' ') + return out.join('\n') +} + +// mode_help_text shows one mode's usage, options and examples +fn mode_help_text(mode HelpMode) string { + mut out := []string{} + out << '${name_style(mode.name)} - ${mode.desc}' + out << '' + out << 'usage vpac ${mode.key} ${mode.usage}'.trim_right(' ') + if mode.options.len > 0 { + mut rows := []Row{} + for f in mode.options { + rows << row(f.name, f.desc) + } + out << '' + out << bold_heading('options') + out << table_text(rows, ' ', ' ') + } + if mode.name == 'search' || mode.name == 'info' { + out << '' + out << bold_heading('fields') + // as wide as the terminal the help is read on, the way info lays + // its own lists out, and info's fallback where there is none + cols, _ := term.get_terminal_size() + out << wrap_names(pkg_field_names, info_width(cols)) + } + if mode.examples.len > 0 { + mut rows := []Row{} + for e in mode.examples { + rows << row(e.cmd, e.desc) + } + out << '' + out << bold_heading('examples') + out << table_text(rows, ' ', ' ') + } + return out.join('\n') +} + +// wrap_names lays the field names out in lines no wider than width, as the +// terminal counts width: a styled or multibyte name is as wide as it shows +fn wrap_names(names []string, width int) string { + if names.len == 0 { + return '' + } + // the lines are wrap_items', info's own wrapping: here indented by two, + // and a line that goes on ends in its comma, which with the space after + // it is the room kept free of the width + return wrap_items(names, width - 4).map(' ' + it).join(',\n') +} diff --git a/src/help_test.v b/src/help_test.v new file mode 100644 index 0000000..2ed259b --- /dev/null +++ b/src/help_test.v @@ -0,0 +1,126 @@ +module main + +import term + +fn widest(text string) int { + mut w := 0 + for line in text.split('\n') { + if visible_width(line) > w { + w = visible_width(line) + } + } + return w +} + +fn test_wrap_names_fits_the_width() { + names := ['name', 'version', 'description', 'architecture', 'url', 'licenses', 'groups', 'provides', + 'depends'] + text := wrap_names(names, 30) + assert widest(text) <= 30, text + // every name, in order, once + assert text.split('\n').map(it.trim_space()).join(' ').split(', ').map(it.trim_space()).join(',') == names.join(',') + assert text.starts_with(' name, version,') + assert !text.ends_with(',') +} + +fn test_wrap_names_counts_what_shows() { + // a multibyte name is as wide as its characters: three of these fit a + // line of 22 columns, which bytes (two a character) would have broken + wide := ['ääää', 'öööö', 'üüüü'] + assert wrap_names(wide, 22) == ' ääää, öööö, üüüü' + // a styled name is as wide as its text, its escapes take no column + styled := ['name', 'version', 'url'].map(term.bold(it)) + assert wrap_names(styled, 23).split('\n').len == 1 + // one name wider than the line still gets a line of its own + assert wrap_names(['a-very-long-field-name', 'x'], 10) == ' a-very-long-field-name,\n x' +} + +fn test_overview_examples_are_the_modes_own() { + // every example the overview names is one mode's, found exactly once, + // with that mode's description: renaming it in its mode fails here + rows := overview_example_rows() + assert rows.len == overview_examples.len + text := help_text() + for cmd in overview_examples { + mut found := []string{} + for m in help_modes { + for e in m.examples { + if e.cmd == cmd { + found << e.desc + } + } + } + assert found.len == 1, cmd + assert text.contains(found[0]), cmd + } +} + +// flag_longs are the long names a mode's struct parses, as the command line +// spells them +fn flag_longs[T]() []string { + mut out := []string{} + $for field in T.fields { + for attr in field.attrs { + if attr.starts_with('long: ') { + out << attr.all_after('long: ').trim_space().replace('_', '-') + } + } + } + return out +} + +fn test_help_names_every_flag_a_mode_parses() { + // a flag the parser takes and the help does not name is a flag nobody + // finds; --help itself is the one every mode has and none lists + mut parsed := map[string][]string{} + parsed['s'] = flag_longs[ConfigSearch]() + parsed['q'] = flag_longs[ConfigInfo]() + parsed['w'] = flag_longs[ConfigWhich]() + parsed['n'] = flag_longs[ConfigDeptest]() + parsed['m'] = flag_longs[ConfigMark]() + parsed['b'] = flag_longs[ConfigBuild]() + parsed['i'] = flag_longs[ConfigInstall]() + parsed['r'] = flag_longs[ConfigRemove]() + parsed['u'] = flag_longs[ConfigUpgrade]() + parsed['l'] = flag_longs[ConfigFiles]() + parsed['o'] = flag_longs[ConfigOwner]() + parsed['d'] = flag_longs[ConfigOrphans]() + parsed['c'] = flag_longs[ConfigClean]() + parsed['t'] = flag_longs[ConfigTree]() + parsed['a'] = flag_longs[ConfigAutoRemove]() + parsed['k'] = flag_longs[ConfigRank]() + parsed['v'] = flag_longs[ConfigVerify]() + parsed['f'] = flag_longs[ConfigFind]() + for m in help_modes { + longs := parsed[m.key] or { + assert false, 'no struct for mode ${m.key}' + continue + } + named := m.options.map(it.name).join(' ') + ' ' + for long in longs { + if long == 'help' { + continue + } + assert named.contains('--${long} ') || named.contains('--${long},'), '${m.name}: --${long} is parsed and not in the help' + } + } +} + +fn test_wrap_names_edges() { + // nothing to lay out is no text, one name is one indented line + assert wrap_names([], 30) == '' + assert wrap_names(['name'], 30) == ' name' + // a width nothing fits gives every name its own line, never an empty + // one and never a lost name + for width in [0, 1, 4, -3] { + assert wrap_names(['aa', 'bb', 'cc'], width) == ' aa,\n bb,\n cc', '${width}' + } + // a line that goes on keeps room for its comma within the width + text := wrap_names(['aaaa', 'bbbb', 'cccc', 'dddd'], 16) + assert widest(text) <= 16, text + assert text == ' aaaa, bbbb,\n cccc, dddd', text + // info's wrapping is the same rule without the indent + assert wrap_items(['aaaa', 'bbbb', 'cccc', 'dddd'], 12) == ['aaaa, bbbb', 'cccc, dddd'] + assert wrap_items([], 12) == [''] + assert wrap_items(['x'], 0) == ['x'] +} diff --git a/src/info.v b/src/info.v new file mode 100644 index 0000000..6ce8386 --- /dev/null +++ b/src/info.v @@ -0,0 +1,200 @@ +module main + +import alpm + +// InfoLookup is how info and tree find their targets: the installed +// packages first, then the sync dbs, which are only set up — and asked +// about their freshness — by the first target that needs them +struct InfoLookup { +mut: + installed &alpm.List + dbs []&alpm.DB + synced bool +} + +// sync_dbs registers the sync dbs once for all targets +fn (mut l InfoLookup) sync_dbs(mut ui TransUI, mut handle &alpm.Handle) ![]&alpm.DB { + if !l.synced { + l.dbs = init_repos(mut handle)! + check_sync_fresh(mut ui, mut handle)! + l.synced = true + } + return l.dbs +} + +// find resolves one target: 'local/name' in the installed packages alone, +// 'repo/name' in that sync db alone, a bare name in the installed packages +// and then every sync db, like pacman's -Qi with its -Si behind it. a name +// may be a dependency string or something provided. what misses gets the +// nearest name of the same scope offered; an error is the target's own, +// for the caller to report and go on from +fn (mut l InfoLookup) find(mut ui TransUI, mut handle &alpm.Handle, raw string) !&alpm.Package { + target := parse_target(raw) + if target.repo in ['', 'local'] { + if p := find_local_target(l.installed, target.name, true) { + return p + } + } + mut scoped := []&alpm.DB{} + if target.repo != 'local' { + scoped = scope_dbs(l.sync_dbs(mut ui, mut handle)!, target.repo)! + if p := find_sync_target(handle, scoped, target.name, target.repo != '') { + return p + } + } + mut names := []string{} + if target.repo in ['', 'local'] { + names << pkg_names(l.installed.pkgs()) + } + names << sync_names(scoped) + fixed := did_you_mean(mut ui, target.name, names)! + if target.repo in ['', 'local'] { + if p := l.installed.pkg_find(fixed) { + return p + } + } + return find_repo_pkg(scoped, fixed) or { error('unknown package: "${fixed}"') } +} + +fn info(config ConfigInfo) ! { + need_query(config.query, 'package')! + fields := parse_fields(config.fields, pkg_field_names)! + mut ui := new_trans_ui(noconfirm: config.noconfirm) + mut handle := init_handle(ui)! + defer { handle.release() or { went_on('release the alpm handle', err) } } + defer { ui.stop() } + + // package archives on disk are shown directly, pacman's -Qp: loaded, not + // installed. -p says every target is one; without it a single target + // that is a file on disk is still taken for the archive it is + if config.file || (config.query.len == 1 && is_local_pkg_file(config.query[0])) { + info_files(handle, config, fields) + return + } + + mut lookup := InfoLookup{ + installed: local_pkgcache(handle)! + } + mut printed := 0 + for target in config.query { + pkg := lookup.find(mut ui, mut handle, target) or { + target_error(err.msg()) + continue + } + if show_pkg(pkg, config, fields, printed == 0) { + printed++ + } + } +} + +// show_pkg is one target's answer: its changelog with -c, its fields +// otherwise. it says whether anything was shown, which is what the blank +// line before the next one goes by +fn show_pkg(pkg &alpm.Package, config ConfigInfo, fields []string, first bool) bool { + if config.changelog { + return show_changelog(pkg, first) + } + show_info(info_fields(pkg, fields, config.fields != ''), first) + return true +} + +// show_info shows one package's fields: a table on a terminal, after a blank +// line unless it is the first; an info event for a frontend +fn show_info(fields []InfoField, first bool) { + if ipc_on() { + emit(InfoEvent{ + fields: fields + }) + return + } + if !first { + println('') + } + println(info_table(fields)) +} + +// pkg_changelog reads a package's changelog whole, in chunks as libalpm +// hands it out (an fread into the buffer, 0 at its end). none when the +// package carries none: libalpm has one for an installed package and for a +// package file, never for a sync db's entry +fn pkg_changelog(pkg &alpm.Package) ?string { + fp := pkg.changelog_open() + if fp == unsafe { nil } { + return none + } + mut text := []u8{} + mut buf := []u8{len: 4096} + for { + n := int(pkg.changelog_read(buf.data, u32(buf.len), fp)) + if n <= 0 { + break + } + text << buf[..n] + } + pkg.changelog_close(fp) or { + warn('could not close the changelog of ${pkg.get_name()}: ${err.msg()}') + } + return text.bytestr() +} + +// show_changelog is pacman's -Qc: the heading, then the changelog as the +// package carries it. a package without one is said and shows nothing, +// which pacman does not count as a failure either +fn show_changelog(pkg &alpm.Package, first bool) bool { + text := pkg_changelog(pkg) or { + warn('no changelog available for ${pkg.get_name()}') + return false + } + if ipc_on() { + emit(ChangelogEvent{ + package: pkg.get_name() + text: text + }) + return true + } + if !first { + println('') + } + println(heading('changelog for ${pkg.get_name()}:')) + println(text.trim_right('\n')) + return true +} + +// info_files shows package archives from disk, pacman's -Qp, each loaded +// the way pacman's query loads one: whole, with no signature asked for, +// since nothing of it is installed. one that does not load is its own +// target's error, and the rest are still shown +fn info_files(handle &alpm.Handle, config ConfigInfo, fields []string) { + mut printed := 0 + for path in config.query { + pkg := handle.pkg_load(path, 1, 0) or { + target_error('could not load ${path}: ${err.msg()}') + continue + } + if show_pkg(pkg, config, fields, printed == 0) { + printed++ + } + pkg.free_pkg() or { warn('could not free the package of ${path}: ${err.msg()}') } + } +} + +// which finds the installed package that provides a dependency +fn which(config ConfigWhich) ! { + need_query(config.query, 'dependency')! + ui := new_trans_ui() + mut handle := init_handle(ui)! + defer { handle.release() or { went_on('release the alpm handle', err) } } + defer { ui.stop() } + + mut pkgcache := local_pkgcache(handle)! + + mut printed := 0 + for target in config.query { + pkg := pkgcache.find_satisfier(local_target_name(target)) or { + target_error('unknown package: "${target}"') + continue + } + show_info(info_fields(pkg, pkg_field_names, false), printed == 0) + printed++ + } +} diff --git a/src/ipc.v b/src/ipc.v new file mode 100644 index 0000000..5dc36c7 --- /dev/null +++ b/src/ipc.v @@ -0,0 +1,661 @@ +@[has_globals] +module main + +import os +import sync +import json2 + +#include + +// --ui ipc is vpac spoken to by a program instead of a person: a GUI, a web +// UI or a test runs a mode as a child and reads json lines, one event per +// line, from its stdout, answering the questions on its stdin. a root child +// re-executed through the root provider keeps the same pipes, so it speaks +// on them too. +// every event is an object whose "type" says what it is; protocol is bumped +// when an event changes in a way a reader must know about: a new event +// type, a new question kind, a field whose meaning or presence changes, or +// a new field a reader has to read to get the answer right. a field that +// is only ever left out when empty and adds detail a reader may ignore +// rides along without a bump, and is described at its struct. 2: clean's +// build_root is absent when no invoker is known, and owner sends one event +// per owner of a directory. 3: the select question (a group's members, +// answered with a list of indices), clean's unused sync dbs, and the +// changelog event. 4: a provides event of an expression or a bare file name +// carries files, the paths matched in each entry's package. 5: clean's +// build_size_partial, which makes build_size a floor +const ipc_protocol = 5 + +// ui_kind is --ui: 'tty' draws for a terminal, 'ipc' speaks the protocol +__global ui_kind = 'tty' + +// ipc_fd is the channel the events go out on, the stdout vpac was given. +// fd 1 itself is pointed at stderr once the channel is open, so a plain +// print of a mode not yet speaking the protocol lands in the log and never +// in the channel +__global ipc_fd = 1 +__global ipc_started = false +__global ipc_mu = sync.new_mutex() + +fn C.dup2(oldfd int, newfd int) int + +fn C.fcntl(fd int, cmd int, arg int) int + +fn ipc_on() bool { + return ui_kind == 'ipc' +} + +// ipc_start opens the channel. it runs in the process that does the work, +// after the escalation: a re-executed child must find the original fds, and +// opens its own channel. the channel is close-on-exec, so the builds and +// hooks vpac runs never hold the frontend's pipe open +fn ipc_start() { + if ipc_started { + return + } + ipc_started = true + fd := C.dup(1) + if fd < 0 { + // a frontend would read plain text as the protocol: better no run + eprintln(error_text('--ui ipc: could not open the channel on stdout')) + exit(1) + } + if C.fcntl(fd, C.F_SETFD, C.FD_CLOEXEC) < 0 { + // without it, every build and every hook keeps the frontend's pipe + // open: said, since the channel is still good for this run + eprintln('--ui ipc: could not mark the channel close-on-exec') + } + // dup2 answers its new fd (1) on success, so only a negative one is a + // failure: fd 1 otherwise still carries the channel, and a plain print + // of a mode that does not speak the protocol would land there + if C.dup2(2, 1) < 0 { + eprintln(error_text('--ui ipc: could not lead the logs onto stderr')) + exit(1) + } + ipc_fd = fd + // the texts of the events are plain + color_flag = 'never' + emit(HelloEvent{ + protocol: ipc_protocol + root: os.geteuid() == 0 + }) +} + +// emit writes one event as one line. the lock keeps the lines of the +// download callbacks and the main thread whole +fn emit[T](event T) { + line := json2.encode(event) + '\n' + ipc_mu.lock() + ok := channel_write(line) + ipc_mu.unlock() + if !ok { + // the reader of the channel is gone, so the run is over; stderr + // still reaches a log, where a person may learn why + eprintln('${error_text('the frontend closed the channel')} -- last event: ${line.trim_space()}') + exit(1) + } +} + +// channel_write writes the whole line on the channel, and answers whether it +// went out, through write(2) +fn channel_write(line string) bool { + return channel_write_to(ipc_fd, line, sys_write) +} + +// WriteFn is write(2) as channel_write_to calls it: what it wrote, and the +// errno's code when that is -1. the system's in a run; a test's own to script the +// interruptions and the stalls no real channel produces on demand +type WriteFn = fn (fd int, buf voidptr, n int) (int, int) + +fn sys_write(fd int, buf voidptr, n int) (int, int) { + written := int(C.write(fd, buf, n)) + return written, if written < 0 { C.errno } else { 0 } +} + +// channel_write_to writes the whole line on fd. os.fd_write gives up without +// a word when the reader is gone, and a half-written json line is garbage to +// a frontend: every byte is seen out, any failure is reported. a write that +// is interrupted is taken again, and a write that answers nothing has made +// no progress, so it is a failure too — waiting it out would be an endless +// loop for a channel nobody reads +fn channel_write_to(fd int, line string, write WriteFn) bool { + str := line.clone() + mut p := unsafe { voidptr(uint(str.str)) } + mut left := str.len + for left > 0 { + written, code := write(fd, p, left) + if written < 0 { + // a signal cut the write short of starting: errno.h's name for + // it on this system, not a number + if code == C.EINTR { + continue + } + return false + } + if written == 0 { + return false + } + left -= written + p = unsafe { voidptr(uint(p) + uint(written)) } + } + return true +} + +// HelpEvent is a help text, the overview or one mode's +struct HelpEvent { + kind string = 'help' @[json: 'type'] + text string +} + +// HelloEvent opens the stream: the protocol, and whether this process runs +// as root (a child the root provider started) +struct HelloEvent { + kind string = 'hello' @[json: 'type'] + protocol int + root bool +} + +// ExitEvent closes it with the exit status the process is about to have +struct ExitEvent { + kind string = 'exit' @[json: 'type'] + status int +} + +// ErrorEvent is an error line. target marks the error of one target a query +// skipped and went on from; any other error ends the run +struct ErrorEvent { + kind string = 'error' @[json: 'type'] + msg string + target bool +} + +// MessageEvent is a line of text a mode reports, a result line such as +// 'system upgraded' or a warning. error marks one of libalpm's errors, which +// is a warning too, for a reader that knows no error flag +struct MessageEvent { + kind string = 'message' @[json: 'type'] + text string + warning bool + error bool @[omitempty] + // verbose marks a line of the verbose log: a failure of housekeeping + // the run went on from, said only because --verbose asked + verbose bool @[omitempty] +} + +// PhaseEvent is a step of the work: a terminal's spinner. it starts, may be +// renamed by another start, and is done +struct PhaseEvent { + kind string = 'phase' @[json: 'type'] + text string + state string +} + +// ProgressEvent is libalpm's progress through a transaction step: per +// package for the package steps (pkg names it, current of total), once for +// the whole-transaction checks. vpac's own counted steps use it too +struct ProgressEvent { + kind string = 'progress' @[json: 'type'] + op string + pkg string @[omitempty] + percent int + current int + total int +} + +// DownloadEvent is a file libalpm downloads: sent as its percent moves (or +// every quarter second while it does not), and once more when it is done, +// with libalpm's result: 0 fetched, 1 already up to date, -1 failed. a retry +// — libalpm moving on to the next mirror — is an event of its own, retry +// set: resume says the download goes on from where it stopped, otherwise it +// starts over, and its byte counts with it +struct DownloadEvent { + kind string = 'download' @[json: 'type'] + file string + downloaded i64 + total i64 + done bool + result int + retry bool @[omitempty] + resume bool @[omitempty] +} + +// TransPkg is one package of a transaction listing. version is what the +// transaction installs or removes; old_version the installed one an +// install or upgrade replaces, empty for a new package. the sizes are in +// bytes: what it downloads, and what it takes on disk once installed +struct TransPkg { + name string + version string + old_version string + download_size i64 + installed_size i64 +} + +// TransactionEvent is the listing a transaction asks its go-ahead for: the +// proceed question follows it. action is install, upgrade, remove or +// autoremove. a --print preview sends it with preview set, and stops there +struct TransactionEvent { + kind string = 'transaction' @[json: 'type'] + action string + packages []TransPkg + download_size i64 + installed_size i64 +mut: + preview bool +} + +// PackagesEvent is a titled list of packages shown beside a transaction or a +// question: the packages an install removes, the ones an upgrade skips +struct PackagesEvent { + kind string = 'packages' @[json: 'type'] + title string + packages []TransPkg +} + +// DoneEvent is a committed transaction's result, the last word of every +// mode that commits one: what it did — installed, downloaded, removed, +// upgraded, marked — and to which packages (install's and remove's targets, +// autoremove's and upgrade's whole transaction). a mark says the reason the +// packages have now: explicit, depend or unknown. a declined or failed +// transaction sends none +struct DoneEvent { + kind string = 'done' @[json: 'type'] + action string + reason string @[omitempty] + packages []string +} + +// QuestionEvent asks the frontend. question is confirm (yes or no, preset +// the answer an empty one takes), proceed (a transaction's go-ahead, preset +// true) or choose (one of choices, by index, preset 0). the answer is a line +// {"id": id, "answer": true|false|index} on stdin, the same type as preset. +// select asks for any number of choices: preset is every index, and the +// answer a list of indices, an empty one for none. +// under --noconfirm, answer carries the default taken and nothing is read +struct QuestionEvent { + kind string = 'question' @[json: 'type'] + id int + question string + msg string + preset json2.Any + choices []string @[omitempty] + answer ?json2.Any +} + +// InvalidEvent says an answer line did not answer the question asked; the +// question stands and the next line is read +struct InvalidEvent { + kind string = 'invalid' @[json: 'type'] + id int + msg string +} + +// IpcPrompter asks over the channel: each question is an event with an id, +// and its answer the next valid line on stdin. end of input answers as a +// terminal's does: no, and the first choice +struct IpcPrompter { +mut: + noconfirm bool + last_id int +} + +fn (mut p IpcPrompter) confirm(msg string, preset bool) bool { + return p.ask('confirm', msg, if preset { 1 } else { 0 }, []string{}) == 1 +} + +fn (mut p IpcPrompter) proceed(msg string) bool { + return p.ask('proceed', msg, 1, []string{}) == 1 +} + +fn (mut p IpcPrompter) choose(msg string, choices []string) int { + return p.ask('choose', msg, 0, choices) +} + +// pick asks which of the choices, the select question. the choices were +// sent ahead as the listing they are, so the question carries their count +// as the preset alone: every index +fn (mut p IpcPrompter) pick(msg string, count int) []bool { + p.last_id++ + id := p.last_id + all := json2.Any([]json2.Any{len: count, init: json2.Any(index)}) + if p.noconfirm { + emit(QuestionEvent{ + id: id + question: 'select' + msg: msg + preset: all + answer: all + }) + return []bool{len: count, init: true} + } + emit(QuestionEvent{ + id: id + question: 'select' + msg: msg + preset: all + }) + for { + // end of input selects nothing, as on a terminal + line := stdin_line() or { return []bool{len: count} } + return parse_select_answer(line, id, count) or { + emit(InvalidEvent{ + id: id + msg: err.msg() + }) + continue + } + } + return []bool{len: count} +} + +// answer_of reads an answer line down to its answer: the object, and the id +// of the question asked, are what tell an answer from noise +fn answer_of(line string, id int) !json2.Any { + doc := json2.decode[json2.Any](line) or { return error('not json: ${line.trim_space()}') } + if doc !is map[string]json2.Any { + return error('an answer is an object: {"id": id, "answer": answer}') + } + m := doc.as_map() + got := m['id'] or { return error('the answer has no id') } + // json2 hands every json number over as f64: a whole one is an id's + // number, a text is not an id at all + gid := whole_of(got) or { return error("the answer's id is not a number") } + if gid != id { + return error('the question asked is ${id}, not ${gid}') + } + return m['answer'] or { return error('the answer has no answer') } +} + +// parse_select_answer reads the answer to a select question: a list of +// indices into its count choices, which may be empty +fn parse_select_answer(line string, id int, count int) ![]bool { + answer := answer_of(line, id)! + if answer !is []json2.Any { + return error('question ${id} takes a list of indices, 0 to ${count - 1}') + } + mut picked := []bool{len: count} + for item in answer.as_array() { + n := whole_of(item) or { + return error('question ${id} takes a list of indices, 0 to ${count - 1}') + } + if n < 0 || n >= count { + return error('question ${id} takes a list of indices, 0 to ${count - 1}') + } + picked[n] = true + } + return picked +} + +// ask sends a question and waits for its answer: 1 or 0 for a yes or no, +// the index for a choice +fn (mut p IpcPrompter) ask(kind string, msg string, preset int, choices []string) int { + p.last_id++ + id := p.last_id + // a yes or no travels as a bool, a choice as its index + preset_v := if kind == 'choose' { json2.Any(preset) } else { json2.Any(preset == 1) } + if p.noconfirm { + emit(QuestionEvent{ + id: id + question: kind + msg: msg + preset: preset_v + choices: choices + answer: preset_v + }) + return preset + } + emit(QuestionEvent{ + id: id + question: kind + msg: msg + preset: preset_v + choices: choices + }) + for { + // end of input, or a stdin that cannot be read: no, or the first + // choice, as on a terminal. an empty line is a line, and invalid + line := stdin_line() or { return 0 } + answer := parse_answer(line, id, kind, choices.len) or { + emit(InvalidEvent{ + id: id + msg: err.msg() + }) + continue + } + return answer + } +} + +// parse_answer reads one answer line for question id: a bool for a yes or +// no, an index into the choices for a choose. the object, the id and the +// answer's type are what tell an answer from noise, and anything else comes +// back as the error the asker turns into an invalid event, keeping the +// question and reading the next line +fn parse_answer(line string, id int, kind string, count int) !int { + answer := answer_of(line, id)! + if kind == 'choose' { + n := whole_of(answer) or { return error('question ${id} takes an index, 0 to ${count - 1}') } + if n < 0 || n >= count { + return error('question ${id} takes an index, 0 to ${count - 1}') + } + return n + } + if answer !is bool { + return error('question ${id} takes true or false') + } + return if answer.bool() { 1 } else { 0 } +} + +// whole_of keeps a json number that is a whole one, like 1 but not 1.5: the +// question ids and the choice indices travel as integers, and json2's f64 is +// the one type describing them +fn whole_of(a json2.Any) ?int { + if a is f64 && a == f64(int(a)) { + return int(a) + } + return none +} + +// report is a result line of a mode: printed on a terminal, a message event +// for a frontend +fn report(text string) { + if ipc_on() { + emit(MessageEvent{ + text: text + }) + return + } + println(text) +} + +// advise is a plain line that goes with a warning, the advice after it: on +// stderr for a terminal, a message event marked as a warning for a frontend +fn advise(text string) { + warning_line(text, text) +} + +// warn is a warning: on stderr for a terminal, a message event marked as a +// warning for a frontend +fn warn(text string) { + warning_line(text, warning(text)) +} + +// verbose_flag is --verbose on the command line, cfg_verbose the config's +// (options :verbose true): either turns the verbose log on. the config's is +// reset with the config; the flag is the command line's and stays +__global verbose_flag = false +__global cfg_verbose = false + +fn verbose_on() bool { + return verbose_flag || cfg_verbose +} + +// went_on is the verbose log's one kind of line: something of the run's +// housekeeping failed — a handle's release, a temp dir's removal — and the +// run went on, because nothing the user asked for depended on it. without +// --verbose it is kept quiet, as it always was; with it the failure is said, +// on stderr for a terminal and as a message event marked verbose for a +// frontend, so a run that leaves something behind can be asked why +fn went_on(what string, err IError) { + if !verbose_on() { + return + } + text := 'could not ${what}: ${err.msg()}' + if ipc_on() { + emit(MessageEvent{ + text: text + warning: true + verbose: true + }) + return + } + eprintln('verbose: ${text}') +} + +// warning_line is the one way a warning or its advice leaves: the plain +// text as a warning message event for a frontend, the terminal's spelling +// of it on stderr otherwise +fn warning_line(text string, on_terminal string) { + if ipc_on() { + emit(MessageEvent{ + text: text + warning: true + }) + return + } + eprintln(on_terminal) +} + +// ListingEvent is a package list, search's or orphans': the fields, and for +// each package its name and its value of every field, in their order. a +// quiet listing sends the names alone; search -g's entries name the group +// they were listed for +struct ListingEvent { + kind string = 'listing' @[json: 'type'] + fields []string + entries []ListEntry +} + +// GroupsEvent lists the groups of the sync dbs, search -g without names +struct GroupsEvent { + kind string = 'groups' @[json: 'type'] + groups []GroupRef +} + +// InfoEvent is one package as info shows it: every field asked for, its +// value as one text, and the items of a list field +struct InfoEvent { + kind string = 'info' @[json: 'type'] + fields []InfoField +} + +// ChangelogEvent is a package's changelog, info -c: the text as the package +// carries it +struct ChangelogEvent { + kind string = 'changelog' @[json: 'type'] + package string + text string +} + +// FilesEvent is the files of a package: an installed one's under the root +// (files), or a sync one's as its file db lists them (find -l, with repo) +struct FilesEvent { + kind string = 'files' @[json: 'type'] + package string + repo string @[omitempty] + paths []string +} + +// ProvidesEvent is find's answer for one path: the sync packages whose files +// hold it, as a listing. a target that matches many files (-x, or a file +// name with no slash) also names them: files[i] are the paths matched in the +// package of entries[i] +struct ProvidesEvent { + kind string = 'provides' @[json: 'type'] + path string + fields []string + entries []ListEntry + files [][]string @[omitempty] +} + +// OwnerEvent is an installed package that owns a path: one event for a +// file, one per owner for a directory (packages share those), the path +// repeated, as pacman -Qo lists them +struct OwnerEvent { + kind string = 'owner' @[json: 'type'] + path string + package string + version string +} + +// UnsatisfiedEvent is deptest's answer: the dependencies no installed +// package satisfies, none when all are +struct UnsatisfiedEvent { + kind string = 'unsatisfied' @[json: 'type'] + deps []string +} + +// TreeItem is a node of a dependency tree: a package (found), or the +// dependency nothing provides (name is then how it was asked for). seen +// marks a package expanded elsewhere in the tree, whose branches are there +struct TreeItem { + name string + version string + found bool + optional bool + seen bool + children []TreeItem +} + +// TreeEvent is one target's tree: its dependencies, or with reverse what +// requires it +struct TreeEvent { + kind string = 'tree' @[json: 'type'] + reverse bool + root TreeItem +} + +// VerifyEvent is verify's report: a line per finding, problem telling the +// ones that count against a package from notes, and how many packages have +// problems +struct VerifyEvent { + kind string = 'verify' @[json: 'type'] + lines []VerifyLine + bad int +} + +// MirrorEvent is one mirror of a ranking: latency in ms, speed in bytes per +// second, last_sync as the mirror status gives it +struct MirrorEvent { + url string + latency_ms i64 + speed f64 + last_sync string +} + +// MirrorsEvent is rank's result, the fastest first +struct MirrorsEvent { + kind string = 'mirrors' @[json: 'type'] + mirrors []MirrorEvent +} + +// CleanEvent is what clean removes: the cached files and the pkgbuild build +// dirs, with their sizes, and the sync db files of repos the config no +// longer names (dbs). the proceed question follows it, except for a +// --print preview, which stops there. build_root is absent when no invoker +// is known (root running vpac c itself): the builds were not looked at then, +// which an empty root beside an empty list would tell as none found +struct CleanEvent { + kind string = 'clean' @[json: 'type'] + cache_dirs []string + build_root ?string + files []string + files_size u64 + builds []string + build_size u64 + // build_size_partial: part of a build could not be read, and build_size + // is a floor, not the size + build_size_partial bool + dbs []string + preview bool +} diff --git a/src/ipc_test.v b/src/ipc_test.v new file mode 100644 index 0000000..eab2aaf --- /dev/null +++ b/src/ipc_test.v @@ -0,0 +1,395 @@ +module main + +import alpm +import json2 +import os + +fn test_parse_answer() ! { + // a yes or no takes a bool, a choice an index in range + assert parse_answer('{"id":1,"answer":true}', 1, 'confirm', 0)! == 1 + assert parse_answer('{"id":1,"answer":false}\n', 1, 'proceed', 0)! == 0 + assert parse_answer('{"id":4,"answer":2}', 4, 'choose', 3)! == 2 + assert parse_answer('{"answer":0,"id":4}', 4, 'choose', 3)! == 0 + // anything else is refused, and the question stands + for line, why in { + 'garbage': 'not json' + '{"answer":true}': 'no id' + '{"id":2,"answer":true}': 'is 1, not 2' + '{"id":1}': 'no answer' + '{"id":1,"answer":1}': 'true or false' + '{"id":1,"answer":"yes"}': 'true or false' + } { + if _ := parse_answer(line, 1, 'confirm', 0) { + assert false, line + } else { + assert err.msg().contains(why), '${line}: ${err.msg()}' + } + } + for line in ['{"id":1,"answer":3}', '{"id":1,"answer":-1}', '{"id":1,"answer":true}'] { + if _ := parse_answer(line, 1, 'choose', 3) { + assert false, line + } + } +} + +// channel_write lays a whole line on the channel: checked against a real +// pipe, and against an fd that refuses writes, where the line's failure +// comes back instead of hanging +fn test_channel_write() ! { + mut p := os.pipe()! + defer { p.close() } + old := ipc_fd + defer { ipc_fd = old } + ipc_fd = p.write_fd + assert channel_write('{"a":1}\n') == true + line, n := os.fd_read(p.read_fd, 64) + assert line[..n] == '{"a":1}\n' + // a whole line again, after the first + assert channel_write('{}\n') == true + line2, n2 := os.fd_read(p.read_fd, 64) + assert line2[..n2] == '{}\n' +} + +fn test_channel_write_fails_rather_than_hangs() ! { + // a descriptor that cannot be written answers an error at once, the + // closest a test gets to a channel whose reader is gone + tmp := os.join_path(os.vtmp_dir(), 'vpac_test_ipc_ro_${os.getpid()}.txt') + os.write_file(tmp, '')! + os.chmod(tmp, 0o444)! + defer { os.rm(tmp) or {} } + mut f := os.open_file(tmp, 'r')! + defer { f.close() } + old := ipc_fd + defer { ipc_fd = old } + ipc_fd = f.fd + assert !channel_write('{"a":1}\n') +} + +// whole_of keeps a json number that is a whole one: the ids and the choice +// indices have to arrive as integers, never as 1.5 or as text +fn test_whole_of() { + assert whole_of(json2.Any(f64(1))) or { -100 } == 1 + assert whole_of(json2.Any(f64(0))) or { -100 } == 0 + assert whole_of(json2.Any(f64(4096))) or { -100 } == 4096 + assert whole_of(json2.Any(f64(1.5))) == none + assert whole_of(json2.Any('1')) == none +} + +fn test_event_shapes() { + // the type field names the event; a yes or no travels as a bool, a + // choice as its index, and an answer only under --noconfirm + assert json2.encode(QuestionEvent{ + id: 3 + question: 'proceed' + msg: 'proceed?' + preset: json2.Any(true) + }) == '{"type":"question","id":3,"question":"proceed","msg":"proceed?","preset":true}' + assert json2.encode(QuestionEvent{ + id: 1 + question: 'choose' + msg: 'pick' + preset: json2.Any(0) + choices: ['a', 'b'] + answer: json2.Any(0) + }) == '{"type":"question","id":1,"question":"choose","msg":"pick","preset":0,"choices":["a","b"],"answer":0}' + // a search -g entry names its group; any other entry has none + assert json2.encode(ListEntry{ + name: 'zsh' + values: [] + group: 'shells' + }) == '{"name":"zsh","values":[],"group":"shells"}' + assert json2.encode(ListEntry{ + name: 'zsh' + values: [] + }) == '{"name":"zsh","values":[]}' + assert json2.encode(DoneEvent{ + action: 'marked' + reason: 'depend' + packages: ['a'] + }) == '{"type":"done","action":"marked","reason":"depend","packages":["a"]}' + assert json2.encode(ProgressEvent{ + op: 'removing' + percent: 50 + current: 1 + total: 2 + }) == '{"type":"progress","op":"removing","percent":50,"current":1,"total":2}' +} + +fn test_download_event_shapes() { + // a progress report keeps its shape: no retry fields unless retrying + assert json2.encode(DownloadEvent{ + file: 'a.pkg' + downloaded: 10 + total: 20 + }) == '{"type":"download","file":"a.pkg","downloaded":10,"total":20,"done":false,"result":0}' + assert json2.encode(DownloadEvent{ + file: 'a.pkg' + retry: true + }) == '{"type":"download","file":"a.pkg","downloaded":0,"total":0,"done":false,"result":0,"retry":true}' + assert json2.encode(DownloadEvent{ + file: 'a.pkg' + retry: true + resume: true + }).ends_with('"retry":true,"resume":true}') +} + +fn test_download_due() { + beat := download_beat + // the first report of a download always goes out + assert download_due(none, 0, 0) + last := DownloadSent{ + percent: 3 + at: 1000 + } + // the percent moved: out, at once + assert download_due(last, 4, 1001) + // the same percent within a beat: held back + assert !download_due(last, 3, 1000 + beat - 1) + // the same percent a beat later: out, so a slow download keeps a frontend + // informed between its percents + assert download_due(last, 3, 1000 + beat) + assert download_due(last, 3, 1000 + 10 * beat) +} + +// downloads_said feeds ipc_download libalpm's own event structs and returns +// the events it sent +fn downloads_said(feed fn (mut ui TransUI)) ![]map[string]json2.Any { + path := os.join_path(os.vtmp_dir(), 'vpac_test_dl_${os.getpid()}') + mut f := os.create(path)! + defer { os.rm(path) or {} } + old := ipc_fd + ipc_fd = f.fd + mut ui := new_trans_ui() + feed(mut ui) + ipc_fd = old + f.close() + mut out := []map[string]json2.Any{} + for line in os.read_lines(path)! { + out << json2.decode[json2.Any](line)!.as_map() + } + return out +} + +fn test_ipc_download_retry() ! { + events := downloads_said(fn (mut ui TransUI) { + mut p := alpm.DownloadEventProgress{ + downloaded: 50 + total: 100 + } + ipc_download(mut ui, 'a.pkg', .progress, voidptr(&p)) + // the same percent right after: held back + ipc_download(mut ui, 'a.pkg', .progress, voidptr(&p)) + mut r := alpm.DownloadEventRetry{ + resume: 0 + } + ipc_download(mut ui, 'a.pkg', .retry, voidptr(&r)) + // started over from the next mirror: its first report goes out, + // whatever the percent last said + p.downloaded = 0 + ipc_download(mut ui, 'a.pkg', .progress, voidptr(&p)) + mut r2 := alpm.DownloadEventRetry{ + resume: 1 + } + ipc_download(mut ui, 'a.pkg', .retry, voidptr(&r2)) + mut c := alpm.DownloadEventCompleted{ + total: 100 + result: 0 + } + ipc_download(mut ui, 'a.pkg', .completed, voidptr(&c)) + })! + assert events.len == 5 + assert events[0]['downloaded']!.int() == 50 + assert events[1]['retry']!.bool() + assert 'resume' !in events[1] + assert events[2]['downloaded']!.int() == 0 + assert 'retry' !in events[2] + assert events[3]['retry']!.bool() + assert events[3]['resume']!.bool() + assert events[4]['done']!.bool() +} + +fn test_ipc_download_dedupes_per_file() ! { + events := downloads_said(fn (mut ui TransUI) { + mut a := alpm.DownloadEventProgress{ + downloaded: 10 + total: 100 + } + mut b := alpm.DownloadEventProgress{ + downloaded: 10 + total: 100 + } + // two files at the same percent are two reports, not one held back + ipc_download(mut ui, 'a.pkg', .progress, voidptr(&a)) + ipc_download(mut ui, 'b.pkg', .progress, voidptr(&b)) + // a's percent moves: out; b stays: held back + a.downloaded = 20 + ipc_download(mut ui, 'a.pkg', .progress, voidptr(&a)) + ipc_download(mut ui, 'b.pkg', .progress, voidptr(&b)) + })! + assert events.map(it['file']!.str()) == ['a.pkg', 'b.pkg', 'a.pkg'] +} + +fn test_message_event_shape() { + // a plain message and a warning keep their shape; only libalpm's errors + // carry the error flag, beside the warning one + assert json2.encode(MessageEvent{ + text: 'system upgraded' + }) == '{"type":"message","text":"system upgraded","warning":false}' + assert json2.encode(MessageEvent{ + text: 'careful' + warning: true + }) == '{"type":"message","text":"careful","warning":true}' + assert json2.encode(MessageEvent{ + text: 'broke' + warning: true + error: true + }) == '{"type":"message","text":"broke","warning":true,"error":true}' +} + +// ScriptedWrites is a write(2) that answers from a script: each step is how +// many bytes the call takes (at most what it is offered), or -1 with an +// errno; what it took is kept, in order +@[heap] +struct ScriptedWrites { +mut: + steps []int + code int + calls int + got []u8 +} + +fn (mut w ScriptedWrites) write(_ int, buf voidptr, n int) (int, int) { + if w.calls >= w.steps.len { + // past the script, take everything + w.got << unsafe { (&u8(buf)).vbytes(n) } + w.calls++ + return n, 0 + } + step := w.steps[w.calls] + w.calls++ + if step < 0 { + return -1, w.code + } + take := if step < n { step } else { n } + w.got << unsafe { (&u8(buf)).vbytes(take) } + return take, 0 +} + +fn scripted_write(steps []int, code int, line string) (bool, string, int) { + mut w := &ScriptedWrites{ + steps: steps + code: code + } + ok := channel_write_to(9, line, fn [mut w] (fd int, buf voidptr, n int) (int, int) { + return w.write(fd, buf, n) + }) + return ok, w.got.bytestr(), w.calls +} + +fn test_channel_write_interrupted_is_taken_again() { + // EINTR before anything went out, and again part way: the line still + // goes out whole, in order, nothing twice + ok, got, calls := scripted_write([-1, 3, -1, 2], C.EINTR, '{"a":1}\n') + assert ok + assert got == '{"a":1}\n' + assert calls == 5 +} + +fn test_channel_write_short_writes_add_up() { + ok, got, _ := scripted_write([1, 1, 1, 1, 1, 1, 1], 0, '{"b":22}\n') + assert ok + assert got == '{"b":22}\n' +} + +fn test_channel_write_without_progress_fails() { + // a write that answers nothing would loop forever: it is a failure, at + // once, whatever went out before it + ok, got, calls := scripted_write([2, 0], 0, '{"c":3}\n') + assert !ok + assert got == '{"' + assert calls == 2 +} + +fn test_channel_write_other_errors_fail() { + // a reader that is gone (EPIPE) is no interruption: no retry + ok, _, calls := scripted_write([-1], 32, '{}\n') + assert !ok + assert calls == 1 +} + +fn test_transaction_event_shapes() ! { + // the listing a go-ahead is asked for: its packages whole, the sizes + // summed by whoever built it, and preview said either way so a reader + // never guesses whether a question follows + ev := TransactionEvent{ + action: 'upgrade' + packages: [ + TransPkg{ + name: 'foo' + version: '2.0-1' + old_version: '1.0-1' + download_size: 10 + installed_size: 30 + }, + TransPkg{ + name: 'new' + version: '1.0-1' + }, + ] + download_size: 10 + installed_size: 30 + } + m := json2.decode[json2.Any](json2.encode(ev))!.as_map() + assert m['type']!.str() == 'transaction' + assert m['action']!.str() == 'upgrade' + assert m['download_size']!.i64() == 10 && m['installed_size']!.i64() == 30 + assert !m['preview']!.bool() + pkgs := m['packages']!.as_array().map(it.as_map()) + assert pkgs.len == 2 + assert pkgs[0]['name']!.str() == 'foo' && pkgs[0]['old_version']!.str() == '1.0-1' + assert pkgs[0]['download_size']!.i64() == 10 && pkgs[0]['installed_size']!.i64() == 30 + // a package that was not installed before has an empty old version, + // present all the same: every package has the same keys + assert pkgs[1]['old_version']!.str() == '' + assert pkgs[1].keys() == pkgs[0].keys() + // a preview is the same event with the mark set + mut preview := ev + preview.preview = true + assert json2.decode[json2.Any](json2.encode(preview))!.as_map()['preview']!.bool() + // a transaction of nothing still carries its list, empty + empty := json2.decode[json2.Any](json2.encode(TransactionEvent{ action: 'remove' }))!.as_map() + assert empty['packages']!.as_array().len == 0 + assert empty['download_size']!.i64() == 0 + // sizes past 32 bits travel whole + big := json2.decode[json2.Any](json2.encode(TransactionEvent{ + action: 'install' + download_size: i64(6) * 1024 * 1024 * 1024 + installed_size: i64(20) * 1024 * 1024 * 1024 + }))!.as_map() + assert big['download_size']!.i64() == i64(6) * 1024 * 1024 * 1024 + assert big['installed_size']!.i64() == i64(20) * 1024 * 1024 * 1024 + // the packages event beside it has the same package shape + shown := json2.decode[json2.Any](json2.encode(PackagesEvent{ + title: '1 packages to remove:' + packages: [TransPkg{ + name: 'old' + version: '1.0-1' + }] + }))!.as_map() + assert shown['type']!.str() == 'packages' + assert shown['packages']!.as_array()[0].as_map().keys() == pkgs[0].keys() + // a provides event names its files only when it has some to name + assert json2.encode(ProvidesEvent{ + path: '/usr/bin/x' + fields: ['name'] + }) == '{"type":"provides","path":"/usr/bin/x","fields":["name"],"entries":[]}' + assert json2.encode(ProvidesEvent{ + path: 'x' + fields: ['name'] + entries: [ListEntry{ + name: 'p' + values: ['p'] + }] + files: [['usr/bin/x']] + }).ends_with(',"files":[["usr/bin/x"]]}') +} diff --git a/src/mirrors.v b/src/mirrors.v new file mode 100644 index 0000000..c68f913 --- /dev/null +++ b/src/mirrors.v @@ -0,0 +1,554 @@ +@[has_globals] +module main + +import blip.vlib.blip.printer +import json2 +import net.http +import os +import time + +// mirror ranking, after rate-mirrors (westandskif/rate-mirrors): gather the +// candidates, drop the unusable ones, time one byte for latency, then time a +// repo database for speed, and rank by speed. the oses the ranker knows are +// in rank_oses; the protocols to rank come from the config + +// the rank form's filters and sizes, (rank :completion :max-delay :candidates +// :retest :top): how complete and how fresh a mirror must be to be probed, +// how many of the lowest latencies get the speed test, how many of the +// fastest are timed again, and how many are answered when -n names none +__global rank_min_completion = 1.0 +__global rank_max_delay = i64(86400) + +// rank_parallelism is how many mirrors to probe at once: the rank form's +// :parallel when it sets one, else the network's :parallel +fn rank_parallelism() int { + return if rank_parallel > 0 { rank_parallel } else { parallel_downloads } +} + +__global rank_speed_candidates = 40 +__global rank_retest = 5 +__global rank_top = 10 + +// RankOs is one os the ranker knows. the mirror data comes from the status +// api when the os publishes one, else from a plain Server = mirrorlist, which +// carries no completion or delay to filter by. repo is the repo whose db the +// speed test pulls, named again in the written urls +struct RankOs { + status_json string + mirrorlist string + repo string +} + +// default_rank_oses are the oses the ranker knows before the config speaks +fn default_rank_oses() map[string]RankOs { + return { + 'artix': RankOs{ + status_json: 'https://status.artixlinux.org/mirrors/status/json/' + repo: 'system' + } + 'arch': RankOs{ + status_json: 'https://archlinux.org/mirrors/status/json/' + repo: 'core' + } + 'cachyos': RankOs{ + mirrorlist: 'https://raw.githubusercontent.com/CachyOS/CachyOS-PKGBUILDS/master/cachyos-mirrorlist/cachyos-mirrorlist' + repo: 'cachyos' + } + } +} + +// rank_oses are the oses the ranker knows: the defaults, and every one the +// config's (mirrorlist ...) form defines or redefines. rank_dir is where a +// ranking is written for the config to require, (rank :dir) +__global rank_oses = default_rank_oses() +__global rank_dir = '/etc/vpac.d/mirrors' + +// rank_os_names spells the known oses for a message, sorted: the text is +// the same whatever order the config's forms came in +fn rank_os_names() string { + mut names := rank_oses.keys() + names.sort() + return names.join(', ') +} + +// rank_os_name picks the os to rank: the one named on the command line, or +// the running system's, read from /etc/os-release +fn rank_os_name(query []string) !string { + if query.len > 1 { + return error('rank takes one os: ${rank_os_names()}') + } + if query.len == 1 { + if query[0] !in rank_oses.keys() { + return error('the ranker knows ${rank_os_names()}, not "${query[0]}": define it with (mirrorlist :name ...) in the config') + } + return query[0] + } + text := os.read_file('/etc/os-release') or { + return error('could not read /etc/os-release to detect the os: pass one of ${rank_os_names()}') + } + mut id := '' + mut like := '' + for line in text.split_into_lines() { + if line.starts_with('ID=') { + id = line[3..].trim_space().trim('"\'') + } else if line.starts_with('ID_LIKE=') { + like = line[8..].trim_space().trim('"\'') + } + } + for candidate in [id, ...like.split(' ')] { + if candidate in rank_oses.keys() { + return candidate + } + } + return error('this system (${id}) is not one the ranker knows: pass one of ${rank_os_names()}, or define it with (mirrorlist :name ...) in the config') +} + +// rank_write_target is where a ranked os is written for the config to require +fn rank_write_target(os_name string) string { + return os.join_path(rank_dir, '${os_name}.lip') +} + +struct StatusMirror { + url string + protocol string + last_sync string + completion_pct ?f64 + delay ?i64 + active bool + country_code string +} + +struct StatusList { + urls []StatusMirror +} + +// Mirror is a candidate: its full url template, with the repo and arch +// placeholders left in place the way the config's mirror files hold them, and +// when it last synced +struct Mirror { + url string + last_sync string +} + +// probe_url is the concrete url of one mirror's repo db: the template with +// the repo and arch substituted in, plus the db file. a path override takes +// the mirror root instead, which is where a custom file hangs from +fn probe_url(m Mirror, spec RankOs, override string) string { + if override != '' { + return m.url.all_before('$') + override + } + return m.url.replace('$repo', spec.repo).replace('$arch', arch) + '/${spec.repo}.db' +} + +fn with_slash(url string) string { + return if url.ends_with('/') { url } else { url + '/' } +} + +// timed_fetch fetches one url with the rank timeout on both directions, and +// hands back the body: it is what the ranker asks of the network, from the +// mirror status on to the mirrorlists, since a stalled dns or a captive +// portal would otherwise visit its hang on the ranking +fn timed_fetch(url string, what string) !string { + return http_text(url, rank_timeout, what, url) +} + +// http_text is one GET bounded by a timeout, in seconds, on both +// directions, answering the body of an answer that succeeded. what names +// the fetch and from the server in the error, so a refusal is told from a +// stall. the ranker's fetches and the pkgbuild rpc both go through it +fn http_text(url string, seconds int, what string, from string) !string { + mut req := http.Request{ + url: url + read_timeout: seconds * time.second + write_timeout: seconds * time.second + } + resp := req.do() or { return error('${what} failed: ${err}') } + if resp.status_code < 200 || resp.status_code >= 300 { + return error('${what} failed: http ${resp.status_code} from ${from}') + } + return resp.body +} + +// fetch_status_mirrors reads an os's mirror status and keeps the mirrors that +// are usable: active, on a configured protocol, fully synced, recently synced, +// with a known country +fn fetch_status_mirrors(os_name string, spec RankOs) ![]Mirror { + body := timed_fetch(spec.status_json, 'fetching the ${os_name} mirror status')! + status := json2.decode[StatusList](body) or { + return error('could not read the ${os_name} mirror status: ${err.msg()}') + } + mut out := []Mirror{} + for m in status.urls { + completion := m.completion_pct or { continue } + delay := m.delay or { continue } + if m.active && m.protocol in cfg_protocols && completion >= rank_min_completion + && delay <= rank_max_delay && m.country_code != '' { + // the status api gives the mirror root; the repo layout of the os + // completes it to the template the config's mirror files hold + out << Mirror{ + url: with_slash(m.url) + '$repo/os/$arch' + last_sync: m.last_sync + } + } + } + return out +} + +// fetch_mirrorlist reads a plain Server = list, for the oses that publish no +// status api: fetched, or read from the disk when the config names a path +fn fetch_mirrorlist(spec RankOs) ![]Mirror { + if spec.mirrorlist.starts_with('/') { + text := os.read_file(spec.mirrorlist) or { + return error('could not read the mirrorlist ${spec.mirrorlist}: ${err.msg()}') + } + return parse_mirrors(text) + } + body := timed_fetch(spec.mirrorlist, 'fetching the mirrorlist')! + return parse_mirrors(body) +} + +// parse_mirrors reads 'Server = url' lines or bare urls, one per line, as the +// mirrorlists write them. the line already carries the os's repo layout, so +// it is kept whole +fn parse_mirrors(text string) []Mirror { + mut out := []Mirror{} + mut seen := map[string]bool{} + for line in text.split_into_lines() { + mut s := line.trim_space() + if s.starts_with('Server = ') { + s = s.all_after('Server = ').trim_space() + } + if s.starts_with('#') || !(s.starts_with('https://') || s.starts_with('http://')) { + continue + } + if seen[s] { + continue + } + seen[s] = true + out << Mirror{ + url: s + } + } + return out +} + +// stdin_text reads stdin to its end, the lines joined again. a read error is +// an error here, not an end: a mirror list cut short must not rank as the +// whole of it +fn stdin_text() !string { + mut lines := []string{} + for { + lines << stdin_line() or { + if err is StdinEnd { + break + } + return err + } + } + return lines.join('\n') +} + +// timed_get fetches a url and returns the milliseconds it took and the size +// of the answer. range asks for the first byte only, which measures latency. +// the timeout comes from the config, and it bounds the probe twice over: each +// read and write on its own, and the answer as a whole. the socket timeouts +// alone start over with every read, so a mirror that trickles its db a few +// bytes at a time would hold a speed probe for as long as it cared to; the +// deadline is looked at on each chunk that arrives, and an answer still +// arriving past it is the probe's failure +fn timed_get(url string, range bool) !(i64, int) { + limit := rank_timeout + deadline := time.now().add(limit * time.second) + mut req := http.Request{ + url: url + read_timeout: limit * time.second + write_timeout: limit * time.second + on_progress: fn [deadline, limit] (_ &http.Request, _ []u8, _ u64) ! { + if time.now() > deadline { + return error('no whole answer within ${limit}s') + } + } + } + if range { + req.header.add_custom('Range', 'bytes=0-0')! + } + start := time.now() + resp := req.do()! + // an answer that needs no body — a 404, a 403 — is a mirror that does + // not serve the repo db: a probe without body size is ranked on air + // unless the status is turned into the probe's failure + if resp.status_code < 200 || resp.status_code >= 300 { + return error('http ${resp.status_code} from ${url}') + } + return (time.now() - start).milliseconds(), resp.body.len +} + +fn probe_latency(m Mirror, spec RankOs, override string) Probe { + ms, _ := timed_get(probe_url(m, spec, override), true) or { + return Probe{ + url: m.url + } + } + return timed_probe(m.url, ms, 0, false) +} + +fn probe_speed(m Mirror, spec RankOs, override string) Probe { + ms, bytes := timed_get(probe_url(m, spec, override), false) or { + return Probe{ + url: m.url + } + } + return timed_probe(m.url, ms, bytes, true) +} + +// timed_probe is a probe's result out of what the timed request measured: +// the latency always, and with speed the bytes a second of a whole fetch — +// one that brought no bytes failed, and one quicker than the clock's +// millisecond counts as one, never a division by zero +fn timed_probe(url string, ms i64, bytes int, speed bool) Probe { + if !speed { + return Probe{ + url: url + latency_ms: ms + ok: true + } + } + if bytes <= 0 { + return Probe{ + url: url + } + } + elapsed := if ms <= 0 { 1 } else { ms } + return Probe{ + url: url + latency_ms: ms + speed: f64(bytes) / (f64(elapsed) / 1000.0) + ok: true + } +} + +// Probe is the result of testing one mirror +struct Probe { + url string + latency_ms i64 + speed f64 + ok bool +} + +// ProbeFn measures one mirror, the os and the path override closed over. it +// answers a Probe on every path — a failure is a Probe that is not ok — and +// that is what lets probe_batch count on one answer per mirror +type ProbeFn = fn (Mirror) Probe + +// probe_batch tests every mirror, rank_parallelism() at a time, and advances +// the bar by each finished probe. quiet draws no bar, so the output can be +// piped. the answers come back in the order they finish, not the input's +fn probe_batch(mut ui TransUI, label string, mirrors []Mirror, probe ProbeFn, quiet bool) []Probe { + mut out := []Probe{cap: mirrors.len} + if mirrors.len == 0 { + return out + } + mut bar := unsafe { &Meter(nil) } + if !quiet { + bar = ui.meter(i64(mirrors.len), label) + bar.start() + } + // a parallelism that slipped past the config's floor would start no + // worker at all: one at a time is the least + conc := if rank_parallelism() < 1 { 1 } else { rank_parallelism() } + workers := if conc < mirrors.len { conc } else { mirrors.len } + // the whole batch is queued, then the queue closed: a worker that finds + // it drained is done. a pool rather than slots of conc means a slow probe + // holds back only its own worker, not the next slot's fast ones + jobs := chan Mirror{cap: mirrors.len} + for m in mirrors { + jobs <- m + } + jobs.close() + // the answers channel holds a whole batch, so a worker never waits on the + // collector to hand its answer over + answers := chan Probe{cap: mirrors.len} + for _ in 0 .. workers { + spawn probe_worker(jobs, answers, probe) + } + // one answer per mirror, each sent by the worker that took it: the probe + // answers on every path, and a panic in any thread ends the process + // rather than stranding this loop. a probe that hangs is bounded by the + // network's own timeouts (rank_timeout on read and write, the net + // module's on connect) and by timed_get's deadline on the whole answer + for _ in 0 .. mirrors.len { + out << <-answers + if !quiet { + bar.add(i64(1)) + } + } + return out +} + +// probe_worker measures mirrors until the queue runs dry. the probe runs on +// this thread: the arguments of a spawned call are evaluated by the caller, +// so spawning the send of a probe's result runs every probe on the collector, +// one after another +fn probe_worker(jobs chan Mirror, answers chan Probe, probe ProbeFn) { + for { + m := <-jobs or { return } + answers <- probe(m) + } +} + +fn speed_mib(bytes_per_sec f64) string { + return '${bytes_per_sec / 1048576.0:.2f} MiB/s' +} + +fn sync_age(last_sync string) string { + if last_sync == '' { + return '-' + } + synced := time.parse_rfc3339(last_sync) or { return '-' } + hours := (time.now().unix() - synced.unix()) / 3600 + return '${hours}h ago' +} + +// mirrors_lip is the blip file of the ranked urls: mirrors/.lip defines +// mirrors-, the way repos.lip expects. each url is a string literal +// escaped by blip's own printer: the urls come from the network and the file +// is config that vpac runs as root, so a quote in a url must stay inside its +// string +fn mirrors_lip(os_name string, urls []string, date string) string { + var := 'mirrors-${os_name}' + mut content := '; mirrors for ${os_name}, ranked by vpac k -w on ${date}\n' + content += '(unless (defined? ${var}) (define ${var} []))\n' + content += '(array-append! ${var} [${urls.map(printer.quote_string(it)).join(' ')}])\n' + return content +} + +// write_config_mirrors writes the ranked urls as the blip file the config +// requires +fn write_config_mirrors(os_name string, urls []string) !string { + target := rank_write_target(os_name) + os.mkdir_all(os.dir(target))! + os.write_file(target, mirrors_lip(os_name, urls, time.now().custom_format('YYYY-MM-DD')))! + return target +} + +// Ranked is one mirror of a ranking: its probe, and when it last synced as +// the mirror status says ('' when it is not known) +struct Ranked { + Probe + last_sync string +} + +// rank_mirrors measures the mirrors of an os and returns the best of them, +// at most config.top, fastest first. the probes draw on the ui unless the +// result goes to a file or a mirrorlist +fn rank_mirrors(mut ui TransUI, os_name string, config ConfigRank) ![]Ranked { + spec := rank_oses[os_name] + mirrors := if config.stdin { + parse_mirrors(stdin_text()!) + } else if spec.status_json != '' { + fetch_status_mirrors(os_name, spec)! + } else { + fetch_mirrorlist(spec)! + } + if mirrors.len == 0 { + return error('no usable mirrors to rank') + } + mut sync_of := map[string]string{} + for m in mirrors { + sync_of[m.url] = m.last_sync + } + + quiet := config.mirrorlist || config.output != '' + override := config.path + mut latency := probe_batch(mut ui, 'latency', mirrors, fn [spec, override] (m Mirror) Probe { + return probe_latency(m, spec, override) + }, quiet).filter(it.ok) + latency.sort(a.latency_ms < b.latency_ms) + if latency.len > rank_speed_candidates { + latency = latency[..rank_speed_candidates].clone() + } + candidates := latency.map(Mirror{ + url: it.url + last_sync: sync_of[it.url] or { '' } + }) + + mut results := probe_batch(mut ui, 'speed', candidates, fn [spec, override] (m Mirror) Probe { + return probe_speed(m, spec, override) + }, quiet).filter(it.ok) + results.sort(a.speed > b.speed) + + // the best few are measured again, one at a time, and averaged, so one + // lucky or unlucky transfer does not decide the order + for i in 0 .. if results.len < rank_retest { results.len } else { rank_retest } { + again := probe_speed(Mirror{ url: results[i].url }, spec, config.path) + if again.ok { + results[i] = Probe{ + url: results[i].url + latency_ms: results[i].latency_ms + speed: (results[i].speed + again.speed) / 2.0 + ok: true + } + } + } + results.sort(a.speed > b.speed) + ui.stop() + + if results.len == 0 { + return error('no mirror answered the speed test') + } + top := if results.len < config.top { results.len } else { config.top } + return results[..top].map(Ranked{ + Probe: it + last_sync: sync_of[it.url] or { '' } + }) +} + +// rank ranks the mirrors, then writes them where config says, or prints them +fn rank(config ConfigRank) ! { + os_name := rank_os_name(config.query)! + mut ui := new_trans_ui() + defer { + ui.stop() + } + ranked := rank_mirrors(mut ui, os_name, config)! + + urls := ranked.map(it.url) + if config.write { + target := write_config_mirrors(os_name, urls)! + report('wrote ${urls.len} mirrors to ${target}') + } + // a frontend gets the ranking itself, and formats it as it needs: the + // mirrorlist and output forms shape the printable text, which under + // --ui ipc lands in the log anyway, so the event goes out before + // whatever those flags do with the result + if ipc_on() { + emit(MirrorsEvent{ + mirrors: ranked.map(MirrorEvent{ + url: it.url + latency_ms: it.latency_ms + speed: it.speed + last_sync: it.last_sync + }) + }) + } + if config.output != '' { + os.write_file(config.output, urls.map('Server = ${it}').join('\n') + '\n')! + report('wrote ${urls.len} mirrors to ${config.output}') + return + } + if config.mirrorlist { + println(urls.map('Server = ${it}').join('\n')) + return + } + if ipc_on() { + return + } + // sync paints the finished spinner frames before the ranking prints + ui.sync() + mut rows := []Row{} + for i, m in ranked { + rows << row('${i + 1}', m.url.all_before('$'), '${m.latency_ms} ms', speed_mib(m.speed), + sync_age(m.last_sync)) + } + println(table_text(rows, '', ' ')) +} diff --git a/src/mirrors_test.v b/src/mirrors_test.v new file mode 100644 index 0000000..e163d36 --- /dev/null +++ b/src/mirrors_test.v @@ -0,0 +1,314 @@ +module main + +import blip.vlib.blip.machine +import net +import sync +import time + +// mirrors_machine is a blip machine set up the way load_config sets one up, +// for what a mirrors file needs +fn mirrors_machine() &machine.Machine { + mut m := machine.new_standalone(&QuietConfigHost{}) + m.prims['array-append!'] = prim_array_append + return m +} + +fn mirrors_read(mut m machine.Machine, var string) ![]string { + return m.run_str(var)!.as_vector().data.map(it.as_string()) +} + +fn test_mirrors_lip_round_trip() ! { + urls := [ + 'https://ok.example/' + r'$repo/os/$arch', + 'https://quote.example/a"b', + 'https://backslash.example/a\\b', + 'https://newline.example/a\nb', + 'https://tab.example/a\tb', + // closes its string and the form, then defines something + 'https://x.example/"]) (define pwned 1) (array-append! mirrors-arch ["', + ] + text := mirrors_lip('arch', urls, '2026-11-08') + assert text.starts_with('; mirrors for arch, ranked by vpac k -w on 2026-11-08\n') + mut m := mirrors_machine() + m.run_str(text)! + assert mirrors_read(mut m, 'mirrors-arch')! == urls + if _ := m.run_str('pwned') { + assert false, 'a url ran as code' + } +} + +fn test_mirrors_lip_appends() ! { + // the file adds to a list the config may have started already + mut m := mirrors_machine() + m.run_str('(define mirrors-arch ["https://first.example/"])')! + m.run_str(mirrors_lip('arch', ['https://second.example/'], 'today'))! + assert mirrors_read(mut m, 'mirrors-arch')! == ['https://first.example/', 'https://second.example/'] +} + +fn test_mirrors_lip_empty() ! { + mut m := mirrors_machine() + m.run_str(mirrors_lip('artix', [], 'today'))! + assert mirrors_read(mut m, 'mirrors-artix')!.len == 0 +} + +// ProbeTally is what a fake probe records across the batch's threads: how +// many ran at once, at the most, and which mirrors it was handed +@[heap] +struct ProbeTally { +mut: + mu &sync.Mutex = sync.new_mutex() + in_flight int + peak int + seen []string + // stalled is set by the first probe that gave up waiting for company, + // so a serial batch fails the test in one wait rather than one per mirror + stalled bool +} + +fn (mut t ProbeTally) enter(url string) { + t.mu.lock() + t.in_flight++ + if t.in_flight > t.peak { + t.peak = t.in_flight + } + t.seen << url + t.mu.unlock() +} + +fn (mut t ProbeTally) leave() { + t.mu.lock() + t.in_flight-- + t.mu.unlock() +} + +// wait_for_peak holds a probe until n probes have been in flight at once, or +// a second has passed: probes that run one after another never get there +fn (mut t ProbeTally) wait_for_peak(n int) { + deadline := time.now().add(time.second) + for { + t.mu.lock() + done := t.peak >= n || t.stalled + t.mu.unlock() + if done { + return + } + if time.now() > deadline { + t.mu.lock() + t.stalled = true + t.mu.unlock() + return + } + time.sleep(time.millisecond) + } +} + +fn probe_mirrors(n int) []Mirror { + return []Mirror{len: n, init: Mirror{ + url: 'https://m${index}.example/' + }} +} + +// probe_batch_with runs a quiet batch with the rank parallelism set to conc, +// the globals it reads put back after +fn probe_batch_with(conc int, mirrors []Mirror, probe ProbeFn) []Probe { + saved_rank, saved_net := rank_parallel, parallel_downloads + defer { + rank_parallel, parallel_downloads = saved_rank, saved_net + } + rank_parallel, parallel_downloads = conc, conc + mut ui := new_trans_ui() + return probe_batch(mut ui, 'test', mirrors, probe, true) +} + +fn test_probe_batch_answers_once_per_mirror() { + mirrors := probe_mirrors(13) + mut tally := &ProbeTally{} + // every other mirror fails: a failed probe is still its mirror's answer + out := probe_batch_with(4, mirrors, fn [mut tally] (m Mirror) Probe { + tally.enter(m.url) + tally.leave() + return Probe{ + url: m.url + ok: m.url.all_after('//m').all_before('.').int() % 2 == 0 + } + }) + assert out.len == mirrors.len + mut got := out.map(it.url) + got.sort() + mut want := mirrors.map(it.url) + want.sort() + assert got == want + assert out.filter(it.ok).len == 7 + tally.seen.sort() + assert tally.seen == want +} + +fn test_probe_batch_probes_run_in_parallel() { + // the probes must overlap, conc of them at once and never more: a probe + // evaluated by the collector before its spawn runs the batch serially + mirrors := probe_mirrors(9) + mut tally := &ProbeTally{} + out := probe_batch_with(3, mirrors, fn [mut tally] (m Mirror) Probe { + tally.enter(m.url) + tally.wait_for_peak(3) + tally.leave() + return Probe{ + url: m.url + ok: true + } + }) + assert out.len == 9 + assert !tally.stalled, 'the probes ran one at a time' + assert tally.peak == 3 +} + +fn test_probe_batch_zero_parallelism_still_probes() { + // a parallelism of 0 slipped past the config's floor starts one worker, + // not none (which would leave the collector waiting forever) + mirrors := probe_mirrors(5) + mut tally := &ProbeTally{} + out := probe_batch_with(0, mirrors, fn [mut tally] (m Mirror) Probe { + tally.enter(m.url) + tally.leave() + return Probe{ + url: m.url + ok: true + } + }) + assert out.len == 5 + assert tally.peak == 1 +} + +fn test_probe_batch_more_workers_than_mirrors() { + mirrors := probe_mirrors(2) + out := probe_batch_with(16, mirrors, fn (m Mirror) Probe { + return Probe{ + url: m.url + ok: true + } + }) + assert out.len == 2 +} + +fn test_probe_batch_empty() { + out := probe_batch_with(4, []Mirror{}, fn (m Mirror) Probe { + assert false, 'no mirror to probe' + return Probe{} + }) + assert out.len == 0 +} + +// trickle_mirror answers every connection on the listener with a body of +// total bytes, sent one byte each pause: each read lands well inside the +// socket timeout while the whole answer takes total pauses. it ends when the +// listener closes, and a client that hangs up ends its own connection +fn trickle_mirror(mut l net.TcpListener, total int, pause time.Duration) { + for { + mut conn := l.accept() or { return } + spawn trickle_answer(mut conn, total, pause) + } +} + +fn trickle_answer(mut conn net.TcpConn, total int, pause time.Duration) { + defer { + conn.close() or {} + } + mut request := []u8{len: 4096} + conn.read(mut request) or { return } + conn.write_string('HTTP/1.1 200 OK\r\nContent-Length: ${total}\r\nConnection: close\r\n\r\n') or { + return + } + for _ in 0 .. total { + conn.write_string('x') or { return } + time.sleep(pause) + } +} + +// trickle_url starts a trickling mirror on a port of its own and answers its +// url with the listener, which the test closes +fn trickle_url(total int, pause time.Duration) !(&net.TcpListener, string) { + mut l := net.listen_tcp(.ip, '127.0.0.1:0')! + port := l.addr()!.port()! + spawn trickle_mirror(mut l, total, pause) + return l, 'http://127.0.0.1:${port}/core.db' +} + +// a mirror that keeps every read short of the socket timeout but the whole +// answer past the rank timeout fails the probe, close to the timeout and not +// at the answer's end (some six seconds here) +fn test_timed_get_bounds_the_whole_answer() ! { + saved := rank_timeout + defer { + rank_timeout = saved + } + rank_timeout = 1 + mut l, url := trickle_url(30, 200 * time.millisecond)! + defer { + l.close() or {} + } + for range in [false, true] { + start := time.now() + if _, bytes := timed_get(url, range) { + assert false, 'a trickled answer of ${bytes} bytes passed the timeout (range ${range})' + } + took := time.now() - start + assert took < 3 * time.second, 'the probe took ${took} (range ${range})' + } +} + +// an answer that is whole within the timeout is measured as before +fn test_timed_get_measures_a_prompt_answer() ! { + saved := rank_timeout + defer { + rank_timeout = saved + } + rank_timeout = 5 + mut l, url := trickle_url(4, time.millisecond)! + defer { + l.close() or {} + } + _, bytes := timed_get(url, false)! + assert bytes == 4 +} + +fn test_rank_os_names_are_sorted() { + // the message spells the oses the same way whatever order the config's + // mirrorlist forms defined them in; one os and none are spelled too + saved := rank_oses.clone() + defer { rank_oses = saved.clone() } + rank_oses = map[string]RankOs{} + assert rank_os_names() == '' + rank_oses['zeta'] = RankOs{} + assert rank_os_names() == 'zeta' + rank_oses['arch'] = RankOs{} + rank_oses['Mid'] = RankOs{} + rank_oses['artix'] = RankOs{} + assert rank_os_names() == 'Mid, arch, artix, zeta' +} + +fn test_timed_probe_edges() { + // latency alone: the bytes are not looked at + lat := timed_probe('u', 12, 0, false) + assert lat.ok && lat.latency_ms == 12 && lat.speed == 0.0 && lat.url == 'u' + // a zero latency is still a mirror that answered + assert timed_probe('u', 0, 0, false).ok + // speed: bytes over seconds + sp := timed_probe('u', 500, 1000, true) + assert sp.ok && sp.speed == 2000.0 && sp.latency_ms == 500 + // a fetch that brought nothing failed, whatever it took + assert !timed_probe('u', 500, 0, true).ok + assert !timed_probe('u', 0, 0, true).ok + // quicker than a millisecond, or a clock that went back, is one + // millisecond: a speed, not a division by zero + assert timed_probe('u', 0, 10, true).speed == 10000.0 + assert timed_probe('u', -5, 10, true).speed == 10000.0 +} + +fn test_http_text_names_the_refusal() ! { + // nothing listens here: the fetch fails as the fetch it was called + if body := http_text('http://127.0.0.1:1/x', 1, 'fetching the test', 'the test server') { + assert false, 'port 1 answered: ${body}' + } else { + assert err.msg().starts_with('fetching the test failed: '), err.msg() + } +} diff --git a/src/modify.v b/src/modify.v new file mode 100644 index 0000000..316bdd0 --- /dev/null +++ b/src/modify.v @@ -0,0 +1,88 @@ +module main + +import alpm + +// mark sets the install reason of installed packages, pacman's -D --asdeps +// and --asexplicit. every target is found first; one that names nothing is +// reported and skipped, as pacman's -D and the other modes do, and the rest +// are marked. the reasons are then written under the db lock, which pacman's +// change_install_reason takes with an empty transaction too: +// alpm_pkg_set_reason writes the db entry right away and locks nothing +fn mark(config ConfigMark) ! { + need_query(config.query, 'package')! + mut ui := new_trans_ui(noconfirm: config.noconfirm) + check_ask_db_lock(mut ui) + mut handle := init_handle(ui)! + defer { handle.release() or { went_on('release the alpm handle', err) } } + defer { ui.stop() } + defer { trans_cleanup(handle) } + + mut pkgcache := local_pkgcache(handle)! + + reason := parse_reason(config.reason)! + + mut pkgs := []&alpm.Package{} + for target in config.query { + mut name := local_target_name(target) + pkg := find_local_target(pkgcache, name, false) or { + name = did_you_mean(mut ui, name, pkg_names(pkgcache.pkgs())) or { + target_error(err.msg()) + continue + } + pkgcache.pkg_find(name) or { + target_error('unknown package: "${name}"') + continue + } + } + add_pkg_once(mut pkgs, pkg) + } + if pkgs.len == 0 { + return + } + + trans_begin(handle, alpm.trans_flag_0)! + // each reason is written to the db as it is set, so a failure leaves the + // ones before it changed: the error names them, so the run is truthful + // about what it did and did not do + mut set := []string{} + for pkg in pkgs { + if pkg.get_reason() != reason { + pkg.set_reason(reason) or { + already := if set.len > 0 { ' (already set: ${set.join(', ')})' } else { '' } + return error('could not set the install reason of ${pkg.get_name()}: ${err.msg()}${already}') + } + set << pkg.get_name() + } + } + + names := pkgs.map(it.get_name()) + if ipc_on() { + emit(DoneEvent{ + action: 'marked' + reason: reason_key(reason) + packages: names + }) + return + } + print_done(mut ui, '${reason_to_str(reason)}:', names.map(name_style(it))) +} + +// reason_key is an install reason as a frontend reads it, and the word +// mark takes for it (parse_reason); every reason named, as reason_to_str +fn reason_key(reason alpm.PackageReason) string { + return match reason { + .explicit { 'explicit' } + .depend { 'depend' } + .unknown { 'unknown' } + } +} + +// parse_reason reads mark's --reason: a reason's key, or a short form of it +fn parse_reason(text string) !alpm.PackageReason { + return match text { + 'e', 'ex', 'explicit' { alpm.PackageReason.explicit } + 'd', 'dep', 'depend', 'dependency' { alpm.PackageReason.depend } + 'u', 'un', 'unknown' { alpm.PackageReason.unknown } + else { error('unknown reason: "${text}"') } + } +} diff --git a/src/orphans.v b/src/orphans.v new file mode 100644 index 0000000..3744c5e --- /dev/null +++ b/src/orphans.v @@ -0,0 +1,74 @@ +module main + +import alpm + +// orphan_pkgs are the installed dependencies that nothing kept reaches through +// its dependencies. the kept packages are the explicitly installed ones and the +// ones an installed package lists as optional, as pacman keeps them. pacman's +// -Qdt only finds the dependencies nothing requires, so a group that only +// requires itself, such as a set of plugins left behind by their app, is missed. +// with optional_too an optional dependency keeps nothing, pacman's -Qdtt: +// what only an optdepends line still names is an orphan as well. +// a dependency reaches every installed package that satisfies it, not the +// first one alone: pacman's compute_requiredby counts a requirer for each +// provider, so two providers of one virtual name are both kept +fn orphan_pkgs(mut pkgcache alpm.List, optional_too bool) []&alpm.Package { + installed := pkgcache.pkgs() + // who could answer for a name: the package called it, and every one + // that provides it, by its place in installed; the version is libalpm's to compare, below + mut answers := map[string][]int{} + for i, pkg in installed { + answers[pkg.get_name()] << i + for p in pkg.get_provides().depends() { + if p.get_name() != pkg.get_name() { + answers[p.get_name()] << i + } + } + } + mut reached := map[string]bool{} + mut queue := []&alpm.Package{} + for pkg in installed { + if pkg.get_reason() != .depend || (!optional_too && pkg.compute_optional_for().len > 0) { + reached[pkg.get_name()] = true + queue << pkg + } + } + for queue.len > 0 { + pkg := queue.pop() + deps := pkg.get_depends() + for dep in deps.depends() { + depstring := dep.compute_string() + for i in answers[dep.get_name()] { + cand := installed[i] + if reached[cand.get_name()] { + continue + } + // a list of the one candidate, for alpm_find_satisfier's + // version and provision comparison + one := &alpm.List(unsafe { nil }).add(voidptr(cand)) + satisfied := one.find_satisfier(depstring) != none + one.free() + if satisfied { + reached[cand.get_name()] = true + queue << cand + } + } + } + } + return installed.filter(it.get_reason() == .depend && !reached[it.get_name()]) +} + +fn orphans(config ConfigOrphans) ! { + mut handle := alpm.initialize(root_path, db_path) or { return err } + defer { handle.release() or { went_on('release the alpm handle', err) } } + + mut pkgcache := local_pkgcache(handle)! + + mut listing := Listing{ + fields: cfg_search_fields.clone() + } + for pkg in orphan_pkgs(mut pkgcache, config.level >= 2) { + listing.add_pkg(pkg, 'local') + } + listing.print() +} diff --git a/src/orphans_test.v b/src/orphans_test.v new file mode 100644 index 0000000..82dc309 --- /dev/null +++ b/src/orphans_test.v @@ -0,0 +1,100 @@ +module main + +import alpm +import os +import testdb + +fn test_orphan_pkgs() ! { + tmp := os.join_path(os.vtmp_dir(), 'vpac_test_orphans_${os.getpid()}') + os.mkdir_all(os.join_path(tmp, 'root'))! + defer { os.rmdir_all(tmp) or {} } + testdb.write_local(os.join_path(tmp, 'db'), [ + // kept: explicit, and everything it reaches + testdb.Pkg{ + name: 'app' + reason: 0 + depends: ['lib1>=1.0', 'libvirtual'] + optdepends: ['opt: extra things'] + }, + testdb.Pkg{ + name: 'lib1' + reason: 1 + depends: ['lib2'] + }, + testdb.Pkg{ + name: 'lib2' + reason: 1 + }, + // reached through what it provides + testdb.Pkg{ + name: 'impl' + reason: 1 + provides: ['libvirtual'] + }, + // a second provider of the same name is required as much as the + // first, as pacman's compute_requiredby has it; one whose provision + // is too old for a versioned dependency is not + testdb.Pkg{ + name: 'impl2' + reason: 1 + provides: ['libvirtual'] + }, + testdb.Pkg{ + name: 'wants-new' + reason: 0 + depends: ['virt>=2'] + }, + testdb.Pkg{ + name: 'virt-new' + reason: 1 + provides: ['virt=2'] + }, + testdb.Pkg{ + name: 'virt-old' + reason: 1 + provides: ['virt=1'] + }, + // kept as an optional dependency of app, with what it needs + testdb.Pkg{ + name: 'opt' + reason: 1 + depends: ['optlib'] + }, + testdb.Pkg{ + name: 'optlib' + reason: 1 + }, + // orphans: one nothing requires, and a pair that only requires + // itself, which pacman's -Qdt misses + testdb.Pkg{ + name: 'old' + reason: 1 + }, + testdb.Pkg{ + name: 'cyc-a' + reason: 1 + depends: ['cyc-b'] + }, + testdb.Pkg{ + name: 'cyc-b' + reason: 1 + depends: ['cyc-a'] + }, + ])! + + handle := alpm.initialize(os.join_path(tmp, 'root') + '/', os.join_path(tmp, 'db') + '/')! + defer { handle.release() or {} } + localdb := handle.get_localdb()! + mut pkgcache := localdb.get_pkgcache() or { return error('the fake local db has no packages') } + assert pkgcache.pkgs().len == 13, 'libalpm read the fake db' + + mut names := orphan_pkgs(mut pkgcache, false).map(it.get_name()) + names.sort() + assert names == ['cyc-a', 'cyc-b', 'old', 'virt-old'] + + // -tt: an optional dependency keeps nothing, so what only an optdepends + // line names is listed too, with what hangs off it + mut all := orphan_pkgs(mut pkgcache, true).map(it.get_name()) + all.sort() + assert all == ['cyc-a', 'cyc-b', 'old', 'opt', 'optlib', 'virt-old'] +} diff --git a/src/pkgbuild.v b/src/pkgbuild.v new file mode 100644 index 0000000..e1e49fb --- /dev/null +++ b/src/pkgbuild.v @@ -0,0 +1,113 @@ +@[has_globals] +module main + +import net.urllib +import json2 + +pub struct PackagePkgbuild { +pub mut: + depends []string @[json: Depends] + make_depends []string @[json: MakeDepends] + check_depends []string @[json: CheckDepends] + description string @[json: Description] + first_submitted i64 @[json: FirstSubmitted] + id i64 @[json: ID] + last_modified i64 @[json: LastModified] + maintainer ?string @[json: Maintainer] + name string @[json: Name] + num_votes i64 @[json: NumVotes] + out_of_date ?i64 @[json: OutOfDate] + package_base string @[json: PackageBase] + package_base_id i64 @[json: PackageBaseID] + popularity f64 @[json: Popularity] + url string @[json: URL] + url_path string @[json: URLPath] + version string @[json: Version] +} + +pub struct PackagesPkgbuild { +pub mut: + count i64 @[json: resultcount] + results []PackagePkgbuild + type string + version i64 + // the rpc's own failure, when it refuses the request; absent when it answers + error_text ?string @[json: error] +} + +// pkgbuild_rpc_timeout is how long one rpc request may take, for the search +// and the info lookups of the pkgbuild repos. a stall would otherwise hang +// the search under a proxy's silent wall +// (pkgbuild :timeout) sets it, in seconds +__global pkgbuild_rpc_timeout = 10 + +// pkgbuild_rpc fetches one url and reads its answer: timed, and demanding an +// http answer the rpc actually gives. what it fetches is returned as text; +// the callers decode their own answer out of it +fn pkgbuild_rpc(url string, what string) !string { + return http_text(url, pkgbuild_rpc_timeout, what, 'the pkgbuild rpc') +} + +// answer_start is the start of an rpc answer that did not decode, for the +// error: at most 200 bytes, of an answer that may be shorter (a captive +// portal's page, a proxy's error) — a plain slice would panic on it +fn answer_start(body string) string { + return body#[..200] +} + +// get_pkgbuild_packages searches one pkgbuild repo's site for a needle. +// the needle is escaped: a query with '&', '#', ' ' or '=' must not break +// the request or smuggle in extra rpc parameters +fn get_pkgbuild_packages(base string, needle string) ![]PackagePkgbuild { + body := pkgbuild_rpc( + '${base}/rpc/v5/search/${urllib.query_escape(needle)}', + 'search', + )! + data := json2.decode[PackagesPkgbuild](body) or { + return error('failed to decode search results: ${err.msg()} (the answer begins: ${answer_start(body)})') + } + if err := data.error_text { + return error('search failed: ${err}') + } + return data.results +} + +// get_pkgbuild_info fetches the full record, dependencies included, of each +// name, from one pkgbuild repo's site. the names are escaped likewise. no +// names asks for nothing and gets it +fn get_pkgbuild_info(base string, names []string) ![]PackagePkgbuild { + if names.len == 0 { + return []PackagePkgbuild{} + } + args := names.map('arg[]=${urllib.query_escape(it)}').join('&') + body := pkgbuild_rpc('${base}/rpc/v5/info?${args}', 'info lookup')! + data := json2.decode[PackagesPkgbuild](body) or { + return error('failed to decode package info: ${err.msg()} (the answer begins: ${answer_start(body)})') + } + if err := data.error_text { + return error('info lookup failed: ${err}') + } + return data.results +} + +// pkgbuild_lookup finds name in the pkgbuild repos, tried in config order: +// the first one that has the package is the one it builds from. it answers +// the record, the repo's site with no trailing slash (so a clone url joins +// with exactly one), and the name the config gives the repo; the site is +// empty when no repo holds the name +fn pkgbuild_lookup(name string) !(PackagePkgbuild, string, string) { + for repo in pkgbuild_repos() { + site := repo.servers[0].trim_right('/') + infos := get_pkgbuild_info(site, [name])! + if infos.len > 0 { + return infos[0], site, repo.name + } + } + return PackagePkgbuild{}, '', '' +} + +// pkgbuild_has names whether any pkgbuild repo holds name +fn pkgbuild_has(name string) !bool { + _, site, _ := pkgbuild_lookup(name)! + return site != '' +} diff --git a/src/pkgbuild_install.v b/src/pkgbuild_install.v new file mode 100644 index 0000000..85a16a1 --- /dev/null +++ b/src/pkgbuild_install.v @@ -0,0 +1,570 @@ +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. +// 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) ![]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') + } + if ask && !ui.noyes('install ${name} from the pkgbuild repo (${node.repo})?') { + 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 +fn pkgbuild_install(mut ui TransUI, mut handle &alpm.Handle, config ConfigInstall, target 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)) 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 +} diff --git a/src/pkgbuild_install_test.v b/src/pkgbuild_install_test.v new file mode 100644 index 0000000..f2661c4 --- /dev/null +++ b/src/pkgbuild_install_test.v @@ -0,0 +1,339 @@ +module main + +import os +import testdb + +fn test_dep_name() { + cases := { + 'glibc': 'glibc' + 'glibc>=2.27': 'glibc' + 'foo<1.0': 'foo' + 'foo<=1.0': 'foo' + 'foo=1.0-2': 'foo' + 'foo>1:2.0': 'foo' + 'gcc-libs': 'gcc-libs' + 'python>=3.12': 'python' + 'libfoo.so=1-64': 'libfoo.so' + // stray spaces, as a published dependency list occasionally spells + ' glibc >=2.27 ': 'glibc' + ' glibc ': 'glibc' + 'git >2.0': 'git' + } + for dep, want in cases { + assert dep_name(dep) == want, dep + } +} + +fn test_review() ! { + old := color_flag + defer { color_flag = old } + color_flag = 'never' + dir := os.join_path(os.vtmp_dir(), 'vpac_test_review_${os.getpid()}') + os.mkdir_all(os.join_path(dir, '.git'))! + defer { os.rmdir_all(dir) or {} } + os.write_file(os.join_path(dir, 'PKGBUILD'), 'pkgname=foo\n')! + os.write_file(os.join_path(dir, 'foo.install'), 'post_install() { :; }')! + os.write_file(os.join_path(dir, 'a.patch'), '')! + + // the PKGBUILD first, then the .install scripts, then every name but .git + mut r := read_review('foo', dir)! + assert r.files.map(it.name) == ['PKGBUILD', 'foo.install'] + assert r.listing == ['PKGBUILD', 'a.patch', 'foo.install'] + r.warnings = pkgbuild_warnings(PackagePkgbuild{ name: 'foo', maintainer: 'me', num_votes: 1 }) + assert review_text(r, 'review foo') == [ + 'warning: maintainer: me, votes: 1', + 'review foo', + 'PKGBUILD', + 'pkgname=foo\n', + 'foo.install', + 'post_install() { :; }', + 'files in the package', + 'PKGBUILD a.patch foo.install', + ].join('\n') + + // a generated package shows its source, then what was generated from it + g := generated_review('foo', 'PKGBUILD.lip', '(lip)', 'pkgname=foo', 'foo.install', 'x') + assert review_text(g, '') == 'PKGBUILD.lip\n(lip)\nPKGBUILD the build runs\npkgname=foo\nfoo.install\nx' + assert generated_review('foo', 'PKGBUILD.vsh', 'v', 'p', 'foo.install', '').files.len == 2 +} + +fn test_makepkg_line() ! { + // the dir is one word to the shell whatever it is called; the build + // command is the config's text, run in it + dir := os.join_path(os.vtmp_dir(), "vpac test's \$dir `x` ${os.getpid()}") + os.mkdir_all(dir)! + defer { os.rmdir_all(dir) or {} } + saved := pkgbuild_makepkg + defer { pkgbuild_makepkg = saved } + pkgbuild_makepkg = 'pwd -P' + res := os.exec(['sh', '-c', makepkg_line(dir)]) + assert res.exit_code == 0, res.output + assert res.output.trim_right('\n') == os.real_path(dir) + // the default is makepkg's own, forcing a rebuild of what is there + reset_config() + assert makepkg_line('/x').ends_with(' && makepkg -f') +} + +fn test_build_dir_takes_a_plain_base_only() ! { + // the dir is removed before the clone, so a base that climbs out of the + // build root is refused before any path is made of it + saved := pkgbuild_dir + defer { pkgbuild_dir = saved } + pkgbuild_dir = '/var/tmp/vpac-builds' + assert pkgbuild_build_dir('u', 'foo-git')! == '/var/tmp/vpac-builds/foo-git' + for bad in ['', '.', '..', '../x', 'a/b', '/etc', '-rf'] { + if d := pkgbuild_build_dir('u', bad) { + assert false, 'accepted "${bad}" as ${d}' + } + } +} + +fn test_packagelist_files() ! { + dir := os.join_path(os.vtmp_dir(), 'vpac_test_pkglist_${os.getpid()}') + os.mkdir_all(dir)! + defer { os.rmdir_all(dir) or {} } + built := os.join_path(dir, 'foo-1.0-1-any.pkg.tar') + os.write_file(built, '')! + // makepkg names every package it can make, built or not: a debug package + // that was not made, and blank or odd lines, are not archives + out := '${built}\n${dir}/foo-debug-1.0-1-any.pkg.tar\n\n ${built} \nwarning: x\n' + assert packagelist_files(out) == [built, built] +} + +fn test_archives_in() ! { + dir := os.join_path(os.vtmp_dir(), 'vpac_test_archives_in_${os.getpid()}') + os.mkdir_all(dir)! + defer { os.rmdir_all(dir) or {} } + for f in ['foo-1.0-1-any.pkg.tar', 'bar-2-1-x86_64.pkg.tar.zst', 'bar-2-1-x86_64.pkg.tar.zst.sig', + 'PKGBUILD', 'notes.tar'] { + os.write_file(os.join_path(dir, f), '')! + } + mut got := archives_in(dir)!.map(os.base(it)) + got.sort() + // an uncompressed archive counts, a signature and other files do not + assert got == ['bar-2-1-x86_64.pkg.tar.zst', 'foo-1.0-1-any.pkg.tar'] +} + +fn test_makepkg_packagelist_names_what_is_built() ! { + if !os.exists_in_system_path('makepkg') { + // no makepkg on this system: the assumption cannot be checked here + return + } + if os.geteuid() == 0 { + // makepkg refuses root + return + } + dir := os.join_path(os.vtmp_dir(), 'vpac_test_packagelist_${os.getpid()}') + out_dir := os.join_path(dir, 'out') + os.mkdir_all(out_dir)! + defer { os.rmdir_all(dir) or {} } + os.write_file(os.join_path(dir, 'PKGBUILD'), [ + 'pkgbase=split', + 'pkgname=(split-a split-b)', + 'pkgver=1.0', + 'pkgrel=1', + "arch=('any')", + 'package_split-a() { :; }', + 'package_split-b() { :; }', + ].join('\n') + '\n')! + // an archive an older build left in the checkout: not this build's + os.write_file(os.join_path(dir, 'split-a-0.9-1-any.pkg.tar.zst'), '')! + saved := pkgbuild_makepkg + defer { pkgbuild_makepkg = saved } + pkgbuild_makepkg = 'makepkg -f' + // the line built_packages runs, as this user rather than through runuser: + // PKGDEST and PKGEXT as a makepkg.conf would set them + res := os.exec(['env', 'PKGDEST=${out_dir}', 'PKGEXT=.pkg.tar', 'sh', '-c', + '${makepkg_line(dir)} --packagelist']) + assert res.exit_code == 0, res.output + listed := res.output.split_into_lines().map(it.trim_space()).filter(it.starts_with('/')) + assert listed == ['${out_dir}/split-a-1.0-1-any.pkg.tar', '${out_dir}/split-b-1.0-1-any.pkg.tar'], res.output + // nothing built yet: nothing to install, the stale archive not among it + assert packagelist_files(res.output) == [] + // built: exactly this version's two, from PKGDEST, uncompressed + for f in listed { + os.write_file(f, '')! + } + assert packagelist_files(res.output) == listed +} + +fn test_run_process_drains_both_pipes() ! { + // more on stderr than a pipe holds, before stdout says anything: a + // reader of stdout alone would wait on a child that waits on it + out, code := run_process(['sh', '-c', 'head -c 300000 /dev/zero >&2; echo ok; exit 3'], + true)! + assert out == 'ok\n' + assert code == 3 + _, plain := run_process(['true'], false)! + assert plain == 0 + if _, _ := run_process(['vpac-no-such-tool'], false) { + assert false + } +} + +fn test_built_install_config_carries_the_command_line() { + outer := ConfigInstall{ + noconfirm: true + asexplicit: true + dbonly: true + nodeps: true + nodeps_level: 2 + overwrite: ['usr/*'] + assume_installed: ['x=1'] + ignore: ['held'] + ignoregroup: ['grp'] + no_upgrade_deps: true + disable_timeout: true + pkgbuild: true + no_pkgbuild_confirm: true + needed: true + query: ['the-target'] + } + target := built_install_config(outer, ['/b/a.pkg.tar.zst', '/b/b.pkg.tar.zst'], true) + // the archives are the targets, not the name that was asked for + assert target.query == ['/b/a.pkg.tar.zst', '/b/b.pkg.tar.zst'] + assert target.asexplicit && !target.asdeps + assert target.ignore == ['held'] && target.ignoregroup == ['grp'] + assert target.no_upgrade_deps && target.disable_timeout && target.noconfirm + assert target.dbonly && target.nodeps && target.nodeps_level == 2 + assert target.overwrite == ['usr/*'] && target.assume_installed == ['x=1'] + // the outer run's own flags stay behind: an archive is not looked up in + // the pkgbuild repo, and --needed was settled before the build + assert !target.pkgbuild && !target.no_pkgbuild_confirm && !target.needed + // a dependency node is a dependency whatever the target was to be + dep := built_install_config(outer, ['/b/dep.pkg.tar.zst'], false) + assert dep.asdeps && !dep.asexplicit + assert dep.ignore == ['held'] && dep.no_upgrade_deps + // and nothing appears that the command line did not say + plain := built_install_config(ConfigInstall{}, [], true) + assert plain == ConfigInstall{} +} + +// node_db writes a local db for the node decisions and points the config at it +fn node_db(name string, pkgs []testdb.Pkg) !string { + tmp := os.join_path(os.vtmp_dir(), 'vpac_test_node_${name}_${os.getpid()}') + os.rmdir_all(tmp) or {} + os.mkdir_all(os.join_path(tmp, 'root'))! + testdb.write_local(os.join_path(tmp, 'db'), pkgs)! + root_path = os.join_path(tmp, 'root') + '/' + db_path = os.join_path(tmp, 'db') + '/' + return tmp +} + +fn node_of(name string, version string, wanted []string, repo_deps []string) PkgbuildNode { + return PkgbuildNode{ + info: PackagePkgbuild{ + name: name + package_base: name + version: version + } + wanted: wanted + repo_deps: repo_deps + } +} + +fn test_node_step_is_decided_on_what_is_installed_now() ! { + saved_root, saved_db := root_path, db_path + tmp := node_db('step', [ + testdb.Pkg{ + name: 'lib' + version: '1.0-1' + }, + testdb.Pkg{ + name: 'impl' + version: '3.0-1' + provides: ['virt=3'] + }, + ])! + defer { + root_path, db_path = saved_root, saved_db + os.rmdir_all(tmp) or {} + } + // a dependency node everything wanted is satisfied for is not built: + // by its own name, by a version it meets, by something that provides it + for wanted in [['lib'], ['lib>=1.0'], ['lib', 'lib<2'], ['virt'], ['virt>=3', 'virt']] { + name := dep_name(wanted[0]) + step := node_step_now(node_of(name, '9-1', wanted, []), false, false)! + assert step.skip, '${wanted} was still to build' + assert step.why.contains('installed now'), step.why + } + // one requirement of several that is not met keeps the build + for wanted in [['lib>=2'], ['lib', 'lib>=2'], ['virt=4'], ['gone'], ['lib', 'gone']] { + step := node_step_now(node_of(dep_name(wanted[0]), '9-1', wanted, []), false, false)! + assert !step.skip, '${wanted} was skipped' + } + // a package of the name at the node's very version does not skip a + // dependency node whose requirement it does not meet, with or without + // --needed: the name being there is not the requirement being met + for needed in [false, true] { + same := node_step_now(node_of('lib', '1.0-1', ['lib>=2'], []), needed, false)! + assert !same.skip + } + // the target is never dropped for being satisfied: it was asked for. + // only --needed skips it, and only at the version it would install + assert !node_step_now(node_of('lib', '1.0-1', [], []), false, true)!.skip + assert !node_step_now(node_of('lib', '1.0-1', ['lib'], []), false, true)!.skip + up := node_step_now(node_of('lib', '1.0-1', [], []), true, true)! + assert up.skip && up.why == 'lib-1.0-1 is up to date, skipped' + assert !node_step_now(node_of('lib', '1.0-2', [], []), true, true)!.skip + assert !node_step_now(node_of('lib', '0.9-1', [], []), true, true)!.skip + assert !node_step_now(node_of('absent', '1.0-1', [], []), true, true)!.skip + // a node nothing wanted and that is no target (never planned so, but + // the rule is spelled) is built + assert !node_step_now(node_of('lib', '1.0-1', [], []), false, false)!.skip + // the repo dependencies left are the ones not installed, in order; + // a provider under another name does not count as the package + deps := node_step_now(node_of('app', '1-1', [], ['new', 'lib', 'virt', 'other']), false, + true)! + assert deps.repo_deps == ['new', 'virt', 'other'] + assert node_step_now(node_of('app', '1-1', [], []), false, true)!.repo_deps.len == 0 + // a skipped node asks for no repo dependencies + assert node_step_now(node_of('lib', '9-1', ['lib'], ['new']), false, false)!.repo_deps.len == 0 +} + +fn test_local_now_sees_what_an_older_handle_does_not() ! { + saved_root, saved_db := root_path, db_path + tmp := node_db('fresh', [testdb.Pkg{ + name: 'first' + }])! + defer { + root_path, db_path = saved_root, saved_db + os.rmdir_all(tmp) or {} + } + // the run's handle reads the local db once + old_handle, old_pkgs := local_now()! + defer { old_handle.release() or {} } + assert old_pkgs.pkg_find('first') != none + // a build's install goes in through another handle: here, written + testdb.write_local(os.join_path(tmp, 'db'), [ + testdb.Pkg{ + name: 'built' + version: '2.0-1' + provides: ['virt=2'] + }, + ])! + // the old list is the past: the staleness the plan must not be made on + assert old_pkgs.pkg_find('built') == none + assert old_pkgs.find_satisfier('virt') == none + // a view opened now has it, and a node waiting for it is dropped + view, now := local_now()! + assert now.pkg_find('built') != none && now.pkg_find('first') != none + assert now.find_satisfier('virt>=2') != none + view.release()! + assert node_step(old_pkgs, node_of('built', '2.0-1', ['virt'], []), false, false).skip == false + assert node_step_now(node_of('built', '2.0-1', ['virt'], []), false, false)!.skip + // an empty local db is a view of nothing, not an error + os.rmdir_all(os.join_path(tmp, 'db', 'local'))! + testdb.write_local(os.join_path(tmp, 'db'), [])! + e_view, empty := local_now()! + assert empty.pkg_find('first') == none + e_view.release()! + assert !node_step_now(node_of('x', '1-1', ['x'], ['dep']), false, false)!.skip + // a db that is not there is an error, with nothing left open + db_path = os.join_path(tmp, 'nowhere') + '/' + if _, _ := local_now() { + assert false, 'a missing db opened' + } + // nothing to install asks for no transaction at all + install_repo_deps([])! +} diff --git a/src/privilege.v b/src/privilege.v new file mode 100644 index 0000000..d68a25e --- /dev/null +++ b/src/privilege.v @@ -0,0 +1,173 @@ +@[has_globals] +module main + +import os +import vmakepkg + +// root_provider is how vpac gets root: the config's (options :root "..."), +// sudo unless it says otherwise. vpac re-runs itself through it with the +// same arguments, so it gives the same pipes and exit status. it is a +// command line of the user's own: any program that runs the words after it +// as root (doas, run0, "sudo -A"), its own arguments parted by spaces. two +// are known by name, since they take the command another way: su wants one +// shell line after -c, and pkexec — which asks through the desktop's polkit +// agent, what a frontend without a terminal (--ui ipc) needs — must be told +// to stay in the working dir +__global root_provider = 'sudo' + +// env_invoker is how the root process learns who asked, so pkgbuild builds can run +// as that user. the provider may drop the environment, so it is passed through +// env, which every provider runs +const env_invoker = 'VPAC_INVOKER' + +// env_v hands the root process the invoker's own v compiler: PKGBUILD.vsh +// packages run through it, and the provider's sanitized path does not know +// where the user keeps theirs +const env_v = 'VPAC_V' + +// shell_words spells a command as the one line su -c hands root's shell: +// every word quoted whole, so the shell reads back exactly these words — +// the arguments are the user's, and nothing in them may become syntax +fn shell_words(words []string) string { + return words.map(vmakepkg.shell_quote).join(' ') +} + +// can_write tells whether this user may write path, or create it when it does +// not exist yet +fn can_write(path string) bool { + target := if os.exists(path) { path } else { os.dir(path) } + return os.is_writable(target) +} + +// root_argv is the words handed to the root provider after its own name: +// the provider's own arguments, then env carrying envs, then vpac and its +// arguments +fn root_argv(provider []string, envs []string, exe string, args []string) []string { + mut run := ['env'] + run << envs + run << exe + run << args + mut out := provider[1..].clone() + match os.base(provider[0]) { + 'su' { + out << ['-c', shell_words(run)] + } + 'pkexec' { + // pkexec starts in root's home otherwise, and a relative target + // (a package file, a repo dir) is relative to where vpac was run + out << '--keep-cwd' + out << run + } + else { + out << run + } + } + return out +} + +// reexec_as_root replaces this process with vpac running as root through the +// root provider. it only returns on error, and not when already root +fn reexec_as_root(args []string) ! { + if os.geteuid() == 0 { + return + } + invoker := current_user()! + words := root_provider.fields() + if words.len == 0 { + return error('config: options :root names no command to get root with') + } + provider := os.find_abs_path_of_executable(words[0]) or { + return error('${words[0]} is needed to run this as root, but it was not found: name another with (options :root "...") in the config') + } + // the compiler rides along, exactly like the invoker does + vbin := os.find_abs_path_of_executable('v') or { '' } + mut envs := ['${env_invoker}=${invoker}'] + if vbin != '' { + envs << '${env_v}=${vbin}' + } + // os.execvp spells argv[0] out of cmdpath itself, so the list handed + // here is the words after the program name, and the process list shows + // the provider correctly spelled rather than one word short + os.execvp(provider, root_argv(words, envs, os.executable(), args))! +} + +#include + +struct C.passwd { + pw_name &char + pw_uid u32 + pw_dir &char +} + +fn C.getpwnam(name &char) &C.passwd + +fn C.getpwuid(uid u32) &C.passwd + +// current_user is the user this process runs as, named from its real uid: +// the user doas, sudo and pkexec report as their caller too. getlogin(3), +// which os.loginname is, answers the session's login instead — the user +// before an su, or nobody without a login session (a frontend started by a +// service) — and a build would land in another user's home, or nowhere +fn current_user() !string { + uid := os.getuid() + pw := C.getpwuid(u32(uid)) + if pw == unsafe { nil } || pw.pw_name == unsafe { nil } { + return error('could not tell which user is running vpac: uid ${uid} is not in the password database') + } + // getpwuid hands out a static buffer: the name is copied out of it + return unsafe { cstring_to_vstring(pw.pw_name) } +} + +// user_uid is a user's uid from the password database, none when there is +// no such user +fn user_uid(user string) ?u32 { + pw := C.getpwnam(&char(user.str)) + if pw == unsafe { nil } { + return none + } + return pw.pw_uid +} + +// invoker_of checks the user the escalation passed on before root builds +// as it: a user of the password database, and not one with root's uid. root +// is told by uid, not by name, since an alias of uid 0 is root to runuser +// and to every file a build or a .vsh generator touches. the name comes from +// vpac's own re-execution; the check keeps a stray or hand-set one from +// aiming the builds at root or at nobody +fn invoker_of(user string) !string { + if user == '' { + return error('pkgbuild packages are built as your user: run vpac as your user, it asks for root itself') + } + uid := user_uid(user) or { + return error('the invoking user "${user}" (${env_invoker}) is not in the password database') + } + if uid == 0 { + return error('pkgbuild packages are built as your user, not as root ("${user}" has uid 0): run vpac as your user, it asks for root itself') + } + return user +} + +// user_home is a user's home dir from the password database, as getent +// passwd finds it: through nss, so a home outside /home (/home2, an ldap +// account) is right. the invoker's $HOME is not asked: the root process +// would then list and size a path the user can set to anything +fn user_home(user string) !string { + pw := C.getpwnam(&char(user.str)) + if pw == unsafe { nil } || pw.pw_dir == unsafe { nil } { + return error('no home directory for user ${user} in the password database') + } + // getpwnam hands out a static buffer: the path is copied out of it + return unsafe { cstring_to_vstring(pw.pw_dir) } +} + +// invoker_user is who asked for this run: the user the escalation passed +// on, or, in a run that never escalated (a --print preview), the user +// running it +fn invoker_user() !string { + if os.geteuid() != 0 { + // the same answer reexec_as_root passes on: a user that cannot be + // told is an error, not an empty user to build under + return current_user() + } + return invoker_of(os.getenv(env_invoker)) +} diff --git a/src/privilege_test.v b/src/privilege_test.v new file mode 100644 index 0000000..28f9fdc --- /dev/null +++ b/src/privilege_test.v @@ -0,0 +1,119 @@ +module main + +import os + +// id_un is the running user as coreutils' id names it: by the real uid, the +// way the escalation tools name their caller +fn id_un() string { + res := os.exec(['id', '-un']) + assert res.exit_code == 0, 'id -un failed: ${res.output}' + return res.output.trim_space() +} + +fn test_current_user_is_the_real_uid() { + // getlogin(3) would answer the session's login, which differs after an + // su and is absent without a login session; the real uid always names + // the user running vpac + assert current_user()! == id_un() +} + +fn test_invoker_user_unescalated_is_the_running_user() { + if os.geteuid() == 0 { + // root reads the invoker from the escalation instead + return + } + assert invoker_user()! == id_un() +} + +fn test_invoker_of_accepts_a_user_of_the_password_database() { + me := current_user()! + if os.getuid() == 0 { + // a root test run has no unprivileged user of its own to accept + return + } + assert invoker_of(me)! == me +} + +fn test_invoker_of_rejects_root_by_uid() { + // root is turned away through its uid, the same check that turns away + // any alias of uid 0: the name 'root' is not special-cased + invoker_of('root') or { + assert err.msg().contains('not as root') + assert err.msg().contains('uid 0') + return + } + assert false, 'root accepted as the invoker' +} + +fn test_invoker_of_rejects_an_unknown_user() { + name := 'vpac-no-such-user-${os.getpid()}' + invoker_of(name) or { + assert err.msg().contains('not in the password database') + assert err.msg().contains(name) + return + } + assert false, 'an unknown user accepted as the invoker' +} + +fn test_invoker_of_rejects_an_empty_name() { + invoker_of('') or { + assert err.msg().contains('run vpac as your user') + return + } + assert false, 'an empty invoker accepted' +} + +fn test_user_uid() { + assert user_uid('root')? == 0 + assert user_uid(current_user()!)? == u32(os.getuid()) + if _ := user_uid('vpac-no-such-user-${os.getpid()}') { + assert false, 'an unknown user has a uid' + } +} + +fn test_user_home_matches_the_password_database() { + // getent passwd reads through nss, as getpwnam does: field 6 is the home + me := current_user()! + res := os.exec(['getent', 'passwd', me]) + if res.exit_code != 0 { + // no getent on this system: nothing to compare against + return + } + fields := res.output.trim_space().split(':') + assert fields.len >= 6 + assert user_home(me)! == fields[5] + if _ := user_home('vpac-no-such-user-${os.getpid()}') { + assert false, 'an unknown user has a home' + } +} + +fn test_shell_words_reads_back_as_the_words() { + // what su -c gives root's shell: the words come back one for one, with + // nothing in them expanded or run + words := ['env', 'VPAC_INVOKER=me', '/usr/bin/vpac', 'i', "it's", '$(id)', '`id`', 'a b', 'x;y', + '--eval=(define x "q")', ''] + line := os.exec(['sh', '-c', + 'set -- ' + shell_words(words) + '; for w in "$@"; do printf "[%s]" "$w"; done']) + assert line.exit_code == 0, line.output + assert line.output == words.map('[${it}]').join('') +} + +// the provider's own arguments come first; su takes the run as one quoted +// shell line, pkexec is kept in the working dir, and a command vpac does +// not know is handed the words as sudo is +fn test_root_argv() { + envs := ['VPAC_INVOKER=me'] + args := ['i', 'a b'] + run := ['env', 'VPAC_INVOKER=me', '/usr/bin/vpac', 'i', 'a b'] + assert root_argv(['sudo'], envs, '/usr/bin/vpac', args) == run + mut custom := ['-A', '--'] + custom << run + assert root_argv(['/opt/bin/myroot', '-A', '--'], envs, '/usr/bin/vpac', args) == custom + mut pk := ['--keep-cwd'] + pk << run + assert root_argv(['pkexec'], envs, '/usr/bin/vpac', args) == pk + su := root_argv(['/usr/bin/su', '-l'], envs, '/usr/bin/vpac', args) + assert su[..2] == ['-l', '-c'] + assert su.len == 3 + assert su[2].contains("'a b'"), su[2] +} diff --git a/src/prompt.v b/src/prompt.v new file mode 100644 index 0000000..4e09f73 --- /dev/null +++ b/src/prompt.v @@ -0,0 +1,247 @@ +module main + +import os +import strconv + +// Prompter is the one way vpac asks the user anything: a yes or no +// question, the go-ahead of a transaction, a pick among numbered choices. +// every prompt of every command goes through the one its TransUI carries +// (ui.yesno, ui.noyes, ui.proceed, ui.choose), so a second frontend answers +// them all by bringing its own. the terminal is the default. +// noconfirm is --noconfirm, the policy every prompter honours: each question +// is still shown, and its default taken without waiting for an answer, so an +// unattended run never blocks +interface Prompter { +mut: + noconfirm bool + // confirm asks a yes or no question; preset is what an empty answer takes + confirm(msg string, preset bool) bool + // proceed asks for the go-ahead of a transaction: pacman's 'Proceed with + // installation? [Y/n]', where an empty answer is yes. noconfirm gives it + proceed(msg string) bool + // choose asks for one of the choices and returns its index; the first is + // the preset. the terminal has listed them already, and asks a number + choose(msg string, choices []string) int + // pick asks for any number of the choices and returns which, one bool + // per choice; all of them is the preset. the terminal has listed them + // already, and asks for numbers and ranges + pick(msg string, count int) []bool +} + +// TermPrompter asks on the terminal, following pacman's question() and +// select_question(). every prompt goes to stderr, the noconfirm echo too, so +// piped output (install -p, search -q) carries only results; pacman prints +// the noconfirm echo on stdout, which mixes it into such output +struct TermPrompter { +mut: + noconfirm bool +} + +// StdinEnd is what stdin_line answers once stdin has nothing left +struct StdinEnd { + Error +} + +fn (e StdinEnd) msg() string { + return 'end of input' +} + +// stdin_line reads one line from stdin, without its newline; a last line +// that has none is a line too, as pacman's fgets gives it. the end of input +// is a StdinEnd, and a read error (stdin closed, or a directory) an error of +// its own: a prompt takes both as no, the way pacman's question() takes the +// NULL fgets answers to both, while a reader of a whole list must not take +// a cut for its end. os.get_raw_line panics on the read error, and keeps the +// newline, which a caller then has to tell an empty answer from the end by +fn stdin_line() !string { + mut buf := &u8(unsafe { nil }) + mut size := uint(0) + n := C.getline(voidptr(&buf), voidptr(&size), C.stdin) + // getline allocates with libc's malloc, even when it fails + defer { + unsafe { C.free(buf) } + } + if n < 0 { + if C.ferror(C.stdin) != 0 { + return error('could not read stdin: ${os.posix_get_error_msg(C.errno)}') + } + return StdinEnd{} + } + // the line is cloned out of getline's buffer either way: a plain slice + // would still point into what the defer frees + line := unsafe { tos(buf, n) } + return if line.ends_with('\n') { line[..line.len - 1].clone() } else { line.clone() } +} + +// the answer labels of a question, the default in bold +fn q_yes_no() string { + return '[' + erole('default', 'Y') + '/n]' +} + +fn q_no_yes() string { + return '[y/' + erole('default', 'N') + ']' +} + +// confirm follows pacman's question(): an empty answer takes the preset, +// y/yes is yes, and anything else is no — the end of input and a stdin that +// cannot be read too, whatever the preset, so an unattended run that meant +// no answer never says yes. with noconfirm the question is printed and the +// preset taken without reading stdin +fn (mut p TermPrompter) confirm(msg string, preset bool) bool { + label := if preset { q_yes_no() } else { q_no_yes() } + os.flush() + if p.noconfirm { + eprintln(erole('prompt', '${msg} ${label}')) + return preset + } + eprint(erole('prompt', '${msg} ${label} ')) + line := stdin_line() or { return false } + return match line.trim_space().to_lower() { + '' { preset } + 'y', 'yes' { true } + else { false } + } +} + +// proceed is confirm with a yes preset; with noconfirm the echo says the +// yes came from the flag +fn (mut p TermPrompter) proceed(msg string) bool { + if p.noconfirm { + os.flush() + eprintln(erole('prompt', '${msg} ${q_yes_no()} (yes, --noconfirm)')) + return true + } + return p.confirm(msg, true) +} + +// choose follows pacman's select_question(): it asks for a number from 1 to +// the count of choices, where an empty answer and end of input (or a stdin +// that cannot be read) take the first, and an answer that is not one of the +// numbers asks again. with noconfirm the question is printed and the first +// taken without reading stdin. end of input is safe to default here: the +// transaction's own 'proceed?' comes after and takes end of input as no +fn (mut p TermPrompter) choose(msg string, choices []string) int { + count := choices.len + label := '[1-${count}, default ' + erole('default', '1') + ']' + os.flush() + if p.noconfirm { + eprintln(erole('prompt', '${msg} ${label}')) + return 0 + } + for { + eprint(erole('prompt', '${msg} ${label} ')) + answer := (stdin_line() or { return 0 }).trim_space() + if answer == '' { + return 0 + } + n := strconv.atoi(answer) or { 0 } + if n >= 1 && n <= count { + return n - 1 + } + eprintln('invalid number: ${answer}') + } +} + +// parse_selection reads an answer to pick the way pacman's +// multiselect_parse does: numbers and ranges (2-4) parted by spaces or +// commas, a leading ^ leaving one out. everything starts selected; an answer +// whose first word selects starts from nothing instead, so '2 5' is those +// two and '^3' is all but the third +fn parse_selection(answer string, count int) ![]bool { + mut picked := []bool{len: count, init: true} + words := answer.replace(',', ' ').fields() + for i, word in words { + mut text := word + include := !text.starts_with('^') + if !include { + text = text[1..] + } else if i == 0 { + picked = []bool{len: count} + } + // a range's dash is looked for past the first byte, as pacman does + mut first := text + mut last := ?string(none) + if text.len > 1 { + if dash := text.index_after('-', 1) { + first = text[..dash] + last = text[dash + 1..] + } + } + start := selection_index(first, 1, count)! + mut end := start + if upto := last { + end = selection_index(upto, start, count)! + } + for n in start .. end + 1 { + picked[n - 1] = include + } + } + return picked +} + +// selection_index is one number of a selection, within its bounds +fn selection_index(text string, min int, max int) !int { + n := strconv.atoi(text) or { return error('invalid number: ${text}') } + if n < min || n > max { + return error('invalid value: ${n} is not between ${min} and ${max}') + } + return n +} + +// pick follows pacman's multiselect_question(): an empty answer takes them +// all, an answer that does not parse asks again. with noconfirm the +// question is printed and all taken. end of input, or a stdin that cannot be +// read, selects nothing: pacman fails the target there, and nothing chosen +// is the same refusal without the abort +fn (mut p TermPrompter) pick(msg string, count int) []bool { + label := '(default=' + erole('default', 'all') + '):' + os.flush() + if p.noconfirm { + eprintln(erole('prompt', '${msg} ${label}')) + return []bool{len: count, init: true} + } + for { + eprint(erole('prompt', '${msg} ${label} ')) + answer := (stdin_line() or { return []bool{len: count} }).trim_space() + if answer == '' { + return []bool{len: count, init: true} + } + return parse_selection(answer, count) or { + eprintln(err.msg()) + continue + } + } + return []bool{len: count} +} + +// yesno asks a question whose empty answer is yes. the live display is +// paused first, as for every prompt: a redraw would erase the question and +// leave the program waiting on one nobody sees +fn (mut ui TransUI) yesno(msg string) bool { + ui.pause() + return ui.prompt.confirm(msg, true) +} + +// noyes asks a question whose empty answer is no +fn (mut ui TransUI) noyes(msg string) bool { + ui.pause() + return ui.prompt.confirm(msg, false) +} + +// proceed asks for the go-ahead of a transaction +fn (mut ui TransUI) proceed(msg string) bool { + ui.pause() + return ui.prompt.proceed(msg) +} + +// choose asks for one of the choices and returns its index +fn (mut ui TransUI) choose(msg string, choices []string) int { + ui.pause() + return ui.prompt.choose(msg, choices) +} + +// pick asks for any number of count choices, already listed +fn (mut ui TransUI) pick(msg string, count int) []bool { + ui.pause() + return ui.prompt.pick(msg, count) +} diff --git a/src/prompt_test.v b/src/prompt_test.v new file mode 100644 index 0000000..e496be2 --- /dev/null +++ b/src/prompt_test.v @@ -0,0 +1,512 @@ +module main + +import json2 +import os + +#include +#include + +fn C.__fpurge(stream &C.FILE) + +fn C.clearerr(stream &C.FILE) + +// Scripted is a second frontend's prompter in miniature: it answers every +// question the same, and keeps what it was asked +struct Scripted { +mut: + noconfirm bool + yes bool + asked []string +} + +fn (mut p Scripted) confirm(msg string, _ bool) bool { + p.asked << msg + return p.yes +} + +fn (mut p Scripted) proceed(msg string) bool { + p.asked << msg + return p.yes +} + +fn (mut p Scripted) choose(msg string, choices []string) int { + p.asked << msg + return choices.len - 1 +} + +fn (mut p Scripted) pick(msg string, count int) []bool { + p.asked << msg + return []bool{len: count, init: p.yes} +} + +fn test_parse_selection_as_pacman() ! { + // the first word selecting starts from nothing; ranges and commas + assert parse_selection('2 4', 5)! == [false, true, false, true, false] + assert parse_selection('1-3,5', 5)! == [true, true, true, false, true] + // a first word leaving out starts from everything + assert parse_selection('^2', 3)! == [true, false, true] + assert parse_selection('^1-2', 3)! == [false, false, true] + // later words add to or take from what stands + assert parse_selection('1-4 ^3', 4)! == [true, true, false, true] + for bad in ['0', '6', 'x', '3-2', '2-9', '1-'] { + if _ := parse_selection(bad, 5) { + assert false, '"${bad}" was taken' + } + } +} + +fn test_select_answer_is_a_list_of_indices() ! { + assert parse_select_answer('{"id": 3, "answer": [0, 2]}', 3, 3)! == [true, false, true] + assert parse_select_answer('{"id": 3, "answer": []}', 3, 3)! == [false, false, false] + for bad in ['{"id": 3, "answer": true}', '{"id": 3, "answer": [3]}', '{"id": 3, "answer": [0.5]}', + '{"id": 2, "answer": [0]}', 'noise'] { + if _ := parse_select_answer(bad, 3, 3) { + assert false, '${bad} was taken' + } + } +} + +fn test_noconfirm_takes_the_defaults() { + // the questions go to stderr; stdin is never read, so none of these blocks + mut ui := new_trans_ui(noconfirm: true) + assert ui.yesno('a?') + assert !ui.noyes('b?') + assert ui.proceed('proceed?') + assert ui.choose('which one?', ['a', 'b', 'c']) == 0 + assert ui.pick('which ones?', 3) == [true, true, true] +} + +fn test_policy_through_the_interface() { + mut ui := new_trans_ui() + assert !ui.prompt.noconfirm + // a mode may flip the policy for one listing, through the interface, + // whichever prompter is behind it + ui.prompt.noconfirm = true + assert ui.proceed('proceed?') +} + +fn test_every_prompt_reaches_the_prompter() ! { + mut ui := new_trans_ui() + ui.prompt = Scripted{ + yes: true + } + assert did_you_mean(mut ui, 'zshh', ['zsh', 'bash'])! == 'zsh' + assert ui.choose('which one?', ['a', 'b', 'c']) == 2 + assert ui.proceed('proceed?') + // nothing near the query: the error comes without a question + if _ := did_you_mean(mut ui, 'qqqqqq', ['zsh']) { + assert false + } + s := ui.prompt as Scripted + assert s.asked.len == 3 + assert s.asked[1..] == ['which one?', 'proceed?'] + + ui.prompt = Scripted{ + yes: false + } + if _ := did_you_mean(mut ui, 'zshh', ['zsh']) { + assert false + } +} + +// StdinSource is what a scripted stdin reads: the text given, a stdin that +// is closed, or a directory, which every read fails on +enum StdinSource { + text + closed + directory +} + +// Scripted run is what on_stdin hands back: the answers the prompts gave, +// what they wrote to stderr, and the ipc channel's lines +struct ScriptedRun { + answers []int + stderr string + channel []string +} + +// reset_stdin drops what stdio buffered of the stdin before, and its end of +// file mark, so one script's leftovers never reach the next +fn reset_stdin() { + C.__fpurge(C.stdin) + C.clearerr(C.stdin) +} + +// on_stdin runs ask with fd 0 reading from source, fd 2 and the ipc channel +// each written to a file, then puts all three back. it is the real stdin +// that is read, through stdio as the prompters read it, so what the libc +// and the line reader make of an end or a failure is what is tested +fn on_stdin(source StdinSource, text string, ask fn () []int) !ScriptedRun { + dir := os.join_path(os.vtmp_dir(), 'vpac_test_prompt_${os.getpid()}') + os.mkdir_all(dir)! + defer { os.rmdir_all(dir) or {} } + os.write_file(os.join_path(dir, 'stdin'), text)! + mut in_file := os.open(os.join_path(dir, 'stdin'))! + defer { in_file.close() } + mut err_file := os.create(os.join_path(dir, 'stderr'))! + mut chan_file := os.create(os.join_path(dir, 'channel'))! + defer { + err_file.close() + chan_file.close() + } + dir_fd := C.open(&char(dir.str), C.O_RDONLY) + saved_in := C.dup(0) + saved_err := C.dup(2) + // whatever was opened is closed again on every way out, the failed + // setup's included: a descriptor left behind would be the next + // script's stdin by number + defer { + for fd in [dir_fd, saved_in, saved_err] { + if fd >= 0 { + C.close(fd) + } + } + } + if dir_fd < 0 || saved_in < 0 || saved_err < 0 { + return error('could not set the scripted stdin up') + } + saved_ipc := ipc_fd + reset_stdin() + // dup2 answers the new descriptor, never 0, on success + wired_in := match source { + .text { C.dup2(in_file.fd, 0) >= 0 } + .closed { C.close(0) == 0 } + .directory { C.dup2(dir_fd, 0) >= 0 } + } + wired_err := C.dup2(err_file.fd, 2) >= 0 + mut answers := []int{} + if wired_in && wired_err { + ipc_fd = chan_file.fd + answers = ask() + ipc_fd = saved_ipc + } + // the real stdin and stderr come back whether or not the script ran + back_in := C.dup2(saved_in, 0) >= 0 + back_err := C.dup2(saved_err, 2) >= 0 + reset_stdin() + if !wired_in || !wired_err { + return error('could not point stdin or stderr at the script') + } + if !back_in || !back_err { + return error('could not put stdin or stderr back after the script') + } + err_file.flush() + chan_file.flush() + return ScriptedRun{ + answers: answers + stderr: os.read_file(os.join_path(dir, 'stderr'))! + channel: os.read_lines(os.join_path(dir, 'channel'))! + } +} + +fn yn(b bool) int { + return if b { 1 } else { 0 } +} + +// confirm_both asks one question on the script with a yes preset, and the +// same on the same script with a no preset +fn confirm_both(text string) ![]int { + yes := on_stdin(.text, text, fn () []int { + mut p := TermPrompter{} + return [yn(p.confirm('a?', true))] + })! + no := on_stdin(.text, text, fn () []int { + mut p := TermPrompter{} + return [yn(p.confirm('a?', false))] + })! + return [yes.answers[0], no.answers[0]] +} + +fn test_term_confirm_reads_the_answer_on_stdin() ! { + // [with a yes preset, with a no preset], as pacman's question() answers + for text, want in { + // end of input is no, whatever the preset + '': [0, 0] + // an empty answer, blanks or not, takes the preset + '\n': [1, 0] + ' \t \n': [1, 0] + 'y\n': [1, 1] + 'Y\n': [1, 1] + 'yes\n': [1, 1] + ' YeS \n': [1, 1] + 'n\n': [0, 0] + 'no\n': [0, 0] + // anything else is no, even with a yes preset + 'maybe\n': [0, 0] + 'yess\n': [0, 0] + // a last line without its newline is an answer, as fgets reads it + 'y': [1, 1] + 'n': [0, 0] + } { + assert confirm_both(text)! == want, 'stdin ${text}' + } +} + +fn test_term_confirm_unreadable_stdin_is_no() ! { + // a closed stdin, or one that is a directory, fails the read: no answer + // comes, so the question is no — no panic, and no yes from the preset + for source in [StdinSource.closed, .directory] { + run := on_stdin(source, '', fn () []int { + mut p := TermPrompter{} + return [yn(p.confirm('a?', true)), yn(p.proceed('go?')), + p.choose('which?', ['x', 'y', 'z'])] + })! + assert run.answers == [0, 0, 0], '${source}' + // the questions were still put + assert run.stderr.contains('a?') && run.stderr.contains('go?') + } +} + +fn test_term_prompts_take_one_line_each() ! { + // each question reads its own line, no more; the end comes after + run := on_stdin(.text, 'y\nn\n\n2\n', fn () []int { + mut p := TermPrompter{} + return [yn(p.confirm('one?', false)), yn(p.confirm('two?', true)), + yn(p.confirm('three?', true)), p.choose('four?', ['a', 'b']), yn(p.confirm('five?', true))] + })! + assert run.answers == [1, 0, 1, 1, 0] + // the prompts go to stderr, in order, with their answer labels + for q in ['one?', 'two?', 'three?', 'four?', 'five?'] { + assert run.stderr.contains(q) + } + assert run.stderr.index('one?')? < run.stderr.index('five?')? +} + +fn test_term_proceed_end_of_input_is_no() ! { + // the go-ahead has a yes preset, which an empty answer takes, but the end + // of input never gives it + for text, want in { + '': 0 + '\n': 1 + 'n\n': 0 + 'yes': 1 + } { + run := on_stdin(.text, text, fn () []int { + mut p := TermPrompter{} + return [yn(p.proceed('proceed?'))] + })! + assert run.answers == [want], 'stdin ${text}' + } +} + +fn test_term_choose_reads_a_number() ! { + for text, want in { + '2\n': 1 + ' 3 \n': 2 + // an empty answer and the end of input take the first + '\n': 0 + '': 0 + // what is not a number of the list asks again + 'x\n9\n0\n3\n': 2 + '-1\n2\n': 1 + // and the end of input after it takes the first + 'x\n': 0 + } { + run := on_stdin(.text, text, fn () []int { + mut p := TermPrompter{} + return [p.choose('which?', ['a', 'b', 'c'])] + })! + assert run.answers == [want], 'stdin ${text}' + // every answer that is not a number of the list is said, and the + // question asked again: once more than the bad answers before the + // good one, or before the input ended + bad := text.split('\n').filter(it.trim_space() in ['x', '9', '0', '-1']) + for b in bad { + assert run.stderr.contains('invalid number: ${b}'), 'stdin ${text}: ${run.stderr}' + } + assert run.stderr.count('which?') == bad.len + 1, 'stdin ${text}: ${run.stderr}' + } +} + +fn test_term_noconfirm_leaves_stdin_unread() ! { + // --noconfirm shows each question and takes its default; the answer on + // stdin is still there for the first question that does read it + run := on_stdin(.text, '3\n', fn () []int { + mut quiet := TermPrompter{ + noconfirm: true + } + mut asks := TermPrompter{} + return [yn(quiet.confirm('a?', false)), yn(quiet.proceed('go?')), + quiet.choose('which?', ['a', 'b', 'c']), asks.choose('again?', ['a', 'b', 'c'])] + })! + assert run.answers == [0, 1, 0, 2] + assert run.stderr.contains('(yes, --noconfirm)') +} + +fn test_stdin_line() ! { + // a line comes without its newline, an empty line as '', a last line + // without a newline whole; then the end, a StdinEnd. an unreadable stdin + // is an error of its own, not the end + run := on_stdin(.text, 'one\n\nlast', fn () []int { + mut got := []int{} + for want in ['one', '', 'last'] { + line := stdin_line() or { return [-1] } + got << yn(line == want) + } + stdin_line() or { got << yn(err is StdinEnd) } + return got + })! + assert run.answers == [1, 1, 1, 1] + for source in [StdinSource.closed, .directory] { + failed := on_stdin(source, '', fn () []int { + stdin_line() or { + return [yn(err !is StdinEnd), yn(err.msg().starts_with('could not read stdin'))] + } + return [-1] + })! + assert failed.answers == [1, 1], '${source}' + } +} + +fn test_stdin_line_outlives_the_read_buffer() ! { + // a line is the caller's own copy: getline's buffer is freed on the way + // out, and the next read (same length, so the allocator hands the same + // block back) must not show through a line already returned. lines with + // and without the newline, an empty one, and a long one that makes + // getline grow its buffer + long := 'x'.repeat(5000) + run := on_stdin(.text, 'aaaa\nbbbb\n\n${long}\ncccc', fn [long] () []int { + mut lines := []string{} + for _ in 0 .. 5 { + lines << stdin_line() or { return [-1] } + // churn the heap between reads, as a prompt's own work does + mut junk := []string{} + for i in 0 .. 64 { + junk << 'zzzz${i}'.repeat(1 + i % 7) + } + } + return [yn(lines == ['aaaa', 'bbbb', '', long, 'cccc']), lines[3].len] + })! + assert run.answers == [1, 5000] +} + +fn test_stdin_text() ! { + run := on_stdin(.text, 'https://a.example/\nhttps://b.example/\n', fn () []int { + text := stdin_text() or { return [-1] } + return [yn(text == 'https://a.example/\nhttps://b.example/')] + })! + assert run.answers == [1] + // a read that fails is an error, not an empty list + failed := on_stdin(.directory, '', fn () []int { + stdin_text() or { return [yn(err.msg().contains('could not read stdin'))] } + return [-1] + })! + assert failed.answers == [1] +} + +// ipc_events decodes the channel's lines, every one a whole json object +fn ipc_events(lines []string) ![]map[string]json2.Any { + mut out := []map[string]json2.Any{} + for line in lines { + out << json2.decode[json2.Any](line)!.as_map() + } + return out +} + +fn test_ipc_prompter_reads_answers_on_stdin() ! { + run := on_stdin(.text, '{"id": 1, "answer": true}\n{"id": 2, "answer": 2}\n', fn () []int { + mut p := IpcPrompter{} + return [yn(p.confirm('a?', false)), p.choose('which?', ['x', 'y', 'z'])] + })! + assert run.answers == [1, 2] + events := ipc_events(run.channel)! + assert events.len == 2 + assert events[0]['type']!.str() == 'question' + assert events[0]['question']!.str() == 'confirm' + assert events[0]['id']!.int() == 1 + assert events[1]['question']!.str() == 'choose' + assert events[1]['id']!.int() == 2 +} + +fn test_ipc_prompter_invalid_lines_keep_the_question() ! { + // noise, an empty line and another question's answer are each an invalid + // event; the question stays, and the next valid line answers it + run := on_stdin(.text, 'garbage\n\n{"id": 9, "answer": true}\n{"id": 1, "answer": false}\n', fn () []int { + mut p := IpcPrompter{} + return [yn(p.confirm('a?', true))] + })! + assert run.answers == [0] + events := ipc_events(run.channel)! + assert events.map(it['type']!.str()) == ['question', 'invalid', 'invalid', 'invalid'] + for e in events[1..] { + assert e['id']!.int() == 1 + } +} + +fn test_ipc_prompter_end_of_input() ! { + // the end of input, and a stdin that cannot be read, answer as on a + // terminal: no, and the first choice — no panic + for source in [StdinSource.text, .closed, .directory] { + run := on_stdin(source, '', fn () []int { + mut p := IpcPrompter{} + return [yn(p.confirm('a?', true)), yn(p.proceed('go?')), p.choose('which?', [ + 'x', + 'y', + ])] + })! + assert run.answers == [0, 0, 0], '${source}' + assert ipc_events(run.channel)!.len == 3 + } +} + +fn test_ipc_prompter_noconfirm_answers_in_the_event() ! { + run := on_stdin(.text, '{"id": 1, "answer": false}\n', fn () []int { + mut p := IpcPrompter{ + noconfirm: true + } + return [yn(p.confirm('a?', true))] + })! + assert run.answers == [1] + events := ipc_events(run.channel)! + assert events.len == 1 + assert events[0]['answer']!.bool() == true +} + +fn test_verbose_log_says_what_a_run_went_on_from() ! { + saved_flag, saved_cfg, saved_kind := verbose_flag, cfg_verbose, ui_kind + defer { + verbose_flag, cfg_verbose, ui_kind = saved_flag, saved_cfg, saved_kind + } + fail := fn () []int { + went_on('release the alpm handle', error('the handle is not there')) + went_on('remove the temp dir /tmp/x', error('')) + return [] + } + // without --verbose a housekeeping failure stays as quiet as it was: + // nothing on stderr, nothing on the channel + verbose_flag, cfg_verbose, ui_kind = false, false, 'tty' + quiet := on_stdin(.text, '', fail)! + assert quiet.stderr == '' && quiet.channel.len == 0 + ui_kind = 'ipc' + quiet_ipc := on_stdin(.text, '', fail)! + assert quiet_ipc.stderr == '' && quiet_ipc.channel.len == 0 + // the flag and the config's option each turn it on, alone + for flag in [true, false] { + verbose_flag, cfg_verbose, ui_kind = flag, !flag, 'tty' + said := on_stdin(.text, '', fail)! + // a terminal gets it on stderr, marked, the reason after the what; + // a failure with no text of its own still names what failed + assert said.stderr == 'verbose: could not release the alpm handle: the handle is not there\nverbose: could not remove the temp dir /tmp/x: \n', said.stderr + assert said.channel.len == 0 + // a frontend gets a message event marked verbose, and a warning for + // a reader that knows no verbose mark; stderr stays clean + ui_kind = 'ipc' + told := on_stdin(.text, '', fail)! + assert told.stderr == '', told.stderr + events := ipc_events(told.channel)! + assert events.len == 2 + assert events[0]['type']!.str() == 'message' + assert events[0]['text']!.str() == 'could not release the alpm handle: the handle is not there' + assert events[0]['verbose']!.bool() && events[0]['warning']!.bool() + } + // an ordinary warning never carries the mark, verbose on or not + verbose_flag, ui_kind = true, 'ipc' + plain := on_stdin(.text, '', fn () []int { + warn('a real warning') + return [] + })! + assert 'verbose' !in ipc_events(plain.channel)![0] + assert verbose_on() + verbose_flag, cfg_verbose = false, false + assert !verbose_on() +} diff --git a/src/remote.v b/src/remote.v new file mode 100644 index 0000000..22827e9 --- /dev/null +++ b/src/remote.v @@ -0,0 +1,454 @@ +module main + +import alpm +import os + +// a target is a local package file if a file with that name exists, +// like pacman's -U handling +fn is_local_pkg_file(path string) bool { + return os.exists(path) && os.is_file(path) +} + +// FileTarget is a package archive an install loads from disk: one named on +// the command line, or one a url fetched into the cache +struct FileTarget { + path string + fetched bool +} + +// load_file_target loads an archive at the signature level pacman's -U +// gives it: the local file level for a file named, the remote file level +// for one fetched. the load is the only check a file package gets — +// libalpm's integrity pass at commit skips one loaded from a file as valid +// already — so a level of 0 here would let a bad signature beside the +// archive install unread +fn load_file_target(handle &alpm.Handle, t FileTarget) !&alpm.Package { + origin := if t.fetched { 'remote' } else { 'local' } + got := if t.fetched { + handle.option_get_remote_file_siglevel() + } else { + handle.option_get_local_file_siglevel() + } + level := got or { return error('could not read the ${origin} file signature level') } + return handle.pkg_load(t.path, 1, int(level)) or { + return error('failed to load ${t.path}: ${err.msg()}') + } +} + +// find_repo_pkg looks a name up in the sync dbs, in order +fn find_repo_pkg(dbs []&alpm.DB, name string) ?&alpm.Package { + for db in dbs { + if p := db.get_pkg(name) { + return p + } + } + return none +} + +// add_pkg_once adds a package unless one with its name is already in the list +fn add_pkg_once(mut pkgs []&alpm.Package, pkg &alpm.Package) { + if pkgs.any(it.get_name() == pkg.get_name()) { + return + } + pkgs << pkg +} + +// expand_group adds the member packages of a sync group to the transaction: +// members already installed at the sync version are skipped, and of the rest +// the user picks, as pacman's -S asks about a group (ask is false for a +// --print preview, and once another target failed: nothing installs then, +// so there is nothing to choose). it answers whether the name was a group at +// all, and how many members went in. a group with nothing left to install +// is said, not passed over in silence: it is still a target that resolved +fn expand_group(mut pkgs []&alpm.Package, mut ui TransUI, handle &alpm.Handle, dbs []&alpm.DB, name string, ask bool) (bool, int) { + found, members := sync_group_members(dbs, name) + if !found { + return false, 0 + } + mut news := []GroupMember{} + for m in members { + if local := handle.find_local_pkg(m.pkg.get_name()) { + if alpm.pkg_vercmp(local.get_version(), m.pkg.get_version()) >= 0 { + continue + } + } + news << m + } + if news.len == 0 { + // --print's output is the list alone + if !ui.print_only { + ui.pause() + report('group ${name}: every member is installed and up to date') + } + return true, 0 + } + chosen := select_members(mut ui, name, news, ask) + for m in chosen { + add_pkg_once(mut pkgs, m.pkg) + } + return true, chosen.len +} + +// skip_up_to_date is --needed: a target installed at the version it would +// install is left out, with pacman's warning. libalpm's needed flag does the +// same inside add_pkg, warning through its log; here the targets are left +// out before they reach the transaction, so its listing never shows them +fn skip_up_to_date(handle &alpm.Handle, pkgs []&alpm.Package) []&alpm.Package { + mut out := []&alpm.Package{} + for pkg in pkgs { + if local := handle.find_local_pkg(pkg.get_name()) { + if alpm.pkg_vercmp(local.get_version(), pkg.get_version()) == 0 { + warn('${pkg.get_name()}-${pkg.get_version()} is up to date, skipped') + continue + } + } + out << pkg + } + return out +} + +// walk_upgrade_deps adds the outdated dependencies of the targets and +// everything that hangs off them to the transaction, with libalpm's provider +// questions answered silently on the way: these walks look the dependencies +// up only to decide what to upgrade with, and the provider question that +// counts comes again in the prepare. the walking window is this function's +// whole body, so its defer is exactly as wide as the walks +fn walk_upgrade_deps(mut ui TransUI, handle &alpm.Handle, mut pkgs []&alpm.Package, mut added map[string]bool) ! { + ui.walking = true + defer { ui.walking = false } + sync_dbs := handle.get_syncdbs()! + mut upgrades := []&alpm.Package{} + upgrades << pkgs + for pkg in pkgs { + for dep in handle.outdated_deps(sync_dbs, pkg) { + upgrades << dep + } + } + for p in upgrades { + if p.get_name() !in added { + handle.add_pkg(p)! + added[p.get_name()] = true + } + } + // with nothing installed nothing can break, and the binding's + // broken_dependents takes libalpm's NULL for an empty local db as an + // error: it is asked only when some package is installed + if local_pkgcache(handle)! == unsafe { nil } { + return + } + for extra in handle.broken_dependents(upgrades, sync_dbs)! { + if extra.get_name() !in added { + handle.add_pkg(extra)! + added[extra.get_name()] = true + } + } +} + +// install_reason is the reason --asdeps or --asexplicit asks for, if any +fn install_reason(config ConfigInstall) ?alpm.PackageReason { + if config.asdeps { + return .depend + } + if config.asexplicit { + return .explicit + } + return none +} + +// mark_installed gives the installed targets the reason --asdeps or +// --asexplicit asks for. libalpm's alldeps and allexplicit flags would reach +// every package of the transaction, the outdated dependencies vpac upgrades +// along with the targets too, so the reason is set on the targets alone once +// they are in, under the db lock as pacman's -D does it +fn mark_installed(handle &alpm.Handle, names []string, reason alpm.PackageReason) ! { + trans_begin(handle, alpm.trans_flag_0)! + defer { trans_cleanup(handle) } + for name in names { + pkg := handle.find_local_pkg(name) or { continue } + if pkg.get_reason() != reason { + pkg.set_reason(reason)! + } + } +} + +// install_pkgs prepares one transaction for all the packages. with the default +// it also adds the outdated dependencies of each one, then lists everything the +// transaction touches and asks before committing. it returns false when the user +// declines +fn install_pkgs(handle &alpm.Handle, mut ui TransUI, mut pkgs []&alpm.Package, config ConfigInstall) !bool { + mut s := ui.spinner(text: 'preparing transaction') + s.start() + defer { stop_spinner(mut s) } + + mut flags := dep_check_flag(config.nodeps, config.nodeps_level) | print_flags(config.print_only) + if config.download_only { + flags |= .download_only + } + if config.dbonly { + flags |= .db_only + } + trans_begin(handle, flags)! + mut added := map[string]bool{} + for pkg in pkgs { + handle.add_pkg(pkg)! + added[pkg.get_name()] = true + } + if !config.no_upgrade_deps { + walk_upgrade_deps(mut ui, handle, mut pkgs, mut added)! + } + + trans_prepare_checked(handle) or { + return error(prepare_error(handle, err.msg(), config.no_upgrade_deps)) + } + // every result print below needs the render thread gone + end_frame(mut ui, mut s) + // --print stops here: the transaction is listed with the archive names, + // and nothing is downloaded or installed + if config.print_only { + if ipc_on() { + mut preview := trans_listing(handle, handle.trans_get_add().pkgs(), .install) + preview.preview = true + emit(preview) + return false + } + for pkg in handle.trans_get_add().pkgs() { + file := pkg.get_filename() + println(if file == '' { pkg.get_name() } else { file }) + } + return false + } + // every transaction is listed and confirmed before it may go: the default + // pulls in upgrades beyond the targets, --no-upgrade-deps still installs + // the ones it names, and pacman's -S asks in both cases. packages the + // transaction removes, such as a conflicting one, are listed too + removals := handle.trans_get_remove().pkgs() + if removals.len > 0 { + ui.show_packages('${removals.len} packages to remove:', removals) + } + if !trans_confirm(mut ui, handle, handle.trans_get_add().pkgs(), .install) { + return false + } + + mut commit := ui.spinner( + text: if config.download_only { + 'downloading packages' + } else { + 'installing packages' + } + ) + commit.start() + defer { stop_spinner(mut commit) } + trans_commit(handle)! + stop_spinner(mut commit) + return true +} + +// install installs the targets. URLs are downloaded first. local files and repo +// packages go into one transaction, confirmed once. names in neither the repos +// nor the pkgbuild repo are offered the closest repo name. pkgbuild packages are built one at a +// time, after that transaction. a target nothing resolves is reported and +// the rest are still looked up, so every bad one is named in one run; then +// nothing installs, as pacman's -S stops after its target errors +fn install(config ConfigInstall) ! { + need_query(config.query, 'package')! + if config.asdeps && config.asexplicit { + return error('--asdeps and --asexplicit contradict each other: pick one') + } + // a --print preview asks nothing and takes no lock, as pacman's + mut ui := new_trans_ui(noconfirm: config.noconfirm || config.print_only) + if !config.print_only { + check_ask_db_lock(mut ui) + } + + // the timeout option is read when the handle is made, so it is set first + if config.disable_timeout { + cfg_disable_timeout = true + } + ui.print_only = config.print_only + ui.download_only = config.download_only + // one handle for the whole install: a url target is fetched through it, + // drawing on the same display and asking through the same prompter as + // the transaction's own downloads + mut handle := init_handle(ui)! + defer { handle.release() or { went_on('release the alpm handle', err) } } + defer { ui.stop() } + defer { trans_cleanup(handle) } + trans_options(config).apply(handle)! + + mut file_targets := []FileTarget{} + mut names := []string{} + for target in config.query { + if is_url(target) { + if config.print_only { + // a url target is printed as it is; nothing is fetched. the + // same message event a build plan goes out as carries this + // line on both a terminal and a frontend + report('would fetch ${target}') + continue + } + file_targets << FileTarget{ + path: fetch_target_url(mut ui, handle, target)! + fetched: true + } + } else if is_local_pkg_file(target) { + file_targets << FileTarget{ + path: target + } + } else { + names << target + } + } + + mut s := ui.spinner(text: 'getting dbs and updating em') + s.start() + defer { stop_spinner(mut s) } + + dbs := init_repos(mut handle)! + if names.len > 0 { + check_sync_fresh(mut ui, mut handle)! + } + + mut pkgs := []&alpm.Package{} + for f in file_targets { + add_pkg_once(mut pkgs, load_file_target(handle, f)!) + } + mut pkgbuild := []string{} + mut missed := 0 + mut groups := map[string]bool{} + for name in names { + if config.pkgbuild { + pkgbuild << name + continue + } + // repo/name looks in that repo alone, for the package and the group + target := parse_target(name) + scoped := scope_dbs(dbs, target.repo) or { + target_error(err.msg()) + missed++ + continue + } + if p := find_sync_target(handle, scoped, target.name, target.repo != '') { + add_pkg_once(mut pkgs, p) + continue + } + // a group named twice is asked about once + if groups[name] { + continue + } + // a group installs the members picked of the ones that are not + // installed at the sync version already + found, _ := expand_group(mut pkgs, mut ui, handle, scoped, target.name, !config.print_only + && missed == 0) + if found { + groups[name] = true + continue + } + // a repo named is the whole search: the pkgbuild repos are no + // fallback for it + if target.repo != '' { + target_error('target not found in ${target.repo}: ${target.name}') + missed++ + continue + } + pkgbuild << name + } + stop_spinner(mut s) + if config.needed { + pkgs = skip_up_to_date(handle, pkgs) + } + + mut pkgbuild_builds := []string{} + if config.pkgbuild && pkgbuild_repos().len == 0 { + return error('no pkgbuild repo in the config: add (repo :name "aur" :type "pkgbuild" :src "https://aur.archlinux.org")') + } + for name in pkgbuild { + if config.pkgbuild { + pkgbuild_builds << name + continue + } + // nothing in the repos: the pkgbuild repos are next, and they review + // before they build + in_the_repos := pkgbuild_has(name) or { return err } + if in_the_repos { + pkgbuild_builds << name + continue + } + // the pkgbuild db is not the only source: a typo of a package that is + // only installed gets its proposal too + fixed := did_you_mean(mut ui, name, all_names(handle, dbs)) or { + target_error('"${name}" is not in the repos or the pkgbuild repo') + missed++ + continue + } + // the accepted suggestion goes the same way the typo would have: a + // pkgbuild package from its repo, a repo package into the + // transaction, and a name nothing carries is the miss it is + fixed_found := pkgbuild_has(fixed) or { return err } + if fixed_found { + pkgbuild_builds << fixed + continue + } + if p := find_repo_pkg(dbs, fixed) { + add_pkg_once(mut pkgs, p) + } else { + target_error('"${fixed}" is not in the repos or the pkgbuild repo') + missed++ + } + } + // the bad targets are all named by now; pacman installs nothing then + if missed > 0 { + return + } + + if config.download_only && pkgbuild_builds.len > 0 { + return error('download-only does not build pkgbuild packages') + } + + if pkgs.len == 0 && pkgbuild_builds.len == 0 { + // --print's output is the list alone + if !config.print_only { + report('there is nothing to do') + } + return + } + + if pkgs.len > 0 { + // the names are read before the commit, which may free the packages + targets := pkgs.map(it.get_name()) + done := targets.map(name_style(it)) + committed := install_pkgs(handle, mut ui, mut pkgs, config)! + // not the defer's work done twice: the pkgbuild installs below begin + // transactions of their own on this handle, so this one is closed + // here, and the defer has nothing left to close when it runs + trans_cleanup(handle) + if !committed { + // --print listed the repo part; the build plan is still listed + if config.print_only { + for name in pkgbuild_builds { + report('would build ${name}') + } + } + return + } + if !config.download_only { + if reason := install_reason(config) { + mark_installed(handle, targets, reason)! + } + } + print_done(mut ui, if config.download_only { + 'downloaded:' + } else { + 'installed:' + }, done) + } + // --print lists the build plan and stops + if config.print_only { + for name in pkgbuild_builds { + report('would build ${name}') + } + return + } + for target in pkgbuild_builds { + pkgbuild_install(mut ui, mut handle, config, target)! + } +} diff --git a/src/remote_test.v b/src/remote_test.v new file mode 100644 index 0000000..b4f77e0 --- /dev/null +++ b/src/remote_test.v @@ -0,0 +1,173 @@ +module main + +import alpm +import os + +fn test_install_reason() { + assert install_reason(ConfigInstall{}) == none + assert install_reason(ConfigInstall{ asdeps: true }) or { panic('none') } == .depend + assert install_reason(ConfigInstall{ asexplicit: true }) or { panic('none') } == .explicit +} + +// reason_db writes a libalpm local db with two packages, one of each reason +fn reason_db(dbpath string) ! { + local := os.join_path(dbpath, 'local') + os.mkdir_all(local)! + os.write_file(os.join_path(local, 'ALPM_DB_VERSION'), '9\n')! + for name, reason in { + 'dep': 1 + 'top': 0 + } { + dir := os.join_path(local, '${name}-1.0-1') + os.mkdir_all(dir)! + os.write_file(os.join_path(dir, 'desc'), '%NAME%\n${name}\n\n%VERSION%\n1.0-1\n\n%REASON%\n${reason}\n\n')! + os.write_file(os.join_path(dir, 'files'), '%FILES%\n\n')! + } +} + +fn local_reason(root string, dbpath string, name string) !alpm.PackageReason { + handle := alpm.initialize(root, dbpath)! + defer { handle.release() or {} } + pkg := handle.find_local_pkg(name) or { return error('${name} is not installed') } + return pkg.get_reason() +} + +fn test_mark_installed() ! { + tmp := os.join_path(os.vtmp_dir(), 'vpac_test_remote_${os.getpid()}') + root := os.join_path(tmp, 'root') + '/' + dbpath := os.join_path(tmp, 'db') + '/' + os.mkdir_all(root)! + reason_db(dbpath)! + defer { os.rmdir_all(tmp) or {} } + + handle := alpm.initialize(root, dbpath)! + // --asexplicit on the dependency, --asdeps on the top package; a name + // that is not installed (a target that failed) is passed over + mark_installed(handle, ['dep', 'missing'], .explicit)! + mark_installed(handle, ['top'], .depend)! + handle.release()! + // the lock is gone again, and a fresh handle reads the new reasons back + // from disk + assert !os.exists(os.join_path(tmp, 'db', 'db.lck')) + assert local_reason(root, dbpath, 'dep')! == .explicit + assert local_reason(root, dbpath, 'top')! == .depend +} + +// SigFixture is a package archive with no signature beside it yet, and the +// root, db and keyring dirs a handle needs, all under one temp dir +struct SigFixture { + tmp string + pkg string +} + +// sig_fixture writes foo-1.0-1-any.pkg.tar, a one-entry archive libalpm +// loads as a package: its .PKGINFO +fn sig_fixture(name string) !SigFixture { + tmp := os.join_path(os.vtmp_dir(), 'vpac_test_sig_${name}_${os.getpid()}') + os.rmdir_all(tmp) or {} + for d in ['root', 'db/local', 'gpg', 'cache', 'src'] { + os.mkdir_all(os.join_path(tmp, d))! + } + os.write_file(os.join_path(tmp, 'db/local/ALPM_DB_VERSION'), '9\n')! + os.write_file(os.join_path(tmp, 'src/.PKGINFO'), 'pkgname = foo\npkgbase = foo\npkgver = 1.0-1\narch = any\nsize = 0\n')! + pkg := os.join_path(tmp, 'foo-1.0-1-any.pkg.tar') + res := os.exec(['tar', '-cf', pkg, '-C', os.join_path(tmp, 'src'), '.PKGINFO']) + if res.exit_code != 0 { + return error('tar failed: ${res.output}') + } + return SigFixture{ + tmp: tmp + pkg: pkg + } +} + +// handle opens the fixture's root with its own keyring dir, so the gpg a +// signature check starts reads and writes nothing outside the fixture +fn (fx SigFixture) handle(local alpm.SigLevel, remote alpm.SigLevel) !&alpm.Handle { + handle := alpm.initialize(os.join_path(fx.tmp, 'root') + '/', os.join_path(fx.tmp, 'db') + '/')! + handle.option_set_gpgdir(os.join_path(fx.tmp, 'gpg') + '/')! + handle.option_set_local_file_siglevel(local)! + handle.option_set_remote_file_siglevel(remote)! + return handle +} + +// loads tells whether the fixture's archive loads as t's origin +fn loads(handle &alpm.Handle, path string, fetched bool) bool { + pkg := load_file_target(handle, FileTarget{ + path: path + fetched: fetched + }) or { return false } + pkg.free_pkg() or {} + return true +} + +const sig_optional = alpm.SigLevel.package | .package_optional +const sig_required = alpm.SigLevel.package + +fn test_load_file_target_verifies_a_signature_beside_the_archive() ! { + fx := sig_fixture('present')! + defer { os.rmdir_all(fx.tmp) or {} } + handle := fx.handle(sig_optional, sig_optional)! + defer { handle.release() or {} } + // optional: an unsigned archive is taken as it is + assert loads(handle, fx.pkg, false) + assert loads(handle, fx.pkg, true) + // a signature beside it is read and must hold. libalpm checks a file + // package at its load only, so a load at level 0 installed this one + os.write_file(fx.pkg + '.sig', 'not a signature')! + for fetched in [false, true] { + load_file_target(handle, FileTarget{ path: fx.pkg, fetched: fetched }) or { + assert err.msg().starts_with('failed to load ${fx.pkg}: ') + assert err.msg().contains('signature'), err.msg() + continue + } + assert false, 'a corrupt signature loaded (fetched: ${fetched})' + } +} + +fn test_load_file_target_takes_the_level_of_its_origin() ! { + fx := sig_fixture('origin')! + defer { os.rmdir_all(fx.tmp) or {} } + // a file named takes the local level, a fetched one the remote level, as + // pacman's -U loads them: the unsigned archive fails where its origin's + // level requires a signature, and only there + local_strict := fx.handle(sig_required, sig_optional)! + assert !loads(local_strict, fx.pkg, false) + assert loads(local_strict, fx.pkg, true) + local_strict.release()! + remote_strict := fx.handle(sig_optional, sig_required)! + assert loads(remote_strict, fx.pkg, false) + assert !loads(remote_strict, fx.pkg, true) + remote_strict.release()! +} + +fn test_init_handle_checks_file_targets_at_the_configured_level() ! { + // the whole way vpac opens a handle for an install: the configured level + // (the default here, pacman's) reaches both kinds of file target + fx := sig_fixture('config')! + defer { os.rmdir_all(fx.tmp) or {} } + saved_root, saved_db, saved_gpg := root_path, db_path, cfg_gpgdir + saved_cache, saved_user, saved_level := cfg_cachedirs.clone(), download_user, cfg_siglevel + saved_hooks := cfg_hookdirs.clone() + cfg_hookdirs = []string{} + defer { + root_path, db_path, cfg_gpgdir = saved_root, saved_db, saved_gpg + cfg_cachedirs = saved_cache.clone() + cfg_hookdirs = saved_hooks.clone() + download_user, cfg_siglevel = saved_user, saved_level + } + root_path = os.join_path(fx.tmp, 'root') + '/' + db_path = os.join_path(fx.tmp, 'db') + '/' + cfg_gpgdir = os.join_path(fx.tmp, 'gpg') + '/' + cfg_cachedirs = [os.join_path(fx.tmp, 'cache') + '/'] + // the sandbox user need not exist where the tests run + download_user = '' + ui := new_trans_ui() + handle := init_handle(ui)! + defer { handle.release() or {} } + assert loads(handle, fx.pkg, false) + assert loads(handle, fx.pkg, true) + os.write_file(fx.pkg + '.sig', 'not a signature')! + assert !loads(handle, fx.pkg, false) + assert !loads(handle, fx.pkg, true) +} diff --git a/src/remove.v b/src/remove.v new file mode 100644 index 0000000..6054460 --- /dev/null +++ b/src/remove.v @@ -0,0 +1,172 @@ +module main + +import alpm + +// local_group_pkgs are the installed members of a group, pacman -R's +// fallback for a target that is no package: the local db's own group +fn local_group_pkgs(handle &alpm.Handle, name string) []&alpm.Package { + localdb := handle.get_localdb() or { return []&alpm.Package{} } + group := localdb.get_group(name) or { return []&alpm.Package{} } + return group.packages.pkgs() +} + +// recurse_flags is pacman's -s: once takes the dependencies the removal +// leaves unneeded, twice (-ss, or --recursive with -s) the ones that were +// installed explicitly too +fn recurse_flags(recursive bool, level int) alpm.TransFlag { + n := level + if recursive { 1 } else { 0 } + return if n >= 2 { + alpm.TransFlag.recurse | .recurse_all + } else if n == 1 { + alpm.TransFlag.recurse + } else { + alpm.trans_flag_0 + } +} + +// remove removes the targets in one transaction, confirmed once +fn remove(config ConfigRemove) ! { + need_query(config.query, 'package')! + // a --print preview asks nothing and takes no lock, as pacman's + mut ui := new_trans_ui(noconfirm: config.noconfirm || config.print_only) + ui.print_only = config.print_only + if !config.print_only { + check_ask_db_lock(mut ui) + } + + mut handle := init_handle(ui)! + defer { handle.release() or { went_on('release the alpm handle', err) } } + defer { ui.stop() } + defer { trans_cleanup(handle) } + TransOptions{ + assume_installed: config.assume_installed + }.apply(handle)! + + mut s := ui.spinner(text: 'preparing removal') + s.start() + defer { stop_spinner(mut s) } + + mut pkgcache := local_pkgcache(handle)! + + // every target is found before the transaction starts, so an unknown + // name removes nothing: each bad one is reported and the rest still + // looked up, and then the run stops, as pacman's -R does. a target is a + // package, what satisfies its version constraint, or a group of the + // local db + mut pkgs := []&alpm.Package{} + mut missed := 0 + for target in config.query { + name := local_target_name(target) + if pkg := find_local_target(pkgcache, name, false) { + add_pkg_once(mut pkgs, pkg) + continue + } + members := local_group_pkgs(handle, name) + if members.len > 0 { + for pkg in members { + add_pkg_once(mut pkgs, pkg) + } + continue + } + stop_spinner(mut s) + fixed := did_you_mean(mut ui, name, pkg_names(pkgcache.pkgs())) or { + target_error(err.msg()) + missed++ + continue + } + pkg := pkgcache.pkg_find(fixed) or { + target_error('unknown package: "${fixed}"') + missed++ + continue + } + add_pkg_once(mut pkgs, pkg) + } + stop_spinner(mut s) + if missed > 0 { + return + } + + // the config can hold a package: refuse before anything is staged + check_hold(pkgs.map(it.get_name()))! + + // recursive takes the dependencies that the removal leaves unneeded too, as + // pacman's -Rs does. they are listed with the packages and confirmed once + mut flags := dep_check_flag(config.nodeps, config.nodeps_level) | print_flags(config.print_only) | recurse_flags(config.recursive, + config.recursive_level) + // pacman's -Ru: a target something still requires is left out by + // libalpm instead of failing the removal + if config.unneeded { + flags |= .unneeded + } + if config.cascade { + flags |= .cascade + } + if config.nosave { + flags |= .no_save + } + if config.dbonly { + flags |= .db_only + } + trans_begin(handle, flags)! + for pkg in pkgs { + handle.remove_pkg(pkg)! + } + + trans_prepare_checked(handle)! + + victims := handle.trans_get_remove().pkgs() + if victims.len == 0 { + // -u left every target where it is needed: pacman's answer, and no + // failure + if config.unneeded { + end_frame(mut ui, mut s) + if !config.print_only { + report('there is nothing to do') + } + return + } + return error('nothing to do') + } + + // --print stops here: what the removal takes is listed the way pacman's + // -Rp lists it, name-version, and nothing is removed + if config.print_only { + end_frame(mut ui, mut s) + if ipc_on() { + mut preview := trans_listing(handle, victims, .remove) + preview.preview = true + emit(preview) + return + } + for pkg in victims { + println('${pkg.get_name()}-${pkg.get_version()}') + } + return + } + + // the transaction is the truth of what goes: recursive and cascade pull + // packages in beyond the targets, and the hold list counts for them too + check_hold(victims.map(it.get_name()))! + + if !trans_confirm(mut ui, handle, victims, .remove) { + return + } + + // the names are read before the commit, which frees the removed packages + // with -u a target may have stayed: the ones that go are the ones named + going := victims.map(it.get_name()) + mut done := []string{} + for pkg in pkgs { + if pkg.get_name() in going { + done << name_style(pkg.get_name()) + } + } + + mut s2 := ui.spinner(text: 'removing packages') + s2.start() + defer { stop_spinner(mut s2) } + trans_commit(handle)! + stop_spinner(mut s2) + + print_done(mut ui, 'removed:', done) +} diff --git a/src/search.v b/src/search.v new file mode 100644 index 0000000..a2d0b2e --- /dev/null +++ b/src/search.v @@ -0,0 +1,363 @@ +module main + +import alpm +import strings + +// terms_match is the classic match: every term is in the name or in the +// description, case ignored. no terms match everything, as pacman's -Ss +// with no target lists everything +fn terms_match(name string, desc string, terms []string) bool { + n, d := name.to_lower(), desc.to_lower() + for term in terms { + t := term.to_lower() + if !n.contains(t) && !d.contains(t) { + return false + } + } + return true +} + +// match_classic is the classic match of a libalpm package +fn match_classic(pkg &alpm.Package, config ConfigSearch) bool { + return terms_match(pkg.get_name(), pkg.get_desc(), config.query) +} + +fn jw_if_match(config ConfigSearch, needle string, haystack string) ?f64 { + score := strings.jaro_winkler_similarity(needle, haystack) + if score >= config.thold { + return score + } + return none +} + +// match_fuzzy_name needs every term to match the name, and scores the name by +// the average of the terms +fn match_fuzzy_name(pkg &alpm.Package, config ConfigSearch) ?f64 { + if config.query.len == 0 { + return none + } + name := pkg.get_name().to_lower() + mut total := 0.0 + for term in config.query { + score := jw_if_match(config, term.to_lower(), name) or { return none } + total += score + } + return total / f64(config.query.len) +} + +// fuzzy_desc_hit is true when one word of the description matches the term +fn fuzzy_desc_hit(config ConfigSearch, term string, words []string) bool { + for h in words { + if _ := jw_if_match(config, term, h) { + return true + } + } + return false +} + +fn match_fuzzy_desc(pkg &alpm.Package, config ConfigSearch) bool { + if config.query.len == 0 { + return false + } + words := pkg.get_desc().to_lower().split(' ').filter(|word| word.runes().len > 1) + for term in config.query { + if !fuzzy_desc_hit(config, term.to_lower(), words) { + return false + } + } + return true +} + +struct Scored { + pkg &alpm.Package + score f64 +} + +fn build_matches(pkgs []&alpm.Package, config ConfigSearch) []&alpm.Package { + return if config.fuzzy { + mut m_name := []Scored{cap: pkgs.len} + for pkg in pkgs { + if s := match_fuzzy_name(pkg, config) { + m_name << Scored{pkg, s} + } + } + // strong name matches lead; desc-only matches trail them. a package + // listed for its name is not listed again for its description: the + // names matched are a set, one lookup per package instead of a scan + // of the matches (one call reads one db, where names are unique) + m_name.sort(a.score > b.score) + m_name_pkg := m_name.map(|pkg| pkg.pkg) + mut by_name := map[string]bool{} + for pkg in m_name_pkg { + by_name[pkg.get_name()] = true + } + m_desc_pkg := pkgs.filter(|pkg| !by_name[pkg.get_name()] && match_fuzzy_desc(pkg, config)) + // one new list, the name matches then the description ones: neither + // of the two it is made of is written to + mut matches := []&alpm.Package{cap: m_name_pkg.len + m_desc_pkg.len} + matches << m_name_pkg + matches << m_desc_pkg + matches + } else { + pkgs.filter(|pkg| match_classic(pkg, config)) + } +} + +// pkgbuild_matches is the classic match for AUR results, which only have a name and +// a description +fn pkgbuild_matches(pkg PackagePkgbuild, terms []string) bool { + return terms_match(pkg.name, pkg.description, terms) +} + +// filtered is true when a filter flag asks for installed packages with a property +fn (config ConfigSearch) filtered() bool { + return config.deps || config.explicit || config.foreign || config.native + || config.unrequired || config.upgrades +} + +// GroupRef is one group of a db, as the bare group listing collects it: a +// sync db's, or the local db's (repo 'local') with -l +struct GroupRef { + repo string + name string +} + +// group_source is how a listing names a db: the local one is 'local', as +// the installed packages are everywhere else +fn group_source(handle &alpm.Handle, db &alpm.DB) string { + if localdb := handle.get_localdb() { + if voidptr(localdb) == voidptr(db) { + return 'local' + } + } + return db.get_name() +} + +// sync_groups lists every group of the dbs, db by db +fn sync_groups(handle &alpm.Handle, dbs []&alpm.DB) []GroupRef { + mut out := []GroupRef{} + for db in dbs { + mut node := db.get_groupcache() or { continue } + for node != unsafe { nil } { + if group := node.get_group() { + out << GroupRef{group_source(handle, db), group.get_name()} + } + node = node.next + } + } + return out +} + +// scope_repo narrows a search to one repo when its first name is one, like +// 'vpac s -r extra zsh': the dbs left, and the query without the repo +fn scope_repo(dbs []&alpm.DB, query []string) ([]&alpm.DB, []string) { + if query.len > 1 && dbs.any(it.get_name() == query[0]) { + return dbs.filter(it.get_name() == query[0]), query[1..] + } + return dbs, query +} + +// collect_group_members lists the members of the named groups of dbs: the +// sync dbs, or the local db for pacman's -Qg. the filters look at the +// installed packages: a member that is not installed cannot pass them, and +// sync_dbs is what the sync-comparing ones compare with +fn collect_group_members(mut listing Listing, handle &alpm.Handle, dbs []&alpm.DB, sync_dbs []&alpm.DB, config ConfigSearch) ! { + for name in config.query { + mut found := false + // a group several dbs carry lists each member once, from the first + // db that has it, as alpm_find_group_pkgs does + mut seen := map[string]bool{} + for db in dbs { + group := db.get_group(name) or { continue } + found = true + for pkg in group.packages.pkgs() { + if seen[pkg.get_name()] { + continue + } + seen[pkg.get_name()] = true + local := handle.find_local_pkg(pkg.get_name()) + if config.installed && local == none { + continue + } + if config.filtered() { + l := local or { continue } + if !pkg_matches_filter(l, config, sync_dbs) { + continue + } + } + listing.add_member(pkg, group_source(handle, db), name) + } + } + // as pacman's -Sg: one missing group fails the run, the rest list + if !found { + target_error('group "${name}" not found') + } + } +} + +// collect_search lists the matches of the query: the installed packages, the +// sync dbs and the pkgbuild repos, each when the config asks for it +fn collect_search(mut listing Listing, mut ui TransUI, mut handle &alpm.Handle, config ConfigSearch) ! { + if config.local { + mut pkgcache := local_pkgcache(handle)! + + sync_dbs := filter_sync_dbs(mut ui, mut handle, config)! + installed := pkgcache.pkgs().filter(|pkg| pkg_matches_filter(pkg, config, sync_dbs)) + for pkg in build_matches(installed, config) { + listing.add_pkg(pkg, 'local') + } + } + + if config.remote { + mut scope := config + dbs, query := scope_repo(init_repos(mut handle)!, config.query) + scope.query = query + if scope.sync_dbs { + check_ask_db_lock(mut ui) + update_repos(mut handle, false)! + } else { + check_sync_fresh(mut ui, mut handle)! + } + + for db in dbs { + mut pkgcache := pkgcache_of(handle, db)! + for pkg in build_matches(pkgcache.pkgs(), scope) { + if scope.installed && handle.find_local_pkg(pkg.get_name()) == none { + continue + } + listing.add_pkg(pkg, db.get_name()) + } + } + } + + if config.pkgbuild { + mut brepos := pkgbuild_repos() + if brepos.len == 0 { + return error('no pkgbuild repo in the config: add (repo :name "aur" :type "pkgbuild" :src "https://aur.archlinux.org")') + } + // a first name that is a pkgbuild repo narrows the search to it + mut bquery := config.query.clone() + if bquery.len > 1 { + known := brepos.map(it.name) + if bquery[0] in known { + brepos = brepos.filter(it.name == bquery[0]) + bquery = bquery[1..] + } + } + // each pkgbuild repo is searched on its own site, and its results + // carry the repo's name + needle := if bquery.len > 0 { bquery[0] } else { '' } + rest := if bquery.len > 1 { bquery[1..] } else { []string{} } + for repo in brepos { + pkgs := get_pkgbuild_packages(repo.servers[0].trim_right('/'), needle) or { return err } + for pkg in pkgs { + if pkgbuild_matches(pkg, rest) { + if config.installed && handle.find_local_pkg(pkg.name) == none { + continue + } + listing.add_pkgbuild(pkg, repo.name) + } + } + } + } +} + +// search collects the matches, then prints them. a search that fails part +// way prints no partial table, but its quiet listing still names what was +// found before the error, the way a stream of names does +fn search(config ConfigSearch) ! { + if config.filtered() && !config.groups && (config.remote || config.pkgbuild) { + return error('the filters only apply to installed packages: use them with -l, not -r or -a') + } + // the groups are the installed packages' or the sync dbs', pacman's -Qg + // or -Sg: asked for both, one of the two would be dropped without a word + if config.groups && config.local && config.remote { + return error('search -g lists the groups of the installed packages (-l) or of the sync dbs (-r), not both at once') + } + mut ui := new_trans_ui(noconfirm: config.noconfirm) + mut handle := init_handle(ui)! + defer { handle.release() or { went_on('release the alpm handle', err) } } + defer { ui.stop() } + + fields := parse_fields(config.fields, cfg_search_fields)! + mut listing := Listing{ + mode: if config.quiet { PrintMode.minimal } else { PrintMode.default } + fields: fields + } + + if config.groups { + mut scope := config + mut dbs := []&alpm.DB{} + mut sync_dbs := []&alpm.DB{} + if config.local { + // pacman's -Qg: the groups of the installed packages, read from + // the local db. the sync dbs come in only for a filter that + // compares with them + dbs << handle.get_localdb() or { + return error('could not open the local database: ${err.msg()}') + } + sync_dbs = filter_sync_dbs(mut ui, mut handle, scope)! + } else { + // the same repo scoping narrows the group listing + scoped, query := scope_repo(init_repos(mut handle)!, config.query) + dbs = scoped.clone() + scope.query = query.clone() + // the sync-comparing filters (--native, --foreign, --upgrades) reach + // into these dbs through pkg_matches_filter, so they run the same + // freshness check the installed-package listing does. the dbs are + // registered above already, and libalpm refuses a second + // registration, so the check is all that is left of + // filter_sync_dbs here + if scope.foreign || scope.native || scope.upgrades { + check_sync_fresh(mut ui, mut handle)! + } + sync_dbs = dbs.clone() + } + if scope.query.len == 0 && config.groups_level >= 2 { + // -gg: every group with its members, pacman's 'group package' + // lines; each group is listed once, whichever dbs carry it + mut names := []string{} + for g in sync_groups(handle, dbs) { + if g.name !in names { + names << g.name + } + } + scope.query = names + collect_group_members(mut listing, handle, dbs, sync_dbs, scope)! + if ipc_on() || config.quiet { + listing.print() + } else { + for e in listing.entries { + println('${e.group} ${name_style(e.name)}') + } + } + return + } + if scope.query.len == 0 { + // no names: every group of every db, one line each + groups := sync_groups(handle, dbs) + if ipc_on() { + emit(GroupsEvent{ + groups: groups + }) + return + } + for g in groups { + println(table_text([row(g.repo, g.name)], ' ', ' ')) + } + return + } + collect_group_members(mut listing, handle, dbs, sync_dbs, scope) or { + listing.print_found() + return err + } + listing.print() + return + } + + collect_search(mut listing, mut ui, mut handle, config) or { + listing.print_found() + return err + } + listing.print() +} diff --git a/src/search_test.v b/src/search_test.v new file mode 100644 index 0000000..e847f9e --- /dev/null +++ b/src/search_test.v @@ -0,0 +1,38 @@ +module main + +fn test_terms_match_edges() { + // every term must be somewhere, in the name or in the description + assert terms_match('zsh', 'a shell', ['zsh']) + assert terms_match('zsh', 'a shell', ['shell']) + assert terms_match('zsh', 'a shell', ['zsh', 'shell']) + assert !terms_match('zsh', 'a shell', ['zsh', 'editor']) + assert !terms_match('zsh', 'a shell', ['bash']) + // case is ignored on both sides + assert terms_match('Zsh', 'A Shell', ['zSH', 'sHELL']) + // a term is a substring, not a word, and may span nothing but itself + assert terms_match('zsh-completions', '', ['sh-comp']) + assert !terms_match('zsh', 'a shell', ['zsh shell']) + // no terms match everything, as a bare pacman -Ss lists everything; an + // empty term is in every text + assert terms_match('zsh', 'a shell', []) + assert terms_match('', '', []) + assert terms_match('zsh', '', ['']) + // nothing to look in matches no real term + assert !terms_match('', '', ['x']) + // multibyte text is matched as text + assert terms_match('grüße', 'ein Paket', ['üß']) +} + +fn test_pkgbuild_matches_as_the_classic_match() { + pkg := PackagePkgbuild{ + name: 'yay-bin' + description: 'Yet another yogurt' + } + assert pkgbuild_matches(pkg, ['yay']) + assert pkgbuild_matches(pkg, ['YOGURT', 'bin']) + assert !pkgbuild_matches(pkg, ['yay', 'paru']) + assert pkgbuild_matches(pkg, []) + // a record with no description still matches by its name + assert pkgbuild_matches(PackagePkgbuild{ name: 'paru' }, ['par']) + assert !pkgbuild_matches(PackagePkgbuild{ name: 'paru' }, ['helper']) +} diff --git a/src/style.v b/src/style.v new file mode 100644 index 0000000..9f5954e --- /dev/null +++ b/src/style.v @@ -0,0 +1,140 @@ +@[has_globals] +module main + +import term + +// color_flag is --color: 'auto' styles a terminal only, 'always' and +// 'never' decide for every stream, as pacman's --color does +__global color_flag = 'auto' +// color_given is whether the command line spelled a --color: the config's +// (options :color) is the default only when it did not +__global color_given = false + +// color_on is whether a stream gets styled: stdout, or stderr with err +fn color_on(err bool) bool { + return match color_flag { + 'always' { true } + 'never' { false } + else { + if err { term.can_show_color_on_stderr() } else { term.can_show_color_on_stdout() } + } + } +} + +// style_names are the styles a theme may name, (color :role [...]): the +// terminal's attributes and its sixteen colors +const style_names = ['none', 'bold', 'dim', 'italic', 'underline', 'reverse', 'black', 'red', 'green', + 'yellow', 'blue', 'magenta', 'cyan', 'white', 'gray', 'bright_black', 'bright_red', 'bright_green', + 'bright_yellow', 'bright_blue', 'bright_magenta', 'bright_cyan', 'bright_white'] + +// apply_style wraps text in one named style; a name outside style_names is +// refused by the config before it gets here +fn apply_style(name string, s string) string { + return match name { + 'bold' { term.bold(s) } + 'dim' { term.dim(s) } + 'italic' { term.italic(s) } + 'underline' { term.underline(s) } + 'reverse' { term.inverse(s) } + 'black' { term.black(s) } + 'red' { term.red(s) } + 'green' { term.green(s) } + 'yellow' { term.yellow(s) } + 'blue' { term.blue(s) } + 'magenta' { term.magenta(s) } + 'cyan' { term.cyan(s) } + 'white' { term.white(s) } + 'gray' { term.gray(s) } + 'bright_black' { term.bright_black(s) } + 'bright_red' { term.bright_red(s) } + 'bright_green' { term.bright_green(s) } + 'bright_yellow' { term.bright_yellow(s) } + 'bright_blue' { term.bright_blue(s) } + 'bright_magenta' { term.bright_magenta(s) } + 'bright_cyan' { term.bright_cyan(s) } + 'bright_white' { term.bright_white(s) } + else { s } + } +} + +// default_theme is what every role wears unless the config's (color ...) +// form dresses it otherwise: the roles are the keys that form takes +fn default_theme() map[string][]string { + return { + 'heading': ['bold'] + 'title': ['bright_blue'] + 'source': ['bright_blue'] + 'name': ['bold'] + 'version': ['bright_green'] + 'branch': ['bright_blue'] + 'old': ['red'] + 'success': ['bold'] + 'warning': ['bold', 'bright_yellow'] + 'error': ['bold', 'red'] + 'prompt': ['bright_white'] + 'default': ['bold'] + } +} + +__global theme = default_theme() + +// themed wraps text in a role's styles, whether or not the stream is styled +fn themed(role string, s string) string { + mut out := s + for name in theme[role] or { []string{} } { + out = apply_style(name, out) + } + return out +} + +// role styles text bound for stdout as a role of the theme, erole text +// bound for stderr +fn role(name string, s string) string { + return if color_on(false) { themed(name, s) } else { s } +} + +fn erole(name string, s string) string { + return if color_on(true) { themed(name, s) } else { s } +} + +fn heading(s string) string { + return role('heading', s) +} + +fn bold_heading(s string) string { + return role('title', s) +} + +fn source_style(s string) string { + return role('source', s) +} + +fn name_style(s string) string { + return role('name', s) +} + +fn version_style(s string) string { + return role('version', s) +} + +fn branch_style(s string) string { + return role('branch', s) +} + +fn old_style(s string) string { + return role('old', s) +} + +fn success(s string) string { + return role('success', s) +} + +// warning goes to either stream, so it is styled only when both would be +fn warning(s string) string { + prefix := 'warning: ' + return if color_on(false) && color_on(true) { + themed('warning', prefix) + s + } else { + prefix + s + } +} diff --git a/src/style_test.v b/src/style_test.v new file mode 100644 index 0000000..0053364 --- /dev/null +++ b/src/style_test.v @@ -0,0 +1,24 @@ +module main + +import term + +fn test_color_flag() { + old := color_flag + defer { color_flag = old } + + color_flag = 'always' + assert color_on(false) && color_on(true) + assert heading('x') == term.bold('x') + assert erole('old', 'x') == term.red('x') + assert warning('w').contains('\x1b[') + assert q_no_yes() == '[y/' + term.bold('N') + ']' + + color_flag = 'never' + assert !color_on(false) && !color_on(true) + assert heading('x') == 'x' + assert version_style('1.0-1') == '1.0-1' + assert erole('old', 'x') == 'x' + assert warning('w') == 'warning: w' + assert q_yes_no() == '[Y/n]' + assert error_text('e') == 'error: e' +} diff --git a/src/suggest.v b/src/suggest.v new file mode 100644 index 0000000..2613df5 --- /dev/null +++ b/src/suggest.v @@ -0,0 +1,72 @@ +@[has_globals] +module main + +import alpm +import strings + +// suggest_thold is how close a name must be to be suggested. it is the fuzzy +// search measure, a little stricter, since the user is asked about the answer +// (options :suggest) sets it +__global suggest_thold = 0.85 + +// closest_name is the name nearest to query, when it is near enough: a score +// at the threshold counts, and ties fall to the name scanned first, which is +// the order the names came in, the config's db order among them +fn closest_name(query string, names []string) ?string { + q := query.to_lower() + mut best := '' + mut best_score := 0.0 + for name in names { + score := strings.jaro_winkler_similarity(q, name.to_lower()) + if score > best_score { + best = name + best_score = score + } + } + if best_score >= suggest_thold { + return best + } + return none +} + +// did_you_mean handles a query that matched no package. it asks about the +// nearest name, and returns it when the user says yes. otherwise, and when no +// name is near, it is the unknown package error. the question goes through +// the ui, which pauses a live display first +fn did_you_mean(mut ui TransUI, query string, names []string) !string { + name := closest_name(query, names) or { + return error('unknown package: "${query}"') + } + if ui.noyes('did you mean ${name_style(name)}?') { + return name + } + return error('unknown package: "${query}"') +} + +fn pkg_names(pkgs []&alpm.Package) []string { + return pkgs.map(it.get_name()) +} + +// sync_names lists the names of the packages in the sync dbs +fn sync_names(dbs []&alpm.DB) []string { + mut names := []string{} + for db in dbs { + mut pkgcache := db.get_pkgcache() or { continue } + names << pkg_names(pkgcache.pkgs()) + } + return names +} + +// all_names lists the names of the installed packages and of the sync dbs +fn all_names(handle &alpm.Handle, dbs []&alpm.DB) []string { + mut names := local_names(handle) + names << sync_names(dbs) + return names +} + +// local_names lists the names of the installed packages +fn local_names(handle &alpm.Handle) []string { + localdb := handle.get_localdb() or { return []string{} } + mut pkgcache := localdb.get_pkgcache() or { return []string{} } + return pkg_names(pkgcache.pkgs()) +} diff --git a/src/suggest_test.v b/src/suggest_test.v new file mode 100644 index 0000000..c5e8a2d --- /dev/null +++ b/src/suggest_test.v @@ -0,0 +1,20 @@ +module main + +fn test_closest_name() ! { + names := ['thunderbird', 'linux-lts', 'linux-lts-developer-edition'] + // a typo finds its name, the name as it is listed + assert closest_name('fireffox', names)? == 'linux-lts' + assert closest_name('linux-lts', names)? == 'linux-lts' + // case does not count + assert closest_name('FireFox', names)? == 'linux-lts' + // nothing near enough: no suggestion at all + if got := closest_name('xyzzy', names) { + assert false, 'suggested ${got}' + } + if got := closest_name('linux-lts', []string{}) { + assert false, 'suggested ${got} from nothing' + } + // a tie falls to the name met first: the config's db order decides + assert closest_name('zshrc', ['zshra', 'zshrb'])? == 'zshra' + assert closest_name('zshrc', ['zshrb', 'zshra'])? == 'zshrb' +} diff --git a/src/table.v b/src/table.v new file mode 100644 index 0000000..e49db5e --- /dev/null +++ b/src/table.v @@ -0,0 +1,123 @@ +module main + +import encoding.utf8 +import encoding.utf8.east_asian + +// vpac's own table printer, ported from divilib.fmt: rows of cells, every +// column padded to its widest value, two spaces apart, like pkgin's listings. +// the widths are the printed widths, so styled values (bold names, colored +// versions) line up with the color sequences counted as zero +pub struct Cell { + value string +} + +pub struct Row { +pub mut: + cols []Cell +} + +// cell makes one column of a row +fn cell(value string) Cell { + return Cell{ + value: value + } +} + +fn row(cols ...string) Row { + mut out := []Cell{} + for c in cols { + out << cell(c) + } + return Row{ + cols: out + } +} + +// kv is a key/value row, the key in bold +fn kv(key string, value string) Row { + return Row{ + cols: [cell(name_style(key)), cell(value)] + } +} + +// visible_width is the printed width of a string in terminal cells: ANSI +// escape sequences count as nothing, and a wide character (CJK, fullwidth +// forms) as two, by its Unicode East Asian Width. ambiguous ones count as +// one, the way terminals outside East Asian locales draw them. the \x1b form +// and the \e033 form divilib used are both handled +fn visible_width(input string) int { + mut result := 0 + mut i := 0 + for i < input.len { + // the length of the sequence marker, and by extension the whole + // sequence, is searched to the terminating byte in the ASCII range. + // the bytes of a multibyte character are never in that range + mut seq := 0 + if input[i] == 0x1b && i + 1 < input.len && input[i + 1] == `[` { + seq = 2 + } else if input[i] == `\\` && i + 4 < input.len && input[i + 1] == `0` + && input[i + 2] == `3` && input[i + 3] == `3` && input[i + 4] == `[` { + seq = 5 + } + if seq > 0 { + i += seq + for i < input.len && !(input[i] >= 0x40 && input[i] <= 0x7e) { + i++ + } + if i < input.len { + i++ + } + continue + } + if input[i] < 0x80 { + result++ + i++ + continue + } + result += match east_asian.east_asian_width_property_at(input, i) { + .full, .wide { 2 } + else { 1 } + } + // a broken sequence advances by one byte, so the loop always ends + _, n := utf8.decode_rune_at(input, i) + i += n + } + return result +} + +// table_text renders the rows: columns padded to their widest value, the +// first line of every row starting with indent and the columns separated by +// sep. the last column is padded too, and the trailing spaces are trimmed +// straight away +fn table_text(rows []Row, indent string, sep string) string { + if rows.len == 0 { + return '' + } + mut col_count := 0 + for r in rows { + if r.cols.len > col_count { + col_count = r.cols.len + } + } + mut widths := []int{len: col_count, init: 0} + for r in rows { + for i, c in r.cols { + w := visible_width(c.value) + if widths[i] < w { + widths[i] = w + } + } + } + mut out := []string{} + for r in rows { + mut line := indent + for i, c in r.cols { + line += c.value + if i < r.cols.len - 1 { + line += ' '.repeat(widths[i] - visible_width(c.value)) + sep + } + } + out << line + } + return out.join('\n') +} diff --git a/src/target.v b/src/target.v new file mode 100644 index 0000000..0d0f8a4 --- /dev/null +++ b/src/target.v @@ -0,0 +1,178 @@ +module main + +import alpm + +// Target is a target as the command line spells it, parted the way pacman's +// process_target parts one: 'repo/name' names the db to look in, and a bare +// name looks everywhere. the name may be a dependency string ('bash>=5') or +// something a package provides ('sh') +struct Target { + repo string + name string +} + +// parse_target splits the db off a target. a slash that leads is no prefix, +// as in pacman; one that ends the target leaves an empty name, which +// nothing is called +fn parse_target(target string) Target { + slash := target.index('/') or { -1 } + if slash <= 0 { + return Target{ + name: target + } + } + return Target{ + repo: target[..slash] + name: target[slash + 1..] + } +} + +// local_target_name is a target of a mode that reads the installed packages +// alone: pacman's -R and -Q take 'local/' off and nothing else +fn local_target_name(target string) string { + if target.starts_with('local/') && target.len > 6 { + return target[6..] + } + return target +} + +// scope_dbs is the sync dbs a target is looked up in: all of them, or the +// one its prefix names. the prefix is a scope, not decoration: a name the +// config does not carry is pacman's 'database not found', never a search of +// everything with the prefix dropped +fn scope_dbs(dbs []&alpm.DB, repo string) ![]&alpm.DB { + if repo == '' { + return dbs + } + scoped := dbs.filter(it.get_name() == repo) + if scoped.len == 0 { + return error('database not found: ${repo}') + } + return scoped +} + +// has_constraint is whether a target asks for a version: a dependency +// string with one of libalpm's operators +fn has_constraint(name string) bool { + return name.contains_any('<>=') +} + +// find_local_target finds an installed package by name. a version +// constraint is answered by what satisfies it; providers says a bare name +// may be something a package provides too, which the modes that only read +// take and the ones that write do not: 'vpac r sh' must not come to mean +// bash +fn find_local_target(pkgcache &alpm.List, name string, providers bool) ?&alpm.Package { + if p := pkgcache.pkg_find(name) { + return p + } + if providers || has_constraint(name) { + return pkgcache.find_satisfier(name) + } + return none +} + +// find_sync_target finds a target in the dbs given, already scoped: the +// package of that name, or else what libalpm resolves the dependency string +// to, as pacman's process_targname asks alpm_find_dbs_satisfier — a version +// constraint, or a provider, with libalpm's own questions about ignored +// packages and several providers. named says the db was named with the +// target, which makes it one to install from for this lookup whatever its +// usage, as in pacman +fn find_sync_target(handle &alpm.Handle, dbs []&alpm.DB, name string, named bool) ?&alpm.Package { + if name == '' { + return none + } + if p := find_repo_pkg(dbs, name) { + return p + } + mut list := unsafe { &alpm.List(nil) } + for db in dbs { + list = list.add(db) + } + defer { list.free() } + if !named { + return handle.find_dbs_satisfier(list, name) + } + mut restore := map[int]alpm.DBUsage{} + for i, db in dbs { + usage := db.get_usage() or { continue } + if !usage.has(.install) { + db.set_usage(usage | .install) or { continue } + restore[i] = usage + } + } + found := handle.find_dbs_satisfier(list, name) + for i, usage in restore { + dbs[i].set_usage(usage) or { + warn('could not put the usage of ${dbs[i].get_name()} back: ${err.msg()}') + } + } + return found +} + +// GroupMember is one package of a sync group, with the db that carries it +struct GroupMember { + repo string + pkg &alpm.Package +} + +// sync_group_members are the packages of a group across the dbs, in db +// order; a name a later db repeats is the earlier db's, as libalpm's +// alpm_find_group_pkgs has it. found says a db had the group at all +fn sync_group_members(dbs []&alpm.DB, name string) (bool, []GroupMember) { + mut found := false + mut out := []GroupMember{} + mut seen := map[string]bool{} + for db in dbs { + group := db.get_group(name) or { continue } + found = true + for pkg in group.packages.pkgs() { + if seen[pkg.get_name()] { + continue + } + seen[pkg.get_name()] = true + out << GroupMember{ + repo: db.get_name() + pkg: pkg + } + } + } + return found, out +} + +// select_members asks which members of a group go in, pacman's +// multiselect: the members are listed numbered, on stderr with the question +// they lead into (a frontend gets them as a listing), and the answer picks +// among them. a --print preview lists and asks nothing: every member +fn select_members(mut ui TransUI, group string, members []GroupMember, ask bool) []GroupMember { + if !ask || members.len == 0 { + return members + } + ui.pause() + if ipc_on() { + mut listing := Listing{ + fields: ['source', 'name', 'version'] + } + for m in members { + listing.add_member(m.pkg, m.repo, group) + } + listing.print() + } else { + count := if members.len == 1 { '1 member' } else { '${members.len} members' } + eprintln(erole('heading', '${count} in group ${group}:')) + mut rows := []Row{} + for i, m in members { + rows << row('${i + 1})', m.repo, m.pkg.get_name(), m.pkg.get_version()) + } + eprintln(table_text(rows, ' ', ' ')) + } + picked := ui.pick('enter a selection', members.len) + mut out := []GroupMember{} + for i, m in members { + if picked[i] { + out << m + } + } + return out +} diff --git a/src/testdb/testdb.v b/src/testdb/testdb.v new file mode 100644 index 0000000..04223d9 --- /dev/null +++ b/src/testdb/testdb.v @@ -0,0 +1,60 @@ +module testdb + +import os + +// testdb writes libalpm local dbs for the tests: every test file is a +// binary of its own, so a writer they share lives in a module they import +// and vpac itself never does — it is in no build of the program. + +// Pkg is one installed package of a written db: what its desc says, and the +// entries of its file list (directories with their trailing slash, as +// libalpm keeps them) +pub struct Pkg { +pub: + name string + version string = '1.0-1' + reason int // 0 explicit, 1 a dependency + depends []string + optdepends []string + provides []string + conflicts []string + groups []string + files []string + // no_files leaves the file list out altogether, a broken entry + no_files bool +} + +// desc is the text of a package's desc file: the sections that have +// something to say, in libalpm's spelling +pub fn (p Pkg) desc() string { + mut out := '%NAME%\n${p.name}\n\n%VERSION%\n${p.version}\n\n%ARCH%\nany\n\n%REASON%\n${p.reason}\n\n' + for key, items in { + 'DEPENDS': p.depends + 'OPTDEPENDS': p.optdepends + 'PROVIDES': p.provides + 'CONFLICTS': p.conflicts + 'GROUPS': p.groups + } { + if items.len > 0 { + out += '%${key}%\n${items.join('\n')}\n\n' + } + } + return out +} + +// write_local lays out a local db (version 9) under dbpath: the version +// file, and one dir per package, named name-version, with its desc and its +// file list. it adds to a db that is there; no packages write an empty one +pub fn write_local(dbpath string, pkgs []Pkg) ! { + local := os.join_path(dbpath, 'local') + os.mkdir_all(local)! + os.write_file(os.join_path(local, 'ALPM_DB_VERSION'), '9\n')! + for p in pkgs { + dir := os.join_path(local, '${p.name}-${p.version}') + os.mkdir_all(dir)! + os.write_file(os.join_path(dir, 'desc'), p.desc())! + if !p.no_files { + os.write_file(os.join_path(dir, 'files'), '%FILES%\n${p.files.join('\n')}\n\n')! + } + } +} diff --git a/src/testdb/testdb_test.v b/src/testdb/testdb_test.v new file mode 100644 index 0000000..6e4f75f --- /dev/null +++ b/src/testdb/testdb_test.v @@ -0,0 +1,56 @@ +module testdb + +import os + +fn test_desc_says_only_what_there_is() { + bare := Pkg{ + name: 'bare' + } + assert bare.desc() == '%NAME%\nbare\n\n%VERSION%\n1.0-1\n\n%ARCH%\nany\n\n%REASON%\n0\n\n' + full := Pkg{ + name: 'full' + version: '2:3.0-4' + reason: 1 + depends: ['a>=1', 'b'] + optdepends: ['c: for more'] + provides: ['virt=2'] + conflicts: ['rival'] + groups: ['g1', 'g2'] + }.desc() + assert full.contains('%VERSION%\n2:3.0-4\n\n') && full.contains('%REASON%\n1\n\n') + assert full.contains('%DEPENDS%\na>=1\nb\n\n') + assert full.contains('%OPTDEPENDS%\nc: for more\n\n') + assert full.contains('%PROVIDES%\nvirt=2\n\n') && full.contains('%CONFLICTS%\nrival\n\n') + assert full.contains('%GROUPS%\ng1\ng2\n\n') + // every section ends in its blank line, the last one too + assert full.ends_with('\n\n') +} + +fn test_write_local_edges() ! { + db := os.join_path(os.vtmp_dir(), 'vpac_testdb_${os.getpid()}') + defer { os.rmdir_all(db) or {} } + // no packages: an empty db, which is a version file and nothing else + write_local(db, [])! + assert os.ls(os.join_path(db, 'local'))! == ['ALPM_DB_VERSION'] + assert os.read_file(os.join_path(db, 'local', 'ALPM_DB_VERSION'))! == '9\n' + write_local(db, [Pkg{ + name: 'a' + files: ['usr/', 'usr/bin/', 'usr/bin/a'] + }, Pkg{ + name: 'broken' + version: '2-1' + no_files: true + }])! + assert os.read_file(os.join_path(db, 'local', 'a-1.0-1', 'files'))! == '%FILES%\nusr/\nusr/bin/\nusr/bin/a\n\n' + assert os.exists(os.join_path(db, 'local', 'broken-2-1', 'desc')) + assert !os.exists(os.join_path(db, 'local', 'broken-2-1', 'files')) + // a second write adds to the db and leaves what was there + write_local(db, [Pkg{ + name: 'later' + }])! + mut names := os.ls(os.join_path(db, 'local'))! + names.sort() + assert names == ['ALPM_DB_VERSION', 'a-1.0-1', 'broken-2-1', 'later-1.0-1'] + // a package with no files has a file list, empty + assert os.read_file(os.join_path(db, 'local', 'later-1.0-1', 'files'))! == '%FILES%\n\n\n' +} diff --git a/src/trans.v b/src/trans.v new file mode 100644 index 0000000..44cd1c3 --- /dev/null +++ b/src/trans.v @@ -0,0 +1,324 @@ +@[has_globals] +module main + +import alpm +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 libalpm takes the db lock +// until after it let go of it. the handler hands it to alpm_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) alpm.TransFlag { + n := level + if nodeps { 1 } else { 0 } + return if n >= 2 { + alpm.TransFlag.no_deps + } else if n == 1 { + alpm.TransFlag.no_depversion + } else { + alpm.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 &alpm.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 := alpm.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 &alpm.Handle, flags alpm.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 &alpm.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) alpm.TransFlag { + return if print_only { + alpm.TransFlag.nolock | .no_conflicts + } else { + alpm.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 &alpm.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 alpm.Errno, problems []alpm.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 &alpm.Handle) ! { + problems, failure := handle.trans_prepare_problems() + if err := failure { + if problems.len == 0 { + return err + } + // the errno is still the prepare's: nothing called libalpm since + return error(prepare_problem_lines(handle.errno(), problems).join('\n')) + } +} + +// runs the commit phase of a prepared transaction. the transaction must +// already have been begun and prepared. +fn trans_commit(handle &alpm.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. alpm_unlock decides +// whether it holds one, from libalpm'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 { + C.alpm_unlock(unsafe { &alpm.Handle(voidptr(h)) }) + } + 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 &alpm.Handle, pkgs []&alpm.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 &alpm.Handle, pkgs []&alpm.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?') +} diff --git a/src/trans_test.v b/src/trans_test.v new file mode 100644 index 0000000..7b76edf --- /dev/null +++ b/src/trans_test.v @@ -0,0 +1,283 @@ +module main + +import alpm +import json2 +import os + +fn test_split_list() { + // repeatable and comma separated, as pacman reads --ignore and friends + assert split_list([]) == [] + assert split_list(['a']) == ['a'] + assert split_list(['a,b', 'c']) == ['a', 'b', 'c'] + assert split_list([' a , b ', ',,', '']) == ['a', 'b'] + assert split_list(['/usr/*,/etc/*']) == ['/usr/*', '/etc/*'] +} + +fn test_dep_check_flag() { + // pacman's -d skips the version checks, -dd every dependency check; + // --nodeps is one -d + assert dep_check_flag(false, 0) == alpm.trans_flag_0 + assert dep_check_flag(true, 0) == alpm.TransFlag.no_depversion + assert dep_check_flag(false, 1) == alpm.TransFlag.no_depversion + assert dep_check_flag(false, 2) == alpm.TransFlag.no_deps + assert dep_check_flag(true, 1) == alpm.TransFlag.no_deps + assert dep_check_flag(false, 3) == alpm.TransFlag.no_deps +} + +// trans_sandbox opens a handle on an empty temp db, and points the ipc +// channel at a file, so what the lifecycle says can be read back +fn trans_sandbox(name string) !(string, &alpm.Handle) { + tmp := os.join_path(os.vtmp_dir(), 'vpac_test_trans_${name}_${os.getpid()}') + os.rmdir_all(tmp) or {} + os.mkdir_all(os.join_path(tmp, 'root'))! + os.mkdir_all(os.join_path(tmp, 'db', 'local'))! + os.write_file(os.join_path(tmp, 'db', 'local', 'ALPM_DB_VERSION'), '9\n')! + handle := alpm.initialize(os.join_path(tmp, 'root') + '/', os.join_path(tmp, 'db') + '/')! + return tmp, handle +} + +// said runs f with --ui ipc on and the channel in a file, and returns the +// texts of the messages f sent +fn said(tmp string, f fn ()) ![]string { + path := os.join_path(tmp, 'channel') + mut file := os.create(path)! + saved_kind, saved_fd := ui_kind, ipc_fd + ui_kind, ipc_fd = 'ipc', file.fd + f() + ui_kind, ipc_fd = saved_kind, saved_fd + file.close() + mut out := []string{} + for line in os.read_lines(path)! { + out << json2.decode[json2.Any](line)!.as_map()['text'] or { json2.Any('') }.str() + } + return out +} + +fn test_trans_cleanup_releases_once() ! { + tmp, handle := trans_sandbox('once')! + defer { os.rmdir_all(tmp) or {} } + defer { handle.release() or {} } + lpath := os.join_path(tmp, 'db', 'db.lck') + trans_begin(handle, alpm.trans_flag_0)! + assert os.exists(lpath) + msgs := said(tmp, fn [handle] () { + trans_cleanup(handle) + // a second cleanup — a defer after an explicit one — is a no-op, + // not a release libalpm would refuse + trans_cleanup(handle) + })! + assert msgs.len == 0 + assert !os.exists(lpath) + mut open := txn_open + assert open.load() == 0 +} + +fn test_trans_cleanup_failure_is_said_and_counts_as_closed() ! { + tmp, handle := trans_sandbox('failure')! + defer { os.rmdir_all(tmp) or {} } + defer { handle.release() or {} } + // the process believes in a transaction libalpm does not have: the + // release fails, the way it would after libalpm dropped it + mut open := txn_open + open.store(txn_locked) + msgs := said(tmp, fn [handle] () { + trans_cleanup(handle) + trans_cleanup(handle) + })! + // said once, and closed: the second cleanup did not try again + assert msgs.len == 1 + assert msgs[0].starts_with('failed to release the transaction: ') + assert open.load() == 0 +} + +fn test_trans_commit_releases() ! { + // a committed transaction lets go of the lock through the commit's own + // cleanup, and leaves the deferred one nothing to do. an empty one would + // not do: libalpm's prepare returns early on nothing and its commit then + // refuses as not prepared, so a package is really removed + tmp, handle := trans_sandbox('commit')! + defer { os.rmdir_all(tmp) or {} } + defer { handle.release() or {} } + entry := os.join_path(tmp, 'db', 'local', 'gone-1.0-1') + os.mkdir_all(entry)! + os.write_file(os.join_path(entry, 'desc'), '%NAME%\ngone\n\n%VERSION%\n1.0-1\n\n')! + os.write_file(os.join_path(entry, 'files'), '%FILES%\n\n')! + trans_begin(handle, alpm.trans_flag_0)! + handle.remove_pkg(handle.find_local_pkg('gone') or { return error('gone is not installed') })! + trans_prepare_checked(handle)! + trans_commit(handle)! + assert !os.exists(os.join_path(tmp, 'db', 'db.lck')) + assert !os.exists(entry) + mut open := txn_open + assert open.load() == 0 + msgs := said(tmp, fn [handle] () { + trans_cleanup(handle) + })! + assert msgs.len == 0 +} + +fn test_trans_options_of_install_and_upgrade() ! { + // the same four flags, read the same way from either command line + want := TransOptions{ + overwrite: ['/usr/*'] + ignore: ['a,b'] + ignoregroup: ['g'] + assume_installed: ['sh=5'] + } + assert trans_options(ConfigInstall{ + overwrite: ['/usr/*'] + ignore: ['a,b'] + ignoregroup: ['g'] + assume_installed: ['sh=5'] + }) == want + assert trans_options(ConfigUpgrade{ + overwrite: ['/usr/*'] + ignore: ['a,b'] + ignoregroup: ['g'] + assume_installed: ['sh=5'] + }) == want + // and they reach the handle a transaction runs on, lists split + tmp, handle := trans_sandbox('options')! + defer { os.rmdir_all(tmp) or {} } + defer { handle.release() or {} } + want.apply(handle)! + mut ignored := handle.option_get_ignore_pkgs() + assert ignored.strs() == ['a', 'b'] + mut overwrite := handle.option_get_overwrite_files() + assert overwrite.strs() == ['/usr/*'] + // a spec that names no package is said, rather than assuming nothing + for spec in ['=', '=1.0', '>=2'] { + TransOptions{ + assume_installed: [spec] + }.apply(handle) or { + assert err.msg().contains('names no package'), err.msg() + continue + } + assert false, '--assume-installed ${spec} was taken' + } +} + +// killed_child forks, lets the child take the db lock of the sandbox the +// way take describes, and kills it with SIGTERM through the installed +// handler; it returns the child's exit status. the child runs V code — the +// handlers' installation and take, a trans_begin in the tests here — on its +// copy of the test's memory, and only ever leaves through _exit (the +// handler's, or the 98 and 99 of a failure), so no defer, no atexit and no +// test-runner report of the parent's runs a second time in it +fn killed_child(handle &alpm.Handle, take fn (&alpm.Handle)) int { + pid := C.fork() + if pid == 0 { + install_interrupt_handlers() + take(handle) + C.kill(C.getpid(), 15) + // the handler exits; reaching here is the failure + C._exit(99) + } + mut status := 0 + C.waitpid(pid, &status, 0) + return (status >> 8) & 0xff +} + +fn test_interrupt_lets_go_of_the_lock() ! { + tmp, handle := trans_sandbox('interrupt')! + defer { os.rmdir_all(tmp) or {} } + defer { handle.release() or {} } + lpath := os.join_path(tmp, 'db', 'db.lck') + // a transaction is open, the lock held: the killed run removes it + status := killed_child(handle, fn (h &alpm.Handle) { + trans_begin(h, alpm.trans_flag_0) or { C._exit(98) } + }) + assert status == 128 + 15 + assert !os.exists(lpath) +} + +fn test_interrupt_right_after_the_lock_is_taken() ! { + tmp, handle := trans_sandbox('interrupt_window')! + defer { os.rmdir_all(tmp) or {} } + defer { handle.release() or {} } + lpath := os.join_path(tmp, 'db', 'db.lck') + // the signal lands between libalpm taking the lock and vpac recording + // the transaction: the handle was published before, so the lock goes + status := killed_child(handle, fn (h &alpm.Handle) { + publish_for_interrupt(h) + h.trans_init(alpm.trans_flag_0) or { C._exit(98) } + }) + assert status == 128 + 15 + assert !os.exists(lpath) +} + +fn test_interrupt_leaves_a_lock_it_does_not_hold() ! { + tmp, handle := trans_sandbox('interrupt_other')! + defer { os.rmdir_all(tmp) or {} } + defer { handle.release() or {} } + lpath := os.join_path(tmp, 'db', 'db.lck') + // another process holds the lock, and this run only previews (--print + // takes none): the killed run leaves the other's lock alone + os.write_file(lpath, '')! + status := killed_child(handle, fn (h &alpm.Handle) { + trans_begin(h, print_flags(true)) or { C._exit(98) } + }) + assert status == 128 + 15 + assert os.exists(lpath) +} + +fn test_trans_publishes_its_handle_while_open() ! { + tmp, handle := trans_sandbox('publish')! + defer { os.rmdir_all(tmp) or {} } + defer { handle.release() or {} } + mut published := interrupt_handle + assert published.load() == 0 + trans_begin(handle, alpm.trans_flag_0)! + assert published.load() == u64(voidptr(handle)) + trans_cleanup(handle) + assert published.load() == 0 + // a begin that fails publishes nothing past its failure: the lock is + // someone else's here + os.write_file(os.join_path(tmp, 'db', 'db.lck'), '')! + if _ := trans_begin(handle, alpm.trans_flag_0) { + assert false, 'a held lock was taken' + } + assert published.load() == 0 +} + +// a failed prepare is worded by its kind, pacman's three shapes and +// libalpm's own text for the rest +fn test_prepare_problem_lines() { + dep := prepare_problem_lines(.unsatisfied_deps, [ + alpm.DepProblem{ + target: 'user' + depend: 'lib<2.0' + causing: 'lib' + }, + alpm.DepProblem{ + target: 'app' + depend: 'gone' + }, + ]) + assert dep == ['could not satisfy dependencies:', + " lib breaks dependency 'lib<2.0' required by user", + " unable to satisfy dependency 'gone' required by app"] + conflict := prepare_problem_lines(.conflicting_deps, [ + alpm.DepProblem{ + target: 'p1' + depend: 'p2' + causing: 'p2' + }, + alpm.DepProblem{ + target: 'p1' + depend: 'virt<2' + causing: 'p3' + }, + ]) + assert conflict == ['unresolvable package conflicts:', ' p1 and p2 are in conflict', + ' p1 and p3 are in conflict (virt<2)'] + wrong_arch := prepare_problem_lines(.pkg_invalid_arch, [alpm.DepProblem{ + target: 'foo-1.0-1-riscv64' + }]) + assert wrong_arch.len == 2 + assert wrong_arch[1] == ' package foo-1.0-1-riscv64 does not have a valid architecture' + other := prepare_problem_lines(.trans_dup_target, [alpm.DepProblem{ + target: 'foo' + }]) + assert other.len == 2 && other[1] == ' foo' +} diff --git a/src/ui.v b/src/ui.v new file mode 100644 index 0000000..6bc7a33 --- /dev/null +++ b/src/ui.v @@ -0,0 +1,937 @@ +@[has_globals] +module main + +import alpm +import sync +import time +import x.progress + +#include "@VMODROOT/src/alpm_log.h" + +fn C.vpac_set_alpm_log(handle &alpm.Handle, ctx voidptr) int + +// ALPM_LOG_ERROR: the one level the log callback tells apart, the other one +// it passes being a warning (alpm_log.h) +const alpm_log_error = 1 + +// ProgressCfg is how the live display draws, the config's (progress ...) and +// (spinner ...) forms. style is the bar graphic, 'classic' or 'block', and +// parts holds the pieces of it the config respelled (start, end, fill, +// head, empty), the style's own standing for the rest. frames empty is the +// display's own spinner +struct ProgressCfg { +mut: + style string = 'classic' + parts map[string]string + length int = 30 + percent bool = true + eta bool = true + elapsed bool + rate bool = true + delay int = 50 + frames []string + interval int = 80 + done string = '✓' + timed bool +} + +__global cfg_progress = ProgressCfg{} + +// spinner_sets are the frame sets (spinner :frames) knows by name +const spinner_sets = ['dots', 'braille', 'line', 'arrows', 'circle', 'quarters', 'grow', 'bounce', + 'pulse', 'ellipsis', 'earth', 'moon'] + +// spinner_frames_named is a frame set by its name, none for a name outside +// spinner_sets +fn spinner_frames_named(name string) ?[]string { + return match name { + 'dots' { progress.spinner_dots() } + 'braille' { progress.spinner_braille() } + 'line' { progress.spinner_line() } + 'arrows' { progress.spinner_arrows() } + 'circle' { progress.spinner_circle() } + 'quarters' { progress.spinner_quarters() } + 'grow' { progress.spinner_grow() } + 'bounce' { progress.spinner_bounce() } + 'pulse' { progress.spinner_pulse() } + 'ellipsis' { progress.spinner_ellipsis() } + 'earth' { progress.spinner_earth() } + 'moon' { progress.spinner_moon() } + else { none } + } +} + +// part_rune is one cell of a bar graphic as the config spelled it: the +// first rune, or fallback for a part it left alone or emptied +fn part_rune(name string, fallback rune) rune { + text := cfg_progress.parts[name] or { return fallback } + runes := text.runes() + return if runes.len > 0 { runes[0] } else { fallback } +} + +// bar_style is the bar graphic the config draws +fn bar_style() progress.Style { + if cfg_progress.style == 'block' { + d := progress.BlockStyle{} + return progress.BlockStyle{ + start: cfg_progress.parts['start'] or { d.start } + end: cfg_progress.parts['end'] or { d.end } + fill: part_rune('fill', d.fill) + empty: part_rune('empty', d.empty) + } + } + d := progress.ClassicStyle{} + return progress.ClassicStyle{ + start: cfg_progress.parts['start'] or { d.start } + end: cfg_progress.parts['end'] or { d.end } + fill: part_rune('fill', d.fill) + // an emptied head is no head: the bar ends in its fill + head: if 'head' in cfg_progress.parts { part_rune('head', 0) } else { d.head } + empty: part_rune('empty', d.empty) + } +} + +// bar_opts dresses a bar the config's way: what a caller asks of its bar +// stays, and the rate is shown only where the caller has one to show +fn bar_opts(o progress.BarOptions) progress.BarOptions { + return progress.BarOptions{ + ...o + style: bar_style() + length: cfg_progress.length + show_percent: cfg_progress.percent + show_left: cfg_progress.eta + show_elapsed: cfg_progress.elapsed + show_rate: o.show_rate && cfg_progress.rate + } +} + +// spinner_opts dresses a spinner the config's way +fn spinner_opts(o progress.SpinnerOptions) progress.SpinnerOptions { + return progress.SpinnerOptions{ + ...o + frames: if cfg_progress.frames.len > 0 { + cfg_progress.frames.clone() + } else { + o.frames.clone() + } + interval: cfg_progress.interval * time.millisecond + done_frame: cfg_progress.done + show_elapsed: cfg_progress.timed + } +} + +// TransUI is a command's user interface: the shared progress display (one +// MultiBar that holds spinners for the command phases, download bars fed by +// alpm's dlcb and transaction phase bars fed by alpm's progresscb) and the +// prompter every question goes through, libalpm's own included. It is passed +// to alpm as the callback context. under --ui ipc there is no MultiBar: the +// same calls send events (Phase, Meter, the callbacks) +// every ui-bearing function spells its ui `mut ui TransUI`, the way it does +// for the _locked helpers: TransUI is @[heap], and a mut value parameter of +// one writes through, so the ui handed to a mode and the one its helpers +// reach are the same struct. only init_handle takes the reference spelled +// out, since it hands the pointer itself to libalpm +@[heap] +struct TransUI { +mut: + mb &progress.MultiBar = unsafe { nil } + // mu guards the fields below against libalpm's download callbacks: with + // parallel downloads on, dlcb arrives on several threads at once, and + // progresscb may join it. every method here takes mu before it touches + // state other callbacks or threads can see, and the _locked helpers + // below it are reached only with the mutex held. the bars and the + // multibar are drawn thread-safely by x.progress itself + mu &sync.Mutex = sync.new_mutex() + dbars map[string]&progress.Bar + pbar &progress.Bar = unsafe { nil } + pkey int + // dpad is the width every download bar reserves for its name, so all + // bars start at the same X coordinate; grows to the longest name seen + dpad int + // prompt asks the user; its noconfirm is --noconfirm, which every + // command that asks anything passes to new_trans_ui + prompt Prompter + // print_only (--print) answers every question silently, as pacman's + // --print does, so the listing on stdout stays clean + print_only bool + // download_only (install -w) fetches an ignored package without asking + download_only bool + // walking is set while install looks dependencies up for itself: the + // questions libalpm raises then are answered as --print answers them + walking bool + // dlast is what each download last reported under --ui ipc, so an event + // goes out as the percent moves or the time passes (download_due), not + // for every chunk; plast is the last progress event, which libalpm may + // send twice + dlast map[string]DownloadSent + plast ProgressEvent +} + +// TransUIOptions are what a command tells its TransUI +@[params] +struct TransUIOptions { + // noconfirm is --noconfirm: every prompt takes its default unasked + noconfirm bool +} + +// new_trans_ui makes a command's TransUI, with the prompter of the frontend +// --ui chose +fn new_trans_ui(o TransUIOptions) &TransUI { + return &TransUI{ + dbars: {} + prompt: if ipc_on() { + Prompter(IpcPrompter{ + noconfirm: o.noconfirm + }) + } else { + Prompter(TermPrompter{ + noconfirm: o.noconfirm + }) + } + } +} + +// group returns the live MultiBar, starting a new one if the previous one was +// paused for a prompt. the alpm callbacks reach the display through this +// struct, so they always draw on the current MultiBar +fn (mut ui TransUI) group() &progress.MultiBar { + ui.mu.lock() + defer { ui.mu.unlock() } + return ui.group_locked() +} + +// group_locked is group, with the ui's mutex already held: download bars and +// the lazy creation of the MultiBar must not race +fn (mut ui TransUI) group_locked() &progress.MultiBar { + if ui.mb == unsafe { nil } { + // the cursor stays visible: confirmation prompts are asked on a + // running display otherwise, and a hidden cursor makes them look dead + ui.mb = progress.MultiBar.new( + hide_cursor: false + delay: cfg_progress.delay * time.millisecond + ) + } + return ui.mb +} + +// Phase is a step a command shows while it works: a spinner on a terminal, +// phase events under --ui ipc +@[heap] +struct Phase { +mut: + spinner &progress.Spinner = unsafe { nil } + text string + started bool + done bool +} + +fn (mut ui TransUI) spinner(opts progress.SpinnerOptions) &Phase { + if ipc_on() { + return &Phase{ + text: opts.text + } + } + return &Phase{ + spinner: ui.group().add_spinner(spinner_opts(opts)) + text: opts.text + } +} + +fn (mut p Phase) start() { + if p.spinner != unsafe { nil } { + p.spinner.start() + return + } + p.started = true + emit(PhaseEvent{ + text: p.text + state: 'start' + }) +} + +// set_text renames the step; a running one reports the new name as a start +fn (mut p Phase) set_text(text string) { + p.text = text + if p.spinner != unsafe { nil } { + p.spinner.set_text(text) + return + } + if p.started && !p.done { + emit(PhaseEvent{ + text: text + state: 'start' + }) + } +} + +fn (p &Phase) is_done() bool { + if p.spinner != unsafe { nil } { + return p.spinner.is_done() + } + return p.done +} + +fn (mut p Phase) finish() { + if p.spinner != unsafe { nil } { + p.spinner.finish() + return + } + if p.done { + return + } + p.done = true + if p.started { + emit(PhaseEvent{ + text: p.text + state: 'done' + }) + } +} + +// Meter is a counted step: a bar on a terminal, progress events under +// --ui ipc, one each time the percent moves +@[heap] +struct Meter { +mut: + bar &progress.Bar = unsafe { nil } + text string + total i64 + count i64 + percent int = -1 +} + +fn (mut ui TransUI) meter(total i64, text string) &Meter { + if ipc_on() { + return &Meter{ + text: text + total: total + } + } + return &Meter{ + bar: ui.group().add_bar(total, bar_opts(text: text + ' ')) + text: text + total: total + } +} + +fn (mut m Meter) start() { + if m.bar != unsafe { nil } { + m.bar.start() + return + } + m.add(0) +} + +fn (mut m Meter) add(n i64) { + if m.bar != unsafe { nil } { + m.bar.add(n) + return + } + m.count += n + pct := if m.total > 0 { int(m.count * 100 / m.total) } else { 100 } + if pct != m.percent { + m.percent = pct + emit(ProgressEvent{ + op: m.text + percent: pct + current: int(m.count) + total: int(m.total) + }) + } +} + +// pause stops the live display before a confirmation prompt. the render +// thread must be gone before the prompt is written, otherwise its redraw can +// erase the prompt and leave the program waiting on a question nobody sees +fn (mut ui TransUI) pause() { + ui.mu.lock() + defer { ui.mu.unlock() } + if ui.mb != unsafe { nil } { + ui.mb.stop() + ui.mb = unsafe { nil } + } + ui.pbar = unsafe { nil } + ui.dbars = map[string]&progress.Bar{} + ui.dpad = 0 + ui.dlast = map[string]DownloadSent{} + ui.plast = ProgressEvent{} +} + +// stop ends the live display, the run over. reached with the ui's mutex, +// like every touch of the display's fields: a download callback creating a +// bar on another thread must not race the stop that tears it down +fn (mut ui TransUI) stop() { + ui.mu.lock() + defer { ui.mu.unlock() } + if ui.mb != unsafe { nil } { + ui.mb.stop() + } +} + +// sync asks the live display to paint right away: the finished frame of a +// spinner that just stopped is otherwise drawn by the next tick, which lands +// behind the result line the caller is about to print +fn (mut ui TransUI) sync() { + if ui.mb != unsafe { nil } { + ui.mb.flush() + } +} + +// stop_spinner finishes a spinner that is still running, so a command that +// fails or asks a question does not leave it turning on screen +fn stop_spinner(mut s Phase) { + if !s.is_done() { + s.finish() + } +} + +// end_frame is the stop a spinner window needs before plain printlns: the +// finished frame goes out right away, and the render thread is stopped. +// stopping the spinner alone leaves the thread drawing, and a further tick +// lands right inside the lines that follow (the report of verify showed it). +// the writes that are safe beside a live frame are the group's own println +// and the prompts, which reach it through ui.pause +fn end_frame(mut ui TransUI, mut s Phase) { + stop_spinner(mut s) + ui.sync() + ui.pause() +} + +// print_done is the transaction result line, e.g. "removed: ". +// every command that commits a transaction reports through it +fn print_done(mut ui TransUI, label string, names []string) { + if ipc_on() { + emit(DoneEvent{ + action: label.trim_right(':') + packages: names + }) + return + } + ui.sync() + ui.group().println('${success(label)} ${names.join(' ')}') +} + +// say is a result line printed beside the live display, a message event +// under --ui ipc +fn (mut ui TransUI) say(text string) { + if ipc_on() { + emit(MessageEvent{ + text: text + }) + return + } + ui.group().println(text) +} + +// warn is a warning printed beside the live display, as say prints a result +// line: above the bars a download may still draw, never through them. under +// --ui ipc it is the warning message event warn() sends +fn (mut ui TransUI) warn(text string) { + if ipc_on() { + warn(text) + return + } + ui.group().println(warning(text)) +} + +// show_packages lists packages under a heading, the way a transaction shows +// the ones it removes or skips: name and version +fn (mut ui TransUI) show_packages(title string, pkgs []&alpm.Package) { + if ipc_on() { + emit(PackagesEvent{ + title: title.trim_right(':') + packages: pkgs.map(TransPkg{ + name: it.get_name() + version: it.get_version() + }) + }) + return + } + println(heading(title)) + println(table_text(pkgs.map(row(name_style(it.get_name()), version_style(it.get_version()))), + ' ', ' ')) +} + +fn safe_vstring(p &u8) string { + return if p == unsafe { nil } { '' } else { unsafe { p.vstring() } } +} + +// download_text pads a download bar's text to the shared name column: every +// bar reserves the same cells for its name (as wide as the longest name seen +// so far, plus the trailing space), so all bars sit at the same X coordinate +// whatever their filenames' lengths. when a longer name arrives later, the +// column widens and the running bars are re-padded in place (set_text is +// thread-safe); finished bars are left alone, their lines are already printed +// reached only with the ui's mutex held, from download_bar +fn (mut ui TransUI) download_text_locked(name string) string { + if name.len + 1 > ui.dpad { + ui.dpad = name.len + 1 + } + for key, mut bar in ui.dbars { + if bar.is_done() { + continue + } + bar.set_text(key + ' '.repeat(ui.dpad - key.len)) + } + return name + ' '.repeat(ui.dpad - name.len) +} + +// download_bar returns the display bar of one download, created on the file's +// first event, when its size is known; the shown group starts with it +// libalpm runs its dlcb on the parallel download threads, so the shared +// state is reached with the ui's mutex, and never the drawing itself +fn (mut ui TransUI) download_bar(name string, total i64, on_end string, show_rate bool) &progress.Bar { + ui.mu.lock() + defer { ui.mu.unlock() } + bar := ui.dbars[name] or { + mb := ui.group_locked() + b := mb.add_bar(total, bar_opts( + text: ui.download_text_locked(name) + show_rate: show_rate + rate_unit: progress.RateUnit.bytes_iec() + on_end: on_end + )) + ui.dbars[name] = b + mb.start() + b + } + return bar +} + +fn cb_download(ctx voidptr, filename &u8, event alpm.DownloadEventType, data voidptr) { + mut ui := &TransUI(ctx) + name := safe_vstring(filename) + if ipc_on() { + ipc_download(mut ui, name, event, data) + return + } + match event { + .init { + // the bar is created at the first progress event, when the + // download size is known + } + .progress { + p := unsafe { &alpm.DownloadEventProgress(data) } + // libalpm runs this callback on its parallel download threads: + // the shared display state is reached through the ui's mutex, the + // drawing itself is x.progress's to keep thread-safe + bar := ui.download_bar(name, p.total, '', true) + bar.set(p.downloaded) + } + .retry { + // libalpm moves on to the next mirror: a download that starts over + // starts its bar over, as pacman's dload_retry_event does, and one + // that resumes keeps its place + r := unsafe { &alpm.DownloadEventRetry(data) } + if r.resume == 0 { + ui.restart_download_bar(name) + } + } + .completed { + c := unsafe { &alpm.DownloadEventCompleted(data) } + // libalpm's result: 1 means the local copy met the time condition + // and nothing was fetched, 0 a finished download, -1 an error. a + // download can finish before its first progress event, so the bar + // may not exist yet; only result 1 is labelled up to date + on_end := if c.result == 1 { '${name} is up to date' } else { '' } + bar := ui.download_bar(name, c.total, on_end, false) + bar.set(c.total) + } + } +} + +// restart_download_bar puts a download's bar back at nothing, when libalpm +// starts the file over from another mirror. a bar not drawn yet has nothing +// to restart +fn (mut ui TransUI) restart_download_bar(name string) { + ui.mu.lock() + defer { ui.mu.unlock() } + mut bar := ui.dbars[name] or { return } + bar.set(0) +} + +// DownloadSent is what a download last reported under --ui ipc: its percent, +// and when, in the monotonic clock's nanoseconds +struct DownloadSent { + percent int + at i64 +} + +// download_beat is the longest a download in progress goes without an +// event: a large file on a slow line moves a percent in minutes, and a +// frontend's rate would stand still that long +const download_beat = i64(250 * time.millisecond) + +// download_due tells whether a progress report goes out: the first one of a +// download, then each time the percent moves or a beat has passed +fn download_due(last ?DownloadSent, percent int, now i64) bool { + sent := last or { return true } + return percent != sent.percent || now - sent.at >= download_beat +} + +// ipc_download reports a download as events: as its percent moves or a beat +// passes, once more when libalpm retries it from the next mirror, and once +// when it is done. the dlcb arrives on libalpm's parallel download threads, +// so the dedupe table is reached with the ui's mutex, and the event goes out +// once the lock is gone +fn ipc_download(mut ui TransUI, name string, event alpm.DownloadEventType, data voidptr) { + match event { + .progress { + p := unsafe { &alpm.DownloadEventProgress(data) } + pct := if p.total > 0 { int(p.downloaded * 100 / p.total) } else { 0 } + now := time.sys_mono_now() + ui.mu.lock() + if !download_due(ui.dlast[name] or { none }, pct, i64(now)) { + ui.mu.unlock() + return + } + ui.dlast[name] = DownloadSent{ + percent: pct + at: i64(now) + } + ui.mu.unlock() + emit(DownloadEvent{ + file: name + downloaded: p.downloaded + total: p.total + }) + } + .retry { + r := unsafe { &alpm.DownloadEventRetry(data) } + // what was reported is history: the next progress goes out + ui.mu.lock() + ui.dlast.delete(name) + ui.mu.unlock() + emit(DownloadEvent{ + file: name + retry: true + resume: r.resume != 0 + }) + } + .completed { + c := unsafe { &alpm.DownloadEventCompleted(data) } + emit(DownloadEvent{ + file: name + downloaded: c.total + total: c.total + done: true + result: int(c.result) + }) + } + else {} + } +} + +fn progress_verb(kind alpm.Progress) string { + return match kind { + .add_start { 'installing' } + .upgrade_start { 'upgrading' } + .downgrade_start { 'downgrading' } + .reinstall_start { 'reinstalling' } + .remove_start { 'removing' } + .conflicts_start { 'checking for file conflicts' } + .diskspace_start { 'checking available disk space' } + .integrity_start { 'checking package integrity' } + .load_start { 'loading package files' } + .keyring_start { 'checking keys in keyring' } + } +} + +fn cb_progress(ctx voidptr, kind alpm.Progress, pkgname &u8, percent i32, howmany uint, current uint) { + mut ui := &TransUI(ctx) + verb := progress_verb(kind) + name := safe_vstring(pkgname) + // pacman draws one bar per package for the package phases (the text is + // '(current/howmany) verb name' and the percent restarts for each + // package), and a single bar per whole-transaction check phase + // (conflicts, diskspace, integrity, load, keyring). libalpm also sends + // the final 100% event with a different `current`, so the phase bars + // must not be keyed on it. + pkg_wise := match kind { + .add_start, .upgrade_start, .downgrade_start, .reinstall_start, .remove_start { + true + } + else { + false + } + } + if ipc_on() { + ev := ProgressEvent{ + op: verb + pkg: if pkg_wise { name } else { '' } + percent: int(percent) + current: int(current) + total: int(howmany) + } + // plast guards the repeats; the shared state is touched holding the + // ui's mutex, and the event goes out with the lock gone + ui.mu.lock() + dup := ev == ui.plast + if !dup { + ui.plast = ev + } + ui.mu.unlock() + if !dup { + emit(ev) + } + return + } + // the key pairs the phase with the package the progress belongs to: the + // bar restarts when either changes. 1000003 is prime; a collision would + // need a transaction packaging over a million files in one phase + pkey := if pkg_wise { int(kind) * 1000003 + int(current) } else { int(kind) } + text := if !pkg_wise || name == '' { + '${verb} ' + } else { + '(${int(current)}/${int(howmany)}) ${verb} ${name} ' + } + ui.mu.lock() + defer { ui.mu.unlock() } + if ui.pbar == unsafe { nil } || ui.pkey != pkey { + ui.pkey = pkey + ui.pbar = ui.group_locked().add_bar(100, bar_opts(text: text)) + ui.group_locked().start() + } + ui.pbar.set_text(text) + ui.pbar.set(i64(percent)) +} + +// cb_question asks libalpm's questions the way pacman's frontend does, with +// pacman's defaults: yes to installing an ignored package, replacing a +// package, deleting a corrupted package file and importing a missing key; no +// to removing a conflicting package and to skipping packages whose +// dependencies cannot be resolved; the first of several providers. libalpm +// presets every answer to 0 before it asks, so a question left unanswered is +// a no, which is not pacman's default for half of them. the live display is +// paused first so it cannot draw over the listings, and every question goes +// through the ui's prompter, whose --noconfirm prints each one and takes its +// default. all of it follows pacman's cb_question in src/pacman/callback.c +fn cb_question(ctx voidptr, q &alpm.Question) { + mut ui := &TransUI(ctx) + kind := unsafe { q.type_ } + // --print lists the transaction and asks nothing: an ignored package and + // a replacement stay in the list, every other question is a no, and a + // provider is the first. install's own dependency walks answer the same + if ui.print_only || ui.walking { + set_answer(q, flag_answer(kind in [.install_ignorepkg, .replace_pkg])) + return + } + ui.pause() + answer := match kind { + .install_ignorepkg { + pkg := unsafe { q.install_ignorepkg.pkg } + // a download installs nothing, so the ignored package is fetched + if ui.download_only { + i32(1) + } else { + flag_answer(ui.yesno('${pkg.get_name()} is ignored. install it anyway?')) + } + } + .replace_pkg { + r := unsafe { q.replace } + old := r.oldpkg.get_name() + flag_answer(ui.yesno('replace ${old} with ${r.newdb.get_name()}/${r.newpkg.get_name()}?')) + } + .conflict_pkg { + conflict := unsafe { q.conflict.conflict } + kept := conflict.package1.get_name() + removed := conflict.package2.get_name() + flag_answer(ui.noyes('${kept} conflicts with ${removed}. remove ${removed}?')) + } + .corrupted_pkg { + c := unsafe { q.corrupted } + path := safe_vstring(c.filepath) + flag_answer(ui.yesno('${path} is corrupted (${c.reason.strerror()}). delete it?')) + } + .remove_pkgs { + // a sysupgrade whose packages have unresolvable dependencies: + // skipping them lets the rest of the upgrade go on + mut list := unsafe { q.remove_pkgs.packages } + pkgs := list.pkgs() + noun := if pkgs.len == 1 { 'package' } else { 'packages' } + ui.show_packages('${pkgs.len} ${noun} cannot be upgraded, their dependencies cannot be resolved:', + pkgs) + flag_answer(ui.noyes('skip them for this upgrade?')) + } + .select_provider { + sp := unsafe { q.select_provider } + mut list := sp.providers + providers := list.pkgs() + title := '${providers.len} providers for ${sp.depend.compute_string()}:' + // a frontend gets them as the choices; the terminal lists them as + // numbered rows first, and those are built only for it + choices := providers.map(provider_choice(it)) + if !ipc_on() { + println(heading(title)) + println(table_text(provider_rows(providers), ' ', ' ')) + } + i32(ui.choose(if ipc_on() { title.trim_right(':') } else { 'which one?' }, choices)) + } + .import_key { + k := unsafe { q.import_key } + fingerprint := safe_vstring(k.fingerprint) + // the uid is unknown for a db signature + uid := safe_vstring(k.uid) + key := if uid == '' { fingerprint } else { '${fingerprint}, "${uid}"' } + flag_answer(ui.yesno('import pgp key ${key}?')) + } + } + set_answer(q, answer) +} + +// provider_choice is a provider as a frontend's choice: repo/name version +fn provider_choice(pkg &alpm.Package) string { + repo := if db := pkg.get_db() { db.get_name() + '/' } else { '' } + return '${repo}${pkg.get_name()} ${pkg.get_version()}' +} + +// provider_rows are the providers numbered for the terminal's listing, the +// number the choose question asks for +fn provider_rows(providers []&alpm.Package) []Row { + mut rows := []Row{} + for i, pkg in providers { + styled := if db := pkg.get_db() { source_style(db.get_name()) + '/' } else { '' } + rows << row('${i + 1})', styled + name_style(pkg.get_name()), version_style(pkg.get_version())) + } + return rows +} + +// alpm_log_line is libalpm's log callback, its V half: alpm_log.h formats +// each error and warning libalpm says, and it is said to the user as +// pacman's cb_log says it. vpac's own dependency walks (ui.walking) look +// things up the transaction's prepare looks up again; what they would say +// is said then, once +@[export: 'vpac_log_line'] +fn alpm_log_line(ctx voidptr, level int, text &char) { + if ctx == unsafe { nil } || text == unsafe { nil } { + return + } + mut ui := unsafe { &TransUI(ctx) } + if ui.walking { + return + } + msg := unsafe { cstring_to_vstring(text) }.trim_space() + if msg == '' { + return + } + ui.alpm_said(level == alpm_log_error, msg) +} + +// alpm_said is a line libalpm logged: printed above any live bars (which +// hold it while they draw, as pacman buffers during progress), or a message +// event a frontend reads as a warning, an error flagged as one +fn (mut ui TransUI) alpm_said(is_error bool, text string) { + if ipc_on() { + emit(MessageEvent{ + text: text + warning: true + error: is_error + }) + return + } + line := if is_error { error_text(text) } else { warning(text) } + ui.mu.lock() + defer { ui.mu.unlock() } + if ui.mb != unsafe { nil } { + ui.mb.println(line) + } else { + eprintln(line) + } +} + +// set_answer writes a question's answer. every question struct keeps its +// answer right after the type, which is what libalpm's alpm_question_any_t +// exposes +fn set_answer(q &alpm.Question, answer i32) { + unsafe { + mut any := &alpm.QuestionAny(q) + any.answer = answer + } +} + +fn flag_answer(yes bool) i32 { + return if yes { 1 } else { 0 } +} + +// init_handle initializes alpm and attaches the progress display callbacks +// and the configured parallel download count +fn init_handle(ui &TransUI) !&alpm.Handle { + handle := alpm.initialize(root_path, db_path) or { + return error('failed to initialize alpm') + } + handle.option_set_dlcb(cb_download, voidptr(ui))! + handle.option_set_progresscb(cb_progress, voidptr(ui))! + handle.option_set_questioncb(cb_question, voidptr(ui))! + // libalpm's errors and warnings, which it says through this alone + if C.vpac_set_alpm_log(handle, voidptr(ui)) != 0 { + return error('could not set the log callback: ${handle.error().msg()}') + } + // the freshly calloc'd handle verifies nothing: pacman defaults to + // checking signature levels, so the configured level is made the + // handle's default for every db registered later, and for local and + // remote files the transaction loads (libalpm tells the two apart as + // pacman's SigLevel does; RemoteFileSigLevel follows SigLevel when it + // is not named). a file is checked at its load only, at the level of its + // origin (load_file_target); the remote level also decides whether a + // url's .sig is fetched, and the url install warns by it + handle.option_set_default_siglevel(cfg_siglevel)! + handle.option_set_local_file_siglevel(cfg_siglevel)! + handle.option_set_remote_file_siglevel(cfg_siglevel)! + // pacman's frontend sets these from the config; without a cache dir + // libalpm falls back to /tmp for downloads + for dir in cfg_cachedirs { + handle.option_add_cachedir(dir)! + } + // pacman's Architecture: without one libalpm's check_arch passes every + // package, whatever it was built for + handle.option_add_architecture(arch)! + // libalpm's own hook dir (under the root) is on the handle already; + // these are the config's, pacman's HookDir + for dir in cfg_hookdirs { + handle.option_add_hookdir(dir)! + } + if cfg_logfile != '' { + handle.option_set_logfile(cfg_logfile)! + } + if cfg_syslog { + handle.option_set_usesyslog(1)! + } + if cfg_gpgdir != '' { + handle.option_set_gpgdir(cfg_gpgdir)! + } + // the ignored packages are libalpm's to skip on upgrades, with a question + // for the user at the start of one + for name in cfg_ignore { + handle.option_add_ignore_pkg(name)! + } + for group in cfg_ignore_groups { + handle.option_add_ignore_group(group)! + } + // pacman.conf's NoUpgrade and NoExtract: globs of files an upgrade keeps + // (writing .pacnew beside them) and files an install never writes + for glob in cfg_noupgrade { + handle.option_add_noupgrade(glob)! + } + for glob in cfg_noextract { + handle.option_add_no_extract(glob)! + } + if cfg_disable_timeout { + handle.option_set_disable_dl_timeout(1)! + } + // pacman's DownloadUser: downloads run as this user, sandboxed. an empty + // one is pacman without DownloadUser, downloads as root, unsandboxed + if download_user != '' { + handle.option_set_sandboxuser(download_user) or { + return error('problem setting the download user "${download_user}" (user does not exist)') + } + } + // pacman's DisableSandboxFilesystem and DisableSandboxSyscalls: the + // downloader and the extraction run without either part of libalpm's + // sandbox. the installed libalpm has these two, not a whole-sandbox switch + if cfg_disable_sandbox { + handle.option_set_disable_sandbox_filesystem(1)! + handle.option_set_disable_sandbox_syscalls(1)! + } + handle.option_set_parallel_downloads(u32(parallel_downloads))! + return handle +} diff --git a/src/ui_test.v b/src/ui_test.v new file mode 100644 index 0000000..971b8c1 --- /dev/null +++ b/src/ui_test.v @@ -0,0 +1,120 @@ +module main + +import alpm +import json2 +import os + +fn test_restart_download_bar() { + mut ui := new_trans_ui() + defer { ui.stop() } + mut bar := ui.download_bar('a.pkg', 100, '', true) + bar.set(60) + assert bar.value() == 60 + // libalpm starts the file over from the next mirror: so does the bar + ui.restart_download_bar('a.pkg') + assert bar.value() == 0 + // a file with no bar drawn yet has nothing to restart, and gets no bar + ui.restart_download_bar('b.pkg') + assert 'b.pkg' !in ui.dbars +} + +fn test_download_retry_through_the_callback() { + // the callback libalpm calls: a retry that starts over resets the bar, + // one that resumes leaves it where it was + mut ui := new_trans_ui() + defer { ui.stop() } + mut p := alpm.DownloadEventProgress{ + downloaded: 40 + total: 100 + } + cb_download(voidptr(ui), c'a.pkg', .progress, voidptr(&p)) + mut bar := ui.dbars['a.pkg'] or { panic('no bar for a.pkg') } + assert bar.value() == 40 + mut resume := alpm.DownloadEventRetry{ + resume: 1 + } + cb_download(voidptr(ui), c'a.pkg', .retry, voidptr(&resume)) + assert bar.value() == 40 + mut over := alpm.DownloadEventRetry{ + resume: 0 + } + cb_download(voidptr(ui), c'a.pkg', .retry, voidptr(&over)) + assert bar.value() == 0 +} + +fn test_stop_twice_is_one_stop() { + // rank stops the display before it prints and again in its defer: the + // second stop finds nothing left to do + mut ui := new_trans_ui() + mut m := ui.meter(3, 'probing') + m.start() + m.add(3) + ui.stop() + ui.stop() + // and a ui that never drew stops just as well + mut quiet := new_trans_ui() + quiet.stop() + quiet.stop() +} + +fn test_stop_spinner_twice_is_one_finish() { + // a mode stops its spinner before a prompt or a print, and its defer + // stops it again on every way out + mut ui := new_trans_ui() + defer { ui.stop() } + mut s := ui.spinner(text: 'working') + s.start() + stop_spinner(mut s) + assert s.is_done() + stop_spinner(mut s) + assert s.is_done() +} + +fn test_phase_finishes_once_under_a_frontend() ! { + // under --ui ipc a phase is events: the second finish sends no second + // done, and a phase that never started sends nothing at all + path := os.join_path(os.vtmp_dir(), 'vpac_test_phase_${os.getpid()}') + mut f := os.create(path)! + defer { os.rm(path) or {} } + saved_kind, saved_fd := ui_kind, ipc_fd + ui_kind, ipc_fd = 'ipc', f.fd + mut ui := new_trans_ui() + mut s := ui.spinner(text: 'working') + s.start() + stop_spinner(mut s) + stop_spinner(mut s) + mut never := ui.spinner(text: 'skipped') + stop_spinner(mut never) + ui.stop() + ui_kind, ipc_fd = saved_kind, saved_fd + f.close() + states := os.read_lines(path)!.map(json2.decode[json2.Any](it)!.as_map()['state']!.str()) + assert states == ['start', 'done'] +} + +fn test_alpm_log_line() ! { + path := os.join_path(os.vtmp_dir(), 'vpac_test_alpmlog_${os.getpid()}') + mut f := os.create(path)! + defer { os.rm(path) or {} } + saved_kind, saved_fd := ui_kind, ipc_fd + ui_kind, ipc_fd = 'ipc', f.fd + mut ui := new_trans_ui() + // vpac's own walk looks up what the prepare looks up again: said once, + // then, not during the walk + ui.walking = true + alpm_log_line(voidptr(ui), 2, c'during the walk\n') + ui.walking = false + // libalpm's lines end in a newline, which the event does not carry + alpm_log_line(voidptr(ui), 2, c'a warning\n') + alpm_log_line(voidptr(ui), alpm_log_error, c'an error\n') + // nothing to say, or no ui to say it on: nothing + alpm_log_line(voidptr(ui), 2, c' \n') + alpm_log_line(unsafe { nil }, 2, c'no ui') + ui_kind, ipc_fd = saved_kind, saved_fd + f.close() + events := os.read_lines(path)!.map(json2.decode[json2.Any](it)!.as_map()) + assert events.map(it['text']!.str()) == ['a warning', 'an error'] + assert events.all(it['warning']!.bool()) + assert 'error' !in events[0] + assert events[1]['error']!.bool() +} diff --git a/src/upgrade.v b/src/upgrade.v new file mode 100644 index 0000000..4ac55be --- /dev/null +++ b/src/upgrade.v @@ -0,0 +1,106 @@ +module main + +fn upgrade(config ConfigUpgrade) ! { + // a --print preview asks nothing and takes no lock, as pacman's + mut ui := new_trans_ui(noconfirm: config.noconfirm || config.print_only) + ui.print_only = config.print_only + if !config.print_only { + check_ask_db_lock(mut ui) + } + + if config.disable_timeout { + cfg_disable_timeout = true + } + mut handle := init_handle(ui)! + defer { handle.release() or { went_on('release the alpm handle', err) } } + defer { ui.stop() } + defer { trans_cleanup(handle) } + trans_options(config).apply(handle)! + + mut s := ui.spinner(text: 'getting dbs and updating em') + s.start() + defer { stop_spinner(mut s) } + + init_repos(mut handle)! + if config.sync_dbs { + update_repos(mut handle, false)! + } else { + check_sync_fresh(mut ui, mut handle)! + } + + // a fresh one shows in either case: the set_text would land on the old + // spinner's frame when the prompt above paused it, and here the old one + // is finished with its work anyway + stop_spinner(mut s) + mut look := ui.spinner(text: 'looking for upgrades') + look.start() + defer { stop_spinner(mut look) } + mut flags := dep_check_flag(config.nodeps, config.nodeps_level) | print_flags(config.print_only) + if config.download_only { + flags |= .download_only + } + if config.dbonly { + flags |= .db_only + } + trans_begin(handle, flags)! + // pacman's -Suu: a local package newer than the sync one goes down to it + handle.sync_sysupgrade(config.downgrade || config.sysupgrade_level >= 2)! + + trans_prepare_checked(handle)! + + targets := handle.trans_get_add().pkgs() + + end_frame(mut ui, mut look) + + if targets.len == 0 { + // --print's output is the list alone + if !config.print_only { + report('nothing to upgrade.') + } + return + } + + // --print stops here: the upgrade is listed with the archive names, as + // install's --print lists a transaction, and nothing is downloaded + if config.print_only { + if ipc_on() { + mut preview := trans_listing(handle, targets, .upgrade) + preview.preview = true + emit(preview) + return + } + for pkg in targets { + file := pkg.get_filename() + println(if file == '' { pkg.get_name() } else { file }) + } + return + } + + // what the upgrade removes on the way — a replaced or conflicting + // package — is listed before the question, as install lists its own + removals := handle.trans_get_remove().pkgs() + if removals.len > 0 { + ui.show_packages('${removals.len} packages to remove:', removals) + } + if !trans_confirm(mut ui, handle, targets, .upgrade) { + return + } + names := targets.map(it.get_name()) + + mut s2 := ui.spinner( + text: if config.download_only { 'downloading the upgrades' } else { 'upgrading system' } + ) + s2.start() + defer { stop_spinner(mut s2) } + trans_commit(handle)! + stop_spinner(mut s2) + // a frontend learns what changed as from every transaction: a done event + if ipc_on() { + emit(DoneEvent{ + action: if config.download_only { 'downloaded' } else { 'upgraded' } + packages: names + }) + return + } + ui.say(if config.download_only { 'upgrades downloaded' } else { 'system upgraded' }) +} diff --git a/src/upgrade_deps.v b/src/upgrade_deps.v new file mode 100644 index 0000000..e009bb1 --- /dev/null +++ b/src/upgrade_deps.v @@ -0,0 +1,17 @@ +module main + +import alpm + +// prepare_error explains a failed transaction when the upgrade of outdated +// dependencies was switched off. a dependency too old for a target is not +// the cause then: libalpm's prepare pulls the newer one in by itself. what +// fails is the other direction — an installed package that needs the very +// version this transaction replaces — which the walk (broken_dependents) +// would have upgraded along. the hint goes on a line of its own, below the +// broken dependencies prepare listed +fn prepare_error(handle &alpm.Handle, msg string, no_upgrade_deps bool) string { + if no_upgrade_deps && handle.errno() == .unsatisfied_deps { + return '${msg}\nwithout --no-upgrade-deps, the installed packages this breaks are upgraded along with it when the repos have a version that fits' + } + return msg +} diff --git a/src/url_install.v b/src/url_install.v new file mode 100644 index 0000000..20f457c --- /dev/null +++ b/src/url_install.v @@ -0,0 +1,93 @@ +module main + +import alpm + +#include + +// is_url reports whether an install target is a URL rather than a name or +// path. like pacman, anything with a scheme is one: libalpm's fetcher, curl, +// knows which schemes it can fetch (file://, ftps://, ...). the scheme is +// spelled the RFC writes it — a letter, then letters, digits, '.', '+', '-', +// closed by '://' — so a path with a stray '://', which is a legal file +// name, keeps being a path +fn is_url(target string) bool { + n := target.index('://') or { return false } + scheme := target[..n] + // a scheme opens with a letter, whatever follows + if scheme.len < 1 || !(scheme[0] >= `a` && scheme[0] <= `z`) && !(scheme[0] >= `A` && scheme[0] <= `Z`) { + return false + } + for c in scheme[1..] { + match c { + `a`...`z`, `A`...`Z`, `0`...`9`, `.`, `+`, `-` { + continue + } + else { + return false + } + } + } + return true +} + +// fetch_url downloads a package from a URL into the cache with libalpm, so the +// download user and the progress bars are the same as for repo packages +fn fetch_url(handle &alpm.Handle, url string) !string { + // libalpm appends to the head of the list, so it needs the address of the head + mut urls := &alpm.List(unsafe { nil }) + url_head := &urls + url_head.append_strdup(url) + defer { + // the strdup'd urls are ours: inner first, then the list + urls.free_inner(fn (p voidptr) { + unsafe { C.free(p) } + }) + urls.free() + } + mut fetched := handle.fetch_pkgurl(urls)! + defer { + // libalpm strdup'd the fetched paths: them and their list are ours + // to free the same way + fetched.free_inner(fn (p voidptr) { + unsafe { C.free(p) } + }) + fetched.free() + } + // strs() wraps the C strings without copying them (vstring), and the + // defer above frees them: the path leaves as a copy, or the install + // would load whatever libalpm puts in that memory next + paths := fetched.strs() + if paths.len == 0 { + return error('nothing was downloaded from ${url}') + } + return paths[0].clone() +} + +// url_trust_warning is what a url install is warned of, by the remote file +// signature level its archive is loaded at: libalpm fetches the .sig beside +// the url when the level checks packages, and the load verifies it. none +// when the level requires a signature, which leaves nothing to warn of +fn url_trust_warning(target string, level alpm.SigLevel) ?string { + if !level.has(.package) { + return '${target}: package signatures are not checked' + } + if level.has(.package_optional) { + return '${target}: the signature is checked only if the server offers one' + } + return none +} + +// fetch_target_url downloads a package archive named by a URL through the +// install's own handle: the download draws on the install's display, and +// whatever libalpm asks on the way goes through the install's prompter. the +// warning before it says what the remote file signature level will check. +// it returns the cached file, installed then with the other targets +fn fetch_target_url(mut ui TransUI, handle &alpm.Handle, target string) !string { + level := handle.option_get_remote_file_siglevel() or { + return error('could not read the remote file signature level') + } + if note := url_trust_warning(target, level) { + ui.warn(note) + } + return fetch_url(handle, target)! +} diff --git a/src/url_install_test.v b/src/url_install_test.v new file mode 100644 index 0000000..33425de --- /dev/null +++ b/src/url_install_test.v @@ -0,0 +1,44 @@ +module main + +import alpm + +fn test_is_url() { + for url in ['https://example.org/foo-1-1-any.pkg.tar.zst', 'http://x/y', 'ftp://x/y', + 'file:///srv/pkgs/foo-1-1-any.pkg.tar.zst', 'ftps://x/y'] { + assert is_url(url), url + } + for target in ['zsh', 'extra/zsh', './foo-1-1-any.pkg.tar.zst', '/tmp/foo.pkg.tar.zst', 'zsh>=5'] { + assert !is_url(target), target + } + // the scheme is spelled as RFC 3986 says: a letter first, then letters, + // digits and '.', '+' or '-', closed by '://'. a path with a stray '://' + // in its name keeps being a path, and a text with '//' walk-in where a + // scheme-opening should be keeps being one too + assert is_url('a+b-c.d://host/x') + // dots are legal letters of a scheme, so a dotted one is one ('file:', + // 'ssh:' say it); a leading '-', an inner space or an opening digit do + // not, and '://' without a scheme before it does not + assert is_url('path.y.tar://') + assert !is_url('-lead://host/x') + assert !is_url('we ird://host/x') + assert !is_url('://host/x') + assert !is_url('9bad://host/x') +} + +fn test_url_trust_warning() { + url := 'https://example.org/foo-1-1-any.pkg.tar.zst' + // no package check: the warning says so + none_level := url_trust_warning(url, alpm.SigLevel.database) or { '' } + assert none_level.contains('not checked') + assert none_level.starts_with(url) + // optional: the .sig is read when the server offers one, not otherwise + optional := url_trust_warning(url, alpm.SigLevel.package | .package_optional) or { '' } + assert optional.contains('only if the server offers one') + // required: the load refuses an unsigned package, nothing to warn of + if note := url_trust_warning(url, alpm.SigLevel.package) { + assert false, 'a required signature was warned of: ${note}' + } + if note := url_trust_warning(url, alpm.SigLevel.package | .database) { + assert false, 'a required signature was warned of: ${note}' + } +} diff --git a/src/verify.v b/src/verify.v new file mode 100644 index 0000000..889b0bd --- /dev/null +++ b/src/verify.v @@ -0,0 +1,201 @@ +module main + +import alpm +import os + +// backups_of lists the backup entries of a package: the config files whose +// expected md5 the db records +fn backups_of(pkg &alpm.Package) []&alpm.Backup { + mut out := []&alpm.Backup{} + mut node := pkg.get_backup() + for node != unsafe { nil } { + if b := node.get_backup() { + out << b + } + node = node.next + } + return out +} + +// stat_denied: the stat failed not because the file is missing but because +// this run may not look at it. the errno is compared by the names errno.h +// gives it on this system, not by the strerror text, whose wording — and +// language — is whatever the system says, nor by a number posix never fixed +fn stat_denied(err IError) bool { + return err.code() == C.EPERM || err.code() == C.EACCES +} + +// VerifyLine is one line of a check's report, the file check's and the full +// (mtree) check's alike. problem is whether it counts against the package; a +// note does not: a modified backup file, a file this user may not read. the +// lines are held until the spinner is gone, because an println during the +// spin would be drawn under the running frame +struct VerifyLine { + problem bool + text string +} + +// verify_levels are how deep the checks go: the db level, -D counted (--db +// one), and the file level, -k counted (--checksums one, --full two). there +// are two of each, as in pacman, where -kkk is -kk and -Dkkk is -Dkk: more +// letters are the deepest level, not a level of their own +fn verify_levels(c ConfigVerify) (int, int) { + db := c.db_level + if c.db { 1 } else { 0 } + file := c.checksums_level + (if c.checksums { 1 } else { 0 }) + (if c.full { 2 } else { 0 }) + return if db > 2 { 2 } else { db }, if file > 2 { 2 } else { file } +} + +// verify checks the files of installed packages the way pacman's -Qk does: +// every file in the db is on disk, of the type the db says, and with -k the +// backed up config files are not modified. it reports only the packages with +// problems, and returns how many there are: main exits 1 when any are +fn verify(config ConfigVerify) !int { + mut ui := new_trans_ui() + // the configured handle: -kk needs the NoExtract globs + mut handle := init_handle(ui)! + defer { handle.release() or { went_on('release the alpm handle', err) } } + defer { ui.stop() } + + mut pkgcache := local_pkgcache(handle)! + + // -D and -DD check the databases, pacman's -Dk and -Dkk, and no files + db_level, level := verify_levels(config) + if db_level > 0 { + // a db error is reported as a failed target, which main counts + verify_db(mut handle, db_level)! + return 0 + } + + mut pkgs := pkgcache.pkgs() + if config.query.len > 0 { + // a target is a name, a versioned dependency or something provided, + // as pacman's -Qk resolves it; one that names nothing installed is + // reported and counted, and the rest are checked + pkgs = []&alpm.Package{} + for target in config.query { + pkg := find_local_target(pkgcache, local_target_name(target), true) or { + target_error('package "${target}" was not found') + continue + } + add_pkg_once(mut pkgs, pkg) + } + if pkgs.len == 0 { + return error('no one of the named packages is installed') + } + } + + mut s := ui.spinner(text: 'checking packages') + s.start() + defer { stop_spinner(mut s) } + + mut lines := []VerifyLine{} + mut bad := 0 + for pkg in pkgs { + // -kk: every file against the mtree, which covers the backup files too + if level >= 2 { + altered, found := verify_pkg_full(handle, pkg) + lines << found + if altered > 0 { + bad++ + } + continue + } + mut problems := 0 + // one name → expected md5 per package: the per-file check reads the + // map instead of walking the backup list again for every file + mut backups := map[string]string{} + if level >= 1 { + for b in backups_of(pkg) { + backups[b.get_name()] = b.get_hash() + } + } + for name in pkg.get_files().names() { + path := '${root_path}${name}' + // pacman's check_file_exists: lstat with the trailing slash + // dropped (its llstat), so a link — broken or not — is there as + // itself, and a directory the db lists that is now a link is + // that link, not the directory it points at + st := os.lstat(if name.ends_with('/') { path.trim_right('/') } else { path }) or { + // a file NoExtract kept off the disk is not missing, and is not + // said, as in pacman + if handle.option_match_no_extract(name) { + continue + } + // a stat denied by permissions is not the file missing, and it + // would drown the run in noise; noted but not counted (upstream + // pacman counts it). the errno comes along on the error, so + // the reading does not lean on strerror's wording + if stat_denied(err) { + lines << VerifyLine{false, '${pkg.get_name()}: warning: ${path} (${err.msg()})'} + } else { + problems++ + lines << VerifyLine{true, '${pkg.get_name()}: missing ${path}'} + } + continue + } + // the db records directories with a trailing slash; anything else + // on disk where it says one, or a directory where it says a file, + // is pacman's file type mismatch. a link where the db says a file + // is the file a package may well ship as a link + kind := st.get_filetype() + wants_dir := name.ends_with('/') + if (kind == .directory) != wants_dir { + problems++ + what := match kind { + .directory { 'a directory' } + .symbolic_link { 'a link' } + else { 'a file' } + } + lines << VerifyLine{true, '${pkg.get_name()}: ${path} is ${what}, the db says ${if wants_dir { + 'a directory' + } else { + 'a file' + }}'} + continue + } + // the checksums read regular files: a link's target is not the + // package's file + if kind == .symbolic_link { + continue + } + if level >= 1 && !wants_dir { + if hash := backups[name] { + // a checksum that libalpm cannot calculate counts as a + // problem, as pacman's "failed to calculate" does + md5 := alpm.compute_md5sum(path) or { + lines << VerifyLine{true, '${pkg.get_name()}: ${path} (failed to calculate MD5 checksum)'} + problems++ + continue + } + if md5 != hash { + problems++ + lines << VerifyLine{true, '${pkg.get_name()}: modified ${path}'} + } + } + } + } + if problems > 0 { + bad++ + } + } + end_frame(mut ui, mut s) + if ipc_on() { + emit(VerifyEvent{ + lines: lines + bad: bad + }) + return bad + } + // now that the frame is stopped, the report prints plainly, one line + // beside the next + for l in lines { + println(l.text) + } + if bad == 0 { + println('no problems found') + return 0 + } + noun := if bad == 1 { '1 package with problems' } else { '${bad} packages with problems' } + println(noun) + return bad +} diff --git a/src/verify_full.v b/src/verify_full.v new file mode 100644 index 0000000..abca18c --- /dev/null +++ b/src/verify_full.v @@ -0,0 +1,290 @@ +module main + +import alpm +import crypto.sha256 +import os + +#flag -larchive +#include +#include + +// libalpm reads a package's mtree for us; these are the libarchive accessors +// pacman's -Qkk reads each entry with +fn C.archive_entry_pathname(entry &C.Archive_entry) &char +fn C.archive_entry_filetype(entry &C.Archive_entry) u32 +fn C.archive_entry_mode(entry &C.Archive_entry) u32 +fn C.archive_entry_uid(entry &C.Archive_entry) i64 +fn C.archive_entry_gid(entry &C.Archive_entry) i64 +fn C.archive_entry_mtime(entry &C.Archive_entry) i64 +fn C.archive_entry_size(entry &C.Archive_entry) i64 +fn C.archive_entry_symlink(entry &C.Archive_entry) &char +fn C.archive_entry_digest(entry &C.Archive_entry, kind int) &u8 + +// the binding's mtree_next hands the entry to its own parameter, so the +// caller never sees it: libalpm is called directly +fn C.alpm_pkg_mtree_next(pkg &alpm.Package, archive &C.Archive, entry &&C.Archive_entry) int + +fn C.archive_error_string(archive &C.Archive) &char + +const ae_ifmt = u32(0o170000) +const ae_ifreg = u32(0o100000) +const ae_ifdir = u32(0o040000) +const ae_iflnk = u32(0o120000) +// the mode bits pacman compares: permissions, setuid, setgid and sticky +const mode_bits = u32(0o7777) + +// MtreeEntry is what a package's mtree records of one of its files +struct MtreeEntry { + path string // as in the mtree, './' stripped + kind u32 // ae_ifreg, ae_ifdir or ae_iflnk + mode u32 + uid i64 + gid i64 + mtime i64 + size i64 + symlink string + sha256 string // hex, empty when the mtree has none +} + +// mtree_entries reads a package's mtree. an error is a broken one: libalpm's +// mtree reader hands an entry over at 0, answers 1 at the mtree's end and +// anything else for entries beyond reading, so the loop tells the end and a +// read failure apart — pacman's own loop stops at anything that is not 0, +// which reports a partial mtree as a complete one. the second value is +// whether the package carries an mtree file at all (packages built before +// mtrees existed do not; that is not an error) +fn mtree_entries(pkg &alpm.Package) !([]MtreeEntry, bool) { + archive := pkg.mtree_open() + if archive == unsafe { nil } { + // libalpm answers nil both for no mtree file and for one libarchive + // cannot open; it tells them apart by the file being there, and so + // does this: a corrupt mtree is the package's problem, not a package + // built before mtrees (pacman's check.c leaves this as a TODO) + handle := pkg.get_handle() + // the reason is read first: libalpm's package getters clear it + reason := handle.error().msg() + mtfile := os.join_path(handle.option_get_dbpath(), 'local', '${pkg.get_name()}-${pkg.get_version()}', + 'mtree') + if os.exists(mtfile) { + return error('the mtree file cannot be read (${reason}): ${mtfile}') + } + return []MtreeEntry{}, false + } + mut out := []MtreeEntry{} + mut entry := &C.Archive_entry(unsafe { nil }) + for { + ret := C.alpm_pkg_mtree_next(pkg, archive, &entry) + if ret != 0 { + if ret != 1 { + // the read's reason is libarchive's, kept on the archive: + // libalpm passes the status through and sets no error of its + // own. it is taken before the close frees the archive, and a + // close that fails too rides along rather than going unsaid + read_err := error('reading the mtree failed: ${mtree_reason(pkg, archive)}') + pkg.mtree_close(archive) or { + return error('${read_err.msg()} (closing it failed too: ${err.msg()})') + } + return read_err + } + break + } + mut path := unsafe { cstring_to_vstring(C.archive_entry_pathname(entry)) } + if path.starts_with('./') { + path = path[2..] + } + link := C.archive_entry_symlink(entry) + out << MtreeEntry{ + path: path + kind: C.archive_entry_filetype(entry) + mode: C.archive_entry_mode(entry) & mode_bits + uid: C.archive_entry_uid(entry) + gid: C.archive_entry_gid(entry) + mtime: C.archive_entry_mtime(entry) + size: C.archive_entry_size(entry) + symlink: if link == unsafe { nil } { '' } else { unsafe { cstring_to_vstring(link) } } + sha256: digest_hex(C.archive_entry_digest(entry, C.ARCHIVE_ENTRY_DIGEST_SHA256)) + } + } + pkg.mtree_close(archive) or { + // the close is the read's last word; the entries fail with it + return error('opening the mtree of ${pkg.get_name()} failed to close it: ${err.msg()}') + } + return out, true +} + +// mtree_reason is why an mtree read stopped: libarchive's message on the +// archive, or libalpm's error when libarchive kept none +fn mtree_reason(pkg &alpm.Package, archive &C.Archive) string { + msg := C.archive_error_string(archive) + if msg != unsafe { nil } { + text := unsafe { cstring_to_vstring(msg) } + if text != '' { + return text + } + } + return pkg.get_handle().error().msg() +} + +// digest_hex is a 32 byte sha256 digest as hex, empty when it is all zero: +// libarchive leaves it so when the mtree records none +fn digest_hex(d &u8) string { + if d == unsafe { nil } { + return '' + } + bytes := unsafe { d.vbytes(32) }.clone() + return if bytes.all(it == 0) { '' } else { bytes.hex() } +} + +// file_sha256 hashes a file in chunks, so a large one is never read whole. +// the read names end of input as its own error (os.Eof); a failure to read +// anything else is the caller's news — a digest of the part that came out +// would pass itself off as the whole file's +fn file_sha256(path string) !string { + mut f := os.open(path)! + defer { f.close() } + mut d := sha256.new() + mut buf := []u8{len: 65536} + for { + n := f.read(mut buf) or { + // end of input is a chunking loop's end, not a failure + if err is os.Eof { + break + } + return err + } + if n == 0 { + break + } + d.write(buf[..n])! + } + return d.sum([]).hex() +} + +// check_file_full compares one file on disk with its mtree entry, the way +// pacman's -Qkk does: the type first, then owner, group and mode, the target +// of a link, and for anything that is not a directory the mtime, and for a +// regular file the size and the sha256. a backup file is expected to change +// in time, size and content, so those only make a note for it +fn check_file_full(path string, e MtreeEntry, backup bool) []VerifyLine { + st := os.lstat(path) or { + // a stat denied by permissions is not a missing file, as in the + // fast check. the errno comes along on the error, so the reading + // does not lean on strerror's wording + if stat_denied(err) { + return [VerifyLine{false, '${path} (${err.msg()})'}] + } + return [VerifyLine{true, '${path} (missing)'}] + } + kind := st.mode & ae_ifmt + if kind != e.kind { + return [VerifyLine{true, '${path} (file type mismatch)'}] + } + mut out := []VerifyLine{} + if i64(st.uid) != e.uid { + out << VerifyLine{true, '${path} (UID mismatch)'} + } + if i64(st.gid) != e.gid { + out << VerifyLine{true, '${path} (GID mismatch)'} + } + if st.mode & mode_bits != e.mode { + out << VerifyLine{true, '${path} (permissions mismatch)'} + } + if kind == ae_iflnk { + // a link that cannot be read is its own finding, as pacman's + // check_symlink says it, not a target that differs + if target := os.readlink(path) { + if target != e.symlink { + out << VerifyLine{true, '${path} (symlink path mismatch)'} + } + } else { + out << VerifyLine{true, '${path} (unable to read symlink contents: ${err.msg()})'} + } + } + // a backup file's changes are the user's: they are noted, not counted + note := fn [backup, path] (what string) VerifyLine { + return if backup { + VerifyLine{false, 'backup file ${path} (${what})'} + } else { + VerifyLine{true, '${path} (${what})'} + } + } + if kind != ae_ifdir && st.mtime != e.mtime { + out << note('modification time mismatch') + } + if kind == ae_ifreg { + if i64(st.size) != e.size { + out << note('size mismatch') + } + if e.sha256 == '' { + out << VerifyLine{true, '${path} (SHA256 checksum information not available)'} + } else if sum := file_sha256(path) { + if sum != e.sha256 { + out << note('SHA256 checksum mismatch') + } + } else { + // unverified counts as altered, as pacman's "failed to calculate" + // does: run as root to read the root-only files + out << VerifyLine{true, '${path} (cannot read: ${err.msg()})'} + } + } + return out +} + +// verify_pkg_full is pacman's -Qkk for one package: every entry of its +// mtree against the disk. the .INSTALL and .CHANGELOG entries are the db's +// own copies; the other dot entries describe the package, not its files. +// the report is held and handed back with the number of altered files: the +// caller prints it after its spinner stops, since an inline println would +// draw under the running frame +fn verify_pkg_full(handle &alpm.Handle, pkg &alpm.Package) (int, []VerifyLine) { + name := pkg.get_name() + mut lines := []VerifyLine{} + // a broken mtree is that package's verdict; the check goes on + entries, has_mtree := mtree_entries(pkg) or { + lines << VerifyLine{true, '${name}: ${err.msg()}'} + return 1, lines + } + if !has_mtree { + lines << VerifyLine{false, '${name}: no mtree file'} + return 0, lines + } + backups := backups_of(pkg).map(it.get_name()) + mut altered := 0 + for e in entries { + path := if e.path.starts_with('.') { + dbfile := match e.path { + '.INSTALL' { 'install' } + '.CHANGELOG' { 'changelog' } + else { '' } + } + if dbfile == '' { + continue + } + // the db the mtree was read from: the handle's, not the global + os.join_path(handle.option_get_dbpath(), 'local', '${name}-${pkg.get_version()}', + dbfile) + } else { + '${root_path}${e.path}' + } + if e.kind !in [ae_ifreg, ae_ifdir, ae_iflnk] { + lines << VerifyLine{false, '${name}: warning: ${path} (file type not recognized)'} + continue + } + // a file NoExtract kept off the disk is not missing + if !os.exists(path) && !os.is_link(path) && handle.option_match_no_extract(e.path) { + continue + } + findings := check_file_full(path, e, e.path in backups) + for f in findings { + lines << VerifyLine{f.problem, if f.problem { + '${name}: ${f.text}' + } else { + '${name}: note: ${f.text}' + }} + } + if findings.any(it.problem) { + altered++ + } + } + return altered, lines +} diff --git a/src/verify_full_test.v b/src/verify_full_test.v new file mode 100644 index 0000000..8fd8899 --- /dev/null +++ b/src/verify_full_test.v @@ -0,0 +1,211 @@ +module main + +import alpm +import crypto.sha256 +import encoding.base64 +import os + +// a file on disk and the mtree entry that matches it exactly +fn full_fixture(dir string) !(string, MtreeEntry) { + path := os.join_path(dir, 'f') + os.write_file(path, 'hello\n')! + os.chmod(path, 0o644)! + os.utime(path, 1700000000, 1700000000)! + st := os.lstat(path)! + return path, MtreeEntry{ + path: 'f' + kind: ae_ifreg + mode: 0o644 + uid: i64(st.uid) + gid: i64(st.gid) + mtime: 1700000000 + size: 6 + sha256: sha256.hexhash('hello\n') + } +} + +fn texts(findings []VerifyLine) []string { + return findings.map(if it.problem { + it.text.all_after('(') + } else { + 'note ${it.text.all_after('(')}' + }) +} + +fn test_check_file_full() ! { + tmp := os.join_path(os.vtmp_dir(), 'vpac_test_verify_${os.getpid()}') + os.mkdir_all(tmp)! + defer { os.rmdir_all(tmp) or {} } + path, e := full_fixture(tmp)! + + assert check_file_full(path, e, false) == [] + assert texts(check_file_full(path, MtreeEntry{ ...e, size: 7 }, false)) == ['size mismatch)'] + assert texts(check_file_full(path, MtreeEntry{ ...e, sha256: '00'.repeat(32) }, false)) == [ + 'SHA256 checksum mismatch)', + ] + assert texts(check_file_full(path, MtreeEntry{ ...e, mtime: 1 }, false)) == [ + 'modification time mismatch)', + ] + assert texts(check_file_full(path, MtreeEntry{ ...e, mode: 0o600 }, false)) == [ + 'permissions mismatch)', + ] + assert texts(check_file_full(path, MtreeEntry{ ...e, uid: e.uid + 1 }, false)) == [ + 'UID mismatch)', + ] + assert texts(check_file_full(path, MtreeEntry{ ...e, sha256: '' }, false)) == [ + 'SHA256 checksum information not available)', + ] + // the wrong type stops the checks there + assert texts(check_file_full(path, MtreeEntry{ ...e, kind: ae_ifdir, size: 0 }, false)) == [ + 'file type mismatch)', + ] + assert texts(check_file_full(os.join_path(tmp, 'gone'), e, false)) == ['missing)'] + + // a backup file may change in time, size and content: notes, no problem + changed := MtreeEntry{ + ...e + mtime: 1 + size: 99 + sha256: '00'.repeat(32) + } + findings := check_file_full(path, changed, true) + assert !findings.any(it.problem) + assert texts(findings) == ['note modification time mismatch)', 'note size mismatch)', + 'note SHA256 checksum mismatch)'] + // but not in mode + assert texts(check_file_full(path, MtreeEntry{ ...e, mode: 0o600 }, true)) == [ + 'permissions mismatch)', + ] +} + +fn test_check_file_full_symlink() ! { + tmp := os.join_path(os.vtmp_dir(), 'vpac_test_verify_link_${os.getpid()}') + os.mkdir_all(tmp)! + defer { os.rmdir_all(tmp) or {} } + link := os.join_path(tmp, 'l') + os.symlink('f', link)! + st := os.lstat(link)! + e := MtreeEntry{ + path: 'l' + kind: ae_iflnk + mode: st.mode & mode_bits + uid: i64(st.uid) + gid: i64(st.gid) + mtime: st.mtime + symlink: 'f' + } + // a link is checked as a link: its target need not exist + assert check_file_full(link, e, false) == [] + assert texts(check_file_full(link, MtreeEntry{ ...e, symlink: 'g' }, false)) == [ + 'symlink path mismatch)', + ] +} + +fn test_digest_hex() { + zero := []u8{len: 32} + assert digest_hex(zero.data) == '' + mut d := []u8{len: 32} + d[0] = 0xab + d[31] = 0x01 + assert digest_hex(d.data) == 'ab' + '00'.repeat(30) + '01' + assert digest_hex(unsafe { nil }) == '' +} + +fn test_file_sha256() ! { + tmp := os.join_path(os.vtmp_dir(), 'vpac_test_sha_${os.getpid()}') + os.mkdir_all(tmp)! + defer { os.rmdir_all(tmp) or {} } + // larger than one 64 KiB chunk + data := 'abcdefgh'.repeat(20000) + path := os.join_path(tmp, 'big') + os.write_file(path, data)! + assert file_sha256(path)! == sha256.hexhash(data) + assert file_sha256(os.join_path(tmp, 'nope')) or { 'error' } == 'error' +} + +// a read that fails never comes back as the partial file's digest: a +// truncated hash would pass itself off as the whole file's +fn test_file_sha256_read_failure() ! { + tmp := os.join_path(os.vtmp_dir(), 'vpac_test_sha_deny_${os.getpid()}') + os.mkdir_all(tmp)! + defer { os.rmdir_all(tmp) or {} } + if sum := file_sha256(tmp) { + assert false, 'a directory hashed as "${sum[0..8]}…"' + } else { + assert err.msg() != '', err.msg() + } +} + +// mtree_pkg installs one package in a temp local db with the given gzipped +// mtree text, and returns the handle and the package libalpm loads for it +fn mtree_pkg(tmp string, name string, mtree []u8) !(&alpm.Handle, &alpm.Package) { + entry := os.join_path(tmp, 'db', 'local', '${name}-1.0-1') + os.mkdir_all(entry)! + os.mkdir_all(os.join_path(tmp, 'root'))! + os.write_file(os.join_path(tmp, 'db', 'local', 'ALPM_DB_VERSION'), '9\n')! + os.write_file(os.join_path(entry, 'desc'), '%NAME%\n${name}\n\n%VERSION%\n1.0-1\n\n')! + os.write_file(os.join_path(entry, 'files'), '%FILES%\n\n')! + if mtree.len > 0 { + os.write_file_array(os.join_path(entry, 'mtree'), mtree)! + } + handle := alpm.initialize(os.join_path(tmp, 'root') + '/', os.join_path(tmp, 'db') + '/')! + pkg := handle.find_local_pkg(name) or { return error('${name} is not installed') } + return handle, pkg +} + +// gzipped is text compressed the way package mtrees ship +fn gzipped(text string) ![]u8 { + res := os.exec(['sh', '-c', 'printf %s "\$0" | gzip -9 | base64 -w0', text]) + if res.exit_code != 0 { + return error('gzip failed: ${res.output}') + } + return base64.decode(res.output.trim_space()) +} + +fn test_verify_pkg_full_broken_mtree() ! { + tmp := os.join_path(os.vtmp_dir(), 'vpac_test_mtree_${os.getpid()}') + os.rmdir_all(tmp) or {} + defer { os.rmdir_all(tmp) or {} } + whole := gzipped('#mtree\n/set type=file uid=0 gid=0 mode=644\n./usr time=1.0 type=dir\n')! + // cut off inside the compressed stream: the read fails part way, and + // that failure — libalpm's reason — is the package's verdict, not a + // package without an mtree + handle, pkg := mtree_pkg(tmp, 'broken', whole[..whole.len / 2])! + defer { handle.release() or {} } + altered, lines := verify_pkg_full(handle, pkg) + assert altered == 1, lines.str() + assert lines.len == 1 + assert lines[0].problem + assert lines[0].text.starts_with('broken: the mtree file cannot be read (libarchive error): '), lines[0].text + assert lines[0].text.ends_with('/local/broken-1.0-1/mtree'), lines[0].text +} + +fn test_verify_pkg_full_no_mtree() ! { + tmp := os.join_path(os.vtmp_dir(), 'vpac_test_nomtree_${os.getpid()}') + os.rmdir_all(tmp) or {} + defer { os.rmdir_all(tmp) or {} } + // a package built before mtrees existed: noted, not a problem + handle, pkg := mtree_pkg(tmp, 'old', [])! + defer { handle.release() or {} } + altered, lines := verify_pkg_full(handle, pkg) + assert altered == 0 + assert lines.map(it.text) == ['old: no mtree file'] + assert !lines[0].problem +} + +fn test_verify_pkg_full_mtree_read_failure() ! { + tmp := os.join_path(os.vtmp_dir(), 'vpac_test_mtree_read_${os.getpid()}') + os.rmdir_all(tmp) or {} + defer { os.rmdir_all(tmp) or {} } + // the mtree opens, and an entry of it is not one: the read stops part + // way, and the package's verdict carries libarchive's own reason + handle, pkg := mtree_pkg(tmp, 'midway', gzipped('#mtree\n./a type=bogus\n')!)! + defer { handle.release() or {} } + altered, lines := verify_pkg_full(handle, pkg) + assert altered == 1, lines.str() + assert lines.len == 1 + assert lines[0].problem + assert lines[0].text.starts_with('midway: reading the mtree failed: '), lines[0].text + reason := lines[0].text.all_after('failed: ') + assert reason != '' && reason != 'unexpected error', lines[0].text +} diff --git a/src/verify_test.v b/src/verify_test.v new file mode 100644 index 0000000..89bc1f2 --- /dev/null +++ b/src/verify_test.v @@ -0,0 +1,45 @@ +module main + +struct LevelCase { + c ConfigVerify + db int + file int +} + +fn test_verify_levels() { + for t in [ + LevelCase{ConfigVerify{}, 0, 0}, + LevelCase{ConfigVerify{ + checksums_level: 1 + }, 0, 1}, + LevelCase{ConfigVerify{ + checksums: true + }, 0, 1}, + LevelCase{ConfigVerify{ + checksums_level: 2 + }, 0, 2}, + LevelCase{ConfigVerify{ + full: true + }, 0, 2}, + // more letters are the deepest level, as pacman's -kkk is -kk + LevelCase{ConfigVerify{ + checksums_level: 3 + }, 0, 2}, + LevelCase{ConfigVerify{ + checksums: true + full: true + }, 0, 2}, + LevelCase{ConfigVerify{ + db: true + }, 1, 0}, + LevelCase{ConfigVerify{ + db_level: 2 + }, 2, 0}, + LevelCase{ConfigVerify{ + db_level: 4 + }, 2, 0}, + ] { + db, file := verify_levels(t.c) + assert db == t.db && file == t.file, '${t.c}' + } +} diff --git a/v.mod b/v.mod new file mode 100644 index 0000000..dc108d9 --- /dev/null +++ b/v.mod @@ -0,0 +1,8 @@ +Module { + name: 'vpac' + description: 'an alpm frontend written in V' + version: '0.0.0' + license: 'GPLv3' + base_url: 'src' + dependencies: ['alpm.v', 'blip'] +} diff --git a/vmakepkg/lip.v b/vmakepkg/lip.v new file mode 100644 index 0000000..824af7b --- /dev/null +++ b/vmakepkg/lip.v @@ -0,0 +1,939 @@ +// vmakepkg holds the build side of blip PKGBUILD.lip files and V-script +// PKGBUILD.vsh files. vpac is its one user: the build mode (vpac b) and the +// --lip-run entry the generated PKGBUILDs call back through; the rest of +// the repo reaches it only by running vpac: +// +// (defpkgbuild foobar ...) lives under pkgs//PKGBUILD.lip or inside +// an arbitrary repo a build was pointed at, and this module: +// 1. validates the form and reads it out as a struct value, +// 2. lip_generate turns it into a PKGBUILD (plus a .install when +// hooks are written) whose phase functions call the runner binary back +// with --lip-run, so the lambdas never become shell, +// 3. lip_run_phase is the runner: it loads the lip and runs one phase in +// a machine where (run) (glob) (pkgdir) (srcdir) (startdir) (this-pkg) +// and (git-desc) exist. +// makepkg keeps everything else: sources, checksums, PGP, fakeroot, lint, +// packaging. unknown options and checksum counts come out of makepkg's own +// mouth, since the generated file is a real PKGBUILD. +module vmakepkg + +import os +import blip.vlib.blip +import blip.vlib.blip.machine +import blip.vlib.blip.host +import blip.vlib.blip.printer + +// ----------------------------------------------------------------- lip pkgs +// +// PKGBUILD.lip files under pkgs/ describe a package in blip: +// +// (defpkgbuild foobar +// ;; — identity — +// :pkgname "foobar" ; or '("foo" "bar") for split +// :pkgver "2.5" ; or (lambda () ...) for VCS +// :pkgrel 2 ; bump on every change +// ;; :epoch 1 ; only to break version ties +// :pkgdesc "Text editor for X11" +// :arch '(:x86-64) ; or '(:any) +// :url "https://example.com/foobar/" +// :license "Apache-2.0 WITH LLVM-exception" ; one SPDX expression +// ;; — dependencies — +// :depends '("glibc" "foobar>=1.8.0") +// :makedepends '("git") +// :checkdepends '("cmocka") +// :optdepends '("cups: printing support") +// ;; — relations — +// :provides '("foobar.so") ; the pkgname itself is implied +// :conflicts '("foobar-git") +// ;; — packaging — +// :backup '("etc/foobar.conf") ; relative, no leading slash +// :options '(:no-strip :docs) ; :no-x becomes !x for makepkg +// ;; — sources & integrity — +// :source '("foobar-2.5.tar.gz::https://example.com/2.5.tar.gz") +// :validpgpkeys '("3B2C6CE3A0FE1EC1D41E39A5F5A0A1B3C9D8E7F6") +// :b2sums '("...") +// ;; — build phases, as code — +// :prepare +// (lambda () +// (run "sed -i 's|/opt|/usr|' src/config.h")) +// :build +// (lambda () +// (run "cmake -B build -DCMAKE_INSTALL_PREFIX=/usr") +// (run "cmake --build build")) +// :check +// (lambda () +// (run "ctest --test-dir build")) +// :package +// (lambda () +// (run "cmake --install build DESTDIR=$pkgdir") +// ;; blip logic instead of fragile shell; for-each comes with the runner: +// (for-each (lambda (doc) +// (run "install -Dm644 ~A ~A/doc/foobar/~A" doc (pkgdir) doc)) +// (glob "docs/*.html")) +// (run "install -Dm644 LICENSE ~A/usr/share/licenses/foobar/LICENSE" (pkgdir))) +// ;; — .install hooks, inline; no separate .install file — +// :post-install +// (lambda (newver) +// (echo "Optional: run foobar-setup to configure autosave")) +// :post-upgrade +// (lambda (newver oldver) +// (echo (format "from ~a to ~a" oldver newver)) +// (run "systemctl try-restart foobar.service"))) +// +// the build translates that into a real PKGBUILD (and a .install when +// hooks are written) in a fresh work dir, where makepkg keeps everything as +// usual. +const lip_list_keys = [ + 'pkgname', + 'arch', + 'license', + 'depends', + 'makedepends', + 'checkdepends', + 'optdepends', + 'provides', + 'conflicts', + 'backup', + 'options', + 'source', + 'validpgpkeys', + 'b2sums', + 'sha256sums', +] + +const lip_phases = ['prepare', 'build', 'check', 'package'] + +const lip_hooks = ['pre-install', 'post-install', 'pre-upgrade', 'post-upgrade', 'pre-remove', + 'post-remove'] + +// lip_hook_arity is the versions pacman hands a .install scriptlet: the new +// version for installs and removes, new and then old for upgrades +fn lip_hook_arity(hook string) int { + if hook in ['pre-upgrade', 'post-upgrade'] { + return 2 + } + return 1 +} + +// lip_fn_name spells a hook as its .install function name: dashes are valid +// in a keyword, underscores are the .install convention +fn lip_fn_name(hook string) string { + return hook.replace('-', '_') +} + +// shell_quote wraps a value for the shell as one word, whatever it holds: +// single quotes around it, each quote inside closed, escaped and reopened. +// the one quoting vpac and the generated PKGBUILDs both use +pub fn shell_quote(s string) string { + return "'" + s.replace("'", "'\\''") + "'" +} + +// lip_tag_name is for error text: 'a keyword' reads better than a dump of the +// tag enum +fn lip_tag_name(t blip.Tag) string { + return match t { + .nil { 'nil' } + .boolean { 'a boolean' } + .integer { 'an integer' } + .float { 'a float' } + .rune { 'a character' } + .string { 'a string' } + .symbol { 'a symbol' } + .keyword { 'a keyword' } + .pair { 'a list' } + .emptylist { 'an empty list' } + .vector { 'a vector' } + .array { 'an array' } + .table { 'a table' } + .buffer { 'a buffer' } + .closure { 'a lambda' } + .primitive { 'a primitive' } + else { 'a struct' } + } +} + +// lip_items_of reads one plain item ("glibc", :any) or a list of them out of +// a value: a quoted list '("a" "b"), or a vector ["a" "b"]. lone keywords are +// allowed as items, matching the arch and options spellings, and the same +// reader takes a single item so a license does not have to hide in a list +fn lip_items_of(v blip.Value, what string) ![]string { + mut out := []string{} + match v.tag { + .string, .keyword, .symbol { + out << v.as_string() + } + .emptylist {} + .vector, .array { + for item in v.as_vector().data { + match item.tag { + .string, .keyword, .symbol { + out << item.as_string() + } + else { + return error('pkgbuild :${what}: items must be strings or keywords, not ${lip_tag_name(item.tag)}') + } + } + } + } + .pair { + mut cur := v + for cur.tag == .pair { + p := cur.as_pair() + match p.car.tag { + .string, .keyword, .symbol { + out << p.car.as_string() + } + else { + return error('pkgbuild :${what}: items must be strings or keywords, not ${lip_tag_name(p.car.tag)}') + } + } + cur = p.cdr + } + // a proper list ends in (): a dotted tail is an item the walk + // above would drop without a word + if cur.tag != .emptylist { + return error('pkgbuild :${what}: a list ends in (), not in a dotted ${lip_tag_name(cur.tag)}') + } + } + else { + return error('pkgbuild :${what} must be a string or a quoted list') + } + } + return out +} + +// lip_arch spells arches the way makepkg reads them: :x86-64 is x86_64 in the +// generated head, :any and everything else pass through +fn lip_arch(a string) string { + if a == 'x86-64' { + return 'x86_64' + } + return a +} + +// lip_option spells one of :options' entries the way makepkg's options array +// wants it: makepkg spells disabled options with a ! in front, and the lip's +// keyword for that is no-, so :no-strip becomes !strip; an enabled option and +// anything already in makepkg's own spelling pass through +fn lip_option(keyword string) string { + if keyword.starts_with('no-') { + return '!' + keyword[3..] + } + return keyword +} + +// lip_hex checks a checksum body: full hex for its own length, or SKIP, so a +// bad sum is named in the lip, not somewhere inside makepkg's diagnosis +fn lip_hex(s string, len int, what string) ! { + if s == 'SKIP' { + return + } + if s.len != len { + return error('${what}: ${s} is ${s.len} characters; ${what} entries are ${len} hex characters or SKIP') + } + for c in s { + if !c.is_hex_digit() { + return error('${what}: ${s} has a character that is not hex (${c.ascii_str()})') + } + } +} + +// lip_key40 checks a PGP fingerprint: the full 40 uppercase hex characters +fn lip_key40(s string, i int) ! { + if s.len != 40 { + return error('validpgpkeys: entry ${i} is ${s.len} characters; fingerprints are 40: the full uppercase one') + } + for c in s { + if !c.is_hex_digit() { + return error('validpgpkeys: entry ${i} has a character that is not hex (${c.ascii_str()})') + } + if c >= `a` && c <= `f` { + return error('validpgpkeys: entry ${i} is lowercase hex (${c.ascii_str()}); uppercase fingerprints only') + } + } +} + +// prim_defpkgbuild validates one (defpkgbuild ...) form and hands back a +// struct value: the scalars checked, the list keys normalised, and the phase +// and hook lambdas kept as the closures they evaluated to. the generator and +// the runner both read out of that one value. one (defpkgbuild ...) per file +// is checked by lip_defpkg_count when the file loads +fn prim_defpkgbuild(args []blip.Value) !blip.Value { + if args.len == 0 { + return error('pkgbuild: (defpkgbuild name ...) needs the name') + } + // the name can be the bare symbol (the format's spelling, pre-bound to + // its own string by the loader), a quoted symbol, or a string + if args[0].tag !in [.string, .symbol] { + return error('pkgbuild: the name is a symbol or a string, not ${lip_tag_name(args[0].tag)}') + } + pkgbase_name := args[0].as_string() + if (args.len - 1) % 2 != 0 { + return error('pkgbuild: :key and value come in pairs') + } + mut fields := []string{} + mut vals := map[string]blip.Value{} + fields << 'name' + vals['name'] = blip.string(pkgbase_name) + mut i := 1 + for i < args.len { + kv := args[i] + if kv.tag != .keyword { + return error('pkgbuild: expected a :key, got ${printer.write(kv)}') + } + key := kv.as_string() + val := args[i + 1] + if key in fields { + return error('pkgbuild :${key} is set twice') + } + if key in lip_list_keys { + mut items := lip_items_of(val, key)! + match key { + 'pkgname' { + if items.len == 0 { + return error('pkgbuild :pkgname must not be empty') + } + for it in items { + if it.contains(' ') { + return error('pkgbuild :pkgname: "${it}" has whitespace in it') + } + } + } + 'arch' { + if items.len == 0 { + return error('pkgbuild :arch must not be empty') + } + for j, it in items { + items[j] = lip_arch(it) + } + } + 'validpgpkeys' { + for j, it in items { + lip_key40(it, j)! + } + } + 'b2sums' { + for it in items { + lip_hex(it, 128, 'b2sums')! + } + } + 'sha256sums' { + for it in items { + lip_hex(it, 64, 'sha256sums')! + } + } + 'backup' { + for it in items { + if it.starts_with('/') { + return error('pkgbuild :backup: "${it}" is absolute; backup paths are relative, no leading slash') + } + } + } + else {} + } + mut item_vals := []blip.Value{} + for it in items { + item_vals << blip.string(it) + } + fields << key + vals[key] = blip.list_from(item_vals) + i += 2 + continue + } + if key in lip_phases || key in lip_hooks { + if val.tag != .closure { + return error('pkgbuild :${key} must be a (lambda ...); makepkg runs it as a function') + } + p := val.as_closure() + arity := if key in lip_hooks { lip_hook_arity(key) } else { 0 } + if p.params.len != arity { + return error('pkgbuild :${key} takes ${arity} parameter${if arity == 1 { + '' + } else { + 's' + }}, not ${p.params.len}') + } + fields << key + vals[key] = val + i += 2 + continue + } + match key { + 'pkgver' { + // a static version is written verbatim; a lambda is the pkgver() + // makepkg runs after the sources are unpacked, for VCS packages + if val.tag != .string && val.tag != .closure { + return error('pkgbuild :pkgver must be a string or a (lambda ...)') + } + fields << key + vals[key] = val + } + 'pkgrel', 'epoch' { + if val.tag != .integer { + return error('pkgbuild :${key} must be an integer') + } + if key == 'epoch' && val.as_int() < 0 { + return error('pkgbuild :epoch is negative; 0 means absent') + } + fields << key + vals[key] = val + } + 'pkgdesc', 'url' { + if val.tag != .string { + return error('pkgbuild :${key} must be a string') + } + fields << key + vals[key] = val + } + else { + // the keys makepkg knows, in the lip's spelling; anything else + // is an error here, where the lip names it + return error('pkgbuild has no key :${key}') + } + } + i += 2 + } + // the fields makepkg refuses to do without. build is not one: makepkg + // runs build() only when the PKGBUILD has one (a data package, the split + // smoke package, has none); package is, the one phase every package runs + for req in ['pkgname', 'pkgver', 'pkgrel', 'pkgdesc', 'arch', 'package'] { + if req !in fields { + return error('pkgbuild: :${req} is required') + } + } + return blip.struct_value('pkgbuild', fields, vals) +} + +// prim_run replaces every ~a in the format with the next argument — +// shell-quoted, so a path with spaces survives — and hands the line to the +// runner's own run helper +fn prim_run(args []blip.Value) !blip.Value { + run(lip_fmt(args)!)! + return blip.nil_value() +} + +// prim_glob spills the pattern into a blip vector, sorted, empty when nothing +// matches: the loop in the format example iterates it directly +fn prim_glob(args []blip.Value) !blip.Value { + if args.len != 1 || args[0].tag != .string { + return error('(glob pattern) takes one string pattern') + } + matches := glob(args[0].as_string())! + mut out := []blip.Value{} + for m in matches { + out << blip.string(m) + } + return blip.vector(out) +} + +// prim_pkgdir is (pkgdir): the directory makepkg is filling, which the +// generated function exports for the phase +fn prim_pkgdir(_ []blip.Value) !blip.Value { + p := os.getenv('VPAC_PKGDIR') + if p == '' { + return error('(pkgdir): only a value inside a pkgbuild phase; let the built PKGBUILD call it') + } + return blip.string(p) +} + +fn prim_srcdir(_ []blip.Value) !blip.Value { + p := os.getenv('VPAC_SRCDIR') + if p == '' { + return error('(srcdir): only a value inside a pkgbuild phase; let the built PKGBUILD call it') + } + return blip.string(p) +} + +fn prim_startdir(_ []blip.Value) !blip.Value { + p := os.getenv('VPAC_STARTDIR') + if p == '' { + return error('(startdir): only a value inside a pkgbuild phase; let the built PKGBUILD call it') + } + return blip.string(p) +} + +// prim_this_pkg is (this-pkg): the name a split lambda runs under — makepkg +// rebinds pkgname for every split while packaging +fn prim_this_pkg(_ []blip.Value) !blip.Value { + p := os.getenv('VPAC_PKGNAME') + if p == '' { + return error('(this-pkg): only a value inside a pkgbuild phase; let the built PKGBUILD call it') + } + return blip.string(p) +} + +// prim_git_desc is (git-desc pattern fallback?): git describe in the cwd the +// phase runs under ($srcdir, where makepkg runs its phases). the fallback +// comes out verbatim when describe finds nothing, so a young tree still has a +// version before its first tag +fn prim_git_desc(args []blip.Value) !blip.Value { + if args.len == 0 || args.len > 2 || args[0].tag != .string { + return error('(git-desc pattern fallback?) takes a string pattern and an optional string fallback') + } + pattern := args[0].as_string() + mut fallback := '' + if args.len == 2 { + if args[1].tag != .string { + return error('(git-desc ...): the fallback must be a string') + } + fallback = args[1].as_string() + } + return blip.string(git_desc(pattern, fallback)!) +} + +// lip_fmt renders the format for run: every ~a takes the next argument, +// shell-quoted, which is what the command needs to survive a path with +// spaces. echo needs none of it: blip's own echo prints plainly, and a hook +// that wants interpolation echoes (format "..." ~a) +fn lip_fmt(args []blip.Value) !string { + if args.len == 0 || args[0].tag != .string { + return error('run: the first argument is the format string') + } + // both spellings of the placeholder are welcome; blip's own format uses + // the lowercase one + fmt_text := args[0].as_string().replace('~A', '~a') + parts := fmt_text.split('~a') + if parts.len - 1 != args.len - 1 { + return error('run: the format has ${parts.len - 1} ~a for ${args.len - 1} argument${if args.len - 1 == 1 { + '' + } else { + 's' + }}') + } + mut out := parts[0] + mut j := 1 + for j < args.len { + arg := args[j] + mut rendered := '' + match arg.tag { + .string { + rendered = arg.as_string() + } + .integer { + rendered = arg.as_int().str() + } + else { + return error('run: argument ${j} is ${lip_tag_name(arg.tag)}; for a path call (pkgdir), (srcdir) or (startdir) and pass it as a ~a in the format') + } + } + rendered = shell_quote(rendered) + out += rendered + out += parts[j] + j++ + } + return out +} + +// lip_new_machine builds a machine with the pkgbuild prims registered +// (defpkgbuild among them). the bare package name is spelled the file's own +// way: the loader pre-binds it before the file loads, prim arg or not +fn lip_new_machine() !&machine.Machine { + mut m := machine.new_standalone(&host.ConsoleHost{}) + m.prims['defpkgbuild'] = prim_defpkgbuild + m.prims['run'] = prim_run + m.prims['glob'] = prim_glob + m.prims['pkgdir'] = prim_pkgdir + m.prims['srcdir'] = prim_srcdir + m.prims['startdir'] = prim_startdir + m.prims['this-pkg'] = prim_this_pkg + m.prims['git-desc'] = prim_git_desc + return m +} + +// lip_delim is true for a byte that ends a symbol: space, a bracket, or a +// comment's or string's opening +fn lip_delim(c u8) bool { + return c in [` `, `\t`, `\n`, `\r`, `(`, `)`, `[`, `]`, `{`, `}`, `;`, `"`] +} + +// lip_defpkg_forms finds the (defpkgbuild ...) forms in a lip's real text, +// blip's own spelling of comments and strings applied: `;` ends a line's +// text, `#|` opens a block comment nested to its `|#`, and a double-quoted +// string hides its contents, so `(defpkgbuild` named in one does not count. +// in code the form only opens at a word boundary, so a symbol with a longer +// name or one quoted into a string is not a second build of the package. +// each form is answered as the offset just past its `(defpkgbuild` +fn lip_defpkg_forms(src string) []int { + mut forms := []int{} + mut i := 0 + for i < src.len { + c := src[i] + if c == `;` { + for i < src.len && src[i] != `\n` { + i++ + } + continue + } + if c == `#` && i + 1 < src.len && src[i + 1] == `|` { + mut level := 1 + i += 2 + for i < src.len && level > 0 { + if src[i] == `#` && i + 1 < src.len && src[i + 1] == `|` { + level++ + i += 2 + } else if src[i] == `|` && i + 1 < src.len && src[i + 1] == `#` { + level-- + i += 2 + } else { + i++ + } + } + continue + } + if c == `"` { + i++ + for i < src.len { + if src[i] == `\\` && i + 1 < src.len { + i += 2 + continue + } + if src[i] == `"` { + i++ + break + } + i++ + } + continue + } + if c == `(` && src[i + 1..].starts_with('defpkgbuild') { + after := i + 1 + 'defpkgbuild'.len + // the symbol ends at space, bracket or end: a same-named text + // inside a bigger symbol name does not open a form + if after >= src.len || lip_delim(src[after]) { + forms << after + } + i = after + continue + } + i++ + } + return forms +} + +// lip_defpkg_name reads the (defpkgbuild name ...) symbol out of the file +// text. the machine evaluates a bare symbol, so the runner and the generator +// pre-bind the name under it before the file loads: the file keeps spelling +// the package bare, the format's own way. the form is found the way +// lip_defpkg_count finds it, so one named in a comment or a string binds +// nothing, and the name runs to the symbol's end, whatever a package name +// may hold (a dot, a plus, an at) +fn lip_defpkg_name(lip string) string { + src := os.read_file(lip) or { return '' } + forms := lip_defpkg_forms(src) + if forms.len == 0 { + return '' + } + mut j := forms[0] + for j < src.len && src[j] in [` `, `\n`, `\r`, `\t`] { + j++ + } + // a quoted or string spelling needs no trick + if j >= src.len || src[j] == `'` || src[j] == `"` { + return '' + } + mut end := j + for end < src.len && !lip_delim(src[end]) { + end++ + } + return src[j..end] +} + +// lip_defpkg_count counts the (defpkgbuild ...) forms in a lip's real text +fn lip_defpkg_count(path string) !int { + return lip_defpkg_forms(os.read_file(path)!).len +} + +// lip_load_in loads one lip into a machine that already has the prims, with +// the pre-bound name, and checks the last form is the defpkgbuild struct +fn lip_load_in(mut m machine.Machine, path string) !blip.Value { + // a lip that cannot be read fails here, with the read's own reason: the + // one-form check is never skipped on the way to a load that reads it + count := lip_defpkg_count(path) or { return error('${path}: ${err.msg()}') } + if count > 1 { + return error('${path}: one (defpkgbuild ...) form per file, not ${count}') + } + name := lip_defpkg_name(path) + if name != '' { + m.envs.define(m.globals, name, blip.string(name)) + } + v := m.load(path)! + if v.tag != .struct_ { + return error('${path}: the last form must be a (defpkgbuild ...)') + } + return v +} + +// lip_load evaluates a PKGBUILD.lip and returns the struct the defpkgbuild +// prim ran it into: the last form's value +pub fn lip_load(path string) !blip.Value { + mut m := lip_new_machine()! + return lip_load_in(mut m, path)! +} + +// lip_make is the one-liner callers want: load the lip, hand back everything +// the generated package needs (the PKGBUILD text, the .install when hooks +// exist, and whether pkgver floats) +pub fn lip_make(lip string, runner string) !LipBet { + meta := lip_load(lip)! + return lip_generate(meta, runner, lip, .lip)! +} + +// lip_run_phase is --lip-run [args...]: it loads the lip, wires +// the phase's closure under a fresh name, and calls it with the remaining +// arguments as the parameters. pkgver's result is the version, printed for +// makepkg's call to read; every other phase's result falls on the floor. a +// failure is nonzero, which fails the makepkg phase like a plain script would +pub fn lip_run_phase(lip string, phase string, params []string) ! { + mut m := lip_new_machine()! + // load on this machine, not lip_load's: the bootstrap macro has to be + // in the machine that runs the file, with its phases + meta := lip_load_in(mut m, lip)! + s := meta.as_struct() + if !s.has(phase) { + return error('${lip}: the pkgbuild has no :${phase}') + } + cb := s.get(phase) + if cb.tag != .closure { + return error('${lip}: :${phase} is not a (lambda ...)') + } + name := m.fresh('PKG-RUN') + m.envs.define(m.globals, name, cb) + mut arg_nodes := []blip.NodeId{} + for arg in params { + arg_nodes << m.string_node(arg) + } + call := m.call_node(m.sym_node(name), arg_nodes) + res := m.run([call])! + if phase == 'pkgver' { + if res.tag != .string { + return error('pkgver: the lambda ran into ${lip_tag_name(res.tag)}, not a version string') + } + println(res.as_string()) + } +} + +// lip_array_line writes a makepkg array: one quoted entry per line, in the +// order the lip declared them +fn lip_array_line(name string, items []string) string { + mut out := '${name}=(' + for it in items { + out += '\n ${shell_quote(it)}' + } + out += '\n)' + return out +} + +// LipKind says which file the phases live in: a lip runs through this +// binary's runner, a PKGBUILD.vsh runs through v itself +pub enum LipKind { + lip + vsh +} + +// delegate_line is the one bash line a phase wrapper hands the work to, per +// kind, with makepkg's own state exported for the runner +fn delegate_line(kind LipKind, phase string, extra string) string { + call := if kind == .lip { + '"\$VPAC_BLIP_RUN" --lip-run "\$VPAC_PKG_LIP" ${phase}' + } else { + '"\$VPAC_VSH_RUN" run "\$VPAC_PKG_VSH" ${phase}' + } + return ' export VPAC_PKGDIR="\$pkgdir" VPAC_SRCDIR="\$srcdir" VPAC_STARTDIR="\$startdir" VPAC_PKGNAME="\$pkgname" VPAC_PKGVER="\$pkgver" + ${call}${extra}' +} + +// lip_phase_fn writes one makepkg function that hands the phase to the +// runner. makepkg's own pkgdir, srcdir and startdir are readonly in its +// shell, so the wrapper exports fresh VPAC_ spellings instead: the runner's +// host primitives read those, and (run) re-exposes makepkg's spellings to +// every command it passes to sh, so the raw $pkgdir of a phase body keeps +// meaning exactly what makepkg says +fn lip_phase_fn(fn_name string, phase string, kind LipKind) string { + return '${fn_name}() { +${delegate_line(kind, phase, '')} +}' +} + +// lip_pkgver_fn writes pkgver() for VCS packages: makepkg captures its stdout +// as the new version, and runs it from $srcdir like the other phases +fn lip_pkgver_fn(kind LipKind) string { + return 'pkgver() { +${delegate_line(kind, 'pkgver', '')} +}' +} + +// lip_hook_fn writes one .install function: pacman passes the versions, the +// runner takes them as the lambda's parameters. libalpm sources the .install +// at install time in a shell of its own, where nothing of the PKGBUILD's — +// its VPAC_ variables, makepkg's pkgdir and srcdir — exists, so the runner +// and the script are written into the function as they were at the build, +// and the package's name is the one thing of makepkg's state handed on. a +// runner or a script that is gone by then is said and fails the scriptlet, +// where an empty command would have been a silent 127 +fn lip_hook_fn(hook string, kind LipKind, runner string, script_path string, pkgname string) string { + argv := lip_hook_arity(hook) + mut args := '' + if argv > 0 { + args = ' "\$1"' + } + if argv > 1 { + args += ' "\$2"' + } + r := shell_quote(runner) + s := shell_quote(script_path) + call := if kind == .lip { '${r} --lip-run ${s} ${hook}' } else { '${r} run ${s} ${hook}' } + gone := shell_quote('${pkgname}: the ${hook} hook needs ${runner} and ${script_path}, and one of them is gone') + return '${lip_fn_name(hook)}() { + if [ ! -x ${r} ] || [ ! -r ${s} ]; then + echo ${gone} >&2 + return 1 + fi + VPAC_PKGNAME=${shell_quote(pkgname)} ${call}${args} +}' +} + +// LipBet is one generated package: the PKGBUILD, the .install when hooks are +// there, and the base the files follow +pub struct LipBet { +pub mut: + text string + install string + dynamic bool + base string +} + +// lip_generate turns the defpkgbuild struct into the PKGBUILD text (and into +// a .install when hooks are written), pointing at this binary and at the +// original lip, wherever they were when the package was built +fn lip_generate(meta blip.Value, runner string, script_path string, kind LipKind) !LipBet { + s := meta.as_struct() + mut names := []string{} + if s.has('pkgname') { + names = lip_items_of(s.get('pkgname'), 'pkgname')! + } + pkgbase := names[0] + mut dynamic := false + pkgver := if s.has('pkgver') { + v := s.get('pkgver') + if v.tag == .string { + v.as_string() + } else { + dynamic = true + '0' + } + } else { + // the entry holds the pkgver function for vsh scripts, so the head + // gets the same 0 placeholder and pkgver() wrapper a lambda would + dynamic = true + '0' + } + rel := s.get('pkgrel').as_int() + mut out := []string{} + head_label := if kind == .lip { + 'from the lip; the lip is the source' + } else { + 'from PKGBUILD.vsh; the script is the source' + } + out << '# Generated by the vpac build ${head_label}' + if kind == .lip { + out << 'VPAC_BLIP_RUN=${shell_quote(runner)}' + out << 'VPAC_PKG_LIP=${shell_quote(script_path)}' + } else { + out << 'VPAC_VSH_RUN=${shell_quote(runner)}' + out << 'VPAC_PKG_VSH=${shell_quote(script_path)}' + } + out << '' + if names.len > 1 { + out << 'pkgbase=${shell_quote(pkgbase)}' + } + if names.len == 1 { + out << 'pkgname=${shell_quote(pkgbase)}' + } else { + out << lip_array_line('pkgname', names) + } + out << 'pkgver=${shell_quote(pkgver)}' + out << 'pkgrel=${rel}' + if s.has('epoch') && s.get('epoch').as_int() > 0 { + out << 'epoch=${s.get('epoch').as_int()}' + } + pkgdesc := s.get('pkgdesc').as_string() + out << 'pkgdesc=${shell_quote(pkgdesc)}' + arches := lip_items_of(s.get('arch'), 'arch')! + out << lip_array_line('arch', arches) + for opt in ['url', 'license'] { + if s.has(opt) { + items := lip_items_of(s.get(opt), opt)! + if opt == 'license' || items.len > 1 { + // makepkg says license must be an array: one entry or many + out << lip_array_line(opt, items) + } else { + out << '${opt}=${shell_quote(items[0])}' + } + } + } + for k in ['depends', 'makedepends', 'checkdepends', 'optdepends', 'provides', 'conflicts', + 'backup', 'options', 'source', 'validpgpkeys'] { + if s.has(k) { + items := lip_items_of(s.get(k), k)! + // the lip spells a disabled option :no-x, makepkg spells !x; a + // PKGBUILD.vsh's spec holds makepkg's own spelling already + worded := if kind == .lip && k == 'options' { items.map(lip_option) } else { items } + out << lip_array_line(k, worded) + } + } + for k in ['b2sums', 'sha256sums'] { + if s.has(k) { + out << lip_array_line(k, lip_items_of(s.get(k), k)!) + } + } + mut has_hooks := false + for h in lip_hooks { + if s.has(h) { + has_hooks = true + } + } + mut install_name := '' + if has_hooks { + install_name = '${pkgbase}.install' + out << 'install=${shell_quote(install_name)}' + } + out << '' + out << "# the phases run as the runner's own code above, nothing here is shell logic" + if dynamic { + out << lip_pkgver_fn(kind) + } + for ph in lip_phases { + if ph == 'package' { + continue + } + if s.has(ph) { + out << lip_phase_fn(ph, ph, kind) + } + } + // a shared :package lambda runs once per split: makepkg rebinds pkgname + // on the way through, so (this-pkg) says which split is being packed + for name in names { + fn_name := if names.len == 1 { 'package' } else { 'package_${name}' } + out << lip_phase_fn(fn_name, 'package', kind) + } + // the hooks are inline in the lip, and live in the package the world + // sees, as pacman's own .install contract expects + mut install := '' + if has_hooks { + mut lines := []string{} + lines << '#!/bin/sh' + lines << '# Generated by the vpac build: the hooks are the source, run through the runner' + for h in lip_hooks { + if s.has(h) { + lines << lip_hook_fn(h, kind, runner, script_path, pkgbase) + } + } + install = lines.join('\n') + '\n' + } + return LipBet{ + text: out.join('\n') + '\n' + install: install + dynamic: dynamic + base: pkgbase + } +} diff --git a/vmakepkg/lip_test.v b/vmakepkg/lip_test.v new file mode 100644 index 0000000..a2ab8b6 --- /dev/null +++ b/vmakepkg/lip_test.v @@ -0,0 +1,396 @@ +module vmakepkg + +import os + +// the generated head's spellings, checked against makepkg +fn test_lip_arch() { + assert lip_arch('x86-64') == 'x86_64' + assert lip_arch('any') == 'any' + assert lip_arch('x86') == 'x86' +} + +fn test_lip_option() { + assert lip_option('no-strip') == '!strip' + assert lip_option('docs') == 'docs' + assert lip_option('zipman') == 'zipman' + assert lip_option('no-docs') == '!docs' +} + +fn test_lip_hook_arity() { + assert lip_hook_arity('pre-install') == 1 + assert lip_hook_arity('post-remove') == 1 + assert lip_hook_arity('pre-upgrade') == 2 + assert lip_hook_arity('post-upgrade') == 2 +} + +fn test_lip_fn_name() { + assert lip_fn_name('pre-install') == 'pre_install' +} + +fn test_shell_quote() { + assert shell_quote("a 'b' c") == "'a '\\''b'\\'' c'" + assert shell_quote('plain') == "'plain'" +} + +fn test_shell_quote_round_trips_through_sh() { + // the property that matters: whatever the value holds, a shell reads it + // back as the one word it was — no expansion, no split, no command + for value in ["it's", '\$HOME', '`id`', '\$(id)', 'a b\tc', 'semi;colon', 'new\nline', 'back\\slash', + '"double"', "'", "''", '*', '-n', '', 'ünï'] { + res := os.exec(['sh', '-c', 'printf %s ' + shell_quote(value)]) + assert res.exit_code == 0, value + assert res.output == value, value + } +} + +// lip_make turns one lip into the PKGBUILD (and the .install) makepkg runs: +// its head is the head a real PKGBUILD spells, its phases delegate to the +// runner, and pkgver stays a static one when the lip's is +fn test_lip_make_golden() ! { + dir := os.join_path(os.vtmp_dir(), 'vpac_lip_make_golden_${os.getpid()}') + os.mkdir_all(dir)! + defer { + os.rmdir_all(dir) or {} + } + lip := os.join_path(dir, 'tiny.lip') + lines := [ + '(defpkgbuild tiny', + ' :pkgname "tiny"', + ' :pkgver "1.0"', + ' :pkgrel 3', + ' :pkgdesc "tiny golden package"', + " :arch '(:any)", + ' :depends \'("bash")', + " :options '(:no-strip :docs)", + ' :build', + ' (lambda () (run "true"))', + ' :package', + ' (lambda () (run "true"))', + ' :post-install', + ' (lambda (newver) (echo "done")))', + ] + os.write_file(lip, lines.join('\n'))! + + bb := lip_make(lip, '/vpac/runner')! + assert bb.base == 'tiny' + assert bb.dynamic == false + // the identity, spelled the way makepkg reads it + assert bb.text.contains("pkgname='tiny'") + assert bb.text.contains("pkgver='1.0'") + assert bb.text.contains('pkgrel=3') + assert bb.text.contains("pkgdesc='tiny golden package'") + assert bb.text.contains("arch=(\n 'any'\n)") + // lists carry one quoted entry a line, and the lip's :no-x becomes + // makepkg's !x + assert bb.text.contains('depends=(') && bb.text.contains(" 'bash'") + assert bb.text.contains("options=(\n '!strip'\n 'docs'\n)") + // the phases call this binary back with the lip they came from + assert bb.text.contains("VPAC_BLIP_RUN='/vpac/runner'") + assert bb.text.contains("VPAC_PKG_LIP='${lip}'") + assert bb.text.contains('build() {\n export') + assert bb.text.contains('package() {\n export') + // a static pkgver runs no pkgver() + assert !bb.text.contains('pkgver()') + // the hooks are the .install the head names, run through the runner + assert bb.install.starts_with('#!/bin/sh') + assert bb.text.contains("install='tiny.install'") + // libalpm sources the .install in a shell of its own: the runner and + // the lip stand in it literally, nothing is read from the PKGBUILD's + // variables, and a missing one is said + assert bb.install.contains("VPAC_PKGNAME='tiny' '/vpac/runner' --lip-run '${lip}' post-install \"\$1\"\n"), bb.install + assert bb.install.contains("if [ ! -x '/vpac/runner' ] || [ ! -r '${lip}' ]; then") + assert !bb.install.contains('\$VPAC_') && !bb.install.contains('\$pkgdir') + // and the function is sh that runs: with no runner there it fails aloud + install_file := os.join_path(dir, 'tiny.install') + os.write_file(install_file, bb.install)! + hook := os.exec(['sh', '-c', '. "\$0"; post_install 1.0 2>&1', install_file]) + assert hook.exit_code == 1 && hook.output.contains('one of them is gone'), hook.output +} + +// a pkgver lambda makes the package a VCS one: pkgver() is generated for +// makepkg to call, and the head carries the placeholder it replaces +fn test_lip_make_dynamic_pkgver() ! { + dir := os.join_path(os.vtmp_dir(), 'vpac_lip_make_dyn_${os.getpid()}') + os.mkdir_all(dir)! + defer { + os.rmdir_all(dir) or {} + } + lip := os.join_path(dir, 'tiny.lip') + lines := [ + '(defpkgbuild tiny', + ' :pkgname "tiny"', + ' :pkgver (lambda () "unused")', + ' :pkgrel 1', + ' :pkgdesc "tiny vcs package"', + " :arch '(:any)", + ' :build', + ' (lambda () (run "true"))', + ' :package', + ' (lambda () (run "true")))', + ] + os.write_file(lip, lines.join('\n'))! + bb := lip_make(lip, '/vpac/runner')! + assert bb.dynamic + assert bb.text.contains("pkgver='0'") + assert bb.text.contains('pkgver() {\n export') +} + +// lip_defpkg_count counts real (defpkgbuild ...) forms: comments of either +// kind stay out, block comments stay out, a string's mention of the form +// stays out, and a longer symbol whose name begins equally is no form +fn test_lip_defpkg_count() { + dir := os.join_path(os.vtmp_dir(), 'vpac_lip_count_${os.getpid()}') + os.mkdir_all(dir)! + defer { + os.rmdir_all(dir) or {} + } + p := os.join_path(dir, 'count.lip') + os.write_file(p, '(defpkgbuild foo\n)')! + assert lip_defpkg_count(p)! == 1 + os.write_file(p, '(defpkgbuild foo\n)\n(defpkgbuild bar\n)')! + assert lip_defpkg_count(p)! == 2 + os.write_file(p, ';; a comment names (defpkgbuild x)\n(defpkgbuild foo\n)')! + assert lip_defpkg_count(p)! == 1 + os.write_file(p, '(defpkgbuild foo ; inline ends the text (defpkgbuild y)\n)')! + assert lip_defpkg_count(p)! == 1 + os.write_file(p, '#| (defpkgbuild z) reduces the block |#\n(defpkgbuild foo\n)')! + assert lip_defpkg_count(p)! == 1 + // a string's mention of the form stays out: the ('no form counts') text + // spells one whole (defpkgbuild ...) inside a string + os.write_file(p, '(defpkgbuild foo\n :defpkgdesc "the string names (defpkgbuild x) whole"\n)')! + assert lip_defpkg_count(p)! == 1 + os.write_file(p, '(defpkg-build foo\n)')! + assert lip_defpkg_count(p)! == 0 + os.write_file(p, '(defpkgbuildy foo\n)')! + assert lip_defpkg_count(p)! == 0 +} + +// the name pre-bound is the real form's: one named in a comment or a string +// before it binds nothing, and the name runs to the symbol's end +fn test_lip_defpkg_name() { + dir := os.join_path(os.vtmp_dir(), 'vpac_lip_name_${os.getpid()}') + os.mkdir_all(dir)! + defer { + os.rmdir_all(dir) or {} + } + p := os.join_path(dir, 'name.lip') + os.write_file(p, '(defpkgbuild foo-bar\n)')! + assert lip_defpkg_name(p) == 'foo-bar' + os.write_file(p, ';; write (defpkgbuild wrong ...) below\n#| (defpkgbuild also-wrong) |#\n(defpkgbuild right\n)')! + assert lip_defpkg_name(p) == 'right' + os.write_file(p, '(defpkgbuild lib.so+x@1)')! + assert lip_defpkg_name(p) == 'lib.so+x@1' + os.write_file(p, '(defpkgbuild "quoted"\n)')! + assert lip_defpkg_name(p) == '' + os.write_file(p, ';; no form at all')! + assert lip_defpkg_name(p) == '' +} + +fn test_lip_load_unreadable() ! { + dir := os.join_path(os.vtmp_dir(), 'vpac_lip_unreadable_${os.getpid()}') + os.mkdir_all(dir)! + defer { + os.rmdir_all(dir) or {} + } + // no file at all, and a directory where the file should be: each fails + // with the read's reason and the path, not a later, other complaint + for p in [os.join_path(dir, 'missing.lip'), dir] { + lip_load(p) or { + assert err.msg().starts_with('${p}: '), err.msg() + assert !err.msg().contains('defpkgbuild'), err.msg() + continue + } + assert false, '${p} loaded' + } + // two forms in a readable file are still the one-form error + two := os.join_path(dir, 'two.lip') + os.write_file(two, '(defpkgbuild foo\n)\n(defpkgbuild bar\n)')! + lip_load(two) or { + assert err.msg().contains('one (defpkgbuild ...) form per file, not 2'), err.msg() + return + } + assert false, 'two forms loaded' +} + +// read_items reads what lip_items_of makes of a blip expression's value +fn read_items(src string) ![]string { + mut m := lip_new_machine()! + return lip_items_of(m.run_str(src)!, 'depends')! +} + +fn test_lip_items_of_every_spelling() ! { + // one item, as a string, a keyword or a symbol + assert read_items('"glibc"')! == ['glibc'] + assert read_items(':any')! == ['any'] + assert read_items("'zsh")! == ['zsh'] + // a quoted list, a vector, and the empty one + assert read_items('\'("a" "b" :c)')! == ['a', 'b', 'c'] + assert read_items('["a" "b" :c]')! == ['a', 'b', 'c'] + assert read_items("'()")! == []string{} + assert read_items('[]')! == []string{} + // a list's items are plain: a number among them is said, in both kinds + for src in ['\'("a" 1)', '["a" 1]'] { + read_items(src) or { + assert err.msg().contains('items must be strings or keywords'), err.msg() + continue + } + assert false, '${src} was read' + } + // a dotted tail is no list: its last item would be dropped silently. + // blip's reader has no dotted syntax ('.' is a symbol), so cons makes one + read_items('(cons "a" "b")') or { + assert err.msg().contains('a list ends in ()'), err.msg() + return + } + assert false, 'a dotted list was read' +} + +fn test_lip_vector_lists_reach_the_pkgbuild() ! { + dir := os.join_path(os.vtmp_dir(), 'vpac_lip_vector_${os.getpid()}') + os.mkdir_all(dir)! + defer { + os.rmdir_all(dir) or {} + } + // the lists spelled as vectors, where the golden lip quotes them + lip := os.join_path(dir, 'vec.lip') + lines := [ + '(defpkgbuild vec', + ' :pkgname "vec"', + ' :pkgver "1.0"', + ' :pkgrel 1', + ' :pkgdesc "vector lists"', + ' :arch [:any]', + ' :depends ["glibc" "zsh"]', + ' :license ["MIT"]', + ' :build (lambda () (run "true"))', + ' :package (lambda () (run "true")))', + ] + os.write_file(lip, lines.join('\n'))! + bb := lip_make(lip, '/vpac/runner')! + // the generator writes an array an item a line + assert bb.text.contains("depends=(\n 'glibc'\n 'zsh'\n)"), bb.text + assert bb.text.contains("arch=(\n 'any'\n)"), bb.text + assert bb.text.contains("license=(\n 'MIT'\n)"), bb.text +} + +// valid_lip is a lip every field of which is right; the corpus below breaks +// one thing at a time +const valid_lip = ['(defpkgbuild corpus', ' :pkgname "corpus"', ' :pkgver "1.0"', ' :pkgrel 1', + ' :pkgdesc "a corpus base"', " :arch '(:any)", ' :build (lambda () (run "true"))', + ' :package (lambda () (run "true")))'] + +// LipCase is a lip broken one way, and what the validator says about it +struct LipCase { + what string + text string + says string +} + +// broken replaces the line of valid_lip that starts with key's spelling, or +// appends extra before the closing parenthesis when key is '' +fn broken(key string, line string) string { + mut lines := valid_lip.clone() + if key == '' { + // the last line ends in defpkgbuild's own ')': the new line takes it + last := lines[lines.len - 1] + lines[lines.len - 1] = last[..last.len - 1] + lines << line + ')' + return lines.join('\n') + } + for i, l in lines { + if l.trim_space().starts_with(':${key} ') { + lines[i] = line + if i == lines.len - 1 { + lines[i] += ')' + } + } + } + return lines.join('\n') +} + +fn test_lip_validation_corpus() ! { + dir := os.join_path(os.vtmp_dir(), 'vpac_lip_corpus_${os.getpid()}') + os.mkdir_all(dir)! + defer { + os.rmdir_all(dir) or {} + } + // the base itself is good + base := os.join_path(dir, 'base.lip') + os.write_file(base, valid_lip.join('\n'))! + lip_make(base, '/vpac/runner')! + + hex64 := 'ab'.repeat(32) + for c in [ + LipCase{'no name', '(defpkgbuild)', 'needs the name'}, + LipCase{'a number for a name', valid_lip.join('\n').replace('(defpkgbuild corpus', '(defpkgbuild 7'), 'the name is a symbol or a string, not'}, + LipCase{'a key without its value', broken('', ' :url'), ':key and value come in pairs'}, + LipCase{'a value where a key goes', broken('', ' "stray" "pair"'), 'expected a :key, got "stray"'}, + LipCase{'a key twice', broken('', ' :pkgrel 2'), ':pkgrel is set twice'}, + LipCase{'an empty name list', broken('pkgname', " :pkgname '()"), ':pkgname must not be empty'}, + LipCase{'a name with a space', broken('pkgname', ' :pkgname "cor pus"'), 'has whitespace in it'}, + LipCase{'no arch', broken('arch', " :arch '()"), ':arch must not be empty'}, + LipCase{'a short b2sum', broken('', ' :b2sums \'("abc")'), 'b2sums: abc is 3 characters; b2sums entries are 128 hex characters or SKIP'}, + LipCase{'a sha256 that is not hex', broken('', ' :sha256sums \'("${'zz'.repeat(32)}")'), 'has a character that is not hex (z)'}, + LipCase{'a short fingerprint', broken('', ' :validpgpkeys \'("ABCDEF")'), 'validpgpkeys: entry 0 is 6 characters'}, + LipCase{'a lowercase fingerprint', broken('', ' :validpgpkeys \'("${'ab'.repeat(20)}")'), 'uppercase fingerprints only'}, + LipCase{'an absolute backup', broken('', ' :backup \'("/etc/x.conf")'), 'is absolute; backup paths are relative'}, + LipCase{'a phase that is no lambda', broken('build', ' :build "make"'), ':build must be a (lambda ...)'}, + LipCase{'a phase with a parameter', broken('build', ' :build (lambda (x) (run "true"))'), ':build takes 0 parameters, not 1'}, + LipCase{'a hook with no version', broken('', ' :post-install (lambda () (run "true"))'), ':post-install takes 1 parameter, not 0'}, + LipCase{'an upgrade hook with one version', broken('', ' :post-upgrade (lambda (new) (run "true"))'), ':post-upgrade takes 2 parameters, not 1'}, + LipCase{'a pkgver that is a number', broken('pkgver', ' :pkgver 3'), ':pkgver must be a string or a (lambda ...)'}, + LipCase{'a pkgrel in quotes', broken('pkgrel', ' :pkgrel "1"'), ':pkgrel must be an integer'}, + LipCase{'a negative epoch', broken('', ' :epoch -1'), 'epoch is negative'}, + LipCase{'a pkgdesc that is a number', broken('pkgdesc', ' :pkgdesc 5'), ':pkgdesc must be a string'}, + LipCase{'an unknown key', broken('', ' :pkgdescription "x"'), 'has no key :pkgdescription'}, + LipCase{'a dotted list', broken('', ' :depends (cons "a" "b")'), 'a list ends in ()'}, + LipCase{'no pkgdesc', broken('pkgdesc', ''), ':pkgdesc is required'}, + LipCase{'no package', broken('package', ' :url "https://example.org"'), ':package is required'}, + ] { + p := os.join_path(dir, 'case.lip') + os.write_file(p, c.text)! + lip_make(p, '/vpac/runner') or { + assert err.msg().contains(c.says), '${c.what}: ${err.msg()}' + continue + } + assert false, '${c.what} was taken:\n${c.text}' + } + // the right lengths and SKIP pass + ok := os.join_path(dir, 'sums.lip') + os.write_file(ok, broken('', ' :sha256sums \'("${hex64}" "SKIP")'))! + lip_make(ok, '/vpac/runner')! +} + +fn test_lip_make_split_golden() ! { + // the split smoke package: two pkgnames, one shared package lambda that + // asks (this-pkg) which split it runs for + lip := os.join_path(@VMODROOT, 'pkgs', 'lipsplit', 'PKGBUILD.lip') + bb := lip_make(lip, '/vpac/runner')! + assert bb.base == 'lipsplit' + assert bb.text.contains("pkgbase='lipsplit'"), bb.text + assert bb.text.contains("pkgname=(\n 'lipsplit'\n 'lipsplit-doc'\n)"), bb.text + // one package function per split, named as makepkg calls it + // (package_$pkgname, the hyphen and all), each running the shared lambda + for name in ['lipsplit', 'lipsplit-doc'] { + assert bb.text.contains('package_${name}() {'), bb.text + } + assert !bb.text.contains('\npackage() {'), bb.text + // no build phase in the lip: none in the PKGBUILD, which makepkg allows + assert !bb.text.contains('build() {'), bb.text + assert bb.install == '' +} + +fn test_lip_without_a_build_phase() ! { + // a data package: no :build, as makepkg allows; the PKGBUILD gets no + // build() wrapper, and still its package() + dir := os.join_path(os.vtmp_dir(), 'vpac_lip_nobuild_${os.getpid()}') + os.mkdir_all(dir)! + defer { + os.rmdir_all(dir) or {} + } + p := os.join_path(dir, 'data.lip') + os.write_file(p, broken('build', ''))! + bb := lip_make(p, '/vpac/runner')! + assert !bb.text.contains('build() {'), bb.text + assert bb.text.contains('package() {'), bb.text +} diff --git a/vmakepkg/vsh.v b/vmakepkg/vsh.v new file mode 100644 index 0000000..24ec85d --- /dev/null +++ b/vmakepkg/vsh.v @@ -0,0 +1,461 @@ +module vmakepkg + +import os +import blip.vlib.blip + +// ------------------------------------------------------------ PKGBUILD.vsh +// +// PKGBUILD.vsh is the same package written as a plain V script, with the +// phases as ordinary V functions: +// +// import vmakepkg +// import os +// +// fn spec() !vmakepkg.Spec { +// return vmakepkg.Spec{ +// pkgname: 'foobar' +// pkgver: '2.5' +// pkgrel: 2 +// pkgdesc: 'Text editor for X11' +// arch: ['x86_64'] +// url: 'https://example.com/foobar/' +// license: 'Apache-2.0' +// depends: ['glibc'] +// options: ['!strip' 'docs'] +// source: ['foobar-2.5.tar.gz::https://example.com/2.5.tar.gz'] +// b2sums: ['...'] +// hooks: ['post-install'] +// } +// } +// +// fn build() ! { +// vmakepkg.run('cmake -B build -DCMAKE_INSTALL_PREFIX=/usr')! +// vmakepkg.run('cmake --build build')! +// } +// +// fn package() ! { +// vmakepkg.run('cmake --install build DESTDIR=' + vmakepkg.pkgdir()!)! +// } +// +// fn post_install(v []string) ! { +// println('hint: run foobar-setup once') +// } +// +// vmakepkg.vsh_entry( +// spec: spec +// build: build +// package: package +// hooks: {'post-install': post_install} +// ) or { eprintln(err); exit(1) } +// +// `v run PKGBUILD.vsh generate` writes the PKGBUILD (and the .install +// beside the script), with the same head validation and phase wrappers the +// lip format gets, delegating to `v run PKGBUILD.vsh `. a +// `pkgver: fn () string` in the entry makes it a VCS package the same way a +// pkgver lambda does for the lip. +// +// the writers for the phases are the runners' own helpers: vmakepkg.run +// shells a line out with makepkg's spellings restored, vmakepkg.pkgdir and +// friends read the values makepkg exported for the running phase. + +// Spec is a vsh package's head, the same fields the lip format reads +pub struct Spec { +pub mut: + pkgname string + pkgnames []string + pkgver string + pkgrel i64 + epoch i64 + pkgdesc string + arch []string + url string + license string + depends []string + makedepends []string + checkdepends []string + optdepends []string + provides []string + conflicts []string + backup []string + options []string + source []string + validpgpkeys []string + b2sums []string + sha256sums []string + hooks []string +} + +// spec_names reads pkgname from a spec: the bare name or the split list. +// both spellings together are one intent, so the same name is not repeated, +// the order of first mention kept +fn spec_names(s &Spec) ![]string { + mut named := []string{} + if s.pkgname != '' { + named << s.pkgname + } + named << s.pkgnames + mut out := []string{} + for it in named { + if it in out { + continue + } + out << it + } + if out.len == 0 { + return error('pkgbuild: :pkgname is required') + } + for it in out { + if it.contains(' ') { + return error('pkgbuild :pkgname: "${it}" has whitespace in it') + } + } + return out +} + +// lip_list wraps string items into a blip list, the shape the head reader +// walks for the array fields +fn lip_list(items []string) blip.Value { + mut out := []blip.Value{} + for it in items { + out << blip.string(it) + } + return blip.list_from(out) +} + +// spec_meta hands the spec to the same head the lip format walks, as one +// struct value: the lists normalised, the sums and fingerprints checked, and +// the phases and hooks the script carries named, so lip_generate tells one +// truth about both kinds. `have` says which phases and hooks the entry +// carries, since the head only prints wrappers the script can answer +fn spec_meta(s &Spec, have map[string]bool) !blip.Value { + mut vals := map[string]blip.Value{} + names := spec_names(s)! + // name is the pkgbase, the canonical first of the names: for a + // split-only spec the bare pkgname spelling is empty and this is what + // carries one + vals['name'] = blip.string(names[0]) + vals['pkgname'] = lip_list(names) + if s.pkgver != '' { + vals['pkgver'] = blip.string(s.pkgver) + } + vals['pkgrel'] = blip.integer(s.pkgrel) + // as the lip's :epoch: 0 means absent, and a negative one is a mistake + // to say, not an epoch to leave out + if s.epoch < 0 { + return error('pkgbuild :epoch is negative; 0 means absent') + } + if s.epoch > 0 { + vals['epoch'] = blip.integer(s.epoch) + } + if s.pkgdesc == '' { + return error('pkgbuild: :pkgdesc is required') + } + vals['pkgdesc'] = blip.string(s.pkgdesc) + if s.arch.len == 0 { + return error('pkgbuild: :arch is required') + } + mut arches := []string{} + for a in s.arch { + arches << lip_arch(a) + } + vals['arch'] = lip_list(arches) + if s.url != '' { + vals['url'] = blip.string(s.url) + } + if s.license != '' { + vals['license'] = blip.string(s.license) + } + map2 := { + 'depends': s.depends + 'makedepends': s.makedepends + 'checkdepends': s.checkdepends + 'optdepends': s.optdepends + 'provides': s.provides + 'conflicts': s.conflicts + 'options': s.options + 'source': s.source + } + for key, items in map2 { + if items.len > 0 { + vals[key] = lip_list(items) + } + } + if s.backup.len > 0 { + for b in s.backup { + if b.starts_with('/') { + return error('pkgbuild :backup: "${b}" is absolute; backup paths are relative, no leading slash') + } + } + vals['backup'] = lip_list(s.backup) + } + if s.validpgpkeys.len > 0 { + for i, k in s.validpgpkeys { + lip_key40(k, i)! + } + vals['validpgpkeys'] = lip_list(s.validpgpkeys) + } + if s.b2sums.len > 0 { + for it in s.b2sums { + lip_hex(it, 128, 'b2sums')! + } + vals['b2sums'] = lip_list(s.b2sums) + } + if s.sha256sums.len > 0 { + for it in s.sha256sums { + lip_hex(it, 64, 'sha256sums')! + } + vals['sha256sums'] = lip_list(s.sha256sums) + } + for phase in ['prepare', 'build', 'check', 'package', 'pkgver'] { + if have[phase] { + vals[phase] = blip.nil_value() + } + } + for h in s.hooks { + if h !in lip_hooks { + return error('pkgbuild hooks: :${h} is not a hook makepkg knows') + } + if !have[h] { + return error('pkgbuild hooks: the entry holds no ${h} body') + } + vals[h] = blip.nil_value() + } + return blip.struct_value('pkgbuild', vals.keys(), vals) +} + +// lip_make_from_spec generates the PKGBUILD (and a .install when hooks are +// carried) from a PKGBUILD.vsh's spec and its entry's phase inventory, +// delegating the phases to `v run` against the script itself +pub fn lip_make_from_spec(s &Spec, runner string, script_path string, have map[string]bool) !LipBet { + meta := spec_meta(s, have)! + return lip_generate(meta, runner, script_path, .vsh)! +} + +// run shells one line out with sh, carrying makepkg's spellings of its state +// into the child shell, like the runner's (run) does from the lip side: the +// phase exported them for this process under the VPAC_ names +pub fn run(cmd string) ! { + // the names reach the shell as env's arguments and the line as sh's: no + // quoting stands between them and the child. the line itself is shell, + // as the script writes it + mut args := ['env'] + pairs := [['pkgdir', 'VPAC_PKGDIR'], ['srcdir', 'VPAC_SRCDIR'], ['startdir', 'VPAC_STARTDIR'], + ['pkgname', 'VPAC_PKGNAME'], ['pkgver', 'VPAC_PKGVER']] + for pair in pairs { + v := os.getenv(pair[1]) + if v != '' { + args << '${pair[0]}=${v}' + } + } + args << ['sh', '-c', cmd] + res := os.system_args(args) + if res != 0 { + return error('run: exit code ${res} from: ${cmd}') + } +} + +// pkgdir is the directory makepkg is filling during the package phase, the +// value of $pkgdir, exported for the phase as VPAC_PKGDIR +pub fn pkgdir() !string { + p := os.getenv('VPAC_PKGDIR') + if p == '' { + return error('pkgdir: the runner only exports it inside a makepkg phase') + } + return p +} + +// srcdir is where the sources were unpacked, $srcdir +pub fn srcdir() !string { + p := os.getenv('VPAC_SRCDIR') + if p == '' { + return error('srcdir: the runner only exports it inside a makepkg phase') + } + return p +} + +// startdir is the build script's own directory, $startdir +pub fn startdir() !string { + p := os.getenv('VPAC_STARTDIR') + if p == '' { + return error('startdir: the runner only exports it inside a makepkg phase') + } + return p +} + +// this_pkg is the split a shared package function is packing right now, +// $pkgname, exported for the phase as VPAC_PKGNAME +pub fn this_pkg() !string { + p := os.getenv('VPAC_PKGNAME') + if p == '' { + return error('this_pkg: the runner only exports it inside a makepkg phase') + } + return p +} + +// glob spills one pattern into a sorted list of matches, empty when nothing +// matches +pub fn glob(pattern string) ![]string { + return os.glob(pattern)! +} + +// git_desc runs git describe in the cwd the phase runs under (srcdir, where +// makepkg runs its phases); the fallback comes out verbatim when describe +// finds nothing, so a young tree still has a version before its first tag +pub fn git_desc(pattern string, fallback string) !string { + res := os.exec(['git', '--no-pager', 'describe', '--long', '--tags', '--match', pattern]) + if res.exit_code != 0 { + if fallback != '' { + return fallback + } + return error('git-desc: git describe failed for ${pattern}: ${res.output.trim_space()}') + } + return res.output.trim_space() +} + +// VshEntry is what a PKGBUILD.vsh hands to vsh_entry: the spec, the phase +// functions, and the hooks by name. generate needs the spec, and makepkg +// needs package (build only when the package has one, as makepkg's build()): +// the entry says so if the script leaves one out +@[params] +pub struct VshEntry { +pub mut: + spec ?fn () !Spec + pkgver ?fn () string + prepare ?fn () ! + build ?fn () ! + check ?fn () ! + package ?fn () ! + hooks map[string]fn ([]string) ! +} + +// vsh_entry is the PKGBUILD.vsh runner, the script's one last line: with the +// generate argument it writes the PKGBUILD and the .install beside the +// script, and otherwise it runs one phase with the arguments pacman or the +// phase wrapper hands it. a failing phase exits nonzero, the way a makepkg +// phase would +pub fn vsh_entry(e VshEntry) ! { + // VPAC_VSH_PATH carries the script's own path: `v run` does not say which + // script called in a way the writer can trust + vsh_run(e, os.args#[1..], os.getenv('VPAC_VSH_PATH'))! +} + +// vsh_run is vsh_entry with the command line and the script's path handed +// in: args are what follows the script's name, the phase first +fn vsh_run(e VshEntry, args []string, script_path string) ! { + phase := if args.len > 0 { args[0] } else { '' } + match phase { + 'generate' { + if script_path == '' { + return error("generate: VPAC_VSH_PATH must hold the script's path") + } + spec := e.spec or { return error('pkgbuild: a :spec is required') } + s := spec()! + // build is optional, as makepkg's build() is; package is not + if e.package == none { + return error('pkgbuild: a :package phase is required') + } + if e.pkgver == none && s.pkgver == '' { + return error('pkgbuild: :pkgver is required') + } + for h in s.hooks { + if h !in e.hooks { + return error('pkgbuild hooks: the entry holds no ${h} body') + } + } + // hooks in the entry that the spec does not list stay a typo + for name in e.hooks.keys() { + if name !in s.hooks { + return error('pkgbuild hooks: the spec does not list :${name}') + } + } + mut have := map[string]bool{} + if e.prepare != none { + have['prepare'] = true + } + if e.pkgver != none { + have['pkgver'] = true + } + for hook in e.hooks.keys() { + have[hook] = true + } + if e.build != none { + have['build'] = true + } + if e.check != none { + have['check'] = true + } + // package is makepkg's ground truth, so its wrapper always lands + have['package'] = true + // the runner the wrappers bake is the persistent v, not this + // process's temp binary: the root side carries it as VPAC_V + vpath := if os.getenv('VPAC_V') != '' { + os.getenv('VPAC_V') + } else { + os.find_abs_path_of_executable('v') or { + return error('generate: the v compiler is not in the path') + } + } + bb := lip_make_from_spec(s, vpath, script_path, have)! + out_dir := os.dir(script_path) + os.write_file('${out_dir}/PKGBUILD', bb.text)! + if bb.install != '' { + os.write_file('${out_dir}/${bb.base}.install', bb.install)! + } + mut wrote := '${out_dir}/PKGBUILD' + if bb.install != '' { + wrote += ' and ${bb.base}.install' + } + println('wrote ${wrote}') + } + 'pkgver' { + if f := e.pkgver { + out := f() + if out == '' { + return error('pkgver: it returned an empty version') + } + println(out) + } else { + return error('pkgver: the entry holds no pkgver function') + } + } + 'prepare' { + if f := e.prepare { + f()! + } else { + return error('prepare: the entry holds no prepare function') + } + } + 'build' { + if f := e.build { + f()! + } else { + return error('build: the entry holds no build function') + } + } + 'check' { + if f := e.check { + f()! + } else { + return error('check: the entry holds no check function') + } + } + 'package' { + if f := e.package { + f()! + } else { + return error('package: the entry holds no package function') + } + } + else { + // no argument: the usage, not a call that lost its phase quietly + if phase == '' { + return error('vsh: give an argument: generate to write the PKGBUILD, or one of the phases (build, check, package, pkgver) or hooks') + } + if phase in e.hooks { + e.hooks[phase](args[1..])! + return + } + return error('vsh: "${phase}" is neither generate, a phase, nor a hook') + } + } +} diff --git a/vmakepkg/vsh_test.v b/vmakepkg/vsh_test.v new file mode 100644 index 0000000..2a1e464 --- /dev/null +++ b/vmakepkg/vsh_test.v @@ -0,0 +1,358 @@ +module vmakepkg + +import os + +// spec_names is the bare pkgname or the split list: both spellings together +// name one intent, so nothing is named twice, and the first mention's place +// is kept +fn test_spec_names() ! { + // the usual spellings, alone and split + assert spec_names(&Spec{ pkgname: 'foobar' })! == ['foobar'] + assert spec_names(&Spec{ pkgnames: ['foo', 'bar'] })! == ['foo', 'bar'] + // a bare name repeated in the split list is one name + assert spec_names(&Spec{ pkgname: 'foo', pkgnames: ['foo', 'bar'] })! == ['foo', 'bar'] + // and a split list of repeats is one each, in first-mention order + assert spec_names(&Spec{ pkgnames: ['a', 'b', 'a', 'c', 'b'] })! == ['a', 'b', 'c'] + // white space in a name is a mistake the lip format refuses too + if _ := spec_names(&Spec{ pkgname: 'foo bar' }) { + assert false, 'a name with whitespace was taken' + } else { + assert err.msg().contains('whitespace'), err.msg() + } +} + +// no name at all is no package +fn test_spec_names_requires_a_name() { + if _ := spec_names(&Spec{ pkgnames: []string{} }) { + assert false, 'a nameless spec was taken' + } else { + assert err.msg().contains('pkgname is required'), err.msg() + } +} + +// spec_meta's name is the pkgbase, the first of the canonical names: for a +// split-only spec the bare pkgname spelling is empty, and this is what +// carries one +fn test_spec_meta_name_is_the_pkgbase() ! { + mut s := Spec{ + pkgnames: ['pkg-a', 'pkg-b'] + pkgver: '2.5' + pkgrel: 2 + pkgdesc: 'a split package' + arch: ['any'] + } + have := map[string]bool{ + 'build': true + 'package': true + } + meta := spec_meta(&s, have)! + st := meta.as_struct() + // the head walks a list for :pkgname; name stays the base + names := lip_items_of(st.get('pkgname'), 'pkgname')! + assert names == ['pkg-a', 'pkg-b'] + assert st.get('name').as_string() == 'pkg-a' +} + +// Calls records which of an entry's functions ran, with what +@[heap] +struct Calls { +mut: + ran []string + args []string +} + +// recording_entry is an entry whose every phase and hook records itself; +// fail names the one phase that fails instead +fn recording_entry(mut c Calls, fail string) VshEntry { + return VshEntry{ + spec: fn () !Spec { + return Spec{ + pkgname: 'rec' + pkgver: '1.0' + pkgrel: 1 + pkgdesc: 'records its phases' + arch: ['any'] + hooks: ['post-install'] + } + } + prepare: fn [mut c, fail] () ! { + c.ran << 'prepare' + if fail == 'prepare' { + return error('prepare broke') + } + } + build: fn [mut c, fail] () ! { + c.ran << 'build' + if fail == 'build' { + return error('build broke') + } + } + check: fn [mut c] () ! { + c.ran << 'check' + } + package: fn [mut c] () ! { + c.ran << 'package' + } + hooks: { + 'post-install': fn [mut c] (args []string) ! { + c.ran << 'post-install' + c.args << args + } + } + } +} + +fn test_vsh_run_dispatches_every_phase() ! { + for phase in ['prepare', 'build', 'check', 'package'] { + mut c := &Calls{} + vsh_run(recording_entry(mut c, ''), [phase], '')! + // the phase asked for, and nothing else + assert c.ran == [phase] + } + // a hook takes the arguments after its name, as pacman hands them + mut c := &Calls{} + vsh_run(recording_entry(mut c, ''), ['post-install', '1.0-1', '0.9-1'], '')! + assert c.ran == ['post-install'] + assert c.args == ['1.0-1', '0.9-1'] +} + +fn test_vsh_run_phase_failures() { + // a failing phase fails the run, so makepkg stops as it would + mut c := &Calls{} + vsh_run(recording_entry(mut c, 'build'), ['build'], '') or { + assert err.msg() == 'build broke' + assert c.ran == ['build'] + return + } + assert false, 'a failing build passed' +} + +fn test_vsh_run_missing_and_unknown() { + // a phase the entry holds no function for, a name that is nothing, and + // no name at all: each says so, nothing runs + empty := VshEntry{} + for phase, says in { + 'prepare': 'prepare: the entry holds no prepare function' + 'build': 'build: the entry holds no build function' + 'check': 'check: the entry holds no check function' + 'package': 'package: the entry holds no package function' + 'pkgver': 'pkgver: the entry holds no pkgver function' + 'post-remove': 'vsh: "post-remove" is neither generate, a phase, nor a hook' + '': 'vsh: give an argument' + } { + args := if phase == '' { []string{} } else { [phase] } + vsh_run(empty, args, '') or { + assert err.msg().starts_with(says), err.msg() + continue + } + assert false, '${phase} ran on an empty entry' + } +} + +fn test_vsh_run_pkgver() ! { + // pkgver prints the version the function computes; an empty one is a + // mistake makepkg would turn into a broken package name + out := capture_stdout(fn () ! { + vsh_run(VshEntry{ + pkgver: fn () string { + return '2.1.r3.gabc' + } + }, ['pkgver'], '')! + })! + assert out == '2.1.r3.gabc\n' + vsh_run(VshEntry{ + pkgver: fn () string { + return '' + } + }, ['pkgver'], '') or { + assert err.msg() == 'pkgver: it returned an empty version' + return + } + assert false, 'an empty pkgver passed' +} + +fn test_vsh_run_generate() ! { + dir := os.join_path(os.vtmp_dir(), 'vpac_vsh_generate_${os.getpid()}') + os.mkdir_all(dir)! + defer { os.rmdir_all(dir) or {} } + script := os.join_path(dir, 'PKGBUILD.vsh') + os.write_file(script, '// the script')! + saved := os.getenv('VPAC_V') + defer { os.setenv('VPAC_V', saved, true) } + os.setenv('VPAC_V', '/usr/bin/v', true) + mut c := &Calls{} + entry := recording_entry(mut c, '') + // generate writes the PKGBUILD, and the .install its hooks need, beside + // the script, and runs no phase + capture_stdout(fn [entry, script] () ! { + vsh_run(entry, ['generate'], script)! + })! + assert c.ran.len == 0 + pkgbuild := os.read_file(os.join_path(dir, 'PKGBUILD'))! + assert pkgbuild.contains("pkgname='rec'"), pkgbuild + for phase in ['prepare', 'build', 'check', 'package'] { + assert pkgbuild.contains('${phase}() {'), phase + } + assert os.exists(os.join_path(dir, 'rec.install')) + // without the script's path there is nowhere to write + vsh_run(entry, ['generate'], '') or { + assert err.msg().contains('VPAC_VSH_PATH') + return + } + assert false, 'generate ran without a script path' +} + +// BadEntry is an entry generate refuses, and what it says +struct BadEntry { + e VshEntry + says string +} + +fn test_vsh_run_generate_checks_the_entry() ! { + dir := os.join_path(os.vtmp_dir(), 'vpac_vsh_generate_bad_${os.getpid()}') + os.mkdir_all(dir)! + defer { os.rmdir_all(dir) or {} } + script := os.join_path(dir, 'PKGBUILD.vsh') + saved := os.getenv('VPAC_V') + defer { os.setenv('VPAC_V', saved, true) } + os.setenv('VPAC_V', '/usr/bin/v', true) + spec := fn () !Spec { + return Spec{ + pkgname: 'bad' + pkgver: '1.0' + pkgrel: 1 + pkgdesc: 'missing parts' + arch: ['any'] + } + } + listed := fn () !Spec { + return Spec{ + pkgname: 'bad' + pkgver: '1.0' + pkgrel: 1 + pkgdesc: 'a hook with no body' + arch: ['any'] + hooks: ['post-install'] + } + } + nop := fn () ! {} + hook := fn (_ []string) ! {} + for t in [ + BadEntry{VshEntry{ + build: nop + package: nop + }, 'a :spec is required'}, + BadEntry{VshEntry{ + spec: spec + build: nop + }, 'a :package phase is required'}, + BadEntry{VshEntry{ + spec: spec + build: nop + package: nop + hooks: { + 'post-install': hook + } + }, 'the spec does not list :post-install'}, + BadEntry{VshEntry{ + spec: listed + build: nop + package: nop + }, 'the entry holds no post-install body'}, + ] { + vsh_run(t.e, ['generate'], script) or { + assert err.msg().contains(t.says), err.msg() + continue + } + assert false, 'generate took an entry it should refuse: ${t.says}' + } + // and it wrote nothing for any of them + assert !os.exists(os.join_path(dir, 'PKGBUILD')) +} + +// capture_stdout runs f with fd 1 going to a file, and returns what came +fn capture_stdout(f fn () !) !string { + path := os.join_path(os.vtmp_dir(), 'vpac_vsh_out_${os.getpid()}') + mut file := os.create(path)! + defer { os.rm(path) or {} } + saved := C.dup(1) + if saved < 0 { + return error('could not save stdout') + } + C.fflush(C.stdout) + C.dup2(file.fd, 1) + mut failure := '' + f() or { failure = err.msg() } + C.fflush(C.stdout) + C.dup2(saved, 1) + C.close(saved) + file.close() + if failure != '' { + return error(failure) + } + return os.read_file(path)! +} + +fn test_vsh_run_generate_without_build() ! { + // no build phase, as makepkg allows: the PKGBUILD has no build() and + // still its package() + dir := os.join_path(os.vtmp_dir(), 'vpac_vsh_nobuild_${os.getpid()}') + os.mkdir_all(dir)! + defer { os.rmdir_all(dir) or {} } + script := os.join_path(dir, 'PKGBUILD.vsh') + saved := os.getenv('VPAC_V') + defer { os.setenv('VPAC_V', saved, true) } + os.setenv('VPAC_V', '/usr/bin/v', true) + entry := VshEntry{ + spec: fn () !Spec { + return Spec{ + pkgname: 'data' + pkgver: '1.0' + pkgrel: 1 + pkgdesc: 'files only' + arch: ['any'] + } + } + package: fn () ! {} + } + capture_stdout(fn [entry, script] () ! { + vsh_run(entry, ['generate'], script)! + })! + pkgbuild := os.read_file(os.join_path(dir, 'PKGBUILD'))! + assert !pkgbuild.contains('build() {'), pkgbuild + assert pkgbuild.contains('package() {'), pkgbuild +} + +fn test_spec_epoch_edges() ! { + base := Spec{ + pkgname: 'ep' + pkgver: '1.0' + pkgrel: 1 + pkgdesc: 'epochs' + arch: ['any'] + } + have := { + 'package': true + } + // absent and 0 are the same: no epoch in the head + zero := spec_meta(&base, have)! + assert !zero.as_struct().has('epoch') + // a positive one is carried as it is + three := spec_meta(&Spec{ + ...base + epoch: 3 + }, have)! + assert three.as_struct().get('epoch').as_int() == 3 + // a negative one is said, as the lip's :epoch says it, not dropped + for bad in [-1, -100] { + if _ := spec_meta(&Spec{ + ...base + epoch: bad + }, have) + { + assert false, 'epoch ${bad} was taken' + } else { + assert err.msg() == 'pkgbuild :epoch is negative; 0 means absent', err.msg() + } + } +} -- 2.56.1