ground zero
@@ -0,0 +1,8 @@
1+[*]
2+charset = utf-8
3+end_of_line = lf
4+insert_final_newline = true
5+trim_trailing_whitespace = true
6+
7+[*.v]
8+indent_style = tab
@@ -0,0 +1,8 @@
1+* text=auto eol=lf
2+*.bat eol=crlf
3+
4+*.v linguist-language=V
5+*.vv linguist-language=V
6+*.vsh linguist-language=V
7+v.mod linguist-language=V
8+.vdocignore linguist-language=ignore
@@ -0,0 +1,34 @@
1+# Binaries for programs and plugins
2+main
3+pacman
4+*.exe
5+*.exe~
6+*.so
7+*.dylib
8+*.dll
9+
10+# Ignore binary output folders
11+bin/
12+
13+# Ignore common editor/system specific metadata
14+.DS_Store
15+.idea/
16+.vscode/
17+*.iml
18+
19+# ENV
20+.env
21+
22+# Web assets and local databases
23+*.db
24+*.js
25+
26+# Modules installed with `v install --local` land beside this file, one
27+# directory per module. Add them here if they should stay out of the repo.
28+
29+# What `v . -o vpac` makes
30+/vpac
31+
32+# Editor swap files
33+*.swp
34+*.kate-swp
@@ -0,0 +1,156 @@
1+# AGENTS.md
2+
3+for agents landing in this repository cold.
4+
5+vpac is a package manager written in V on top of libalpm, the library that
6+backs pacman. it is a frontend of its own — its own listings, prompts,
7+progress drawing, and a json event protocol for other frontends — with a
8+config file of its own, and two package sources beyond the sync dbs: the
9+pkgbuild repos and arbitrary git repos built with vpac itself.
10+
11+## the repository
12+
13+```
14+src/ module main: the frontend. one file per mode, plus the shared
15+ parts every mode reaches for.
16+src/cli.v argument parsing and mode dispatch. modes: s q w n m b i r u
17+ l o d c t a k v f (search info which deptest mark build
18+ install remove upgrade files owner orphans clean tree
19+ autoremove rank verify find).
20+src/config.v the configuration. the forms (path pkg network rank pkgbuild
21+ options search clean tree color progress spinner
22+ mirrorlist repo) are read from a blip file, /etc/vpac.d/config.lip by
23+ default, and every setting keeps a __global here.
24+src/trans.v transaction begin/prepare/commit/cleanup and the interrupt
25+ handler. src/db.v holds the db paths, repo registration and
26+ freshness; src/db_check.v is verify's -D modes.
27+src/ipc.v --ui ipc: the event protocol (one json object per line) and
28+ the prompter a frontend answers questions with.
29+src/ui.v the shared progress display and callback wiring for libalpm;
30+ src/prompt.v the terminal's side of every question.
31+(the rest of src/)
32+ one file per command. install is remote.v, and remove.v
33+ autoremove.v upgrade.v modify.v write the db too; find.v
34+ files.v orphans.v deptest.v are read-only; verify.v and
35+ verify_full.v check the disk; pkgbuild.v pkgbuild_install.v
36+ build_repo.v mirrors.v privilege.v are the network- and
37+ privilege-flavored ones.
38+vmakepkg/ a library module of its own: PKGBUILD.lip (blip format;
39+ lip.v) and PKGBUILD.vsh (a V script; vsh.v) both turn into a
40+ real PKGBUILD (and a .install for hooks) whose phases makepkg
41+ runs, delegating back into vpac or v.
42+pkgs/ two tiny packages vpac itself builds as smoke tests of the
43+ vmakepkg formats.
44+src/*_test.v, vmakepkg/*_test.v the tests.
45+src/testdb/ a module only the tests import: the one writer of libalpm
46+ local dbs they share. vpac never imports it, so it is in no
47+ build of the program.
48+```
49+
50+## the cross-references, and the rule about them
51+
52+the binary links libalpm through the V module `alpm` (a file that begins
53+`module alpm`), evaluates its config and lip files through the module
54+`blip.vlib.blip`, and reuses this repo's own `vmakepkg`. these dependencies
55+live outside the repository: on a machine, V finds them under its module
56+directory (typically ~/.vmodules), often as symlinks to checkouts beside vpac.
57+
58+- if a build cannot resolve `alpm`, `blip` or `vmakepkg`, find where those
59+ checkouts are on this machine (ask, or look in V's module directory) —
60+ never stub a missing module or patch a module cache to make it work.
61+- parity questions ("what does pacman do?", "is this libalpm behavior?") are
62+ answered in the pacman C source — the checkout that holds
63+ `lib/libalpm/*.c` — and in libalpm's headers, not guessed. vpac follows
64+ pacman's defaults closely; a lot of what looks odd is pacman's own
65+ behavior spelled out. cross-reference before you fix.
66+- signature and checksum semantics: libalpm distinguishes the default, local
67+ file and remote file siglevels; pacman maps its config onto all three.
68+
69+## building and testing
70+
71+- the compiler is `v`. `v . -o vpac` compiles to ./vpac at the repo root.
72+ `v test src` and `v test vmakepkg` run the two suites.
73+ there is no install step: link or copy ./vpac where you want it.
74+- a change is finished when `v -check .` is clean, both test suites pass,
75+ and every touched .v file has been through the formatter (`v fmt -w` on
76+ the file; the formatter reflows — check the result).
77+- tests are hermetic: each src/*_test.v compiles as its own binary and
78+ builds its own local dbs under V's temp dir. they need no network and no
79+ root. globals a test touches (config, cache dirs, colors) are saved and
80+ restored inside the test.
81+- smoke checks against a real system are read-only only unless you are
82+ meant to change it: search, info, --print previews, verify, find, tree
83+ are safe. installs, removals and rank -w are not.
84+
85+## house style
86+
87+- prose comments, lowercase, sparsely worded: they say why — the intent, the
88+ pacman or posix cross-reference, the data's shape — not what the line does.
89+ when you change behavior, move the comment with it.
90+- error discipline: no panics behind doors a user walks through; every
91+ libalpm call's error is handled; a housekeeping failure the run goes on
92+ from (a handle's release, a temp dir's removal) is not `or {}` but
93+ `or { went_on('release the alpm handle', err) }`, which --verbose says;
94+ ?T (may be none) and !T (may fail) are unwrapped with their own syntax
95+ and are not interchangeable.
96+- identifiers snake_case, files named for their one concern. the formatter
97+ is the arbiter of layout; do not hand-alignment what v fmt will rewrite.
98+
99+## gotchas learned the hard way (do not rediscover them)
100+
101+- os.File.read reports end of input as an os.Eof error: end a chunked read
102+ with `err is os.Eof`, and treat anything else as failure (a truncated
103+ digest must never pass as a whole one).
104+- dup(2) and dup2(2) answer their new descriptor on success — never 0 — so a
105+ check against `!= 0` fires on every success; check `fd < 0`.
106+- `lock` is a V keyword. so a variable named it does not compile; spell the
107+ lock's path `lpath` instead.
108+- the flag attributes read the field's long name with dashes: @[long:
109+ no_upgrade_deps] accepts --no-upgrade-deps. spell help text with dashes.
110+- a `?T` if-guard cannot read `err` — only a `!T` call's `or {}` has one.
111+ a `!` call cannot hide inside a function that returns ?T: either handle
112+ the error inline or widen the return.
113+- defer always runs, including through `or { return err }`: pair
114+ trans_begin with `defer { trans_cleanup(handle) }` at the moment of begin
115+ and never also release by hand (alpm_release is not idempotent).
116+- assigning one array to another needs the checker's `.clone()`; a borrowed
117+ &T passed to a mut method is the local copy, never a write to the C side.
118+- the repo's __global config values are the whole config surface:
119+ load_config resets every one of them before reading the file, so a second
120+ load in one process starts clean (tests depend on this).
121+
122+## conventions that hold the system together
123+
124+- every question goes through ui.yesno / ui.noyes / ui.proceed / ui.choose,
125+ which pause the live display first. --noconfirm takes each preset printed;
126+ --print answers silently; pkgbuild installs refuse --noconfirm unless
127+ --nopkgbuildconfirm (the first question's preset is no).
128+- the ipc protocol is a versioned surface (const ipc_protocol in ipc.v): an
129+ event whose shape a reader must know about bumps it. once ipc_start ran,
130+ plain prints never touch stdout — they are led to stderr, so the channel
131+ stays whole json lines.
132+- the config can hold packages (pkg :hold): the check runs on the targets
133+ and again on the transaction's final victim set, after prepare.
134+- modes that change the system re-execute themselves as root through the
135+ root provider (the config's options :root: sudo by default, any command
136+ that runs its arguments as root; su and pkexec are known by name),
137+ carrying the config and the invoker's name across (VPAC_INVOKER, VPAC_V).
138+ pkgbuild builds and
139+ the build mode run as that invoking user, never as root. --lip-run is vpac
140+ internal: the entry generated PKGBUILDs call back through, not a mode.
141+- read-only modes may open a lean alpm.initialize handle; anything that
142+ writes goes through init_handle so libalpm's callbacks and the
143+ configured siglevel, cachedirs, ignores and parallelism attach.
144+
145+## the issue tracker
146+
147+there is no TODO file: the checklist of the 2026-11-09 review sweep
148+moved into the issue tracker — 140 issues, one per checklist id, and #2
149+their index. tracker numbers do not match the ids; look an id up in the
150+index (#2) first. later sweeps filed some findings two or three times:
151+close the duplicates of an issue with it. work changes state in the
152+tracker, not in files: open an issue first (`fj issue create -R origin`),
153+push the fix, then close the issue with the resolution
154+(`fj issue close -R origin N -w "..."`). fj talks to
155+the origin host (git.vorelabs.dev) and needs a token such as configured
156+under `fj auth list` — user read, repository read, issue read/write.
@@ -0,0 +1,58 @@
1+## introduction
2+
3+[vpac](https://vpac.vorelabs.dev/) is *versatile* package manager based on [libalpm](https://man.archlinux.org/man/libalpm.3)
4+
5+## features
6+
7+vpac not only posses full pacman parity, but also extends on top of it:
8+
9+- advanced orphan detection: `vpac d -tt` also lists the dependencies only an optdepends line keeps
10+- mirror ranking by latency and download speed (`vpac k`), written to the files the config requires
11+- pkgbuild repos, the AUR among them: search them, review a PKGBUILD, and build and install from them (`vpac b`, `vpac i -b`)
12+- 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`)
13+- file lookup in the sync file dbs (`vpac f`), with regular expressions too
14+- a json event protocol for other frontends (`--ui ipc`)
15+- one config file, written in [blip](https://git.vorelabs.dev/vorelabs/blip), that can pull its mirror lists from files of their own
16+
17+## quick start
18+
19+Clone this repository, then:
20+
21+```sh
22+./install.vsh # asks a few questions, writes /etc/vpac.d/config.lip
23+v . -o vpac # builds vpac into ./vpac
24+ln -sf $PWD/vpac /usr/local/bin/vpac
25+vpac k -w # ranks the mirrors for your system into the config's mirror file
26+vpac s -r linux-lts # search the sync databases
27+```
28+
29+`install.vsh` also asks whether to keep vpac's database, cache, keys and hooks
30+in pacman's directories, and whether to turn libalpm's download sandbox off.
31+Answer no to the first only if you mean to keep vpac's state apart from
32+pacman's: a separate database does not know the packages pacman installed.
33+
34+Building needs the V compiler, `v`. It also needs the `alpm` and `blip`
35+modules, which V finds under its module directory, and libalpm's headers and
36+library.
37+
38+`v test src` and `v test vmakepkg` run the test suites.
39+
40+## docs
41+
42+- [usage](docs/usage.md): the command line, every mode and its options
43+- [configuration](docs/configuration.md): every form and key in `config.lip`, with its default
44+
45+## coming soon
46+
47+- drop-in pacman shim
48+- configuration profils
49+- state snapshots
50+- extended flake-like makepkg
51+
52+## state
53+
54+an honest assessment of vpac's state:
55+
56+- [X] good enough to keep along pacman
57+- [ ] can fully replace pacman
58+- [ ] can be installed on any compatible OS
@@ -0,0 +1,356 @@
1+#!/usr/bin/env v
2+
3+import os
4+
5+// install.vsh sets vpac's config up for a new user: it asks a few questions,
6+// then writes /etc/vpac.d/config.lip and the mirror file the config requires,
7+// /etc/vpac.d/mirrors/<os>.lip. the config stays in /etc/vpac.d whatever the
8+// answers: the pacman choice only picks where the db, cache, keys, hooks and
9+// log live. VPAC_ETC writes the two files into another directory instead, a
10+// trial that needs no root and makes no directory outside it. the binary is
11+// built with `v . -o vpac`, which the installer's next steps name.
12+
13+const default_etc = '/etc/vpac.d'
14+
15+// distro is an os the config is written for: its name, which is also the rank
16+// name (mirrors/<name>.lip defines mirrors-<name>), its repos, and the url its
17+// mirrors start from, with the $repo and $arch placeholders left in it
18+struct Distro {
19+ name string
20+ repos []string
21+ src string
22+}
23+
24+fn distros() []Distro {
25+ return [
26+ Distro{
27+ name: 'arch'
28+ repos: ['core', 'extra']
29+ src: 'https://geo.mirror.pkgbuild.com/\$repo/os/\$arch'
30+ },
31+ Distro{
32+ name: 'artix'
33+ repos: ['system', 'world', 'galaxy']
34+ src: 'https://mirror1.artixlinux.org/repos/\$repo/os/\$arch'
35+ },
36+ Distro{
37+ name: 'cachyos'
38+ repos: ['cachyos']
39+ src: 'https://mirror.cachyos.org/repo/\$arch/\$repo'
40+ },
41+ ]
42+}
43+
44+// paths are where vpac keeps its db, cache, keyring and hooks, and its log
45+struct Paths {
46+ db string
47+ cache string
48+ gpg string
49+ hook string
50+ log string
51+}
52+
53+// pacman_paths are the directories pacman itself uses, which libalpm defaults
54+// to. the local db is pacman's own, so vpac sees the packages pacman installed
55+fn pacman_paths() Paths {
56+ return Paths{
57+ db: '/var/lib/pacman/'
58+ cache: '/var/cache/pacman/pkg/'
59+ gpg: '/etc/pacman.d/gnupg/'
60+ hook: '/etc/pacman.d/hooks/'
61+ log: '/var/log/pacman.log'
62+ }
63+}
64+
65+// own_paths are vpac's own, apart from pacman's. the db starts empty: it does
66+// not know the packages pacman installed, and the keyring has no keys until
67+// they are imported into it
68+fn own_paths() Paths {
69+ return Paths{
70+ db: '/var/lib/vpac/'
71+ cache: '/var/cache/vpac/pkg/'
72+ gpg: '/etc/vpac.d/gnupg/'
73+ hook: '/etc/vpac.d/hooks/'
74+ log: '/var/log/vpac.log'
75+ }
76+}
77+
78+// answers are what the questions settled
79+struct Answers {
80+ distro string
81+ aur bool
82+ root string
83+ parallel int
84+ color string
85+ sandbox bool
86+ arch string
87+}
88+
89+fn main() {
90+ run() or {
91+ eprintln('install: ${err}')
92+ exit(1)
93+ }
94+}
95+
96+fn run() ! {
97+ trial := os.getenv('VPAC_ETC') != ''
98+ etc := if trial { os.getenv('VPAC_ETC') } else { default_etc }
99+ config := os.join_path(etc, 'config.lip')
100+ mut replace := false
101+ if os.exists(config) {
102+ println('${config} exists.')
103+ keep := ask_yes('replace it? the old file is kept as config.lip.old', false)!
104+ if !keep {
105+ println('kept ${config}: nothing changed')
106+ return
107+ }
108+ replace = true
109+ }
110+
111+ mut paths := own_paths()
112+ if found('pacman') {
113+ if ask_yes("pacman is installed: keep vpac's db, cache, keys, hooks and log in pacman's directories?", true)! {
114+ paths = pacman_paths()
115+ } else {
116+ println("note: vpac's own db starts empty and does not see the packages pacman installed")
117+ }
118+ } else {
119+ 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")
120+ }
121+
122+ distro := ask_choice('mirrors for which os', distros().map(it.name), detect_distro())!
123+ aur := ask_yes('add the AUR as a pkgbuild repo', true)!
124+ providers := ['doas', 'sudo', 'pkexec', 'su']
125+ root := ask_choice('the command vpac gets root with', providers, root_default())!
126+ parallel := ask_count('parallel downloads', 3, 1)!
127+ color := ask_choice('color output', ['auto', 'always', 'never'], 'auto')!
128+ sandbox := ask_yes("turn libalpm's sandbox off for downloads and extraction (pacman's DisableSandbox)", false)!
129+
130+ // the root command runs when the files are written to /etc: the same one
131+ // the config names for vpac's own escalation
132+ escalate := !trial && os.getuid() != 0
133+ if escalate && !found(root) {
134+ return error('${root} is not installed: install it, or run install.vsh as root')
135+ }
136+
137+ a := Answers{
138+ distro: distro
139+ aur: aur
140+ root: root
141+ parallel: parallel
142+ color: color
143+ sandbox: sandbox
144+ arch: os.uname().machine
145+ }
146+ d := distro_named(distro)
147+ mirror := os.join_path(etc, 'mirrors', '${d.name}.lip')
148+ write_mirror := !os.exists(mirror)
149+
150+ // the files are staged in a temp dir and then moved into place, so the
151+ // root command only copies
152+ stage := os.join_path(os.temp_dir(), 'vpac-install-${os.getpid()}')
153+ os.mkdir_all(os.join_path(stage, 'mirrors'))!
154+ defer {
155+ os.rmdir_all(stage) or { eprintln('install: could not remove ${stage}: ${err}') }
156+ }
157+ staged_config := os.join_path(stage, 'config.lip')
158+ staged_mirror := os.join_path(stage, 'mirrors', '${d.name}.lip')
159+ os.write_file(staged_config, config_text(a, paths, d))!
160+ os.write_file(staged_mirror, mirror_text(d))!
161+
162+ mut cmds := ['mkdir -p ${sh_quote(etc)} ${sh_quote(os.join_path(etc, 'mirrors'))}']
163+ if !trial {
164+ cmds << 'mkdir -p ${sh_quote(paths.db)} ${sh_quote(paths.cache)} ${sh_quote(paths.gpg)} ${sh_quote(paths.hook)}'
165+ }
166+ if replace {
167+ cmds << 'cp -f ${sh_quote(config)} ${sh_quote(config + '.old')}'
168+ }
169+ cmds << 'install -m 644 ${sh_quote(staged_config)} ${sh_quote(config)}'
170+ if write_mirror {
171+ cmds << 'install -m 644 ${sh_quote(staged_mirror)} ${sh_quote(mirror)}'
172+ }
173+ line := cmds.join(' && ')
174+ argv := if escalate { root_argv(root, line) } else { ['sh', '-c', line] }
175+ code := os.system_args(argv)
176+ if code != 0 {
177+ return error('writing ${config} failed (exit ${code}): fix the cause and run install.vsh again')
178+ }
179+
180+ println('wrote ${config}')
181+ if write_mirror {
182+ println('wrote ${mirror}: one default url, which vpac k -w ranks')
183+ } else {
184+ println('kept ${mirror}: it is already there')
185+ }
186+ println('')
187+ println('next:')
188+ println(term.bold(' v . -o vpac ') + ' build vpac')
189+ println(term.bold(' ln -sf $PWD/vpac /usr/local/bin') + ' symlink vpac to /usr/local/bin/vpac')
190+ println(term.bold(' vpac k -w ') + ' rank the ${d.name} mirrors into ${mirror}')
191+}
192+
193+// distro_named is the distro with the name, or the first one when none has it
194+fn distro_named(name string) Distro {
195+ for d in distros() {
196+ if d.name == name {
197+ return d
198+ }
199+ }
200+ return distros()[0]
201+}
202+
203+// detect_distro reads /etc/os-release the way the ranker does: the ID, then the
204+// ID_LIKE, the first name that is one of the distros
205+fn detect_distro() string {
206+ text := os.read_file('/etc/os-release') or { return 'arch' }
207+ mut id := ''
208+ mut like := ''
209+ for line in text.split_into_lines() {
210+ if line.starts_with('ID=') {
211+ id = line[3..].trim('"\'')
212+ } else if line.starts_with('ID_LIKE=') {
213+ like = line[8..].trim('"\'')
214+ }
215+ }
216+ for candidate in [id, ...like.split(' ')] {
217+ for d in distros() {
218+ if d.name == candidate {
219+ return candidate
220+ }
221+ }
222+ }
223+ return 'arch'
224+}
225+
226+// found reports whether an executable is on the PATH
227+fn found(exe string) bool {
228+ path := os.find_abs_path_of_executable(exe) or { '' }
229+ return path != ''
230+}
231+
232+// root_default is the first root command on the machine, in the order the
233+// installer prefers them
234+fn root_default() string {
235+ for p in ['doas', 'sudo', 'pkexec', 'su'] {
236+ if found(p) {
237+ return p
238+ }
239+ }
240+ return 'su'
241+}
242+
243+// root_argv is the command that runs one shell line as root through the root
244+// command. su takes the line with -c, the others run it through sh
245+fn root_argv(provider string, line string) []string {
246+ if provider == 'su' {
247+ return ['su', '-c', line]
248+ }
249+ return [provider, 'sh', '-c', line]
250+}
251+
252+// sh_quote spells one word for a posix shell, in single quotes
253+fn sh_quote(s string) string {
254+ return "'" + s.replace("'", "'\\''") + "'"
255+}
256+
257+// read_answer reads one line off stdin. the end of input is an error and not an
258+// answer, so a run with stdin closed stops before it writes anything
259+fn read_answer(prompt string) !string {
260+ line := os.input_opt(prompt) or {
261+ return error('stdin closed before the questions were answered: nothing was written')
262+ }
263+ return line.trim_space()
264+}
265+
266+// ask reads one answer: the default when it is left empty
267+fn ask(question string, default string) !string {
268+ suffix := if default == '' { '' } else { ' [${default}]' }
269+ answer := read_answer('${question}${suffix}: ')!
270+ return if answer == '' { default } else { answer }
271+}
272+
273+fn ask_yes(question string, default bool) !bool {
274+ hint := if default { 'Y/n' } else { 'y/N' }
275+ for {
276+ raw := read_answer('${question} [${hint}]: ')!
277+ match raw.to_lower() {
278+ '' { return default }
279+ 'y', 'yes' { return true }
280+ 'n', 'no' { return false }
281+ else { println('answer y or n') }
282+ }
283+ }
284+ return default
285+}
286+
287+fn ask_choice(question string, choices []string, default string) !string {
288+ for {
289+ answer := ask('${question} (${choices.join(' / ')})', default)!
290+ if answer in choices {
291+ return answer
292+ }
293+ println('answer one of: ${choices.join(', ')}')
294+ }
295+ return default
296+}
297+
298+fn ask_count(question string, default int, min int) !int {
299+ for {
300+ answer := ask(question, '${default}')!
301+ if answer.len > 0 && answer.bytes().all(it.is_digit()) && answer.int() >= min {
302+ return answer.int()
303+ }
304+ println('answer a whole number, ${min} or more')
305+ }
306+ return default
307+}
308+
309+// config_text is the one config file: every form a user is likely to want,
310+// with the mirror file of the distro required beside it
311+fn config_text(a Answers, p Paths, d Distro) string {
312+ mut repos := []string{}
313+ for name in d.repos {
314+ repos << '(repo\n :name "${name}"\n :src mirrors-${d.name})'
315+ }
316+ if a.aur {
317+ repos << '(repo\n :name "aur"\n :type "pkgbuild"\n :src "https://aur.archlinux.org")'
318+ }
319+ return '; vpac config, written by install.vsh: edit it by hand, or run install.vsh again.
320+(require "mirrors/${d.name}.lip")
321+
322+(path
323+ :root "/"
324+ :db "${p.db}"
325+ :log "${p.log}"
326+ :gpg "${p.gpg}"
327+ :cache ["${p.cache}"]
328+ :hook ["${p.hook}"])
329+
330+(pkg
331+ :arch "${a.arch}"
332+ :hold ["pacman" "glibc"])
333+
334+(network
335+ :parallel ${a.parallel}
336+ :protocols ["https"]
337+ :user "alpm"' +
338+ if a.sandbox if { ':disable-sandbox true' } else { '' } +
339+'
340+
341+(options
342+ :root "${a.root}"
343+ :color "${a.color}")
344+
345+${repos.join('\n\n')}
346+'
347+}
348+
349+// mirror_text is a mirror file as rank writes one: mirrors-<os> is defined
350+// and holds the urls, here the distro's one url until the ranking replaces it
351+fn mirror_text(d Distro) string {
352+ return '; mirrors for ${d.name}, the default until vpac k -w ranks them
353+(unless (defined? mirrors-${d.name}) (define mirrors-${d.name} []))
354+(array-append! mirrors-${d.name} ["${d.src}"])
355+'
356+}
@@ -0,0 +1,35 @@
1+(defpkgbuild lipsmoke
2+ ;; — identity —
3+ :pkgname "lipsmoke"
4+ :pkgver "1.0"
5+ :pkgrel 1
6+ :pkgdesc "a tiny smoke test that a lip package builds end to end"
7+ :arch '(:any)
8+ :url "https://example.org/lipsmoke"
9+ :license "MIT"
10+ ;; — dependencies —
11+ :depends '("bash")
12+ ;; — sources & integrity —
13+ :source '("lipsmoke.sh" "readme.txt")
14+ :b2sums '("0d2649f267def0d9a231544898208afd025f675015b38ad05e3806c136ec8ecd176fe29f3988b4be078e08c63f34178e966e15bfc17c7f738e86db0fb4107276"
15+ "5eae74e3630b54f9271b53c7a1ad8b665e687efe08ec193b730ff36dc69c171021b2ecedcc6658e462c9f7c513bc87a76e0faf49326d60eb04d3323b36e72da1")
16+ ;; — phases: one of each, including the loop/glob payoff —
17+ :build
18+ (lambda ()
19+ (run "install -m755 lipsmoke.sh just")
20+ (echo "lipsmoke: build finished"))
21+ :package
22+ (lambda ()
23+ (run "install -Dm755 just ~a/usr/bin/lipsmoke" (pkgdir))
24+ (for-each (lambda (doc)
25+ (run "install -Dm644 ~a ~a/usr/share/doc/lipsmoke/~a" doc (pkgdir) doc))
26+ (glob "*.txt"))
27+ (echo "lipsmoke: package finished"))
28+ ;; — .install hooks, inline; pacman hands the versions as arguments —
29+ :pre-install
30+ (lambda (newver)
31+ (echo (format "lipsmoke: pre-installing ~a" newver))
32+ (echo "lipsmoke: pre-done"))
33+ :post-install
34+ (lambda (newver)
35+ (echo (format "lipsmoke: installed ~a, run lipsmoke for a hello" newver))))
@@ -0,0 +1,2 @@
1+#!/bin/bash
2+echo "just, from the lip pipeline"
@@ -0,0 +1 @@
1+the lipsmoke readme
@@ -0,0 +1,15 @@
1+(defpkgbuild lipsplit
2+ ;; two arch-independent splits from one tree, one shared :package lambda
3+ :pkgname '("lipsplit" "lipsplit-doc")
4+ :pkgver "3.2"
5+ :pkgrel 1
6+ :pkgdesc "smoke test of split packages written in blip"
7+ :arch '(:any)
8+ :license "MIT"
9+ :depends '("bash")
10+ :source '("shared.txt")
11+ :b2sums '("f7d65eb3c70eddb9257e9539ab502e85fa754f5a7389631fd3171d944dc6fa466f73f525feaa8e83f5126a29e77fdf4774b3e27f99c4da23a86e7bda5041b92f")
12+ :package
13+ (lambda ()
14+ ;; each split runs its own invocation: (this-pkg) says which
15+ (run "install -Dm644 shared.txt ~a/root-of-~a" (pkgdir) (this-pkg))))
@@ -0,0 +1,61 @@
1+#!/usr/bin/env v
2+
3+// a package written as a V script: the spec is a struct, the phases are
4+// functions, and vsh_entry turns it into a makepkg package
5+import vmakepkg
6+import os
7+
8+fn spec() !vmakepkg.Spec {
9+ return vmakepkg.Spec{
10+ pkgname: 'vshsmoke'
11+ pkgver: '1.4'
12+ pkgrel: 1
13+ pkgdesc: 'a smoke test that a PKGBUILD.vsh builds end to end'
14+ arch: ['any']
15+ url: 'https://example.org/vshsmoke'
16+ license: 'MIT'
17+ depends: ['bash']
18+ source: ['vshsmoke.sh', 'readme.txt']
19+ b2sums: [
20+ '5395122afa0a2a2f169f4dbf6da935531a81c968adfc2e284f8cdeb36db10bd6966f679e5b6f768c1962b507dd1fe5973a0fe18ce77affc1064a0f8a8e4eca8b',
21+ '1645d573e1441b363804b7f6e1bbd71b87ee87027d0110be97bc8de7e2682d391ae0812770de7c218d0018ee3f4ad6607039019ed7b3c814963ecae80b12f77d',
22+ ]
23+ hooks: ['post-install']
24+ }
25+}
26+
27+fn build() ! {
28+ // the cwd is the sources makepkg unpacked; run shells out with makepkg's
29+ // own spellings of its state restored
30+ vmakepkg.run('install -m755 vshsmoke.sh vsh')!
31+ println('vshsmoke: build finished')
32+}
33+
34+fn package() ! {
35+ pd := vmakepkg.pkgdir()!
36+ mut docs := []string{}
37+ // the binary is the package whether or not a doc came beside it
38+ vmakepkg.run('install -Dm755 vsh ${vmakepkg.shell_quote(pd)}/usr/bin/vshsmoke')!
39+ for doc in vmakepkg.glob('*.txt')! {
40+ name := os.base(doc)
41+ vmakepkg.run('install -Dm644 ${vmakepkg.shell_quote(doc)} ${vmakepkg.shell_quote(pd)}/usr/share/doc/vshsmoke/${vmakepkg.shell_quote(name)}')!
42+ docs << doc
43+ }
44+ println('vshsmoke: package finished (${docs.len} docs unpacked alongside)')
45+}
46+
47+fn post_install(_ []string) ! {
48+ println('vshsmoke: installed, run vshsmoke for a hello')
49+}
50+
51+vmakepkg.vsh_entry(
52+ spec: spec
53+ build: build
54+ package: package
55+ hooks: {
56+ 'post-install': post_install
57+ }
58+) or {
59+ eprintln(err)
60+ exit(1)
61+}
@@ -0,0 +1 @@
1+# the readme the vsh smoke ships
@@ -0,0 +1,2 @@
1+#!/bin/bash
2+echo "vsh smoke ok"
@@ -0,0 +1,30 @@
1+// alpm_log.h is the C half of libalpm's log callback (ui.v holds the V
2+// half). the callback takes a va_list, which V cannot receive portably —
3+// a pointer on x86_64, a struct on aarch64 — so the line is formatted here,
4+// with vsnprintf, and handed over whole. only ERROR and WARNING pass, the
5+// levels pacman's cb_log prints by default: alpm_loglevel_t is bit flags
6+#ifndef VPAC_ALPM_LOG_H
7+#define VPAC_ALPM_LOG_H
8+
9+#include <stdarg.h>
10+#include <stdio.h>
11+#include <alpm.h>
12+
13+// vpac_log_line is exported by ui.v
14+void vpac_log_line(void *ctx, int level, char *text);
15+
16+static void vpac_alpm_log(void *ctx, alpm_loglevel_t level, const char *fmt, va_list args) {
17+ if(!(level & (ALPM_LOG_ERROR | ALPM_LOG_WARNING)) || fmt == NULL || fmt[0] == '\0') {
18+ return;
19+ }
20+ char line[4096];
21+ vsnprintf(line, sizeof line, fmt, args);
22+ vpac_log_line(ctx, (int)level, line);
23+}
24+
25+// vpac_set_alpm_log installs the callback, ctx being the run's TransUI
26+static int vpac_set_alpm_log(alpm_handle_t *handle, void *ctx) {
27+ return alpm_option_set_logcb(handle, vpac_alpm_log, ctx);
28+}
29+
30+#endif
@@ -0,0 +1,72 @@
1+module main
2+
3+import alpm
4+
5+// mirrors pacman's -Rns $(pacman -Qtdq) idiom: remove every orphaned
6+// package, letting the transaction pull in the dependencies that become
7+// unneeded along the way (recurse), dropping their config files (nosave)
8+fn autoremove(config ConfigAutoRemove) ! {
9+ mut ui := new_trans_ui(noconfirm: config.noconfirm)
10+ check_ask_db_lock(mut ui)
11+
12+ mut handle := init_handle(ui)!
13+ defer { handle.release() or { went_on('release the alpm handle', err) } }
14+ defer { ui.stop() }
15+ defer { trans_cleanup(handle) }
16+
17+ mut s := ui.spinner(text: 'finding orphans')
18+ s.start()
19+ defer { stop_spinner(mut s) }
20+
21+ mut pkgcache := local_pkgcache(handle)!
22+
23+ orphs := orphan_pkgs(mut pkgcache, false)
24+ if orphs.len == 0 {
25+ stop_spinner(mut s)
26+ ui.pause()
27+ report('no orphans')
28+ return
29+ }
30+ // the config can hold a package even when it is an orphan
31+ check_hold(orphs.map(it.get_name()))!
32+
33+ s.set_text('preparing removal')
34+ trans_begin(handle, alpm.TransFlag.recurse | alpm.TransFlag.no_save)!
35+ for pkg in orphs {
36+ handle.remove_pkg(pkg)!
37+ }
38+
39+ trans_prepare_checked(handle)!
40+
41+ // never empty: every orphan is a target, recurse only adds to them, and
42+ // without the unneeded flag libalpm drops no target, it fails instead
43+ victims := handle.trans_get_remove().pkgs()
44+
45+ stop_spinner(mut s)
46+
47+ // the transaction is the truth of what goes: a package held by the
48+ // config that only the recurse would reach counts for the hold list too
49+ check_hold(victims.map(it.get_name()))!
50+
51+ if !trans_confirm(mut ui, handle, victims, .autoremove) {
52+ return
53+ }
54+
55+ // the names are read before the commit, which frees the removed packages
56+ names := victims.map(it.get_name())
57+
58+ mut s2 := ui.spinner(text: 'removing orphans')
59+ s2.start()
60+ defer { stop_spinner(mut s2) }
61+ trans_commit(handle)!
62+ stop_spinner(mut s2)
63+ // a frontend learns what went as from every transaction: a done event
64+ if ipc_on() {
65+ emit(DoneEvent{
66+ action: 'removed'
67+ packages: names
68+ })
69+ return
70+ }
71+ ui.say('removed ${success(names.len.str())} orphaned packages')
72+}
@@ -0,0 +1,300 @@
1+module main
2+
3+import crypto.sha256
4+import vmakepkg
5+import os
6+
7+fn C.mkdtemp(template &char) &char
8+
9+// A package is pulled from an arbitrary repo — a directory or a git url —
10+// under the config's pkgbuild build dir, reviewed whole, built with the
11+// system's makepkg and installed. A bash PKGBUILD runs makepkg exactly as the
12+// original spells it; a PKGBUILD.lip gets a generated PKGBUILD whose phases
13+// run as blip through this very binary.
14+struct ConfigBuild {
15+pub mut:
16+ show_help bool @[long: help; short: h]
17+ noconfirm bool @[long: noconfirm]
18+ no_pkgbuild_confirm bool @[long: nopkgbuildconfirm]
19+ query []string @[tail]
20+}
21+
22+// generated_review is the review of a generated package: the source (the
23+// lip or the .vsh) and the PKGBUILD plus .install it produced, so the user
24+// agrees with everything makepkg will execute
25+fn generated_review(package string, source_name string, source_text string, pkg_text string, install_name string, install_text string) ReviewEvent {
26+ mut parts := [ReviewFile{
27+ name: source_name
28+ text: source_text
29+ }, ReviewFile{
30+ name: 'PKGBUILD'
31+ text: pkg_text
32+ generated: true
33+ }]
34+ if install_text != '' {
35+ parts << ReviewFile{
36+ name: install_name
37+ text: install_text
38+ generated: true
39+ }
40+ }
41+ return ReviewEvent{
42+ package: package
43+ files: parts
44+ }
45+}
46+
47+// install_name_of reads the install file a generated PKGBUILD's head names,
48+// spelled the way makepkg accepts one: '=' with spaces, quotes of either
49+// kind; '' when it names none. it names a file beside the PKGBUILD: anything
50+// that leaves the build dir already (an absolute path, a '..' climb) is not a
51+// name this reader agrees to read. makepkg reads the line through bash, so a
52+// name spelled with a variable or followed by a comment comes back as
53+// written, naming no file here — review_the_rest covers that
54+fn install_name_of(pkg_text string) !string {
55+ mut name := ''
56+ for line in pkg_text.split('\n') {
57+ s := line.trim_space()
58+ if !s.starts_with('install') {
59+ continue
60+ }
61+ rest := s[7..].trim_space()
62+ if !rest.starts_with('=') {
63+ continue
64+ }
65+ val := rest[1..].trim_space().trim('\'"')
66+ if val == '' {
67+ continue
68+ }
69+ if val.starts_with('/') || val in ['.', '..'] || val.starts_with('../')
70+ || val.contains('/../') || val.ends_with('/..') {
71+ return error('b: the install file name "${val}" is not a plain name beside the PKGBUILD')
72+ }
73+ name = val
74+ }
75+ return name
76+}
77+
78+// review_the_rest completes a generated PKGBUILD's review the way read_review
79+// shows a plain one's: every .install file of the build dir, not only the
80+// one install_name_of could resolve, and the build dir's files. the install
81+// scriptlet runs as root at install time, so one makepkg packs under a name
82+// this reader could not resolve must not get there unseen; such a name is
83+// said, beside the files that may be it
84+fn review_the_rest(mut review ReviewEvent, work_dir string, install_name string, resolved bool) ! {
85+ mut names := os.ls(work_dir)!
86+ names.sort()
87+ on_view := review.files.map(it.name)
88+ for f in names {
89+ if f == '.git' {
90+ continue
91+ }
92+ review.listing << f
93+ if f.ends_with('.install') && f !in on_view && os.is_file('${work_dir}/${f}') {
94+ review.files << ReviewFile{
95+ name: f
96+ text: os.read_file('${work_dir}/${f}')!
97+ }
98+ }
99+ }
100+ if install_name != '' && !resolved {
101+ review.warnings << 'the install file "${install_name}" could not be resolved: every .install file is shown'
102+ }
103+}
104+
105+// pull_dir copies a local repo into its build dir as the building user: a
106+// root-owned copy would stop makepkg from touching anything
107+fn pull_dir(user string, src string, dst string) ! {
108+ run_as_user(user, ['mkdir', '-p', os.dir(dst)])!
109+ run_as_user(user, ['rm', '-rf', dst])!
110+ run_as_user(user, ['cp', '-R', src, dst])!
111+}
112+
113+// write_as_user lays a generated file (a PKGBUILD or a .install out of a
114+// PKGBUILD.lip) into the work dir with the building user's ownership, the way
115+// pull_dir gives the clone theirs: a file that belongs to the root process
116+// would make makepkg's reads and the cleanups beside it trip. the text goes
117+// into a read-only temp file of the root process, and install copies it over.
118+// the temp file lives in a directory mkdtemp made for this one write: its
119+// name cannot be guessed and nobody else may write in it, so no link can be
120+// planted where the root process is about to write
121+fn write_as_user(user string, path string, text string) ! {
122+ template := os.join_path(os.temp_dir(), 'vpac.XXXXXX').clone()
123+ if C.mkdtemp(&char(template.str)) == unsafe { nil } {
124+ return error('could not make a temp dir: ${os.posix_get_error_msg(C.errno)}')
125+ }
126+ defer {
127+ os.rmdir_all(template) or { went_on('remove the temp dir ${template}', err) }
128+ }
129+ // the building user reads the file through it, and writes nothing in it
130+ os.chmod(template, 0o755)!
131+ tmp := os.join_path(template, 'text')
132+ os.write_file(tmp, text)!
133+ os.chmod(tmp, 0o444)!
134+ run_as_user(user, ['install', '-m', '644', tmp, path])!
135+}
136+
137+// repo_name is the name a repo goes by: the last part of its path or url,
138+// without a .git suffix. an scp-style git address (user@host:path) counts
139+// from after the colon. empty when the target names nothing, like / or .
140+fn repo_name(source string) string {
141+ name := os.base(source.trim_right('/')).all_after_last(':').trim_string_right('.git')
142+ return if name in ['', '.', '..', '/'] { '' } else { name }
143+}
144+
145+// is_scp_remote reports scp-style git remotes (user@host:path): a colon that
146+// comes before the first slash, where the colon of a host:port transfer url
147+// or of a plain path with a colon in it would not. git itself accepts both
148+// spellings of that, so the clone does not need the target spelled further
149+fn is_scp_remote(target string) bool {
150+ colon := target.index(':') or { return false }
151+ // no slash: the colon splits the host from the path
152+ slash := target.index('/') or { return true }
153+ return colon < slash
154+}
155+
156+// is_git_url reports whether git clone can fetch the target: a transfer url,
157+// a name ending in .git, or an scp-style remote
158+fn is_git_url(target string) bool {
159+ return target.ends_with('.git') || target.contains('://') || is_scp_remote(target)
160+}
161+
162+// repo_work_dir is where a b target is pulled and built, and the name the
163+// repo goes by. the dir is the name and a hash of the source, so two repos
164+// of one name (a fork, a mirror, two checkouts) and a pkgbuild package of
165+// that name never share it, and the same repo always lands in the same dir.
166+// a directory is keyed on its real path, so ./x and /abs/x are one repo
167+fn repo_work_dir(user string, target string) !(string, string) {
168+ source := if os.is_dir(target) { os.real_path(target) } else { target.trim_right('/') }
169+ name := repo_name(source)
170+ if name == '' {
171+ return error('b: "${target}" names no repo to build')
172+ }
173+ return name, pkgbuild_build_dir(user, '${name}-${sha256.hexhash(source)[..8]}')!
174+}
175+
176+// build_repo_target pulls one target, reviews it, builds and installs it.
177+// a target is an existing directory (a checkout, taken as the repo stands)
178+// or a git url to clone; bare names belong to the pkgbuild repos, which the
179+// --pkgbuild installs already cover, so the error points there
180+fn build_repo_target(config ConfigBuild, target string, mut ui TransUI) ! {
181+ user := invoker_user()!
182+ base, work_dir := repo_work_dir(user, target)!
183+ // with --nopkgbuildconfirm nothing is asked, and the review is still
184+ // shown: the record of what was built stays in the output
185+ ask := !config.no_pkgbuild_confirm
186+ ui.pause()
187+ run_as_user(user, ['mkdir', '-p', os.dir(work_dir)])!
188+ defer { ui.sync() }
189+ if os.is_dir(target) {
190+ pull_dir(user, target, work_dir)!
191+ } else if is_git_url(target) {
192+ // git is the one tool a clone cannot happen without: an absent one is
193+ // said plainly, below user's name, before anything pulls
194+ run_as_user(user, ['sh', '-c', 'git --version >/dev/null']) or {
195+ return error('git is needed to clone ${target} as user ${user}, but it was not found (or failed): ${err.msg()}')
196+ }
197+ run_as_user(user, ['rm', '-rf', work_dir])!
198+ run_as_user(user, ['git', 'clone', '--depth', '${pkgbuild_depth}', target, work_dir])!
199+ } else {
200+ return error('b: "${target}" is neither a directory nor a git url; pkgbuild repos are covered by vpac i --pkgbuild ${target}')
201+ }
202+ // makepkg builds either spelling; a bash PKGBUILD keeps the
203+ // plain makepkg flow, the lip one generates its PKGBUILD through this
204+ // binary's blip runner, and a PKGBUILD.vsh asks its own script to write
205+ // the PKGBUILD through v
206+ work_lip := '${work_dir}/PKGBUILD.lip'
207+ mut work_vsh := '${work_dir}/PKGBUILD.vsh'
208+ if os.exists(work_lip) {
209+ bb := vmakepkg.lip_make(work_lip, os.executable())!
210+ install_name := if bb.install != '' { '${bb.base}.install' } else { '' }
211+ review := generated_review(base, os.base(work_lip), os.read_file(work_lip)!,
212+ bb.text, install_name, bb.install)
213+ show_review(review, '')
214+ if ask && !ui.noyes('build and install ${base}?') {
215+ return
216+ }
217+ write_as_user(user, '${work_dir}/PKGBUILD', bb.text)!
218+ if bb.install != '' {
219+ write_as_user(user, '${work_dir}/${bb.base}.install', bb.install)!
220+ }
221+ } else if os.exists(work_vsh) {
222+ // v run compiles its temp to the script's own name inside the work
223+ // dir, right on top of the PKGBUILD the script writes, so the script
224+ // hides before anything runs
225+ hsh := '${work_dir}/.vsh'
226+ run_as_user(user, ['mv', work_vsh, hsh])!
227+ work_vsh = hsh
228+ // v lives where every tool of this project lives, and runuser's
229+ // sanitized path may not carry it, so the script runs by full path
230+ vbin := if os.getenv(env_v) != '' {
231+ os.getenv(env_v)
232+ } else {
233+ os.find_abs_path_of_executable('v') or {
234+ return error('the v compiler is not in the path; it is needed to run a PKGBUILD.vsh')
235+ }
236+ }
237+ // the temp compile goes to the side of the PKGBUILD the script writes.
238+ // the compiled runner is only for the generation: it is gone before
239+ // the review lists the dir and before makepkg could pack it, whether
240+ // the generation went through or not
241+ generated := run_as_user(user, ['sh', '-c',
242+ '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'])
243+ run_as_user(user, ['rm', '-f', '${work_dir}/.vshgen']) or {
244+ warn('could not remove the generator ${work_dir}/.vshgen: ${err.msg()}')
245+ }
246+ generated!
247+ if !os.exists('${work_dir}/PKGBUILD') {
248+ return error('${work_vsh} wrote no PKGBUILD')
249+ }
250+ pkg_text := os.read_file('${work_dir}/PKGBUILD')!
251+ install_name := install_name_of(pkg_text)!
252+ install_path := '${work_dir}/${install_name}'
253+ resolved := install_name != '' && os.is_file(install_path)
254+ install_text := if resolved { os.read_file(install_path)! } else { '' }
255+ mut review := generated_review(base, 'PKGBUILD.vsh', os.read_file(work_vsh)!, pkg_text,
256+ install_name, install_text)
257+ review_the_rest(mut review, work_dir, install_name, resolved)!
258+ show_review(review, '')
259+ if ask && !ui.noyes('build and install ${base}?') {
260+ return
261+ }
262+ } else if os.exists('${work_dir}/PKGBUILD') {
263+ show_review(read_review(base, work_dir)!, 'review ${base}')
264+ if ask && !ui.noyes('build and install ${base}?') {
265+ return
266+ }
267+ } else {
268+ return error('${work_dir} holds neither PKGBUILD, PKGBUILD.lip nor PKGBUILD.vsh')
269+ }
270+ build_phase(base, 'start')
271+ run_as_user(user, ['sh', '-c', makepkg_line(work_dir)])!
272+ build_phase(base, 'done')
273+ // everything makepkg produced goes into one install: a split package's
274+ // set lands with one transaction, one listing and one go-ahead, the way
275+ // the pkgbuild installs batch their own
276+ archives := built_packages(user, work_dir)!
277+ if archives.len == 0 {
278+ return error('b: makepkg built nothing for ${base} that its --packagelist names')
279+ }
280+ install(ConfigInstall{
281+ query: archives
282+ noconfirm: config.noconfirm
283+ })!
284+}
285+
286+// build_repo is the mode's entry: every query is one repo to build
287+fn build_repo(config ConfigBuild) ! {
288+ need_query(config.query, 'repo (a directory or a git url)')!
289+ // --noconfirm would take the build question's preset, which is no, and
290+ // build nothing with a clean exit: the refusal says so first, as the
291+ // pkgbuild installs' does
292+ if config.noconfirm && !config.no_pkgbuild_confirm {
293+ return error('a build is asked about: drop --noconfirm, or pass --nopkgbuildconfirm, to build ${config.query.join(', ')}')
294+ }
295+ mut ui := new_trans_ui(noconfirm: config.noconfirm)
296+ defer { ui.stop() }
297+ for target in config.query {
298+ build_repo_target(config, target, mut ui)!
299+ }
300+}
@@ -0,0 +1,158 @@
1+module main
2+
3+import os
4+
5+fn test_repo_name() {
6+ // the last part of the path or url, without a .git suffix. trim_right
7+ // would have cut a set of characters: digit came out as d, gist as gis
8+ cases := {
9+ 'https://example.org/mything.git': 'mything'
10+ 'https://example.org/mything': 'mything'
11+ 'https://example.org/mything.git/': 'mything'
12+ 'https://example.org/digit': 'digit'
13+ 'https://example.org/gist.git': 'gist'
14+ 'git@github.com:foo/bar.git': 'bar'
15+ 'git@host:bar.git': 'bar'
16+ '/home/u/src/thing': 'thing'
17+ '/home/u/src/thing/': 'thing'
18+ '/': ''
19+ '.': ''
20+ '': ''
21+ }
22+ for source, want in cases {
23+ got := repo_name(source)
24+ assert got == want, 'repo_name("${source}") is "${got}", not "${want}"'
25+ }
26+}
27+
28+fn test_repo_work_dir_urls() ! {
29+ old := pkgbuild_dir
30+ pkgbuild_dir = '/builds'
31+ defer { pkgbuild_dir = old }
32+
33+ name, one := repo_work_dir('u', 'https://one.example/mything.git')!
34+ _, two := repo_work_dir('u', 'https://two.example/mything.git')!
35+ _, one_slash := repo_work_dir('u', 'https://one.example/mything.git/')!
36+ assert name == 'mything'
37+ hash := one.all_after('/builds/mything-')
38+ assert one.starts_with('/builds/mything-') && hash.len == 8
39+ assert hash.bytes().all(it.is_hex_digit())
40+ // the same name from another source is another dir; a trailing slash is
41+ // the same source
42+ assert one != two
43+ assert one == one_slash
44+ // and a pkgbuild package of that name builds elsewhere
45+ assert one != pkgbuild_build_dir('u', 'mything')!
46+ if _, _ := repo_work_dir('u', '/') {
47+ assert false, '/ names no repo'
48+ }
49+}
50+
51+fn test_is_git_url() {
52+ // the transfer urls and the .git names, as always
53+ assert is_git_url('https://example.org/mything.git')
54+ assert is_git_url('git://example.org/mything')
55+ // scp-style: user@host:path — a colon before any slash, the way git
56+ // spells a clone it will fetch over ssh
57+ assert is_git_url('git@github.com:foo/bar')
58+ assert is_git_url('git@host:bar.git')
59+ assert is_scp_remote('git@host:bar.git')
60+ // a path's slash comes first; a bare file with a colon in its name has
61+ // no slash before it either, but hosts come before the colon in scp
62+ for not in ['/home/u/mything', '/home/u/we:ird', '/dev/null:too'] {
63+ assert !is_scp_remote(not), not
64+ }
65+}
66+
67+fn test_repo_work_dir_directories() ! {
68+ old := pkgbuild_dir
69+ pkgbuild_dir = '/builds'
70+ defer { pkgbuild_dir = old }
71+ tmp := os.join_path(os.vtmp_dir(), 'vpac_test_build_repo_${os.getpid()}')
72+ os.mkdir_all(os.join_path(tmp, 'a', 'mything'))!
73+ os.mkdir_all(os.join_path(tmp, 'b', 'mything'))!
74+ defer { os.rmdir_all(tmp) or {} }
75+ cwd := os.getwd()
76+ defer { os.chdir(cwd) or {} }
77+
78+ _, a := repo_work_dir('u', os.join_path(tmp, 'a', 'mything'))!
79+ _, b := repo_work_dir('u', os.join_path(tmp, 'b', 'mything'))!
80+ assert a != b
81+ // a directory is keyed on its real path: relative, trailing slash and .
82+ // all name the same checkout
83+ os.chdir(os.join_path(tmp, 'a'))!
84+ _, rel := repo_work_dir('u', 'mything/')!
85+ os.chdir(os.join_path(tmp, 'a', 'mything'))!
86+ dot_name, dot := repo_work_dir('u', '.')!
87+ assert rel == a
88+ assert dot == a
89+ assert dot_name == 'mything'
90+}
91+
92+fn test_install_name_of() ! {
93+ for text, want in {
94+ 'pkgname=x\ninstall=x.install\n': 'x.install'
95+ 'install = "x.install"': 'x.install'
96+ "install='x.install'": 'x.install'
97+ // bash reads these; this reader takes them as written
98+ 'install="\${pkgname}.install"': '\${pkgname}.install'
99+ 'install=x.install # the hooks': 'x.install # the hooks'
100+ // none named, or a command in a function body, which is no assignment
101+ 'pkgname=x\n': ''
102+ 'package() {\n install -Dm755 x "$pkgdir/x"\n}': ''
103+ 'installdir=/opt': ''
104+ // the last assignment is the one bash keeps
105+ 'install=a.install\ninstall=b.install': 'b.install'
106+ } {
107+ assert install_name_of(text)! == want, text
108+ }
109+ for escape in ['install=/etc/x.install', 'install=../x.install', 'install=a/../../x.install',
110+ 'install=..'] {
111+ install_name_of(escape) or {
112+ assert err.msg().contains('is not a plain name beside the PKGBUILD'), err.msg()
113+ continue
114+ }
115+ assert false, '${escape} was taken'
116+ }
117+}
118+
119+fn test_review_the_rest_shows_every_install_file() ! {
120+ dir := os.join_path(os.vtmp_dir(), 'vpac_test_review_rest_${os.getpid()}')
121+ os.rmdir_all(dir) or {}
122+ os.mkdir_all(os.join_path(dir, '.git'))!
123+ defer { os.rmdir_all(dir) or {} }
124+ pkg_text := 'pkgname=x\ninstall="\${pkgname}.install"\n'
125+ os.write_file(os.join_path(dir, 'PKGBUILD'), pkg_text)!
126+ os.write_file(os.join_path(dir, 'x.install'), 'post_install() { rm -rf /; }')!
127+ os.write_file(os.join_path(dir, 'other.install'), 'post_upgrade() { :; }')!
128+ os.write_file(os.join_path(dir, 'x.patch'), 'patch')!
129+ // the generated head spells its install file with a variable: the reader
130+ // cannot resolve it, and the scriptlet makepkg packs must still be shown
131+ name := install_name_of(pkg_text)!
132+ mut review := generated_review('x', 'PKGBUILD.vsh', 'script', pkg_text, name, '')
133+ review_the_rest(mut review, dir, name, false)!
134+ files := review.files.map(it.name)
135+ assert 'x.install' in files && 'other.install' in files, files.str()
136+ assert review.files.filter(it.name == 'x.install')[0].text == 'post_install() { rm -rf /; }'
137+ assert review.listing == ['PKGBUILD', 'other.install', 'x.install', 'x.patch']
138+ assert review.warnings.len == 1
139+ assert review.warnings[0].contains('"\${pkgname}.install"'), review.warnings[0]
140+
141+ // a name the reader resolved is shown once, and nothing is warned of
142+ mut plain := generated_review('x', 'PKGBUILD.vsh', 'script', 'install=x.install', 'x.install',
143+ 'post_install() { rm -rf /; }')
144+ review_the_rest(mut plain, dir, 'x.install', true)!
145+ assert plain.files.filter(it.name == 'x.install').len == 1
146+ assert plain.files.any(it.name == 'other.install')
147+ assert plain.warnings.len == 0
148+}
149+
150+fn test_build_refuses_noconfirm_alone() {
151+ // the build question's preset is no: --noconfirm alone would build
152+ // nothing and exit clean, so it is refused before anything is pulled
153+ build_repo(ConfigBuild{ noconfirm: true, query: ['/nonexistent/repo'] }) or {
154+ assert err.msg().contains('--nopkgbuildconfirm'), err.msg()
155+ return
156+ }
157+ assert false, 'built under --noconfirm'
158+}
@@ -0,0 +1,436 @@
1+module main
2+
3+import alpm
4+import os
5+import v.profiler
6+
7+// one archive file sitting in the cache, with its .sig companion removed
8+// alongside it, like pacman's cleancache does. the failures are collected and
9+// reported after: a clean that could not remove a file does not look
10+// successful, and the meter only moves past the files that went
11+fn cache_purge(mut ui TransUI, files []string) {
12+ mut bar := ui.meter(files.len, 'removing cached packages')
13+ bar.start()
14+ mut failed := []string{}
15+ for f in files {
16+ os.rm(f) or {
17+ failed << f
18+ continue
19+ }
20+ // the sig goes only once its package did. one that was never signed
21+ // has no companion to remove, so only a real failure is reported
22+ if os.exists(f + '.sig') {
23+ os.rm(f + '.sig') or { failed << f + '.sig' }
24+ }
25+ bar.add(1)
26+ }
27+ if failed.len > 0 {
28+ warn('could not remove ${failed.len} of ${files.len} cached files: ${failed.map(os.base(it)).join(', ')}')
29+ }
30+}
31+
32+// is_pkg_archive is whether a file name is a package archive's: compressed
33+// (.pkg.tar.zst and the like) or the plain .pkg.tar makepkg writes with no
34+// compression, as pacman's cache clean takes both; never a signature
35+fn is_pkg_archive(f string) bool {
36+ return (f.contains('.pkg.tar.') || f.ends_with('.pkg.tar')) && !f.ends_with('.sig')
37+}
38+
39+fn cached_pkg_files() ![]string {
40+ mut out := []string{}
41+ for dir in cfg_cachedirs {
42+ names := os.ls(dir) or {
43+ // one unreadable cache dir does not take the others' cleaning
44+ // down with it: the run cleans what it can see, and says so
45+ warn('could not list the cache directory ${dir}: ${err.msg()}, cleaning the rest')
46+ continue
47+ }
48+ // package archives only, with their directory prefixed; sigs go with
49+ // their package, dbs stay
50+ out << names.filter(|f| is_pkg_archive(f)).map(|f| os.join_path(dir, f))
51+ }
52+ return out
53+}
54+
55+// sync_db_exts are the files a sync db is kept as, sigs and file dbs too
56+const sync_db_exts = ['.db.sig', '.files.sig', '.db', '.files']
57+
58+// unused_sync_dbs are the sync db files of repos the config does not name
59+// any more, what pacman's -Sc asks about as 'unused repositories'. pacman
60+// clears everything else out of the sync dir with them; only what is
61+// plainly a db goes here, so the sync stamp and anything unknown stay
62+fn unused_sync_dbs() []string {
63+ dir := db_path + 'sync/'
64+ if !os.is_dir(dir) {
65+ return []string{}
66+ }
67+ mut names := os.ls(dir) or {
68+ warn('could not list the sync databases in ${dir}: ${err.msg()}, none is cleaned')
69+ return []string{}
70+ }
71+ names.sort()
72+ known := cfg_repos.filter(it.kind != 'pkgbuild').map(it.name)
73+ mut out := []string{}
74+ for f in names {
75+ for ext in sync_db_exts {
76+ if f.len > ext.len && f.ends_with(ext) {
77+ if f[..f.len - ext.len] !in known {
78+ out << dir + f
79+ }
80+ break
81+ }
82+ }
83+ }
84+ return out
85+}
86+
87+// a cached package archive: pkgname-pkgver-pkgrel-arch.pkg.tar[.*]
88+struct CacheFile {
89+ name string
90+ version string
91+ file string
92+}
93+
94+// installed_file is whether a cached archive is the installed version of its
95+// package. the cache is listed as full paths and the prefixes are
96+// name-version-, so the file name is what they are matched against: its
97+// name and version read out whole, as pacman compares the archive's own, so
98+// a package whose name merely begins with another's name-version- is not
99+// taken for it. a name that does not read as an archive's is matched by its
100+// beginning, the careful way round: it is kept
101+fn installed_file(f string, keep_prefixes []string) bool {
102+ if c := parse_cache_file(f) {
103+ return '${c.name}-${c.version}-' in keep_prefixes
104+ }
105+ name := os.base(f)
106+ return keep_prefixes.any(|k| name.starts_with(k))
107+}
108+
109+fn parse_cache_file(f string) ?CacheFile {
110+ base := os.base(f).all_before('.pkg.tar')
111+ toks := base.split('-')
112+ if toks.len < 4 {
113+ return none
114+ }
115+ arch_t := toks.last()
116+ rel := toks[toks.len - 2]
117+ ver := toks[toks.len - 3]
118+ name := toks[..toks.len - 3].join('-')
119+ if arch_t == '' || rel == '' || ver == '' || name == '' {
120+ return none
121+ }
122+ return CacheFile{
123+ name: name
124+ version: ver + '-' + rel
125+ file: f
126+ }
127+}
128+
129+// paccache's KeepInstalled+KeepN: keep the newest `keep_n` versions of every
130+// package, plus whatever is currently installed. an installed version is
131+// kept once even though it also counts among the newest, so the answer is a
132+// set and the caller's filtering reads it straight
133+fn paccache_keep(keep_n int, files []string, keep_prefixes []string) map[string]bool {
134+ mut groups := map[string][]CacheFile{}
135+ mut kept := map[string]bool{}
136+ for f in files {
137+ // installed versions are always kept, and they still count among the
138+ // newest: -k 2 keeps two versions, not the installed one and two more
139+ if installed_file(f, keep_prefixes) {
140+ kept[f] = true
141+ }
142+ cf := parse_cache_file(f) or { continue }
143+ if cf.name !in groups {
144+ groups[cf.name] = []CacheFile{}
145+ }
146+ groups[cf.name] << cf
147+ }
148+ for name in groups.keys() {
149+ mut gg := groups[name]
150+ // newest first, using the same vercmp as pacman
151+ gg.sort_with_compare(fn (a &CacheFile, b &CacheFile) int {
152+ return alpm.pkg_vercmp(b.version, a.version)
153+ })
154+ for i, cf in gg {
155+ if i < keep_n {
156+ kept[cf.file] = true
157+ }
158+ }
159+ }
160+ return kept
161+}
162+
163+// BuildClean is what vpac c does with the pkgbuild build dirs: of the builds
164+// found under root, the ones it removes and their size
165+struct BuildClean {
166+ user string
167+ root string
168+mut:
169+ found int
170+ dirs []string
171+ size u64
172+ // partial says the size is a floor: part of a build could not be read,
173+ // and what is there is more than was counted
174+ partial bool
175+}
176+
177+// build_dirs_to_clean picks the pkgbuild builds vpac c removes. like paru's
178+// and yay's clean, a build stays while its package is installed: its dir is
179+// named after an installed package base (vpac i --pkgbuild), or it holds a
180+// built archive of an installed package (vpac b, split packages). with all,
181+// every build goes. a build is pulled afresh each time, so nothing in a
182+// removed one is ever reused
183+fn build_dirs_to_clean(user string, all bool, bases []string, names []string) !BuildClean {
184+ root := pkgbuild_root(user)!
185+ mut bc := BuildClean{
186+ user: user
187+ root: root
188+ }
189+ if !os.is_dir(root) {
190+ return bc
191+ }
192+ for entry in os.ls(root)! {
193+ dir := os.join_path(root, entry)
194+ if os.is_link(dir) || !os.is_dir(dir) {
195+ continue
196+ }
197+ bc.found++
198+ if !all && build_in_use(dir, entry, bases, names) {
199+ continue
200+ }
201+ bc.dirs << dir
202+ size, whole := tree_size(dir)
203+ bc.size += size
204+ if !whole {
205+ bc.partial = true
206+ }
207+ }
208+ return bc
209+}
210+
211+// build_in_use is whether a build dir belongs to an installed package
212+fn build_in_use(dir string, entry string, bases []string, names []string) bool {
213+ if entry in bases {
214+ return true
215+ }
216+ // fail closed: when the build cannot even be listed, it cannot be proven
217+ // unused, and clean never deletes something it is not sure of. clean runs
218+ // as root through run_as_user, so an unreadable dir is reported plainly
219+ pkgs := archives_in(dir) or {
220+ warn("could not list the built packages of '${dir}': ${err.msg()}, keeping the build")
221+ return true
222+ }
223+ for archive in pkgs {
224+ cf := parse_cache_file(os.base(archive)) or { continue }
225+ if cf.name in names {
226+ return true
227+ }
228+ }
229+ return false
230+}
231+
232+// tree_size adds up the files under path, and says whether that is the
233+// whole of it: a directory that cannot be listed is warned about and
234+// counted as nothing, which makes the sum a floor and not the size. the
235+// rest of the tree is still counted. links are not followed: a build tree
236+// may point anywhere
237+fn tree_size(path string) (u64, bool) {
238+ if os.is_link(path) {
239+ return 0, true
240+ }
241+ if !os.is_dir(path) {
242+ return os.file_size(path), true
243+ }
244+ names := os.ls(path) or {
245+ warn('could not read ${path}: ${err.msg()}, its size is left out')
246+ return 0, false
247+ }
248+ mut total := u64(0)
249+ mut whole := true
250+ for name in names {
251+ size, sub_whole := tree_size(os.join_path(path, name))
252+ total += size
253+ whole = whole && sub_whole
254+ }
255+ return total, whole
256+}
257+
258+// size_text spells a size for a person; one that is a floor says so
259+fn size_text(size u64, partial bool) string {
260+ text := profiler.format_bytes(size)
261+ return if partial { 'at least ${text}' } else { text }
262+}
263+
264+// clean_event is what a frontend is told before the proceed question. the
265+// build root goes out only when an invoker was known and its builds looked
266+// at; BuildClean{} is the unlooked-at one
267+fn clean_event(to_remove []string, total u64, builds BuildClean, dbs []string, preview bool) CleanEvent {
268+ return CleanEvent{
269+ cache_dirs: cfg_cachedirs
270+ build_root: if builds.user != '' { ?string(builds.root) } else { none }
271+ files: to_remove
272+ files_size: total
273+ builds: builds.dirs
274+ build_size: builds.size
275+ build_size_partial: builds.partial
276+ dbs: dbs
277+ preview: preview
278+ }
279+}
280+
281+fn clean(config ConfigClean) ! {
282+ mut ui := new_trans_ui(noconfirm: config.noconfirm)
283+ mut handle := init_handle(ui)!
284+ defer { handle.release() or { went_on('release the alpm handle', err) } }
285+ defer { ui.stop() }
286+
287+ mut pkgcache := local_pkgcache(handle)!
288+ installed := pkgcache.pkgs()
289+
290+ // the package cache: everything with -a or -cc (pacman's -Scc),
291+ // otherwise pacman's default KeepInstalled clean method, optionally
292+ // paccache style with -k N: keep the newest N versions of every package
293+ every := config.all || config.level >= 2
294+ pkg_files := cached_pkg_files()!
295+ to_remove := if every {
296+ pkg_files
297+ } else {
298+ mut keep_prefixes := installed.map(|pkg| '${pkg.get_name()}-${pkg.get_version()}-')
299+ // pacman's KeepCurrent: a version a sync db still carries stays too
300+ if config.keep_current {
301+ for db in init_repos(mut handle)! {
302+ // a sync db that cannot be read would keep nothing: what it
303+ // carries would be cleaned as if no repo had it any more
304+ mut cache := pkgcache_of(handle, db)!
305+ keep_prefixes << cache.pkgs().map(|pkg| '${pkg.get_name()}-${pkg.get_version()}-')
306+ }
307+ }
308+ to_keep := if config.keep > 0 {
309+ // a set of paths, not a list: a cache of thousands of archives is
310+ // filtered by map lookup per file, not a scan per file
311+ paccache_keep(config.keep, pkg_files, keep_prefixes)
312+ } else {
313+ mut keep := map[string]bool{}
314+ for f in pkg_files.filter(|f| installed_file(f, keep_prefixes)) {
315+ keep[f] = true
316+ }
317+ keep
318+ }
319+ pkg_files.filter(|f| !to_keep[f])
320+ }
321+ mut total := u64(0)
322+ for f in to_remove {
323+ total += os.file_size(f)
324+ }
325+
326+ // the pkgbuild builds are the invoker's: root running vpac c itself has
327+ // none, since builds never run as root. a root session nobody asked for
328+ // says so, instead of quietly leaving every build dir behind it
329+ mut builds := BuildClean{}
330+ if user := invoker_user() {
331+ builds = build_dirs_to_clean(user, config.all, installed.map(it.get_base()),
332+ installed.map(it.get_name()))!
333+ } else {
334+ warn('pkgbuild builds are not cleaned: run vpac as your own user')
335+ }
336+
337+ // the sync dbs of repos the config dropped go with any clean, as
338+ // pacman's -Sc offers
339+ dbs := unused_sync_dbs()
340+
341+ // a frontend gets what would go as one event; the proceed question follows
342+ // it unless this is a --print preview
343+ if ipc_on() {
344+ emit(clean_event(to_remove, total, builds, dbs, config.print_only))
345+ if config.print_only || (to_remove.len == 0 && builds.dirs.len == 0 && dbs.len == 0) {
346+ return
347+ }
348+ }
349+ // --print lists what would go, a path a line, and removes nothing
350+ if config.print_only {
351+ for f in to_remove {
352+ println(f)
353+ }
354+ for dir in builds.dirs {
355+ println(dir)
356+ }
357+ for f in dbs {
358+ println(f)
359+ }
360+ return
361+ }
362+
363+ mut summary := [kv('cache directory', cfg_cachedirs.join(', '))]
364+ if pkg_files.len > 0 {
365+ if every {
366+ summary << kv('remove', 'all ${pkg_files.len} files (${profiler.format_bytes(total)})')
367+ } else {
368+ summary << kv('keep', 'all locally installed packages')
369+ if config.keep_current {
370+ summary << row('', 'the versions the sync dbs carry')
371+ }
372+ if config.keep > 0 {
373+ summary << row('', 'the ${config.keep} newest versions of every package')
374+ }
375+ summary << kv('remove', if to_remove.len == 0 {
376+ 'nothing'
377+ } else {
378+ '${to_remove.len} files (${profiler.format_bytes(total)})'
379+ })
380+ }
381+ }
382+ if builds.found > 0 {
383+ summary << kv('build directory', builds.root)
384+ if config.all {
385+ summary << kv('remove', 'all ${builds.found} builds (${size_text(builds.size, builds.partial)})')
386+ } else {
387+ summary << kv('keep', 'the builds of installed packages')
388+ summary << kv('remove', if builds.dirs.len == 0 {
389+ 'nothing'
390+ } else {
391+ '${builds.dirs.len} builds (${size_text(builds.size, builds.partial)}): ${builds.dirs.map(os.base(it)).join(', ')}'
392+ })
393+ }
394+ }
395+ if dbs.len > 0 {
396+ summary << kv('database directory', db_path + 'sync/')
397+ summary << kv('remove', '${dbs.len} files of unused repos: ${dbs.map(os.base(it)).join(', ')}')
398+ }
399+ if !ipc_on() {
400+ println(table_text(summary, '', ' '))
401+ }
402+ if to_remove.len == 0 && builds.dirs.len == 0 && dbs.len == 0 {
403+ println(if pkg_files.len == 0 && builds.found == 0 {
404+ 'cache is empty'
405+ } else {
406+ 'nothing to remove'
407+ })
408+ return
409+ }
410+ if !ui.proceed('proceed?') {
411+ return
412+ }
413+ if to_remove.len > 0 {
414+ cache_purge(mut ui, to_remove)
415+ }
416+ if dbs.len > 0 {
417+ mut failed := []string{}
418+ for f in dbs {
419+ os.rm(f) or { failed << os.base(f) }
420+ }
421+ if failed.len > 0 {
422+ warn('could not remove ${failed.len} of ${dbs.len} unused sync database files: ${failed.join(', ')}')
423+ }
424+ }
425+ if builds.dirs.len > 0 {
426+ // removed as the user who built them, the way the builds clear their
427+ // own dirs: root never deletes inside the user's tree
428+ mut s := ui.spinner(text: 'removing pkgbuild builds')
429+ s.start()
430+ defer { stop_spinner(mut s) }
431+ mut args := ['rm', '-rf', '--']
432+ args << builds.dirs
433+ run_as_user(builds.user, args)!
434+ stop_spinner(mut s)
435+ }
436+}
@@ -0,0 +1,193 @@
1+module main
2+
3+import json2
4+import os
5+
6+fn test_parse_cache_file() {
7+ cases := {
8+ 'zsh-5.9.2-1-x86_64.pkg.tar.zst': 'zsh 5.9.2-1'
9+ '/var/cache/pacman/pkg/zsh-5.9.2-1-x86_64.pkg.tar.zst': 'zsh 5.9.2-1'
10+ 'gcc-libs-14.2.1+r1-1-x86_64.pkg.tar.zst': 'gcc-libs 14.2.1+r1-1'
11+ 'vim-2:9.1.0-1-x86_64.pkg.tar.zst': 'vim 2:9.1.0-1'
12+ 'python-3.12.7-1-x86_64.pkg.tar.xz': 'python 3.12.7-1'
13+ // dashes in the cache dir are not part of the name
14+ '/tmp/a-dir-with-dashes/foo-1.0-1-any.pkg.tar.zst': 'foo 1.0-1'
15+ }
16+ for file, want in cases {
17+ cf := parse_cache_file(file) or {
18+ assert false, '${file} did not parse'
19+ continue
20+ }
21+ assert '${cf.name} ${cf.version}' == want, file
22+ assert cf.file == file
23+ }
24+ for bad in ['broken.pkg.tar.zst', 'a-1-x.pkg.tar.zst', '-1-1-any.pkg.tar.zst'] {
25+ if cf := parse_cache_file(bad) {
26+ assert false, '${bad} parsed as ${cf.name} ${cf.version}'
27+ }
28+ }
29+}
30+
31+fn test_installed_file() {
32+ prefixes := ['zsh-5.9.2-1-', 'gcc-libs-14.2.1-1-']
33+ // the cache is listed as full paths: the file name is what counts
34+ assert installed_file('/var/cache/pacman/pkg/zsh-5.9.2-1-x86_64.pkg.tar.zst', prefixes)
35+ assert installed_file('zsh-5.9.2-1-x86_64.pkg.tar.zst', prefixes)
36+ assert installed_file('/c/gcc-libs-14.2.1-1-x86_64.pkg.tar.zst', prefixes)
37+ assert !installed_file('/var/cache/pacman/pkg/zsh-5.9.1-1-x86_64.pkg.tar.zst', prefixes)
38+ assert !installed_file('/c/zsh-completions-0.35-1-any.pkg.tar.zst', prefixes)
39+ // a dir that looks like the prefix does not make its files installed
40+ assert !installed_file('/c/zsh-5.9.2-1-x/foo-1.0-1-any.pkg.tar.zst', prefixes)
41+ assert !installed_file('/c/zsh-5.9.2-1-x86_64.pkg.tar.zst', [])
42+ // an uncompressed archive is one too
43+ assert installed_file('/c/zsh-5.9.2-1-x86_64.pkg.tar', prefixes)
44+ assert is_pkg_archive('zsh-5.9.2-1-x86_64.pkg.tar') && is_pkg_archive('a-1-1-any.pkg.tar.zst')
45+ assert !is_pkg_archive('a-1-1-any.pkg.tar.zst.sig') && !is_pkg_archive('core.db')
46+ // a package whose name begins with another's name-version- is its own:
47+ // zsh-5.9.2-1-extras 2-1 is not zsh 5.9.2-1
48+ assert !installed_file('/c/zsh-5.9.2-1-extras-2-1-any.pkg.tar.zst', prefixes)
49+}
50+
51+// an unreadable cache dir does not stop the cleaning of the ones that read:
52+// the files of the rest come through, spelled out whole
53+fn test_cached_pkg_files_skips_a_lost_cache_dir() ! {
54+ tmp := os.join_path(os.vtmp_dir(), 'vpac_test_cache_${os.getpid()}')
55+ real := os.join_path(tmp, 'pkg') + '/'
56+ os.mkdir_all(real)!
57+ defer {
58+ os.rmdir_all(tmp) or {}
59+ }
60+ os.write_file(os.join_path(real, 'zsh-5.9.2-1-x86_64.pkg.tar.zst'), '.')!
61+ os.write_file(os.join_path(real, 'zsh-5.9.2-1-x86_64.pkg.tar.zst.sig'), '.')!
62+
63+ mut old := cfg_cachedirs.clone()
64+ defer { cfg_cachedirs = old.clone() }
65+ cfg_cachedirs = [real, '/nonexistent-vpac-test/']
66+ files := cached_pkg_files()!
67+ assert files == ['${real}zsh-5.9.2-1-x86_64.pkg.tar.zst'], files.str()
68+ // the spelled-out path is a real one
69+ assert os.exists(files[0])
70+}
71+
72+// kept_names is the set paccache_keep keeps, as sorted file names
73+fn kept_names(kept map[string]bool) []string {
74+ mut names := map[string]bool{}
75+ for f, on in kept {
76+ if !on {
77+ continue
78+ }
79+ names[os.base(f).all_before('.pkg.tar.')] = true
80+ }
81+ mut out := names.keys()
82+ out.sort()
83+ return out
84+}
85+
86+fn test_paccache_keep() {
87+ files := [
88+ '/c/foo-1.9-1-any.pkg.tar.zst',
89+ '/c/foo-1.10-1-any.pkg.tar.zst',
90+ '/c/zsh-5.9.1-1-x86_64.pkg.tar.zst',
91+ '/c/zsh-5.9.2-1-x86_64.pkg.tar.zst',
92+ '/c/zsh-6.0-1-x86_64.pkg.tar.zst',
93+ ]
94+ installed := ['zsh-5.9.2-1-']
95+ // newest by pacman's vercmp: 1.10 is newer than 1.9. the installed
96+ // version is always kept, and it counts among the newest
97+ assert kept_names(paccache_keep(1, files, installed)) == ['foo-1.10-1-any', 'zsh-5.9.2-1-x86_64',
98+ 'zsh-6.0-1-x86_64']
99+ assert kept_names(paccache_keep(2, files, installed)) == ['foo-1.10-1-any', 'foo-1.9-1-any',
100+ 'zsh-5.9.2-1-x86_64', 'zsh-6.0-1-x86_64']
101+ assert kept_names(paccache_keep(3, files, installed)).len == 5
102+ assert kept_names(paccache_keep(1, files, [])) == ['foo-1.10-1-any', 'zsh-6.0-1-x86_64']
103+}
104+
105+fn test_clean_event_build_root() ! {
106+ saved := cfg_cachedirs.clone()
107+ defer { cfg_cachedirs = saved.clone() }
108+ cfg_cachedirs = ['/cache/']
109+ // no invoker known: the builds were not looked at, and the event says so
110+ // by leaving the root out, rather than an empty one beside no builds
111+ unknown := clean_event(['/cache/a.pkg.tar.zst'], 10, BuildClean{}, []string{}, false)
112+ assert unknown.build_root == none
113+ text := json2.encode(unknown)
114+ assert !text.contains('build_root'), text
115+ assert text.contains('"files":["/cache/a.pkg.tar.zst"]')
116+ // an invoker known, with no build found: the root goes out, the list is
117+ // empty, and that does mean none
118+ looked := clean_event([], 0, BuildClean{
119+ user: 'someone'
120+ root: '/home/someone/.cache/vpac/pkgbuild'
121+ }, ['/db/sync/gone.db'], true)
122+ assert looked.build_root? == '/home/someone/.cache/vpac/pkgbuild'
123+ doc := json2.decode[json2.Any](json2.encode(looked))!.as_map()
124+ assert doc['build_root']!.str() == '/home/someone/.cache/vpac/pkgbuild'
125+ assert doc['builds']!.as_array().len == 0
126+ assert doc['dbs']!.as_array().map(it.str()) == ['/db/sync/gone.db']
127+ assert doc['preview']!.bool()
128+ assert doc['type']!.str() == 'clean'
129+}
130+
131+fn test_tree_size_says_when_it_is_a_floor() ! {
132+ tmp := os.join_path(os.vtmp_dir(), 'vpac_test_tree_size_${os.getpid()}')
133+ deep := os.join_path(tmp, 'a', 'closed')
134+ os.mkdir_all(deep)!
135+ os.mkdir_all(os.join_path(tmp, 'b', 'empty'))!
136+ defer {
137+ os.chmod(deep, 0o755) or {}
138+ os.rmdir_all(tmp) or {}
139+ }
140+ os.write_file(os.join_path(tmp, 'top'), 'x'.repeat(10))!
141+ os.write_file(os.join_path(tmp, 'a', 'file'), 'x'.repeat(100))!
142+ os.write_file(os.join_path(deep, 'hidden'), 'x'.repeat(1000))!
143+ os.write_file(os.join_path(tmp, 'b', 'file'), 'x'.repeat(5))!
144+ // a link is not followed, whatever it points at, and is no gap
145+ os.symlink(os.join_path(tmp, 'a'), os.join_path(tmp, 'b', 'link'))!
146+ os.symlink('/nonexistent-vpac-test', os.join_path(tmp, 'b', 'dangling'))!
147+ // everything readable: the whole size, said to be whole
148+ size, whole := tree_size(tmp)
149+ assert size == 1115 && whole
150+ // a plain file, an empty dir and a link are each whole
151+ fsize, fwhole := tree_size(os.join_path(tmp, 'top'))
152+ assert fsize == 10 && fwhole
153+ esize, ewhole := tree_size(os.join_path(tmp, 'b', 'empty'))
154+ assert esize == 0 && ewhole
155+ lsize, lwhole := tree_size(os.join_path(tmp, 'b', 'link'))
156+ assert lsize == 0 && lwhole
157+ // what is not there is nothing, and not a gap in something
158+ gsize, gwhole := tree_size(os.join_path(tmp, 'gone'))
159+ assert gsize == 0 && gwhole
160+ if os.geteuid() == 0 {
161+ // root reads a closed directory all the same
162+ return
163+ }
164+ // a directory that cannot be listed, two levels down: the rest is
165+ // still counted, and the sum is said to be a floor all the way up
166+ os.chmod(deep, 0o000)!
167+ psize, pwhole := tree_size(tmp)
168+ assert psize == 115 && !pwhole
169+ asize, awhole := tree_size(os.join_path(tmp, 'a'))
170+ assert asize == 100 && !awhole
171+ // its sibling is not tainted by it
172+ bsize, bwhole := tree_size(os.join_path(tmp, 'b'))
173+ assert bsize == 5 && bwhole
174+ // the closed directory itself is nothing, and not whole
175+ csize, cwhole := tree_size(deep)
176+ assert csize == 0 && !cwhole
177+ // the builds' sum carries the mark, and a person is told 'at least'
178+ saved := pkgbuild_dir
179+ defer { pkgbuild_dir = saved }
180+ pkgbuild_dir = tmp
181+ bc := build_dirs_to_clean('nobody', true, [], [])!
182+ assert bc.dirs.len == 2 && bc.size == 105 && bc.partial
183+ assert size_text(bc.size, bc.partial) == 'at least 105B' || size_text(bc.size, bc.partial).starts_with('at least 105')
184+ assert !size_text(105, false).starts_with('at least')
185+ ev := json2.decode[json2.Any](json2.encode(clean_event([], 0, bc, [], false)))!.as_map()
186+ assert ev['build_size_partial']!.bool() && ev['build_size']!.i64() == 105
187+ // a build tree that is all readable leaves the mark off, and present
188+ os.chmod(deep, 0o755)!
189+ ok := build_dirs_to_clean('nobody', true, [], [])!
190+ assert ok.size == 1105 && !ok.partial
191+ whole_ev := json2.decode[json2.Any](json2.encode(clean_event([], 0, ok, [], false)))!.as_map()
192+ assert !whole_ev['build_size_partial']!.bool()
193+}
@@ -0,0 +1,753 @@
1+@[has_globals]
2+module main
3+
4+import flag
5+import os
6+import vmakepkg
7+
8+struct ConfigSearch {
9+pub mut:
10+ show_help bool @[long: help; short: h]
11+ noconfirm bool @[long: noconfirm]
12+ local bool @[long: local; short: l]
13+ remote bool @[long: remote; short: r]
14+ pkgbuild bool @[long: pkgbuild; short: b]
15+ quiet bool @[long: quiet; short: q]
16+ fuzzy bool @[long: fuzzy; short: f]
17+ thold f64 = 0.9 @[long: thold; short: t]
18+ sync_dbs bool @[long: sync; short: s]
19+ deps bool @[long: deps; short: d]
20+ explicit bool @[long: explicit; short: e]
21+ foreign bool @[long: foreign; short: m]
22+ native bool @[long: native; short: n]
23+ unrequired bool @[long: unrequired]
24+ // --unrequired given twice is pacman's -tt; the flag parser counts short
25+ // flags only, so parse_mode counts the long one itself
26+ unrequired_level int @[ignore]
27+ upgrades bool @[long: upgrades; short: u]
28+ groups bool @[long: groups]
29+ groups_level int @[only: g; repeats]
30+ installed bool @[long: installed; short: i]
31+ fields string @[long: fields; short: F]
32+ query []string @[tail]
33+}
34+
35+struct ConfigInstall {
36+pub mut:
37+ show_help bool @[long: help; short: h]
38+ noconfirm bool @[long: noconfirm]
39+ no_upgrade_deps bool @[long: no_upgrade_deps]
40+ pkgbuild bool @[long: pkgbuild; short: b]
41+ no_pkgbuild_confirm bool @[long: nopkgbuildconfirm]
42+ download_only bool @[long: download_only; short: w]
43+ print_only bool @[long: print; short: p]
44+ needed bool @[long: needed]
45+ asdeps bool @[long: asdeps]
46+ asexplicit bool @[long: asexplicit]
47+ dbonly bool @[long: dbonly]
48+ nodeps bool @[long: nodeps]
49+ nodeps_level int @[only: d; repeats]
50+ overwrite []string @[long: overwrite]
51+ ignore []string @[long: ignore]
52+ ignoregroup []string @[long: ignoregroup]
53+ assume_installed []string @[long: assume_installed]
54+ disable_timeout bool @[long: disable_timeout]
55+ query []string @[tail]
56+}
57+
58+// trans_options are the transaction options a command line carries:
59+// install's and upgrade's are the same four flags, read through one body
60+fn trans_options[T](c T) TransOptions {
61+ return TransOptions{
62+ overwrite: c.overwrite
63+ ignore: c.ignore
64+ ignoregroup: c.ignoregroup
65+ assume_installed: c.assume_installed
66+ }
67+}
68+
69+struct ConfigInfo {
70+pub mut:
71+ show_help bool @[long: help; short: h]
72+ noconfirm bool @[long: noconfirm]
73+ fields string @[long: fields; short: F]
74+ changelog bool @[long: changelog; short: c]
75+ file bool @[long: file; short: p]
76+ query []string @[tail]
77+}
78+
79+struct ConfigWhich {
80+pub mut:
81+ show_help bool @[long: help; short: h]
82+ query []string @[tail]
83+}
84+
85+struct ConfigRank {
86+pub mut:
87+ show_help bool @[long: help; short: h]
88+ stdin bool @[long: stdin]
89+ top int = 10 @[long: top; short: n]
90+ mirrorlist bool @[long: mirrorlist; short: m]
91+ output string @[long: output; short: o]
92+ path string @[long: path]
93+ write bool @[long: write; short: w]
94+ query []string @[tail]
95+}
96+
97+struct ConfigVerify {
98+pub mut:
99+ show_help bool @[long: help; short: h]
100+ checksums bool @[long: checksums]
101+ checksums_level int @[only: k; repeats]
102+ full bool @[long: full]
103+ db bool @[long: db]
104+ db_level int @[only: D; repeats]
105+ query []string @[tail]
106+}
107+
108+struct ConfigFind {
109+pub mut:
110+ show_help bool @[long: help; short: h]
111+ noconfirm bool @[long: noconfirm]
112+ refresh bool @[long: refresh; short: y]
113+ list bool @[long: list; short: l]
114+ quiet bool @[long: quiet; short: q]
115+ regex bool @[long: regex; short: x]
116+ machinereadable bool @[long: machinereadable]
117+ repos string @[long: repos; short: r]
118+ query []string @[tail]
119+}
120+
121+struct ConfigMark {
122+pub mut:
123+ show_help bool @[long: help; short: h]
124+ noconfirm bool @[long: noconfirm]
125+ reason string @[long: reason; short: r]
126+ query []string @[tail]
127+}
128+
129+struct ConfigRemove {
130+pub mut:
131+ show_help bool @[long: help; short: h]
132+ noconfirm bool @[long: noconfirm]
133+ print_only bool @[long: print; short: p]
134+ recursive bool @[long: recursive]
135+ recursive_level int @[only: s; repeats]
136+ unneeded bool @[long: unneeded; short: u]
137+ cascade bool @[long: cascade; short: c]
138+ nosave bool @[long: nosave; short: n]
139+ dbonly bool @[long: dbonly]
140+ nodeps bool @[long: nodeps]
141+ nodeps_level int @[only: d; repeats]
142+ assume_installed []string @[long: assume_installed]
143+ query []string @[tail]
144+}
145+
146+struct ConfigUpgrade {
147+pub mut:
148+ show_help bool @[long: help; short: h]
149+ noconfirm bool @[long: noconfirm]
150+ print_only bool @[long: print; short: p]
151+ sync_dbs bool @[long: sync; short: s]
152+ download_only bool @[long: download_only; short: w]
153+ dbonly bool @[long: dbonly]
154+ nodeps bool @[long: nodeps]
155+ nodeps_level int @[only: d; repeats]
156+ downgrade bool @[long: downgrade]
157+ sysupgrade_level int @[only: u; repeats]
158+ overwrite []string @[long: overwrite]
159+ ignore []string @[long: ignore]
160+ ignoregroup []string @[long: ignoregroup]
161+ disable_timeout bool @[long: disable_timeout]
162+ assume_installed []string @[long: assume_installed]
163+}
164+
165+struct ConfigFiles {
166+pub mut:
167+ show_help bool @[long: help; short: h]
168+ noconfirm bool @[long: noconfirm]
169+ query []string @[tail]
170+}
171+
172+struct ConfigOwner {
173+pub mut:
174+ show_help bool @[long: help; short: h]
175+ quiet bool @[long: quiet; short: q]
176+ query []string @[tail]
177+}
178+
179+struct ConfigOrphans {
180+pub mut:
181+ show_help bool @[long: help; short: h]
182+ // pacman's -Qdt and -Qdtt: twice lists the dependencies something still
183+ // names as optional too
184+ level int @[only: t; repeats]
185+}
186+
187+struct ConfigClean {
188+pub mut:
189+ show_help bool @[long: help; short: h]
190+ noconfirm bool @[long: noconfirm]
191+ print_only bool @[long: print; short: p]
192+ all bool @[long: all; short: a]
193+ keep int @[long: keep; short: k]
194+ keep_current bool @[long: keep_current]
195+ // pacman's -Sc and -Scc: once is the default clean, twice every archive
196+ level int @[only: c; repeats]
197+}
198+
199+struct ConfigTree {
200+pub mut:
201+ show_help bool @[long: help; short: h]
202+ noconfirm bool @[long: noconfirm]
203+ reverse bool @[long: reverse; short: r]
204+ optional bool @[long: optional; short: o]
205+ depth int @[long: depth; short: d]
206+ query []string @[tail]
207+}
208+
209+struct ConfigAutoRemove {
210+pub mut:
211+ show_help bool @[long: help; short: h]
212+ noconfirm bool @[long: noconfirm]
213+}
214+
215+@[noreturn]
216+fn print_err(e string) {
217+ if ipc_on() {
218+ // an error before the run started ends it all the same: the channel
219+ // opens for it (once: ipc_start is guarded), so every stream starts
220+ // with its hello and ends with its exit
221+ ipc_start()
222+ emit(ErrorEvent{
223+ msg: e
224+ })
225+ } else {
226+ eprintln(error_text(e))
227+ }
228+ end_run(1)
229+}
230+
231+// error_text is an error line the way vpac prints them, 'error: ' in bold red
232+fn error_text(e string) string {
233+ return erole('error', 'error: ') + e
234+}
235+
236+// failed_targets counts the targets a query reported bad and skipped. like
237+// pacman's queries, it goes on with the rest, and main exits 1 at the end
238+// when any failed
239+__global failed_targets = 0
240+
241+// target_error reports one bad target of a query that goes on with the next
242+fn target_error(e string) {
243+ failed_targets++
244+ if ipc_on() {
245+ emit(ErrorEvent{
246+ msg: e
247+ target: true
248+ })
249+ return
250+ }
251+ os.flush()
252+ eprintln(error_text(e))
253+}
254+
255+// need_query stops a command that acts on targets when none were given
256+fn need_query(query []string, what string) ! {
257+ if query.len == 0 {
258+ return error('no ${what} given')
259+ }
260+}
261+
262+// scan_globals collects vpac's own flags, wherever they stand in the command
263+// line: --config chooses the config file, --eval extends the config with blip
264+// code run after it. both repeatable, both also usable as --flag=value. the
265+// flags are stripped from the args (the program name stays first, the mode
266+// second), so a mode never sees them; escalation still gets the original
267+// args, so the root process reads the same config and evals
268+fn scan_globals(args []string) !(string, []string, []string) {
269+ // the frontend is settled before any other flag can fail: an error is
270+ // told over the channel whenever --ui ipc is on the command line, not
271+ // only when it happens to come before the flag that is wrong
272+ if kind := scan_ui(args) {
273+ ui_kind = kind
274+ }
275+ mut chosen := ''
276+ mut evals := []string{}
277+ mut rest := [args[0]]
278+ mut i := 1
279+ for i < args.len {
280+ arg := args[i]
281+ if arg == '--config' || arg == '--eval' {
282+ if i + 1 >= args.len {
283+ return error('${arg} needs a value')
284+ }
285+ value := args[i + 1]
286+ if value == '' {
287+ return error('${arg} needs a value')
288+ }
289+ if arg == '--config' {
290+ chosen = value
291+ } else {
292+ evals << value
293+ }
294+ i += 2
295+ } else if arg.starts_with('--config=') {
296+ chosen = arg.all_after('=')
297+ if chosen == '' {
298+ return error('--config needs a file')
299+ }
300+ i++
301+ } else if arg.starts_with('--eval=') {
302+ expr := arg.all_after('=')
303+ if expr == '' {
304+ return error('--eval needs blip code')
305+ }
306+ evals << expr
307+ i++
308+ } else if arg == '--color' || arg.starts_with('--color=') {
309+ // pacman's --color: auto (the default) styles a terminal only
310+ mut value := arg.all_after('=')
311+ if arg == '--color' {
312+ if i + 1 >= args.len {
313+ return error('--color needs a value: auto, always or never')
314+ }
315+ i++
316+ value = args[i]
317+ }
318+ if value !in ['auto', 'always', 'never'] {
319+ return error('--color takes auto, always or never, not "${value}"')
320+ }
321+ color_flag = value
322+ color_given = true
323+ i++
324+ } else if arg == '--verbose' {
325+ // the verbose log: the housekeeping failures a run goes on from
326+ verbose_flag = true
327+ i++
328+ } else if arg == '--ui' || arg.starts_with('--ui=') {
329+ // the frontend: tty, a person at a terminal, or ipc, a program
330+ // speaking json lines (ipc.v)
331+ mut value := arg.all_after('=')
332+ if arg == '--ui' {
333+ if i + 1 >= args.len {
334+ return error('--ui needs a value: tty or ipc')
335+ }
336+ i++
337+ value = args[i]
338+ }
339+ if value !in ['tty', 'ipc'] {
340+ return error('--ui takes tty or ipc, not "${value}"')
341+ }
342+ ui_kind = value
343+ i++
344+ } else {
345+ rest << arg
346+ i++
347+ }
348+ }
349+ return chosen, evals, rest
350+}
351+
352+// global_value_flags are vpac's own flags that take the next argument as
353+// their value when spelled without '='
354+const global_value_flags = ['--config', '--eval', '--color', '--ui']
355+
356+// scan_ui finds the --ui the command line settles on — the last valid one,
357+// as scan_globals lets the last win — stepping over the values of the other
358+// globals the way scan_globals reads them, so an --eval whose code is the
359+// text '--ui' is not taken for the flag. none when there is no valid one:
360+// a bad value is scan_globals' error to give, on the terminal
361+fn scan_ui(args []string) ?string {
362+ mut found := ?string(none)
363+ mut i := 1
364+ for i < args.len {
365+ arg := args[i]
366+ if arg.starts_with('--ui=') {
367+ value := arg.all_after('=')
368+ if value in ['tty', 'ipc'] {
369+ found = value
370+ }
371+ } else if arg == '--ui' && i + 1 < args.len && args[i + 1] in ['tty', 'ipc'] {
372+ found = args[i + 1]
373+ }
374+ i += if arg in global_value_flags { 2 } else { 1 }
375+ }
376+ return found
377+}
378+
379+// ModeConfig is a mode's command line, parsed: which mode, with its flags
380+type ModeConfig = ConfigAutoRemove
381+ | ConfigBuild
382+ | ConfigClean
383+ | ConfigDeptest
384+ | ConfigFiles
385+ | ConfigFind
386+ | ConfigInfo
387+ | ConfigInstall
388+ | ConfigMark
389+ | ConfigOrphans
390+ | ConfigOwner
391+ | ConfigRank
392+ | ConfigRemove
393+ | ConfigSearch
394+ | ConfigTree
395+ | ConfigUpgrade
396+ | ConfigVerify
397+ | ConfigWhich
398+
399+// mode_flags reads a mode's flags into its struct, then lays the config's
400+// options under them: a flag the config turns on (options :noconfirm true)
401+// is on for every mode that has it, as if it stood on the command line.
402+// the command line can only add to that; --eval turns one off for a run.
403+// an option the mode's struct has no field for is an error
404+fn mode_flags[T](args []string) !T {
405+ mut c, unknown := flag.to_struct[T](args, skip: 2)!
406+ // what the parser could not place is an option the mode does not have:
407+ // said, as pacman says it, instead of a run that quietly leaves a
408+ // mistyped flag out of a transaction
409+ bad := unknown.filter(it.len > 1 && it.starts_with('-'))
410+ if bad.len > 0 {
411+ return error('unknown option: ${bad.map('"${it}"').join(', ')}')
412+ }
413+ // the rest of it are targets that stand before a flag: the parser's
414+ // tail takes only the ones after the last flag, and these lead them
415+ early := unknown.filter(!(it.len > 1 && it.starts_with('-')))
416+ if early.len > 0 {
417+ mut placed := false
418+ $for field in T.fields {
419+ $if field.name == 'query' {
420+ mut query := early.clone()
421+ query << c.query
422+ c.query = query
423+ placed = true
424+ }
425+ }
426+ if !placed {
427+ return error('this mode takes no targets: ${early.map('"${it}"').join(', ')}')
428+ }
429+ }
430+ $for field in T.fields {
431+ $if field.typ is bool {
432+ if opt_flags[field.name] {
433+ c.$(field.name) = true
434+ }
435+ }
436+ }
437+ return c
438+}
439+
440+// flag_given is whether the command line spells a flag, by its long name or
441+// its short letter: what settles that a config default steps back. a letter
442+// is looked for in any bundle of short flags, so a doubt reads as given and
443+// leaves the mode's own default
444+fn flag_given(args []string, long string, short string) bool {
445+ for a in args#[2..] {
446+ if a == '--${long}' || a.starts_with('--${long}=') {
447+ return true
448+ }
449+ if a.len > 1 && a[0] == `-` && a[1] != `-` && a.contains(short) {
450+ return true
451+ }
452+ }
453+ return false
454+}
455+
456+// parse_mode reads the mode and its flags. it runs before any escalation, so
457+// a flag that does not parse is an error the user sees before a root prompt
458+fn parse_mode(args []string) !ModeConfig {
459+ return match args[1] {
460+ 's', 'S', 'search' {
461+ // a long flag given twice is the flag parser's error, so the
462+ // repeats of --unrequired are counted and folded into one here
463+ level := args.count(it == '--unrequired')
464+ mut once := []string{cap: args.len}
465+ for i, arg in args {
466+ if arg == '--unrequired' && args[..i].contains(arg) {
467+ continue
468+ }
469+ once << arg
470+ }
471+ mut c := mode_flags[ConfigSearch](once)!
472+ if !flag_given(once, 'thold', 't') {
473+ c.thold = cfg_search_thold
474+ } else if c.thold < 0.0 || c.thold > 1.0 {
475+ // the config's (search :thold) is held to the same range
476+ return error('--thold must be between 0 and 1, not ${c.thold}')
477+ }
478+ c.unrequired_level = level
479+ c.groups = c.groups || c.groups_level > 0
480+ if !c.local && !c.remote && !c.pkgbuild {
481+ // the filters only work on the installed packages; the
482+ // groups are the sync dbs' unless -l asks for the local ones
483+ c.local = c.filtered() && !c.groups
484+ c.remote = !c.filtered() || c.groups
485+ }
486+ ModeConfig(c)
487+ }
488+ 'q', 'Q', 'info' {
489+ c := mode_flags[ConfigInfo](args)!
490+ ModeConfig(c)
491+ }
492+ 'w', 'W', 'which' {
493+ c := mode_flags[ConfigWhich](args)!
494+ ModeConfig(c)
495+ }
496+ 'n', 'N', 'deptest' {
497+ c := mode_flags[ConfigDeptest](args)!
498+ ModeConfig(c)
499+ }
500+ 'm', 'M', 'mark' {
501+ c := mode_flags[ConfigMark](args)!
502+ ModeConfig(c)
503+ }
504+ 'b', 'B', 'build' {
505+ c := mode_flags[ConfigBuild](args)!
506+ ModeConfig(c)
507+ }
508+ 'i', 'I', 'install' {
509+ c := mode_flags[ConfigInstall](args)!
510+ ModeConfig(c)
511+ }
512+ 'r', 'R', 'remove' {
513+ c := mode_flags[ConfigRemove](args)!
514+ ModeConfig(c)
515+ }
516+ 'u', 'U', 'upgrade' {
517+ c := mode_flags[ConfigUpgrade](args)!
518+ ModeConfig(c)
519+ }
520+ 'l', 'L', 'files' {
521+ c := mode_flags[ConfigFiles](args)!
522+ ModeConfig(c)
523+ }
524+ 'o', 'O', 'owner' {
525+ c := mode_flags[ConfigOwner](args)!
526+ ModeConfig(c)
527+ }
528+ 'd', 'D', 'orphans' {
529+ c := mode_flags[ConfigOrphans](args)!
530+ ModeConfig(c)
531+ }
532+ 'c', 'C', 'clean' {
533+ mut c := mode_flags[ConfigClean](args)!
534+ if !flag_given(args, 'keep', 'k') {
535+ c.keep = cfg_clean_keep
536+ }
537+ ModeConfig(c)
538+ }
539+ 't', 'T', 'tree' {
540+ mut c := mode_flags[ConfigTree](args)!
541+ if !flag_given(args, 'depth', 'd') {
542+ c.depth = cfg_tree_depth
543+ }
544+ ModeConfig(c)
545+ }
546+ 'a', 'A', 'autoremove' {
547+ c := mode_flags[ConfigAutoRemove](args)!
548+ ModeConfig(c)
549+ }
550+ 'k', 'K', 'rank' {
551+ mut c := mode_flags[ConfigRank](args)!
552+ if !flag_given(args, 'top', 'n') {
553+ c.top = rank_top
554+ } else if c.top < 1 {
555+ // the config's (rank :top) is held to the same floor
556+ return error('--top must be at least 1, not ${c.top}')
557+ }
558+ ModeConfig(c)
559+ }
560+ 'v', 'V', 'verify' {
561+ c := mode_flags[ConfigVerify](args)!
562+ ModeConfig(c)
563+ }
564+ 'f', 'F', 'find' {
565+ c := mode_flags[ConfigFind](args)!
566+ ModeConfig(c)
567+ }
568+ else {
569+ error('unknown subcommand: "${args[1]}"')
570+ }
571+ }
572+}
573+
574+// needs_root is whether a mode runs as root: the ones that change the
575+// system, except a --print preview, which changes nothing and stays the
576+// user's as pacman's --print does; find -y, which writes the file dbs; and
577+// rank when the file it writes is not the user's to write. rank -w writes
578+// the config's mirror file under /etc, so that is known before any ranking
579+fn needs_root(c ModeConfig) !bool {
580+ return match c {
581+ ConfigInstall { !c.print_only }
582+ ConfigRemove { !c.print_only }
583+ ConfigUpgrade { !c.print_only }
584+ ConfigClean { !c.print_only }
585+ ConfigBuild, ConfigMark, ConfigAutoRemove { true }
586+ ConfigFind { c.refresh }
587+ ConfigRank {
588+ mut target := c.output
589+ if target == '' && c.write {
590+ target = rank_write_target(rank_os_name(c.query)!)
591+ }
592+ target != '' && !can_write(target)
593+ }
594+ else { false }
595+ }
596+}
597+
598+// run_mode runs a parsed mode and returns its exit status: 0, or what the
599+// mode's outcome asks for
600+fn run_mode(c ModeConfig) !int {
601+ match c {
602+ ConfigSearch {
603+ search(c)!
604+ }
605+ ConfigInfo {
606+ info(c)!
607+ }
608+ ConfigWhich {
609+ which(c)!
610+ }
611+ ConfigDeptest {
612+ // pacman's -T: 127 tells makepkg a dependency is missing
613+ if deptest(c)!.len > 0 {
614+ return 127
615+ }
616+ }
617+ ConfigMark {
618+ mark(c)!
619+ }
620+ ConfigBuild {
621+ build_repo(c)!
622+ }
623+ ConfigInstall {
624+ install(c)!
625+ }
626+ ConfigRemove {
627+ remove(c)!
628+ }
629+ ConfigUpgrade {
630+ upgrade(c)!
631+ }
632+ ConfigFiles {
633+ files(c)!
634+ }
635+ ConfigOwner {
636+ owner(c)!
637+ }
638+ ConfigOrphans {
639+ orphans(c)!
640+ }
641+ ConfigClean {
642+ clean(c)!
643+ }
644+ ConfigTree {
645+ tree(c)!
646+ }
647+ ConfigAutoRemove {
648+ autoremove(c)!
649+ }
650+ ConfigRank {
651+ rank(c)!
652+ }
653+ ConfigVerify {
654+ if verify(c)! > 0 {
655+ return 1
656+ }
657+ }
658+ ConfigFind {
659+ find(c)!
660+ }
661+ }
662+ return 0
663+}
664+
665+fn main() {
666+ // --lip-run <lip> <phase> [args...] is what a PKGBUILD generated from a
667+ // PKGBUILD.lip calls back (vpac b): it runs one phase of the lip. it is no
668+ // mode, reads no config and never needs root
669+ if os.args.len > 3 && os.args[1] == '--lip-run' {
670+ vmakepkg.lip_run_phase(os.args[2], os.args[3], os.args[4..]) or {
671+ eprintln(error_text('lip: ${err.msg()}'))
672+ exit(1)
673+ }
674+ exit(0)
675+ }
676+ chosen, evals, args := scan_globals(os.args) or { print_err(err.msg()) }
677+ // the config comes first: it is required, and everything downstream reads
678+ // it, including the escalation to root
679+ load_config(chosen, evals) or { print_err(err.msg()) }
680+ // the config's color is the default a --color on the command line beats
681+ if !color_given && opt_color != '' {
682+ color_flag = opt_color
683+ }
684+ // a killed run lets go of the db lock it holds (on_interrupt)
685+ install_interrupt_handlers()
686+ // no mode, or help: the overview. an option where the mode belongs is
687+ // one no global scan took, and an error as pacman's unknown options are
688+ if args.len < 2 || args[1] in ['h', 'help', '-h', '--help'] {
689+ if ipc_on() {
690+ ipc_start()
691+ }
692+ show_help(help_text())
693+ end_run(0)
694+ }
695+ if args[1].starts_with('-') {
696+ print_err('unknown option "${args[1]}" before the mode (vpac --help lists the modes)')
697+ }
698+ // the mode is parsed before anything else happens: a bad flag is an error
699+ // here, not a panic in a root process. 'vpac <mode> -h' prints that
700+ // mode's options and never runs the command; the flag parser reads the
701+ // -h, so one bundled with others (-lh) counts and one that is another
702+ // flag's value does not. a help request beside flags that do not parse
703+ // is still answered with the help
704+ config := parse_mode(args) or {
705+ if args[2..].any(it == '-h' || it == '--help') {
706+ mode_help(args[1])
707+ }
708+ print_err(err.msg())
709+ }
710+ if config.show_help {
711+ mode_help(args[1])
712+ }
713+ // a mode that changes the system runs as root, through the root
714+ // provider; the original command line is passed, globals included, so
715+ // the root process reads the same config and evals
716+ root := needs_root(config) or { print_err(err.msg()) }
717+ if root {
718+ reexec_as_root(os.args[1..]) or { print_err(err.msg()) }
719+ }
720+ // this is the process that does the work: a frontend's channel opens here
721+ if ipc_on() {
722+ ipc_start()
723+ }
724+ mut status := run_mode(config) or { print_err(err.msg()) }
725+ // a query that skipped bad targets still fails, after showing the rest
726+ if failed_targets > 0 && status == 0 {
727+ status = 1
728+ }
729+ end_run(status)
730+}
731+
732+// mode_help prints one mode's options and ends the run
733+@[noreturn]
734+fn mode_help(name string) {
735+ if ipc_on() {
736+ ipc_start()
737+ }
738+ mode := find_mode(name) or { print_err('unknown subcommand: "${name}"') }
739+ show_help(mode_help_text(mode))
740+ end_run(0)
741+}
742+
743+// end_run is the one exit of a run, an error's included: the status, told
744+// to a frontend first as the exit event that closes every stream
745+@[noreturn]
746+fn end_run(status int) {
747+ if ipc_on() {
748+ emit(ExitEvent{
749+ status: status
750+ })
751+ }
752+ exit(status)
753+}
@@ -0,0 +1,324 @@
1+module main
2+
3+import alpm
4+import os
5+
6+// --eval takes its blip from the next argument or from =; an empty one is
7+// refused like an empty --config or --color value is
8+fn test_scan_globals_eval() ! {
9+ mut chosen := ''
10+ mut evals := []string{}
11+ mut rest := []string{}
12+ chosen, evals, rest = scan_globals(['vpac', '--eval', '(define x 1)', 's', 'zsh'])!
13+ assert chosen == ''
14+ assert evals == ['(define x 1)']
15+ assert rest == ['vpac', 's', 'zsh']
16+
17+ chosen, evals, rest = scan_globals(['vpac', '--eval=(define x 2)', '--config=other.lip', 's'])!
18+ assert chosen == 'other.lip'
19+ assert evals == ['(define x 2)']
20+ assert rest == ['vpac', 's']
21+
22+ for arg in ['--eval=', '--eval', '--config=', '--config'] {
23+ if _, _, _ := scan_globals(['vpac', arg]) {
24+ assert false, '"${arg}" was taken without its value'
25+ } else {
26+ assert err.msg().contains('needs'), '"${arg}": ${err.msg()}'
27+ }
28+ }
29+}
30+
31+// the global flags parse wherever they stand, and none of them bleeds into
32+// the rest the mode sees
33+fn test_scan_globals_mixed() ! {
34+ saved_kind, saved_color := ui_kind, color_flag
35+ defer {
36+ ui_kind, color_flag = saved_kind, saved_color
37+ }
38+ _, _, rest := scan_globals(['vpac', 'i', '--color=never', 'zsh', '--ui', 'ipc'])!
39+ assert rest == ['vpac', 'i', 'zsh']
40+}
41+
42+fn test_scan_ui() {
43+ for args, want in {
44+ 'vpac s --ui ipc': 'ipc'
45+ 'vpac --ui=ipc s': 'ipc'
46+ 'vpac --ui tty s': 'tty'
47+ // the last valid one wins, as in scan_globals
48+ 'vpac --ui tty s --ui ipc': 'ipc'
49+ 'vpac --ui=ipc --ui=tty': 'tty'
50+ // another global's value is stepped over, not read as a flag
51+ 'vpac --eval --ui ipc': ''
52+ 'vpac --config --ui --ui ipc': 'ipc'
53+ // no valid one: none, and scan_globals says why on the terminal
54+ 'vpac s zsh': ''
55+ 'vpac --ui bogus s': ''
56+ 'vpac --ui': ''
57+ 'vpac --ui=': ''
58+ } {
59+ got := scan_ui(args.split(' ')) or { '' }
60+ assert got == want, args
61+ }
62+}
63+
64+// an error in any global is told the frontend's way when --ui ipc is on the
65+// command line, wherever it stands: the ui is settled before the error
66+fn test_scan_globals_settles_the_ui_before_failing() {
67+ saved_kind := ui_kind
68+ defer { ui_kind = saved_kind }
69+ for args in ['vpac --color sometimes --ui ipc s', 'vpac --color sometimes s --ui=ipc',
70+ 'vpac --ui ipc --color sometimes s'] {
71+ ui_kind = 'tty'
72+ if _, _, _ := scan_globals(args.split(' ')) {
73+ assert false, '${args} was accepted'
74+ }
75+ assert ui_kind == 'ipc', args
76+ }
77+ // a bad --ui itself names no frontend: the terminal tells it
78+ ui_kind = 'tty'
79+ if _, _, _ := scan_globals('vpac --color sometimes --ui bogus s'.split(' ')) {
80+ assert false
81+ }
82+ assert ui_kind == 'tty'
83+}
84+
85+// the doubled flags are counts, as pacman reads -ss, -cc, -gg, -tt and -uu
86+fn test_doubled_flags_count() ! {
87+ r := parse_mode(['vpac', 'r', '-ss', '-u', 'foo'])! as ConfigRemove
88+ assert r.recursive_level == 2 && r.unneeded && r.query == ['foo']
89+ assert recurse_flags(r.recursive, r.recursive_level) == alpm.TransFlag.recurse | .recurse_all
90+ one := parse_mode(['vpac', 'r', '--recursive', 'foo'])! as ConfigRemove
91+ assert recurse_flags(one.recursive, one.recursive_level) == alpm.TransFlag.recurse
92+
93+ c := parse_mode(['vpac', 'c', '-cc'])! as ConfigClean
94+ assert c.level == 2 && !c.keep_current
95+ kc := parse_mode(['vpac', 'c', '--keep-current'])! as ConfigClean
96+ assert kc.keep_current && kc.level == 0
97+
98+ u := parse_mode(['vpac', 'u', '-uu'])! as ConfigUpgrade
99+ assert u.sysupgrade_level == 2
100+ d := parse_mode(['vpac', 'd', '-tt'])! as ConfigOrphans
101+ assert d.level == 2
102+}
103+
104+fn test_search_group_and_unrequired_counts() ! {
105+ g := parse_mode(['vpac', 's', '-gg'])! as ConfigSearch
106+ assert g.groups && g.groups_level == 2
107+ // groups are the sync dbs' unless -l asks for the installed ones
108+ assert g.remote && !g.local
109+ lg := parse_mode(['vpac', 's', '-l', '-g', 'base'])! as ConfigSearch
110+ assert lg.groups && lg.local && !lg.remote && lg.query == ['base']
111+ long := parse_mode(['vpac', 's', '--groups'])! as ConfigSearch
112+ assert long.groups
113+
114+ t := parse_mode(['vpac', 's', '--unrequired'])! as ConfigSearch
115+ assert t.unrequired && t.unrequired_level == 1 && t.local
116+ tt := parse_mode(['vpac', 's', '--unrequired', '-d', '--unrequired'])! as ConfigSearch
117+ assert tt.unrequired && tt.unrequired_level == 2 && tt.deps
118+}
119+
120+fn test_new_query_flags_parse() ! {
121+ q := parse_mode(['vpac', 'q', '-c', '-p', 'a.pkg.tar', 'b.pkg.tar'])! as ConfigInfo
122+ assert q.changelog && q.file && q.query == ['a.pkg.tar', 'b.pkg.tar']
123+ o := parse_mode(['vpac', 'o', '-q', '/usr/bin/ls'])! as ConfigOwner
124+ assert o.quiet
125+ f := parse_mode(['vpac', 'f', '-x', '--machinereadable', 'ls$'])! as ConfigFind
126+ assert f.regex && f.machinereadable && f.query == ['ls$']
127+}
128+
129+fn test_ranged_flags_are_checked() ! {
130+ // the flags are held to the ranges the config's forms are
131+ for bad in [['vpac', 's', '--thold', '2', 'x'], ['vpac', 's', '-t', '1.5', 'x'],
132+ ['vpac', 's', '--thold', '-1', 'x'], ['vpac', 'k', '--top', '0'], ['vpac', 'k', '--top',
133+ '-2']] {
134+ if _ := parse_mode(bad) {
135+ assert false, 'parsed ${bad}'
136+ }
137+ }
138+ s := parse_mode(['vpac', 's', '--thold', '0.5', 'x'])! as ConfigSearch
139+ assert s.thold == 0.5
140+ k := parse_mode(['vpac', 'k', '--top', '3'])! as ConfigRank
141+ assert k.top == 3
142+}
143+
144+fn test_help_flag_is_the_parsers() ! {
145+ // bundled with other flags it still asks for help; as another flag's
146+ // value it does not
147+ s := parse_mode(['vpac', 's', '-lh'])! as ConfigSearch
148+ assert s.show_help && s.local
149+ q := parse_mode(['vpac', 'q', '--fields', '-h', 'x'])! as ConfigInfo
150+ assert !q.show_help && q.fields == '-h'
151+}
152+
153+fn test_parse_target() {
154+ assert parse_target('bash') == Target{
155+ name: 'bash'
156+ }
157+ assert parse_target('core/bash') == Target{'core', 'bash'}
158+ assert parse_target('local/bash>=5') == Target{'local', 'bash>=5'}
159+ // a leading slash is no db prefix
160+ assert parse_target('/bash').repo == ''
161+ assert local_target_name('local/bash') == 'bash'
162+ assert local_target_name('core/bash') == 'core/bash'
163+ assert has_constraint('bash>=5') && has_constraint('sh=1') && !has_constraint('bash')
164+}
165+
166+fn test_flags_nothing_read_are_gone() ! {
167+ // install's -u, -s and -v and search's -v parsed into fields no code
168+ // read: a flag that does nothing is refused instead of taken
169+ for dead in [['vpac', 'i', '-u', 'x'], ['vpac', 'i', '--upgrade-deps', 'x'],
170+ ['vpac', 'i', '-s', 'x'], ['vpac', 'i', '--sync', 'x'], ['vpac', 'i', '-v', 'x'],
171+ ['vpac', 's', '-v', 'x']] {
172+ if _ := parse_mode(dead) {
173+ assert false, 'parsed ${dead}'
174+ }
175+ }
176+ // the ones that do something still parse, bundled too
177+ w := parse_mode(['vpac', 'i', '-w', 'x'])! as ConfigInstall
178+ assert w.download_only && w.query == ['x']
179+ wp := parse_mode(['vpac', 'i', '-wp', '--no-upgrade-deps', 'x'])! as ConfigInstall
180+ assert wp.download_only && wp.print_only && wp.no_upgrade_deps
181+ s := parse_mode(['vpac', 's', '-s', 'x'])! as ConfigSearch
182+ assert s.sync_dbs
183+}
184+
185+fn test_unknown_mode_flags_are_errors() ! {
186+ // a flag the mode has no field for is named, not dropped: long, short,
187+ // bundled with known ones, before or after the targets, and a mistyped
188+ // spelling of a real one
189+ for bad in [['vpac', 'q', '--bogus', 'bash'], ['vpac', 'q', '-Z', 'bash'],
190+ ['vpac', 'q', 'bash', '--bogus'], ['vpac', 'i', '--noconfrim', 'x'],
191+ ['vpac', 'i', '--asdep', 'x'], ['vpac', 'r', '--print', '--bogus', 'x'],
192+ ['vpac', 's', '-t', '-1', 'x']] {
193+ if c := parse_mode(bad) {
194+ assert false, 'parsed ${bad} as ${c}'
195+ } else {
196+ assert err.msg().contains('unknown option') || err.msg().contains('--thold'), err.msg()
197+ }
198+ }
199+ named := parse_mode(['vpac', 'q', '--bogus', '-Z', 'bash']) or {
200+ assert err.msg() == 'unknown option: "--bogus", "-Z"', err.msg()
201+ ModeConfig(ConfigInfo{})
202+ }
203+ assert (named as ConfigInfo).query.len == 0
204+ // what is known still parses in every position, and a mode with no
205+ // flags given at all is not an error
206+ q := parse_mode(['vpac', 'q', 'bash', '-c', 'zsh'])! as ConfigInfo
207+ assert q.changelog && q.query == ['bash', 'zsh']
208+ bare := parse_mode(['vpac', 'd'])! as ConfigOrphans
209+ assert bare.level == 0
210+ // targets that stand before a flag are targets all the same, in the
211+ // order given, with the ones after it
212+ mixed := parse_mode(['vpac', 'i', 'a', '--needed', 'b', '-w', 'c', 'd'])! as ConfigInstall
213+ assert mixed.query == ['a', 'b', 'c', 'd'] && mixed.needed && mixed.download_only
214+ lead := parse_mode(['vpac', 'r', 'a', 'b', '--print'])! as ConfigRemove
215+ assert lead.query == ['a', 'b'] && lead.print_only
216+ // a lone dash names neither a flag nor a target: the parser's error
217+ if d := parse_mode(['vpac', 'q', '-', '-c']) {
218+ assert false, 'a lone dash parsed: ${d}'
219+ }
220+ // a mode with no targets says so of one given before a flag
221+ if o := parse_mode(['vpac', 'd', 'stray', '-t']) {
222+ assert false, 'orphans took a target: ${o}'
223+ } else {
224+ assert err.msg().contains('takes no targets'), err.msg()
225+ }
226+}
227+
228+fn test_needs_root_by_mode() ! {
229+ root := fn (args []string) !bool {
230+ return needs_root(parse_mode(args)!)!
231+ }
232+ // what changes the system runs as root
233+ for args in [['vpac', 'i', 'x'], ['vpac', 'r', 'x'], ['vpac', 'u'], ['vpac', 'c'],
234+ ['vpac', 'm', '-r', 'd', 'x'], ['vpac', 'a'], ['vpac', 'b', '/x'], ['vpac', 'f', '-y',
235+ '/x'], ['vpac', 'i', '-w', 'x'], ['vpac', 'u', '-w'], ['vpac', 'i', '--dbonly', 'x']] {
236+ assert root(args)!, '${args} runs as the user'
237+ }
238+ // a --print preview changes nothing and stays the user's, whatever
239+ // else is asked beside it
240+ for args in [['vpac', 'i', '-p', 'x'], ['vpac', 'r', '--print', 'x'], ['vpac', 'u', '-p'],
241+ ['vpac', 'c', '-p'], ['vpac', 'i', '-p', '--dbonly', '--noconfirm', 'x'],
242+ ['vpac', 'c', '-p', '-a']] {
243+ assert !root(args)!, '${args} asks for root'
244+ }
245+ // what only reads never asks for root
246+ for args in [['vpac', 's', 'x'], ['vpac', 'q', 'x'], ['vpac', 'w', 'x'], ['vpac', 'n', 'x'],
247+ ['vpac', 'l', 'x'], ['vpac', 'o', '/x'], ['vpac', 'd'], ['vpac', 't', 'x'], ['vpac', 'v'],
248+ ['vpac', 'f', '/x'], ['vpac', 'f', '-l', 'x'], ['vpac', 'k', 'arch']] {
249+ assert !root(args)!, '${args} asks for root'
250+ }
251+}
252+
253+fn test_needs_root_for_rank_follows_the_file() ! {
254+ if os.geteuid() == 0 {
255+ // root may write anywhere: there is no 'not the user's' to tell
256+ return
257+ }
258+ tmp := os.join_path(os.vtmp_dir(), 'vpac_test_needs_root_${os.getpid()}')
259+ os.mkdir_all(os.join_path(tmp, 'ro'))!
260+ saved_dir := rank_dir
261+ defer {
262+ rank_dir = saved_dir
263+ os.chmod(os.join_path(tmp, 'ro'), 0o755) or {}
264+ os.rmdir_all(tmp) or {}
265+ }
266+ os.chmod(os.join_path(tmp, 'ro'), 0o555)!
267+ os_name := rank_oses.keys()[0]
268+ // printing a ranking writes nothing
269+ assert !needs_root(ConfigRank{ query: [os_name] })!
270+ // -o: a file the user may write, or may create, is the user's
271+ assert !needs_root(ConfigRank{ output: os.join_path(tmp, 'new.lip'), query: [os_name] })!
272+ os.write_file(os.join_path(tmp, 'there.lip'), '')!
273+ assert !needs_root(ConfigRank{ output: os.join_path(tmp, 'there.lip'), query: [os_name] })!
274+ // one it may not is root's: an existing read-only file, a new file in
275+ // a read-only dir, and a path under a dir that is not there
276+ os.chmod(os.join_path(tmp, 'there.lip'), 0o444)!
277+ assert needs_root(ConfigRank{ output: os.join_path(tmp, 'there.lip'), query: [os_name] })!
278+ assert needs_root(ConfigRank{ output: os.join_path(tmp, 'ro', 'new.lip'), query: [os_name] })!
279+ assert needs_root(ConfigRank{ output: os.join_path(tmp, 'gone', 'new.lip'), query: [os_name] })!
280+ // -w writes the config's mirror file: the rank dir decides, and -o,
281+ // when both are given, is the file that is written
282+ rank_dir = tmp
283+ assert !needs_root(ConfigRank{ write: true, query: [os_name] })!
284+ rank_dir = os.join_path(tmp, 'ro')
285+ assert needs_root(ConfigRank{ write: true, query: [os_name] })!
286+ assert !needs_root(ConfigRank{
287+ write: true
288+ output: os.join_path(tmp, 'new.lip')
289+ query: [os_name]
290+ })!
291+ // an os the ranker does not know is an error before any escalation
292+ if _ := needs_root(ConfigRank{ write: true, query: ['no-such-os'] }) {
293+ assert false, 'an unknown os was ranked'
294+ }
295+}
296+
297+fn test_verbose_is_a_global_flag() ! {
298+ saved := verbose_flag
299+ defer { verbose_flag = saved }
300+ // wherever it stands, it is taken off the mode's arguments and turns
301+ // the verbose log on; without it the log stays off
302+ for args in [['vpac', '--verbose', 'i', 'x'], ['vpac', 'i', '--verbose', 'x'],
303+ ['vpac', 'i', 'x', '--verbose'], ['vpac', '--verbose', '--verbose', 'i', 'x']] {
304+ verbose_flag = false
305+ _, _, rest := scan_globals(args)!
306+ assert rest == ['vpac', 'i', 'x'], '${args}'
307+ assert verbose_flag, '${args}'
308+ }
309+ verbose_flag = false
310+ _, _, plain := scan_globals(['vpac', 'i', 'x'])!
311+ assert plain == ['vpac', 'i', 'x'] && !verbose_flag
312+ // as the value of another global it is that flag's value, not the flag
313+ _, evals, rest := scan_globals(['vpac', '--eval', '--verbose', 's'])!
314+ assert evals == ['--verbose'] && rest == ['vpac', 's'] && !verbose_flag
315+ // the short letter is not it: -v stays the mode's to refuse or to take
316+ _, _, short := scan_globals(['vpac', 'i', '-v', 'x'])!
317+ assert short == ['vpac', 'i', '-v', 'x'] && !verbose_flag
318+ // and it takes no value
319+ _, _, eq := scan_globals(['vpac', 'i', '--verbose=yes', 'x'])!
320+ assert eq == ['vpac', 'i', '--verbose=yes', 'x'] && !verbose_flag
321+ if _ := parse_mode(eq) {
322+ assert false, '--verbose=yes parsed as a mode flag'
323+ }
324+}
@@ -0,0 +1,1027 @@
1+@[has_globals]
2+module main
3+
4+import os
5+import blip.vlib.blip
6+import blip.vlib.blip.machine
7+import alpm
8+
9+// config_path is the file read at startup, written in blip: a lisp dialect
10+// embedded from V. the file is required, since the config carries parts of
11+// vpac (the repos, for one); a setting no form of it names keeps the
12+// default its __global is declared with below, which reset_config puts
13+// back before every load
14+pub const config_path = '/etc/vpac.d/config.lip'
15+
16+// the settings below were consts until the config existed. root_path and
17+// db_path are joined onto file names directly, so they keep a trailing slash
18+__global root_path = '/'
19+__global db_path = '/var/lib/pacman/'
20+__global arch = 'x86_64'
21+__global parallel_downloads = 3
22+// the rank form: how many mirrors to probe at once (0 = unset, so the rank
23+// parallelism falls back to the network's parallel) and how long one probe
24+// may take
25+__global rank_parallel = 0
26+__global rank_timeout = 10
27+// the pkgbuild form: the command that builds and how deep the clone is.
28+// where it builds is path :dir. the build command is the system's makepkg,
29+// which ships in the pacman package with the libalpm vpac runs on; :makepkg
30+// names another
31+// the build command is trusted text: it is spelled whole into a shell that
32+// runs it in the cloned dir, first as the building user and through the
33+// reviews of the pkgbuild for its content. vpac does not vet it — the config
34+// is code the machine's user writes (like pacman.conf no more and no less),
35+// and whoever controls a user's config already controls their shell
36+__global pkgbuild_makepkg = 'makepkg -f'
37+__global pkgbuild_depth = 1
38+// the unprivileged user libalpm downloads as, like DownloadUser in pacman.conf
39+__global download_user = 'alpm'
40+// the configured directories and lists. the defaults are the values the
41+// hardcoded vpac used
42+__global cfg_cachedirs = ['/var/cache/pacman/pkg/']
43+// pacman's default HookDir, beside the system one libalpm adds by itself
44+__global cfg_hookdirs = ['/etc/pacman.d/hooks/']
45+// where pkgbuild packages are cloned and built (path :build): a relative
46+// dir is taken under the invoking user's home, because makepkg runs as that user
47+__global pkgbuild_dir = '.cache/vpac/pkgbuild'
48+__global cfg_logfile = ''
49+// the keyring signatures are checked against: pacman's GPGDir default, not
50+// moved under a fake root (pacman keeps it as configuration). libalpm has
51+// no default of its own, and without one gpgme falls back on root's own
52+// ~/.gnupg, where no packager's key is
53+__global cfg_gpgdir = '/etc/pacman.d/gnupg/'
54+__global cfg_protocols = ['https']
55+// the signature level every sync db is registered with and packages are
56+// checked against. libalpm's freshly calloc'd handle verifies nothing, so
57+// vpac defaults to pacman's shipped SigLevel: a package and a database
58+// signature are both verified when they are present, and a mismatching one
59+// fails. override with (network :siglevel [...])
60+__global cfg_siglevel = alpm.SigLevel.package | .package_optional | .database | .database_optional
61+__global cfg_hold = []string{}
62+__global cfg_ignore = []string{}
63+// the rest of pacman.conf's [options]: groups ignored as cfg_ignore's packages
64+// are, files an upgrade or an install leaves alone, and the download timeout
65+__global cfg_ignore_groups = []string{}
66+__global cfg_noupgrade = []string{}
67+__global cfg_noextract = []string{}
68+__global cfg_disable_timeout = false
69+// pacman.conf's DisableSandboxFilesystem and DisableSandboxSyscalls: libalpm
70+// sandboxes its downloads and extracts, and this turns both parts off
71+__global cfg_disable_sandbox = false
72+// pacman.conf's UseSyslog: libalpm logs to syslog too, (path :syslog true)
73+__global cfg_syslog = false
74+// cfg_repos holds the repos the config defines
75+__global cfg_repos = []CfgRepo{}
76+
77+// CfgRepo is one registered repo: a name, a kind ('sync', or 'pkgbuild' for
78+// a site to build from), and the urls to fetch it from, where a url keeps
79+// the $repo and $arch placeholders
80+struct CfgRepo {
81+ name string
82+ kind string
83+ servers []string
84+ // what the db is used for, as pacman.conf's Usage; every use by default
85+ usage alpm.DBUsage = alpm.db_usage_all
86+}
87+
88+// QuietConfigHost reads the config file from the real filesystem and throws
89+// away anything it prints: a config is read for its definitions, and its
90+// output has no place in vpac's own. it never reads stdin
91+struct QuietConfigHost {}
92+
93+fn (h &QuietConfigHost) host_print(_ string) {}
94+
95+fn (h &QuietConfigHost) host_write(_ string) {}
96+
97+fn (h &QuietConfigHost) host_read_line() ?string {
98+ return none
99+}
100+
101+fn (h &QuietConfigHost) host_load(path string) !string {
102+ return os.read_file(path)
103+}
104+
105+// str_of reads one quoted string out of a config value
106+// usage_of reads a repo's :usage, pacman.conf's Usage: one or more of sync,
107+// search, install, upgrade and all
108+fn usage_of(v blip.Value, what string) !alpm.DBUsage {
109+ names := match v.tag {
110+ .string { [v.as_string()] }
111+ else { strs_of(v, what)! }
112+ }
113+ if names.len == 0 {
114+ return error('config: ${what} needs at least one of sync, search, install, upgrade, all')
115+ }
116+ mut usage := unsafe { alpm.DBUsage(0) }
117+ for name in names {
118+ usage |= match name.to_lower() {
119+ 'sync' { alpm.DBUsage.sync }
120+ 'search' { alpm.DBUsage.search }
121+ 'install' { alpm.DBUsage.install }
122+ 'upgrade' { alpm.DBUsage.upgrade }
123+ 'all' { alpm.db_usage_all }
124+ else {
125+ return error('config: ${what} takes sync, search, install, upgrade and all, not "${name}"')
126+ }
127+ }
128+ }
129+ return usage
130+}
131+
132+fn bool_of(v blip.Value, what string) !bool {
133+ if v.tag != .boolean {
134+ return error('config: ${what} must be true or false')
135+ }
136+ return v.as_bool()
137+}
138+
139+fn str_of(v blip.Value, what string) !string {
140+ if v.tag != .string {
141+ return error('config: ${what} must be a quoted string')
142+ }
143+ return v.as_string()
144+}
145+
146+// strs_of reads a string or an array of strings out of a config value
147+fn strs_of(v blip.Value, what string) ![]string {
148+ mut out := []string{}
149+ match v.tag {
150+ .emptylist {}
151+ .string {
152+ out << v.as_string()
153+ }
154+ .vector, .array {
155+ for item in v.as_vector().data {
156+ out << str_of(item, what)!
157+ }
158+ }
159+ else {
160+ return error('config: ${what} must be a string or an array of strings')
161+ }
162+ }
163+ return out
164+}
165+
166+// int_of reads one integer out of a config value
167+fn int_of(v blip.Value, what string) !int {
168+ if v.tag != .integer {
169+ return error('config: ${what} must be an integer')
170+ }
171+ return int(v.as_int())
172+}
173+
174+// float_of reads a number out of a config value, an integer taken as one
175+fn float_of(v blip.Value, what string) !f64 {
176+ return match v.tag {
177+ .float { v.as_float() }
178+ .integer { f64(v.as_int()) }
179+ else { error('config: ${what} must be a number') }
180+ }
181+}
182+
183+// ratio_of reads a number between 0 and 1: a threshold, a completion
184+fn ratio_of(v blip.Value, what string) !f64 {
185+ f := float_of(v, what)!
186+ if f < 0.0 || f > 1.0 {
187+ return error('config: ${what} must be between 0 and 1')
188+ }
189+ return f
190+}
191+
192+// count_of reads an integer no smaller than min
193+fn count_of(v blip.Value, what string, min int) !int {
194+ n := int_of(v, what)!
195+ if n < min {
196+ return error('config: ${what} must be at least ${min}')
197+ }
198+ return n
199+}
200+
201+// siglevel_names are the names (network :siglevel) accepts, mapped onto
202+// libalpm's SigLevel bits, plus what each one means
203+const siglevel_names = {
204+ 'package': alpm.SigLevel.package
205+ 'package_optional': alpm.SigLevel.package_optional
206+ 'package_marginal_ok': alpm.SigLevel.package_marginal_ok
207+ 'package_unknown_ok': alpm.SigLevel.package_unknown_ok
208+ 'database': alpm.SigLevel.database
209+ 'database_optional': alpm.SigLevel.database_optional
210+ 'database_marginal_ok': alpm.SigLevel.database_marginal_ok
211+ 'database_unknown_ok': alpm.SigLevel.database_unknown_ok
212+}
213+
214+// siglevel_of reads a SigLevel out of a config value: one name or an array
215+// of names, e.g. (network :siglevel ['package' 'database_optional'])
216+fn siglevel_of(v blip.Value, what string) !alpm.SigLevel {
217+ names := match v.tag {
218+ .string { [v.as_string()] }
219+ else { strs_of(v, what)! }
220+ }
221+ // an empty one verifies nothing: libalpm would take the silent answer
222+ // as handing everything over unsigned, which nobody ever means
223+ if names.len == 0 {
224+ return error('config: ${what} needs at least one of: ${siglevel_names.keys().join(', ')}')
225+ }
226+ mut level := unsafe { alpm.SigLevel(0) }
227+ for name in names {
228+ key := name.to_lower()
229+ bit := siglevel_names[key] or {
230+ return error('config: ${what} must be one or more of: ${siglevel_names.keys().join(', ')}')
231+ }
232+ level |= bit
233+ }
234+ return level
235+}
236+
237+// dir_path checks a configured directory: names are joined onto it directly,
238+// so it must not be empty and it has to end with a slash
239+fn dir_path(what string, value string) !string {
240+ if value == '' {
241+ return error('config: ${what} must not be empty')
242+ }
243+ return if value.ends_with('/') { value } else { value + '/' }
244+}
245+
246+// keyword_of reads the :key a config form applies to
247+fn keyword_of(v blip.Value, form string) !string {
248+ if v.tag != .keyword {
249+ return error('config: ${form} expected a :key')
250+ }
251+ return v.as_string()
252+}
253+
254+// keyword_args walks a config form's arguments as keyword, value pairs
255+fn keyword_args(form string, args []blip.Value) !([]string, []blip.Value) {
256+ if args.len % 2 != 0 {
257+ return error('config: ${form} keys and values come in pairs')
258+ }
259+ mut keys := []string{}
260+ mut values := []blip.Value{}
261+ mut i := 0
262+ for i < args.len {
263+ keys << keyword_of(args[i], form)!
264+ values << args[i + 1]
265+ i += 2
266+ }
267+ return keys, values
268+}
269+
270+// prim_path is the config's (path ...) form: root, db, log, gpg, cache, hook,
271+// and :syslog true for pacman.conf's UseSyslog
272+fn prim_path(args []blip.Value) !blip.Value {
273+ keys, values := keyword_args('path', args)!
274+ mut i := 0
275+ for i < keys.len {
276+ match keys[i] {
277+ 'root' {
278+ root_path = dir_path('path :root', str_of(values[i], 'path :root')!)!
279+ }
280+ 'db' {
281+ db_path = dir_path('path :db', str_of(values[i], 'path :db')!)!
282+ }
283+ 'log' {
284+ cfg_logfile = str_of(values[i], 'path :log')!
285+ }
286+ 'syslog' {
287+ cfg_syslog = bool_of(values[i], 'path :syslog')!
288+ }
289+ 'gpg' {
290+ cfg_gpgdir = dir_path('path :gpg', str_of(values[i], 'path :gpg')!)!
291+ }
292+ 'cache' {
293+ dirs := strs_of(values[i], 'path :cache')!
294+ cfg_cachedirs = []string{}
295+ for dir in dirs {
296+ cfg_cachedirs << dir_path('path :cache', dir)!
297+ }
298+ }
299+ 'hook' {
300+ dirs := strs_of(values[i], 'path :hook')!
301+ cfg_hookdirs = []string{}
302+ for dir in dirs {
303+ cfg_hookdirs << dir_path('path :hook', dir)!
304+ }
305+ }
306+ 'build' {
307+ d := str_of(values[i], 'path :build')!
308+ if d == '' {
309+ return error('config: path :build must not be empty')
310+ }
311+ pkgbuild_dir = d
312+ }
313+ else {
314+ return error('config: path has no key :${keys[i]}')
315+ }
316+ }
317+ i++
318+ }
319+ return blip.nil_value()
320+}
321+
322+// prim_pkg is the config's (pkg ...) form: arch, hold, ignore, and pacman.conf's
323+// IgnoreGroup, NoUpgrade and NoExtract as :ignoregroup, :noupgrade and
324+// :noextract, each a list, e.g. (pkg :noextract ["usr/share/doc/*"])
325+fn prim_pkg(args []blip.Value) !blip.Value {
326+ keys, values := keyword_args('pkg', args)!
327+ mut i := 0
328+ for i < keys.len {
329+ match keys[i] {
330+ 'arch' {
331+ a := str_of(values[i], 'pkg :arch')!
332+ // it fills the $arch of every server url and is the one
333+ // architecture libalpm installs for: one plain word
334+ if a == '' || a.contains('/') || a.fields().len != 1 || a.fields()[0] != a {
335+ return error('config: pkg :arch must be one plain word, such as x86_64')
336+ }
337+ arch = a
338+ }
339+ 'hold' {
340+ cfg_hold = strs_of(values[i], 'pkg :hold')!
341+ }
342+ 'ignore' {
343+ cfg_ignore = strs_of(values[i], 'pkg :ignore')!
344+ }
345+ 'ignoregroup' {
346+ cfg_ignore_groups = strs_of(values[i], 'pkg :ignoregroup')!
347+ }
348+ 'noupgrade' {
349+ cfg_noupgrade = strs_of(values[i], 'pkg :noupgrade')!
350+ }
351+ 'noextract' {
352+ cfg_noextract = strs_of(values[i], 'pkg :noextract')!
353+ }
354+ else {
355+ return error('config: pkg has no key :${keys[i]}')
356+ }
357+ }
358+ i++
359+ }
360+ return blip.nil_value()
361+}
362+
363+// prim_network is the config's (network ...) form: parallel, protocols, user,
364+// siglevel, :disable-timeout true for pacman.conf's DisableDownloadTimeout, and
365+// :disable-sandbox true for its DisableSandbox
366+fn prim_network(args []blip.Value) !blip.Value {
367+ keys, values := keyword_args('network', args)!
368+ mut i := 0
369+ for i < keys.len {
370+ match keys[i] {
371+ 'parallel' {
372+ n := int_of(values[i], 'network :parallel')!
373+ if n < 1 {
374+ return error('config: network :parallel must be at least 1')
375+ }
376+ parallel_downloads = n
377+ }
378+ 'protocols' {
379+ protos := strs_of(values[i], 'network :protocols')!
380+ if protos.len == 0 {
381+ return error('config: network :protocols needs at least one, https or http')
382+ }
383+ // a scheme no mirror is listed under would filter every
384+ // mirror out without a word
385+ for proto in protos {
386+ if proto !in ['https', 'http'] {
387+ return error('config: network :protocols takes https and http, not "${proto}"')
388+ }
389+ }
390+ cfg_protocols = protos.clone()
391+ }
392+ 'user' {
393+ download_user = str_of(values[i], 'network :user')!
394+ }
395+ 'siglevel' {
396+ cfg_siglevel = siglevel_of(values[i], 'network :siglevel')!
397+ }
398+ 'disable-timeout' {
399+ cfg_disable_timeout = bool_of(values[i], 'network :disable-timeout')!
400+ }
401+ 'disable-sandbox' {
402+ cfg_disable_sandbox = bool_of(values[i], 'network :disable-sandbox')!
403+ }
404+ else {
405+ return error('config: network has no key :${keys[i]}')
406+ }
407+ }
408+ i++
409+ }
410+ return blip.nil_value()
411+}
412+
413+// prim_rank is the config's (rank ...) form: parallel and timeout for the
414+// mirror ranking. the parallelism falls back to the network's parallel when
415+// the rank form does not set its own. :top is how many mirrors are answered,
416+// :completion (0 to 1) and :max-delay (seconds) what a mirror must report to
417+// be probed, :candidates how many get the speed test, :retest how many of
418+// the fastest are timed twice, :dir where rank -w writes
419+fn prim_rank(args []blip.Value) !blip.Value {
420+ keys, values := keyword_args('rank', args)!
421+ mut i := 0
422+ for i < keys.len {
423+ match keys[i] {
424+ 'parallel' {
425+ n := int_of(values[i], 'rank :parallel')!
426+ if n < 1 {
427+ return error('config: rank :parallel must be at least 1')
428+ }
429+ rank_parallel = n
430+ }
431+ 'timeout' {
432+ n := int_of(values[i], 'rank :timeout')!
433+ if n < 1 {
434+ return error('config: rank :timeout must be at least 1')
435+ }
436+ rank_timeout = n
437+ }
438+ 'top' {
439+ rank_top = count_of(values[i], 'rank :top', 1)!
440+ }
441+ 'dir' {
442+ d := str_of(values[i], 'rank :dir')!
443+ if !d.starts_with('/') {
444+ return error('config: rank :dir must be an absolute path')
445+ }
446+ rank_dir = d.trim_right('/')
447+ }
448+ 'candidates' {
449+ rank_speed_candidates = count_of(values[i], 'rank :candidates', 1)!
450+ }
451+ 'retest' {
452+ rank_retest = count_of(values[i], 'rank :retest', 0)!
453+ }
454+ 'completion' {
455+ rank_min_completion = ratio_of(values[i], 'rank :completion')!
456+ }
457+ 'max-delay' {
458+ rank_max_delay = i64(count_of(values[i], 'rank :max-delay', 0)!)
459+ }
460+ else {
461+ return error('config: rank has no key :${keys[i]}')
462+ }
463+ }
464+ i++
465+ }
466+ return blip.nil_value()
467+}
468+
469+// prim_repo is the config's (repo ...) form: a repo's name, its type ('sync',
470+// or 'pkgbuild', a site to build from) and the mirrors it is fetched
471+// from, with $repo and $arch left as placeholders
472+// :usage is pacman.conf's Usage: a list of sync, search, install, upgrade
473+// and all; every use when it is left out
474+fn prim_repo(args []blip.Value) !blip.Value {
475+ keys, values := keyword_args('repo', args)!
476+ mut repo := CfgRepo{
477+ kind: 'sync'
478+ }
479+ mut i := 0
480+ for i < keys.len {
481+ match keys[i] {
482+ 'name' {
483+ rname := str_of(values[i], 'repo :name')!
484+ repo = CfgRepo{
485+ ...repo
486+ name: rname
487+ }
488+ }
489+ 'type' {
490+ rkind := str_of(values[i], 'repo :type')!
491+ if rkind !in ['sync', 'pkgbuild'] {
492+ return error("config: repo :type is 'sync' or 'pkgbuild', not '${rkind}'")
493+ }
494+ repo = CfgRepo{
495+ ...repo
496+ kind: rkind
497+ }
498+ }
499+ 'src' {
500+ rservers := strs_of(values[i], 'repo :src')!
501+ if rservers.len == 0 {
502+ return error('config: repo :src needs at least one url')
503+ }
504+ for server in rservers {
505+ if server == '' {
506+ return error('config: repo :src has an empty url in it')
507+ }
508+ }
509+ repo = CfgRepo{
510+ ...repo
511+ servers: rservers
512+ }
513+ }
514+ 'usage' {
515+ rusage := usage_of(values[i], 'repo :usage')!
516+ repo = CfgRepo{
517+ ...repo
518+ usage: rusage
519+ }
520+ }
521+ else {
522+ return error('config: repo has no key :${keys[i]}')
523+ }
524+ }
525+ i++
526+ }
527+ if repo.name == '' {
528+ return error('config: repo needs a :name')
529+ }
530+ // libalpm refuses a second db of a name, and 'local' is its own db's:
531+ // said here, by name, instead of late and from inside a mode
532+ if repo.name == 'local' {
533+ return error('config: a repo cannot be named local, the installed packages are')
534+ }
535+ if cfg_repos.any(it.name == repo.name) {
536+ return error('config: repo ${repo.name} is defined twice')
537+ }
538+ if repo.kind == 'sync' && repo.servers.len == 0 {
539+ return error('config: a sync repo takes at least one :src')
540+ }
541+ if repo.kind == 'pkgbuild' && repo.servers.len != 1 {
542+ return error('config: a pkgbuild repo takes one :src, the site to build from')
543+ }
544+ cfg_repos << repo
545+ return blip.nil_value()
546+}
547+
548+// pkgbuild_repos are the configured pkgbuild repos, in config order. the
549+// --pkgbuild flags search and build from all of them, each under its own name
550+fn pkgbuild_repos() []CfgRepo {
551+ return cfg_repos.filter(it.kind == 'pkgbuild')
552+}
553+
554+// prim_pkgbuild is the config's (pkgbuild ...) form: makepkg, depth, and
555+// timeout, the seconds one lookup of a pkgbuild repo may take. where the
556+// build happens is path :build
557+fn prim_pkgbuild(args []blip.Value) !blip.Value {
558+ keys, values := keyword_args('pkgbuild', args)!
559+ mut i := 0
560+ for i < keys.len {
561+ match keys[i] {
562+ 'makepkg' {
563+ m := str_of(values[i], 'pkgbuild :makepkg')!
564+ if m == '' {
565+ return error('config: pkgbuild :makepkg must not be empty')
566+ }
567+ pkgbuild_makepkg = m
568+ }
569+ 'depth' {
570+ n := int_of(values[i], 'pkgbuild :depth')!
571+ if n < 1 {
572+ return error('config: pkgbuild :depth must be at least 1')
573+ }
574+ pkgbuild_depth = n
575+ }
576+ 'timeout' {
577+ pkgbuild_rpc_timeout = count_of(values[i], 'pkgbuild :timeout', 1)!
578+ }
579+ else {
580+ return error('config: pkgbuild has no key :${keys[i]}')
581+ }
582+ }
583+ i++
584+ }
585+ return blip.nil_value()
586+}
587+
588+// option_flags are the mode flags (options ...) can turn on for every run,
589+// by the config's key: each names the field the modes' flag structs keep it
590+// in, so a mode that has no such flag is simply not touched
591+const option_flags = {
592+ 'noconfirm': 'noconfirm'
593+ 'nopkgbuildconfirm': 'no_pkgbuild_confirm'
594+ 'needed': 'needed'
595+ 'no-upgrade-deps': 'no_upgrade_deps'
596+ 'quiet': 'quiet'
597+ 'keep-current': 'keep_current'
598+ 'fuzzy': 'fuzzy'
599+ 'disable-timeout': 'disable_timeout'
600+}
601+
602+// opt_flags holds the fields of option_flags the config turned on;
603+// opt_color is options :color, empty when the config names none
604+__global opt_flags = map[string]bool{}
605+__global opt_color = ''
606+
607+// prim_options is the config's (options ...) form: root, the command vpac
608+// gets root with (privilege.v); color, the --color a run starts from;
609+// verbose, the verbose log of a run's housekeeping failures (--verbose);
610+// sync-age, the hours after which the sync dbs are called stale (0: never);
611+// suggest, how close (0 to 1) a name must be to be offered for a typo; and
612+// the mode flags of option_flags, true or false
613+fn prim_options(args []blip.Value) !blip.Value {
614+ keys, values := keyword_args('options', args)!
615+ mut i := 0
616+ for i < keys.len {
617+ match keys[i] {
618+ 'root' {
619+ r := str_of(values[i], 'options :root')!
620+ if r.trim_space() == '' {
621+ return error('config: options :root must not be empty')
622+ }
623+ root_provider = r
624+ }
625+ 'color' {
626+ c := str_of(values[i], 'options :color')!
627+ if c !in ['auto', 'always', 'never'] {
628+ return error('config: options :color takes auto, always or never, not "${c}"')
629+ }
630+ opt_color = c
631+ }
632+ 'sync-age' {
633+ // hours; 0 never warns
634+ sync_max_age = i64(count_of(values[i], 'options :sync-age', 0)!) * 3600
635+ }
636+ 'suggest' {
637+ suggest_thold = ratio_of(values[i], 'options :suggest')!
638+ }
639+ 'verbose' {
640+ // the verbose log for every run, as --verbose for one
641+ cfg_verbose = bool_of(values[i], 'options :verbose')!
642+ }
643+ else {
644+ field := option_flags[keys[i]] or {
645+ return error('config: options has no key :${keys[i]}')
646+ }
647+ // only what is on is held: a false takes back an earlier
648+ // true (an --eval over the file) and leaves no entry behind
649+ if bool_of(values[i], 'options :${keys[i]}')! {
650+ opt_flags[field] = true
651+ } else {
652+ opt_flags.delete(field)
653+ }
654+ }
655+ }
656+ i++
657+ }
658+ return blip.nil_value()
659+}
660+
661+// prim_search is the config's (search ...) form: fields, the columns of a
662+// listing when --fields names none, and thold, the fuzzy threshold
663+fn prim_search(args []blip.Value) !blip.Value {
664+ keys, values := keyword_args('search', args)!
665+ mut i := 0
666+ for i < keys.len {
667+ match keys[i] {
668+ 'fields' {
669+ names := strs_of(values[i], 'search :fields')!
670+ if names.len == 0 {
671+ return error('config: search :fields needs at least one field')
672+ }
673+ cfg_search_fields = parse_fields(names.join(','), []string{}) or {
674+ return error('config: search :fields: ${err.msg()}')
675+ }
676+ }
677+ 'thold' {
678+ cfg_search_thold = ratio_of(values[i], 'search :thold')!
679+ }
680+ else {
681+ return error('config: search has no key :${keys[i]}')
682+ }
683+ }
684+ i++
685+ }
686+ return blip.nil_value()
687+}
688+
689+// prim_clean is the config's (clean ...) form: keep, the versions of every
690+// package the cache keeps when -k names none
691+fn prim_clean(args []blip.Value) !blip.Value {
692+ keys, values := keyword_args('clean', args)!
693+ mut i := 0
694+ for i < keys.len {
695+ match keys[i] {
696+ 'keep' {
697+ cfg_clean_keep = count_of(values[i], 'clean :keep', 0)!
698+ }
699+ else {
700+ return error('config: clean has no key :${keys[i]}')
701+ }
702+ }
703+ i++
704+ }
705+ return blip.nil_value()
706+}
707+
708+// prim_tree is the config's (tree ...) form: depth, how deep a tree is
709+// drawn when -d names none
710+fn prim_tree(args []blip.Value) !blip.Value {
711+ keys, values := keyword_args('tree', args)!
712+ mut i := 0
713+ for i < keys.len {
714+ match keys[i] {
715+ 'depth' {
716+ cfg_tree_depth = count_of(values[i], 'tree :depth', 0)!
717+ }
718+ else {
719+ return error('config: tree has no key :${keys[i]}')
720+ }
721+ }
722+ i++
723+ }
724+ return blip.nil_value()
725+}
726+
727+// prim_color is the config's (color ...) form, the theme: each key is a role
728+// of default_theme, each value one style or a list of them out of
729+// style_names, e.g. (color :version "cyan" :warning ["bold" "magenta"])
730+fn prim_color(args []blip.Value) !blip.Value {
731+ keys, values := keyword_args('color', args)!
732+ mut i := 0
733+ for i < keys.len {
734+ if keys[i] !in theme {
735+ return error('config: color has no role :${keys[i]}, the roles are: ${default_theme().keys().join(', ')}')
736+ }
737+ styles := strs_of(values[i], 'color :${keys[i]}')!
738+ for style in styles {
739+ if style !in style_names {
740+ return error('config: color :${keys[i]} takes ${style_names.join(', ')}, not "${style}"')
741+ }
742+ }
743+ theme[keys[i]] = styles.clone()
744+ i++
745+ }
746+ return blip.nil_value()
747+}
748+
749+// prim_mirrorlist is the config's (mirrorlist ...) form: an os for the
750+// ranker, new or one of its own redefined. :name is what rank is asked for
751+// (and what /etc/os-release is matched against), :repo the repo whose db the
752+// speed test pulls, and the mirrors come from one of :status, a mirror
753+// status json api as arch publishes, or :list, a Server = mirrorlist at a
754+// url or an absolute path
755+fn prim_mirrorlist(args []blip.Value) !blip.Value {
756+ keys, values := keyword_args('mirrorlist', args)!
757+ mut name := ''
758+ mut status := ''
759+ mut list := ''
760+ mut repo := ''
761+ mut i := 0
762+ for i < keys.len {
763+ match keys[i] {
764+ 'name' { name = str_of(values[i], 'mirrorlist :name')! }
765+ 'status' { status = str_of(values[i], 'mirrorlist :status')! }
766+ 'list' { list = str_of(values[i], 'mirrorlist :list')! }
767+ 'repo' { repo = str_of(values[i], 'mirrorlist :repo')! }
768+ else { return error('config: mirrorlist has no key :${keys[i]}') }
769+ }
770+ i++
771+ }
772+ if name == '' || name.contains('/') || name.starts_with('.') || name.starts_with('-')
773+ || name.fields().len != 1 || name.fields()[0] != name {
774+ return error('config: mirrorlist needs a :name, one plain word')
775+ }
776+ if repo == '' {
777+ return error('config: mirrorlist ${name} needs a :repo, the repo whose db is timed')
778+ }
779+ if (status == '') == (list == '') {
780+ return error('config: mirrorlist ${name} takes one of :status and :list')
781+ }
782+ if status != '' && !status.starts_with('https://') && !status.starts_with('http://') {
783+ return error('config: mirrorlist ${name} :status must be an http or https url')
784+ }
785+ if list != '' && !list.starts_with('https://') && !list.starts_with('http://')
786+ && !list.starts_with('/') {
787+ return error('config: mirrorlist ${name} :list must be a url or an absolute path')
788+ }
789+ rank_oses[name] = RankOs{
790+ status_json: status
791+ mirrorlist: list
792+ repo: repo
793+ }
794+ return blip.nil_value()
795+}
796+
797+// cell_of reads one piece of a bar graphic: text of exactly one rune, or of
798+// at most one when it may be left out
799+fn cell_of(v blip.Value, what string, may_be_empty bool) !string {
800+ text := str_of(v, what)!
801+ n := text.runes().len
802+ if n > 1 || (n == 0 && !may_be_empty) {
803+ return error('config: ${what} must be one character')
804+ }
805+ return text
806+}
807+
808+// prim_progress is the config's (progress ...) form, the bars: style
809+// ('classic' or 'block'); the graphic's pieces start, end, fill, head and
810+// empty; length in cells (0 fills the terminal); percent, eta, elapsed and
811+// rate, true or false; delay, the milliseconds between redraws
812+fn prim_progress(args []blip.Value) !blip.Value {
813+ keys, values := keyword_args('progress', args)!
814+ mut i := 0
815+ for i < keys.len {
816+ what := 'progress :${keys[i]}'
817+ match keys[i] {
818+ 'style' {
819+ s := str_of(values[i], what)!
820+ if s !in ['classic', 'block'] {
821+ return error('config: ${what} is classic or block, not "${s}"')
822+ }
823+ cfg_progress.style = s
824+ }
825+ 'start', 'end' {
826+ cfg_progress.parts[keys[i]] = str_of(values[i], what)!
827+ }
828+ 'fill', 'empty' {
829+ cfg_progress.parts[keys[i]] = cell_of(values[i], what, false)!
830+ }
831+ 'head' {
832+ cfg_progress.parts[keys[i]] = cell_of(values[i], what, true)!
833+ }
834+ 'length' {
835+ cfg_progress.length = count_of(values[i], what, 0)!
836+ }
837+ 'percent' {
838+ cfg_progress.percent = bool_of(values[i], what)!
839+ }
840+ 'eta' {
841+ cfg_progress.eta = bool_of(values[i], what)!
842+ }
843+ 'elapsed' {
844+ cfg_progress.elapsed = bool_of(values[i], what)!
845+ }
846+ 'rate' {
847+ cfg_progress.rate = bool_of(values[i], what)!
848+ }
849+ 'delay' {
850+ cfg_progress.delay = count_of(values[i], what, 1)!
851+ }
852+ else {
853+ return error('config: progress has no key :${keys[i]}')
854+ }
855+ }
856+ i++
857+ }
858+ return blip.nil_value()
859+}
860+
861+// prim_spinner is the config's (spinner ...) form: frames, a set by name
862+// (spinner_sets) or a list of frames of one's own; interval, the
863+// milliseconds a frame stays; done, what a finished step shows in place of
864+// the animation; elapsed, whether the time taken is shown
865+fn prim_spinner(args []blip.Value) !blip.Value {
866+ keys, values := keyword_args('spinner', args)!
867+ mut i := 0
868+ for i < keys.len {
869+ what := 'spinner :${keys[i]}'
870+ match keys[i] {
871+ 'frames' {
872+ if values[i].tag == .string {
873+ name := values[i].as_string()
874+ cfg_progress.frames = spinner_frames_named(name) or {
875+ return error('config: ${what} knows ${spinner_sets.join(', ')}, not "${name}"; a list gives frames of your own')
876+ }
877+ } else {
878+ frames := strs_of(values[i], what)!
879+ if frames.len == 0 {
880+ return error('config: ${what} needs at least one frame')
881+ }
882+ cfg_progress.frames = frames.clone()
883+ }
884+ }
885+ 'interval' {
886+ cfg_progress.interval = count_of(values[i], what, 1)!
887+ }
888+ 'done' {
889+ cfg_progress.done = str_of(values[i], what)!
890+ }
891+ 'elapsed' {
892+ cfg_progress.timed = bool_of(values[i], what)!
893+ }
894+ else {
895+ return error('config: spinner has no key :${keys[i]}')
896+ }
897+ }
898+ i++
899+ }
900+ return blip.nil_value()
901+}
902+
903+// prim_array_append is (array-append! dst src): every element of src pushed
904+// onto dst. it is std.lip's, provided by the host so the config's mirror lists
905+// are fillable without vpac loading std.lip
906+fn prim_array_append(args []blip.Value) !blip.Value {
907+ if args.len != 2 {
908+ return error('config: array-append! needs an array and an array of values')
909+ }
910+ if args[0].tag !in [.vector, .array] {
911+ return error('config: array-append! the first argument must be an array')
912+ }
913+ match args[1].tag {
914+ .vector, .array {
915+ for item in args[1].as_vector().data {
916+ args[0].as_vector().push(item)
917+ }
918+ }
919+ .emptylist {}
920+ else {
921+ return error('config: array-append! the second argument must be an array')
922+ }
923+ }
924+ return args[0]
925+}
926+
927+// reset_config puts every config global back at its declared default, the
928+// values the hardcoded vpac used. load_config runs it first, so a second
929+// load in one process neither duplicates the repos nor keeps settings the
930+// new file does not name; a failed load can leave values behind, and the
931+// next load starts clean again
932+fn reset_config() {
933+ root_path = '/'
934+ root_provider = 'sudo'
935+ opt_flags = map[string]bool{}
936+ opt_color = ''
937+ cfg_verbose = false
938+ sync_max_age = i64(24 * 60 * 60)
939+ suggest_thold = 0.85
940+ pkgbuild_rpc_timeout = 10
941+ rank_min_completion = 1.0
942+ rank_max_delay = i64(86400)
943+ rank_speed_candidates = 40
944+ rank_retest = 5
945+ rank_top = 10
946+ cfg_search_fields = search_default_fields.clone()
947+ cfg_search_thold = 0.9
948+ cfg_clean_keep = 0
949+ cfg_tree_depth = 0
950+ theme = default_theme()
951+ rank_oses = default_rank_oses()
952+ rank_dir = '/etc/vpac.d/mirrors'
953+ cfg_progress = ProgressCfg{}
954+ db_path = '/var/lib/pacman/'
955+ arch = 'x86_64'
956+ parallel_downloads = 3
957+ rank_parallel = 0
958+ rank_timeout = 10
959+ pkgbuild_makepkg = 'makepkg -f'
960+ pkgbuild_depth = 1
961+ download_user = 'alpm'
962+ pkgbuild_dir = '.cache/vpac/pkgbuild'
963+ cfg_cachedirs = ['/var/cache/pacman/pkg/']
964+ cfg_hookdirs = ['/etc/pacman.d/hooks/']
965+ cfg_logfile = ''
966+ cfg_gpgdir = '/etc/pacman.d/gnupg/'
967+ cfg_protocols = ['https']
968+ cfg_siglevel = alpm.SigLevel.package | .package_optional | .database | .database_optional
969+ cfg_hold = []string{}
970+ cfg_ignore = []string{}
971+ cfg_ignore_groups = []string{}
972+ cfg_noupgrade = []string{}
973+ cfg_noextract = []string{}
974+ cfg_disable_timeout = false
975+ cfg_disable_sandbox = false
976+ cfg_syslog = false
977+ cfg_repos = []CfgRepo{}
978+}
979+
980+// load_config reads the config file -- the one --config names, else
981+// config_path -- and evaluates it in a machine that provides the config
982+// forms. the file is required: vpac has no defaults to fall back to once its
983+// repos, paths and mirror lists live in the config. the --eval snippets run
984+// after it, in the same machine, so they can extend or override the file for
985+// this run. a file that does not parse, or a form with the wrong keys, stops
986+// vpac, because running on silently could act on the wrong database
987+fn load_config(chosen string, evals []string) ! {
988+ reset_config()
989+ path := if chosen != '' { chosen } else { config_path }
990+ if !os.exists(path) {
991+ return error('${path} is required: write it, starting with (require ...) for each part')
992+ }
993+ mut m := machine.new_standalone(&QuietConfigHost{})
994+ m.prims['path'] = prim_path
995+ m.prims['pkg'] = prim_pkg
996+ m.prims['network'] = prim_network
997+ m.prims['rank'] = prim_rank
998+ m.prims['pkgbuild'] = prim_pkgbuild
999+ m.prims['options'] = prim_options
1000+ m.prims['search'] = prim_search
1001+ m.prims['clean'] = prim_clean
1002+ m.prims['tree'] = prim_tree
1003+ m.prims['color'] = prim_color
1004+ m.prims['mirrorlist'] = prim_mirrorlist
1005+ m.prims['progress'] = prim_progress
1006+ m.prims['spinner'] = prim_spinner
1007+ m.prims['repo'] = prim_repo
1008+ m.prims['array-append!'] = prim_array_append
1009+ m.load(path) or {
1010+ return error('config: ${err.msg()}')
1011+ }
1012+ for code in evals {
1013+ m.run_str(code) or {
1014+ return error('config --eval: ${err.msg()}')
1015+ }
1016+ }
1017+}
1018+
1019+// check_hold refuses to remove a package the config holds, as pacman does for
1020+// HoldPkg. libalpm has no option for it, so it is a frontend check
1021+fn check_hold(names []string) ! {
1022+ for name in names {
1023+ if name in cfg_hold {
1024+ return error('${name} is held by the config: remove it from pkg :hold first')
1025+ }
1026+ }
1027+}
@@ -0,0 +1,445 @@
1+module main
2+
3+import os
4+import time
5+import x.progress
6+
7+fn config_tmp(name string) !string {
8+ tmp := os.join_path(os.vtmp_dir(), 'vpac_test_config_${name}_${os.getpid()}')
9+ os.mkdir_all(os.join_path(tmp, 'db', 'local'))!
10+ os.write_file(os.join_path(tmp, 'db', 'local', 'ALPM_DB_VERSION'), '9\n')!
11+ return tmp
12+}
13+
14+fn test_config_options() ! {
15+ tmp := config_tmp('options')!
16+ defer { os.rmdir_all(tmp) or {} }
17+ cfg := os.join_path(tmp, 'config.lip')
18+ os.write_file(cfg, '(path :db "${tmp}/db/")\n' +
19+ '(pkg :ignoregroup ["kde-applications"] :noupgrade ["etc/foo.conf"] :noextract ["usr/share/doc/*" "usr/share/man/*"])\n' +
20+ '(path :syslog true)\n' + '(network :disable-timeout true :disable-sandbox true)\n' + r'(repo :name "core" :src ["https://example.org/$repo"] :usage ["sync" "Search"])' +
21+ '\n' + r'(repo :name "extra" :src ["https://example.org/$repo"])' + '\n')!
22+ load_config(cfg, [])!
23+
24+ assert cfg_ignore_groups == ['kde-applications']
25+ assert cfg_noupgrade == ['etc/foo.conf']
26+ assert cfg_noextract == ['usr/share/doc/*', 'usr/share/man/*']
27+ assert cfg_disable_timeout
28+ assert cfg_disable_sandbox
29+ assert cfg_syslog
30+ core := cfg_repos.filter(it.name == 'core')[0]
31+ extra := cfg_repos.filter(it.name == 'extra')[0]
32+ // pacman's Usage bits: Sync 1, Search 2; every use when none is given
33+ assert int(core.usage) == 1 | 2
34+ assert int(extra.usage) == 15
35+
36+ // and libalpm gets them from init_handle
37+ ui := new_trans_ui()
38+ mut handle := init_handle(ui)!
39+ defer { handle.release() or {} }
40+ mut groups := handle.option_get_ignore_groups()
41+ assert groups.strs() == ['kde-applications']
42+ mut noupgrade := handle.option_get_noupgrades()
43+ assert noupgrade.strs() == ['etc/foo.conf']
44+ mut noextract := handle.option_get_no_extracts()
45+ assert noextract.strs() == ['usr/share/doc/*', 'usr/share/man/*']
46+ assert handle.option_match_no_extract('usr/share/doc/zsh/README')
47+ assert !handle.option_match_no_extract('usr/bin/zsh')
48+ assert handle.option_get_disable_sandbox_filesystem()
49+ assert handle.option_get_disable_sandbox_syscalls()
50+}
51+
52+// the sandbox stays on unless the config turns it off: a config that does not
53+// name it, or names it false, leaves libalpm's sandbox on for the handle
54+fn test_config_disable_sandbox_defaults_on() ! {
55+ tmp := config_tmp('sandbox')!
56+ defer {
57+ os.rmdir_all(tmp) or {}
58+ reset_config()
59+ }
60+ cfg := os.join_path(tmp, 'config.lip')
61+ os.write_file(cfg, '(network :parallel 2)\n')!
62+ load_config(cfg, [])!
63+ assert !cfg_disable_sandbox
64+ ui := new_trans_ui()
65+ mut handle := init_handle(ui)!
66+ defer { handle.release() or {} }
67+ assert !handle.option_get_disable_sandbox_filesystem()
68+ assert !handle.option_get_disable_sandbox_syscalls()
69+ // a false written out is the same as leaving it out
70+ os.write_file(cfg, '(network :disable-sandbox false)\n')!
71+ load_config(cfg, [])!
72+ assert !cfg_disable_sandbox
73+}
74+
75+fn test_config_rejects_bad_values() ! {
76+ tmp := config_tmp('bad')!
77+ defer { os.rmdir_all(tmp) or {} }
78+ cfg := os.join_path(tmp, 'config.lip')
79+ for form, says in {
80+ '(repo :name "x" :usage ["sometimes"])': 'takes sync, search, install, upgrade and all'
81+ '(repo :name "x" :usage [])': 'needs at least one'
82+ '(network :disable-timeout "yes")': 'must be true or false'
83+ '(network :disable-sandbox "yes")': 'must be true or false'
84+ // an empty one verifies nothing, and a list of no protocols accepts
85+ // no transfers; a repo that names no servers has nothing to fetch
86+ '(network :siglevel [])': 'needs at least one of'
87+ '(network :protocols [])': 'needs at least one'
88+ '(network :protocols ["ftp"])': 'takes https and http'
89+ '(network :protocols ["https" "HTTPS"])': 'takes https and http'
90+ '(pkg :arch "")': 'must be one plain word'
91+ '(pkg :arch "x86 64")': 'must be one plain word'
92+ '(pkg :arch " x86_64")': 'must be one plain word'
93+ '(pkg :arch "a/b")': 'must be one plain word'
94+ '(repo :name "local" :src ["http://x"])': 'cannot be named local'
95+ '(repo :name "x" :src ["http://x"]) (repo :name "x" :src ["http://y"])': 'is defined twice'
96+ '(repo :name "x" :src ["http://x"]) (repo :name "x" :type "pkgbuild" :src ["http://y"])': 'is defined twice'
97+ '(mirrorlist :name "my os" :repo "core" :status "https://x")': 'one plain word'
98+ '(mirrorlist :name "os\t" :repo "core" :status "https://x")': 'one plain word'
99+ '(repo :name "x" :src [])': 'needs at least one url'
100+ '(repo :name "x" :src "")': 'has an empty url in it'
101+ '(repo :name "x" :type "sync")': 'takes at least one :src'
102+ '(options :root " ")': 'must not be empty'
103+ '(options :colour "always")': 'has no key :colour'
104+ '(options :color "sometimes")': 'takes auto, always or never'
105+ '(options :noconfirm "yes")': 'must be true or false'
106+ '(options :suggest 2)': 'between 0 and 1'
107+ '(options :sync-age -1)': 'at least 0'
108+ '(search :fields ["nope"])': 'unknown field'
109+ '(search :thold "high")': 'must be a number'
110+ '(rank :top 0)': 'at least 1'
111+ '(pkgbuild :timeout 0)': 'at least 1'
112+ '(color :nope "red")': 'has no role :nope'
113+ '(progress :style "round")': 'classic or block'
114+ '(progress :fill "==")': 'must be one character'
115+ '(progress :empty "")': 'must be one character'
116+ '(spinner :frames "nope")': 'not "nope"'
117+ '(spinner :frames [])': 'at least one frame'
118+ '(mirrorlist :name "x" :repo "core")': 'one of :status and :list'
119+ '(mirrorlist :name "x" :list "/m")': 'needs a :repo'
120+ '(mirrorlist :name "a/b" :list "/m" :repo "c")': 'one plain word'
121+ '(mirrorlist :name "x" :status "/m" :repo "c")': 'http or https url'
122+ '(rank :dir "mirrors")': 'absolute path'
123+ '(color :name "pink")': 'not "pink"'
124+ } {
125+ os.write_file(cfg, form + '\n')!
126+ if _ := load_config(cfg, []) {
127+ assert false, '${form} was accepted'
128+ } else {
129+ assert err.msg().contains(says), '${form}: ${err.msg()}'
130+ }
131+ }
132+ // a list may be a single string, as everywhere in the config
133+ os.write_file(cfg, '(pkg :noupgrade "etc/foo.conf")\n')!
134+ load_config(cfg, [])!
135+ assert cfg_noupgrade == ['etc/foo.conf']
136+}
137+
138+// a second load answers nothing of the first's: every global is back at its
139+// default before the file is read, so nothing is kept that the new file does
140+// not name, and no repo of the old load survives
141+fn test_config_resets_between_loads() ! {
142+ tmp := config_tmp('reset')!
143+ defer { os.rmdir_all(tmp) or {} }
144+ cfg := os.join_path(tmp, 'config.lip')
145+ os.write_file(cfg, '(repo :name "one" :src ["https://one.example/$repo"])\n
146+(network :parallel 5 :siglevel ["package" "database"])\n(pkg :hold ["glibc"] :ignore ["flatpak"])\n(options :root "doas -n")\n')!
147+ load_config(cfg, [])!
148+ assert root_provider == 'doas -n'
149+ assert cfg_repos.map(it.name) == ['one']
150+ assert cfg_repos.len == 1
151+ assert parallel_downloads == 5
152+ assert cfg_hold == ['glibc']
153+ assert cfg_ignore == ['flatpak']
154+ assert cfg_disable_timeout == false
155+
156+ os.write_file(cfg, '(repo :name "two" :src "https://two.example/$repo")\n')!
157+ load_config(cfg, [])!
158+ assert cfg_repos.map(it.name) == ['two']
159+ assert cfg_repos.len == 1
160+ assert parallel_downloads == 3
161+ assert root_provider == 'sudo'
162+ assert opt_color == ''
163+ assert opt_flags.len == 0
164+ assert cfg_hold == []string{}
165+ assert cfg_ignore == []string{}
166+}
167+
168+// check_hold refuses a name on the hold list, the targets of a removal as
169+// well as whatever a transaction pulls in beyond them
170+fn test_check_hold() {
171+ mut old := cfg_hold.clone()
172+ defer { cfg_hold = old.clone() }
173+ cfg_hold = ['held', 'base']
174+ check_hold(['other', 'more']) or {
175+ assert false, 'a name off the hold list was refused'
176+ }
177+ if _ := check_hold(['fine', 'held']) {
178+ assert false, 'a held package was let through'
179+ } else {
180+ assert err.msg().contains('held'), err.msg()
181+ }
182+}
183+
184+// the keyring dir defaults to pacman's GPGDir, so a config that names no
185+// :gpg checks signatures against the system keyring, not root's ~/.gnupg;
186+// a named one overrides it for its load only
187+fn test_config_gpgdir_default() ! {
188+ tmp := config_tmp('gpgdir')!
189+ defer { os.rmdir_all(tmp) or {} }
190+ cfg := os.join_path(tmp, 'config.lip')
191+ saved := cfg_gpgdir
192+ defer { cfg_gpgdir = saved }
193+
194+ os.write_file(cfg, '(network :parallel 2)\n')!
195+ load_config(cfg, [])!
196+ assert cfg_gpgdir == '/etc/pacman.d/gnupg/'
197+
198+ os.write_file(cfg, '(path :gpg "${tmp}/keys")\n')!
199+ load_config(cfg, [])!
200+ assert cfg_gpgdir == '${tmp}/keys/'
201+
202+ os.write_file(cfg, '(network :parallel 2)\n')!
203+ load_config(cfg, [])!
204+ assert cfg_gpgdir == '/etc/pacman.d/gnupg/'
205+}
206+
207+// the default reaches the handle every writing mode opens
208+fn test_init_handle_sets_the_default_gpgdir() ! {
209+ tmp := config_tmp('gpghandle')!
210+ defer { os.rmdir_all(tmp) or {} }
211+ os.mkdir_all(os.join_path(tmp, 'root'))!
212+ saved_root, saved_db, saved_user := root_path, db_path, download_user
213+ defer {
214+ reset_config()
215+ root_path, db_path, download_user = saved_root, saved_db, saved_user
216+ }
217+ reset_config()
218+ root_path = os.join_path(tmp, 'root') + '/'
219+ db_path = os.join_path(tmp, 'db') + '/'
220+ // the sandbox user need not exist where the tests run
221+ download_user = ''
222+ ui := new_trans_ui()
223+ handle := init_handle(ui)!
224+ defer { handle.release() or {} }
225+ assert handle.option_get_gpgdir() == '/etc/pacman.d/gnupg/'
226+}
227+
228+// the config's options are the flags a run starts with: on for every mode
229+// that has the flag, untouched where it has none, and off again by --eval
230+fn test_config_options_set_mode_flags() ! {
231+ tmp := config_tmp('flags')!
232+ defer {
233+ os.rmdir_all(tmp) or {}
234+ reset_config()
235+ }
236+ cfg := os.join_path(tmp, 'config.lip')
237+ os.write_file(cfg, '(options :noconfirm true :needed true :nopkgbuildconfirm true :no-upgrade-deps true :color "never")\n')!
238+ load_config(cfg, [])!
239+ assert opt_color == 'never'
240+ install_mode := parse_mode(['vpac', 'i', 'foo'])!
241+ if install_mode is ConfigInstall {
242+ assert install_mode.noconfirm && install_mode.needed
243+ assert install_mode.no_pkgbuild_confirm && install_mode.no_upgrade_deps
244+ assert install_mode.query == ['foo']
245+ } else {
246+ assert false
247+ }
248+ remove_mode := parse_mode(['vpac', 'r', 'foo'])!
249+ if remove_mode is ConfigRemove {
250+ assert remove_mode.noconfirm
251+ } else {
252+ assert false
253+ }
254+ load_config(cfg, ['(options :noconfirm false)'])!
255+ again := parse_mode(['vpac', 'i', 'foo'])!
256+ if again is ConfigInstall {
257+ assert !again.noconfirm && again.needed
258+ } else {
259+ assert false
260+ }
261+}
262+
263+// the tunables the modes read are the config's: thresholds, sizes, the
264+// defaults a flag would otherwise carry, and the theme. a flag on the
265+// command line still wins, and the next load puts every one back
266+fn test_config_tunables() ! {
267+ tmp := config_tmp('tunables')!
268+ old_color := color_flag
269+ defer {
270+ os.rmdir_all(tmp) or {}
271+ color_flag = old_color
272+ reset_config()
273+ }
274+ cfg := os.join_path(tmp, 'config.lip')
275+ os.write_file(cfg, '(options :sync-age 0 :suggest 0.5 :fuzzy true)\n' +
276+ '(search :fields ["name" "version"] :thold 0.7)\n' +
277+ '(rank :top 3 :candidates 12 :retest 0 :completion 0.9 :max-delay 3600)\n' +
278+ '(pkgbuild :timeout 30)\n(clean :keep 2)\n(tree :depth 4)\n' +
279+ '(color :version "cyan" :warning ["bold" "magenta"] :name "none")\n')!
280+ load_config(cfg, [])!
281+ assert sync_max_age == 0
282+ assert suggest_thold == 0.5
283+ assert cfg_search_fields == ['name', 'version']
284+ assert rank_speed_candidates == 12 && rank_retest == 0
285+ assert rank_min_completion == 0.9 && rank_max_delay == 3600
286+ assert pkgbuild_rpc_timeout == 30
287+
288+ search_mode := parse_mode(['vpac', 's', 'foo'])!
289+ if search_mode is ConfigSearch {
290+ assert search_mode.thold == 0.7 && search_mode.fuzzy
291+ } else {
292+ assert false
293+ }
294+ given := parse_mode(['vpac', 's', '--thold', '0.95', 'foo'])!
295+ if given is ConfigSearch {
296+ assert given.thold == 0.95
297+ } else {
298+ assert false
299+ }
300+ rank_mode := parse_mode(['vpac', 'k', 'arch'])!
301+ if rank_mode is ConfigRank {
302+ assert rank_mode.top == 3
303+ } else {
304+ assert false
305+ }
306+ rank_given := parse_mode(['vpac', 'k', '-n', '7', 'arch'])!
307+ if rank_given is ConfigRank {
308+ assert rank_given.top == 7
309+ } else {
310+ assert false
311+ }
312+ clean_mode := parse_mode(['vpac', 'c'])!
313+ if clean_mode is ConfigClean {
314+ assert clean_mode.keep == 2
315+ } else {
316+ assert false
317+ }
318+ tree_mode := parse_mode(['vpac', 't', 'foo'])!
319+ if tree_mode is ConfigTree {
320+ assert tree_mode.depth == 4
321+ } else {
322+ assert false
323+ }
324+
325+ color_flag = 'always'
326+ assert version_style('1') == '\x1b[36m1\x1b[39m'
327+ assert name_style('n') == 'n'
328+ assert warning('w').starts_with('\x1b[')
329+
330+ os.write_file(cfg, '(path :db "${tmp}/db/")\n')!
331+ load_config(cfg, [])!
332+ assert sync_max_age == 24 * 60 * 60
333+ assert cfg_search_fields == search_default_fields
334+ assert rank_top == 10 && cfg_clean_keep == 0 && cfg_tree_depth == 0
335+ assert theme == default_theme()
336+}
337+
338+// the live display and the ranker's oses are the config's too: a bar's
339+// graphic and columns, a spinner's frames, and an os defined beside the
340+// ranker's own, which a mirrorlist on the disk is enough for
341+fn test_config_display_and_mirrorlists() ! {
342+ tmp := config_tmp('display')!
343+ defer {
344+ os.rmdir_all(tmp) or {}
345+ reset_config()
346+ }
347+ list := os.join_path(tmp, 'mirrorlist')
348+ os.write_file(list, 'Server = https://one.example/\$repo/os/\$arch\n# a comment\nServer = https://two.example/\$repo/os/\$arch\n')!
349+ cfg := os.join_path(tmp, 'config.lip')
350+ 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' +
351+ '(spinner :frames ["a" "b"] :interval 200 :done "ok" :elapsed true)\n' +
352+ '(mirrorlist :name "myos" :list "${list}" :repo "main")\n' +
353+ '(mirrorlist :name "arch" :status "https://example.org/status.json" :repo "core")\n' +
354+ '(rank :dir "${tmp}/ranked/")\n')!
355+ load_config(cfg, [])!
356+
357+ bar := bar_opts(text: 'x', show_rate: true)
358+ assert bar.text == 'x' && bar.length == 12
359+ assert !bar.show_percent && !bar.show_left && bar.show_elapsed && !bar.show_rate
360+ style := bar.style
361+ if style is progress.ClassicStyle {
362+ assert style.start == '|' && style.end == '|'
363+ assert style.fill == `#` && style.empty == `.` && style.head == 0
364+ } else {
365+ assert false, 'the bar is not the classic one'
366+ }
367+ spin := spinner_opts(text: 'working')
368+ assert spin.text == 'working' && spin.frames == ['a', 'b']
369+ assert spin.interval == 200 * time.millisecond
370+ assert spin.done_frame == 'ok' && spin.show_elapsed
371+
372+ assert rank_os_name(['myos'])! == 'myos'
373+ assert rank_oses['arch'].status_json == 'https://example.org/status.json'
374+ assert 'artix' in rank_oses
375+ mirrors := fetch_mirrorlist(rank_oses['myos'])!
376+ assert mirrors.len == 2, mirrors.str()
377+ assert rank_write_target('myos') == '${tmp}/ranked/myos.lip'
378+
379+ os.write_file(cfg, '(spinner :frames "line")\n(progress :style "block")\n')!
380+ load_config(cfg, [])!
381+ assert cfg_progress.frames == progress.spinner_line()
382+ assert bar_opts(text: 'x').style is progress.BlockStyle
383+ assert bar_opts(text: 'x').length == 30
384+ assert 'myos' !in rank_oses
385+ assert rank_write_target('arch') == '/etc/vpac.d/mirrors/arch.lip'
386+}
387+
388+// an option the config turns off holds no entry: only what is on is kept,
389+// and a false after a true takes the true back
390+fn test_config_options_hold_only_what_is_on() ! {
391+ tmp := config_tmp('optflags')!
392+ defer {
393+ os.rmdir_all(tmp) or {}
394+ reset_config()
395+ }
396+ cfg := os.join_path(tmp, 'config.lip')
397+ os.write_file(cfg, '(options :noconfirm false :needed true)\n')!
398+ load_config(cfg, [])!
399+ assert 'noconfirm' !in opt_flags
400+ assert opt_flags == {
401+ 'needed': true
402+ }
403+ // a later form, as an --eval is, turns it off again and leaves nothing
404+ load_config(cfg, ['(options :needed false)'])!
405+ assert opt_flags.len == 0
406+ mode := parse_mode(['vpac', 'i', 'foo'])! as ConfigInstall
407+ assert !mode.needed && !mode.noconfirm
408+ // the key of the flag nothing read is gone with the flag
409+ for form in ['(options :upgrade-deps true)', '(options :verbose "yes")'] {
410+ os.write_file(cfg, form + '\n')!
411+ if _ := load_config(cfg, []) {
412+ assert false, '${form} was accepted'
413+ }
414+ }
415+}
416+
417+// options :verbose turns the verbose log on for every run, and a load that
418+// does not name it turns it off again: it is the config's, reset with it
419+fn test_config_verbose_is_reset_with_the_config() ! {
420+ tmp := config_tmp('verbose')!
421+ saved_flag := verbose_flag
422+ defer {
423+ verbose_flag = saved_flag
424+ os.rmdir_all(tmp) or {}
425+ reset_config()
426+ }
427+ verbose_flag = false
428+ cfg := os.join_path(tmp, 'config.lip')
429+ os.write_file(cfg, '(options :verbose true)\n')!
430+ load_config(cfg, [])!
431+ assert cfg_verbose && verbose_on()
432+ // an --eval after the file takes it back for a run
433+ load_config(cfg, ['(options :verbose false)'])!
434+ assert !cfg_verbose && !verbose_on()
435+ os.write_file(cfg, '(options :color "never")\n')!
436+ load_config(cfg, [])!
437+ assert !cfg_verbose
438+ // the command line's flag is not the config's to reset
439+ verbose_flag = true
440+ load_config(cfg, [])!
441+ assert verbose_on() && !cfg_verbose
442+ // and it is no mode flag: no mode's struct grows a field from it
443+ mode := parse_mode(['vpac', 'i', 'foo'])! as ConfigInstall
444+ assert mode.query == ['foo']
445+}
@@ -0,0 +1,167 @@
1+@[has_globals]
2+module main
3+
4+import alpm
5+import os
6+import time
7+
8+// arch and the download user are configurable through config.lip
9+
10+// pkgcache_of is a db's package list. libalpm hands an empty db's list over
11+// as NULL, the NULL it answers an error with too: alpm_db_get_pkgcache
12+// clears the error first, so alpm_errno tells the two apart. an empty db is
13+// an empty list here — a nil one, which every list reader takes as such
14+// (pkgs, pkg_find, find_satisfier) — never a failure: a fresh root has no
15+// package installed, and pacman finds nothing in it rather than failing
16+fn pkgcache_of(handle &alpm.Handle, db &alpm.DB) !&alpm.List {
17+ return db.get_pkgcache() or {
18+ e := handle.errno()
19+ if e != .ok {
20+ return error('could not read the packages of ${db.get_name()}: ${e.strerror()}')
21+ }
22+ unsafe { &alpm.List(nil) }
23+ }
24+}
25+
26+// local_pkgcache is the installed packages' list, as pkgcache_of reads one
27+fn local_pkgcache(handle &alpm.Handle) !&alpm.List {
28+ localdb := handle.get_localdb() or { return error('could not open the local database: ${err.msg()}') }
29+ return pkgcache_of(handle, localdb)
30+}
31+
32+// lock_path is a function because db_path is configurable
33+fn lock_path() string {
34+ return db_path + 'db.lck'
35+}
36+
37+fn check_db_lock() bool {
38+ return os.exists(lock_path())
39+}
40+
41+// check_ask_db_lock warns about a db lock left behind and offers to remove it.
42+// it goes right before vpac takes the lock: a transaction or a db update.
43+// reading the dbs takes no lock, as pacman's -Ss and -Si take none, so a
44+// read-only command checks only when it is about to update them. only root
45+// can remove the lock, so anyone else gets the warning alone. the warning
46+// goes to stderr with the prompt it leads into
47+fn check_ask_db_lock(mut ui TransUI) {
48+ if !check_db_lock() {
49+ return
50+ }
51+ // one path, spelled once: the warning, the advice and the removal read
52+ // the same path, and the removal says exactly what went wrong with it
53+ lpath := lock_path()
54+ warn('database lock already exists (${lpath})')
55+ advise("if you're sure a package manager is not already running, you can remove it")
56+ if os.geteuid() != 0 {
57+ advise('run as root to remove it')
58+ return
59+ }
60+ if ui.noyes('do you want to remove ${lpath}?') {
61+ os.rm(lpath) or { report('failed to remove ${lpath}: ${err.msg()}') }
62+ }
63+}
64+
65+// init_repo registers one sync db under its name and mirrors; the arch comes
66+// from the config, so the parameter is named a to keep the global visible
67+// the handle parameter of the three functions here is spelled
68+// `mut handle alpm.Handle`, which is already the caller's pointer: spelled
69+// `mut handle &alpm.Handle` the same body hands libalpm a pointer one level
70+// off, and alpm_db_update crashes on it (tried for the review's sake, and
71+// caught by test_sync_stamp_keeps_an_old_server_time_fresh). leave it
72+fn init_repo(mut handle alpm.Handle, repo string, servers []string, a string, usage alpm.DBUsage) !&alpm.DB {
73+ // the siglevel is the configured one (pacman's default without config):
74+ // libalpm's own default is 0, which verifies nothing
75+ db := handle.register_syncdb(repo, int(cfg_siglevel))!
76+ for server in servers {
77+ db.add_server(server.replace('$repo', repo).replace('$arch', a))!
78+ }
79+ db.set_usage(usage)!
80+ return db
81+}
82+
83+// a sync db counts as synced if its file is this recent, or if vpac updated
84+// the dbs this recently. libalpm sets the file time from the mirror, so an
85+// unchanged db keeps an old time, and the stamp covers that case
86+// (options :sync-age hours) sets it; 0 never calls a db stale
87+__global sync_max_age = i64(24 * 60 * 60)
88+
89+// sync_stamp is a function because db_path is configurable
90+fn sync_stamp() string {
91+ return db_path + 'sync/vpac.synced'
92+}
93+
94+fn update_repos(mut handle alpm.Handle, force bool) ! {
95+ // one db_update call: libalpm itself updates only the stale dbs, and
96+ // "up to date" (returned as 1) is an answer, not an error. whatever it
97+ // did, the dbs are known current now, so the stamp is written
98+ handle.db_update(handle.get_syncdbs()!, force)!
99+ // the stamp is what every later freshness check reads: when it cannot
100+ // be written, the dbs count stale again next time — said, not hidden
101+ os.write_file(sync_stamp(), '') or {
102+ warn('could not write the sync stamp ${sync_stamp()}: ${err.msg()}')
103+ }
104+}
105+
106+// stale_sync_dbs lists the sync dbs not synced within sync_max_age. a sync
107+// db listing that fails is said: an empty answer would read as 'fresh
108+// enough', and it never was
109+fn stale_sync_dbs(handle &alpm.Handle) []string {
110+ dbs := handle.get_syncdbs() or {
111+ warn('could not list the sync databases: ${err.msg()}')
112+ return []string{}
113+ }
114+ stamp := if os.exists(sync_stamp()) { os.file_last_mod_unix(sync_stamp()) } else { i64(0) }
115+ now := time.now().unix()
116+ mut stale := []string{}
117+ for db in dbs.dbs() {
118+ name := db.get_name()
119+ file := '${db_path}sync/${name}.db'
120+ file_time := if os.exists(file) { os.file_last_mod_unix(file) } else { i64(0) }
121+ newest := if stamp > file_time { stamp } else { file_time }
122+ if sync_max_age > 0 && now - newest > sync_max_age {
123+ stale << name
124+ }
125+ }
126+ return stale
127+}
128+
129+// check_sync_fresh asks whether to update the sync dbs when any are stale.
130+// only root can update them, so anyone else gets the warning and carries on,
131+// and so does a --print preview, which changes nothing. the warning goes to
132+// stderr, so it stays out of piped results
133+fn check_sync_fresh(mut ui TransUI, mut handle &alpm.Handle) ! {
134+ stale := stale_sync_dbs(handle)
135+ if stale.len == 0 {
136+ return
137+ }
138+ ui.pause()
139+ warn('sync databases not synced in the last day: ${stale.join(', ')}')
140+ if ui.print_only {
141+ return
142+ }
143+ if os.geteuid() != 0 {
144+ advise('run as root to update them')
145+ return
146+ }
147+ if !ui.yesno('update them now?') {
148+ return
149+ }
150+ check_ask_db_lock(mut ui)
151+ update_repos(mut handle, false)!
152+}
153+
154+// init_repos registers the sync dbs the config defines, in the order the
155+// config lists them. the pkgbuild repo is not a sync db: it is built from,
156+// not downloaded. urls keep the $repo and $arch placeholders for libalpm to
157+// substitute
158+fn init_repos(mut handle alpm.Handle) ![]&alpm.DB {
159+ mut dbs := []&alpm.DB{}
160+ for repo in cfg_repos {
161+ if repo.kind == 'pkgbuild' {
162+ continue
163+ }
164+ dbs << init_repo(mut handle, repo.name, repo.servers, arch, repo.usage)!
165+ }
166+ return dbs
167+}
@@ -0,0 +1,157 @@
1+module main
2+
3+import alpm
4+import os
5+
6+// pacman's -Dk and -Dkk, as vpac v -D and -DD. every check returns the
7+// errors it found, as pacman words them
8+
9+// db_local_files: every entry of the local db has its description and its
10+// file list. the other checks read both, so they wait for this one
11+fn db_local_files(dbpath string) ![]string {
12+ local := '${dbpath}local'
13+ mut out := []string{}
14+ mut entries := os.ls(local) or { return error('could not open the local database ${local}: ${err.msg()}') }
15+ entries.sort()
16+ for entry in entries {
17+ if entry == 'ALPM_DB_VERSION' {
18+ continue
19+ }
20+ if !os.exists(os.join_path(local, entry, 'desc')) {
21+ out << "'${entry}': description file is missing"
22+ }
23+ if !os.exists(os.join_path(local, entry, 'files')) {
24+ out << "'${entry}': file list is missing"
25+ }
26+ }
27+ return out
28+}
29+
30+// db_missing_deps: every dependency of the packages, satisfied among the
31+// packages themselves
32+fn db_missing_deps(handle &alpm.Handle, pkgs &alpm.List) []string {
33+ mut out := []string{}
34+ mut head := handle.checkdeps(unsafe { nil }, unsafe { nil }, pkgs, 0)
35+ defer {
36+ // the misses and the depends inside them are libalpm's to free;
37+ // inner first, then the list, as pacman's check_db_missing_deps does
38+ head.free_inner(fn (p voidptr) {
39+ unsafe {
40+ miss := &alpm.DepMissing(p)
41+ miss.free()
42+ }
43+ })
44+ head.free()
45+ }
46+ // node walks to nil; the head is what lives
47+ mut node := head
48+ for node != unsafe { nil } {
49+ miss := unsafe { &alpm.DepMissing(node.data) }
50+ target := unsafe { cstring_to_vstring(miss.target) }
51+ out << "missing '${miss.depend.compute_string()}' dependency for '${target}'"
52+ node = node.next
53+ }
54+ return out
55+}
56+
57+// db_package_conflicts: no two installed packages conflict
58+fn db_package_conflicts(handle &alpm.Handle, pkgs &alpm.List) []string {
59+ mut out := []string{}
60+ mut head := handle.checkconflicts(pkgs)
61+ defer {
62+ // the conflicts are libalpm's to free, as pacman's
63+ // check_db_local_package_conflicts does: inner, then the list
64+ head.free_inner(fn (p voidptr) {
65+ unsafe {
66+ conf := &alpm.Conflict(p)
67+ conf.free()
68+ }
69+ })
70+ head.free()
71+ }
72+ // node walks to nil; the head is what lives
73+ mut node := head
74+ for node != unsafe { nil } {
75+ c := unsafe { &alpm.Conflict(node.data) }
76+ out << "'${c.package1.get_name()}' conflicts with '${c.package2.get_name()}'"
77+ node = node.next
78+ }
79+ return out
80+}
81+
82+// db_filelist_conflicts: no file, directories aside, belongs to two
83+// packages. every pair of owners is reported, in file order
84+fn db_filelist_conflicts(pkgs []&alpm.Package) []string {
85+ // the owners of every file seen so far, so a third package that shares
86+ // one clashes with both of the ones before it
87+ mut owners := map[string][]string{}
88+ mut clashes := map[string][]string{}
89+ for pkg in pkgs {
90+ for name in pkg.get_files().names() {
91+ if name.ends_with('/') {
92+ continue
93+ }
94+ for other in owners[name] {
95+ clashes[name] << "file owned by '${other}' and '${pkg.get_name()}': '${name}'"
96+ }
97+ owners[name] << pkg.get_name()
98+ }
99+ }
100+ mut names := clashes.keys()
101+ names.sort()
102+ mut out := []string{}
103+ for name in names {
104+ out << clashes[name]
105+ }
106+ return out
107+}
108+
109+// check_db_local is -Dk: the local db's files, then its packages'
110+// dependencies, conflicts and shared files. the checks accumulate: each one
111+// speaks for itself, and none hides the later ones behind an early return
112+fn check_db_local(handle &alpm.Handle, dbpath string) ![]string {
113+ mut out := db_local_files(dbpath)!
114+ mut pkgcache := local_pkgcache(handle)!
115+ out << db_missing_deps(handle, pkgcache)
116+ out << db_package_conflicts(handle, pkgcache)
117+ out << db_filelist_conflicts(pkgcache.pkgs())
118+ return out
119+}
120+
121+// check_db_sync is -Dkk: every sync package's dependencies, satisfied
122+// across all the sync dbs. a cache that cannot be read has the db say so;
123+// the check does not quietly pretend that db has no packages
124+fn check_db_sync(handle &alpm.Handle) ![]string {
125+ mut all := &alpm.List(unsafe { nil })
126+ mut syncdbs := handle.get_syncdbs()!
127+ for db in syncdbs.dbs() {
128+ // a cache that cannot be read is named, so its unchecked packages
129+ // are not read as an empty db; an empty db is one, and checks fine
130+ mut cache := pkgcache_of(handle, db) or {
131+ warn('${err.msg()}: its packages are not checked')
132+ continue
133+ }
134+ for pkg in cache.pkgs() {
135+ all = all.add(pkg)
136+ }
137+ }
138+ defer { all.free() }
139+ return db_missing_deps(handle, all)
140+}
141+
142+// verify_db is vpac v -D (level 1) and -DD (level 2). each error is a failed
143+// target, so vpac exits 1 when there is any
144+fn verify_db(mut handle &alpm.Handle, level int) ! {
145+ errors := if level >= 2 {
146+ init_repos(mut handle)!
147+ check_db_sync(handle)!
148+ } else {
149+ check_db_local(handle, db_path)!
150+ }
151+ for e in errors {
152+ target_error(e)
153+ }
154+ if errors.len == 0 {
155+ report('no database errors found')
156+ }
157+}
@@ -0,0 +1,109 @@
1+module main
2+
3+import alpm
4+import os
5+import testdb
6+
7+fn check_tmp(name string) !(string, string) {
8+ tmp := os.join_path(os.vtmp_dir(), 'vpac_test_dbcheck_${name}_${os.getpid()}')
9+ os.mkdir_all(os.join_path(tmp, 'root'))!
10+ return tmp, os.join_path(tmp, 'db') + '/'
11+}
12+
13+fn test_db_local_files() ! {
14+ tmp, dbpath := check_tmp('files')!
15+ defer { os.rmdir_all(tmp) or {} }
16+ testdb.write_local(dbpath, [testdb.Pkg{
17+ name: 'whole'
18+ }])!
19+ os.mkdir_all(os.join_path(dbpath, 'local', 'nodesc-1.0-1'))!
20+ os.write_file(os.join_path(dbpath, 'local', 'nodesc-1.0-1', 'files'), '%FILES%\n\n')!
21+ os.mkdir_all(os.join_path(dbpath, 'local', 'nofiles-1.0-1'))!
22+ os.write_file(os.join_path(dbpath, 'local', 'nofiles-1.0-1', 'desc'), '%NAME%\nnofiles\n\n')!
23+ assert db_local_files(dbpath)! == ["'nodesc-1.0-1': description file is missing",
24+ "'nofiles-1.0-1': file list is missing"]
25+}
26+
27+fn test_check_db_local() ! {
28+ tmp, dbpath := check_tmp('local')!
29+ defer { os.rmdir_all(tmp) or {} }
30+ testdb.write_local(dbpath, [
31+ testdb.Pkg{
32+ name: 'app'
33+ depends: ['lib>=1.0', 'gone', 'old<1.0']
34+ files: ['usr/', 'usr/bin/', 'usr/bin/app', 'usr/share/shared']
35+ },
36+ testdb.Pkg{
37+ name: 'lib'
38+ files: ['usr/', 'usr/lib/libx.so']
39+ },
40+ testdb.Pkg{
41+ name: 'old'
42+ },
43+ testdb.Pkg{
44+ name: 'rival'
45+ conflicts: ['app']
46+ files: ['usr/', 'usr/share/shared']
47+ },
48+ ])!
49+ handle := alpm.initialize(os.join_path(tmp, 'root') + '/', dbpath)!
50+ defer { handle.release() or {} }
51+ errors := check_db_local(handle, dbpath)!
52+ // a dependency nothing provides, one whose version does not match, two
53+ // packages in conflict, and a file two packages own. the shared usr/
54+ // directory is no clash
55+ assert "missing 'gone' dependency for 'app'" in errors
56+ assert "missing 'old<1.0' dependency for 'app'" in errors
57+ assert errors.any(it.contains('conflicts with') && it.contains("'app'")
58+ && it.contains("'rival'"))
59+ assert "file owned by 'app' and 'rival': 'usr/share/shared'" in errors
60+ assert errors.len == 4, errors.str()
61+}
62+
63+fn test_check_db_local_clean() ! {
64+ tmp, dbpath := check_tmp('clean')!
65+ defer { os.rmdir_all(tmp) or {} }
66+ testdb.write_local(dbpath, [
67+ testdb.Pkg{
68+ name: 'app'
69+ depends: ['lib']
70+ files: ['usr/', 'usr/bin/app']
71+ },
72+ testdb.Pkg{
73+ name: 'lib'
74+ files: ['usr/', 'usr/lib/lib.so']
75+ },
76+ ])!
77+ handle := alpm.initialize(os.join_path(tmp, 'root') + '/', dbpath)!
78+ defer { handle.release() or {} }
79+ assert check_db_local(handle, dbpath)! == []
80+}
81+
82+fn test_db_local_files_edges() ! {
83+ tmp, dbpath := check_tmp('fileedges')!
84+ defer { os.rmdir_all(tmp) or {} }
85+ // a local db that is not there cannot be checked, which is an error
86+ if got := db_local_files(dbpath) {
87+ assert false, 'a missing local db checked clean: ${got}'
88+ } else {
89+ assert err.msg().contains('could not open the local database'), err.msg()
90+ }
91+ // the version file alone is an empty db: it is no package entry, and
92+ // nothing is missing from it
93+ testdb.write_local(dbpath, [])!
94+ assert os.exists(os.join_path(dbpath, 'local', 'ALPM_DB_VERSION'))
95+ assert db_local_files(dbpath)! == []
96+ // an entry with neither file is named for both, in order
97+ os.mkdir_all(os.join_path(dbpath, 'local', 'bare-1.0-1'))!
98+ assert db_local_files(dbpath)! == ["'bare-1.0-1': description file is missing",
99+ "'bare-1.0-1': file list is missing"]
100+ // whole entries beside it stay unnamed, and the order is the names'
101+ testdb.write_local(dbpath, [testdb.Pkg{
102+ name: 'aaa'
103+ }, testdb.Pkg{
104+ name: 'zzz'
105+ }])!
106+ os.rm(os.join_path(dbpath, 'local', 'zzz-1.0-1', 'files'))!
107+ assert db_local_files(dbpath)! == ["'bare-1.0-1': description file is missing",
108+ "'bare-1.0-1': file list is missing", "'zzz-1.0-1': file list is missing"]
109+}
@@ -0,0 +1,66 @@
1+module main
2+
3+import os
4+
5+// the signature level libalpm ends up with, read back through vpac's own
6+// setup. the alpm binding once wrote its SigLevel bits as masks where a V
7+// flag enum takes positions, and libalpm got 6 instead of 3075: no package
8+// or database signature was ever checked
9+fn test_default_siglevel_reaches_libalpm() ! {
10+ // package | package_optional | database | database_optional
11+ want := 1 | 2 | 1024 | 2048
12+ assert int(cfg_siglevel) == want
13+
14+ old_db := db_path
15+ tmp := os.join_path(os.vtmp_dir(), 'vpac_test_db_${os.getpid()}')
16+ os.mkdir_all(os.join_path(tmp, 'local'))!
17+ os.write_file(os.join_path(tmp, 'local', 'ALPM_DB_VERSION'), '9\n')!
18+ db_path = tmp + '/'
19+ defer {
20+ db_path = old_db
21+ os.rmdir_all(tmp) or {}
22+ }
23+
24+ ui := new_trans_ui()
25+ mut handle := init_handle(ui)!
26+ defer { handle.release() or {} }
27+ default := handle.option_get_default_siglevel() or { return error('no default siglevel') }
28+ local_file := handle.option_get_local_file_siglevel() or { return error('no local file siglevel') }
29+ remote_file := handle.option_get_remote_file_siglevel() or {
30+ return error('no remote file siglevel')
31+ }
32+ assert int(default) == want
33+ assert int(local_file) == want
34+ assert int(remote_file) == want
35+ // the configured architecture is on the handle, so check_arch has one
36+ // to compare a package's with
37+ arches := handle.option_get_architectures() or { return error('no architectures') }
38+ assert arches.count() == 1
39+ assert arches.get_str() or { '' } == arch
40+ // and pacman's default hook dir, after libalpm's own
41+ hooks := handle.option_get_hookdirs() or { return error('no hookdirs') }
42+ assert hooks.count() == 2
43+ db := init_repo(mut handle, 'core', [], arch, .sync | .search)!
44+ assert int(db.get_siglevel()) == want
45+ // the usage the repo form gives reaches libalpm the same way
46+ usage := db.get_usage() or { return error('no usage') }
47+ assert int(usage) == 1 | 2
48+}
49+
50+// every name the config's (network :siglevel ...) takes is libalpm's bit
51+fn test_siglevel_names() {
52+ want := {
53+ 'package': 1 << 0
54+ 'package_optional': 1 << 1
55+ 'package_marginal_ok': 1 << 2
56+ 'package_unknown_ok': 1 << 3
57+ 'database': 1 << 10
58+ 'database_optional': 1 << 11
59+ 'database_marginal_ok': 1 << 12
60+ 'database_unknown_ok': 1 << 13
61+ }
62+ assert siglevel_names.len == want.len
63+ for name, bit in want {
64+ assert int(siglevel_names[name] or { panic(name) }) == bit, name
65+ }
66+}
@@ -0,0 +1,45 @@
1+module main
2+
3+import alpm
4+
5+struct ConfigDeptest {
6+pub mut:
7+ show_help bool @[long: help; short: h]
8+ query []string @[tail]
9+}
10+
11+// unsatisfied_deps are the dependencies no installed package satisfies, in
12+// the order and the spelling they were given
13+fn unsatisfied_deps(pkgcache &alpm.List, deps []string) []string {
14+ mut out := []string{}
15+ for dep in deps {
16+ if _ := pkgcache.find_satisfier(dep) {
17+ continue
18+ }
19+ out << dep
20+ }
21+ return out
22+}
23+
24+// deptest is pacman's -T: it prints every dependency no installed package
25+// satisfies and returns them; main exits 127 when there is one, the code
26+// makepkg tells apart from a failure. it changes nothing, so it needs no root
27+fn deptest(config ConfigDeptest) ![]string {
28+ need_query(config.query, 'dependency')!
29+ handle := alpm.initialize(root_path, db_path) or { return err }
30+ defer { handle.release() or { went_on('release the alpm handle', err) } }
31+ pkgcache := local_pkgcache(handle)!
32+ missing := unsatisfied_deps(pkgcache, config.query)
33+ if ipc_on() {
34+ emit(UnsatisfiedEvent{
35+ deps: missing
36+ })
37+ } else {
38+ for dep in missing {
39+ println(dep)
40+ }
41+ }
42+ // the defer above releases the handle; a second release here would free
43+ // it twice
44+ return missing
45+}
@@ -0,0 +1,81 @@
1+module main
2+
3+import alpm
4+import os
5+
6+fn test_unsatisfied_deps() ! {
7+ tmp := os.join_path(os.vtmp_dir(), 'vpac_test_deptest_${os.getpid()}')
8+ local := os.join_path(tmp, 'db', 'local')
9+ os.mkdir_all(os.join_path(tmp, 'root'))!
10+ os.mkdir_all(local)!
11+ defer { os.rmdir_all(tmp) or {} }
12+ os.write_file(os.join_path(local, 'ALPM_DB_VERSION'), '9\n')!
13+ for name, extra in {
14+ 'zsh': ''
15+ 'impl': '%PROVIDES%\nlibfoo.so=1-64\nvirtual\n\n'
16+ } {
17+ dir := os.join_path(local, '${name}-5.9-1')
18+ os.mkdir_all(dir)!
19+ os.write_file(os.join_path(dir, 'desc'), '%NAME%\n${name}\n\n%VERSION%\n5.9-1\n\n${extra}')!
20+ }
21+ handle := alpm.initialize(os.join_path(tmp, 'root') + '/', os.join_path(tmp, 'db') + '/')!
22+ defer { handle.release() or {} }
23+ pkgcache := handle.get_localdb()!.get_pkgcache() or { return error('empty db') }
24+
25+ // names, versions and provisions, kept in the order and spelling given
26+ assert unsatisfied_deps(pkgcache, ['zsh', 'zsh>=5', 'zsh=5.9-1', 'virtual', 'libfoo.so=1-64']) == []
27+ assert unsatisfied_deps(pkgcache, ['zsh<5', 'gone', 'zsh', 'zsh>6', 'libfoo.so=2']) == [
28+ 'zsh<5',
29+ 'gone',
30+ 'zsh>6',
31+ 'libfoo.so=2',
32+ ]
33+ assert unsatisfied_deps(pkgcache, []) == []
34+}
35+
36+// no dependency, no run: pacman's -T speaks up as well
37+fn test_deptest_needs_a_query() ! {
38+ if _ := deptest(ConfigDeptest{}) {
39+ assert false, 'an empty query ran'
40+ } else {
41+ assert err.msg().contains('no dependency'), err.msg()
42+ }
43+}
44+
45+// deptest itself, against a db on disk: what it answers is what is missing,
46+// in the order asked, and the db is only read
47+fn test_deptest_reads_the_configured_db() ! {
48+ tmp := os.join_path(os.vtmp_dir(), 'vpac_test_deptest_run_${os.getpid()}')
49+ local := os.join_path(tmp, 'db', 'local')
50+ os.mkdir_all(os.join_path(tmp, 'root'))!
51+ os.mkdir_all(local)!
52+ saved_root, saved_db := root_path, db_path
53+ defer {
54+ root_path, db_path = saved_root, saved_db
55+ os.rmdir_all(tmp) or {}
56+ }
57+ root_path = os.join_path(tmp, 'root') + '/'
58+ db_path = os.join_path(tmp, 'db') + '/'
59+ os.write_file(os.join_path(local, 'ALPM_DB_VERSION'), '9\n')!
60+ // nothing installed: every dependency is missing, and that is an
61+ // answer, not an error
62+ assert deptest(ConfigDeptest{ query: ['zsh', 'sh'] })! == ['zsh', 'sh']
63+ dir := os.join_path(local, 'zsh-5.9-1')
64+ os.mkdir_all(dir)!
65+ os.write_file(os.join_path(dir, 'desc'), '%NAME%\nzsh\n\n%VERSION%\n5.9-1\n\n%PROVIDES%\nsh\n\n')!
66+ assert deptest(ConfigDeptest{ query: ['zsh', 'sh'] })! == []
67+ assert deptest(ConfigDeptest{ query: ['zsh>=6', 'sh', 'zsh=5.9-1', 'bash'] })! == [
68+ 'zsh>=6',
69+ 'bash',
70+ ]
71+ // the same dependency asked twice is answered twice
72+ assert deptest(ConfigDeptest{ query: ['bash', 'bash'] })! == ['bash', 'bash']
73+ // the run took no lock and left the db as it was
74+ assert !os.exists(os.join_path(tmp, 'db', 'db.lck'))
75+ assert os.ls(local)!.len == 2
76+ // a db that is not there is an error, not 'everything is missing'
77+ db_path = os.join_path(tmp, 'nowhere') + '/'
78+ if got := deptest(ConfigDeptest{ query: ['zsh'] }) {
79+ assert false, 'a missing db answered ${got}'
80+ }
81+}
@@ -0,0 +1,246 @@
1+module main
2+
3+import alpm
4+import v.profiler
5+
6+// DepTracer walks the dependency graph straight from libalpm: the local db
7+// answers for installed packages and the sync dbs for everything else, so a
8+// package that is not installed can be traced too. the sync dbs are the
9+// lookup's: set up, and asked about their freshness, by the first target or
10+// dependency the installed packages do not answer, so a tree that stays
11+// among them never touches the sync dbs
12+struct DepTracer {
13+mut:
14+ handle &alpm.Handle
15+ ui &TransUI
16+ lookup &InfoLookup
17+ installed &alpm.List
18+ sync_lost bool
19+ reverse bool
20+ optional bool
21+ max_depth int
22+ seen map[string]bool
23+}
24+
25+// TreeNode is one node of the tree: a resolved package, or a dependency that
26+// nothing provides (pkg is nil then, and dep is how it was asked for). tag
27+// marks an optional dependency
28+struct TreeNode {
29+ pkg &alpm.Package = unsafe { nil }
30+ dep string
31+ tag string
32+}
33+
34+// TreeBranch is a node with the branches below it, as the tracer collects
35+// them. a package already expanded higher up is seen, and is not expanded
36+// again, which also stops cycles
37+struct TreeBranch {
38+ node TreeNode
39+ seen bool
40+ children []TreeBranch
41+}
42+
43+// tree_label is the name and version, then the size: what the package takes
44+// on disk when installed, or what it downloads when it is only in the repos
45+fn tree_label(pkg &alpm.Package) string {
46+ label := '${name_style(pkg.get_name())} ${version_style(pkg.get_version())}'
47+ if pkg.get_origin() == .syncdb {
48+ return '${label} (${profiler.format_bytes(u64(pkg.download_size()))} to download)'
49+ }
50+ return '${label} (${profiler.format_bytes(u64(pkg.get_isize()))})'
51+}
52+
53+// node_label is the line a node draws: the package's label, or the
54+// dependency nothing provides
55+fn node_label(node TreeNode) string {
56+ if node.pkg == unsafe { nil } {
57+ return old_style('${node.dep} (not found)') + node.tag
58+ }
59+ return tree_label(node.pkg) + node.tag
60+}
61+
62+fn (mut t DepTracer) dep_node(depstring string, tag string) TreeNode {
63+ if pkg := t.installed.find_satisfier(depstring) {
64+ return TreeNode{
65+ pkg: pkg
66+ tag: tag
67+ }
68+ }
69+ // sync dbs that cannot be set up are said once; the tree goes on with
70+ // what is installed, and the dependency draws as not found
71+ if !t.sync_lost {
72+ t.lookup.sync_dbs(mut t.ui, mut t.handle) or {
73+ warn('the sync databases are left out of the tree: ${err.msg()}')
74+ t.sync_lost = true
75+ }
76+ }
77+ if dbs := t.handle.get_syncdbs() {
78+ if pkg := t.handle.find_dbs_satisfier(dbs, depstring) {
79+ return TreeNode{
80+ pkg: pkg
81+ tag: tag
82+ }
83+ }
84+ }
85+ return TreeNode{
86+ dep: depstring
87+ tag: tag
88+ }
89+}
90+
91+// children are what the package depends on, or with -r what requires it
92+fn (mut t DepTracer) children(pkg &alpm.Package) []TreeNode {
93+ mut nodes := []TreeNode{}
94+ if t.reverse {
95+ for name in pkg.compute_required_by() {
96+ if p := t.installed.pkg_find(name) {
97+ nodes << TreeNode{
98+ pkg: p
99+ }
100+ }
101+ }
102+ return nodes
103+ }
104+ for dep in pkg.get_depends().depends() {
105+ nodes << t.dep_node(dep.compute_string(), '')
106+ }
107+ if t.optional {
108+ for dep in pkg.get_opt_depends().depends() {
109+ nodes << t.dep_node(dep.compute_string(), ' (optional)')
110+ }
111+ }
112+ return nodes
113+}
114+
115+// branches collects the tree below nodes, depth first: a package is
116+// expanded the first time it appears, down to the max depth, and later
117+// appearances are marked seen
118+fn (mut t DepTracer) branches(nodes []TreeNode, depth int) []TreeBranch {
119+ mut out := []TreeBranch{}
120+ for node in nodes {
121+ if node.pkg == unsafe { nil } {
122+ out << TreeBranch{
123+ node: node
124+ }
125+ continue
126+ }
127+ name := node.pkg.get_name()
128+ if t.seen[name] {
129+ out << TreeBranch{
130+ node: node
131+ seen: true
132+ }
133+ continue
134+ }
135+ t.seen[name] = true
136+ out << TreeBranch{
137+ node: node
138+ children: if t.max_depth == 0 || depth < t.max_depth {
139+ t.branches(t.children(node.pkg), depth + 1)
140+ } else {
141+ []TreeBranch{}
142+ }
143+ }
144+ }
145+ return out
146+}
147+
148+// tree_item is a branch as a frontend gets it, plain
149+fn tree_item(b TreeBranch) TreeItem {
150+ optional := b.node.tag != ''
151+ if b.node.pkg == unsafe { nil } {
152+ return TreeItem{
153+ name: b.node.dep
154+ optional: optional
155+ }
156+ }
157+ return TreeItem{
158+ name: b.node.pkg.get_name()
159+ version: b.node.pkg.get_version()
160+ found: true
161+ optional: optional
162+ seen: b.seen
163+ children: b.children.map(tree_item(it))
164+ }
165+}
166+
167+// print_branches draws the branch for each node, then the ones below it
168+fn print_branches(branches []TreeBranch, prefix string) {
169+ for i, b in branches {
170+ last := i == branches.len - 1
171+ branch := branch_style(if last { '└── ' } else { '├── ' })
172+ println(prefix + branch + node_label(b.node) + if b.seen { ' (seen)' } else { '' })
173+ print_branches(b.children, prefix + branch_style(if last { ' ' } else { '│ ' }))
174+ }
175+}
176+
177+fn tree(config ConfigTree) ! {
178+ need_query(config.query, 'package')!
179+ mut ui := new_trans_ui(noconfirm: config.noconfirm)
180+ mut handle := init_handle(ui)!
181+ defer { handle.release() or { went_on('release the alpm handle', err) } }
182+ defer { ui.stop() }
183+
184+ // the roots are found as info finds its targets: installed first, then
185+ // the sync dbs, a repo/ prefix scoping the search. the lookup sets the
186+ // sync dbs up when a target or a dependency first needs them
187+ mut lookup := InfoLookup{
188+ installed: local_pkgcache(handle)!
189+ }
190+ // a dependency several sync packages provide is drawn with the first, as
191+ // pactree draws it: libalpm's provider question is answered silently
192+ // there. the flag rides the whole walk, and lands false again on the way
193+ // out, the scope the way walk_upgrade_deps keeps its own
194+ ui.walking = true
195+ defer { ui.walking = false }
196+ mut installed := local_pkgcache(handle)!
197+
198+ for i, target in config.query {
199+ // one target that resolves to nothing does not take the rest of
200+ // them down with it
201+ root := lookup.find(mut ui, mut handle, target) or {
202+ target_error(err.msg())
203+ continue
204+ }
205+
206+ // the blank line between trees is a terminal's frame; under ipc each
207+ // tree leaves as its own event, and a stray line on stdout is not
208+ // something a structured reader asked for
209+ if i > 0 && !ipc_on() {
210+ println('')
211+ }
212+ mut t := DepTracer{
213+ handle: handle
214+ ui: ui
215+ lookup: &lookup
216+ installed: installed
217+ reverse: config.reverse
218+ optional: config.optional
219+ max_depth: config.depth
220+ }
221+ t.seen[root.get_name()] = true
222+ branches := t.branches(t.children(root), 1)
223+ if ipc_on() {
224+ emit(TreeEvent{
225+ reverse: config.reverse
226+ root: TreeItem{
227+ name: root.get_name()
228+ version: root.get_version()
229+ found: true
230+ children: branches.map(tree_item(it))
231+ }
232+ })
233+ continue
234+ }
235+ println(tree_label(root))
236+ if branches.len == 0 {
237+ if config.reverse {
238+ println('nothing requires it')
239+ } else {
240+ println('no dependencies')
241+ }
242+ continue
243+ }
244+ print_branches(branches, '')
245+ }
246+}
@@ -0,0 +1,234 @@
1+@[has_globals]
2+module main
3+
4+import alpm
5+import time
6+import v.profiler
7+
8+// pkg_field_names are the fields info and search can show. both take the same
9+// names through --fields, so a field means the same thing in either command
10+const pkg_field_names = ['source', 'name', 'version', 'description', 'arch', 'url', 'licenses',
11+ 'groups', 'provides', 'depends', 'optdepends', 'required_by', 'optional_for', 'conflicts',
12+ 'replaces', 'size', 'packager', 'build_date', 'install_date', 'install_reason', 'install_script',
13+ 'validation']
14+
15+// search_default_fields are the columns of a search unless --fields says otherwise
16+const search_default_fields = ['source', 'name', 'version', 'description']
17+
18+// cfg_search_fields are the columns the config asks for, (search :fields):
19+// search_default_fields unless it says otherwise. cfg_search_thold is the
20+// fuzzy search's threshold when --thold names none, (search :thold)
21+__global cfg_search_fields = ['source', 'name', 'version', 'description']
22+__global cfg_search_thold = 0.9
23+// what a mode starts from when its flag names nothing: (clean :keep), the
24+// versions of a package the cache keeps, and (tree :depth), how deep a tree
25+// is drawn; 0 leaves each to the mode
26+__global cfg_clean_keep = 0
27+__global cfg_tree_depth = 0
28+
29+// parse_fields reads --fields: nothing gives the defaults, 'all' every field,
30+// and anything else a comma separated list of field names
31+fn parse_fields(spec string, defaults []string) ![]string {
32+ if spec == '' {
33+ return defaults
34+ }
35+ if spec == 'all' {
36+ return pkg_field_names
37+ }
38+ mut out := []string{}
39+ for f in spec.split(',') {
40+ name := f.trim_space()
41+ if name !in pkg_field_names {
42+ return error('unknown field "${name}", the fields are: ${pkg_field_names.join(', ')}')
43+ }
44+ out << name
45+ }
46+ return out
47+}
48+
49+// strs_text is a list of strings as one value: 'a, b'. the list arrives as a
50+// borrowed pointer, and strs() walks it without writing to it — the mut
51+// binding is only the mutable receiver the method spells, never a write to
52+// the C list
53+fn strs_text(list &alpm.List) string {
54+ mut l := unsafe { list }
55+ return l.strs().join(', ')
56+}
57+
58+// pkg_source is where an alpm package comes from: 'local', or the sync repo
59+fn pkg_source(pkg &alpm.Package) string {
60+ origin := pkg.get_origin()
61+ if origin == .file {
62+ return 'file'
63+ }
64+ if origin != .syncdb {
65+ return 'local'
66+ }
67+ db := pkg.get_db() or { return 'remote' }
68+ return db.get_name()
69+}
70+
71+// pkg_field_items gives a field's value as separate items, for the fields that
72+// wrap their lists across lines. none for the fields whose value is one piece
73+// of text
74+fn pkg_field_items(pkg &alpm.Package, field string) ?[]string {
75+ return match field {
76+ 'licenses' {
77+ pkg.get_licenses().strs()
78+ }
79+ 'groups' {
80+ pkg.get_groups().strs()
81+ }
82+ 'provides' {
83+ pkg.get_provides().depends().map(|d| d.compute_string())
84+ }
85+ 'depends' {
86+ pkg.get_depends().depends().map(|d| d.compute_string())
87+ }
88+ // for a sync package libalpm looks through every sync db, as pacman -Sii
89+ 'required_by' {
90+ pkg.compute_required_by()
91+ }
92+ 'optional_for' {
93+ pkg.compute_optional_for()
94+ }
95+ 'conflicts' {
96+ pkg.get_conflicts().depends().map(|d| d.compute_string())
97+ }
98+ 'replaces' {
99+ pkg.get_replaces().depends().map(|d| d.compute_string())
100+ }
101+ // every optional dependency of its own line: name, then its reason.
102+ // an installed one carries pacman's [installed] mark
103+ 'optdepends' {
104+ pkg.get_opt_depends().depends().map(|d| optdepend_text(d, pkg))
105+ }
106+ else {
107+ none
108+ }
109+ }
110+}
111+
112+// optdepend_text is one line of the optional deps: name, then its reason. an
113+// installed package marks the deps the local db satisfies, as pacman's -Qi
114+// does; a sync package's list stays bare, like pacman's -Si
115+fn optdepend_text(d alpm.Depend, pkg &alpm.Package) string {
116+ name := d.get_name()
117+ desc := d.get_desc()
118+ text := if desc == '' { name } else { '${name}: ${desc}' }
119+ // the local cache hangs off the package's own db, no separate lookup
120+ if pkg.get_origin() != .localdb {
121+ return text
122+ }
123+ if db := pkg.get_db() {
124+ if cache := db.get_pkgcache() {
125+ if _ := cache.find_satisfier(d.compute_string()) {
126+ return text + ' [installed]'
127+ }
128+ }
129+ }
130+ return text
131+}
132+
133+// pkg_field is one field of an alpm package. '' when the field does not apply,
134+// such as the install fields of a package that is not installed
135+fn pkg_field(pkg &alpm.Package, source string, field string) string {
136+ sync := pkg.get_origin() == .syncdb
137+ return match field {
138+ 'source' {
139+ source
140+ }
141+ 'name' {
142+ pkg.get_name()
143+ }
144+ 'version' {
145+ pkg.get_version()
146+ }
147+ 'description' {
148+ pkg.get_desc()
149+ }
150+ 'arch' {
151+ pkg.get_arch()
152+ }
153+ 'url' {
154+ pkg.get_url()
155+ }
156+ 'licenses' {
157+ strs_text(pkg.get_licenses())
158+ }
159+ 'groups' {
160+ strs_text(pkg.get_groups())
161+ }
162+ 'provides' {
163+ depends_text(pkg.get_provides())
164+ }
165+ 'depends' {
166+ depends_text(pkg.get_depends())
167+ }
168+ // the mark rides along here too, since info's one-value fields and
169+ // the listing columns of search read the same sense from the field:
170+ // an installed package marks the deps the local db satisfies, as
171+ // pacman's -Qi and -Ss listings do
172+ 'optdepends' {
173+ pkg.get_opt_depends().depends().map(|d| optdepend_text(d, pkg)).join(', ')
174+ }
175+ 'required_by' {
176+ pkg.compute_required_by().join(', ')
177+ }
178+ 'optional_for' {
179+ pkg.compute_optional_for().join(', ')
180+ }
181+ 'conflicts' {
182+ depends_text(pkg.get_conflicts())
183+ }
184+ 'replaces' {
185+ depends_text(pkg.get_replaces())
186+ }
187+ 'size' {
188+ if sync {
189+ profiler.format_bytes(u64(pkg.download_size())) + ' to download'
190+ } else {
191+ profiler.format_bytes(u64(pkg.get_isize()))
192+ }
193+ }
194+ 'packager' {
195+ pkg.get_packager()
196+ }
197+ 'build_date' {
198+ time.unix(pkg.get_build_date()).format_ss()
199+ }
200+ 'install_date' {
201+ if sync { '' } else { time.unix(pkg.get_install_date()).format_ss() }
202+ }
203+ 'install_reason' {
204+ if sync { '' } else { reason_to_str(pkg.get_reason()) }
205+ }
206+ 'install_script' {
207+ if sync {
208+ ''
209+ } else {
210+ if pkg.has_scriptlet() { 'yes' } else { 'no' }
211+ }
212+ }
213+ 'validation' {
214+ validation_to_str(pkg.get_validation())
215+ }
216+ else {
217+ ''
218+ }
219+ }
220+}
221+
222+// pkgbuild_field is one field of a pkgbuild result. the rpc only knows some of
223+// them; the source is the repo's own name
224+fn pkgbuild_field(info PackagePkgbuild, field string, source string) string {
225+ return match field {
226+ 'source' { source }
227+ 'name' { info.name }
228+ 'version' { info.version }
229+ 'description' { info.description }
230+ 'url' { info.url }
231+ 'packager' { info.maintainer or { '' } }
232+ else { '' }
233+ }
234+}
@@ -0,0 +1,221 @@
1+module main
2+
3+import alpm
4+import os
5+
6+fn files(config ConfigFiles) ! {
7+ need_query(config.query, 'package')!
8+ // no display: the ui is there for the did-you-mean question
9+ mut ui := new_trans_ui(noconfirm: config.noconfirm)
10+ defer { ui.stop() }
11+ mut handle := alpm.initialize(root_path, db_path) or { return err }
12+ defer { handle.release() or { went_on('release the alpm handle', err) } }
13+
14+ mut pkgcache := local_pkgcache(handle)!
15+
16+ for target in config.query {
17+ mut name := local_target_name(target)
18+ pkg := find_local_target(pkgcache, name, true) or {
19+ name = did_you_mean(mut ui, name, pkg_names(pkgcache.pkgs())) or {
20+ target_error(err.msg())
21+ continue
22+ }
23+ pkgcache.pkg_find(name) or {
24+ target_error('unknown package: "${name}"')
25+ continue
26+ }
27+ }
28+
29+ paths := pkg_paths(pkg)
30+ if ipc_on() {
31+ emit(FilesEvent{
32+ package: pkg.get_name()
33+ paths: paths
34+ })
35+ continue
36+ }
37+ println(table_text(paths.map(row(name_style(pkg.get_name()), it)), '', ' '))
38+ }
39+}
40+
41+// pkg_paths are the files of an installed package, as paths under the root
42+fn pkg_paths(pkg &alpm.Package) []string {
43+ return pkg.get_files().names().map('${root_path}${it}')
44+}
45+
46+// OwnerQuery is one target of owner mode, the way pacman's query_fileowner
47+// shapes it: rel is what the filelists are searched for, relative to the
48+// root — a directory spelled with its trailing slash, as filelists spell
49+// one — and dir says a directory is asked for
50+struct OwnerQuery {
51+ rel string
52+ dir bool
53+}
54+
55+// file_owners are the installed packages whose filelists hold q.rel, an
56+// exact match as alpm_filelist_contains makes it. a file has one owner and
57+// the walk stops there; a directory is shared, and every owner answers, as
58+// in pacman
59+fn file_owners(pkgs []&alpm.Package, q OwnerQuery) []&alpm.Package {
60+ mut out := []&alpm.Package{}
61+ for pkg in pkgs {
62+ if pkg.get_files().contains(q.rel) != none {
63+ out << pkg
64+ if !q.dir {
65+ break
66+ }
67+ }
68+ }
69+ return out
70+}
71+
72+// owner_query makes a target into the path the filelists are searched for,
73+// step for step as pacman's query_fileowner does: trailing slashes go, a
74+// missing bare name is looked up in PATH, the directory the name sits in is
75+// canonicalized while the name itself is not (a symlink is owned as the
76+// link, the way a filelist lists it), and a directory takes its slash back
77+fn owner_query(target string) !OwnerQuery {
78+ if target == '' {
79+ return error('empty path')
80+ }
81+ // a trailing slash would make lstat follow a directory symlink; it still
82+ // asks for a directory, unless what is there says otherwise. / stays
83+ mut p := target
84+ mut dir := false
85+ for p.len > 1 && p.ends_with('/') {
86+ p = p[..p.len - 1]
87+ dir = true
88+ }
89+ mut missing := false
90+ mut kind := os.FileType.unknown
91+ if st := os.lstat(p) {
92+ kind = st.get_filetype()
93+ } else {
94+ missing = true
95+ // not a path but a program name: the first PATH entry that holds it
96+ if !p.contains('/') {
97+ if found := search_path(p) {
98+ p = found
99+ missing = false
100+ kind = (os.lstat(p) or { os.Stat{} }).get_filetype()
101+ }
102+ }
103+ }
104+ // a directory that cannot be resolved (it does not exist) leaves the
105+ // path as named. pacman proceeds with it verbatim, which drops a relative
106+ // one as outside the root; it is made absolute here instead, so a file a
107+ // package lists under a since deleted directory still finds its owner
108+ mut path := lrealpath(p) or { os.abs_path(p) }
109+ // an existing path is a directory by what it is, a missing one by the
110+ // slash it was given
111+ dir = if missing { dir } else { kind == .directory }
112+ if dir && !path.ends_with('/') {
113+ path += '/'
114+ }
115+ // the root itself is the empty relative path: no package lists it, so it
116+ // gets the plain no-owner answer, not the outside-root one. the real
117+ // filespace '/' and a fake root '/x/' both end in their slash, which a
118+ // missing root (no directory to say so) can lack
119+ if path == root_path || path + '/' == root_path {
120+ return OwnerQuery{
121+ dir: true
122+ }
123+ }
124+ if !path.starts_with(root_path) {
125+ return error('file is outside of root (${root_path}): ${path}')
126+ }
127+ return OwnerQuery{
128+ rel: path[root_path.len..]
129+ dir: dir
130+ }
131+}
132+
133+// search_path is pacman's own PATH search for a bare name: the first entry
134+// where the name exists at all, as lstat sees it — a link or a file that is
135+// not executable counts, as in pacman. an empty entry would be the working
136+// directory, which the caller has looked in already
137+fn search_path(name string) ?string {
138+ for entry in os.getenv('PATH').split(':') {
139+ if entry == '' {
140+ continue
141+ }
142+ candidate := '${entry.trim_right('/')}/${name}'
143+ if _ := os.lstat(candidate) {
144+ return candidate
145+ }
146+ }
147+ return none
148+}
149+
150+// lrealpath is pacman's: the directory a path names its file in is resolved
151+// (links, '.' and '..'), and the file itself is kept as named, so a link
152+// stays the link. a path ending in '.' or '..' names a directory, which is
153+// resolved whole. none when the directory does not resolve
154+fn lrealpath(path string) ?string {
155+ base := path.all_after_last('/')
156+ if base in ['.', '..'] {
157+ return realpath(path)
158+ }
159+ slash := path.last_index('/') or { -1 }
160+ dname := match slash {
161+ -1 { '.' }
162+ 0 { '/' }
163+ else { path[..slash] }
164+ }
165+ resolved := realpath(dname)?
166+ return if resolved.ends_with('/') { resolved + base } else { '${resolved}/${base}' }
167+}
168+
169+// realpath is realpath(3), none when it fails: os.real_path hands back its
170+// input on failure, which here must tell a resolved path from an unresolved
171+fn realpath(path string) ?string {
172+ res := C.realpath(&char(path.str), unsafe { nil })
173+ if res == unsafe { nil } {
174+ return none
175+ }
176+ out := unsafe { cstring_to_vstring(res) }
177+ unsafe { C.free(res) }
178+ return out
179+}
180+
181+fn owner(config ConfigOwner) ! {
182+ need_query(config.query, 'file')!
183+ mut handle := alpm.initialize(root_path, db_path) or { return err }
184+ defer { handle.release() or { went_on('release the alpm handle', err) } }
185+
186+ mut pkgcache := local_pkgcache(handle)!
187+
188+ installed := pkgcache.pkgs()
189+ for target in config.query {
190+ q := owner_query(target) or {
191+ target_error(err.msg())
192+ continue
193+ }
194+ path := '${root_path}${q.rel}'
195+ owners := file_owners(installed, q)
196+ if owners.len == 0 {
197+ target_error('no package owns ${path}')
198+ continue
199+ }
200+ // a directory's owners are one event each, the path repeated
201+ if ipc_on() {
202+ for pkg in owners {
203+ emit(OwnerEvent{
204+ path: path
205+ package: pkg.get_name()
206+ version: pkg.get_version()
207+ })
208+ }
209+ continue
210+ }
211+ // pacman's -Qqo: the owners' names alone
212+ if config.quiet {
213+ for pkg in owners {
214+ println(pkg.get_name())
215+ }
216+ continue
217+ }
218+ println(table_text(owners.map(row(name_style(path), name_style(it.get_name()),
219+ version_style(it.get_version()))), '', ' '))
220+ }
221+}
@@ -0,0 +1,231 @@
1+module main
2+
3+import alpm
4+import os
5+import testdb
6+
7+// OwnerFixture is a small filespace laid out the way a merged-/usr system
8+// lays one out, with the links pacman's owner query has to see through or
9+// keep: bin is a link to usr/bin, usr/bin/alias a link to a file beside it
10+struct OwnerFixture {
11+ tmp string
12+ real string // tmp with its own links resolved: what canonical paths start with
13+}
14+
15+fn owner_fixture(name string) !OwnerFixture {
16+ tmp := os.join_path(os.vtmp_dir(), 'vpac_test_files_${name}_${os.getpid()}')
17+ os.rmdir_all(tmp) or {}
18+ for d in ['usr/bin', 'usr/share/doc', 'etc', 'nopath'] {
19+ os.mkdir_all(os.join_path(tmp, d))!
20+ }
21+ os.write_file(os.join_path(tmp, 'usr/bin/tool'), '#!/bin/sh\n')!
22+ os.chmod(os.join_path(tmp, 'usr/bin/tool'), 0o755)!
23+ // pacman's PATH search takes any name that exists, executable or not
24+ os.write_file(os.join_path(tmp, 'usr/bin/plain'), '')!
25+ os.write_file(os.join_path(tmp, 'etc/fstab'), '')!
26+ os.symlink('usr/bin', os.join_path(tmp, 'bin'))!
27+ os.symlink('tool', os.join_path(tmp, 'usr/bin/alias'))!
28+ os.symlink('nowhere', os.join_path(tmp, 'dangling'))!
29+ return OwnerFixture{
30+ tmp: tmp
31+ real: os.real_path(tmp)
32+ }
33+}
34+
35+// in_fixture runs f with the root at the fixture, the working directory in
36+// it and PATH set; the globals and the process state are put back after
37+fn in_fixture(fx OwnerFixture, cwd string, path string, f fn () !) ! {
38+ old_root := root_path
39+ old_path := os.getenv('PATH')
40+ old_cwd := os.getwd()
41+ defer {
42+ root_path = old_root
43+ os.setenv('PATH', old_path, true)
44+ os.chdir(old_cwd) or {}
45+ }
46+ root_path = fx.real + '/'
47+ os.setenv('PATH', path, true)
48+ os.chdir(os.join_path(fx.tmp, cwd))!
49+ f()!
50+}
51+
52+fn oq(target string) !OwnerQuery {
53+ return owner_query(target)!
54+}
55+
56+fn test_owner_query_resolves_the_directory_not_the_name() ! {
57+ fx := owner_fixture('resolve')!
58+ defer { os.rmdir_all(fx.tmp) or {} }
59+ in_fixture(fx, '', '/nonexistent', fn [fx] () ! {
60+ // a merged-/usr link in the directory part is seen through: pacman
61+ // answers /bin/ls as /usr/bin/ls
62+ assert oq('${fx.tmp}/bin/tool')! == OwnerQuery{'usr/bin/tool', false}
63+ // '..' and '.' in the directory part are resolved too
64+ assert oq('${fx.tmp}/usr/../usr/bin/tool')! == OwnerQuery{'usr/bin/tool', false}
65+ assert oq('${fx.tmp}/usr/./bin/tool')! == OwnerQuery{'usr/bin/tool', false}
66+ // the name itself stays the link: a filelist lists the link, and its
67+ // owner is the answer, not the target's
68+ assert oq('${fx.tmp}/usr/bin/alias')! == OwnerQuery{'usr/bin/alias', false}
69+ assert oq('./usr/bin/alias')! == OwnerQuery{'usr/bin/alias', false}
70+ assert oq('${fx.tmp}/bin/alias')! == OwnerQuery{'usr/bin/alias', false}
71+ // a dangling link exists as itself
72+ assert oq('dangling')! == OwnerQuery{'dangling', false}
73+ // a relative path, through a link
74+ assert oq('bin/tool')! == OwnerQuery{'usr/bin/tool', false}
75+ })!
76+}
77+
78+fn test_owner_query_directories() ! {
79+ fx := owner_fixture('dirs')!
80+ defer { os.rmdir_all(fx.tmp) or {} }
81+ in_fixture(fx, '', '/nonexistent', fn [fx] () ! {
82+ // a directory is asked for with its trailing slash, as filelists
83+ // spell one, given with slashes or not
84+ assert oq('${fx.tmp}/usr/share/doc')! == OwnerQuery{'usr/share/doc/', true}
85+ assert oq('${fx.tmp}/usr/share/doc///')! == OwnerQuery{'usr/share/doc/', true}
86+ // a link to a directory is the link, even with a slash after it: the
87+ // slash is dropped so lstat does not follow it, and what is there,
88+ // a link, says it is no directory
89+ assert oq('${fx.tmp}/bin')! == OwnerQuery{'bin', false}
90+ assert oq('${fx.tmp}/bin/')! == OwnerQuery{'bin', false}
91+ // a missing path is a directory by its slash alone
92+ assert oq('${fx.tmp}/usr/share/gone/')! == OwnerQuery{'usr/share/gone/', true}
93+ assert oq('${fx.tmp}/usr/share/gone')! == OwnerQuery{'usr/share/gone', false}
94+ // a path ending in '.' or '..' is resolved whole
95+ os.chdir(os.join_path(fx.tmp, 'usr/bin'))!
96+ assert oq('.')! == OwnerQuery{'usr/bin/', true}
97+ assert oq('..')! == OwnerQuery{'usr/', true}
98+ assert oq('../bin/..')! == OwnerQuery{'usr/', true}
99+ })!
100+}
101+
102+fn test_owner_query_bare_names() ! {
103+ fx := owner_fixture('names')!
104+ defer { os.rmdir_all(fx.tmp) or {} }
105+ in_fixture(fx, 'etc', '/nonexistent::${fx.tmp}/bin/', fn [fx] () ! {
106+ // a name the working directory holds is that file, not a command
107+ assert oq('fstab')! == OwnerQuery{'etc/fstab', false}
108+ // a name it lacks is looked up in PATH, empty entries and trailing
109+ // slashes and all; the PATH entry's link is seen through
110+ assert oq('tool')! == OwnerQuery{'usr/bin/tool', false}
111+ // a PATH hit need not be executable, and a link found there stays
112+ // the link
113+ assert oq('plain')! == OwnerQuery{'usr/bin/plain', false}
114+ assert oq('alias')! == OwnerQuery{'usr/bin/alias', false}
115+ // a name found nowhere is the working directory's missing file, as
116+ // in pacman, so a deleted file still finds the package that listed it
117+ assert oq('nosuch')! == OwnerQuery{'etc/nosuch', false}
118+ })!
119+ in_fixture(fx, 'nopath', '', fn [fx] () ! {
120+ // no PATH at all: the name stays in the working directory
121+ assert oq('tool')! == OwnerQuery{'nopath/tool', false}
122+ })!
123+}
124+
125+fn test_owner_query_unresolvable_directory() ! {
126+ fx := owner_fixture('missing')!
127+ defer { os.rmdir_all(fx.tmp) or {} }
128+ in_fixture(fx, '', '/nonexistent', fn [fx] () ! {
129+ // a directory that does not exist cannot be resolved: the path is
130+ // made absolute as named, so it still answers inside the root
131+ assert oq('${fx.tmp}/gone/dir/file')! == OwnerQuery{'gone/dir/file', false}
132+ assert oq('gone/dir/file')! == OwnerQuery{'gone/dir/file', false}
133+ assert oq('gone/../usr/bin/tool')! == OwnerQuery{'usr/bin/tool', false}
134+ })!
135+}
136+
137+fn test_owner_query_root_and_outside() ! {
138+ old := root_path
139+ defer { root_path = old }
140+
141+ root_path = '/'
142+ // the root itself: no package lists it, but it is not outside the root
143+ assert owner_query('/')!.rel == ''
144+ assert owner_query('///')!.rel == ''
145+
146+ fx := owner_fixture('root')!
147+ defer { os.rmdir_all(fx.tmp) or {} }
148+ root_path = fx.real + '/'
149+ assert owner_query(fx.real)!.rel == ''
150+ assert owner_query(fx.real + '/')!.rel == ''
151+ // a fake root that does not exist (yet) is still the root itself
152+ root_path = '/vpac-no-such-root-${os.getpid()}/sys/'
153+ assert owner_query(root_path)!.rel == ''
154+ assert owner_query(root_path.trim_right('/'))!.rel == ''
155+ for outside in ['/vpac-no-such-root-${os.getpid()}/sysfoo', '/etc', '/'] {
156+ if got := owner_query(outside) {
157+ assert false, '${outside} is outside ${root_path}, yet gave "${got.rel}"'
158+ } else {
159+ assert err.msg().starts_with('file is outside of root')
160+ }
161+ }
162+
163+ if _ := owner_query('') {
164+ assert false, 'an empty path has no owner query'
165+ }
166+}
167+
168+fn test_lrealpath() ! {
169+ fx := owner_fixture('lrealpath')!
170+ defer { os.rmdir_all(fx.tmp) or {} }
171+ assert lrealpath('${fx.tmp}/bin/alias')? == '${fx.real}/usr/bin/alias'
172+ // '..' after a link climbs from the link's target, as the kernel does:
173+ // bin is usr/bin, so bin/.. is usr, not the fixture's top
174+ assert lrealpath('${fx.tmp}/bin/..')? == '${fx.real}/usr'
175+ assert lrealpath('/')? == '/'
176+ assert lrealpath('/usr')? == '/usr'
177+ if got := lrealpath('${fx.tmp}/gone/file') {
178+ assert false, 'an unresolvable directory gave ${got}'
179+ }
180+ assert realpath(fx.tmp + '/bin')? == fx.real + '/usr/bin'
181+ if got := realpath(fx.tmp + '/dangling') {
182+ assert false, 'a dangling link resolved to ${got}'
183+ }
184+}
185+
186+// write_owner_db lays out a local db whose packages own files
187+fn write_owner_db(dbpath string, pkgs map[string][]string) ! {
188+ mut out := []testdb.Pkg{}
189+ for name, files in pkgs {
190+ out << testdb.Pkg{
191+ name: name
192+ files: files
193+ }
194+ }
195+ testdb.write_local(dbpath, out)!
196+}
197+
198+fn test_file_owners() ! {
199+ tmp := os.join_path(os.vtmp_dir(), 'vpac_test_files_owners_${os.getpid()}')
200+ os.mkdir_all(os.join_path(tmp, 'root'))!
201+ defer { os.rmdir_all(tmp) or {} }
202+ write_owner_db(os.join_path(tmp, 'db'), {
203+ 'filesystem': ['bin', 'usr/', 'usr/bin/', 'usr/share/']
204+ 'coreutils': ['usr/', 'usr/bin/', 'usr/bin/ls', 'usr/share/', 'usr/share/man/']
205+ 'zsh': ['usr/', 'usr/bin/', 'usr/bin/zsh', 'usr/share/', 'usr/share/man/']
206+ })!
207+ handle := alpm.initialize(os.join_path(tmp, 'root') + '/', os.join_path(tmp, 'db') + '/')!
208+ defer { handle.release() or {} }
209+ mut localdb := handle.get_localdb()!
210+ mut pkgcache := localdb.get_pkgcache() or { return error('the test db has no pkgcache') }
211+ pkgs := pkgcache.pkgs()
212+ owners := fn [pkgs] (rel string, dir bool) []string {
213+ mut names := file_owners(pkgs, OwnerQuery{rel, dir}).map(it.get_name())
214+ names.sort()
215+ return names
216+ }
217+
218+ // a file has its one owner
219+ assert owners('usr/bin/ls', false) == ['coreutils']
220+ // a directory answers every package that lists it
221+ assert owners('usr/share/man/', true) == ['coreutils', 'zsh']
222+ assert owners('usr/bin/', true) == ['coreutils', 'filesystem', 'zsh']
223+ // the match is exact: a directory is not found without its slash, a file
224+ // not with one, and a link is owned as itself
225+ assert owners('usr/bin', false) == []
226+ assert owners('usr/bin/ls/', true) == []
227+ assert owners('bin', false) == ['filesystem']
228+ assert owners('usr/bin/nope', false) == []
229+ // the root itself is listed by nobody
230+ assert owners('', true) == []
231+}
@@ -0,0 +1,48 @@
1+module main
2+
3+import alpm
4+
5+// filter_sync_dbs loads the sync dbs when a filter compares the installed
6+// packages with them. the other filters need no sync data
7+fn filter_sync_dbs(mut ui TransUI, mut handle &alpm.Handle, config ConfigSearch) ![]&alpm.DB {
8+ if !(config.foreign || config.native || config.upgrades) {
9+ return []&alpm.DB{}
10+ }
11+ dbs := init_repos(mut handle)!
12+ check_sync_fresh(mut ui, mut handle)!
13+ return dbs
14+}
15+
16+// pkg_matches_filter is true when an installed package passes every filter
17+// given, the way pacman's -Q filters combine
18+fn pkg_matches_filter(pkg &alpm.Package, config ConfigSearch, sync_dbs []&alpm.DB) bool {
19+ reason := pkg.get_reason()
20+ if config.deps && reason != .depend {
21+ return false
22+ }
23+ if config.explicit && reason != .explicit {
24+ return false
25+ }
26+ // pacman's -Qt: required by nothing, and optional for nothing either;
27+ // twice (-Qtt) what is only optionally required passes too
28+ if config.unrequired && (pkg.compute_required_by().len > 0
29+ || (config.unrequired_level < 2 && pkg.compute_optional_for().len > 0)) {
30+ return false
31+ }
32+ if config.foreign || config.native || config.upgrades {
33+ sync_pkg := find_repo_pkg(sync_dbs, pkg.get_name())
34+ if config.foreign && sync_pkg != none {
35+ return false
36+ }
37+ if config.native && sync_pkg == none {
38+ return false
39+ }
40+ if config.upgrades {
41+ newer := sync_pkg or { return false }
42+ if alpm.pkg_vercmp(pkg.get_version(), newer.get_version()) >= 0 {
43+ return false
44+ }
45+ }
46+ }
47+ return true
48+}
@@ -0,0 +1,476 @@
1+module main
2+
3+import alpm
4+
5+#include <regex.h>
6+
7+@[typedef]
8+struct C.regex_t {}
9+
10+fn C.regcomp(preg &C.regex_t, pattern &char, cflags int) int
11+
12+fn C.regexec(preg &C.regex_t, text &char, nmatch uint, pmatch voidptr, eflags int) int
13+
14+fn C.regfree(preg &C.regex_t)
15+
16+// FilePattern is one -x target, compiled as pacman's files_search compiles
17+// it: a posix extended expression, case ignored. a target with a slash is
18+// matched against whole paths, one without against file names alone
19+struct FilePattern {
20+ re &C.regex_t
21+ whole bool
22+}
23+
24+// find_rel is a target as the filelists spell paths, with no leading slash.
25+// as in pacman's files_search the slashes go while more than one byte is
26+// left, so a target of slashes alone stays '/' instead of becoming the empty
27+// expression that matches everything
28+fn find_rel(target string) string {
29+ mut rel := target
30+ for rel.len > 1 && rel[0] == `/` {
31+ rel = rel[1..]
32+ }
33+ return rel
34+}
35+
36+fn file_pattern(target string) !FilePattern {
37+ whole := target.contains('/')
38+ text := if whole { find_rel(target) } else { target }
39+ re := &C.regex_t{}
40+ if C.regcomp(re, &char(text.str), C.REG_EXTENDED | C.REG_NOSUB | C.REG_ICASE | C.REG_NEWLINE) != 0 {
41+ return error("invalid regular expression '${target}'")
42+ }
43+ return FilePattern{
44+ re: re
45+ whole: whole
46+ }
47+}
48+
49+// matches is whether a filelist entry answers the pattern. a file name is
50+// what follows the last slash: a directory has none, and is no match
51+fn (p FilePattern) matches(file string) bool {
52+ text := if p.whole { file } else { file.all_after_last('/') }
53+ if text == '' || (!p.whole && !file.contains('/')) {
54+ return false
55+ }
56+ return C.regexec(p.re, &char(text.str), 0, unsafe { nil }, 0) == 0
57+}
58+
59+// find is pacman's -F: the sync file databases, one .files file per repo.
60+// a path asks which repo package provides it, -l lists the files of a sync
61+// package, and -y refreshes the file dbs. the file dbs are the sync dbs read
62+// with a .files extension, so they live in their own handle. -r narrows the
63+// repos searched, while -y still refreshes all of them
64+fn find(config ConfigFind) ! {
65+ need_query(config.query, 'a file path, or a package name with -l')!
66+
67+ mut ui := new_trans_ui(noconfirm: config.noconfirm)
68+ mut handle := find_handle(mut ui, config.refresh)!
69+ defer { handle.release() or { went_on('release the alpm handle', err) } }
70+ defer { ui.stop() }
71+
72+ dbs := init_repos(mut handle)!
73+ mut filter := []string{}
74+ if config.repos != '' {
75+ filter = config.repos.split(',').map(it.trim_space()).filter(it != '')
76+ known := dbs.map(it.get_name())
77+ for name in filter {
78+ if name !in known {
79+ return error('not a sync repo: ${name} (these are: ${known.join(', ')})')
80+ }
81+ }
82+ }
83+
84+ if config.refresh {
85+ check_ask_db_lock(mut ui)
86+ mut s := ui.spinner(text: 'refreshing file databases')
87+ s.start()
88+ defer { stop_spinner(mut s) }
89+ // "up to date" is libalpm saying nothing needed fetching: success
90+ handle.db_update(handle.get_syncdbs()!, false) or {
91+ return error('could not refresh the file databases: ${err.msg()}')
92+ }
93+ stop_spinner(mut s)
94+ }
95+
96+ if config.list {
97+ find_list(mut ui, dbs, filter, config)!
98+ return
99+ }
100+ find_owner(mut ui, dbs, filter, config)!
101+}
102+
103+// find_handle opens the handle the file dbs are read through, with their
104+// .files extension. a refresh downloads, as root: it takes the full handle,
105+// so the download runs as the sandbox user with the configured keyring,
106+// timeout and progress, as pacman -Fy's does. reading needs none of that,
107+// and keeps the lean handle of the read-only modes
108+fn find_handle(mut ui TransUI, refresh bool) !&alpm.Handle {
109+ handle := if refresh {
110+ init_handle(ui)!
111+ } else {
112+ alpm.initialize(root_path, db_path) or { return err }
113+ }
114+ handle.option_set_dbext('.files') or {
115+ handle.release() or { went_on('release the alpm handle', err) }
116+ return err
117+ }
118+ return handle
119+}
120+
121+// FileCache is one file db loaded: the db, for its name, and its package cache
122+struct FileCache {
123+ db &alpm.DB
124+ cache &alpm.List
125+}
126+
127+// find_caches loads the file db package caches the named repos ask for, with
128+// a name in the error, because a missing .files file is the one thing a first
129+// run trips over. an empty filter loads them all
130+fn find_caches(dbs []&alpm.DB, filter []string) ![]FileCache {
131+ mut out := []FileCache{}
132+ for db in dbs {
133+ if filter.len > 0 && db.get_name() !in filter {
134+ continue
135+ }
136+ // a db with no packages is an empty one, not a broken one
137+ cache := pkgcache_of(db.get_handle(), db) or {
138+ return error('the file database of ${db.get_name()} is missing or broken (${err.msg()}): refresh it with vpac f -y')
139+ }
140+ out << FileCache{
141+ db: db
142+ cache: cache
143+ }
144+ }
145+ return out
146+}
147+
148+// OwnerRef is one claim in the inverted file index: the repo whose file db
149+// listed the package, and the package by its place in the pkgs list the
150+// index walks (the list of packages itself is kept beside the index, so no
151+// pointer-bearing struct has to live in the map's cells)
152+struct OwnerRef {
153+ repo string
154+ pkg_i int
155+}
156+
157+// owner_index is the inverted file index of the caches: every file and
158+// directory the file dbs hold, naming the packages that carry them. each
159+// query path would otherwise walk every package and its C-side filelist
160+// once, which is what makes an owner search over a full file db crawl
161+// (alpm_filelist_contains is a scan per path). the keys carry no trailing
162+// slash — a directory entry and a file land under the same key — and the
163+// entries are ordered as the dbs and their packages come, the same order
164+// the walk reports them in
165+fn owner_index(caches []FileCache) OwnerIndex {
166+ mut index := OwnerIndex{}
167+ for fc in caches {
168+ for pkg in fc.cache.pkgs() {
169+ pkg_i := index.pkgs.len
170+ index.pkgs << pkg
171+ for name in pkg.get_files().names() {
172+ key := name.trim_right('/')
173+ if key == '' {
174+ continue
175+ }
176+ index.refs[key] << OwnerRef{
177+ repo: fc.db.get_name()
178+ pkg_i: pkg_i
179+ }
180+ }
181+ }
182+ }
183+ return index
184+}
185+
186+// OwnerIndex is owner_index's answer, one value: a multi-path search takes it
187+// as it is built, where two variables filled after the fact would each be a
188+// copy of an index as large as every filelist of the dbs
189+struct OwnerIndex {
190+mut:
191+ refs map[string][]OwnerRef
192+ pkgs []&alpm.Package
193+}
194+
195+// owner_matches answers whether a file db entry provides the path. directories
196+// in a filelist carry a trailing slash, so the query, given without its own,
197+// is tried both ways
198+fn owner_matches(pkg &alpm.Package, rel string) bool {
199+ return pkg.get_files().contains(rel) != none
200+ || pkg.get_files().contains(rel + '/') != none
201+}
202+
203+// OwnerHit is one path's matches, kept so the results print only after the
204+// spinner stops. files are the paths that matched in each package: the path
205+// asked for, or every file an expression or a bare file name found — listed
206+// is set for those two, whose answer is the files and not only the packages
207+struct OwnerHit {
208+ path string
209+ listed bool
210+mut:
211+ repos []string
212+ pkgs []&alpm.Package
213+ files [][]string
214+}
215+
216+// machine_line is pacman's --machinereadable line: repo, package, version
217+// and path, parted by NUL bytes
218+fn machine_line(repo string, pkg &alpm.Package, file string) string {
219+ return [repo, pkg.get_name(), pkg.get_version(), file].join('\0')
220+}
221+
222+// find_owner answers which repo package provides a path, pacman's -Fo. the
223+// paths are relative to root, with or without the leading slash, and every
224+// path given is searched
225+fn find_owner(mut ui TransUI, dbs []&alpm.DB, filter []string, config ConfigFind) ! {
226+ // -x: every expression compiles before anything is searched, and a bad
227+ // one stops the run once all of them are named, as in pacman
228+ mut patterns := []FilePattern{}
229+ defer {
230+ for p in patterns {
231+ C.regfree(p.re)
232+ }
233+ }
234+ if config.regex {
235+ mut bad := 0
236+ for target in config.query {
237+ patterns << file_pattern(target) or {
238+ target_error(err.msg())
239+ bad++
240+ continue
241+ }
242+ }
243+ if bad > 0 {
244+ return
245+ }
246+ }
247+ mut s := ui.spinner(text: 'searching file databases')
248+ // quiet pipes its results: no spinner to glue a finished line onto them
249+ spun := !config.quiet && !config.machinereadable
250+ if spun {
251+ s.start()
252+ }
253+ defer { stop_spinner(mut s) }
254+
255+ caches := find_caches(dbs, filter)!
256+ // many paths or one: building the index costs about one walk of every
257+ // filelist, so a single-path search keeps its own walk, and a multi-path
258+ // one pays once and does every later path by lookup. an expression is
259+ // no key to look up: it walks
260+ index := if config.query.len > 1 && !config.regex {
261+ owner_index(caches)
262+ } else {
263+ OwnerIndex{}
264+ }
265+ mut hits := []OwnerHit{}
266+ for qi, path in config.query {
267+ // a target with no slash is a file name, looked for in every
268+ // directory, as pacman's files_search does without -x too
269+ by_name := !path.contains('/')
270+ mut hit := OwnerHit{
271+ path: path
272+ listed: config.regex || by_name
273+ }
274+ // the keys of the index and the entries of a filelist are matched
275+ // without the query's trailing slash, the same in both branches below
276+ rel := find_rel(path).trim_right('/')
277+ if hit.listed {
278+ for fc in caches {
279+ for pkg in fc.cache.pkgs() {
280+ names := pkg.get_files().names()
281+ matched := if config.regex {
282+ names.filter(patterns[qi].matches(it))
283+ } else {
284+ // a directory entry ends in its slash and has no
285+ // file name; an entry with no slash has no directory
286+ names.filter(it.contains('/') && it.all_after_last('/') == path)
287+ }
288+ if matched.len > 0 {
289+ hit.repos << fc.db.get_name()
290+ hit.pkgs << pkg
291+ hit.files << matched
292+ }
293+ }
294+ }
295+ hits << hit
296+ continue
297+ }
298+ if rel == '' {
299+ // reported with the misses, once the spinner is gone
300+ hits << hit
301+ continue
302+ }
303+ if config.query.len > 1 {
304+ // alpm's own lookup matches the file and every directory on
305+ // the way to it, which is what pacman's -Fo does; the index
306+ // answers in the same order the walk would
307+ for ref in index.refs[rel] {
308+ hit.repos << ref.repo
309+ hit.pkgs << index.pkgs[ref.pkg_i]
310+ hit.files << [rel]
311+ }
312+ } else {
313+ for fc in caches {
314+ for pkg in fc.cache.pkgs() {
315+ // alpm's own lookup matches the file and every directory
316+ // on the way to it, which is what pacman's -Fo does
317+ if owner_matches(pkg, rel) {
318+ hit.repos << fc.db.get_name()
319+ hit.pkgs << pkg
320+ hit.files << [rel]
321+ }
322+ }
323+ }
324+ }
325+ // a miss is kept too: it is reported in its place among the results
326+ hits << hit
327+ }
328+ if spun {
329+ end_frame(mut ui, mut s)
330+ }
331+
332+ for hit in hits {
333+ if hit.pkgs.len == 0 {
334+ if hit.path.trim_left('/') == '' && !hit.listed {
335+ target_error('a file path is needed, not "${hit.path}"')
336+ } else {
337+ target_error('no package provides ${hit.path}')
338+ }
339+ } else if ipc_on() {
340+ mut listing := Listing{
341+ fields: ['source', 'name', 'version', 'description']
342+ }
343+ for i, pkg in hit.pkgs {
344+ listing.add_pkg(pkg, hit.repos[i])
345+ }
346+ emit(ProvidesEvent{
347+ path: hit.path
348+ fields: listing.fields
349+ entries: listing.entries
350+ files: if hit.listed { hit.files } else { [][]string{} }
351+ })
352+ } else if config.machinereadable {
353+ // one line a matched path, for a program to split
354+ for i, pkg in hit.pkgs {
355+ for file in hit.files[i] {
356+ println(machine_line(hit.repos[i], pkg, file))
357+ }
358+ }
359+ } else if config.quiet {
360+ for i, pkg in hit.pkgs {
361+ // pacman's -Fq prints repo/pkg, which is what tells packages
362+ // that share a name apart
363+ println('${hit.repos[i]}/${pkg.get_name()}')
364+ }
365+ } else if hit.listed {
366+ // an expression or a file name finds many files: each is listed
367+ // with its package
368+ if config.query.len > 1 {
369+ println(heading(hit.path))
370+ }
371+ mut rows := []Row{}
372+ for i, pkg in hit.pkgs {
373+ for file in hit.files[i] {
374+ rows << row(file, source_style(hit.repos[i]), name_style(pkg.get_name()),
375+ version_style(pkg.get_version()))
376+ }
377+ }
378+ println(table_text(rows, '', ' '))
379+ } else {
380+ if config.query.len > 1 {
381+ println(heading(hit.path))
382+ }
383+ mut listing := Listing{
384+ fields: ['source', 'name', 'version', 'description']
385+ }
386+ for i, pkg in hit.pkgs {
387+ listing.add_pkg(pkg, hit.repos[i])
388+ }
389+ listing.print()
390+ }
391+ }
392+}
393+
394+// find_list lists the files of a sync package from the file dbs, pacman's -Fl
395+fn find_list(mut ui TransUI, dbs []&alpm.DB, filter []string, config ConfigFind) ! {
396+ mut s := ui.spinner(text: 'searching file databases')
397+ // quiet pipes its results: no spinner to glue a finished line onto them
398+ plain := config.quiet || config.machinereadable
399+ spun := !plain
400+ if spun {
401+ s.start()
402+ }
403+ defer { stop_spinner(mut s) }
404+
405+ caches := find_caches(dbs, filter)!
406+ mut lines := []string{}
407+ mut rows := []Row{}
408+ mut missing := []string{}
409+ for target in config.query {
410+ // a target may name its repo, repo/package, as pacman's -Fl takes it
411+ want_repo, name := if target.contains('/') {
412+ target.all_before('/'), target.all_after('/')
413+ } else {
414+ '', target
415+ }
416+ if name == '' {
417+ missing << target
418+ continue
419+ }
420+ // the package the caches hold, or the miss it is: pkg keeps the nil
421+ // answer as none instead of a sentinel &alpm.Package
422+ mut pkg := ?&alpm.Package(none)
423+ mut repo := ''
424+ for fc in caches {
425+ if want_repo != '' && fc.db.get_name() != want_repo {
426+ continue
427+ }
428+ if p := fc.cache.pkg_find(name) {
429+ pkg = ?&alpm.Package(p)
430+ repo = fc.db.get_name()
431+ break
432+ }
433+ }
434+ if p := pkg {
435+ // the miss is counted, the hit is listed; under ipc it leaves as
436+ // soon as it is collected, like find_owner's answers do
437+ if ipc_on() {
438+ emit(FilesEvent{
439+ package: p.get_name()
440+ repo: repo
441+ paths: p.get_files().names()
442+ })
443+ continue
444+ }
445+ for file in p.get_files().names() {
446+ // quiet is pacman's -Flq: the file paths alone, with no package
447+ // name, so a file two packages hold is listed twice; the form's
448+ // help says 'repo/pkg for paths, file paths for -l'
449+ if config.machinereadable {
450+ lines << machine_line(repo, p, file)
451+ } else if config.quiet {
452+ lines << file
453+ } else {
454+ // pacman's dump_file_list: the package, then the path
455+ rows << row(name_style(p.get_name()), file)
456+ }
457+ }
458+ } else {
459+ // no cache holds it: the miss is named once the listing is out
460+ missing << target
461+ }
462+ }
463+ if spun {
464+ end_frame(mut ui, mut s)
465+ }
466+ if plain && lines.len > 0 {
467+ println(lines.join('\n'))
468+ } else if !plain && rows.len > 0 {
469+ println(table_text(rows, ' ', ' '))
470+ }
471+ // the misses follow the listing: written while the spinner ran, they
472+ // would be drawn over
473+ for name in missing {
474+ target_error('"${name}" is not in the file databases: refresh them with vpac f -y')
475+ }
476+}
@@ -0,0 +1,261 @@
1+module main
2+
3+import alpm
4+import term
5+
6+enum PrintMode {
7+ default
8+ minimal
9+}
10+
11+// Listing is a package list as search and orphans collect it: the fields
12+// asked for, and one entry per package with its values as plain text. print
13+// is the terminal's rendering of it
14+struct Listing {
15+pub mut:
16+ mode PrintMode
17+ fields []string
18+ entries []ListEntry
19+}
20+
21+// ListEntry is one package of a listing: its name, and its value of every
22+// field of the listing, in their order. the quiet mode collects the name
23+// alone. group is the group a search -g member was listed for
24+struct ListEntry {
25+ name string
26+ values []string
27+ group string @[omitempty]
28+}
29+
30+fn shown(value string) string {
31+ return if value == '' { '-' } else { value }
32+}
33+
34+fn field_cell(field string, value string) Cell {
35+ text := shown(value)
36+ return match field {
37+ 'name' { cell(name_style(text)) }
38+ 'version' { cell(version_style(text)) }
39+ 'source' { cell(source_style(text)) }
40+ else { cell(text) }
41+ }
42+}
43+
44+fn (mut l Listing) add_pkg(pkg &alpm.Package, source string) {
45+ l.entries << ListEntry{
46+ name: pkg.get_name()
47+ values: if l.mode == .minimal {
48+ []string{}
49+ } else {
50+ l.fields.map(pkg_field(pkg, source, it))
51+ }
52+ }
53+}
54+
55+// add_member adds a member of a group, search -g's
56+fn (mut l Listing) add_member(pkg &alpm.Package, source string, group string) {
57+ l.add_pkg(pkg, source)
58+ last := l.entries.pop()
59+ l.entries << ListEntry{
60+ ...last
61+ group: group
62+ }
63+}
64+
65+fn (mut l Listing) add_pkgbuild(info PackagePkgbuild, source string) {
66+ l.entries << ListEntry{
67+ name: info.name
68+ values: if l.mode == .minimal {
69+ []string{}
70+ } else {
71+ l.fields.map(pkgbuild_field(info, it, source))
72+ }
73+ }
74+}
75+
76+// print renders the listing: the quiet mode one name a line, the default a
77+// table with every value styled by its field
78+fn (l Listing) print() {
79+ if ipc_on() {
80+ emit(ListingEvent{
81+ fields: if l.mode == .minimal { []string{} } else { l.fields }
82+ entries: l.entries
83+ })
84+ return
85+ }
86+ if l.mode == .minimal {
87+ for e in l.entries {
88+ println(e.name)
89+ }
90+ return
91+ }
92+ if l.entries.len > 0 {
93+ // a listing of group members leads each row with its group, as
94+ // pacman's -Sg does and as the ipc entries carry it
95+ grouped := l.entries.any(it.group != '')
96+ mut rows := []Row{}
97+ for e in l.entries {
98+ mut r := listing_row(l.fields, e)
99+ if grouped {
100+ r.cols.insert(0, cell(shown(e.group)))
101+ }
102+ rows << r
103+ }
104+ println(table_text(rows, '', ' '))
105+ }
106+}
107+
108+// print_found is the output of a listing whose collection failed part way:
109+// the quiet mode names what was found, the default prints nothing
110+fn (l Listing) print_found() {
111+ if l.mode == .minimal {
112+ l.print()
113+ }
114+}
115+
116+fn listing_row(fields []string, e ListEntry) Row {
117+ mut cols := []Cell{}
118+ // an entry always carries one value per field of its listing; a mismatch
119+ // shortens the row instead of tripping a bounds panic mid-render
120+ for i, f in fields {
121+ value := if i < e.values.len { e.values[i] } else { '' }
122+ cols << field_cell(f, value)
123+ }
124+ return Row{
125+ cols: cols
126+ }
127+}
128+
129+// reason_to_str is an install reason as a person reads it; reason_key is
130+// the same reason as a frontend reads it. every reason is named in both, no
131+// else: one libalpm adds fails the build here, rather than reading as
132+// 'unknown' in one spelling and something else in the other
133+pub fn reason_to_str(reason alpm.PackageReason) string {
134+ return match reason {
135+ .explicit { 'explicitly installed' }
136+ .depend { 'installed as a dependency' }
137+ .unknown { 'unknown' }
138+ }
139+}
140+
141+pub fn validation_to_str(validation alpm.PkgValidation) string {
142+ if validation == .unknown {
143+ return 'unknown'
144+ }
145+ if validation == .none {
146+ return 'none'
147+ }
148+ mut parts := []string{}
149+ if int(validation) & int(alpm.PkgValidation.md5sum) != 0 {
150+ parts << 'MD5 checksum'
151+ }
152+ if int(validation) & int(alpm.PkgValidation.sha256sum) != 0 {
153+ parts << 'SHA-256 checksum'
154+ }
155+ if int(validation) & int(alpm.PkgValidation.signature) != 0 {
156+ parts << 'signature'
157+ }
158+ return parts.join(', ')
159+}
160+
161+fn depends_text(deps &alpm.List) string {
162+ mut d := unsafe { deps }
163+ return d.depends().map(|dep| dep.compute_string()).join(', ')
164+}
165+
166+// InfoField is one field of a package as info collects it: the field's name,
167+// its value as one piece of text, and for the list fields the items that the
168+// terminal fills into lines
169+struct InfoField {
170+ field string
171+ value string
172+ items []string
173+}
174+
175+// wrap_items fills as many items into one line as the width allows, joining
176+// with ', '. the cells are measured the way the table prints them, so styled
177+// and wide text wrap right
178+fn wrap_items(items []string, avail int) []string {
179+ mut wide := avail
180+ if wide < 1 {
181+ wide = 1
182+ }
183+ mut out := []string{}
184+ mut line := ''
185+ for item in items {
186+ cand := if line == '' { item } else { '${line}, ${item}' }
187+ if line != '' && visible_width(cand) > wide {
188+ out << line
189+ line = item
190+ } else {
191+ line = cand
192+ }
193+ }
194+ if line != '' {
195+ out << line
196+ }
197+ return if out.len == 0 { [''] } else { out }
198+}
199+
200+// info_fields collects what info shows of a package: the fields asked for,
201+// in order. an empty one is left out unless the fields were named on the
202+// command line (explicit)
203+fn info_fields(pkg &alpm.Package, fields []string, explicit bool) []InfoField {
204+ source := pkg_source(pkg)
205+ mut out := []InfoField{}
206+ for f in fields {
207+ value := pkg_field(pkg, source, f)
208+ if value == '' && !explicit {
209+ continue
210+ }
211+ out << InfoField{
212+ field: f
213+ value: value
214+ items: pkg_field_items(pkg, f) or { []string{} }.filter(it != '')
215+ }
216+ }
217+ return out
218+}
219+
220+// the width info wraps to when the terminal tells none (output into a pipe
221+// or a file answers 0), and the narrowest a terminal may answer before its
222+// answer is taken for none: a column count that small is no real terminal
223+const info_fallback_cols = 80
224+const info_min_cols = 9
225+
226+// info_width is the width the info table wraps to for a terminal's columns
227+fn info_width(cols int) int {
228+ return if cols >= info_min_cols { cols } else { info_fallback_cols }
229+}
230+
231+// info_table renders a package's fields. the list fields fill as many items
232+// per line as the terminal lets them, opt depends give every line its own,
233+// and the continuation lines are padded from the start to the value column
234+fn info_table(fields []InfoField) string {
235+ if fields.len == 0 {
236+ // the fields list is empty: nothing to show
237+ return ''
238+ }
239+ cols, _ := term.get_terminal_size()
240+ width := info_width(cols)
241+ labels := fields.map(it.field.replace('_', ' '))
242+ mut label_w := 0
243+ for l in labels {
244+ if l.len > label_w {
245+ label_w = l.len
246+ }
247+ }
248+ pad := ' '.repeat(label_w + 2)
249+ avail := width - label_w - 2
250+ mut text := []string{}
251+ for i, f in fields {
252+ lines := if f.field == 'optdepends' { f.items } else { wrap_items(f.items, avail) }
253+ first := if f.items.len == 0 { f.value } else { lines[0] }
254+ text << '${heading(labels[i])}${' '.repeat(label_w - labels[i].len + 2)}${shown(first)}'
255+ // an empty optdepends has no lines at all: -F all shows it as '-'
256+ for line in lines#[1..] {
257+ text << '${pad}${line}'
258+ }
259+ }
260+ return text.join('\n')
261+}
@@ -0,0 +1,93 @@
1+module main
2+
3+fn test_listing_renders_plain_entries() {
4+ old := color_flag
5+ defer { color_flag = old }
6+ color_flag = 'never'
7+
8+ // the entries are plain values; the render styles them, and shows an
9+ // empty one as '-'
10+ l := Listing{
11+ fields: ['name', 'version', 'description']
12+ entries: [ListEntry{
13+ name: 'zsh'
14+ values: ['zsh', '5.9-1', '']
15+ }, ListEntry{
16+ name: 'bash'
17+ values: ['bash', '5.2-1', 'shell']
18+ }]
19+ }
20+ assert table_text(l.entries.map(listing_row(l.fields, it)), '', ' ') == 'zsh 5.9-1 -\nbash 5.2-1 shell'
21+}
22+
23+// a row built against another listing's fields is shortened, not tripped
24+// over: an entry always carries one value per field, but a mismatched one
25+// fills its tail with empties and renders as '-' instead of panicking
26+fn test_listing_row_survives_a_short_entry() {
27+ old := color_flag
28+ defer { color_flag = old }
29+ color_flag = 'never'
30+
31+ r := listing_row(['name', 'version', 'description'], ListEntry{
32+ name: 'zsh'
33+ values: ['zsh']
34+ })
35+ assert r.cols.len == 3
36+ assert table_text([r], '', ' ') == 'zsh - -'
37+}
38+
39+fn test_info_table() {
40+ old := color_flag
41+ defer { color_flag = old }
42+ color_flag = 'never'
43+
44+ assert info_table([]) == ''
45+ // -F all on a package without optional deps: an optdepends with no
46+ // items shows '-' and draws no continuation line
47+ assert info_table([InfoField{
48+ field: 'optdepends'
49+ }, InfoField{
50+ field: 'install_reason'
51+ value: 'explicitly installed'
52+ }]) == 'optdepends -\ninstall reason explicitly installed'
53+ // optdepends puts each item on its own line, padded to the value column
54+ assert info_table([InfoField{
55+ field: 'optdepends'
56+ value: 'a, b'
57+ items: ['a: x', 'b']
58+ }]) == 'optdepends a: x\n b'
59+}
60+
61+fn test_reason_spellings() ! {
62+ // every reason in both spellings, and the frontend's key is a word mark
63+ // reads back as that reason
64+ for reason, want in {
65+ alpm.PackageReason.explicit: ['explicit', 'explicitly installed']
66+ alpm.PackageReason.depend: ['depend', 'installed as a dependency']
67+ alpm.PackageReason.unknown: ['unknown', 'unknown']
68+ } {
69+ assert [reason_key(reason), reason_to_str(reason)] == want
70+ assert parse_reason(reason_key(reason))! == reason
71+ }
72+ for short, reason in {
73+ 'e': alpm.PackageReason.explicit
74+ 'dep': alpm.PackageReason.depend
75+ 'dependency': alpm.PackageReason.depend
76+ 'u': alpm.PackageReason.unknown
77+ } {
78+ assert parse_reason(short)! == reason
79+ }
80+ if _ := parse_reason('optional') {
81+ assert false, 'an unknown reason was read'
82+ }
83+}
84+
85+fn test_info_width() {
86+ // no terminal (a pipe answers 0), or a size no terminal has: the fallback
87+ assert info_width(0) == info_fallback_cols
88+ assert info_width(-1) == info_fallback_cols
89+ assert info_width(info_min_cols - 1) == info_fallback_cols
90+ // a terminal's own width, from the narrowest one taken on
91+ assert info_width(info_min_cols) == info_min_cols
92+ assert info_width(132) == 132
93+}
@@ -0,0 +1,2339 @@
1+module main
2+
3+import alpm
4+import crypto.sha256
5+import json2
6+import net.http
7+import net.urllib
8+import os
9+import testdb
10+import time
11+
12+#include <stdio_ext.h>
13+
14+fn C.__fpurge(stream &C.FILE)
15+
16+fn C.clearerr(stream &C.FILE)
17+
18+// the modes that commit a transaction, run whole under --ui ipc against a
19+// system that lives in a temp dir: a root, a local db, a sync repo served
20+// over file:// with real package archives, and a cache. libalpm does every
21+// step for real — download, validation, extraction, db writes — and the
22+// events the mode sends are read back line by line, as a frontend reads them
23+
24+// FakePkg is a package of the fake system: its files are paths under the
25+// root with their content
26+struct FakePkg {
27+ name string
28+ version string = '1.0-1'
29+ reason int // installed ones: 0 explicit, 1 a dependency
30+ depends []string
31+ provides []string
32+ groups []string
33+ desc string
34+ // changelog is the text the package carries as its changelog, if any
35+ changelog string
36+ files map[string]string
37+}
38+
39+// FakeSystem is the temp dir a run's whole system lives in
40+struct FakeSystem {
41+ tmp string
42+}
43+
44+fn fake_system(name string) !FakeSystem {
45+ tmp := os.join_path(os.vtmp_dir(), 'vpac_test_frontend_${name}_${os.getpid()}')
46+ os.rmdir_all(tmp) or {}
47+ // pkgbuild is the build dir the runs point pkgbuild_dir at: it is there,
48+ // empty, so a mode that lists the builds reads a dir and not an error
49+ for d in ['root', 'db/local', 'db/sync', 'cache', 'repo', 'gpg', 'build', 'dbsrc', 'pkgbuild'] {
50+ os.mkdir_all(os.join_path(tmp, d))!
51+ }
52+ os.write_file(os.join_path(tmp, 'db/local/ALPM_DB_VERSION'), '9\n')!
53+ return FakeSystem{
54+ tmp: tmp
55+ }
56+}
57+
58+fn (s FakeSystem) path(rel string) string {
59+ return os.join_path(s.tmp, rel)
60+}
61+
62+// file_list is a package's filelist the way libalpm keeps one: every
63+// directory on the way, with its slash, then the files, sorted
64+fn file_list(files map[string]string) []string {
65+ mut set := map[string]bool{}
66+ for f, _ in files {
67+ parts := f.split('/')
68+ for i in 1 .. parts.len {
69+ set[parts[..i].join('/') + '/'] = true
70+ }
71+ set[f] = true
72+ }
73+ mut out := set.keys()
74+ out.sort()
75+ return out
76+}
77+
78+// install_local puts p in the local db as installed, its files on the root
79+fn (s FakeSystem) install_local(p FakePkg) ! {
80+ // the db entry is the shared writer's; the changelog and the files on
81+ // the root are this fake system's own
82+ testdb.write_local(s.path('db'), [
83+ testdb.Pkg{
84+ name: p.name
85+ version: p.version
86+ reason: p.reason
87+ depends: p.depends
88+ provides: p.provides
89+ groups: p.groups
90+ files: file_list(p.files)
91+ },
92+ ])!
93+ if p.changelog != '' {
94+ os.write_file(s.path('db/local/${p.name}-${p.version}/changelog'), p.changelog)!
95+ }
96+ for f, content in p.files {
97+ os.mkdir_all(os.dir(s.path('root/${f}')))!
98+ os.write_file(s.path('root/${f}'), content)!
99+ }
100+}
101+
102+// publish builds an archive of each package into the repo, writes the repo's
103+// core.db naming them with their checksums, and puts that db in the sync dir
104+// fresh, so no mode asks to update it
105+fn (s FakeSystem) publish(pkgs []FakePkg) ! {
106+ for p in pkgs {
107+ src := s.path('build/${p.name}-${p.version}')
108+ os.mkdir_all(src)!
109+ mut info := 'pkgname = ${p.name}\npkgbase = ${p.name}\npkgver = ${p.version}\npkgdesc = ${p.name} for a test\narch = any\nsize = 0\n'
110+ for d in p.depends {
111+ info += 'depend = ${d}\n'
112+ }
113+ for v in p.provides {
114+ info += 'provides = ${v}\n'
115+ }
116+ for g in p.groups {
117+ info += 'group = ${g}\n'
118+ }
119+ if p.changelog != '' {
120+ os.write_file(os.join_path(src, '.CHANGELOG'), p.changelog)!
121+ }
122+ os.write_file(os.join_path(src, '.PKGINFO'), info)!
123+ for f, content in p.files {
124+ os.mkdir_all(os.dir(os.join_path(src, f)))!
125+ os.write_file(os.join_path(src, f), content)!
126+ }
127+ file := '${p.name}-${p.version}-any.pkg.tar'
128+ tar(s.path('repo/${file}'), src, os.ls(src)!)!
129+ text := if p.desc != '' { p.desc } else { '${p.name} for a test' }
130+ mut desc := '%FILENAME%\n${file}\n\n%NAME%\n${p.name}\n\n%VERSION%\n${p.version}\n\n%DESC%\n${text}\n\n'
131+ desc += '%CSIZE%\n${os.file_size(s.path('repo/${file}'))}\n\n%ISIZE%\n0\n\n'
132+ desc += '%SHA256SUM%\n${sha256.hexhash(os.read_file(s.path('repo/${file}'))!)}\n\n%ARCH%\nany\n\n'
133+ if p.depends.len > 0 {
134+ desc += '%DEPENDS%\n${p.depends.join('\n')}\n\n'
135+ }
136+ if p.provides.len > 0 {
137+ desc += '%PROVIDES%\n${p.provides.join('\n')}\n\n'
138+ }
139+ if p.groups.len > 0 {
140+ desc += '%GROUPS%\n${p.groups.join('\n')}\n\n'
141+ }
142+ os.mkdir_all(s.path('dbsrc/${p.name}-${p.version}'))!
143+ os.write_file(s.path('dbsrc/${p.name}-${p.version}/desc'), desc)!
144+ }
145+ tar(s.path('repo/core.db'), s.path('dbsrc'), os.ls(s.path('dbsrc'))!)!
146+ os.cp(s.path('repo/core.db'), s.path('db/sync/core.db'))!
147+ // the file db beside it, the way a repo serves one: each entry's desc and
148+ // its file list. it stays on the server until a find -y fetches it
149+ for p in pkgs {
150+ entry := s.path('filessrc/${p.name}-${p.version}')
151+ os.mkdir_all(entry)!
152+ os.cp(s.path('dbsrc/${p.name}-${p.version}/desc'), os.join_path(entry, 'desc'))!
153+ os.write_file(os.join_path(entry, 'files'), '%FILES%\n${file_list(p.files).join('\n')}\n\n')!
154+ }
155+ tar(s.path('repo/core.files'), s.path('filessrc'), os.ls(s.path('filessrc'))!)!
156+}
157+
158+fn tar(out string, dir string, entries []string) ! {
159+ mut args := ['tar', '-cf', out, '-C', dir]
160+ args << entries
161+ res := os.exec(args)
162+ if res.exit_code != 0 {
163+ return error('tar failed: ${res.output}')
164+ }
165+}
166+
167+// installed is the local db's name to version, read the way the next
168+// command would read it: a fresh handle
169+fn (s FakeSystem) installed() !map[string]string {
170+ handle := alpm.initialize(s.path('root') + '/', s.path('db') + '/')!
171+ defer { handle.release() or {} }
172+ // an empty db is no packages; one that cannot be read is an error, not
173+ // 'nothing installed' (pkgcache_of tells the two apart by libalpm's errno)
174+ mut cache := local_pkgcache(handle)!
175+ mut out := map[string]string{}
176+ for p in cache.pkgs() {
177+ out[p.get_name()] = p.get_version()
178+ }
179+ return out
180+}
181+
182+fn (s FakeSystem) reason_of(name string) !alpm.PackageReason {
183+ handle := alpm.initialize(s.path('root') + '/', s.path('db') + '/')!
184+ defer { handle.release() or {} }
185+ return (handle.find_local_pkg(name) or { return error('${name} is not installed') }).get_reason()
186+}
187+
188+// FrontendRun is what a mode sent on the channel, decoded, and the error it
189+// returned ('' when it returned none)
190+struct FrontendRun {
191+ events []map[string]json2.Any
192+ err string
193+ // stdout is what reached fd 1 itself, beside the channel
194+ stdout string
195+ // failed is how many targets this run reported bad, main's exit status
196+ // counting them
197+ failed int
198+}
199+
200+fn (r FrontendRun) of(kind string) []map[string]json2.Any {
201+ return r.events.filter(it['type'] or { json2.Any('') }.str() == kind)
202+}
203+
204+// done is the run's one done event; it fails when there is not exactly one
205+fn (r FrontendRun) done() !map[string]json2.Any {
206+ dones := r.of('done')
207+ if dones.len != 1 {
208+ return error('${dones.len} done events in ${r.events.map(it['type'] or { json2.Any('') }.str())}')
209+ }
210+ return dones[0]
211+}
212+
213+fn sorted_strs(v json2.Any) []string {
214+ mut out := v.as_array().map(it.str())
215+ out.sort()
216+ return out
217+}
218+
219+// run runs a mode on the system the way a frontend runs vpac: --ui ipc, the
220+// events on a channel (a file here), the answers on stdin. the config is
221+// aimed at the system — its root and dbs, its cache, its keyring dir, its
222+// repo over file:// — and put back at its defaults after, with the ui
223+fn (s FakeSystem) run(stdin string, mode fn () !) !FrontendRun {
224+ return s.run_ui('ipc', stdin, mode)
225+}
226+
227+// run_ui is run with the ui kind given: 'tty' runs the mode as a terminal
228+// sees it, with no channel, its output read back from fd 1
229+fn (s FakeSystem) run_ui(kind string, stdin string, mode fn () !) !FrontendRun {
230+ chan_path := s.path('channel')
231+ out_path := s.path('stdout')
232+ mut out_file := os.create(out_path)!
233+ saved_out := C.dup(1)
234+ if saved_out < 0 {
235+ return error('could not save stdout')
236+ }
237+ in_path := s.path('stdin')
238+ os.write_file(in_path, stdin)!
239+ mut chan_file := os.create(chan_path)!
240+ mut in_file := os.open(in_path)!
241+ saved_in := C.dup(0)
242+ if saved_in < 0 {
243+ return error('could not save stdin')
244+ }
245+ saved_kind, saved_color, saved_fd := ui_kind, color_flag, ipc_fd
246+ // a process-wide count, as main reads it at the end of its one run: each
247+ // run here starts from none, and puts the count back after
248+ saved_failed := failed_targets
249+ failed_targets = 0
250+ defer {
251+ failed_targets = saved_failed
252+ }
253+ reset_config()
254+ root_path = s.path('root') + '/'
255+ db_path = s.path('db') + '/'
256+ cfg_cachedirs = [s.path('cache') + '/']
257+ cfg_gpgdir = s.path('gpg') + '/'
258+ // the machine's own hooks stay out of a fake system's transactions
259+ cfg_hookdirs = []string{}
260+ // the sandbox user need not exist where the tests run
261+ download_user = ''
262+ // the pkgbuild builds are the system's own too: never the ones in the
263+ // home of whoever runs the tests, which a clean would otherwise look at
264+ pkgbuild_dir = s.path('pkgbuild')
265+ cfg_repos = [CfgRepo{
266+ name: 'core'
267+ kind: 'sync'
268+ servers: ['file://' + s.path('repo')]
269+ }]
270+ ui_kind = kind
271+ color_flag = 'never'
272+ ipc_fd = chan_file.fd
273+ C.__fpurge(C.stdin)
274+ C.clearerr(C.stdin)
275+ C.dup2(in_file.fd, 0)
276+ C.fflush(C.stdout)
277+ C.dup2(out_file.fd, 1)
278+
279+ mut msg := ''
280+ mode() or { msg = err.msg() }
281+
282+ C.fflush(C.stdout)
283+ C.dup2(saved_out, 1)
284+ C.close(saved_out)
285+ out_file.close()
286+ C.dup2(saved_in, 0)
287+ C.close(saved_in)
288+ C.__fpurge(C.stdin)
289+ C.clearerr(C.stdin)
290+ ui_kind, color_flag, ipc_fd = saved_kind, saved_color, saved_fd
291+ reset_config()
292+ in_file.close()
293+ chan_file.close()
294+ mut events := []map[string]json2.Any{}
295+ for line in os.read_lines(chan_path)! {
296+ // every line is one whole json object, or the channel is broken
297+ events << json2.decode[json2.Any](line)!.as_map()
298+ }
299+ return FrontendRun{
300+ events: events
301+ err: msg
302+ stdout: os.read_file(out_path)!
303+ failed: failed_targets
304+ }
305+}
306+
307+fn (s FakeSystem) lock_left() bool {
308+ return os.exists(s.path('db/db.lck'))
309+}
310+
311+fn foo(version string, content string) FakePkg {
312+ return FakePkg{
313+ name: 'foo'
314+ version: version
315+ files: {
316+ 'usr/share/foo/hello': content
317+ }
318+ }
319+}
320+
321+fn test_upgrade_ends_with_a_done_event() ! {
322+ s := fake_system('upgrade')!
323+ defer { os.rmdir_all(s.tmp) or {} }
324+ s.install_local(foo('1.0-1', 'one'))!
325+ s.publish([foo('2.0-1', 'two')])!
326+
327+ run := s.run('', fn () ! {
328+ upgrade(ConfigUpgrade{ noconfirm: true })!
329+ })!
330+ assert run.err == ''
331+ done := run.done()!
332+ assert done['action']!.str() == 'upgraded'
333+ assert sorted_strs(done['packages']!) == ['foo']
334+ // the listing and the go-ahead came first, the done last of them
335+ assert run.of('transaction').len == 1
336+ assert run.of('question').len == 1
337+ // and it happened: the new version is on the root and in the local db
338+ assert os.read_file(s.path('root/usr/share/foo/hello'))! == 'two'
339+ assert s.installed()! == {
340+ 'foo': '2.0-1'
341+ }
342+ assert !s.lock_left()
343+}
344+
345+fn test_upgrade_with_nothing_to_do_sends_no_done() ! {
346+ s := fake_system('uptodate')!
347+ defer { os.rmdir_all(s.tmp) or {} }
348+ s.install_local(foo('1.0-1', 'one'))!
349+ s.publish([foo('1.0-1', 'one')])!
350+ run := s.run('', fn () ! {
351+ upgrade(ConfigUpgrade{ noconfirm: true })!
352+ })!
353+ assert run.err == ''
354+ assert run.of('done').len == 0
355+ assert run.of('message').any(it['text']!.str() == 'nothing to upgrade.')
356+}
357+
358+fn test_install_ends_with_a_done_event() ! {
359+ s := fake_system('install')!
360+ defer { os.rmdir_all(s.tmp) or {} }
361+ s.publish([
362+ FakePkg{
363+ name: 'bar'
364+ depends: ['baz']
365+ files: {
366+ 'usr/bin/bar': 'bar'
367+ }
368+ },
369+ FakePkg{
370+ name: 'baz'
371+ files: {
372+ 'usr/lib/libbaz': 'baz'
373+ }
374+ },
375+ ])!
376+ run := s.run('', fn () ! {
377+ install(ConfigInstall{ noconfirm: true, query: ['bar'] })!
378+ })!
379+ assert run.err == ''
380+ done := run.done()!
381+ assert done['action']!.str() == 'installed'
382+ // the targets: the dependency comes along, but is not one
383+ assert sorted_strs(done['packages']!) == ['bar']
384+ assert s.installed()! == {
385+ 'bar': '1.0-1'
386+ 'baz': '1.0-1'
387+ }
388+ assert s.reason_of('bar')! == .explicit
389+ assert s.reason_of('baz')! == .depend
390+ assert os.read_file(s.path('root/usr/bin/bar'))! == 'bar'
391+ assert !s.lock_left()
392+}
393+
394+fn test_remove_ends_with_a_done_event() ! {
395+ s := fake_system('remove')!
396+ defer { os.rmdir_all(s.tmp) or {} }
397+ s.install_local(foo('1.0-1', 'one'))!
398+ run := s.run('', fn () ! {
399+ remove(ConfigRemove{ noconfirm: true, query: ['foo'] })!
400+ })!
401+ assert run.err == ''
402+ done := run.done()!
403+ assert done['action']!.str() == 'removed'
404+ assert sorted_strs(done['packages']!) == ['foo']
405+ assert s.installed()!.len == 0
406+ assert !os.exists(s.path('root/usr/share/foo/hello'))
407+ assert !s.lock_left()
408+}
409+
410+fn test_autoremove_ends_with_a_done_event() ! {
411+ s := fake_system('autoremove')!
412+ defer { os.rmdir_all(s.tmp) or {} }
413+ s.install_local(FakePkg{
414+ name: 'app'
415+ depends: ['lib']
416+ })!
417+ s.install_local(FakePkg{
418+ name: 'lib'
419+ reason: 1
420+ })!
421+ s.install_local(FakePkg{
422+ name: 'orphan'
423+ reason: 1
424+ })!
425+ // an orphan whose own dependency becomes unneeded with it: the recurse
426+ // takes it along, and the done event names it with the rest
427+ s.install_local(FakePkg{
428+ name: 'stray'
429+ reason: 1
430+ depends: ['leaf']
431+ })!
432+ s.install_local(FakePkg{
433+ name: 'leaf'
434+ reason: 1
435+ })!
436+ run := s.run('', fn () ! {
437+ autoremove(ConfigAutoRemove{ noconfirm: true })!
438+ })!
439+ assert run.err == ''
440+ done := run.done()!
441+ assert done['action']!.str() == 'removed'
442+ assert sorted_strs(done['packages']!) == ['leaf', 'orphan', 'stray']
443+ // the text line of a terminal is not sent beside it
444+ assert !run.of('message').any(it['text']!.str().contains('orphaned packages'))
445+ mut left := s.installed()!.keys()
446+ left.sort()
447+ assert left == ['app', 'lib']
448+ assert !s.lock_left()
449+}
450+
451+fn test_mark_ends_with_a_done_event() ! {
452+ s := fake_system('mark')!
453+ defer { os.rmdir_all(s.tmp) or {} }
454+ s.install_local(foo('1.0-1', 'one'))!
455+ run := s.run('', fn () ! {
456+ mark(ConfigMark{ reason: 'd', query: ['foo'] })!
457+ })!
458+ assert run.err == ''
459+ done := run.done()!
460+ assert done['action']!.str() == 'marked'
461+ assert done['reason']!.str() == 'depend'
462+ assert sorted_strs(done['packages']!) == ['foo']
463+ assert s.reason_of('foo')! == .depend
464+ assert !s.lock_left()
465+}
466+
467+fn test_declined_transaction_sends_no_done() ! {
468+ s := fake_system('decline')!
469+ defer { os.rmdir_all(s.tmp) or {} }
470+ s.install_local(foo('1.0-1', 'one'))!
471+ // the frontend says no to the go-ahead, question 1
472+ run := s.run('{"id": 1, "answer": false}\n', fn () ! {
473+ remove(ConfigRemove{ query: ['foo'] })!
474+ })!
475+ assert run.err == ''
476+ questions := run.of('question')
477+ assert questions.len == 1
478+ assert questions[0]['question']!.str() == 'proceed'
479+ assert run.of('done').len == 0
480+ // nothing changed, and the transaction let go of the lock
481+ assert s.installed()! == {
482+ 'foo': '1.0-1'
483+ }
484+ assert os.exists(s.path('root/usr/share/foo/hello'))
485+ assert !s.lock_left()
486+}
487+
488+fn test_print_preview_sends_no_done() ! {
489+ s := fake_system('preview')!
490+ defer { os.rmdir_all(s.tmp) or {} }
491+ s.install_local(foo('1.0-1', 'one'))!
492+ s.publish([foo('2.0-1', 'two')])!
493+ run := s.run('', fn () ! {
494+ upgrade(ConfigUpgrade{ print_only: true })!
495+ })!
496+ assert run.err == ''
497+ listing := run.of('transaction')
498+ assert listing.len == 1
499+ assert listing[0]['preview']!.bool()
500+ assert run.of('done').len == 0
501+ assert run.of('question').len == 0
502+ assert s.installed()! == {
503+ 'foo': '1.0-1'
504+ }
505+ assert !s.lock_left()
506+}
507+
508+fn test_prepare_failure_sends_no_done_and_lets_go_of_the_lock() ! {
509+ s := fake_system('prepare')!
510+ defer { os.rmdir_all(s.tmp) or {} }
511+ // a dependency no repo has: prepare fails, and says on what
512+ s.publish([FakePkg{
513+ name: 'needy'
514+ depends: ['nowhere']
515+ }])!
516+ run := s.run('', fn () ! {
517+ install(ConfigInstall{ noconfirm: true, query: ['needy'] })!
518+ })!
519+ assert run.err != ''
520+ assert run.err.contains('nowhere'), run.err
521+ assert run.of('done').len == 0
522+ assert s.installed()!.len == 0
523+ assert !s.lock_left()
524+}
525+
526+// an empty local db is a db with no packages, not a broken one: the modes
527+// that read it answer nothing found, as pacman does on a fresh root (the
528+// install above runs on one too)
529+fn test_an_empty_system_is_no_error() ! {
530+ s := fake_system('empty')!
531+ defer { os.rmdir_all(s.tmp) or {} }
532+ s.publish([foo('1.0-1', 'one')])!
533+ orphaned := s.run('', fn () ! {
534+ orphans(ConfigOrphans{})!
535+ })!
536+ assert orphaned.err == ''
537+ verified := s.run('', fn () ! {
538+ verify(ConfigVerify{})!
539+ })!
540+ assert verified.err == ''
541+ searched := s.run('', fn () ! {
542+ search(ConfigSearch{ local: true, query: ['foo'] })!
543+ })!
544+ assert searched.err == ''
545+ // a name to act on is unknown, said so, not a database failure: mark
546+ // and remove report it as the bad target it is
547+ marked := s.run('', fn () ! {
548+ mark(ConfigMark{ reason: 'd', query: ['foo'] })!
549+ })!
550+ assert marked.err == '' && marked.failed == 1
551+ assert marked.of('error')[0]['msg']!.str().contains('unknown package')
552+ assert !s.lock_left()
553+ removed := s.run('', fn () ! {
554+ remove(ConfigRemove{ noconfirm: true, query: ['foo'] })!
555+ })!
556+ assert removed.err == '' && removed.failed == 1
557+ assert removed.of('error')[0]['msg']!.str().contains('unknown package')
558+ assert !s.lock_left()
559+}
560+
561+fn test_pkgcache_of() ! {
562+ s := fake_system('pkgcache')!
563+ defer { os.rmdir_all(s.tmp) or {} }
564+ handle := alpm.initialize(s.path('root') + '/', s.path('db') + '/')!
565+ // empty: a nil list, which reads as no packages
566+ mut empty := local_pkgcache(handle)!
567+ assert empty == unsafe { nil }
568+ assert empty.pkgs().len == 0
569+ assert empty.pkg_find('foo') == none
570+ handle.release()!
571+
572+ s.install_local(foo('1.0-1', 'one'))!
573+ full_handle := alpm.initialize(s.path('root') + '/', s.path('db') + '/')!
574+ mut full := local_pkgcache(full_handle)!
575+ assert full.pkgs().map(it.get_name()) == ['foo']
576+ full_handle.release()!
577+
578+ if os.geteuid() == 0 {
579+ // root reads the unreadable dir below anyway
580+ return
581+ }
582+ // a db libalpm cannot read is still an error, with libalpm's reason. the
583+ // handle opens first: libalpm reads the packages only when asked
584+ broken := alpm.initialize(s.path('root') + '/', s.path('db') + '/')!
585+ defer { broken.release() or {} }
586+ os.chmod(s.path('db/local'), 0)!
587+ defer { os.chmod(s.path('db/local'), 0o755) or {} }
588+ if mut got := local_pkgcache(broken) {
589+ assert false, 'an unreadable local db read as ${got.pkgs().len} packages'
590+ } else {
591+ assert err.msg().starts_with('could not read the packages of local: '), err.msg()
592+ }
593+}
594+
595+fn test_url_install_through_the_install_handle() ! {
596+ s := fake_system('url')!
597+ defer { os.rmdir_all(s.tmp) or {} }
598+ s.publish([foo('1.0-1', 'one')])!
599+ url := 'file://' + s.path('repo/foo-1.0-1-any.pkg.tar')
600+ run := s.run('', fn [url] () ! {
601+ install(ConfigInstall{ noconfirm: true, query: [url] })!
602+ })!
603+ assert run.err == ''
604+ done := run.done()!
605+ assert done['action']!.str() == 'installed'
606+ assert sorted_strs(done['packages']!) == ['foo']
607+ assert os.read_file(s.path('root/usr/share/foo/hello'))! == 'one'
608+ // the trust warning is a warning to a frontend, and comes before the
609+ // download it is about, which comes before the transaction
610+ kinds := run.events.map(it['type']!.str())
611+ warned := run.events.filter(it['type']!.str() == 'message'
612+ && it['text']!.str().contains('signature'))
613+ assert warned.len == 1
614+ assert warned[0]['warning']!.bool()
615+ first_warning := run.events.index(warned[0])
616+ first_download := kinds.index('download')
617+ assert first_download > first_warning
618+ assert kinds.index('transaction') > first_download
619+ assert run.of('download').any(it['file']!.str().starts_with('foo-1.0-1-any.pkg.tar'))
620+ // the archive was fetched into the cache, as libalpm fetches one
621+ assert os.exists(s.path('cache/foo-1.0-1-any.pkg.tar'))
622+ assert !s.lock_left()
623+}
624+
625+fn test_url_install_refuses_a_bad_signature_beside_it() ! {
626+ s := fake_system('urlsig')!
627+ defer { os.rmdir_all(s.tmp) or {} }
628+ s.publish([foo('1.0-1', 'one')])!
629+ // the server offers a signature that does not hold: libalpm fetches it
630+ // with the archive, and the load at the remote level reads it
631+ os.write_file(s.path('repo/foo-1.0-1-any.pkg.tar.sig'), 'not a signature')!
632+ url := 'file://' + s.path('repo/foo-1.0-1-any.pkg.tar')
633+ run := s.run('', fn [url] () ! {
634+ install(ConfigInstall{ noconfirm: true, query: [url] })!
635+ })!
636+ assert run.err.contains('signature'), run.err
637+ assert run.of('done').len == 0
638+ assert s.installed()!.len == 0
639+ assert !os.exists(s.path('root/usr/share/foo/hello'))
640+ assert !s.lock_left()
641+}
642+
643+fn test_find_refresh_takes_the_full_handle() ! {
644+ s := fake_system('findhandle')!
645+ defer { os.rmdir_all(s.tmp) or {} }
646+ run := s.run('', fn () ! {
647+ // a sandbox user that exists wherever the test runs: this one
648+ download_user = current_user()!
649+ mut ui := new_trans_ui()
650+ refresh := find_handle(mut ui, true)!
651+ defer { refresh.release() or {} }
652+ // the refresh downloads as the sandbox user, from the file dbs
653+ if refresh.option_get_sandboxuser() != download_user {
654+ return error('a refresh downloads as "${refresh.option_get_sandboxuser()}"')
655+ }
656+ if refresh.option_get_dbext() != '.files' {
657+ return error('a refresh reads ${refresh.option_get_dbext()}')
658+ }
659+ read := find_handle(mut ui, false)!
660+ defer { read.release() or {} }
661+ if read.option_get_dbext() != '.files' {
662+ return error('a lookup reads ${read.option_get_dbext()}')
663+ }
664+ })!
665+ assert run.err == ''
666+}
667+
668+fn test_find_refresh_fetches_the_file_dbs() ! {
669+ s := fake_system('findrefresh')!
670+ defer { os.rmdir_all(s.tmp) or {} }
671+ s.publish([FakePkg{
672+ name: 'bar'
673+ files: {
674+ 'usr/bin/bar': 'bar'
675+ }
676+ }])!
677+ assert !os.exists(s.path('db/sync/core.files'))
678+ run := s.run('', fn () ! {
679+ find(ConfigFind{ refresh: true, query: ['/usr/bin/bar'] })!
680+ })!
681+ assert run.err == ''
682+ // fetched through the full handle: its progress reached the frontend
683+ assert run.of('download').any(it['file']!.str().starts_with('core.files'))
684+ assert os.exists(s.path('db/sync/core.files'))
685+ // and read: the repo package that provides the path
686+ provides := run.of('provides')
687+ assert provides.len == 1
688+ entries := provides[0]['entries']!.as_array()
689+ assert entries.len == 1
690+ assert entries[0].as_map()['name']!.str() == 'bar'
691+}
692+
693+// verify_lines runs the fast check on the system, with the NoExtract globs
694+// given, and returns its report: the lines, and how many packages are bad
695+fn (s FakeSystem) verify_lines(noextract []string) !([]string, int) {
696+ run := s.run('', fn [noextract] () ! {
697+ cfg_noextract = noextract.clone()
698+ verify(ConfigVerify{})!
699+ })!
700+ if run.err != '' {
701+ return error(run.err)
702+ }
703+ events := run.of('verify')
704+ if events.len != 1 {
705+ return error('${events.len} verify events')
706+ }
707+ lines := events[0]['lines']!.as_array().map(it.as_map()['text']!.str())
708+ return lines, events[0]['bad']!.int()
709+}
710+
711+fn test_verify_fast_check_as_pacman() ! {
712+ s := fake_system('verify')!
713+ defer { os.rmdir_all(s.tmp) or {} }
714+ s.install_local(FakePkg{
715+ name: 'docs'
716+ files: {
717+ 'usr/bin/docs': 'docs'
718+ 'usr/share/man/man1/docs.1': 'man'
719+ 'usr/share/doc/docs/README.md': 'readme'
720+ }
721+ })!
722+ s.install_local(FakePkg{
723+ name: 'dirs'
724+ files: {
725+ 'usr/share/dirs/a': 'a'
726+ }
727+ })!
728+ s.install_local(FakePkg{
729+ name: 'intact'
730+ files: {
731+ 'usr/lib/intact': 'ok'
732+ }
733+ })!
734+ // a man page NoExtract kept off the disk, and a binary that is gone
735+ os.rm(s.path('root/usr/share/man/man1/docs.1'))!
736+ os.rm(s.path('root/usr/bin/docs'))!
737+ // a directory the db lists, now a link to one elsewhere: the file in it
738+ // is still reached through the link
739+ os.mkdir_all(s.path('root/usr/share/elsewhere'))!
740+ os.write_file(s.path('root/usr/share/elsewhere/a'), 'a')!
741+ os.rmdir_all(s.path('root/usr/share/dirs'))!
742+ os.symlink('elsewhere', s.path('root/usr/share/dirs'))!
743+
744+ lines, bad := s.verify_lines(['usr/share/man/*'])!
745+ root := s.path('root')
746+ assert bad == 2, lines.str()
747+ assert 'docs: missing ${root}/usr/bin/docs' in lines
748+ assert 'dirs: ${root}/usr/share/dirs/ is a link, the db says a directory' in lines
749+ // NoExtract's file is not missing, and not said at all, as in pacman
750+ assert !lines.any(it.contains('docs.1')), lines.str()
751+ assert !lines.any(it.starts_with('intact')), lines.str()
752+ assert lines.len == 2, lines.str()
753+
754+ // without the NoExtract glob, the man page is missing like any file
755+ lines2, bad2 := s.verify_lines([])!
756+ assert bad2 == 2
757+ assert 'docs: missing ${root}/usr/share/man/man1/docs.1' in lines2
758+}
759+
760+fn test_verify_fast_check_lets_links_be() ! {
761+ s := fake_system('verifylinks')!
762+ defer { os.rmdir_all(s.tmp) or {} }
763+ s.install_local(FakePkg{
764+ name: 'linked'
765+ files: {
766+ 'usr/lib/libx.so.1': 'lib'
767+ 'usr/lib/libx.so': ''
768+ 'usr/lib/dangling': ''
769+ }
770+ })!
771+ // a package's file may be a link, to its neighbour or to nothing at all
772+ os.rm(s.path('root/usr/lib/libx.so'))!
773+ os.symlink('libx.so.1', s.path('root/usr/lib/libx.so'))!
774+ os.rm(s.path('root/usr/lib/dangling'))!
775+ os.symlink('nowhere', s.path('root/usr/lib/dangling'))!
776+ lines, bad := s.verify_lines([])!
777+ assert bad == 0, lines.str()
778+ assert lines.len == 0
779+}
780+
781+// fake_pkg is a FakePkg with no files, at a version, with its dependencies
782+fn fake_pkg(name string, version string, depends []string) FakePkg {
783+ return FakePkg{
784+ name: name
785+ version: version
786+ depends: depends
787+ }
788+}
789+
790+fn test_install_upgrades_the_whole_outdated_closure() ! {
791+ // app needs mid, mid needs low: both installed, both outdated. the walk
792+ // is the dependency closure, not one level of it
793+ s := fake_system('closure')!
794+ defer { os.rmdir_all(s.tmp) or {} }
795+ s.install_local(FakePkg{ ...fake_pkg('mid', '1.0-1', ['low']), reason: 1 })!
796+ s.install_local(FakePkg{ ...fake_pkg('low', '1.0-1', []), reason: 1 })!
797+ s.publish([fake_pkg('app', '1.0-1', ['mid']), fake_pkg('mid', '2.0-1', ['low']),
798+ fake_pkg('low', '2.0-1', [])])!
799+ run := s.run('', fn () ! {
800+ install(ConfigInstall{ noconfirm: true, query: ['app'] })!
801+ })!
802+ assert run.err == ''
803+ assert s.installed()! == {
804+ 'app': '1.0-1'
805+ 'mid': '2.0-1'
806+ 'low': '2.0-1'
807+ }
808+ // what came along is still a dependency
809+ assert s.reason_of('mid')! == .depend
810+}
811+
812+fn test_install_no_upgrade_deps_leaves_the_closure() ! {
813+ s := fake_system('noclosure')!
814+ defer { os.rmdir_all(s.tmp) or {} }
815+ s.install_local(FakePkg{ ...fake_pkg('mid', '1.0-1', ['low']), reason: 1 })!
816+ s.install_local(FakePkg{ ...fake_pkg('low', '1.0-1', []), reason: 1 })!
817+ s.publish([fake_pkg('app', '1.0-1', ['mid']), fake_pkg('mid', '2.0-1', ['low']),
818+ fake_pkg('low', '2.0-1', [])])!
819+ run := s.run('', fn () ! {
820+ install(ConfigInstall{ noconfirm: true, no_upgrade_deps: true, query: ['app'] })!
821+ })!
822+ assert run.err == ''
823+ assert s.installed()! == {
824+ 'app': '1.0-1'
825+ 'mid': '1.0-1'
826+ 'low': '1.0-1'
827+ }
828+}
829+
830+fn test_install_brings_along_what_it_would_break() ! {
831+ // user needs lib below 2.0; installing lib 2.0 breaks it, so the repo's
832+ // user, which takes the new lib, comes along in the same transaction
833+ s := fake_system('broken')!
834+ defer { os.rmdir_all(s.tmp) or {} }
835+ s.install_local(fake_pkg('user', '1.0-1', ['lib<2.0']))!
836+ s.install_local(FakePkg{ ...fake_pkg('lib', '1.0-1', []), reason: 1 })!
837+ s.publish([fake_pkg('lib', '2.0-1', []), fake_pkg('user', '2.0-1', ['lib>=2.0'])])!
838+ run := s.run('', fn () ! {
839+ install(ConfigInstall{ noconfirm: true, query: ['lib'] })!
840+ })!
841+ assert run.err == ''
842+ assert s.installed()! == {
843+ 'lib': '2.0-1'
844+ 'user': '2.0-1'
845+ }
846+ // the transaction listed it before the go-ahead
847+ listing := run.of('transaction')
848+ assert listing.len == 1
849+}
850+
851+fn test_no_upgrade_deps_failure_says_what_breaks() ! {
852+ // --no-upgrade-deps keeps an installed package that needs the old lib at
853+ // its version: prepare fails on it, and the hint names the cause
854+ s := fake_system('noupbreak')!
855+ defer { os.rmdir_all(s.tmp) or {} }
856+ s.install_local(fake_pkg('user', '1.0-1', ['lib<2.0']))!
857+ s.install_local(FakePkg{ ...fake_pkg('lib', '1.0-1', []), reason: 1 })!
858+ s.publish([fake_pkg('lib', '2.0-1', []), fake_pkg('user', '2.0-1', ['lib>=2.0'])])!
859+ run := s.run('', fn () ! {
860+ install(ConfigInstall{ noconfirm: true, no_upgrade_deps: true, query: ['lib'] })!
861+ })!
862+ lines := run.err.split('\n')
863+ assert lines[0] == 'could not satisfy dependencies:', run.err
864+ assert lines[1] == " lib breaks dependency 'lib<2.0' required by user", run.err
865+ assert lines[2].starts_with('without --no-upgrade-deps, the installed packages this breaks are upgraded along'), run.err
866+ assert s.installed()!['lib']! == '1.0-1'
867+ assert !s.lock_left()
868+}
869+
870+fn test_no_upgrade_deps_still_takes_a_newer_dependency() ! {
871+ // a target that needs a newer dependency than is installed gets it even
872+ // under --no-upgrade-deps: libalpm's prepare pulls it in, which is why
873+ // the hint never blames this case
874+ s := fake_system('noupnewer')!
875+ defer { os.rmdir_all(s.tmp) or {} }
876+ s.install_local(FakePkg{ ...fake_pkg('lib', '1.0-1', []), reason: 1 })!
877+ s.publish([fake_pkg('lib', '2.0-1', []), fake_pkg('app', '1.0-1', ['lib>=2.0'])])!
878+ run := s.run('', fn () ! {
879+ install(ConfigInstall{ noconfirm: true, no_upgrade_deps: true, query: ['app'] })!
880+ })!
881+ assert run.err == ''
882+ assert s.installed()! == {
883+ 'app': '1.0-1'
884+ 'lib': '2.0-1'
885+ }
886+}
887+
888+fn test_mark_failure_names_what_was_set() ! {
889+ if os.geteuid() == 0 {
890+ // root writes the read-only desc below anyway
891+ return
892+ }
893+ s := fake_system('markfail')!
894+ defer { os.rmdir_all(s.tmp) or {} }
895+ for name in ['aa', 'bb', 'cc'] {
896+ s.install_local(fake_pkg(name, '1.0-1', []))!
897+ }
898+ // bb's db entry cannot be written: its reason cannot change
899+ os.chmod(s.path('db/local/bb-1.0-1/desc'), 0o444)!
900+ run := s.run('', fn () ! {
901+ mark(ConfigMark{ reason: 'd', query: ['aa', 'bb', 'cc'] })!
902+ })!
903+ assert run.err.starts_with('could not set the install reason of bb: '), run.err
904+ assert run.err.ends_with(' (already set: aa)'), run.err
905+ assert run.of('done').len == 0
906+ // what the error says is what the db holds
907+ assert s.reason_of('aa')! == .depend
908+ assert s.reason_of('bb')! == .explicit
909+ assert s.reason_of('cc')! == .explicit
910+ assert !s.lock_left()
911+}
912+
913+fn test_provider_question_under_a_frontend() ! {
914+ // app needs a shell two repo packages provide: libalpm asks which, the
915+ // frontend gets the providers as the choices, and the answer is what is
916+ // installed
917+ s := fake_system('provider')!
918+ defer { os.rmdir_all(s.tmp) or {} }
919+ s.publish([fake_pkg('app', '1.0-1', ['shell']),
920+ FakePkg{ ...fake_pkg('bash', '1.0-1', []), provides: ['shell'] },
921+ FakePkg{ ...fake_pkg('dash', '1.0-1', []), provides: ['shell'] }])!
922+ // the frontend picks the second provider of question 1
923+ run := s.run('{"id": 1, "answer": 1}\n{"id": 2, "answer": true}\n', fn () ! {
924+ install(ConfigInstall{ query: ['app'] })!
925+ })!
926+ assert run.err == ''
927+ questions := run.of('question')
928+ assert questions.len == 2
929+ assert questions[0]['question']!.str() == 'choose'
930+ assert questions[0]['msg']!.str() == '2 providers for shell'
931+ choices := questions[0]['choices']!.as_array().map(it.str())
932+ assert choices.len == 2
933+ assert choices.all(it.starts_with('core/') && it.ends_with(' 1.0-1'))
934+ chosen := choices[1].all_after('/').all_before(' ')
935+ assert questions[1]['question']!.str() == 'proceed'
936+ installed := s.installed()!
937+ assert chosen in installed && installed.len == 2, installed.str()
938+ assert 'app' in installed
939+}
940+
941+fn test_provider_rows_number_the_choices() ! {
942+ s := fake_system('providerrows')!
943+ defer { os.rmdir_all(s.tmp) or {} }
944+ s.publish([fake_pkg('bash', '1.0-1', []), fake_pkg('dash', '2.0-1', [])])!
945+ run := s.run('', fn () ! {
946+ mut handle := init_handle(new_trans_ui())!
947+ defer { handle.release() or {} }
948+ dbs := init_repos(mut handle)!
949+ bash := dbs[0].get_pkg('bash') or { return error('no bash') }
950+ dash := dbs[0].get_pkg('dash') or { return error('no dash') }
951+ if provider_choice(dash) != 'core/dash 2.0-1' {
952+ return error('choice ${provider_choice(dash)}')
953+ }
954+ text := table_text(provider_rows([bash, dash]), '', ' ')
955+ if text.split('\n').map(it.trim_space()) != ['1) core/bash 1.0-1', '2) core/dash 2.0-1'] {
956+ return error('rows ${text}')
957+ }
958+ })!
959+ assert run.err == ''
960+}
961+
962+fn test_fuzzy_search_lists_name_matches_then_desc_matches_once() ! {
963+ s := fake_system('fuzzy')!
964+ defer { os.rmdir_all(s.tmp) or {} }
965+ s.publish([FakePkg{
966+ ...fake_pkg('zsh', '1.0-1', [])
967+ desc: 'zsh is the z shell'
968+ }, FakePkg{
969+ ...fake_pkg('fish', '1.0-1', [])
970+ desc: 'a friendly shell, much like zsh'
971+ }, FakePkg{
972+ ...fake_pkg('bash', '1.0-1', [])
973+ desc: 'the gnu bourne again shell'
974+ }, FakePkg{
975+ ...fake_pkg('zsh-doc', '1.0-1', [])
976+ desc: 'documentation'
977+ }])!
978+ run := s.run('', fn () ! {
979+ mut handle := init_handle(new_trans_ui())!
980+ defer { handle.release() or {} }
981+ dbs := init_repos(mut handle)!
982+ mut cache := pkgcache_of(handle, dbs[0])!
983+ got := build_matches(cache.pkgs(), ConfigSearch{
984+ fuzzy: true
985+ thold: 0.9
986+ query: ['zsh']
987+ }).map(it.get_name())
988+ // zsh by its name (and not again for its desc), then fish by its desc;
989+ // bash matches neither, and zsh-doc's name is too far at this threshold
990+ if got != ['zsh', 'fish'] {
991+ return error('matched ${got}')
992+ }
993+ })!
994+ assert run.err == ''
995+}
996+
997+// with_file_dbs publishes the packages with their file db already synced,
998+// as a find without -y reads it
999+fn with_file_dbs(name string, pkgs []FakePkg) !FakeSystem {
1000+ s := fake_system(name)!
1001+ s.publish(pkgs)!
1002+ os.cp(s.path('repo/core.files'), s.path('db/sync/core.files'))!
1003+ return s
1004+}
1005+
1006+// providers_of maps each path a find answered to the packages it named
1007+fn providers_of(run FrontendRun) map[string][]string {
1008+ mut out := map[string][]string{}
1009+ for e in run.of('provides') {
1010+ mut names := e['entries']!.as_array().map(it.as_map()['name']!.str())
1011+ names.sort()
1012+ out[e['path']!.str()] = names
1013+ }
1014+ return out
1015+}
1016+
1017+fn test_find_owner_index_answers_as_the_walk() ! {
1018+ s := with_file_dbs('findowner', [
1019+ FakePkg{
1020+ name: 'bar'
1021+ files: {
1022+ 'usr/bin/bar': 'bar'
1023+ }
1024+ },
1025+ FakePkg{
1026+ name: 'baz'
1027+ files: {
1028+ 'usr/bin/baz': 'baz'
1029+ 'usr/lib/libbaz': 'lib'
1030+ }
1031+ },
1032+ ])!
1033+ defer { os.rmdir_all(s.tmp) or {} }
1034+ paths := ['/usr/bin/bar', 'usr/lib/libbaz', '/usr/bin/', '/usr/bin', '/nope']
1035+ // several paths at once go through the index
1036+ many := s.run('', fn [paths] () ! {
1037+ find(ConfigFind{ query: paths })!
1038+ })!
1039+ got := providers_of(many)
1040+ assert got['/usr/bin/bar']! == ['bar']
1041+ assert got['usr/lib/libbaz']! == ['baz']
1042+ // a directory is every package's that carries it, with or without its slash
1043+ assert got['/usr/bin/']! == ['bar', 'baz']
1044+ assert got['/usr/bin']! == ['bar', 'baz']
1045+ // the miss is named, as a target error, and counted
1046+ misses := many.of('error').filter(it['target']!.bool())
1047+ assert misses.len == 1
1048+ assert misses[0]['msg']!.str() == 'no package provides /nope'
1049+ // one path at a time walks the filelists: the same answers
1050+ for p in paths {
1051+ one := s.run('', fn [p] () ! {
1052+ find(ConfigFind{ query: [p] })!
1053+ })!
1054+ assert providers_of(one)[p] or { []string{} } == got[p] or { []string{} }, p
1055+ }
1056+}
1057+
1058+fn test_find_list_names_its_misses() ! {
1059+ s := with_file_dbs('findlist', [FakePkg{
1060+ name: 'bar'
1061+ files: {
1062+ 'usr/bin/bar': 'bar'
1063+ }
1064+ }])!
1065+ defer { os.rmdir_all(s.tmp) or {} }
1066+ run := s.run('', fn () ! {
1067+ find(ConfigFind{ list: true, query: ['bar', 'nothere'] })!
1068+ })!
1069+ lists := run.of('files')
1070+ assert lists.len == 1
1071+ assert lists[0]['package']!.str() == 'bar'
1072+ assert lists[0]['repo']!.str() == 'core'
1073+ assert lists[0]['paths']!.as_array().map(it.str()) == ['usr/', 'usr/bin/', 'usr/bin/bar']
1074+ misses := run.of('error').filter(it['target']!.bool())
1075+ assert misses.len == 1
1076+ assert misses[0]['msg']!.str().contains('nothere')
1077+}
1078+
1079+// stale_after_update updates the sync dbs over file:// and answers what
1080+// the freshness check then calls stale
1081+fn (s FakeSystem) stale_after_update() !FrontendRun {
1082+ return s.run('', fn () ! {
1083+ mut handle := init_handle(new_trans_ui())!
1084+ defer { handle.release() or {} }
1085+ init_repos(mut handle)!
1086+ update_repos(mut handle, false)!
1087+ stale := stale_sync_dbs(handle)
1088+ report('stale: ${stale.join(',')}')
1089+ })!
1090+}
1091+
1092+fn test_sync_stamp_keeps_an_old_server_time_fresh() ! {
1093+ s := fake_system('stamp')!
1094+ defer { os.rmdir_all(s.tmp) or {} }
1095+ s.publish([foo('1.0-1', 'one')])!
1096+ // the server's db has not changed in two days: libalpm gives the copy
1097+ // it downloads the server's time, so only vpac's stamp says it is current
1098+ two_days_ago := time.now().unix() - 2 * sync_max_age
1099+ os.utime(s.path('repo/core.db'), two_days_ago, two_days_ago)!
1100+ os.rm(s.path('db/sync/core.db'))!
1101+ run := s.stale_after_update()!
1102+ assert run.err == ''
1103+ assert os.file_last_mod_unix(s.path('db/sync/core.db')) <= two_days_ago + 1
1104+ assert os.exists(s.path('db/sync/vpac.synced'))
1105+ assert run.of('message').any(it['text']!.str() == 'stale: ')
1106+}
1107+
1108+fn test_sync_stamp_that_cannot_be_written_is_said() ! {
1109+ s := fake_system('stampfail')!
1110+ defer { os.rmdir_all(s.tmp) or {} }
1111+ s.publish([foo('1.0-1', 'one')])!
1112+ two_days_ago := time.now().unix() - 2 * sync_max_age
1113+ os.utime(s.path('repo/core.db'), two_days_ago, two_days_ago)!
1114+ os.rm(s.path('db/sync/core.db'))!
1115+ // the stamp's path leads nowhere writable: its write fails, and no stamp
1116+ // is there after it (a link into a directory that does not exist)
1117+ os.symlink(s.path('nowhere/vpac.synced'), s.path('db/sync/vpac.synced'))!
1118+ run := s.stale_after_update()!
1119+ assert run.err == ''
1120+ // said, as a warning naming the stamp, and the db counts stale again —
1121+ // touching the db instead would feed libalpm's If-Modified-Since a lie
1122+ warned := run.of('message').filter(it['warning'] or { json2.Any(false) }.bool())
1123+ assert warned.len == 1
1124+ assert warned[0]['text']!.str().starts_with('could not write the sync stamp ${s.path('db/sync/vpac.synced')}')
1125+ assert run.of('message').any(it['text']!.str() == 'stale: core')
1126+}
1127+
1128+fn test_libalpm_warnings_reach_the_frontend() ! {
1129+ // installing what is installed already: libalpm says so at warning level,
1130+ // through its log callback alone, as pacman prints it
1131+ s := fake_system('alpmwarn')!
1132+ defer { os.rmdir_all(s.tmp) or {} }
1133+ s.install_local(foo('1.0-1', 'one'))!
1134+ s.publish([foo('1.0-1', 'one')])!
1135+ run := s.run('', fn () ! {
1136+ install(ConfigInstall{ noconfirm: true, query: ['foo'] })!
1137+ })!
1138+ assert run.err == ''
1139+ said := run.of('message').filter(it['text']!.str() == 'foo-1.0-1 is up to date -- reinstalling')
1140+ assert said.len == 1, run.of('message').str()
1141+ assert said[0]['warning']!.bool()
1142+ assert 'error' !in said[0]
1143+}
1144+
1145+fn test_libalpm_errors_reach_the_frontend() ! {
1146+ // a corrupt mtree: libalpm's error names the file and libarchive's reason
1147+ s := fake_system('alpmerror')!
1148+ defer { os.rmdir_all(s.tmp) or {} }
1149+ s.install_local(foo('1.0-1', 'one'))!
1150+ res := os.exec(['sh', '-c', 'printf "#mtree\\n./a type=file\\n" | gzip | head -c 15 > "\$0"',
1151+ s.path('db/local/foo-1.0-1/mtree')])
1152+ assert res.exit_code == 0, res.output
1153+ run := s.run('', fn () ! {
1154+ verify(ConfigVerify{
1155+ checksums_level: 2
1156+ })!
1157+ })!
1158+ assert run.err == ''
1159+ errors := run.of('message').filter(it['error'] or { json2.Any(false) }.bool())
1160+ assert errors.len == 1, run.of('message').str()
1161+ assert errors[0]['text']!.str() == 'error while reading file ${s.path('db/local/foo-1.0-1/mtree')}: truncated gzip input'
1162+ assert errors[0]['warning']!.bool()
1163+}
1164+
1165+fn test_mark_and_verify_skip_what_names_nothing() ! {
1166+ s := fake_system('skiptargets')!
1167+ defer { os.rmdir_all(s.tmp) or {} }
1168+ s.install_local(foo('1.0-1', 'one'))!
1169+ s.install_local(FakePkg{
1170+ ...fake_pkg('impl', '1.0-1', [])
1171+ provides: ['virt=2']
1172+ })!
1173+ // a bad target is reported and counted; the good ones are still marked
1174+ marked := s.run('', fn () ! {
1175+ mark(ConfigMark{ reason: 'd', query: ['nope', 'foo'] })!
1176+ })!
1177+ assert marked.err == '' && marked.failed == 1
1178+ assert marked.of('done')[0]['packages']!.as_array().map(it.str()) == ['foo']
1179+ // verify resolves a versioned name and a provision, as pacman's -Qk
1180+ // does, and names the target nothing answers
1181+ checked := s.run('', fn () ! {
1182+ verify(ConfigVerify{ query: ['foo>=1.0', 'virt', 'ghost'] })!
1183+ })!
1184+ assert checked.err == '', checked.err
1185+ assert checked.failed == 1
1186+ assert target_errors(checked) == ['package "ghost" was not found']
1187+ none_there := s.run('', fn () ! {
1188+ verify(ConfigVerify{ query: ['ghost'] })!
1189+ })!
1190+ assert none_there.err.contains('no one of the named packages'), none_there.err
1191+}
1192+
1193+fn test_tree_of_several_targets_under_a_frontend() ! {
1194+ s := fake_system('tree')!
1195+ defer { os.rmdir_all(s.tmp) or {} }
1196+ s.publish([fake_pkg('app', '1.0-1', ['lib']), fake_pkg('lib', '1.0-1', [])])!
1197+ run := s.run('', fn () ! {
1198+ tree(ConfigTree{ query: ['app', 'lib', 'nope'] })!
1199+ })!
1200+ assert run.err == ''
1201+ // each tree is its own event, every channel line one json object, and
1202+ // nothing at all reaches stdout — the blank line between trees is a
1203+ // terminal's frame
1204+ trees := run.of('tree')
1205+ assert trees.len == 2
1206+ assert trees[0]['root']!.as_map()['name']!.str() == 'app'
1207+ children := trees[0]['root']!.as_map()['children']!.as_array()
1208+ assert children.len == 1 && children[0].as_map()['name']!.str() == 'lib'
1209+ assert trees[1]['root']!.as_map()['name']!.str() == 'lib'
1210+ assert run.of('error').filter(it['target']!.bool()).len == 1
1211+ assert run.stdout == '', run.stdout
1212+}
1213+
1214+fn test_tree_leaves_the_sync_dbs_alone_until_needed() ! {
1215+ // no sync db was ever fetched here, so setting them up warns that they
1216+ // are not synced: a tree among installed packages never gets that far,
1217+ // one that has to look past them does
1218+ s := fake_system('treelazy')!
1219+ defer { os.rmdir_all(s.tmp) or {} }
1220+ s.install_local(fake_pkg('app', '1.0-1', ['lib']))!
1221+ s.install_local(fake_pkg('lib', '1.0-1', []))!
1222+ s.install_local(fake_pkg('broken', '1.0-1', ['gone']))!
1223+ stale := fn (run FrontendRun) int {
1224+ return run.of('message').filter(it['text'] or { json2.Any('') }.str().contains('not synced')).len
1225+ }
1226+ for query in [['app'], ['local/app', 'lib'], ['lib']] {
1227+ local := s.run('', fn [query] () ! {
1228+ tree(ConfigTree{ query: query })!
1229+ })!
1230+ assert local.err == '', local.err
1231+ assert local.of('tree').len == query.len
1232+ assert stale(local) == 0, '${query}: ${local.of('message')}'
1233+ }
1234+ // the reverse tree reads the installed packages alone, too
1235+ reverse := s.run('', fn () ! {
1236+ tree(ConfigTree{ reverse: true, query: ['lib'] })!
1237+ })!
1238+ assert reverse.of('tree').len == 1 && stale(reverse) == 0
1239+ // a target that is not installed, and a dependency nothing installed
1240+ // answers, each reach for the sync dbs — once, however many ask
1241+ for query in [['nowhere'], ['broken'], ['broken', 'nowhere', 'core/x']] {
1242+ past := s.run('', fn [query] () ! {
1243+ tree(ConfigTree{ query: query })!
1244+ })!
1245+ assert stale(past) == 1, '${query}: ${past.of('message')}'
1246+ }
1247+ // what nothing provides is still drawn, as not found
1248+ broken := s.run('', fn () ! {
1249+ tree(ConfigTree{ query: ['broken'] })!
1250+ })!
1251+ child := broken.of('tree')[0]['root']!.as_map()['children']!.as_array()[0].as_map()
1252+ assert child['name']!.str() == 'gone' && !(child['found'] or { json2.Any(false) }.bool())
1253+}
1254+
1255+fn test_tree_of_several_targets_on_a_terminal() ! {
1256+ s := fake_system('treetty')!
1257+ defer { os.rmdir_all(s.tmp) or {} }
1258+ s.publish([fake_pkg('app', '1.0-1', ['lib']), fake_pkg('lib', '1.0-1', [])])!
1259+ run := s.run_ui('tty', '', fn () ! {
1260+ tree(ConfigTree{ query: ['app', 'lib'] })!
1261+ })!
1262+ assert run.err == ''
1263+ // the terminal gets the trees on stdout, a blank line between them
1264+ trees := run.stdout.split('\n\n')
1265+ assert trees.len == 2, run.stdout
1266+ assert trees[0].starts_with('app'), run.stdout
1267+ assert trees[1].starts_with('lib'), run.stdout
1268+ assert run.events.len == 0
1269+}
1270+
1271+fn test_failed_targets_count_per_run() ! {
1272+ // one run's bad targets are its own: the next run in the same process
1273+ // starts from none, as each vpac process does
1274+ s := with_file_dbs('failedcount', [FakePkg{
1275+ name: 'bar'
1276+ files: {
1277+ 'usr/bin/bar': 'bar'
1278+ }
1279+ }])!
1280+ defer { os.rmdir_all(s.tmp) or {} }
1281+ misses := s.run('', fn () ! {
1282+ find(ConfigFind{ query: ['/nope', '/usr/bin/bar', '/neither'] })!
1283+ })!
1284+ assert misses.failed == 2
1285+ clean := s.run('', fn () ! {
1286+ find(ConfigFind{ query: ['/usr/bin/bar'] })!
1287+ })!
1288+ assert clean.failed == 0
1289+ // and a run leaves the count of whoever called it as it found it: the
1290+ // run's own is in its result, not in the global after it
1291+ failed_targets = 7
1292+ defer { failed_targets = 0 }
1293+ again := s.run('', fn () ! {
1294+ find(ConfigFind{ query: ['/nope'] })!
1295+ })!
1296+ assert again.failed == 1
1297+ assert failed_targets == 7
1298+}
1299+
1300+fn test_install_of_several_archives_is_one_transaction() ! {
1301+ // what a split build hands install: its archives, as local files, which
1302+ // go in together — one listing, one go-ahead, one done event
1303+ s := fake_system('archives')!
1304+ defer { os.rmdir_all(s.tmp) or {} }
1305+ s.publish([FakePkg{
1306+ name: 'split-a'
1307+ files: {
1308+ 'usr/share/split/a': 'a'
1309+ }
1310+ }, FakePkg{
1311+ name: 'split-b'
1312+ files: {
1313+ 'usr/share/split/b': 'b'
1314+ }
1315+ }])!
1316+ archives := ['split-a', 'split-b'].map(s.path('repo/${it}-1.0-1-any.pkg.tar'))
1317+ run := s.run('', fn [archives] () ! {
1318+ install(ConfigInstall{ noconfirm: true, query: archives })!
1319+ })!
1320+ assert run.err == ''
1321+ assert run.of('transaction').len == 1
1322+ assert run.of('question').len == 1
1323+ done := run.done()!
1324+ assert sorted_strs(done['packages']!) == ['split-a', 'split-b']
1325+ assert s.installed()! == {
1326+ 'split-a': '1.0-1'
1327+ 'split-b': '1.0-1'
1328+ }
1329+ assert os.read_file(s.path('root/usr/share/split/b'))! == 'b'
1330+}
1331+
1332+// FakeRpc answers the pkgbuild rpc's info and search requests from a set of
1333+// packages, or every request with raw when it is set
1334+struct FakeRpc {
1335+ pkgs map[string]PackagePkgbuild
1336+ raw string
1337+}
1338+
1339+fn (mut h FakeRpc) handle(req http.Request) http.Response {
1340+ if h.raw != '' {
1341+ return http.new_response(body: h.raw)
1342+ }
1343+ u := urllib.parse(req.url) or { return http.new_response(status: .bad_request) }
1344+ mut results := []PackagePkgbuild{}
1345+ if u.path == '/rpc/v5/info' {
1346+ q := urllib.parse_query(u.raw_query) or { urllib.new_values() }
1347+ for name in q.get_all('arg[]') {
1348+ if p := h.pkgs[name] {
1349+ results << p
1350+ }
1351+ }
1352+ } else if u.path.starts_with('/rpc/v5/search/') {
1353+ needle := u.path.all_after('/rpc/v5/search/')
1354+ // by name, so several results come in an order a test can name
1355+ mut names := h.pkgs.keys().filter(it.contains(needle))
1356+ names.sort()
1357+ for name in names {
1358+ results << h.pkgs[name]
1359+ }
1360+ }
1361+ return http.new_response(
1362+ body: json2.encode(PackagesPkgbuild{
1363+ count: results.len
1364+ results: results
1365+ type: 'multiinfo'
1366+ version: 5
1367+ })
1368+ )
1369+}
1370+
1371+// aur_pkg is a pkgbuild repo package of the fake rpc
1372+fn aur_pkg(name string, depends []string, make_depends []string) PackagePkgbuild {
1373+ return PackagePkgbuild{
1374+ name: name
1375+ package_base: name
1376+ version: '1.0-1'
1377+ depends: depends
1378+ make_depends: make_depends
1379+ }
1380+}
1381+
1382+// fake_rpc serves h on a free localhost port until the returned server is
1383+// stopped, and answers its base url
1384+fn fake_rpc(h FakeRpc) !(&http.Server, string) {
1385+ mut server := &http.Server{
1386+ addr: '127.0.0.1:0'
1387+ handler: h
1388+ show_startup_message: false
1389+ worker_num: 1
1390+ }
1391+ spawn server.listen_and_serve()
1392+ server.wait_till_running()!
1393+ return server, 'http://${server.addr}'
1394+}
1395+
1396+fn test_pkgbuild_info_from_the_rpc() ! {
1397+ mut server, base := fake_rpc(FakeRpc{
1398+ pkgs: {
1399+ 'yay-bin': aur_pkg('yay-bin', ['pacman'], [])
1400+ }
1401+ })!
1402+ defer { server.stop() }
1403+ got := get_pkgbuild_info(base, ['yay-bin', 'nothere'])!
1404+ assert got.map(it.name) == ['yay-bin']
1405+ assert got[0].depends == ['pacman']
1406+ found := get_pkgbuild_packages(base, 'yay')!
1407+ assert found.map(it.name) == ['yay-bin']
1408+ // no names asks for nothing, without a request
1409+ assert get_pkgbuild_info(base, [])!.len == 0
1410+}
1411+
1412+fn test_pkgbuild_rpc_short_garbage_is_an_error() ! {
1413+ // a 200 whose body is no json and shorter than the quote of it: an error
1414+ // naming what came, not a panic
1415+ mut server, base := fake_rpc(FakeRpc{
1416+ raw: 'oops'
1417+ })!
1418+ defer { server.stop() }
1419+ get_pkgbuild_info(base, ['x']) or {
1420+ assert err.msg().starts_with('failed to decode package info'), err.msg()
1421+ assert err.msg().ends_with('(the answer begins: oops)'), err.msg()
1422+ get_pkgbuild_packages(base, 'x') or {
1423+ assert err.msg().ends_with('(the answer begins: oops)'), err.msg()
1424+ return
1425+ }
1426+ assert false, 'the search took garbage'
1427+ }
1428+ assert false, 'the info lookup took garbage'
1429+}
1430+
1431+// resolve walks name through the fake system's local and sync dbs and the
1432+// fake rpc, as pkgbuild_install does, and answers the build plan
1433+fn resolve(s FakeSystem, base string, name string) ![]PkgbuildNode {
1434+ // the closure captures by value: the plan comes out through the heap
1435+ mut plan := &Plan{}
1436+ run := s.run('', fn [base, name, mut plan] () ! {
1437+ cfg_repos << CfgRepo{
1438+ name: 'aur'
1439+ kind: 'pkgbuild'
1440+ servers: [base]
1441+ }
1442+ mut handle := init_handle(new_trans_ui())!
1443+ defer { handle.release() or {} }
1444+ init_repos(mut handle)!
1445+ plan.nodes << pkgbuild_plan(handle, name)!
1446+ })!
1447+ if run.err != '' {
1448+ return error(run.err)
1449+ }
1450+ return plan.nodes
1451+}
1452+
1453+@[heap]
1454+struct Plan {
1455+mut:
1456+ nodes []PkgbuildNode
1457+}
1458+
1459+fn test_pkgbuild_resolver_orders_the_build() ! {
1460+ s := fake_system('resolver')!
1461+ defer { os.rmdir_all(s.tmp) or {} }
1462+ // glibc installed, lib in the repos, the rest only in the pkgbuild repo
1463+ s.install_local(fake_pkg('glibc', '1.0-1', []))!
1464+ s.publish([fake_pkg('lib', '1.0-1', [])])!
1465+ mut server, base := fake_rpc(FakeRpc{
1466+ pkgs: {
1467+ 'top': PackagePkgbuild{
1468+ ...aur_pkg('top', ['mid', 'lib', 'glibc>=1.0', 'shared'], ['tool'])
1469+ check_depends: ['checker']
1470+ }
1471+ 'checker': aur_pkg('checker', [], [])
1472+ 'mid': aur_pkg('mid', ['leaf', 'shared'], [])
1473+ 'leaf': aur_pkg('leaf', [], [])
1474+ 'shared': aur_pkg('shared', [], [])
1475+ 'tool': aur_pkg('tool', [], [])
1476+ }
1477+ })!
1478+ defer { server.stop() }
1479+ plan := resolve(s, base, 'top')!
1480+ // dependencies first, each once (shared is reached twice), the target last
1481+ // what check() needs is planned as what the build needs is
1482+ assert plan.map(it.info.name) == ['leaf', 'shared', 'mid', 'tool', 'checker', 'top']
1483+ // a repo package is installed before the build that needs it; an
1484+ // installed one is not touched; the site is the pkgbuild repo it came from
1485+ top := plan.last()
1486+ assert top.repo_deps == ['lib']
1487+ assert plan.all(it.site == base)
1488+ assert plan.filter(it.info.name != 'top').all(it.repo_deps.len == 0)
1489+ // every node carries what wanted it, as the dependents spelled it: the
1490+ // target nothing, a node wanted twice both spellings once each
1491+ wanted := fn [plan] (name string) []string {
1492+ return plan.filter(it.info.name == name)[0].wanted
1493+ }
1494+ assert wanted('top') == []
1495+ assert wanted('mid') == ['mid'] && wanted('leaf') == ['leaf']
1496+ assert wanted('shared') == ['shared']
1497+ assert wanted('checker') == ['checker']
1498+ // a site the config spells with a trailing slash joins a clone url with
1499+ // one slash all the same
1500+ slashed := resolve(s, base + '/', 'leaf')!
1501+ assert slashed[0].site == base
1502+}
1503+
1504+fn test_pkgbuild_resolver_refuses_cycles_and_unknowns() ! {
1505+ s := fake_system('resolverbad')!
1506+ defer { os.rmdir_all(s.tmp) or {} }
1507+ s.publish([fake_pkg('lib', '1.0-1', [])])!
1508+ mut server, base := fake_rpc(FakeRpc{
1509+ pkgs: {
1510+ 'c1': aur_pkg('c1', ['c2'], [])
1511+ 'c2': aur_pkg('c2', ['c1'], [])
1512+ 'needy': aur_pkg('needy', ['ghost>=2'], [])
1513+ }
1514+ })!
1515+ defer { server.stop() }
1516+ resolve(s, base, 'c1') or {
1517+ assert err.msg() == 'circular pkgbuild dependency: c1 is walked as its own dependency', err.msg()
1518+ resolve(s, base, 'needy') or {
1519+ assert err.msg() == '"ghost" is not in the repos or the pkgbuild repo', err.msg()
1520+ return
1521+ }
1522+ assert false, 'a dependency nowhere was planned'
1523+ }
1524+ assert false, 'a cycle was planned'
1525+}
1526+
1527+// target_errors are the messages of the target errors a run reported
1528+fn target_errors(run FrontendRun) []string {
1529+ return run.of('error').filter(it['target'] or { json2.Any(false) }.bool()).map(it['msg'] or {
1530+ json2.Any('')
1531+ }.str())
1532+}
1533+
1534+fn test_install_scopes_a_target_to_its_repo() ! {
1535+ s := fake_system('scope')!
1536+ defer { os.rmdir_all(s.tmp) or {} }
1537+ s.publish([fake_pkg('foo', '1.0-1', [])])!
1538+ // a repo the config does not carry is an error, not a prefix to drop
1539+ bad := s.run('', fn () ! {
1540+ install(ConfigInstall{ noconfirm: true, query: ['nope/foo'] })!
1541+ })!
1542+ assert target_errors(bad) == ['database not found: nope']
1543+ assert s.installed()!.len == 0
1544+ // a name the repo named does not hold is not looked up anywhere else
1545+ miss := s.run('', fn () ! {
1546+ install(ConfigInstall{ noconfirm: true, query: ['core/nothere'] })!
1547+ })!
1548+ assert target_errors(miss) == ['target not found in core: nothere']
1549+ good := s.run('', fn () ! {
1550+ install(ConfigInstall{ noconfirm: true, query: ['core/foo'] })!
1551+ })!
1552+ assert good.err == '' && good.failed == 0
1553+ assert s.installed()! == {
1554+ 'foo': '1.0-1'
1555+ }
1556+}
1557+
1558+fn test_install_resolves_constraints_and_providers() ! {
1559+ s := fake_system('satisfier')!
1560+ defer { os.rmdir_all(s.tmp) or {} }
1561+ s.publish([fake_pkg('foo', '2.0-1', []),
1562+ FakePkg{ ...fake_pkg('bash', '1.0-1', []), provides: ['sh'] }])!
1563+ run := s.run('', fn () ! {
1564+ install(ConfigInstall{ noconfirm: true, query: ['foo>=2', 'sh'] })!
1565+ })!
1566+ assert run.err == '' && run.failed == 0, run.err
1567+ assert s.installed()! == {
1568+ 'foo': '2.0-1'
1569+ 'bash': '1.0-1'
1570+ }
1571+ // a version nothing has is a miss like any other
1572+ old := s.run('', fn () ! {
1573+ install(ConfigInstall{ noconfirm: true, query: ['core/foo>=3'] })!
1574+ })!
1575+ assert target_errors(old) == ['target not found in core: foo>=3']
1576+}
1577+
1578+fn test_install_names_every_bad_target_and_installs_nothing() ! {
1579+ s := fake_system('badtargets')!
1580+ defer { os.rmdir_all(s.tmp) or {} }
1581+ s.publish([fake_pkg('foo', '1.0-1', [])])!
1582+ run := s.run('', fn () ! {
1583+ install(ConfigInstall{ noconfirm: true, query: ['zzzzzz', 'foo', 'qqqqqq'] })!
1584+ })!
1585+ // both misses are told, not only the first, and the good one waits
1586+ assert run.err == ''
1587+ assert run.failed == 2
1588+ assert target_errors(run).len == 2
1589+ assert run.of('done').len == 0
1590+ assert s.installed()!.len == 0
1591+ assert !s.lock_left()
1592+}
1593+
1594+fn tool(name string) FakePkg {
1595+ return FakePkg{
1596+ ...fake_pkg(name, '1.0-1', [])
1597+ groups: ['tools']
1598+ }
1599+}
1600+
1601+fn test_install_asks_which_members_of_a_group() ! {
1602+ s := fake_system('groupselect')!
1603+ defer { os.rmdir_all(s.tmp) or {} }
1604+ s.publish([tool('aa'), tool('bb'), tool('cc')])!
1605+ // the frontend picks the first and the third, then lets it go
1606+ run := s.run('{"id": 1, "answer": [0, 2]}\n{"id": 2, "answer": true}\n', fn () ! {
1607+ install(ConfigInstall{ query: ['tools'] })!
1608+ })!
1609+ assert run.err == '', run.err
1610+ // the members go out as a listing, each naming its group, then the question
1611+ lists := run.of('listing')
1612+ assert lists.len == 1
1613+ members := lists[0]['entries']!.as_array().map(it.as_map())
1614+ assert members.map(it['name'] or { json2.Any('') }.str()) == ['aa', 'bb', 'cc']
1615+ assert members.all(it['group'] or { json2.Any('') }.str() == 'tools')
1616+ questions := run.of('question')
1617+ assert questions[0]['question']!.str() == 'select'
1618+ assert questions[0]['preset']!.as_array().len == 3
1619+ assert s.installed()! == {
1620+ 'aa': '1.0-1'
1621+ 'cc': '1.0-1'
1622+ }
1623+ // --noconfirm takes every member left; the installed ones are not offered
1624+ rest := s.run('', fn () ! {
1625+ install(ConfigInstall{ noconfirm: true, query: ['tools'] })!
1626+ })!
1627+ assert rest.err == ''
1628+ assert rest.of('listing')[0]['entries']!.as_array().len == 1
1629+ assert s.installed()!.len == 3
1630+ // nothing left: said, and no failure
1631+ done := s.run('', fn () ! {
1632+ install(ConfigInstall{ noconfirm: true, query: ['tools'] })!
1633+ })!
1634+ assert done.err == '' && done.failed == 0
1635+ assert done.of('message').any(it['text'] or { json2.Any('') }.str().contains('every member'))
1636+}
1637+
1638+fn test_group_selection_on_a_terminal() ! {
1639+ s := fake_system('groupselecttty')!
1640+ defer { os.rmdir_all(s.tmp) or {} }
1641+ s.publish([tool('aa'), tool('bb'), tool('cc')])!
1642+ // all but the second, then the go-ahead
1643+ run := s.run_ui('tty', '^2\ny\n', fn () ! {
1644+ install(ConfigInstall{ query: ['tools'] })!
1645+ })!
1646+ assert run.err == '', run.err
1647+ assert s.installed()! == {
1648+ 'aa': '1.0-1'
1649+ 'cc': '1.0-1'
1650+ }
1651+ // --print lists every member and asks nothing
1652+ preview := s.run_ui('tty', '', fn () ! {
1653+ install(ConfigInstall{ print_only: true, query: ['tools'] })!
1654+ })!
1655+ assert preview.stdout.trim_space() == 'bb-1.0-1-any.pkg.tar', preview.stdout
1656+}
1657+
1658+fn test_remove_takes_a_group_and_names_every_bad_target() ! {
1659+ s := fake_system('removegroup')!
1660+ defer { os.rmdir_all(s.tmp) or {} }
1661+ s.install_local(tool('aa'))!
1662+ s.install_local(tool('bb'))!
1663+ s.install_local(fake_pkg('keep', '1.0-1', []))!
1664+ // one unknown target stops the removal, after every one is named
1665+ bad := s.run('', fn () ! {
1666+ remove(ConfigRemove{ noconfirm: true, query: ['zzzzzz', 'tools', 'qqqqqq'] })!
1667+ })!
1668+ assert bad.failed == 2
1669+ assert s.installed()!.len == 3
1670+ assert !s.lock_left()
1671+ run := s.run('', fn () ! {
1672+ remove(ConfigRemove{ noconfirm: true, query: ['tools'] })!
1673+ })!
1674+ assert run.err == '', run.err
1675+ assert sorted_strs(run.done()!['packages']!) == ['aa', 'bb']
1676+ assert s.installed()! == {
1677+ 'keep': '1.0-1'
1678+ }
1679+}
1680+
1681+fn test_remove_unneeded_and_recursive_levels() ! {
1682+ s := fake_system('removelevels')!
1683+ defer { os.rmdir_all(s.tmp) or {} }
1684+ s.install_local(fake_pkg('app', '1.0-1', ['lib', 'tool']))!
1685+ s.install_local(FakePkg{ ...fake_pkg('lib', '1.0-1', []), reason: 1 })!
1686+ // tool was installed explicitly, though app needs it
1687+ s.install_local(fake_pkg('tool', '1.0-1', []))!
1688+ s.install_local(fake_pkg('other', '1.0-1', []))!
1689+ // -u: lib stays where app needs it, other goes, and that is no failure
1690+ u := s.run('', fn () ! {
1691+ remove(ConfigRemove{ noconfirm: true, unneeded: true, query: ['lib', 'other'] })!
1692+ })!
1693+ assert u.err == '', u.err
1694+ assert sorted_strs(u.done()!['packages']!) == ['other']
1695+ assert 'lib' in s.installed()!
1696+ none_left := s.run('', fn () ! {
1697+ remove(ConfigRemove{ noconfirm: true, unneeded: true, query: ['lib'] })!
1698+ })!
1699+ assert none_left.err == '' && none_left.of('done').len == 0
1700+ // a version constraint names what satisfies it
1701+ // -s takes lib, a dependency; tool was asked for by name and stays
1702+ one := s.run('', fn () ! {
1703+ remove(ConfigRemove{ print_only: true, recursive_level: 1, query: ['app>=1'] })!
1704+ })!
1705+ assert one.err == '', one.err
1706+ assert sorted_strs(one.of('transaction')[0]['packages']!.as_array().map(it.as_map()['name'] or {
1707+ json2.Any('')
1708+ })) == ['app', 'lib']
1709+ // -ss takes the explicitly installed dependency too
1710+ two := s.run('', fn () ! {
1711+ remove(ConfigRemove{ print_only: true, recursive_level: 2, query: ['app'] })!
1712+ })!
1713+ assert sorted_strs(two.of('transaction')[0]['packages']!.as_array().map(it.as_map()['name'] or {
1714+ json2.Any('')
1715+ })) == ['app', 'lib', 'tool']
1716+}
1717+
1718+fn test_upgrade_downgrades_only_when_asked() ! {
1719+ s := fake_system('downgrade')!
1720+ defer { os.rmdir_all(s.tmp) or {} }
1721+ s.install_local(foo('2.0-1', 'two'))!
1722+ s.publish([foo('1.0-1', 'one')])!
1723+ plain := s.run('', fn () ! {
1724+ upgrade(ConfigUpgrade{ noconfirm: true })!
1725+ })!
1726+ assert plain.err == ''
1727+ assert s.installed()!['foo']! == '2.0-1'
1728+ down := s.run('', fn () ! {
1729+ upgrade(ConfigUpgrade{ noconfirm: true, sysupgrade_level: 2 })!
1730+ })!
1731+ assert down.err == '', down.err
1732+ assert s.installed()!['foo']! == '1.0-1'
1733+}
1734+
1735+fn test_info_changelog_and_package_files() ! {
1736+ s := fake_system('changelog')!
1737+ defer { os.rmdir_all(s.tmp) or {} }
1738+ s.install_local(FakePkg{ ...fake_pkg('logged', '1.0-1', []), changelog: 'first release\n' })!
1739+ s.install_local(fake_pkg('silent', '1.0-1', []))!
1740+ s.publish([
1741+ FakePkg{ ...fake_pkg('filed', '1.0-1', []), changelog: 'from the archive\n' },
1742+ fake_pkg('other', '2.0-1', []),
1743+ ])!
1744+ run := s.run('', fn () ! {
1745+ info(ConfigInfo{ changelog: true, query: ['logged', 'silent'] })!
1746+ })!
1747+ assert run.err == '' && run.failed == 0
1748+ logs := run.of('changelog')
1749+ assert logs.len == 1
1750+ assert logs[0]['package']!.str() == 'logged'
1751+ assert logs[0]['text']!.str() == 'first release\n'
1752+ // the one without is said, and is no failure, as in pacman
1753+ assert run.of('message').any(it['text'] or { json2.Any('') }.str().contains('no changelog available for silent'))
1754+
1755+ // -p: every target is a package file, and one that does not load is its
1756+ // own error
1757+ archives := ['filed-1.0-1', 'other-2.0-1'].map(s.path('repo/${it}-any.pkg.tar'))
1758+ mut targets := archives.clone()
1759+ targets << s.path('repo/nothere.pkg.tar')
1760+ files := s.run('', fn [targets] () ! {
1761+ info(ConfigInfo{ file: true, fields: 'name,version', query: targets })!
1762+ })!
1763+ infos := files.of('info')
1764+ assert infos.len == 2
1765+ assert files.failed == 1
1766+ first := archives[0]
1767+ log := s.run('', fn [first] () ! {
1768+ info(ConfigInfo{ file: true, changelog: true, query: [first] })!
1769+ })!
1770+ assert log.of('changelog')[0]['text']!.str() == 'from the archive\n'
1771+ tty := s.run_ui('tty', '', fn () ! {
1772+ info(ConfigInfo{ changelog: true, query: ['logged'] })!
1773+ })!
1774+ assert tty.stdout == 'changelog for logged:\nfirst release\n', tty.stdout
1775+}
1776+
1777+fn test_info_scopes_and_satisfiers() ! {
1778+ s := fake_system('infoscope')!
1779+ defer { os.rmdir_all(s.tmp) or {} }
1780+ s.install_local(FakePkg{ ...fake_pkg('bash', '1.0-1', []), provides: ['sh'] })!
1781+ s.publish([fake_pkg('bash', '2.0-1', []), fake_pkg('zsh', '1.0-1', [])])!
1782+ version_of := fn (run FrontendRun) string {
1783+ for f in run.of('info')[0]['fields'] or { json2.Any([]json2.Any{}) }.as_array() {
1784+ m := f.as_map()
1785+ if m['field'] or { json2.Any('') }.str() == 'version' {
1786+ return m['value'] or { json2.Any('') }.str()
1787+ }
1788+ }
1789+ return ''
1790+ }
1791+ // bare: the installed one; core/: the repo's; a provider resolves
1792+ for target, version in {
1793+ 'bash': '1.0-1'
1794+ 'local/bash': '1.0-1'
1795+ 'core/bash': '2.0-1'
1796+ 'sh': '1.0-1'
1797+ 'bash>=2': '2.0-1'
1798+ } {
1799+ run := s.run('', fn [target] () ! {
1800+ info(ConfigInfo{ noconfirm: true, query: [target] })!
1801+ })!
1802+ assert run.failed == 0, target
1803+ assert version_of(run) == version, target
1804+ }
1805+ // local/ never reaches the sync dbs, and an unknown repo is an error
1806+ for target, msg in {
1807+ 'local/zsh': 'unknown package: "zsh"'
1808+ 'nope/bash': 'database not found: nope'
1809+ } {
1810+ run := s.run('', fn [target] () ! {
1811+ info(ConfigInfo{ noconfirm: true, query: [target] })!
1812+ })!
1813+ assert target_errors(run) == [msg], target
1814+ }
1815+}
1816+
1817+fn test_search_local_groups_and_all_members() ! {
1818+ s := fake_system('localgroups')!
1819+ defer { os.rmdir_all(s.tmp) or {} }
1820+ s.install_local(tool('aa'))!
1821+ s.install_local(fake_pkg('plain', '1.0-1', []))!
1822+ s.publish([tool('aa'), tool('bb'), FakePkg{
1823+ ...fake_pkg('cc', '1.0-1', [])
1824+ groups: [
1825+ 'extras',
1826+ ]
1827+ }])!
1828+ names := fn (run FrontendRun) []string {
1829+ return run.of('listing')[0]['entries'] or { json2.Any([]json2.Any{}) }.as_array().map('${it.as_map()['group'] or {
1830+ json2.Any('')
1831+ }.str()} ${it.as_map()['name'] or { json2.Any('') }.str()}')
1832+ }
1833+ // -l -g: the local db's groups, the installed members alone
1834+ local := s.run('', fn () ! {
1835+ search(ConfigSearch{ local: true, groups: true, query: ['tools'] })!
1836+ })!
1837+ assert local.err == '', local.err
1838+ assert names(local) == ['tools aa']
1839+ bare := s.run('', fn () ! {
1840+ search(ConfigSearch{ local: true, groups: true })!
1841+ })!
1842+ groups := bare.of('groups')[0]['groups']!.as_array().map(it.as_map())
1843+ assert groups.len == 1
1844+ assert groups[0]['repo']!.str() == 'local' && groups[0]['name']!.str() == 'tools'
1845+ // -gg: every group of the sync dbs with its members
1846+ all := s.run('', fn () ! {
1847+ search(ConfigSearch{ remote: true, groups: true, groups_level: 2 })!
1848+ })!
1849+ mut got := names(all)
1850+ got.sort()
1851+ assert got == ['extras cc', 'tools aa', 'tools bb']
1852+ tty := s.run_ui('tty', '', fn () ! {
1853+ search(ConfigSearch{ local: true, groups: true, groups_level: 2 })!
1854+ })!
1855+ assert tty.stdout == 'tools aa\n', tty.stdout
1856+ // a sync-comparing filter on the sync groups: the dbs are registered
1857+ // once, and only the installed member can pass
1858+ native := s.run('', fn () ! {
1859+ search(ConfigSearch{ remote: true, groups: true, native: true, query: ['tools'] })!
1860+ })!
1861+ assert native.err == '', native.err
1862+ assert names(native) == ['tools aa']
1863+ // the terminal's table leads with the group, as the ipc entries carry it
1864+ named := s.run_ui('tty', '', fn () ! {
1865+ search(ConfigSearch{ remote: true, groups: true, fields: 'name', query: ['tools'] })!
1866+ })!
1867+ assert named.err == '', named.err
1868+ assert named.stdout.split_into_lines().map(it.fields().join(' ')) == ['tools aa', 'tools bb'], named.stdout
1869+}
1870+
1871+fn test_owner_quiet_names_the_package_alone() ! {
1872+ s := fake_system('ownerquiet')!
1873+ defer { os.rmdir_all(s.tmp) or {} }
1874+ s.install_local(foo('1.0-1', 'one'))!
1875+ path := s.path('root/usr/share/foo/hello')
1876+ run := s.run_ui('tty', '', fn [path] () ! {
1877+ owner(ConfigOwner{ quiet: true, query: [path] })!
1878+ })!
1879+ assert run.err == ''
1880+ assert run.stdout == 'foo\n', run.stdout
1881+}
1882+
1883+fn test_find_regex_and_machinereadable() ! {
1884+ s := with_file_dbs('findregex', [
1885+ FakePkg{
1886+ name: 'bar'
1887+ files: {
1888+ 'usr/bin/bar': 'bar'
1889+ 'usr/share/bar/x': 'x'
1890+ }
1891+ },
1892+ FakePkg{
1893+ name: 'baz'
1894+ files: {
1895+ 'usr/bin/baz': 'baz'
1896+ }
1897+ },
1898+ ])!
1899+ defer { os.rmdir_all(s.tmp) or {} }
1900+ // without a slash the expression is tried on file names, case ignored
1901+ names := s.run('', fn () ! {
1902+ find(ConfigFind{ regex: true, query: ['^BA.$'] })!
1903+ })!
1904+ assert providers_of(names)['^BA.$']! == ['bar', 'baz']
1905+ // with one, on whole paths
1906+ paths := s.run('', fn () ! {
1907+ find(ConfigFind{ regex: true, query: ['share/.*x$', '/usr/bin/ba[rz]'] })!
1908+ })!
1909+ got := providers_of(paths)
1910+ assert got['share/.*x$']! == ['bar']
1911+ assert got['/usr/bin/ba[rz]']! == ['bar', 'baz']
1912+ // a bad expression is named and nothing is searched
1913+ bad := s.run('', fn () ! {
1914+ find(ConfigFind{ regex: true, query: ['(', 'bar'] })!
1915+ })!
1916+ assert target_errors(bad) == ["invalid regular expression '('"]
1917+ assert bad.of('provides').len == 0
1918+ // pacman's --machinereadable: repo, package, version, path, NUL parted
1919+ machine := s.run_ui('tty', '', fn () ! {
1920+ find(ConfigFind{ regex: true, machinereadable: true, query: ['usr/bin/ba.'] })!
1921+ })!
1922+ assert machine.stdout == 'core\0bar\x001.0-1\0usr/bin/bar\ncore\0baz\x001.0-1\0usr/bin/baz\n', machine.stdout.bytes().str()
1923+ exact := s.run_ui('tty', '', fn () ! {
1924+ find(ConfigFind{ machinereadable: true, query: ['/usr/bin/bar'] })!
1925+ })!
1926+ assert exact.stdout == 'core\0bar\x001.0-1\0usr/bin/bar\n', exact.stdout.bytes().str()
1927+ list := s.run_ui('tty', '', fn () ! {
1928+ find(ConfigFind{ list: true, machinereadable: true, query: ['baz'] })!
1929+ })!
1930+ assert list.stdout.split('\n')[2] == 'core\0baz\x001.0-1\0usr/bin/baz', list.stdout.bytes().str()
1931+ // an expression's event names the files it matched, one list a package
1932+ matched := paths.of('provides').filter(it['path']!.str() == 'share/.*x$')
1933+ assert matched[0]['files']!.as_array().map(it.as_array().map(it.str())) == [
1934+ ['usr/share/bar/x'],
1935+ ]
1936+}
1937+
1938+fn test_find_names_slashes_and_scoped_lists() ! {
1939+ s := with_file_dbs('findnames', [
1940+ FakePkg{
1941+ name: 'bar'
1942+ files: {
1943+ 'usr/bin/bar': 'bar'
1944+ 'usr/share/bar/x': 'x'
1945+ }
1946+ },
1947+ FakePkg{
1948+ name: 'baz'
1949+ files: {
1950+ 'usr/bin/baz': 'baz'
1951+ }
1952+ },
1953+ ])!
1954+ defer { os.rmdir_all(s.tmp) or {} }
1955+ // a target with no slash is a file name: the directory usr/share/bar/
1956+ // has none, the file usr/bin/bar does
1957+ name := s.run('', fn () ! {
1958+ find(ConfigFind{ query: ['bar'] })!
1959+ })!
1960+ assert providers_of(name)['bar']! == ['bar']
1961+ assert name.of('provides')[0]['files']!.as_array().map(it.as_array().map(it.str())) == [
1962+ ['usr/bin/bar'],
1963+ ]
1964+ // a trailing slash on a file's path answers the same alone as among
1965+ // others: the walk and the index match it the same way
1966+ alone := s.run('', fn () ! {
1967+ find(ConfigFind{ query: ['/usr/bin/bar/'] })!
1968+ })!
1969+ among := s.run('', fn () ! {
1970+ find(ConfigFind{ query: ['/usr/bin/bar/', '/usr/bin/baz'] })!
1971+ })!
1972+ assert providers_of(alone)['/usr/bin/bar/']! == ['bar']
1973+ assert providers_of(among)['/usr/bin/bar/']! == ['bar']
1974+ // slashes alone never become the empty expression
1975+ assert find_rel('//') == '/' && find_rel('/usr/bin') == 'usr/bin' && find_rel('x') == 'x'
1976+ // -l takes repo/package, and lists the package before the path
1977+ scoped := s.run_ui('tty', '', fn () ! {
1978+ find(ConfigFind{ list: true, query: ['core/baz'] })!
1979+ })!
1980+ assert scoped.err == '', scoped.err
1981+ assert scoped.stdout.split_into_lines().map(it.fields().join(' ')) == ['baz usr/', 'baz usr/bin/',
1982+ 'baz usr/bin/baz'], scoped.stdout
1983+ other := s.run('', fn () ! {
1984+ find(ConfigFind{ list: true, query: ['nope/baz', 'core/'] })!
1985+ })!
1986+ assert other.of('files').len == 0
1987+ assert target_errors(other).len == 2
1988+}
1989+
1990+fn test_clean_levels_and_unused_sync_dbs() ! {
1991+ s := fake_system('cleandbs')!
1992+ defer { os.rmdir_all(s.tmp) or {} }
1993+ s.install_local(foo('1.0-1', 'one'))!
1994+ for f in ['foo-1.0-1-any.pkg.tar.zst', 'gone-1.0-1-any.pkg.tar.zst'] {
1995+ os.write_file(s.path('cache/${f}'), 'x')!
1996+ }
1997+ // core is configured; old is a repo the config dropped
1998+ for f in ['core.db', 'core.files', 'old.db', 'old.db.sig', 'old.files', 'vpac.synced'] {
1999+ os.write_file(s.path('db/sync/${f}'), 'x')!
2000+ }
2001+ preview := s.run('', fn () ! {
2002+ clean(ConfigClean{ print_only: true })!
2003+ })!
2004+ assert preview.err == '', preview.err
2005+ ev := preview.of('clean')[0].clone()
2006+ assert ev['files']!.as_array().map(os.base(it.str())) == ['gone-1.0-1-any.pkg.tar.zst']
2007+ assert ev['dbs']!.as_array().map(os.base(it.str())) == ['old.db', 'old.db.sig', 'old.files']
2008+ // -cc is every cached package, the installed one too
2009+ all := s.run('', fn () ! {
2010+ clean(ConfigClean{ print_only: true, level: 2 })!
2011+ })!
2012+ assert all.of('clean')[0]['files']!.as_array().len == 2
2013+ run := s.run('', fn () ! {
2014+ clean(ConfigClean{ noconfirm: true, level: 1 })!
2015+ })!
2016+ assert run.err == '', run.err
2017+ mut left := os.ls(s.path('db/sync'))!
2018+ left.sort()
2019+ assert left == ['core.db', 'core.files', 'vpac.synced']
2020+ assert os.ls(s.path('cache'))! == ['foo-1.0-1-any.pkg.tar.zst']
2021+}
2022+
2023+// dead_mirror aims the repo at a server that has nothing: every refresh
2024+// against it fails
2025+fn (s FakeSystem) dead_mirror() {
2026+ cfg_repos = [CfgRepo{
2027+ name: 'core'
2028+ kind: 'sync'
2029+ servers: ['file://' + s.path('nowhere')]
2030+ }]
2031+}
2032+
2033+fn test_a_failed_refresh_is_an_error() ! {
2034+ s := fake_system('deadmirror')!
2035+ defer { os.rmdir_all(s.tmp) or {} }
2036+ s.install_local(foo('1.0-1', 'one'))!
2037+ s.publish([foo('2.0-1', 'two')])!
2038+ up := s.run_ui('tty', '', fn [s] () ! {
2039+ s.dead_mirror()
2040+ upgrade(ConfigUpgrade{ noconfirm: true, sync_dbs: true })!
2041+ })!
2042+ se := s.run('', fn [s] () ! {
2043+ s.dead_mirror()
2044+ search(ConfigSearch{ remote: true, sync_dbs: true, query: ['foo'] })!
2045+ })!
2046+ fy := s.run('', fn [s] () ! {
2047+ s.dead_mirror()
2048+ find(ConfigFind{ refresh: true, query: ['/usr/share/foo/hello'] })!
2049+ })!
2050+ assert up.err != ''
2051+ assert se.err != ''
2052+ assert fy.err != ''
2053+ assert s.installed()!['foo']! == '1.0-1'
2054+}
2055+
2056+// check is an assertion inside a run's closure, where a failed assert would
2057+// leave the fake system's redirected fds behind: it fails the run instead
2058+fn check(ok bool, what string) ! {
2059+ if !ok {
2060+ return error('check failed: ${what}')
2061+ }
2062+}
2063+
2064+fn test_targets_resolve_by_scope_version_and_provision() ! {
2065+ s := fake_system('targets')!
2066+ defer { os.rmdir_all(s.tmp) or {} }
2067+ s.install_local(fake_pkg('app', '1.0-1', ['lib']))!
2068+ s.install_local(FakePkg{
2069+ ...fake_pkg('impl', '1.0-1', [])
2070+ provides: ['virt=2']
2071+ })!
2072+ s.publish([fake_pkg('app', '2.0-1', ['lib']), fake_pkg('lib', '1.0-1', []), FakePkg{
2073+ ...fake_pkg('simpl', '1.0-1', [])
2074+ provides: ['svirt=3']
2075+ }])!
2076+ run := s.run('', fn () ! {
2077+ mut ui := new_trans_ui()
2078+ mut handle := init_handle(ui)!
2079+ defer { handle.release() or {} }
2080+ dbs := init_repos(mut handle)!
2081+ local := local_pkgcache(handle)!
2082+ // the scope is all the dbs, or the one named; an unknown name is an
2083+ // error and never a search of everything
2084+ check(scope_dbs(dbs, '')!.len == 1, 'no scope keeps every db')!
2085+ check(scope_dbs(dbs, 'core')!.map(it.get_name()) == ['core'], 'core scopes to core')!
2086+ if _ := scope_dbs(dbs, 'extra') {
2087+ return error('an unknown repo scoped')
2088+ } else {
2089+ check(err.msg() == 'database not found: extra', err.msg())!
2090+ }
2091+ if _ := scope_dbs([], 'core') {
2092+ return error('a repo was found among no dbs')
2093+ }
2094+ // installed: by name, by a constraint it meets, and by provision
2095+ // only where the caller takes providers
2096+ check(find_local_target(local, 'app', false) != none, 'app by name')!
2097+ check(find_local_target(local, 'app>=1.0', false) != none, 'app by a met constraint')!
2098+ check(find_local_target(local, 'app>=2', false) == none, 'app by an unmet constraint')!
2099+ check(find_local_target(local, 'virt', false) == none, 'a provision without providers')!
2100+ check(find_local_target(local, 'virt', true) != none, 'a provision with providers')!
2101+ check(find_local_target(local, 'virt>=3', true) == none, 'a provision too old')!
2102+ check(find_local_target(local, '', true) == none, 'the empty name')!
2103+ check(find_local_target(local, 'ap', true) == none, 'a prefix of a name')!
2104+ // sync: by name, constraint and provision; the empty name is nothing
2105+ check(find_sync_target(handle, dbs, 'app', false) != none, 'sync app')!
2106+ check(find_sync_target(handle, dbs, 'app>=2.0', false) != none, 'sync app>=2.0')!
2107+ check(find_sync_target(handle, dbs, 'app>2.0', false) == none, 'sync app>2.0')!
2108+ check(find_sync_target(handle, dbs, 'svirt', false) != none, 'sync provision')!
2109+ check(find_sync_target(handle, dbs, 'svirt=4', false) == none, 'sync provision, wrong version')!
2110+ check(find_sync_target(handle, dbs, '', false) == none, 'sync empty name')!
2111+ check(find_sync_target(handle, []&alpm.DB{}, 'app', false) == none, 'no dbs')!
2112+ // a db not for installing answers a provision only when it was
2113+ // named with the target, and its usage is put back after
2114+ dbs[0].set_usage(.sync | .search)!
2115+ check(find_sync_target(handle, dbs, 'svirt', false) == none, 'usage without install')!
2116+ check(find_sync_target(handle, dbs, 'svirt', true) != none, 'named db, usage lifted')!
2117+ usage := dbs[0].get_usage() or { return error('no usage') }
2118+ check(!usage.has(.install), 'the usage was put back')!
2119+ // by name it is found either way: the name is asked of the db itself
2120+ check(find_sync_target(handle, dbs, 'app', false) != none, 'by name whatever the usage')!
2121+ })!
2122+ assert run.err == '', run.err
2123+}
2124+
2125+fn test_filters_combine_as_pacmans_query_filters() ! {
2126+ s := fake_system('filters')!
2127+ defer { os.rmdir_all(s.tmp) or {} }
2128+ // app: explicit, in the repos, newer there. lib: a dependency app needs.
2129+ // own: explicit, in no repo. loose: a dependency nothing needs, older in
2130+ // the repos than installed. opt-only would need optdepends, which the
2131+ // level-2 unrequired check is covered with in orphans_test
2132+ s.install_local(fake_pkg('app', '1.0-1', ['lib']))!
2133+ s.install_local(FakePkg{
2134+ ...fake_pkg('lib', '1.0-1', [])
2135+ reason: 1
2136+ })!
2137+ s.install_local(fake_pkg('own', '1.0-1', []))!
2138+ s.install_local(FakePkg{
2139+ ...fake_pkg('loose', '2.0-1', [])
2140+ reason: 1
2141+ })!
2142+ s.publish([fake_pkg('app', '2.0-1', ['lib']), fake_pkg('lib', '1.0-1', []),
2143+ fake_pkg('loose', '1.0-1', [])])!
2144+ run := s.run('', fn () ! {
2145+ mut ui := new_trans_ui()
2146+ mut handle := init_handle(ui)!
2147+ defer { handle.release() or {} }
2148+ dbs := init_repos(mut handle)!
2149+ mut local := local_pkgcache(handle)!
2150+ pass := fn [mut local, dbs] (c ConfigSearch) []string {
2151+ mut names := local.pkgs().filter(pkg_matches_filter(it, c, dbs)).map(it.get_name())
2152+ names.sort()
2153+ return names
2154+ }
2155+ check(pass(ConfigSearch{}) == ['app', 'lib', 'loose', 'own'], 'no filter passes all')!
2156+ check(pass(ConfigSearch{ explicit: true }) == ['app', 'own'], 'explicit')!
2157+ check(pass(ConfigSearch{ deps: true }) == ['lib', 'loose'], 'deps')!
2158+ // the two reasons together pass nothing: no package is both
2159+ check(pass(ConfigSearch{ deps: true, explicit: true }) == [], 'deps and explicit')!
2160+ check(pass(ConfigSearch{ unrequired: true, unrequired_level: 1 }) == ['app', 'loose', 'own'], 'unrequired')!
2161+ check(pass(ConfigSearch{ deps: true, unrequired: true, unrequired_level: 1 }) == ['loose'], 'unrequired deps')!
2162+ check(pass(ConfigSearch{ foreign: true }) == ['own'], 'foreign')!
2163+ check(pass(ConfigSearch{ native: true }) == ['app', 'lib', 'loose'], 'native')!
2164+ check(pass(ConfigSearch{ native: true, foreign: true }) == [], 'native and foreign')!
2165+ // an upgrade is a strictly newer sync version: an equal one, an
2166+ // older one (loose) and a package in no repo are not
2167+ check(pass(ConfigSearch{ upgrades: true }) == ['app'], 'upgrades')!
2168+ check(pass(ConfigSearch{ upgrades: true, deps: true }) == [], 'upgrades among deps')!
2169+ check(pass(ConfigSearch{ upgrades: true, foreign: true }) == [], 'upgrades of foreign')!
2170+ // with no sync dbs to compare with, everything is foreign
2171+ none_synced := local.pkgs().filter(pkg_matches_filter(it, ConfigSearch{ native: true },
2172+ []&alpm.DB{}))
2173+ check(none_synced.len == 0, 'native with no sync dbs')!
2174+ // the filters that need no sync data never load it
2175+ check(filter_sync_dbs(mut ui, mut handle, ConfigSearch{ explicit: true, unrequired: true })!.len == 0,
2176+ 'no sync dbs for local-only filters')!
2177+ })!
2178+ assert run.err == '', run.err
2179+}
2180+
2181+fn test_search_groups_take_one_side_and_fuzzy_keeps_its_order() ! {
2182+ s := fake_system('searchedges')!
2183+ defer { os.rmdir_all(s.tmp) or {} }
2184+ s.install_local(tool('aa'))!
2185+ s.publish([tool('aa'), FakePkg{
2186+ ...fake_pkg('zeditor', '1.0-1', [])
2187+ desc: 'an editor'
2188+ }, FakePkg{
2189+ ...fake_pkg('notes', '1.0-1', [])
2190+ desc: 'a small editor for notes'
2191+ }, FakePkg{
2192+ ...fake_pkg('editor', '1.0-1', [])
2193+ desc: 'the editor'
2194+ }])!
2195+ // -g with both sides named would drop one of them: refused, before any
2196+ // db is opened, with or without a group named
2197+ for query in [[]string{}, ['tools']] {
2198+ both := s.run('', fn [query] () ! {
2199+ search(ConfigSearch{ local: true, remote: true, groups: true, query: query })!
2200+ })!
2201+ assert both.err.contains('not both at once'), both.err
2202+ assert both.of('listing').len == 0 && both.of('groups').len == 0
2203+ }
2204+ // each side alone still answers
2205+ for local in [true, false] {
2206+ one := s.run('', fn [local] () ! {
2207+ search(ConfigSearch{ local: local, remote: !local, groups: true, query: ['tools'] })!
2208+ })!
2209+ assert one.err == '', one.err
2210+ assert one.of('listing').len == 1
2211+ }
2212+ // fuzzy: the names that match lead, best first, and a package matched
2213+ // by its description alone trails them, listed once
2214+ fuzzy := s.run('', fn () ! {
2215+ search(ConfigSearch{ remote: true, fuzzy: true, thold: 0.8, fields: 'name', query: ['editor'] })!
2216+ })!
2217+ assert fuzzy.err == '', fuzzy.err
2218+ names := fuzzy.of('listing')[0]['entries']!.as_array().map(it.as_map()['name']!.str())
2219+ assert names == ['editor', 'zeditor', 'notes'], names.str()
2220+ // a term nothing is near matches nothing, and is no error
2221+ none_near := s.run('', fn () ! {
2222+ search(ConfigSearch{ remote: true, fuzzy: true, thold: 0.8, query: ['qqqqqqqq'] })!
2223+ })!
2224+ assert none_near.err == ''
2225+ assert none_near.of('listing')[0]['entries'] or { json2.Any([]json2.Any{}) }.as_array().len == 0
2226+}
2227+
2228+fn test_info_fields_and_listing_on_real_packages() ! {
2229+ s := fake_system('formatreal')!
2230+ defer { os.rmdir_all(s.tmp) or {} }
2231+ s.install_local(FakePkg{
2232+ ...fake_pkg('app', '1.0-1', ['lib>=1', 'glibc'])
2233+ provides: ['virt=2']
2234+ groups: ['tools']
2235+ })!
2236+ s.install_local(fake_pkg('bare', '2.0-1', []))!
2237+ run := s.run_ui('tty', '', fn () ! {
2238+ mut ui := new_trans_ui()
2239+ mut handle := init_handle(ui)!
2240+ defer { handle.release() or {} }
2241+ local := local_pkgcache(handle)!
2242+ app := local.pkg_find('app') or { return error('no app') }
2243+ bare := local.pkg_find('bare') or { return error('no bare') }
2244+ // asked for by default, an empty field is left out; named on the
2245+ // command line it is shown, empty
2246+ fields := ['name', 'version', 'depends', 'provides', 'groups', 'url']
2247+ quiet := info_fields(bare, fields, false)
2248+ check(quiet.map(it.field) == ['name', 'version'], 'empty fields left out: ${quiet.map(it.field)}')!
2249+ named := info_fields(bare, fields, true)
2250+ check(named.map(it.field) == fields, 'named fields all shown')!
2251+ check(named.filter(it.field == 'depends')[0].value == '', 'an empty value stays empty')!
2252+ check(named.filter(it.field == 'depends')[0].items.len == 0, 'and has no items')!
2253+ // a list field carries its items one by one, a plain one none
2254+ full := info_fields(app, fields, false)
2255+ check(full.map(it.field) == ['name', 'version', 'depends', 'provides', 'groups'], 'app fields: ${full.map(it.field)}')!
2256+ deps := full.filter(it.field == 'depends')[0]
2257+ check(deps.items == ['lib>=1', 'glibc'] && deps.value == 'lib>=1, glibc', 'depends items: ${deps}')!
2258+ check(full.filter(it.field == 'name')[0].items.len == 0, 'a plain field has no items')!
2259+ check(full.filter(it.field == 'provides')[0].items == ['virt=2'], 'provides items')!
2260+ // no fields asked for is nothing to show, not a crash
2261+ check(info_fields(app, [], true).len == 0, 'no fields')!
2262+ check(info_table([]) == '', 'an empty table is no text')!
2263+ // a listing: the default mode holds a value per field, the quiet one
2264+ // the name alone, and a member carries its group
2265+ mut l := Listing{
2266+ fields: ['name', 'version', 'groups']
2267+ }
2268+ l.add_pkg(app, 'local')
2269+ l.add_pkg(bare, 'local')
2270+ check(l.entries[0].values == ['app', '1.0-1', 'tools'], 'values: ${l.entries[0].values}')!
2271+ check(l.entries[1].values == ['bare', '2.0-1', ''], 'an empty value is kept in its place')!
2272+ mut q := Listing{
2273+ mode: .minimal
2274+ fields: ['name', 'version']
2275+ }
2276+ q.add_pkg(app, 'local')
2277+ q.add_member(bare, 'local', 'tools')
2278+ check(q.entries.all(it.values.len == 0), 'quiet entries hold no values')!
2279+ check(q.entries[1].group == 'tools' && q.entries[0].group == '', 'the member has its group')!
2280+ // what the terminal gets: a table with '-' for the empty value, the
2281+ // names alone for the quiet one, nothing at all for an empty listing
2282+ l.print()
2283+ println('--')
2284+ q.print()
2285+ println('--')
2286+ Listing{
2287+ fields: ['name']
2288+ }.print()
2289+ println('--')
2290+ // a collection that failed part way shows what a quiet listing
2291+ // found, and nothing of a table
2292+ l.print_found()
2293+ q.print_found()
2294+ })!
2295+ assert run.err == '', run.err
2296+ parts := run.stdout.split('--\n')
2297+ assert parts.len == 4, run.stdout
2298+ assert parts[0].split_into_lines().map(it.fields().join(' ')) == ['app 1.0-1 tools', 'bare 2.0-1 -'], parts[0]
2299+ assert parts[1] == 'app\nbare\n'
2300+ assert parts[2] == ''
2301+ assert parts[3] == 'app\nbare\n'
2302+}
2303+
2304+fn test_pkgbuild_plan_gathers_every_spelling_that_wanted_a_node() ! {
2305+ s := fake_system('wanted')!
2306+ defer { os.rmdir_all(s.tmp) or {} }
2307+ // dep 1.0 is installed, and too old for everything that asks for it
2308+ s.install_local(fake_pkg('dep', '1.0-1', []))!
2309+ s.publish([fake_pkg('lib', '1.0-1', [])])!
2310+ mut server, base := fake_rpc(FakeRpc{
2311+ pkgs: {
2312+ 'top': aur_pkg('top', ['a', 'b', 'dep>=2'], [])
2313+ 'a': aur_pkg('a', ['dep>=2', 'dep>=3'], [])
2314+ 'b': aur_pkg('b', ['dep>=3'], ['dep>=2'])
2315+ 'dep': aur_pkg('dep', [], [])
2316+ }
2317+ })!
2318+ defer { server.stop() }
2319+ plan := resolve(s, base, 'top')!
2320+ assert plan.map(it.info.name) == ['dep', 'a', 'b', 'top']
2321+ // the node is planned once, and holds each spelling once, in the order
2322+ // they were met, those that came after it was planned too
2323+ assert plan[0].wanted == ['dep>=2', 'dep>=3']
2324+ assert plan[1].wanted == ['a'] && plan[2].wanted == ['b'] && plan[3].wanted == []
2325+ // the plan is made on the local db of this moment: with dep new enough
2326+ // for everyone installed since, it is planned by nobody
2327+ os.rmdir_all(s.path('db/local/dep-1.0-1'))!
2328+ s.install_local(fake_pkg('dep', '3.0-1', []))!
2329+ again := resolve(s, base, 'top')!
2330+ assert again.map(it.info.name) == ['a', 'b', 'top']
2331+ // new enough for some and not for all, it is still planned, and wanted
2332+ // by the one spelling it does not meet: a spelling that is met already
2333+ // plans nothing and is not held
2334+ os.rmdir_all(s.path('db/local/dep-3.0-1'))!
2335+ s.install_local(fake_pkg('dep', '2.0-1', []))!
2336+ partly := resolve(s, base, 'top')!
2337+ assert partly.map(it.info.name) == ['dep', 'a', 'b', 'top']
2338+ assert partly[0].wanted == ['dep>=3']
2339+}
@@ -0,0 +1,476 @@
1+module main
2+
3+import term
4+
5+struct HelpFlag {
6+ name string
7+ desc string
8+}
9+
10+struct HelpExample {
11+ cmd string
12+ desc string
13+}
14+
15+struct HelpMode {
16+ key string
17+ name string
18+ desc string
19+ usage string
20+ options []HelpFlag
21+ examples []HelpExample
22+}
23+
24+const help_modes = [
25+ HelpMode{
26+ key: 's'
27+ name: 'search'
28+ desc: 'search packages in the local, sync and pkgbuild databases'
29+ usage: '[options] <term...>'
30+ options: [
31+ HelpFlag{'-l, --local', 'search the installed packages'},
32+ HelpFlag{'-r, --remote', 'search the sync databases (the default)'},
33+ HelpFlag{'-b, --pkgbuild', 'search the pkgbuild repo'},
34+ HelpFlag{'-f, --fuzzy', 'fuzzy matching instead of substring matching'},
35+ HelpFlag{'-t, --thold <0-1>', 'fuzzy match threshold (default 0.9)'},
36+ HelpFlag{'-q, --quiet', 'print package names only'},
37+ HelpFlag{'-s, --sync', 'refresh the sync databases first'},
38+ HelpFlag{'-F, --fields <list>', 'columns to show: all, or a comma list (see fields)'},
39+ HelpFlag{'-d, --deps', 'installed packages installed as dependencies [filter]'},
40+ HelpFlag{'-e, --explicit', 'installed packages installed explicitly [filter]'},
41+ HelpFlag{'-m, --foreign', 'installed packages not in the sync dbs [filter]'},
42+ HelpFlag{'-n, --native', 'installed packages found in the sync dbs [filter]'},
43+ HelpFlag{'--unrequired', 'installed packages nothing requires [filter]'},
44+ HelpFlag{'', 'twice keeps the ones only optionally required'},
45+ HelpFlag{'-u, --upgrades', 'installed packages with a newer version in the sync dbs [filter]'},
46+ HelpFlag{'-g, --groups', 'list the groups, or the members of the groups named'},
47+ HelpFlag{'', 'with -gg every group with its members'},
48+ HelpFlag{'', 'with -l the installed groups'},
49+ HelpFlag{'--noconfirm', 'take the default at every prompt, never read stdin'},
50+ HelpFlag{'-i, --installed', 'keep only packages that are installed locally'},
51+ ]
52+ examples: [
53+ HelpExample{'vpac s -r linux-lts', 'search the sync databases for linux-lts'},
54+ HelpExample{'vpac s -l -F name,version,size', 'installed packages with their sizes'},
55+ HelpExample{'vpac s -l -e', 'installed packages installed explicitly'},
56+ HelpExample{'vpac s -l -u', 'installed packages with an update available'},
57+ HelpExample{'vpac s -r visual code', 'packages with both words in the name or description'},
58+ HelpExample{'vpac s -l -f -t 0.8 patchelv', 'fuzzy search the installed packages'},
59+ HelpExample{'vpac s -g base-devel', 'the members of a sync group'},
60+ HelpExample{'vpac s -l -gg', 'every installed group with its members'},
61+ ]
62+ },
63+ HelpMode{
64+ key: 'q'
65+ name: 'info'
66+ desc: 'show package information, falling back to the sync databases'
67+ usage: '[options] <package|file...>'
68+ options: [
69+ HelpFlag{'-F, --fields <list>', 'fields to show: all, or a comma list (see fields)'},
70+ HelpFlag{'-c, --changelog', 'show the changelog of the package instead'},
71+ HelpFlag{'-p, --file', 'the targets are package files, not installed or sync packages'},
72+ HelpFlag{'--noconfirm', 'take the default at every prompt, never read stdin'},
73+ ]
74+ examples: [
75+ HelpExample{'vpac q patchelf', 'show what is installed for patchelf'},
76+ HelpExample{'vpac q -F name,version,depends bash', 'only those three fields'},
77+ HelpExample{'vpac q extra/bash', 'the bash of one repo; local/bash is the installed one'},
78+ HelpExample{"vpac q 'sh>=5'", 'whatever satisfies a dependency'},
79+ HelpExample{'vpac q -c bash', 'the changelog bash was packaged with'},
80+ HelpExample{'vpac q -p ./a.pkg.tar.zst ./b.pkg.tar.zst', 'package files on disk'},
81+ ]
82+ },
83+ HelpMode{
84+ key: 'w'
85+ name: 'which'
86+ desc: 'find the installed package that provides a dependency'
87+ usage: '<dependency...>'
88+ examples: [
89+ HelpExample{'vpac w libpng.so', 'which package provides libpng.so'},
90+ ]
91+ },
92+ HelpMode{
93+ key: 'n'
94+ name: 'deptest'
95+ desc: 'print the dependencies no installed package satisfies, exit 127 if any'
96+ usage: '<dependency...>'
97+ examples: [
98+ HelpExample{"vpac n 'glibc>=2.40' cowsay", 'print whichever of the two is not satisfied'},
99+ ]
100+ },
101+ HelpMode{
102+ key: 'm'
103+ name: 'mark'
104+ desc: 'change why an installed package is installed'
105+ usage: '-r <reason> <package...>'
106+ options: [
107+ HelpFlag{'-r, --reason <reason>', 'explicit, depend or unknown'},
108+ HelpFlag{'--noconfirm', 'take the default at every prompt, never read stdin'},
109+ ]
110+ examples: [
111+ HelpExample{'vpac m -r depend patchelf', 'mark patchelf as installed as a dependency'},
112+ ]
113+ },
114+ HelpMode{
115+ key: 'i'
116+ name: 'install'
117+ desc: 'install from the repos, a local file or the pkgbuild repo (asked first)'
118+ usage: '[options] <package|file...>'
119+ options: [
120+ HelpFlag{'--no-upgrade-deps', 'leave outdated dependencies and their dependents alone'},
121+ HelpFlag{'--needed', 'skip the targets installed at the version they would install'},
122+ HelpFlag{'--asdeps', 'mark the targets as installed as dependencies'},
123+ HelpFlag{'--asexplicit', 'mark the targets as explicitly installed'},
124+ HelpFlag{'-d, --nodeps', 'skip the dependency version checks'},
125+ HelpFlag{'-dd', 'skips the dependency checks'},
126+ HelpFlag{'--assume-installed <pkg=ver>', 'count a dependency as installed (repeatable, comma separated)'},
127+ HelpFlag{'--overwrite <glob>', 'overwrite conflicting files that match (repeatable, comma separated)'},
128+ HelpFlag{'--ignore <pkg>', 'leave a package out of this run (repeatable, comma separated)'},
129+ HelpFlag{'--ignoregroup <group>', 'leave a group out of this run (repeatable, comma separated)'},
130+ HelpFlag{'--dbonly', 'change the database only, not the files on disk'},
131+ HelpFlag{'--disable-timeout', 'let slow downloads take their time'},
132+ HelpFlag{'-b, --pkgbuild', 'build from the pkgbuild repo only, offering the PKGBUILD for review first'},
133+ HelpFlag{'--nopkgbuildconfirm', 'skip the questions asked while installing from the pkgbuild repo'},
134+ HelpFlag{'-w, --download-only', 'download the packages into the cache, and install nothing'},
135+ HelpFlag{'-p, --print', 'list the archives the transaction would install, and install nothing'},
136+ HelpFlag{'--noconfirm', 'answer yes to repo prompts, and refuse pkgbuild builds unless --nopkgbuildconfirm'},
137+ ]
138+ examples: [
139+ HelpExample{'vpac i patchelf', 'install patchelf, upgrading its outdated dependencies'},
140+ HelpExample{'vpac i ./foo-1.0-1-x86_64.pkg.tar.zst', 'install a local package file'},
141+ HelpExample{'vpac i patchelf bash', 'install both in one transaction, confirmed once'},
142+ HelpExample{'vpac i --needed --asdeps patchelf', 'install patchelf as a dependency, unless it is up to date'},
143+ HelpExample{'vpac i extra/patchelf', 'install it from that repo and no other'},
144+ HelpExample{"vpac i 'bash>=5' sh", 'install what satisfies a version, or provides a name'},
145+ HelpExample{'vpac i base-devel', 'install a group: its members are listed, to pick from'},
146+ ]
147+ },
148+ HelpMode{
149+ key: 'r'
150+ name: 'remove'
151+ desc: 'remove an installed package'
152+ usage: '[options] <package...>'
153+ options: [
154+ HelpFlag{'-s, --recursive', 'also remove the dependencies the removal leaves unneeded'},
155+ HelpFlag{'-ss', 'the explicitly installed ones too'},
156+ HelpFlag{'-u, --unneeded', 'leave the targets something still requires, instead of failing'},
157+ HelpFlag{'-c, --cascade', 'also remove the packages that depend on the targets'},
158+ HelpFlag{'-n, --nosave', 'remove changed config files too, instead of keeping .pacsave copies'},
159+ HelpFlag{'-d, --nodeps', 'skip the dependency version checks'},
160+ HelpFlag{'-dd', 'skips the dependency checks'},
161+ HelpFlag{'--assume-installed <pkg=ver>', 'count a dependency as installed (repeatable, comma separated)'},
162+ HelpFlag{'--dbonly', 'change the database only, not the files on disk'},
163+ HelpFlag{'-p, --print', 'list the packages the removal would take, as name-version, and remove nothing'},
164+ HelpFlag{'--noconfirm', 'take the default at every prompt, never read stdin'},
165+ ]
166+ examples: [
167+ HelpExample{'vpac r patchelf', 'remove patchelf'},
168+ HelpExample{'vpac r -s patchelf', 'remove patchelf and the dependencies only it needed'},
169+ HelpExample{'vpac r -c libfoo', 'remove libfoo and every package that needs it'},
170+ HelpExample{'vpac r -ss patchelf', 'also the dependencies that were installed explicitly'},
171+ HelpExample{'vpac r -u libfoo libbar', 'remove whichever of them nothing needs'},
172+ HelpExample{'vpac r xorg-apps', 'remove the installed members of a group'},
173+ ]
174+ },
175+ HelpMode{
176+ key: 'u'
177+ name: 'upgrade'
178+ desc: 'upgrade the whole system'
179+ usage: '[options]'
180+ options: [
181+ HelpFlag{'-s, --sync', 'refresh the sync databases first'},
182+ HelpFlag{'-w, --download-only', 'download the upgrades without installing them'},
183+ HelpFlag{'-uu, --downgrade', 'also downgrade packages newer than the sync dbs carry'},
184+ HelpFlag{'--ignore <pkg>', 'hold a package back this time (repeatable, comma separated)'},
185+ HelpFlag{'--ignoregroup <group>', 'hold a group back this time (repeatable, comma separated)'},
186+ HelpFlag{'-d, --nodeps', 'skip the dependency version checks'},
187+ HelpFlag{'-dd', 'skips the dependency checks'},
188+ HelpFlag{'--assume-installed <pkg=ver>', 'count a dependency as installed (repeatable, comma separated)'},
189+ HelpFlag{'--overwrite <glob>', 'overwrite conflicting files that match (repeatable, comma separated)'},
190+ HelpFlag{'--dbonly', 'change the database only, not the files on disk'},
191+ HelpFlag{'--disable-timeout', 'let slow downloads take their time'},
192+ HelpFlag{'-p, --print', 'list the archives the upgrade would install, and upgrade nothing'},
193+ HelpFlag{'--noconfirm', 'take the default at every prompt, never read stdin'},
194+ ]
195+ examples: [
196+ HelpExample{'vpac u -s', 'refresh the databases and upgrade the system'},
197+ HelpExample{'vpac u --ignore linux', 'upgrade everything but linux'},
198+ HelpExample{'vpac u -s -w', 'refresh, then only download what the upgrade needs'},
199+ HelpExample{'vpac u -uu', 'bring packages newer than the repos back down to them'},
200+ ]
201+ },
202+ HelpMode{
203+ key: 'l'
204+ name: 'files'
205+ desc: 'list the files of an installed package'
206+ usage: '[options] <package...>'
207+ options: [
208+ HelpFlag{'--noconfirm', 'take the default at every prompt, never read stdin'},
209+ ]
210+ examples: [
211+ HelpExample{'vpac l bash', 'list the files bash installed'},
212+ ]
213+ },
214+ HelpMode{
215+ key: 'o'
216+ name: 'owner'
217+ desc: 'find the installed package that owns a file, or every one that owns a directory'
218+ usage: '[options] <file...>'
219+ options: [
220+ HelpFlag{'-q, --quiet', 'print the package names only'},
221+ ]
222+ examples: [
223+ HelpExample{'vpac o /usr/bin/ls', 'which package owns /usr/bin/ls'},
224+ HelpExample{'vpac o -q /usr/bin/ls', 'only its name'},
225+ HelpExample{'vpac o ls', 'a bare name the current directory lacks is looked up in PATH'},
226+ ]
227+ },
228+ HelpMode{
229+ key: 'd'
230+ name: 'orphans'
231+ desc: 'list packages installed as dependencies that nothing requires'
232+ usage: '[options]'
233+ options: [
234+ HelpFlag{'-t', '-tt also lists the ones something names as an optional dependency'},
235+ ]
236+ examples: [
237+ HelpExample{'vpac d', 'list the orphans'},
238+ HelpExample{'vpac d -tt', 'and the dependencies only an optdepends line keeps'},
239+ ]
240+ },
241+ HelpMode{
242+ key: 'b'
243+ name: 'build'
244+ desc: 'build and install a package from an arbitrary repo'
245+ usage: '[options] <repo...>'
246+ options: [
247+ HelpFlag{'--nopkgbuildconfirm', 'skip the build question; the review is still shown'},
248+ HelpFlag{'--noconfirm', 'answer yes to the install prompts, and refuse to build unless --nopkgbuildconfirm'},
249+ ]
250+ examples: [
251+ HelpExample{'vpac b ~/src/mything', 'build a local checkout, review included, and install it'},
252+ HelpExample{'vpac b https://example.org/mything.git', 'clone the repo under the pkgbuild build dir and install'},
253+ HelpExample{'vpac b -h', 'show the options of the mode'},
254+ ]
255+ },
256+ HelpMode{
257+ key: 'c'
258+ name: 'clean'
259+ desc: 'clean the package cache and the pkgbuild builds'
260+ usage: '[options]'
261+ options: [
262+ HelpFlag{'-c', 'the default clean'},
263+ HelpFlag{'-cc', 'removes every cached package'},
264+ HelpFlag{'-a, --all', 'remove every cached file and every pkgbuild build'},
265+ HelpFlag{'-k, --keep <n>', 'keep the n newest versions of every package'},
266+ HelpFlag{'--keep-current', 'also keep the versions the sync dbs carry'},
267+ HelpFlag{'-p, --print', 'list the files and builds the clean would remove, and remove nothing'},
268+ HelpFlag{'--noconfirm', 'take the default at every prompt, never read stdin'},
269+ ]
270+ examples: [
271+ 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'},
272+ HelpExample{'vpac c -cc', 'remove every cached package'},
273+ HelpExample{'vpac c -k 2', 'keep the two newest versions of every cached package'},
274+ ]
275+ },
276+ HelpMode{
277+ key: 'a'
278+ name: 'autoremove'
279+ desc: 'remove every orphan, and the dependencies that become unneeded'
280+ usage: '[options]'
281+ options: [
282+ HelpFlag{'--noconfirm', 'take the default at every prompt, never read stdin'},
283+ ]
284+ examples: [
285+ HelpExample{'vpac a', 'remove all orphans'},
286+ ]
287+ },
288+ HelpMode{
289+ key: 'k'
290+ name: 'rank'
291+ desc: 'rank mirrors by latency and download speed'
292+ usage: '[options] [os]'
293+ options: [
294+ HelpFlag{'-n, --top <n>', 'show the n fastest mirrors (default 10)'},
295+ HelpFlag{'-w, --write', 'write the ranking to <os>.lip in the mirrors dir (/etc/vpac.d/mirrors), as root if needed'},
296+ HelpFlag{'-m, --mirrorlist', 'print the result as mirrorlist Server lines'},
297+ HelpFlag{'-o, --output <file>', 'write the Server lines to a file, as root if needed'},
298+ HelpFlag{'--stdin', 'rank the mirrors listed on stdin, instead of the os mirror list'},
299+ HelpFlag{'--path <file>', 'file to time for speed, under the mirror root'},
300+ ]
301+ examples: [
302+ HelpExample{'vpac k -n 5', 'the five fastest mirrors of this system'},
303+ HelpExample{'vpac k -w', 'rank and write the config mirror file for this system'},
304+ HelpExample{'vpac k -n 5 cachyos', 'the five fastest CachyOS mirrors'},
305+ HelpExample{'vpac k -m -o /tmp/mirrorlist arch', 'write the fastest Arch mirrors to a file'},
306+ HelpExample{'cat list.txt | vpac k --stdin', 'rank the mirrors in a list, one url per line'},
307+ ]
308+ },
309+ HelpMode{
310+ key: 't'
311+ name: 'tree'
312+ desc: 'show the dependency tree of a package'
313+ usage: '[options] <package...>'
314+ options: [
315+ HelpFlag{'-r, --reverse', 'show what requires the package instead'},
316+ HelpFlag{'-o, --optional', 'include optional dependencies'},
317+ HelpFlag{'-d, --depth <n>', 'show n levels only (default: all)'},
318+ HelpFlag{'--noconfirm', 'take the default at every prompt, never read stdin'},
319+ ]
320+ examples: [
321+ HelpExample{'vpac t -d 2 bash', 'dependencies of bash, two levels deep'},
322+ HelpExample{'vpac t -r glibc', 'packages that require glibc'},
323+ ]
324+ },
325+ HelpMode{
326+ key: 'v'
327+ name: 'verify'
328+ desc: 'check the files of installed packages'
329+ usage: '[options] [package...]'
330+ options: [
331+ HelpFlag{'-k, --checksums', 'also check that backed up config files are unmodified'},
332+ HelpFlag{'-kk, --full', "check every file against the package's mtree: type, owner, mode, link, time, size, sha256"},
333+ HelpFlag{'-D, --db', 'check the local db instead: its files, dependencies, conflicts, shared files'},
334+ HelpFlag{'-DD', "check that every sync package's dependencies resolve"},
335+ ]
336+ examples: [
337+ HelpExample{'vpac v', 'check every installed package'},
338+ HelpExample{'vpac v glibc', 'check one package'},
339+ HelpExample{'vpac v -k', 'also check the backup files'},
340+ HelpExample{'vpac v -kk glibc', 'check every file of glibc; run as root to read root-only files'},
341+ HelpExample{'vpac v -D', 'check the local package database for consistency'},
342+ ]
343+ },
344+ HelpMode{
345+ key: 'f'
346+ name: 'find'
347+ desc: 'find the sync package that provides a file, from the file dbs'
348+ usage: '[options] <path...> | -l <package...>'
349+ options: [
350+ HelpFlag{'-l, --list', 'list the files of a sync package instead'},
351+ HelpFlag{'-y, --refresh', 'refresh the file dbs first (as root)'},
352+ HelpFlag{'-r, --repos <list>', 'comma separated repos to search (default: all)'},
353+ HelpFlag{'-q, --quiet', 'repo/pkg for paths, file paths for -l'},
354+ HelpFlag{'-x, --regex', 'the targets are regular expressions: with a slash matched against paths, without against file names'},
355+ HelpFlag{'--machinereadable', 'one line a file, its repo, package, version and path parted by NUL bytes'},
356+ HelpFlag{'--noconfirm', 'take the default at every prompt, never read stdin'},
357+ ]
358+ examples: [
359+ HelpExample{'vpac f /usr/bin/vlc', 'which sync package provides /usr/bin/vlc'},
360+ HelpExample{'vpac f -l dolphin', 'the files of an uninstalled package'},
361+ HelpExample{"vpac f -x '^usr/bin/vl.*'", 'every package with a file the expression matches'},
362+ HelpExample{'vpac f -y', 'refresh the file dbs first'},
363+ ]
364+ },
365+]
366+
367+// find_mode matches a mode by its short key or its name
368+fn find_mode(name string) ?HelpMode {
369+ for m in help_modes {
370+ if m.key == name || m.name == name {
371+ return m
372+ }
373+ }
374+ return none
375+}
376+
377+// show_help prints a help text, or sends it as a help event
378+fn show_help(text string) {
379+ if ipc_on() {
380+ emit(HelpEvent{
381+ text: text
382+ })
383+ return
384+ }
385+ println(text)
386+}
387+
388+// overview_examples are the overview's examples: some of the modes' own,
389+// named by their command, so each is written once, in its mode
390+const overview_examples = ['vpac s -r linux-lts', 'vpac i patchelf', 'vpac c -k 2', 'vpac t -d 2 bash']
391+
392+// overview_example_rows finds the overview's examples in the modes
393+fn overview_example_rows() []Row {
394+ mut rows := []Row{}
395+ for cmd in overview_examples {
396+ for m in help_modes {
397+ for e in m.examples {
398+ if e.cmd == cmd {
399+ rows << row(e.cmd, e.desc)
400+ }
401+ }
402+ }
403+ }
404+ return rows
405+}
406+
407+fn help_text() string {
408+ mut modes := []Row{}
409+ for m in help_modes {
410+ modes << row(heading(m.key), m.name, m.desc)
411+ }
412+ examples := overview_example_rows()
413+
414+ mut out := []string{}
415+ out << bold_heading('usage') + ' vpac [flags] <mode> [options] [args]'
416+ out << ' --config <file> read this config instead of ${config_path}'
417+ out << ' --eval <blip> run blip after the config, extending it for this run'
418+ out << ' --color <when> auto, always or never: auto styles a terminal only'
419+ out << ' --ui <kind> tty, or ipc: json lines on stdout, answers on stdin'
420+ out << ' --verbose say the housekeeping failures a run otherwise goes on from'
421+ out << ' vpac <mode> -h show the options of a mode'
422+ out << ''
423+ out << bold_heading('modes')
424+ out << table_text(modes, ' ', ' ')
425+ out << ''
426+ out << bold_heading('examples')
427+ out << table_text(examples, ' ', ' ')
428+ return out.join('\n')
429+}
430+
431+// mode_help_text shows one mode's usage, options and examples
432+fn mode_help_text(mode HelpMode) string {
433+ mut out := []string{}
434+ out << '${name_style(mode.name)} - ${mode.desc}'
435+ out << ''
436+ out << 'usage vpac ${mode.key} ${mode.usage}'.trim_right(' ')
437+ if mode.options.len > 0 {
438+ mut rows := []Row{}
439+ for f in mode.options {
440+ rows << row(f.name, f.desc)
441+ }
442+ out << ''
443+ out << bold_heading('options')
444+ out << table_text(rows, ' ', ' ')
445+ }
446+ if mode.name == 'search' || mode.name == 'info' {
447+ out << ''
448+ out << bold_heading('fields')
449+ // as wide as the terminal the help is read on, the way info lays
450+ // its own lists out, and info's fallback where there is none
451+ cols, _ := term.get_terminal_size()
452+ out << wrap_names(pkg_field_names, info_width(cols))
453+ }
454+ if mode.examples.len > 0 {
455+ mut rows := []Row{}
456+ for e in mode.examples {
457+ rows << row(e.cmd, e.desc)
458+ }
459+ out << ''
460+ out << bold_heading('examples')
461+ out << table_text(rows, ' ', ' ')
462+ }
463+ return out.join('\n')
464+}
465+
466+// wrap_names lays the field names out in lines no wider than width, as the
467+// terminal counts width: a styled or multibyte name is as wide as it shows
468+fn wrap_names(names []string, width int) string {
469+ if names.len == 0 {
470+ return ''
471+ }
472+ // the lines are wrap_items', info's own wrapping: here indented by two,
473+ // and a line that goes on ends in its comma, which with the space after
474+ // it is the room kept free of the width
475+ return wrap_items(names, width - 4).map(' ' + it).join(',\n')
476+}
@@ -0,0 +1,126 @@
1+module main
2+
3+import term
4+
5+fn widest(text string) int {
6+ mut w := 0
7+ for line in text.split('\n') {
8+ if visible_width(line) > w {
9+ w = visible_width(line)
10+ }
11+ }
12+ return w
13+}
14+
15+fn test_wrap_names_fits_the_width() {
16+ names := ['name', 'version', 'description', 'architecture', 'url', 'licenses', 'groups', 'provides',
17+ 'depends']
18+ text := wrap_names(names, 30)
19+ assert widest(text) <= 30, text
20+ // every name, in order, once
21+ assert text.split('\n').map(it.trim_space()).join(' ').split(', ').map(it.trim_space()).join(',') == names.join(',')
22+ assert text.starts_with(' name, version,')
23+ assert !text.ends_with(',')
24+}
25+
26+fn test_wrap_names_counts_what_shows() {
27+ // a multibyte name is as wide as its characters: three of these fit a
28+ // line of 22 columns, which bytes (two a character) would have broken
29+ wide := ['ääää', 'öööö', 'üüüü']
30+ assert wrap_names(wide, 22) == ' ääää, öööö, üüüü'
31+ // a styled name is as wide as its text, its escapes take no column
32+ styled := ['name', 'version', 'url'].map(term.bold(it))
33+ assert wrap_names(styled, 23).split('\n').len == 1
34+ // one name wider than the line still gets a line of its own
35+ assert wrap_names(['a-very-long-field-name', 'x'], 10) == ' a-very-long-field-name,\n x'
36+}
37+
38+fn test_overview_examples_are_the_modes_own() {
39+ // every example the overview names is one mode's, found exactly once,
40+ // with that mode's description: renaming it in its mode fails here
41+ rows := overview_example_rows()
42+ assert rows.len == overview_examples.len
43+ text := help_text()
44+ for cmd in overview_examples {
45+ mut found := []string{}
46+ for m in help_modes {
47+ for e in m.examples {
48+ if e.cmd == cmd {
49+ found << e.desc
50+ }
51+ }
52+ }
53+ assert found.len == 1, cmd
54+ assert text.contains(found[0]), cmd
55+ }
56+}
57+
58+// flag_longs are the long names a mode's struct parses, as the command line
59+// spells them
60+fn flag_longs[T]() []string {
61+ mut out := []string{}
62+ $for field in T.fields {
63+ for attr in field.attrs {
64+ if attr.starts_with('long: ') {
65+ out << attr.all_after('long: ').trim_space().replace('_', '-')
66+ }
67+ }
68+ }
69+ return out
70+}
71+
72+fn test_help_names_every_flag_a_mode_parses() {
73+ // a flag the parser takes and the help does not name is a flag nobody
74+ // finds; --help itself is the one every mode has and none lists
75+ mut parsed := map[string][]string{}
76+ parsed['s'] = flag_longs[ConfigSearch]()
77+ parsed['q'] = flag_longs[ConfigInfo]()
78+ parsed['w'] = flag_longs[ConfigWhich]()
79+ parsed['n'] = flag_longs[ConfigDeptest]()
80+ parsed['m'] = flag_longs[ConfigMark]()
81+ parsed['b'] = flag_longs[ConfigBuild]()
82+ parsed['i'] = flag_longs[ConfigInstall]()
83+ parsed['r'] = flag_longs[ConfigRemove]()
84+ parsed['u'] = flag_longs[ConfigUpgrade]()
85+ parsed['l'] = flag_longs[ConfigFiles]()
86+ parsed['o'] = flag_longs[ConfigOwner]()
87+ parsed['d'] = flag_longs[ConfigOrphans]()
88+ parsed['c'] = flag_longs[ConfigClean]()
89+ parsed['t'] = flag_longs[ConfigTree]()
90+ parsed['a'] = flag_longs[ConfigAutoRemove]()
91+ parsed['k'] = flag_longs[ConfigRank]()
92+ parsed['v'] = flag_longs[ConfigVerify]()
93+ parsed['f'] = flag_longs[ConfigFind]()
94+ for m in help_modes {
95+ longs := parsed[m.key] or {
96+ assert false, 'no struct for mode ${m.key}'
97+ continue
98+ }
99+ named := m.options.map(it.name).join(' ') + ' '
100+ for long in longs {
101+ if long == 'help' {
102+ continue
103+ }
104+ assert named.contains('--${long} ') || named.contains('--${long},'), '${m.name}: --${long} is parsed and not in the help'
105+ }
106+ }
107+}
108+
109+fn test_wrap_names_edges() {
110+ // nothing to lay out is no text, one name is one indented line
111+ assert wrap_names([], 30) == ''
112+ assert wrap_names(['name'], 30) == ' name'
113+ // a width nothing fits gives every name its own line, never an empty
114+ // one and never a lost name
115+ for width in [0, 1, 4, -3] {
116+ assert wrap_names(['aa', 'bb', 'cc'], width) == ' aa,\n bb,\n cc', '${width}'
117+ }
118+ // a line that goes on keeps room for its comma within the width
119+ text := wrap_names(['aaaa', 'bbbb', 'cccc', 'dddd'], 16)
120+ assert widest(text) <= 16, text
121+ assert text == ' aaaa, bbbb,\n cccc, dddd', text
122+ // info's wrapping is the same rule without the indent
123+ assert wrap_items(['aaaa', 'bbbb', 'cccc', 'dddd'], 12) == ['aaaa, bbbb', 'cccc, dddd']
124+ assert wrap_items([], 12) == ['']
125+ assert wrap_items(['x'], 0) == ['x']
126+}
@@ -0,0 +1,200 @@
1+module main
2+
3+import alpm
4+
5+// InfoLookup is how info and tree find their targets: the installed
6+// packages first, then the sync dbs, which are only set up — and asked
7+// about their freshness — by the first target that needs them
8+struct InfoLookup {
9+mut:
10+ installed &alpm.List
11+ dbs []&alpm.DB
12+ synced bool
13+}
14+
15+// sync_dbs registers the sync dbs once for all targets
16+fn (mut l InfoLookup) sync_dbs(mut ui TransUI, mut handle &alpm.Handle) ![]&alpm.DB {
17+ if !l.synced {
18+ l.dbs = init_repos(mut handle)!
19+ check_sync_fresh(mut ui, mut handle)!
20+ l.synced = true
21+ }
22+ return l.dbs
23+}
24+
25+// find resolves one target: 'local/name' in the installed packages alone,
26+// 'repo/name' in that sync db alone, a bare name in the installed packages
27+// and then every sync db, like pacman's -Qi with its -Si behind it. a name
28+// may be a dependency string or something provided. what misses gets the
29+// nearest name of the same scope offered; an error is the target's own,
30+// for the caller to report and go on from
31+fn (mut l InfoLookup) find(mut ui TransUI, mut handle &alpm.Handle, raw string) !&alpm.Package {
32+ target := parse_target(raw)
33+ if target.repo in ['', 'local'] {
34+ if p := find_local_target(l.installed, target.name, true) {
35+ return p
36+ }
37+ }
38+ mut scoped := []&alpm.DB{}
39+ if target.repo != 'local' {
40+ scoped = scope_dbs(l.sync_dbs(mut ui, mut handle)!, target.repo)!
41+ if p := find_sync_target(handle, scoped, target.name, target.repo != '') {
42+ return p
43+ }
44+ }
45+ mut names := []string{}
46+ if target.repo in ['', 'local'] {
47+ names << pkg_names(l.installed.pkgs())
48+ }
49+ names << sync_names(scoped)
50+ fixed := did_you_mean(mut ui, target.name, names)!
51+ if target.repo in ['', 'local'] {
52+ if p := l.installed.pkg_find(fixed) {
53+ return p
54+ }
55+ }
56+ return find_repo_pkg(scoped, fixed) or { error('unknown package: "${fixed}"') }
57+}
58+
59+fn info(config ConfigInfo) ! {
60+ need_query(config.query, 'package')!
61+ fields := parse_fields(config.fields, pkg_field_names)!
62+ mut ui := new_trans_ui(noconfirm: config.noconfirm)
63+ mut handle := init_handle(ui)!
64+ defer { handle.release() or { went_on('release the alpm handle', err) } }
65+ defer { ui.stop() }
66+
67+ // package archives on disk are shown directly, pacman's -Qp: loaded, not
68+ // installed. -p says every target is one; without it a single target
69+ // that is a file on disk is still taken for the archive it is
70+ if config.file || (config.query.len == 1 && is_local_pkg_file(config.query[0])) {
71+ info_files(handle, config, fields)
72+ return
73+ }
74+
75+ mut lookup := InfoLookup{
76+ installed: local_pkgcache(handle)!
77+ }
78+ mut printed := 0
79+ for target in config.query {
80+ pkg := lookup.find(mut ui, mut handle, target) or {
81+ target_error(err.msg())
82+ continue
83+ }
84+ if show_pkg(pkg, config, fields, printed == 0) {
85+ printed++
86+ }
87+ }
88+}
89+
90+// show_pkg is one target's answer: its changelog with -c, its fields
91+// otherwise. it says whether anything was shown, which is what the blank
92+// line before the next one goes by
93+fn show_pkg(pkg &alpm.Package, config ConfigInfo, fields []string, first bool) bool {
94+ if config.changelog {
95+ return show_changelog(pkg, first)
96+ }
97+ show_info(info_fields(pkg, fields, config.fields != ''), first)
98+ return true
99+}
100+
101+// show_info shows one package's fields: a table on a terminal, after a blank
102+// line unless it is the first; an info event for a frontend
103+fn show_info(fields []InfoField, first bool) {
104+ if ipc_on() {
105+ emit(InfoEvent{
106+ fields: fields
107+ })
108+ return
109+ }
110+ if !first {
111+ println('')
112+ }
113+ println(info_table(fields))
114+}
115+
116+// pkg_changelog reads a package's changelog whole, in chunks as libalpm
117+// hands it out (an fread into the buffer, 0 at its end). none when the
118+// package carries none: libalpm has one for an installed package and for a
119+// package file, never for a sync db's entry
120+fn pkg_changelog(pkg &alpm.Package) ?string {
121+ fp := pkg.changelog_open()
122+ if fp == unsafe { nil } {
123+ return none
124+ }
125+ mut text := []u8{}
126+ mut buf := []u8{len: 4096}
127+ for {
128+ n := int(pkg.changelog_read(buf.data, u32(buf.len), fp))
129+ if n <= 0 {
130+ break
131+ }
132+ text << buf[..n]
133+ }
134+ pkg.changelog_close(fp) or {
135+ warn('could not close the changelog of ${pkg.get_name()}: ${err.msg()}')
136+ }
137+ return text.bytestr()
138+}
139+
140+// show_changelog is pacman's -Qc: the heading, then the changelog as the
141+// package carries it. a package without one is said and shows nothing,
142+// which pacman does not count as a failure either
143+fn show_changelog(pkg &alpm.Package, first bool) bool {
144+ text := pkg_changelog(pkg) or {
145+ warn('no changelog available for ${pkg.get_name()}')
146+ return false
147+ }
148+ if ipc_on() {
149+ emit(ChangelogEvent{
150+ package: pkg.get_name()
151+ text: text
152+ })
153+ return true
154+ }
155+ if !first {
156+ println('')
157+ }
158+ println(heading('changelog for ${pkg.get_name()}:'))
159+ println(text.trim_right('\n'))
160+ return true
161+}
162+
163+// info_files shows package archives from disk, pacman's -Qp, each loaded
164+// the way pacman's query loads one: whole, with no signature asked for,
165+// since nothing of it is installed. one that does not load is its own
166+// target's error, and the rest are still shown
167+fn info_files(handle &alpm.Handle, config ConfigInfo, fields []string) {
168+ mut printed := 0
169+ for path in config.query {
170+ pkg := handle.pkg_load(path, 1, 0) or {
171+ target_error('could not load ${path}: ${err.msg()}')
172+ continue
173+ }
174+ if show_pkg(pkg, config, fields, printed == 0) {
175+ printed++
176+ }
177+ pkg.free_pkg() or { warn('could not free the package of ${path}: ${err.msg()}') }
178+ }
179+}
180+
181+// which finds the installed package that provides a dependency
182+fn which(config ConfigWhich) ! {
183+ need_query(config.query, 'dependency')!
184+ ui := new_trans_ui()
185+ mut handle := init_handle(ui)!
186+ defer { handle.release() or { went_on('release the alpm handle', err) } }
187+ defer { ui.stop() }
188+
189+ mut pkgcache := local_pkgcache(handle)!
190+
191+ mut printed := 0
192+ for target in config.query {
193+ pkg := pkgcache.find_satisfier(local_target_name(target)) or {
194+ target_error('unknown package: "${target}"')
195+ continue
196+ }
197+ show_info(info_fields(pkg, pkg_field_names, false), printed == 0)
198+ printed++
199+ }
200+}
@@ -0,0 +1,661 @@
1+@[has_globals]
2+module main
3+
4+import os
5+import sync
6+import json2
7+
8+#include <unistd.h>
9+
10+// --ui ipc is vpac spoken to by a program instead of a person: a GUI, a web
11+// UI or a test runs a mode as a child and reads json lines, one event per
12+// line, from its stdout, answering the questions on its stdin. a root child
13+// re-executed through the root provider keeps the same pipes, so it speaks
14+// on them too.
15+// every event is an object whose "type" says what it is; protocol is bumped
16+// when an event changes in a way a reader must know about: a new event
17+// type, a new question kind, a field whose meaning or presence changes, or
18+// a new field a reader has to read to get the answer right. a field that
19+// is only ever left out when empty and adds detail a reader may ignore
20+// rides along without a bump, and is described at its struct. 2: clean's
21+// build_root is absent when no invoker is known, and owner sends one event
22+// per owner of a directory. 3: the select question (a group's members,
23+// answered with a list of indices), clean's unused sync dbs, and the
24+// changelog event. 4: a provides event of an expression or a bare file name
25+// carries files, the paths matched in each entry's package. 5: clean's
26+// build_size_partial, which makes build_size a floor
27+const ipc_protocol = 5
28+
29+// ui_kind is --ui: 'tty' draws for a terminal, 'ipc' speaks the protocol
30+__global ui_kind = 'tty'
31+
32+// ipc_fd is the channel the events go out on, the stdout vpac was given.
33+// fd 1 itself is pointed at stderr once the channel is open, so a plain
34+// print of a mode not yet speaking the protocol lands in the log and never
35+// in the channel
36+__global ipc_fd = 1
37+__global ipc_started = false
38+__global ipc_mu = sync.new_mutex()
39+
40+fn C.dup2(oldfd int, newfd int) int
41+
42+fn C.fcntl(fd int, cmd int, arg int) int
43+
44+fn ipc_on() bool {
45+ return ui_kind == 'ipc'
46+}
47+
48+// ipc_start opens the channel. it runs in the process that does the work,
49+// after the escalation: a re-executed child must find the original fds, and
50+// opens its own channel. the channel is close-on-exec, so the builds and
51+// hooks vpac runs never hold the frontend's pipe open
52+fn ipc_start() {
53+ if ipc_started {
54+ return
55+ }
56+ ipc_started = true
57+ fd := C.dup(1)
58+ if fd < 0 {
59+ // a frontend would read plain text as the protocol: better no run
60+ eprintln(error_text('--ui ipc: could not open the channel on stdout'))
61+ exit(1)
62+ }
63+ if C.fcntl(fd, C.F_SETFD, C.FD_CLOEXEC) < 0 {
64+ // without it, every build and every hook keeps the frontend's pipe
65+ // open: said, since the channel is still good for this run
66+ eprintln('--ui ipc: could not mark the channel close-on-exec')
67+ }
68+ // dup2 answers its new fd (1) on success, so only a negative one is a
69+ // failure: fd 1 otherwise still carries the channel, and a plain print
70+ // of a mode that does not speak the protocol would land there
71+ if C.dup2(2, 1) < 0 {
72+ eprintln(error_text('--ui ipc: could not lead the logs onto stderr'))
73+ exit(1)
74+ }
75+ ipc_fd = fd
76+ // the texts of the events are plain
77+ color_flag = 'never'
78+ emit(HelloEvent{
79+ protocol: ipc_protocol
80+ root: os.geteuid() == 0
81+ })
82+}
83+
84+// emit writes one event as one line. the lock keeps the lines of the
85+// download callbacks and the main thread whole
86+fn emit[T](event T) {
87+ line := json2.encode(event) + '\n'
88+ ipc_mu.lock()
89+ ok := channel_write(line)
90+ ipc_mu.unlock()
91+ if !ok {
92+ // the reader of the channel is gone, so the run is over; stderr
93+ // still reaches a log, where a person may learn why
94+ eprintln('${error_text('the frontend closed the channel')} -- last event: ${line.trim_space()}')
95+ exit(1)
96+ }
97+}
98+
99+// channel_write writes the whole line on the channel, and answers whether it
100+// went out, through write(2)
101+fn channel_write(line string) bool {
102+ return channel_write_to(ipc_fd, line, sys_write)
103+}
104+
105+// WriteFn is write(2) as channel_write_to calls it: what it wrote, and the
106+// errno's code when that is -1. the system's in a run; a test's own to script the
107+// interruptions and the stalls no real channel produces on demand
108+type WriteFn = fn (fd int, buf voidptr, n int) (int, int)
109+
110+fn sys_write(fd int, buf voidptr, n int) (int, int) {
111+ written := int(C.write(fd, buf, n))
112+ return written, if written < 0 { C.errno } else { 0 }
113+}
114+
115+// channel_write_to writes the whole line on fd. os.fd_write gives up without
116+// a word when the reader is gone, and a half-written json line is garbage to
117+// a frontend: every byte is seen out, any failure is reported. a write that
118+// is interrupted is taken again, and a write that answers nothing has made
119+// no progress, so it is a failure too — waiting it out would be an endless
120+// loop for a channel nobody reads
121+fn channel_write_to(fd int, line string, write WriteFn) bool {
122+ str := line.clone()
123+ mut p := unsafe { voidptr(uint(str.str)) }
124+ mut left := str.len
125+ for left > 0 {
126+ written, code := write(fd, p, left)
127+ if written < 0 {
128+ // a signal cut the write short of starting: errno.h's name for
129+ // it on this system, not a number
130+ if code == C.EINTR {
131+ continue
132+ }
133+ return false
134+ }
135+ if written == 0 {
136+ return false
137+ }
138+ left -= written
139+ p = unsafe { voidptr(uint(p) + uint(written)) }
140+ }
141+ return true
142+}
143+
144+// HelpEvent is a help text, the overview or one mode's
145+struct HelpEvent {
146+ kind string = 'help' @[json: 'type']
147+ text string
148+}
149+
150+// HelloEvent opens the stream: the protocol, and whether this process runs
151+// as root (a child the root provider started)
152+struct HelloEvent {
153+ kind string = 'hello' @[json: 'type']
154+ protocol int
155+ root bool
156+}
157+
158+// ExitEvent closes it with the exit status the process is about to have
159+struct ExitEvent {
160+ kind string = 'exit' @[json: 'type']
161+ status int
162+}
163+
164+// ErrorEvent is an error line. target marks the error of one target a query
165+// skipped and went on from; any other error ends the run
166+struct ErrorEvent {
167+ kind string = 'error' @[json: 'type']
168+ msg string
169+ target bool
170+}
171+
172+// MessageEvent is a line of text a mode reports, a result line such as
173+// 'system upgraded' or a warning. error marks one of libalpm's errors, which
174+// is a warning too, for a reader that knows no error flag
175+struct MessageEvent {
176+ kind string = 'message' @[json: 'type']
177+ text string
178+ warning bool
179+ error bool @[omitempty]
180+ // verbose marks a line of the verbose log: a failure of housekeeping
181+ // the run went on from, said only because --verbose asked
182+ verbose bool @[omitempty]
183+}
184+
185+// PhaseEvent is a step of the work: a terminal's spinner. it starts, may be
186+// renamed by another start, and is done
187+struct PhaseEvent {
188+ kind string = 'phase' @[json: 'type']
189+ text string
190+ state string
191+}
192+
193+// ProgressEvent is libalpm's progress through a transaction step: per
194+// package for the package steps (pkg names it, current of total), once for
195+// the whole-transaction checks. vpac's own counted steps use it too
196+struct ProgressEvent {
197+ kind string = 'progress' @[json: 'type']
198+ op string
199+ pkg string @[omitempty]
200+ percent int
201+ current int
202+ total int
203+}
204+
205+// DownloadEvent is a file libalpm downloads: sent as its percent moves (or
206+// every quarter second while it does not), and once more when it is done,
207+// with libalpm's result: 0 fetched, 1 already up to date, -1 failed. a retry
208+// — libalpm moving on to the next mirror — is an event of its own, retry
209+// set: resume says the download goes on from where it stopped, otherwise it
210+// starts over, and its byte counts with it
211+struct DownloadEvent {
212+ kind string = 'download' @[json: 'type']
213+ file string
214+ downloaded i64
215+ total i64
216+ done bool
217+ result int
218+ retry bool @[omitempty]
219+ resume bool @[omitempty]
220+}
221+
222+// TransPkg is one package of a transaction listing. version is what the
223+// transaction installs or removes; old_version the installed one an
224+// install or upgrade replaces, empty for a new package. the sizes are in
225+// bytes: what it downloads, and what it takes on disk once installed
226+struct TransPkg {
227+ name string
228+ version string
229+ old_version string
230+ download_size i64
231+ installed_size i64
232+}
233+
234+// TransactionEvent is the listing a transaction asks its go-ahead for: the
235+// proceed question follows it. action is install, upgrade, remove or
236+// autoremove. a --print preview sends it with preview set, and stops there
237+struct TransactionEvent {
238+ kind string = 'transaction' @[json: 'type']
239+ action string
240+ packages []TransPkg
241+ download_size i64
242+ installed_size i64
243+mut:
244+ preview bool
245+}
246+
247+// PackagesEvent is a titled list of packages shown beside a transaction or a
248+// question: the packages an install removes, the ones an upgrade skips
249+struct PackagesEvent {
250+ kind string = 'packages' @[json: 'type']
251+ title string
252+ packages []TransPkg
253+}
254+
255+// DoneEvent is a committed transaction's result, the last word of every
256+// mode that commits one: what it did — installed, downloaded, removed,
257+// upgraded, marked — and to which packages (install's and remove's targets,
258+// autoremove's and upgrade's whole transaction). a mark says the reason the
259+// packages have now: explicit, depend or unknown. a declined or failed
260+// transaction sends none
261+struct DoneEvent {
262+ kind string = 'done' @[json: 'type']
263+ action string
264+ reason string @[omitempty]
265+ packages []string
266+}
267+
268+// QuestionEvent asks the frontend. question is confirm (yes or no, preset
269+// the answer an empty one takes), proceed (a transaction's go-ahead, preset
270+// true) or choose (one of choices, by index, preset 0). the answer is a line
271+// {"id": id, "answer": true|false|index} on stdin, the same type as preset.
272+// select asks for any number of choices: preset is every index, and the
273+// answer a list of indices, an empty one for none.
274+// under --noconfirm, answer carries the default taken and nothing is read
275+struct QuestionEvent {
276+ kind string = 'question' @[json: 'type']
277+ id int
278+ question string
279+ msg string
280+ preset json2.Any
281+ choices []string @[omitempty]
282+ answer ?json2.Any
283+}
284+
285+// InvalidEvent says an answer line did not answer the question asked; the
286+// question stands and the next line is read
287+struct InvalidEvent {
288+ kind string = 'invalid' @[json: 'type']
289+ id int
290+ msg string
291+}
292+
293+// IpcPrompter asks over the channel: each question is an event with an id,
294+// and its answer the next valid line on stdin. end of input answers as a
295+// terminal's does: no, and the first choice
296+struct IpcPrompter {
297+mut:
298+ noconfirm bool
299+ last_id int
300+}
301+
302+fn (mut p IpcPrompter) confirm(msg string, preset bool) bool {
303+ return p.ask('confirm', msg, if preset { 1 } else { 0 }, []string{}) == 1
304+}
305+
306+fn (mut p IpcPrompter) proceed(msg string) bool {
307+ return p.ask('proceed', msg, 1, []string{}) == 1
308+}
309+
310+fn (mut p IpcPrompter) choose(msg string, choices []string) int {
311+ return p.ask('choose', msg, 0, choices)
312+}
313+
314+// pick asks which of the choices, the select question. the choices were
315+// sent ahead as the listing they are, so the question carries their count
316+// as the preset alone: every index
317+fn (mut p IpcPrompter) pick(msg string, count int) []bool {
318+ p.last_id++
319+ id := p.last_id
320+ all := json2.Any([]json2.Any{len: count, init: json2.Any(index)})
321+ if p.noconfirm {
322+ emit(QuestionEvent{
323+ id: id
324+ question: 'select'
325+ msg: msg
326+ preset: all
327+ answer: all
328+ })
329+ return []bool{len: count, init: true}
330+ }
331+ emit(QuestionEvent{
332+ id: id
333+ question: 'select'
334+ msg: msg
335+ preset: all
336+ })
337+ for {
338+ // end of input selects nothing, as on a terminal
339+ line := stdin_line() or { return []bool{len: count} }
340+ return parse_select_answer(line, id, count) or {
341+ emit(InvalidEvent{
342+ id: id
343+ msg: err.msg()
344+ })
345+ continue
346+ }
347+ }
348+ return []bool{len: count}
349+}
350+
351+// answer_of reads an answer line down to its answer: the object, and the id
352+// of the question asked, are what tell an answer from noise
353+fn answer_of(line string, id int) !json2.Any {
354+ doc := json2.decode[json2.Any](line) or { return error('not json: ${line.trim_space()}') }
355+ if doc !is map[string]json2.Any {
356+ return error('an answer is an object: {"id": id, "answer": answer}')
357+ }
358+ m := doc.as_map()
359+ got := m['id'] or { return error('the answer has no id') }
360+ // json2 hands every json number over as f64: a whole one is an id's
361+ // number, a text is not an id at all
362+ gid := whole_of(got) or { return error("the answer's id is not a number") }
363+ if gid != id {
364+ return error('the question asked is ${id}, not ${gid}')
365+ }
366+ return m['answer'] or { return error('the answer has no answer') }
367+}
368+
369+// parse_select_answer reads the answer to a select question: a list of
370+// indices into its count choices, which may be empty
371+fn parse_select_answer(line string, id int, count int) ![]bool {
372+ answer := answer_of(line, id)!
373+ if answer !is []json2.Any {
374+ return error('question ${id} takes a list of indices, 0 to ${count - 1}')
375+ }
376+ mut picked := []bool{len: count}
377+ for item in answer.as_array() {
378+ n := whole_of(item) or {
379+ return error('question ${id} takes a list of indices, 0 to ${count - 1}')
380+ }
381+ if n < 0 || n >= count {
382+ return error('question ${id} takes a list of indices, 0 to ${count - 1}')
383+ }
384+ picked[n] = true
385+ }
386+ return picked
387+}
388+
389+// ask sends a question and waits for its answer: 1 or 0 for a yes or no,
390+// the index for a choice
391+fn (mut p IpcPrompter) ask(kind string, msg string, preset int, choices []string) int {
392+ p.last_id++
393+ id := p.last_id
394+ // a yes or no travels as a bool, a choice as its index
395+ preset_v := if kind == 'choose' { json2.Any(preset) } else { json2.Any(preset == 1) }
396+ if p.noconfirm {
397+ emit(QuestionEvent{
398+ id: id
399+ question: kind
400+ msg: msg
401+ preset: preset_v
402+ choices: choices
403+ answer: preset_v
404+ })
405+ return preset
406+ }
407+ emit(QuestionEvent{
408+ id: id
409+ question: kind
410+ msg: msg
411+ preset: preset_v
412+ choices: choices
413+ })
414+ for {
415+ // end of input, or a stdin that cannot be read: no, or the first
416+ // choice, as on a terminal. an empty line is a line, and invalid
417+ line := stdin_line() or { return 0 }
418+ answer := parse_answer(line, id, kind, choices.len) or {
419+ emit(InvalidEvent{
420+ id: id
421+ msg: err.msg()
422+ })
423+ continue
424+ }
425+ return answer
426+ }
427+}
428+
429+// parse_answer reads one answer line for question id: a bool for a yes or
430+// no, an index into the choices for a choose. the object, the id and the
431+// answer's type are what tell an answer from noise, and anything else comes
432+// back as the error the asker turns into an invalid event, keeping the
433+// question and reading the next line
434+fn parse_answer(line string, id int, kind string, count int) !int {
435+ answer := answer_of(line, id)!
436+ if kind == 'choose' {
437+ n := whole_of(answer) or { return error('question ${id} takes an index, 0 to ${count - 1}') }
438+ if n < 0 || n >= count {
439+ return error('question ${id} takes an index, 0 to ${count - 1}')
440+ }
441+ return n
442+ }
443+ if answer !is bool {
444+ return error('question ${id} takes true or false')
445+ }
446+ return if answer.bool() { 1 } else { 0 }
447+}
448+
449+// whole_of keeps a json number that is a whole one, like 1 but not 1.5: the
450+// question ids and the choice indices travel as integers, and json2's f64 is
451+// the one type describing them
452+fn whole_of(a json2.Any) ?int {
453+ if a is f64 && a == f64(int(a)) {
454+ return int(a)
455+ }
456+ return none
457+}
458+
459+// report is a result line of a mode: printed on a terminal, a message event
460+// for a frontend
461+fn report(text string) {
462+ if ipc_on() {
463+ emit(MessageEvent{
464+ text: text
465+ })
466+ return
467+ }
468+ println(text)
469+}
470+
471+// advise is a plain line that goes with a warning, the advice after it: on
472+// stderr for a terminal, a message event marked as a warning for a frontend
473+fn advise(text string) {
474+ warning_line(text, text)
475+}
476+
477+// warn is a warning: on stderr for a terminal, a message event marked as a
478+// warning for a frontend
479+fn warn(text string) {
480+ warning_line(text, warning(text))
481+}
482+
483+// verbose_flag is --verbose on the command line, cfg_verbose the config's
484+// (options :verbose true): either turns the verbose log on. the config's is
485+// reset with the config; the flag is the command line's and stays
486+__global verbose_flag = false
487+__global cfg_verbose = false
488+
489+fn verbose_on() bool {
490+ return verbose_flag || cfg_verbose
491+}
492+
493+// went_on is the verbose log's one kind of line: something of the run's
494+// housekeeping failed — a handle's release, a temp dir's removal — and the
495+// run went on, because nothing the user asked for depended on it. without
496+// --verbose it is kept quiet, as it always was; with it the failure is said,
497+// on stderr for a terminal and as a message event marked verbose for a
498+// frontend, so a run that leaves something behind can be asked why
499+fn went_on(what string, err IError) {
500+ if !verbose_on() {
501+ return
502+ }
503+ text := 'could not ${what}: ${err.msg()}'
504+ if ipc_on() {
505+ emit(MessageEvent{
506+ text: text
507+ warning: true
508+ verbose: true
509+ })
510+ return
511+ }
512+ eprintln('verbose: ${text}')
513+}
514+
515+// warning_line is the one way a warning or its advice leaves: the plain
516+// text as a warning message event for a frontend, the terminal's spelling
517+// of it on stderr otherwise
518+fn warning_line(text string, on_terminal string) {
519+ if ipc_on() {
520+ emit(MessageEvent{
521+ text: text
522+ warning: true
523+ })
524+ return
525+ }
526+ eprintln(on_terminal)
527+}
528+
529+// ListingEvent is a package list, search's or orphans': the fields, and for
530+// each package its name and its value of every field, in their order. a
531+// quiet listing sends the names alone; search -g's entries name the group
532+// they were listed for
533+struct ListingEvent {
534+ kind string = 'listing' @[json: 'type']
535+ fields []string
536+ entries []ListEntry
537+}
538+
539+// GroupsEvent lists the groups of the sync dbs, search -g without names
540+struct GroupsEvent {
541+ kind string = 'groups' @[json: 'type']
542+ groups []GroupRef
543+}
544+
545+// InfoEvent is one package as info shows it: every field asked for, its
546+// value as one text, and the items of a list field
547+struct InfoEvent {
548+ kind string = 'info' @[json: 'type']
549+ fields []InfoField
550+}
551+
552+// ChangelogEvent is a package's changelog, info -c: the text as the package
553+// carries it
554+struct ChangelogEvent {
555+ kind string = 'changelog' @[json: 'type']
556+ package string
557+ text string
558+}
559+
560+// FilesEvent is the files of a package: an installed one's under the root
561+// (files), or a sync one's as its file db lists them (find -l, with repo)
562+struct FilesEvent {
563+ kind string = 'files' @[json: 'type']
564+ package string
565+ repo string @[omitempty]
566+ paths []string
567+}
568+
569+// ProvidesEvent is find's answer for one path: the sync packages whose files
570+// hold it, as a listing. a target that matches many files (-x, or a file
571+// name with no slash) also names them: files[i] are the paths matched in the
572+// package of entries[i]
573+struct ProvidesEvent {
574+ kind string = 'provides' @[json: 'type']
575+ path string
576+ fields []string
577+ entries []ListEntry
578+ files [][]string @[omitempty]
579+}
580+
581+// OwnerEvent is an installed package that owns a path: one event for a
582+// file, one per owner for a directory (packages share those), the path
583+// repeated, as pacman -Qo lists them
584+struct OwnerEvent {
585+ kind string = 'owner' @[json: 'type']
586+ path string
587+ package string
588+ version string
589+}
590+
591+// UnsatisfiedEvent is deptest's answer: the dependencies no installed
592+// package satisfies, none when all are
593+struct UnsatisfiedEvent {
594+ kind string = 'unsatisfied' @[json: 'type']
595+ deps []string
596+}
597+
598+// TreeItem is a node of a dependency tree: a package (found), or the
599+// dependency nothing provides (name is then how it was asked for). seen
600+// marks a package expanded elsewhere in the tree, whose branches are there
601+struct TreeItem {
602+ name string
603+ version string
604+ found bool
605+ optional bool
606+ seen bool
607+ children []TreeItem
608+}
609+
610+// TreeEvent is one target's tree: its dependencies, or with reverse what
611+// requires it
612+struct TreeEvent {
613+ kind string = 'tree' @[json: 'type']
614+ reverse bool
615+ root TreeItem
616+}
617+
618+// VerifyEvent is verify's report: a line per finding, problem telling the
619+// ones that count against a package from notes, and how many packages have
620+// problems
621+struct VerifyEvent {
622+ kind string = 'verify' @[json: 'type']
623+ lines []VerifyLine
624+ bad int
625+}
626+
627+// MirrorEvent is one mirror of a ranking: latency in ms, speed in bytes per
628+// second, last_sync as the mirror status gives it
629+struct MirrorEvent {
630+ url string
631+ latency_ms i64
632+ speed f64
633+ last_sync string
634+}
635+
636+// MirrorsEvent is rank's result, the fastest first
637+struct MirrorsEvent {
638+ kind string = 'mirrors' @[json: 'type']
639+ mirrors []MirrorEvent
640+}
641+
642+// CleanEvent is what clean removes: the cached files and the pkgbuild build
643+// dirs, with their sizes, and the sync db files of repos the config no
644+// longer names (dbs). the proceed question follows it, except for a
645+// --print preview, which stops there. build_root is absent when no invoker
646+// is known (root running vpac c itself): the builds were not looked at then,
647+// which an empty root beside an empty list would tell as none found
648+struct CleanEvent {
649+ kind string = 'clean' @[json: 'type']
650+ cache_dirs []string
651+ build_root ?string
652+ files []string
653+ files_size u64
654+ builds []string
655+ build_size u64
656+ // build_size_partial: part of a build could not be read, and build_size
657+ // is a floor, not the size
658+ build_size_partial bool
659+ dbs []string
660+ preview bool
661+}
@@ -0,0 +1,395 @@
1+module main
2+
3+import alpm
4+import json2
5+import os
6+
7+fn test_parse_answer() ! {
8+ // a yes or no takes a bool, a choice an index in range
9+ assert parse_answer('{"id":1,"answer":true}', 1, 'confirm', 0)! == 1
10+ assert parse_answer('{"id":1,"answer":false}\n', 1, 'proceed', 0)! == 0
11+ assert parse_answer('{"id":4,"answer":2}', 4, 'choose', 3)! == 2
12+ assert parse_answer('{"answer":0,"id":4}', 4, 'choose', 3)! == 0
13+ // anything else is refused, and the question stands
14+ for line, why in {
15+ 'garbage': 'not json'
16+ '{"answer":true}': 'no id'
17+ '{"id":2,"answer":true}': 'is 1, not 2'
18+ '{"id":1}': 'no answer'
19+ '{"id":1,"answer":1}': 'true or false'
20+ '{"id":1,"answer":"yes"}': 'true or false'
21+ } {
22+ if _ := parse_answer(line, 1, 'confirm', 0) {
23+ assert false, line
24+ } else {
25+ assert err.msg().contains(why), '${line}: ${err.msg()}'
26+ }
27+ }
28+ for line in ['{"id":1,"answer":3}', '{"id":1,"answer":-1}', '{"id":1,"answer":true}'] {
29+ if _ := parse_answer(line, 1, 'choose', 3) {
30+ assert false, line
31+ }
32+ }
33+}
34+
35+// channel_write lays a whole line on the channel: checked against a real
36+// pipe, and against an fd that refuses writes, where the line's failure
37+// comes back instead of hanging
38+fn test_channel_write() ! {
39+ mut p := os.pipe()!
40+ defer { p.close() }
41+ old := ipc_fd
42+ defer { ipc_fd = old }
43+ ipc_fd = p.write_fd
44+ assert channel_write('{"a":1}\n') == true
45+ line, n := os.fd_read(p.read_fd, 64)
46+ assert line[..n] == '{"a":1}\n'
47+ // a whole line again, after the first
48+ assert channel_write('{}\n') == true
49+ line2, n2 := os.fd_read(p.read_fd, 64)
50+ assert line2[..n2] == '{}\n'
51+}
52+
53+fn test_channel_write_fails_rather_than_hangs() ! {
54+ // a descriptor that cannot be written answers an error at once, the
55+ // closest a test gets to a channel whose reader is gone
56+ tmp := os.join_path(os.vtmp_dir(), 'vpac_test_ipc_ro_${os.getpid()}.txt')
57+ os.write_file(tmp, '')!
58+ os.chmod(tmp, 0o444)!
59+ defer { os.rm(tmp) or {} }
60+ mut f := os.open_file(tmp, 'r')!
61+ defer { f.close() }
62+ old := ipc_fd
63+ defer { ipc_fd = old }
64+ ipc_fd = f.fd
65+ assert !channel_write('{"a":1}\n')
66+}
67+
68+// whole_of keeps a json number that is a whole one: the ids and the choice
69+// indices have to arrive as integers, never as 1.5 or as text
70+fn test_whole_of() {
71+ assert whole_of(json2.Any(f64(1))) or { -100 } == 1
72+ assert whole_of(json2.Any(f64(0))) or { -100 } == 0
73+ assert whole_of(json2.Any(f64(4096))) or { -100 } == 4096
74+ assert whole_of(json2.Any(f64(1.5))) == none
75+ assert whole_of(json2.Any('1')) == none
76+}
77+
78+fn test_event_shapes() {
79+ // the type field names the event; a yes or no travels as a bool, a
80+ // choice as its index, and an answer only under --noconfirm
81+ assert json2.encode(QuestionEvent{
82+ id: 3
83+ question: 'proceed'
84+ msg: 'proceed?'
85+ preset: json2.Any(true)
86+ }) == '{"type":"question","id":3,"question":"proceed","msg":"proceed?","preset":true}'
87+ assert json2.encode(QuestionEvent{
88+ id: 1
89+ question: 'choose'
90+ msg: 'pick'
91+ preset: json2.Any(0)
92+ choices: ['a', 'b']
93+ answer: json2.Any(0)
94+ }) == '{"type":"question","id":1,"question":"choose","msg":"pick","preset":0,"choices":["a","b"],"answer":0}'
95+ // a search -g entry names its group; any other entry has none
96+ assert json2.encode(ListEntry{
97+ name: 'zsh'
98+ values: []
99+ group: 'shells'
100+ }) == '{"name":"zsh","values":[],"group":"shells"}'
101+ assert json2.encode(ListEntry{
102+ name: 'zsh'
103+ values: []
104+ }) == '{"name":"zsh","values":[]}'
105+ assert json2.encode(DoneEvent{
106+ action: 'marked'
107+ reason: 'depend'
108+ packages: ['a']
109+ }) == '{"type":"done","action":"marked","reason":"depend","packages":["a"]}'
110+ assert json2.encode(ProgressEvent{
111+ op: 'removing'
112+ percent: 50
113+ current: 1
114+ total: 2
115+ }) == '{"type":"progress","op":"removing","percent":50,"current":1,"total":2}'
116+}
117+
118+fn test_download_event_shapes() {
119+ // a progress report keeps its shape: no retry fields unless retrying
120+ assert json2.encode(DownloadEvent{
121+ file: 'a.pkg'
122+ downloaded: 10
123+ total: 20
124+ }) == '{"type":"download","file":"a.pkg","downloaded":10,"total":20,"done":false,"result":0}'
125+ assert json2.encode(DownloadEvent{
126+ file: 'a.pkg'
127+ retry: true
128+ }) == '{"type":"download","file":"a.pkg","downloaded":0,"total":0,"done":false,"result":0,"retry":true}'
129+ assert json2.encode(DownloadEvent{
130+ file: 'a.pkg'
131+ retry: true
132+ resume: true
133+ }).ends_with('"retry":true,"resume":true}')
134+}
135+
136+fn test_download_due() {
137+ beat := download_beat
138+ // the first report of a download always goes out
139+ assert download_due(none, 0, 0)
140+ last := DownloadSent{
141+ percent: 3
142+ at: 1000
143+ }
144+ // the percent moved: out, at once
145+ assert download_due(last, 4, 1001)
146+ // the same percent within a beat: held back
147+ assert !download_due(last, 3, 1000 + beat - 1)
148+ // the same percent a beat later: out, so a slow download keeps a frontend
149+ // informed between its percents
150+ assert download_due(last, 3, 1000 + beat)
151+ assert download_due(last, 3, 1000 + 10 * beat)
152+}
153+
154+// downloads_said feeds ipc_download libalpm's own event structs and returns
155+// the events it sent
156+fn downloads_said(feed fn (mut ui TransUI)) ![]map[string]json2.Any {
157+ path := os.join_path(os.vtmp_dir(), 'vpac_test_dl_${os.getpid()}')
158+ mut f := os.create(path)!
159+ defer { os.rm(path) or {} }
160+ old := ipc_fd
161+ ipc_fd = f.fd
162+ mut ui := new_trans_ui()
163+ feed(mut ui)
164+ ipc_fd = old
165+ f.close()
166+ mut out := []map[string]json2.Any{}
167+ for line in os.read_lines(path)! {
168+ out << json2.decode[json2.Any](line)!.as_map()
169+ }
170+ return out
171+}
172+
173+fn test_ipc_download_retry() ! {
174+ events := downloads_said(fn (mut ui TransUI) {
175+ mut p := alpm.DownloadEventProgress{
176+ downloaded: 50
177+ total: 100
178+ }
179+ ipc_download(mut ui, 'a.pkg', .progress, voidptr(&p))
180+ // the same percent right after: held back
181+ ipc_download(mut ui, 'a.pkg', .progress, voidptr(&p))
182+ mut r := alpm.DownloadEventRetry{
183+ resume: 0
184+ }
185+ ipc_download(mut ui, 'a.pkg', .retry, voidptr(&r))
186+ // started over from the next mirror: its first report goes out,
187+ // whatever the percent last said
188+ p.downloaded = 0
189+ ipc_download(mut ui, 'a.pkg', .progress, voidptr(&p))
190+ mut r2 := alpm.DownloadEventRetry{
191+ resume: 1
192+ }
193+ ipc_download(mut ui, 'a.pkg', .retry, voidptr(&r2))
194+ mut c := alpm.DownloadEventCompleted{
195+ total: 100
196+ result: 0
197+ }
198+ ipc_download(mut ui, 'a.pkg', .completed, voidptr(&c))
199+ })!
200+ assert events.len == 5
201+ assert events[0]['downloaded']!.int() == 50
202+ assert events[1]['retry']!.bool()
203+ assert 'resume' !in events[1]
204+ assert events[2]['downloaded']!.int() == 0
205+ assert 'retry' !in events[2]
206+ assert events[3]['retry']!.bool()
207+ assert events[3]['resume']!.bool()
208+ assert events[4]['done']!.bool()
209+}
210+
211+fn test_ipc_download_dedupes_per_file() ! {
212+ events := downloads_said(fn (mut ui TransUI) {
213+ mut a := alpm.DownloadEventProgress{
214+ downloaded: 10
215+ total: 100
216+ }
217+ mut b := alpm.DownloadEventProgress{
218+ downloaded: 10
219+ total: 100
220+ }
221+ // two files at the same percent are two reports, not one held back
222+ ipc_download(mut ui, 'a.pkg', .progress, voidptr(&a))
223+ ipc_download(mut ui, 'b.pkg', .progress, voidptr(&b))
224+ // a's percent moves: out; b stays: held back
225+ a.downloaded = 20
226+ ipc_download(mut ui, 'a.pkg', .progress, voidptr(&a))
227+ ipc_download(mut ui, 'b.pkg', .progress, voidptr(&b))
228+ })!
229+ assert events.map(it['file']!.str()) == ['a.pkg', 'b.pkg', 'a.pkg']
230+}
231+
232+fn test_message_event_shape() {
233+ // a plain message and a warning keep their shape; only libalpm's errors
234+ // carry the error flag, beside the warning one
235+ assert json2.encode(MessageEvent{
236+ text: 'system upgraded'
237+ }) == '{"type":"message","text":"system upgraded","warning":false}'
238+ assert json2.encode(MessageEvent{
239+ text: 'careful'
240+ warning: true
241+ }) == '{"type":"message","text":"careful","warning":true}'
242+ assert json2.encode(MessageEvent{
243+ text: 'broke'
244+ warning: true
245+ error: true
246+ }) == '{"type":"message","text":"broke","warning":true,"error":true}'
247+}
248+
249+// ScriptedWrites is a write(2) that answers from a script: each step is how
250+// many bytes the call takes (at most what it is offered), or -1 with an
251+// errno; what it took is kept, in order
252+@[heap]
253+struct ScriptedWrites {
254+mut:
255+ steps []int
256+ code int
257+ calls int
258+ got []u8
259+}
260+
261+fn (mut w ScriptedWrites) write(_ int, buf voidptr, n int) (int, int) {
262+ if w.calls >= w.steps.len {
263+ // past the script, take everything
264+ w.got << unsafe { (&u8(buf)).vbytes(n) }
265+ w.calls++
266+ return n, 0
267+ }
268+ step := w.steps[w.calls]
269+ w.calls++
270+ if step < 0 {
271+ return -1, w.code
272+ }
273+ take := if step < n { step } else { n }
274+ w.got << unsafe { (&u8(buf)).vbytes(take) }
275+ return take, 0
276+}
277+
278+fn scripted_write(steps []int, code int, line string) (bool, string, int) {
279+ mut w := &ScriptedWrites{
280+ steps: steps
281+ code: code
282+ }
283+ ok := channel_write_to(9, line, fn [mut w] (fd int, buf voidptr, n int) (int, int) {
284+ return w.write(fd, buf, n)
285+ })
286+ return ok, w.got.bytestr(), w.calls
287+}
288+
289+fn test_channel_write_interrupted_is_taken_again() {
290+ // EINTR before anything went out, and again part way: the line still
291+ // goes out whole, in order, nothing twice
292+ ok, got, calls := scripted_write([-1, 3, -1, 2], C.EINTR, '{"a":1}\n')
293+ assert ok
294+ assert got == '{"a":1}\n'
295+ assert calls == 5
296+}
297+
298+fn test_channel_write_short_writes_add_up() {
299+ ok, got, _ := scripted_write([1, 1, 1, 1, 1, 1, 1], 0, '{"b":22}\n')
300+ assert ok
301+ assert got == '{"b":22}\n'
302+}
303+
304+fn test_channel_write_without_progress_fails() {
305+ // a write that answers nothing would loop forever: it is a failure, at
306+ // once, whatever went out before it
307+ ok, got, calls := scripted_write([2, 0], 0, '{"c":3}\n')
308+ assert !ok
309+ assert got == '{"'
310+ assert calls == 2
311+}
312+
313+fn test_channel_write_other_errors_fail() {
314+ // a reader that is gone (EPIPE) is no interruption: no retry
315+ ok, _, calls := scripted_write([-1], 32, '{}\n')
316+ assert !ok
317+ assert calls == 1
318+}
319+
320+fn test_transaction_event_shapes() ! {
321+ // the listing a go-ahead is asked for: its packages whole, the sizes
322+ // summed by whoever built it, and preview said either way so a reader
323+ // never guesses whether a question follows
324+ ev := TransactionEvent{
325+ action: 'upgrade'
326+ packages: [
327+ TransPkg{
328+ name: 'foo'
329+ version: '2.0-1'
330+ old_version: '1.0-1'
331+ download_size: 10
332+ installed_size: 30
333+ },
334+ TransPkg{
335+ name: 'new'
336+ version: '1.0-1'
337+ },
338+ ]
339+ download_size: 10
340+ installed_size: 30
341+ }
342+ m := json2.decode[json2.Any](json2.encode(ev))!.as_map()
343+ assert m['type']!.str() == 'transaction'
344+ assert m['action']!.str() == 'upgrade'
345+ assert m['download_size']!.i64() == 10 && m['installed_size']!.i64() == 30
346+ assert !m['preview']!.bool()
347+ pkgs := m['packages']!.as_array().map(it.as_map())
348+ assert pkgs.len == 2
349+ assert pkgs[0]['name']!.str() == 'foo' && pkgs[0]['old_version']!.str() == '1.0-1'
350+ assert pkgs[0]['download_size']!.i64() == 10 && pkgs[0]['installed_size']!.i64() == 30
351+ // a package that was not installed before has an empty old version,
352+ // present all the same: every package has the same keys
353+ assert pkgs[1]['old_version']!.str() == ''
354+ assert pkgs[1].keys() == pkgs[0].keys()
355+ // a preview is the same event with the mark set
356+ mut preview := ev
357+ preview.preview = true
358+ assert json2.decode[json2.Any](json2.encode(preview))!.as_map()['preview']!.bool()
359+ // a transaction of nothing still carries its list, empty
360+ empty := json2.decode[json2.Any](json2.encode(TransactionEvent{ action: 'remove' }))!.as_map()
361+ assert empty['packages']!.as_array().len == 0
362+ assert empty['download_size']!.i64() == 0
363+ // sizes past 32 bits travel whole
364+ big := json2.decode[json2.Any](json2.encode(TransactionEvent{
365+ action: 'install'
366+ download_size: i64(6) * 1024 * 1024 * 1024
367+ installed_size: i64(20) * 1024 * 1024 * 1024
368+ }))!.as_map()
369+ assert big['download_size']!.i64() == i64(6) * 1024 * 1024 * 1024
370+ assert big['installed_size']!.i64() == i64(20) * 1024 * 1024 * 1024
371+ // the packages event beside it has the same package shape
372+ shown := json2.decode[json2.Any](json2.encode(PackagesEvent{
373+ title: '1 packages to remove:'
374+ packages: [TransPkg{
375+ name: 'old'
376+ version: '1.0-1'
377+ }]
378+ }))!.as_map()
379+ assert shown['type']!.str() == 'packages'
380+ assert shown['packages']!.as_array()[0].as_map().keys() == pkgs[0].keys()
381+ // a provides event names its files only when it has some to name
382+ assert json2.encode(ProvidesEvent{
383+ path: '/usr/bin/x'
384+ fields: ['name']
385+ }) == '{"type":"provides","path":"/usr/bin/x","fields":["name"],"entries":[]}'
386+ assert json2.encode(ProvidesEvent{
387+ path: 'x'
388+ fields: ['name']
389+ entries: [ListEntry{
390+ name: 'p'
391+ values: ['p']
392+ }]
393+ files: [['usr/bin/x']]
394+ }).ends_with(',"files":[["usr/bin/x"]]}')
395+}
@@ -0,0 +1,554 @@
1+@[has_globals]
2+module main
3+
4+import blip.vlib.blip.printer
5+import json2
6+import net.http
7+import os
8+import time
9+
10+// mirror ranking, after rate-mirrors (westandskif/rate-mirrors): gather the
11+// candidates, drop the unusable ones, time one byte for latency, then time a
12+// repo database for speed, and rank by speed. the oses the ranker knows are
13+// in rank_oses; the protocols to rank come from the config
14+
15+// the rank form's filters and sizes, (rank :completion :max-delay :candidates
16+// :retest :top): how complete and how fresh a mirror must be to be probed,
17+// how many of the lowest latencies get the speed test, how many of the
18+// fastest are timed again, and how many are answered when -n names none
19+__global rank_min_completion = 1.0
20+__global rank_max_delay = i64(86400)
21+
22+// rank_parallelism is how many mirrors to probe at once: the rank form's
23+// :parallel when it sets one, else the network's :parallel
24+fn rank_parallelism() int {
25+ return if rank_parallel > 0 { rank_parallel } else { parallel_downloads }
26+}
27+
28+__global rank_speed_candidates = 40
29+__global rank_retest = 5
30+__global rank_top = 10
31+
32+// RankOs is one os the ranker knows. the mirror data comes from the status
33+// api when the os publishes one, else from a plain Server = mirrorlist, which
34+// carries no completion or delay to filter by. repo is the repo whose db the
35+// speed test pulls, named again in the written urls
36+struct RankOs {
37+ status_json string
38+ mirrorlist string
39+ repo string
40+}
41+
42+// default_rank_oses are the oses the ranker knows before the config speaks
43+fn default_rank_oses() map[string]RankOs {
44+ return {
45+ 'artix': RankOs{
46+ status_json: 'https://status.artixlinux.org/mirrors/status/json/'
47+ repo: 'system'
48+ }
49+ 'arch': RankOs{
50+ status_json: 'https://archlinux.org/mirrors/status/json/'
51+ repo: 'core'
52+ }
53+ 'cachyos': RankOs{
54+ mirrorlist: 'https://raw.githubusercontent.com/CachyOS/CachyOS-PKGBUILDS/master/cachyos-mirrorlist/cachyos-mirrorlist'
55+ repo: 'cachyos'
56+ }
57+ }
58+}
59+
60+// rank_oses are the oses the ranker knows: the defaults, and every one the
61+// config's (mirrorlist ...) form defines or redefines. rank_dir is where a
62+// ranking is written for the config to require, (rank :dir)
63+__global rank_oses = default_rank_oses()
64+__global rank_dir = '/etc/vpac.d/mirrors'
65+
66+// rank_os_names spells the known oses for a message, sorted: the text is
67+// the same whatever order the config's forms came in
68+fn rank_os_names() string {
69+ mut names := rank_oses.keys()
70+ names.sort()
71+ return names.join(', ')
72+}
73+
74+// rank_os_name picks the os to rank: the one named on the command line, or
75+// the running system's, read from /etc/os-release
76+fn rank_os_name(query []string) !string {
77+ if query.len > 1 {
78+ return error('rank takes one os: ${rank_os_names()}')
79+ }
80+ if query.len == 1 {
81+ if query[0] !in rank_oses.keys() {
82+ return error('the ranker knows ${rank_os_names()}, not "${query[0]}": define it with (mirrorlist :name ...) in the config')
83+ }
84+ return query[0]
85+ }
86+ text := os.read_file('/etc/os-release') or {
87+ return error('could not read /etc/os-release to detect the os: pass one of ${rank_os_names()}')
88+ }
89+ mut id := ''
90+ mut like := ''
91+ for line in text.split_into_lines() {
92+ if line.starts_with('ID=') {
93+ id = line[3..].trim_space().trim('"\'')
94+ } else if line.starts_with('ID_LIKE=') {
95+ like = line[8..].trim_space().trim('"\'')
96+ }
97+ }
98+ for candidate in [id, ...like.split(' ')] {
99+ if candidate in rank_oses.keys() {
100+ return candidate
101+ }
102+ }
103+ 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')
104+}
105+
106+// rank_write_target is where a ranked os is written for the config to require
107+fn rank_write_target(os_name string) string {
108+ return os.join_path(rank_dir, '${os_name}.lip')
109+}
110+
111+struct StatusMirror {
112+ url string
113+ protocol string
114+ last_sync string
115+ completion_pct ?f64
116+ delay ?i64
117+ active bool
118+ country_code string
119+}
120+
121+struct StatusList {
122+ urls []StatusMirror
123+}
124+
125+// Mirror is a candidate: its full url template, with the repo and arch
126+// placeholders left in place the way the config's mirror files hold them, and
127+// when it last synced
128+struct Mirror {
129+ url string
130+ last_sync string
131+}
132+
133+// probe_url is the concrete url of one mirror's repo db: the template with
134+// the repo and arch substituted in, plus the db file. a path override takes
135+// the mirror root instead, which is where a custom file hangs from
136+fn probe_url(m Mirror, spec RankOs, override string) string {
137+ if override != '' {
138+ return m.url.all_before('$') + override
139+ }
140+ return m.url.replace('$repo', spec.repo).replace('$arch', arch) + '/${spec.repo}.db'
141+}
142+
143+fn with_slash(url string) string {
144+ return if url.ends_with('/') { url } else { url + '/' }
145+}
146+
147+// timed_fetch fetches one url with the rank timeout on both directions, and
148+// hands back the body: it is what the ranker asks of the network, from the
149+// mirror status on to the mirrorlists, since a stalled dns or a captive
150+// portal would otherwise visit its hang on the ranking
151+fn timed_fetch(url string, what string) !string {
152+ return http_text(url, rank_timeout, what, url)
153+}
154+
155+// http_text is one GET bounded by a timeout, in seconds, on both
156+// directions, answering the body of an answer that succeeded. what names
157+// the fetch and from the server in the error, so a refusal is told from a
158+// stall. the ranker's fetches and the pkgbuild rpc both go through it
159+fn http_text(url string, seconds int, what string, from string) !string {
160+ mut req := http.Request{
161+ url: url
162+ read_timeout: seconds * time.second
163+ write_timeout: seconds * time.second
164+ }
165+ resp := req.do() or { return error('${what} failed: ${err}') }
166+ if resp.status_code < 200 || resp.status_code >= 300 {
167+ return error('${what} failed: http ${resp.status_code} from ${from}')
168+ }
169+ return resp.body
170+}
171+
172+// fetch_status_mirrors reads an os's mirror status and keeps the mirrors that
173+// are usable: active, on a configured protocol, fully synced, recently synced,
174+// with a known country
175+fn fetch_status_mirrors(os_name string, spec RankOs) ![]Mirror {
176+ body := timed_fetch(spec.status_json, 'fetching the ${os_name} mirror status')!
177+ status := json2.decode[StatusList](body) or {
178+ return error('could not read the ${os_name} mirror status: ${err.msg()}')
179+ }
180+ mut out := []Mirror{}
181+ for m in status.urls {
182+ completion := m.completion_pct or { continue }
183+ delay := m.delay or { continue }
184+ if m.active && m.protocol in cfg_protocols && completion >= rank_min_completion
185+ && delay <= rank_max_delay && m.country_code != '' {
186+ // the status api gives the mirror root; the repo layout of the os
187+ // completes it to the template the config's mirror files hold
188+ out << Mirror{
189+ url: with_slash(m.url) + '$repo/os/$arch'
190+ last_sync: m.last_sync
191+ }
192+ }
193+ }
194+ return out
195+}
196+
197+// fetch_mirrorlist reads a plain Server = list, for the oses that publish no
198+// status api: fetched, or read from the disk when the config names a path
199+fn fetch_mirrorlist(spec RankOs) ![]Mirror {
200+ if spec.mirrorlist.starts_with('/') {
201+ text := os.read_file(spec.mirrorlist) or {
202+ return error('could not read the mirrorlist ${spec.mirrorlist}: ${err.msg()}')
203+ }
204+ return parse_mirrors(text)
205+ }
206+ body := timed_fetch(spec.mirrorlist, 'fetching the mirrorlist')!
207+ return parse_mirrors(body)
208+}
209+
210+// parse_mirrors reads 'Server = url' lines or bare urls, one per line, as the
211+// mirrorlists write them. the line already carries the os's repo layout, so
212+// it is kept whole
213+fn parse_mirrors(text string) []Mirror {
214+ mut out := []Mirror{}
215+ mut seen := map[string]bool{}
216+ for line in text.split_into_lines() {
217+ mut s := line.trim_space()
218+ if s.starts_with('Server = ') {
219+ s = s.all_after('Server = ').trim_space()
220+ }
221+ if s.starts_with('#') || !(s.starts_with('https://') || s.starts_with('http://')) {
222+ continue
223+ }
224+ if seen[s] {
225+ continue
226+ }
227+ seen[s] = true
228+ out << Mirror{
229+ url: s
230+ }
231+ }
232+ return out
233+}
234+
235+// stdin_text reads stdin to its end, the lines joined again. a read error is
236+// an error here, not an end: a mirror list cut short must not rank as the
237+// whole of it
238+fn stdin_text() !string {
239+ mut lines := []string{}
240+ for {
241+ lines << stdin_line() or {
242+ if err is StdinEnd {
243+ break
244+ }
245+ return err
246+ }
247+ }
248+ return lines.join('\n')
249+}
250+
251+// timed_get fetches a url and returns the milliseconds it took and the size
252+// of the answer. range asks for the first byte only, which measures latency.
253+// the timeout comes from the config, and it bounds the probe twice over: each
254+// read and write on its own, and the answer as a whole. the socket timeouts
255+// alone start over with every read, so a mirror that trickles its db a few
256+// bytes at a time would hold a speed probe for as long as it cared to; the
257+// deadline is looked at on each chunk that arrives, and an answer still
258+// arriving past it is the probe's failure
259+fn timed_get(url string, range bool) !(i64, int) {
260+ limit := rank_timeout
261+ deadline := time.now().add(limit * time.second)
262+ mut req := http.Request{
263+ url: url
264+ read_timeout: limit * time.second
265+ write_timeout: limit * time.second
266+ on_progress: fn [deadline, limit] (_ &http.Request, _ []u8, _ u64) ! {
267+ if time.now() > deadline {
268+ return error('no whole answer within ${limit}s')
269+ }
270+ }
271+ }
272+ if range {
273+ req.header.add_custom('Range', 'bytes=0-0')!
274+ }
275+ start := time.now()
276+ resp := req.do()!
277+ // an answer that needs no body — a 404, a 403 — is a mirror that does
278+ // not serve the repo db: a probe without body size is ranked on air
279+ // unless the status is turned into the probe's failure
280+ if resp.status_code < 200 || resp.status_code >= 300 {
281+ return error('http ${resp.status_code} from ${url}')
282+ }
283+ return (time.now() - start).milliseconds(), resp.body.len
284+}
285+
286+fn probe_latency(m Mirror, spec RankOs, override string) Probe {
287+ ms, _ := timed_get(probe_url(m, spec, override), true) or {
288+ return Probe{
289+ url: m.url
290+ }
291+ }
292+ return timed_probe(m.url, ms, 0, false)
293+}
294+
295+fn probe_speed(m Mirror, spec RankOs, override string) Probe {
296+ ms, bytes := timed_get(probe_url(m, spec, override), false) or {
297+ return Probe{
298+ url: m.url
299+ }
300+ }
301+ return timed_probe(m.url, ms, bytes, true)
302+}
303+
304+// timed_probe is a probe's result out of what the timed request measured:
305+// the latency always, and with speed the bytes a second of a whole fetch —
306+// one that brought no bytes failed, and one quicker than the clock's
307+// millisecond counts as one, never a division by zero
308+fn timed_probe(url string, ms i64, bytes int, speed bool) Probe {
309+ if !speed {
310+ return Probe{
311+ url: url
312+ latency_ms: ms
313+ ok: true
314+ }
315+ }
316+ if bytes <= 0 {
317+ return Probe{
318+ url: url
319+ }
320+ }
321+ elapsed := if ms <= 0 { 1 } else { ms }
322+ return Probe{
323+ url: url
324+ latency_ms: ms
325+ speed: f64(bytes) / (f64(elapsed) / 1000.0)
326+ ok: true
327+ }
328+}
329+
330+// Probe is the result of testing one mirror
331+struct Probe {
332+ url string
333+ latency_ms i64
334+ speed f64
335+ ok bool
336+}
337+
338+// ProbeFn measures one mirror, the os and the path override closed over. it
339+// answers a Probe on every path — a failure is a Probe that is not ok — and
340+// that is what lets probe_batch count on one answer per mirror
341+type ProbeFn = fn (Mirror) Probe
342+
343+// probe_batch tests every mirror, rank_parallelism() at a time, and advances
344+// the bar by each finished probe. quiet draws no bar, so the output can be
345+// piped. the answers come back in the order they finish, not the input's
346+fn probe_batch(mut ui TransUI, label string, mirrors []Mirror, probe ProbeFn, quiet bool) []Probe {
347+ mut out := []Probe{cap: mirrors.len}
348+ if mirrors.len == 0 {
349+ return out
350+ }
351+ mut bar := unsafe { &Meter(nil) }
352+ if !quiet {
353+ bar = ui.meter(i64(mirrors.len), label)
354+ bar.start()
355+ }
356+ // a parallelism that slipped past the config's floor would start no
357+ // worker at all: one at a time is the least
358+ conc := if rank_parallelism() < 1 { 1 } else { rank_parallelism() }
359+ workers := if conc < mirrors.len { conc } else { mirrors.len }
360+ // the whole batch is queued, then the queue closed: a worker that finds
361+ // it drained is done. a pool rather than slots of conc means a slow probe
362+ // holds back only its own worker, not the next slot's fast ones
363+ jobs := chan Mirror{cap: mirrors.len}
364+ for m in mirrors {
365+ jobs <- m
366+ }
367+ jobs.close()
368+ // the answers channel holds a whole batch, so a worker never waits on the
369+ // collector to hand its answer over
370+ answers := chan Probe{cap: mirrors.len}
371+ for _ in 0 .. workers {
372+ spawn probe_worker(jobs, answers, probe)
373+ }
374+ // one answer per mirror, each sent by the worker that took it: the probe
375+ // answers on every path, and a panic in any thread ends the process
376+ // rather than stranding this loop. a probe that hangs is bounded by the
377+ // network's own timeouts (rank_timeout on read and write, the net
378+ // module's on connect) and by timed_get's deadline on the whole answer
379+ for _ in 0 .. mirrors.len {
380+ out << <-answers
381+ if !quiet {
382+ bar.add(i64(1))
383+ }
384+ }
385+ return out
386+}
387+
388+// probe_worker measures mirrors until the queue runs dry. the probe runs on
389+// this thread: the arguments of a spawned call are evaluated by the caller,
390+// so spawning the send of a probe's result runs every probe on the collector,
391+// one after another
392+fn probe_worker(jobs chan Mirror, answers chan Probe, probe ProbeFn) {
393+ for {
394+ m := <-jobs or { return }
395+ answers <- probe(m)
396+ }
397+}
398+
399+fn speed_mib(bytes_per_sec f64) string {
400+ return '${bytes_per_sec / 1048576.0:.2f} MiB/s'
401+}
402+
403+fn sync_age(last_sync string) string {
404+ if last_sync == '' {
405+ return '-'
406+ }
407+ synced := time.parse_rfc3339(last_sync) or { return '-' }
408+ hours := (time.now().unix() - synced.unix()) / 3600
409+ return '${hours}h ago'
410+}
411+
412+// mirrors_lip is the blip file of the ranked urls: mirrors/<os>.lip defines
413+// mirrors-<os>, the way repos.lip expects. each url is a string literal
414+// escaped by blip's own printer: the urls come from the network and the file
415+// is config that vpac runs as root, so a quote in a url must stay inside its
416+// string
417+fn mirrors_lip(os_name string, urls []string, date string) string {
418+ var := 'mirrors-${os_name}'
419+ mut content := '; mirrors for ${os_name}, ranked by vpac k -w on ${date}\n'
420+ content += '(unless (defined? ${var}) (define ${var} []))\n'
421+ content += '(array-append! ${var} [${urls.map(printer.quote_string(it)).join(' ')}])\n'
422+ return content
423+}
424+
425+// write_config_mirrors writes the ranked urls as the blip file the config
426+// requires
427+fn write_config_mirrors(os_name string, urls []string) !string {
428+ target := rank_write_target(os_name)
429+ os.mkdir_all(os.dir(target))!
430+ os.write_file(target, mirrors_lip(os_name, urls, time.now().custom_format('YYYY-MM-DD')))!
431+ return target
432+}
433+
434+// Ranked is one mirror of a ranking: its probe, and when it last synced as
435+// the mirror status says ('' when it is not known)
436+struct Ranked {
437+ Probe
438+ last_sync string
439+}
440+
441+// rank_mirrors measures the mirrors of an os and returns the best of them,
442+// at most config.top, fastest first. the probes draw on the ui unless the
443+// result goes to a file or a mirrorlist
444+fn rank_mirrors(mut ui TransUI, os_name string, config ConfigRank) ![]Ranked {
445+ spec := rank_oses[os_name]
446+ mirrors := if config.stdin {
447+ parse_mirrors(stdin_text()!)
448+ } else if spec.status_json != '' {
449+ fetch_status_mirrors(os_name, spec)!
450+ } else {
451+ fetch_mirrorlist(spec)!
452+ }
453+ if mirrors.len == 0 {
454+ return error('no usable mirrors to rank')
455+ }
456+ mut sync_of := map[string]string{}
457+ for m in mirrors {
458+ sync_of[m.url] = m.last_sync
459+ }
460+
461+ quiet := config.mirrorlist || config.output != ''
462+ override := config.path
463+ mut latency := probe_batch(mut ui, 'latency', mirrors, fn [spec, override] (m Mirror) Probe {
464+ return probe_latency(m, spec, override)
465+ }, quiet).filter(it.ok)
466+ latency.sort(a.latency_ms < b.latency_ms)
467+ if latency.len > rank_speed_candidates {
468+ latency = latency[..rank_speed_candidates].clone()
469+ }
470+ candidates := latency.map(Mirror{
471+ url: it.url
472+ last_sync: sync_of[it.url] or { '' }
473+ })
474+
475+ mut results := probe_batch(mut ui, 'speed', candidates, fn [spec, override] (m Mirror) Probe {
476+ return probe_speed(m, spec, override)
477+ }, quiet).filter(it.ok)
478+ results.sort(a.speed > b.speed)
479+
480+ // the best few are measured again, one at a time, and averaged, so one
481+ // lucky or unlucky transfer does not decide the order
482+ for i in 0 .. if results.len < rank_retest { results.len } else { rank_retest } {
483+ again := probe_speed(Mirror{ url: results[i].url }, spec, config.path)
484+ if again.ok {
485+ results[i] = Probe{
486+ url: results[i].url
487+ latency_ms: results[i].latency_ms
488+ speed: (results[i].speed + again.speed) / 2.0
489+ ok: true
490+ }
491+ }
492+ }
493+ results.sort(a.speed > b.speed)
494+ ui.stop()
495+
496+ if results.len == 0 {
497+ return error('no mirror answered the speed test')
498+ }
499+ top := if results.len < config.top { results.len } else { config.top }
500+ return results[..top].map(Ranked{
501+ Probe: it
502+ last_sync: sync_of[it.url] or { '' }
503+ })
504+}
505+
506+// rank ranks the mirrors, then writes them where config says, or prints them
507+fn rank(config ConfigRank) ! {
508+ os_name := rank_os_name(config.query)!
509+ mut ui := new_trans_ui()
510+ defer {
511+ ui.stop()
512+ }
513+ ranked := rank_mirrors(mut ui, os_name, config)!
514+
515+ urls := ranked.map(it.url)
516+ if config.write {
517+ target := write_config_mirrors(os_name, urls)!
518+ report('wrote ${urls.len} mirrors to ${target}')
519+ }
520+ // a frontend gets the ranking itself, and formats it as it needs: the
521+ // mirrorlist and output forms shape the printable text, which under
522+ // --ui ipc lands in the log anyway, so the event goes out before
523+ // whatever those flags do with the result
524+ if ipc_on() {
525+ emit(MirrorsEvent{
526+ mirrors: ranked.map(MirrorEvent{
527+ url: it.url
528+ latency_ms: it.latency_ms
529+ speed: it.speed
530+ last_sync: it.last_sync
531+ })
532+ })
533+ }
534+ if config.output != '' {
535+ os.write_file(config.output, urls.map('Server = ${it}').join('\n') + '\n')!
536+ report('wrote ${urls.len} mirrors to ${config.output}')
537+ return
538+ }
539+ if config.mirrorlist {
540+ println(urls.map('Server = ${it}').join('\n'))
541+ return
542+ }
543+ if ipc_on() {
544+ return
545+ }
546+ // sync paints the finished spinner frames before the ranking prints
547+ ui.sync()
548+ mut rows := []Row{}
549+ for i, m in ranked {
550+ rows << row('${i + 1}', m.url.all_before('$'), '${m.latency_ms} ms', speed_mib(m.speed),
551+ sync_age(m.last_sync))
552+ }
553+ println(table_text(rows, '', ' '))
554+}
@@ -0,0 +1,314 @@
1+module main
2+
3+import blip.vlib.blip.machine
4+import net
5+import sync
6+import time
7+
8+// mirrors_machine is a blip machine set up the way load_config sets one up,
9+// for what a mirrors file needs
10+fn mirrors_machine() &machine.Machine {
11+ mut m := machine.new_standalone(&QuietConfigHost{})
12+ m.prims['array-append!'] = prim_array_append
13+ return m
14+}
15+
16+fn mirrors_read(mut m machine.Machine, var string) ![]string {
17+ return m.run_str(var)!.as_vector().data.map(it.as_string())
18+}
19+
20+fn test_mirrors_lip_round_trip() ! {
21+ urls := [
22+ 'https://ok.example/' + r'$repo/os/$arch',
23+ 'https://quote.example/a"b',
24+ 'https://backslash.example/a\\b',
25+ 'https://newline.example/a\nb',
26+ 'https://tab.example/a\tb',
27+ // closes its string and the form, then defines something
28+ 'https://x.example/"]) (define pwned 1) (array-append! mirrors-arch ["',
29+ ]
30+ text := mirrors_lip('arch', urls, '2026-11-08')
31+ assert text.starts_with('; mirrors for arch, ranked by vpac k -w on 2026-11-08\n')
32+ mut m := mirrors_machine()
33+ m.run_str(text)!
34+ assert mirrors_read(mut m, 'mirrors-arch')! == urls
35+ if _ := m.run_str('pwned') {
36+ assert false, 'a url ran as code'
37+ }
38+}
39+
40+fn test_mirrors_lip_appends() ! {
41+ // the file adds to a list the config may have started already
42+ mut m := mirrors_machine()
43+ m.run_str('(define mirrors-arch ["https://first.example/"])')!
44+ m.run_str(mirrors_lip('arch', ['https://second.example/'], 'today'))!
45+ assert mirrors_read(mut m, 'mirrors-arch')! == ['https://first.example/', 'https://second.example/']
46+}
47+
48+fn test_mirrors_lip_empty() ! {
49+ mut m := mirrors_machine()
50+ m.run_str(mirrors_lip('artix', [], 'today'))!
51+ assert mirrors_read(mut m, 'mirrors-artix')!.len == 0
52+}
53+
54+// ProbeTally is what a fake probe records across the batch's threads: how
55+// many ran at once, at the most, and which mirrors it was handed
56+@[heap]
57+struct ProbeTally {
58+mut:
59+ mu &sync.Mutex = sync.new_mutex()
60+ in_flight int
61+ peak int
62+ seen []string
63+ // stalled is set by the first probe that gave up waiting for company,
64+ // so a serial batch fails the test in one wait rather than one per mirror
65+ stalled bool
66+}
67+
68+fn (mut t ProbeTally) enter(url string) {
69+ t.mu.lock()
70+ t.in_flight++
71+ if t.in_flight > t.peak {
72+ t.peak = t.in_flight
73+ }
74+ t.seen << url
75+ t.mu.unlock()
76+}
77+
78+fn (mut t ProbeTally) leave() {
79+ t.mu.lock()
80+ t.in_flight--
81+ t.mu.unlock()
82+}
83+
84+// wait_for_peak holds a probe until n probes have been in flight at once, or
85+// a second has passed: probes that run one after another never get there
86+fn (mut t ProbeTally) wait_for_peak(n int) {
87+ deadline := time.now().add(time.second)
88+ for {
89+ t.mu.lock()
90+ done := t.peak >= n || t.stalled
91+ t.mu.unlock()
92+ if done {
93+ return
94+ }
95+ if time.now() > deadline {
96+ t.mu.lock()
97+ t.stalled = true
98+ t.mu.unlock()
99+ return
100+ }
101+ time.sleep(time.millisecond)
102+ }
103+}
104+
105+fn probe_mirrors(n int) []Mirror {
106+ return []Mirror{len: n, init: Mirror{
107+ url: 'https://m${index}.example/'
108+ }}
109+}
110+
111+// probe_batch_with runs a quiet batch with the rank parallelism set to conc,
112+// the globals it reads put back after
113+fn probe_batch_with(conc int, mirrors []Mirror, probe ProbeFn) []Probe {
114+ saved_rank, saved_net := rank_parallel, parallel_downloads
115+ defer {
116+ rank_parallel, parallel_downloads = saved_rank, saved_net
117+ }
118+ rank_parallel, parallel_downloads = conc, conc
119+ mut ui := new_trans_ui()
120+ return probe_batch(mut ui, 'test', mirrors, probe, true)
121+}
122+
123+fn test_probe_batch_answers_once_per_mirror() {
124+ mirrors := probe_mirrors(13)
125+ mut tally := &ProbeTally{}
126+ // every other mirror fails: a failed probe is still its mirror's answer
127+ out := probe_batch_with(4, mirrors, fn [mut tally] (m Mirror) Probe {
128+ tally.enter(m.url)
129+ tally.leave()
130+ return Probe{
131+ url: m.url
132+ ok: m.url.all_after('//m').all_before('.').int() % 2 == 0
133+ }
134+ })
135+ assert out.len == mirrors.len
136+ mut got := out.map(it.url)
137+ got.sort()
138+ mut want := mirrors.map(it.url)
139+ want.sort()
140+ assert got == want
141+ assert out.filter(it.ok).len == 7
142+ tally.seen.sort()
143+ assert tally.seen == want
144+}
145+
146+fn test_probe_batch_probes_run_in_parallel() {
147+ // the probes must overlap, conc of them at once and never more: a probe
148+ // evaluated by the collector before its spawn runs the batch serially
149+ mirrors := probe_mirrors(9)
150+ mut tally := &ProbeTally{}
151+ out := probe_batch_with(3, mirrors, fn [mut tally] (m Mirror) Probe {
152+ tally.enter(m.url)
153+ tally.wait_for_peak(3)
154+ tally.leave()
155+ return Probe{
156+ url: m.url
157+ ok: true
158+ }
159+ })
160+ assert out.len == 9
161+ assert !tally.stalled, 'the probes ran one at a time'
162+ assert tally.peak == 3
163+}
164+
165+fn test_probe_batch_zero_parallelism_still_probes() {
166+ // a parallelism of 0 slipped past the config's floor starts one worker,
167+ // not none (which would leave the collector waiting forever)
168+ mirrors := probe_mirrors(5)
169+ mut tally := &ProbeTally{}
170+ out := probe_batch_with(0, mirrors, fn [mut tally] (m Mirror) Probe {
171+ tally.enter(m.url)
172+ tally.leave()
173+ return Probe{
174+ url: m.url
175+ ok: true
176+ }
177+ })
178+ assert out.len == 5
179+ assert tally.peak == 1
180+}
181+
182+fn test_probe_batch_more_workers_than_mirrors() {
183+ mirrors := probe_mirrors(2)
184+ out := probe_batch_with(16, mirrors, fn (m Mirror) Probe {
185+ return Probe{
186+ url: m.url
187+ ok: true
188+ }
189+ })
190+ assert out.len == 2
191+}
192+
193+fn test_probe_batch_empty() {
194+ out := probe_batch_with(4, []Mirror{}, fn (m Mirror) Probe {
195+ assert false, 'no mirror to probe'
196+ return Probe{}
197+ })
198+ assert out.len == 0
199+}
200+
201+// trickle_mirror answers every connection on the listener with a body of
202+// total bytes, sent one byte each pause: each read lands well inside the
203+// socket timeout while the whole answer takes total pauses. it ends when the
204+// listener closes, and a client that hangs up ends its own connection
205+fn trickle_mirror(mut l net.TcpListener, total int, pause time.Duration) {
206+ for {
207+ mut conn := l.accept() or { return }
208+ spawn trickle_answer(mut conn, total, pause)
209+ }
210+}
211+
212+fn trickle_answer(mut conn net.TcpConn, total int, pause time.Duration) {
213+ defer {
214+ conn.close() or {}
215+ }
216+ mut request := []u8{len: 4096}
217+ conn.read(mut request) or { return }
218+ conn.write_string('HTTP/1.1 200 OK\r\nContent-Length: ${total}\r\nConnection: close\r\n\r\n') or {
219+ return
220+ }
221+ for _ in 0 .. total {
222+ conn.write_string('x') or { return }
223+ time.sleep(pause)
224+ }
225+}
226+
227+// trickle_url starts a trickling mirror on a port of its own and answers its
228+// url with the listener, which the test closes
229+fn trickle_url(total int, pause time.Duration) !(&net.TcpListener, string) {
230+ mut l := net.listen_tcp(.ip, '127.0.0.1:0')!
231+ port := l.addr()!.port()!
232+ spawn trickle_mirror(mut l, total, pause)
233+ return l, 'http://127.0.0.1:${port}/core.db'
234+}
235+
236+// a mirror that keeps every read short of the socket timeout but the whole
237+// answer past the rank timeout fails the probe, close to the timeout and not
238+// at the answer's end (some six seconds here)
239+fn test_timed_get_bounds_the_whole_answer() ! {
240+ saved := rank_timeout
241+ defer {
242+ rank_timeout = saved
243+ }
244+ rank_timeout = 1
245+ mut l, url := trickle_url(30, 200 * time.millisecond)!
246+ defer {
247+ l.close() or {}
248+ }
249+ for range in [false, true] {
250+ start := time.now()
251+ if _, bytes := timed_get(url, range) {
252+ assert false, 'a trickled answer of ${bytes} bytes passed the timeout (range ${range})'
253+ }
254+ took := time.now() - start
255+ assert took < 3 * time.second, 'the probe took ${took} (range ${range})'
256+ }
257+}
258+
259+// an answer that is whole within the timeout is measured as before
260+fn test_timed_get_measures_a_prompt_answer() ! {
261+ saved := rank_timeout
262+ defer {
263+ rank_timeout = saved
264+ }
265+ rank_timeout = 5
266+ mut l, url := trickle_url(4, time.millisecond)!
267+ defer {
268+ l.close() or {}
269+ }
270+ _, bytes := timed_get(url, false)!
271+ assert bytes == 4
272+}
273+
274+fn test_rank_os_names_are_sorted() {
275+ // the message spells the oses the same way whatever order the config's
276+ // mirrorlist forms defined them in; one os and none are spelled too
277+ saved := rank_oses.clone()
278+ defer { rank_oses = saved.clone() }
279+ rank_oses = map[string]RankOs{}
280+ assert rank_os_names() == ''
281+ rank_oses['zeta'] = RankOs{}
282+ assert rank_os_names() == 'zeta'
283+ rank_oses['arch'] = RankOs{}
284+ rank_oses['Mid'] = RankOs{}
285+ rank_oses['artix'] = RankOs{}
286+ assert rank_os_names() == 'Mid, arch, artix, zeta'
287+}
288+
289+fn test_timed_probe_edges() {
290+ // latency alone: the bytes are not looked at
291+ lat := timed_probe('u', 12, 0, false)
292+ assert lat.ok && lat.latency_ms == 12 && lat.speed == 0.0 && lat.url == 'u'
293+ // a zero latency is still a mirror that answered
294+ assert timed_probe('u', 0, 0, false).ok
295+ // speed: bytes over seconds
296+ sp := timed_probe('u', 500, 1000, true)
297+ assert sp.ok && sp.speed == 2000.0 && sp.latency_ms == 500
298+ // a fetch that brought nothing failed, whatever it took
299+ assert !timed_probe('u', 500, 0, true).ok
300+ assert !timed_probe('u', 0, 0, true).ok
301+ // quicker than a millisecond, or a clock that went back, is one
302+ // millisecond: a speed, not a division by zero
303+ assert timed_probe('u', 0, 10, true).speed == 10000.0
304+ assert timed_probe('u', -5, 10, true).speed == 10000.0
305+}
306+
307+fn test_http_text_names_the_refusal() ! {
308+ // nothing listens here: the fetch fails as the fetch it was called
309+ if body := http_text('http://127.0.0.1:1/x', 1, 'fetching the test', 'the test server') {
310+ assert false, 'port 1 answered: ${body}'
311+ } else {
312+ assert err.msg().starts_with('fetching the test failed: '), err.msg()
313+ }
314+}
@@ -0,0 +1,88 @@
1+module main
2+
3+import alpm
4+
5+// mark sets the install reason of installed packages, pacman's -D --asdeps
6+// and --asexplicit. every target is found first; one that names nothing is
7+// reported and skipped, as pacman's -D and the other modes do, and the rest
8+// are marked. the reasons are then written under the db lock, which pacman's
9+// change_install_reason takes with an empty transaction too:
10+// alpm_pkg_set_reason writes the db entry right away and locks nothing
11+fn mark(config ConfigMark) ! {
12+ need_query(config.query, 'package')!
13+ mut ui := new_trans_ui(noconfirm: config.noconfirm)
14+ check_ask_db_lock(mut ui)
15+ mut handle := init_handle(ui)!
16+ defer { handle.release() or { went_on('release the alpm handle', err) } }
17+ defer { ui.stop() }
18+ defer { trans_cleanup(handle) }
19+
20+ mut pkgcache := local_pkgcache(handle)!
21+
22+ reason := parse_reason(config.reason)!
23+
24+ mut pkgs := []&alpm.Package{}
25+ for target in config.query {
26+ mut name := local_target_name(target)
27+ pkg := find_local_target(pkgcache, name, false) or {
28+ name = did_you_mean(mut ui, name, pkg_names(pkgcache.pkgs())) or {
29+ target_error(err.msg())
30+ continue
31+ }
32+ pkgcache.pkg_find(name) or {
33+ target_error('unknown package: "${name}"')
34+ continue
35+ }
36+ }
37+ add_pkg_once(mut pkgs, pkg)
38+ }
39+ if pkgs.len == 0 {
40+ return
41+ }
42+
43+ trans_begin(handle, alpm.trans_flag_0)!
44+ // each reason is written to the db as it is set, so a failure leaves the
45+ // ones before it changed: the error names them, so the run is truthful
46+ // about what it did and did not do
47+ mut set := []string{}
48+ for pkg in pkgs {
49+ if pkg.get_reason() != reason {
50+ pkg.set_reason(reason) or {
51+ already := if set.len > 0 { ' (already set: ${set.join(', ')})' } else { '' }
52+ return error('could not set the install reason of ${pkg.get_name()}: ${err.msg()}${already}')
53+ }
54+ set << pkg.get_name()
55+ }
56+ }
57+
58+ names := pkgs.map(it.get_name())
59+ if ipc_on() {
60+ emit(DoneEvent{
61+ action: 'marked'
62+ reason: reason_key(reason)
63+ packages: names
64+ })
65+ return
66+ }
67+ print_done(mut ui, '${reason_to_str(reason)}:', names.map(name_style(it)))
68+}
69+
70+// reason_key is an install reason as a frontend reads it, and the word
71+// mark takes for it (parse_reason); every reason named, as reason_to_str
72+fn reason_key(reason alpm.PackageReason) string {
73+ return match reason {
74+ .explicit { 'explicit' }
75+ .depend { 'depend' }
76+ .unknown { 'unknown' }
77+ }
78+}
79+
80+// parse_reason reads mark's --reason: a reason's key, or a short form of it
81+fn parse_reason(text string) !alpm.PackageReason {
82+ return match text {
83+ 'e', 'ex', 'explicit' { alpm.PackageReason.explicit }
84+ 'd', 'dep', 'depend', 'dependency' { alpm.PackageReason.depend }
85+ 'u', 'un', 'unknown' { alpm.PackageReason.unknown }
86+ else { error('unknown reason: "${text}"') }
87+ }
88+}
@@ -0,0 +1,74 @@
1+module main
2+
3+import alpm
4+
5+// orphan_pkgs are the installed dependencies that nothing kept reaches through
6+// its dependencies. the kept packages are the explicitly installed ones and the
7+// ones an installed package lists as optional, as pacman keeps them. pacman's
8+// -Qdt only finds the dependencies nothing requires, so a group that only
9+// requires itself, such as a set of plugins left behind by their app, is missed.
10+// with optional_too an optional dependency keeps nothing, pacman's -Qdtt:
11+// what only an optdepends line still names is an orphan as well.
12+// a dependency reaches every installed package that satisfies it, not the
13+// first one alone: pacman's compute_requiredby counts a requirer for each
14+// provider, so two providers of one virtual name are both kept
15+fn orphan_pkgs(mut pkgcache alpm.List, optional_too bool) []&alpm.Package {
16+ installed := pkgcache.pkgs()
17+ // who could answer for a name: the package called it, and every one
18+ // that provides it, by its place in installed; the version is libalpm's to compare, below
19+ mut answers := map[string][]int{}
20+ for i, pkg in installed {
21+ answers[pkg.get_name()] << i
22+ for p in pkg.get_provides().depends() {
23+ if p.get_name() != pkg.get_name() {
24+ answers[p.get_name()] << i
25+ }
26+ }
27+ }
28+ mut reached := map[string]bool{}
29+ mut queue := []&alpm.Package{}
30+ for pkg in installed {
31+ if pkg.get_reason() != .depend || (!optional_too && pkg.compute_optional_for().len > 0) {
32+ reached[pkg.get_name()] = true
33+ queue << pkg
34+ }
35+ }
36+ for queue.len > 0 {
37+ pkg := queue.pop()
38+ deps := pkg.get_depends()
39+ for dep in deps.depends() {
40+ depstring := dep.compute_string()
41+ for i in answers[dep.get_name()] {
42+ cand := installed[i]
43+ if reached[cand.get_name()] {
44+ continue
45+ }
46+ // a list of the one candidate, for alpm_find_satisfier's
47+ // version and provision comparison
48+ one := &alpm.List(unsafe { nil }).add(voidptr(cand))
49+ satisfied := one.find_satisfier(depstring) != none
50+ one.free()
51+ if satisfied {
52+ reached[cand.get_name()] = true
53+ queue << cand
54+ }
55+ }
56+ }
57+ }
58+ return installed.filter(it.get_reason() == .depend && !reached[it.get_name()])
59+}
60+
61+fn orphans(config ConfigOrphans) ! {
62+ mut handle := alpm.initialize(root_path, db_path) or { return err }
63+ defer { handle.release() or { went_on('release the alpm handle', err) } }
64+
65+ mut pkgcache := local_pkgcache(handle)!
66+
67+ mut listing := Listing{
68+ fields: cfg_search_fields.clone()
69+ }
70+ for pkg in orphan_pkgs(mut pkgcache, config.level >= 2) {
71+ listing.add_pkg(pkg, 'local')
72+ }
73+ listing.print()
74+}
@@ -0,0 +1,100 @@
1+module main
2+
3+import alpm
4+import os
5+import testdb
6+
7+fn test_orphan_pkgs() ! {
8+ tmp := os.join_path(os.vtmp_dir(), 'vpac_test_orphans_${os.getpid()}')
9+ os.mkdir_all(os.join_path(tmp, 'root'))!
10+ defer { os.rmdir_all(tmp) or {} }
11+ testdb.write_local(os.join_path(tmp, 'db'), [
12+ // kept: explicit, and everything it reaches
13+ testdb.Pkg{
14+ name: 'app'
15+ reason: 0
16+ depends: ['lib1>=1.0', 'libvirtual']
17+ optdepends: ['opt: extra things']
18+ },
19+ testdb.Pkg{
20+ name: 'lib1'
21+ reason: 1
22+ depends: ['lib2']
23+ },
24+ testdb.Pkg{
25+ name: 'lib2'
26+ reason: 1
27+ },
28+ // reached through what it provides
29+ testdb.Pkg{
30+ name: 'impl'
31+ reason: 1
32+ provides: ['libvirtual']
33+ },
34+ // a second provider of the same name is required as much as the
35+ // first, as pacman's compute_requiredby has it; one whose provision
36+ // is too old for a versioned dependency is not
37+ testdb.Pkg{
38+ name: 'impl2'
39+ reason: 1
40+ provides: ['libvirtual']
41+ },
42+ testdb.Pkg{
43+ name: 'wants-new'
44+ reason: 0
45+ depends: ['virt>=2']
46+ },
47+ testdb.Pkg{
48+ name: 'virt-new'
49+ reason: 1
50+ provides: ['virt=2']
51+ },
52+ testdb.Pkg{
53+ name: 'virt-old'
54+ reason: 1
55+ provides: ['virt=1']
56+ },
57+ // kept as an optional dependency of app, with what it needs
58+ testdb.Pkg{
59+ name: 'opt'
60+ reason: 1
61+ depends: ['optlib']
62+ },
63+ testdb.Pkg{
64+ name: 'optlib'
65+ reason: 1
66+ },
67+ // orphans: one nothing requires, and a pair that only requires
68+ // itself, which pacman's -Qdt misses
69+ testdb.Pkg{
70+ name: 'old'
71+ reason: 1
72+ },
73+ testdb.Pkg{
74+ name: 'cyc-a'
75+ reason: 1
76+ depends: ['cyc-b']
77+ },
78+ testdb.Pkg{
79+ name: 'cyc-b'
80+ reason: 1
81+ depends: ['cyc-a']
82+ },
83+ ])!
84+
85+ handle := alpm.initialize(os.join_path(tmp, 'root') + '/', os.join_path(tmp, 'db') + '/')!
86+ defer { handle.release() or {} }
87+ localdb := handle.get_localdb()!
88+ mut pkgcache := localdb.get_pkgcache() or { return error('the fake local db has no packages') }
89+ assert pkgcache.pkgs().len == 13, 'libalpm read the fake db'
90+
91+ mut names := orphan_pkgs(mut pkgcache, false).map(it.get_name())
92+ names.sort()
93+ assert names == ['cyc-a', 'cyc-b', 'old', 'virt-old']
94+
95+ // -tt: an optional dependency keeps nothing, so what only an optdepends
96+ // line names is listed too, with what hangs off it
97+ mut all := orphan_pkgs(mut pkgcache, true).map(it.get_name())
98+ all.sort()
99+ assert all == ['cyc-a', 'cyc-b', 'old', 'opt', 'optlib', 'virt-old']
100+}
@@ -0,0 +1,113 @@
1+@[has_globals]
2+module main
3+
4+import net.urllib
5+import json2
6+
7+pub struct PackagePkgbuild {
8+pub mut:
9+ depends []string @[json: Depends]
10+ make_depends []string @[json: MakeDepends]
11+ check_depends []string @[json: CheckDepends]
12+ description string @[json: Description]
13+ first_submitted i64 @[json: FirstSubmitted]
14+ id i64 @[json: ID]
15+ last_modified i64 @[json: LastModified]
16+ maintainer ?string @[json: Maintainer]
17+ name string @[json: Name]
18+ num_votes i64 @[json: NumVotes]
19+ out_of_date ?i64 @[json: OutOfDate]
20+ package_base string @[json: PackageBase]
21+ package_base_id i64 @[json: PackageBaseID]
22+ popularity f64 @[json: Popularity]
23+ url string @[json: URL]
24+ url_path string @[json: URLPath]
25+ version string @[json: Version]
26+}
27+
28+pub struct PackagesPkgbuild {
29+pub mut:
30+ count i64 @[json: resultcount]
31+ results []PackagePkgbuild
32+ type string
33+ version i64
34+ // the rpc's own failure, when it refuses the request; absent when it answers
35+ error_text ?string @[json: error]
36+}
37+
38+// pkgbuild_rpc_timeout is how long one rpc request may take, for the search
39+// and the info lookups of the pkgbuild repos. a stall would otherwise hang
40+// the search under a proxy's silent wall
41+// (pkgbuild :timeout) sets it, in seconds
42+__global pkgbuild_rpc_timeout = 10
43+
44+// pkgbuild_rpc fetches one url and reads its answer: timed, and demanding an
45+// http answer the rpc actually gives. what it fetches is returned as text;
46+// the callers decode their own answer out of it
47+fn pkgbuild_rpc(url string, what string) !string {
48+ return http_text(url, pkgbuild_rpc_timeout, what, 'the pkgbuild rpc')
49+}
50+
51+// answer_start is the start of an rpc answer that did not decode, for the
52+// error: at most 200 bytes, of an answer that may be shorter (a captive
53+// portal's page, a proxy's error) — a plain slice would panic on it
54+fn answer_start(body string) string {
55+ return body#[..200]
56+}
57+
58+// get_pkgbuild_packages searches one pkgbuild repo's site for a needle.
59+// the needle is escaped: a query with '&', '#', ' ' or '=' must not break
60+// the request or smuggle in extra rpc parameters
61+fn get_pkgbuild_packages(base string, needle string) ![]PackagePkgbuild {
62+ body := pkgbuild_rpc(
63+ '${base}/rpc/v5/search/${urllib.query_escape(needle)}',
64+ 'search',
65+ )!
66+ data := json2.decode[PackagesPkgbuild](body) or {
67+ return error('failed to decode search results: ${err.msg()} (the answer begins: ${answer_start(body)})')
68+ }
69+ if err := data.error_text {
70+ return error('search failed: ${err}')
71+ }
72+ return data.results
73+}
74+
75+// get_pkgbuild_info fetches the full record, dependencies included, of each
76+// name, from one pkgbuild repo's site. the names are escaped likewise. no
77+// names asks for nothing and gets it
78+fn get_pkgbuild_info(base string, names []string) ![]PackagePkgbuild {
79+ if names.len == 0 {
80+ return []PackagePkgbuild{}
81+ }
82+ args := names.map('arg[]=${urllib.query_escape(it)}').join('&')
83+ body := pkgbuild_rpc('${base}/rpc/v5/info?${args}', 'info lookup')!
84+ data := json2.decode[PackagesPkgbuild](body) or {
85+ return error('failed to decode package info: ${err.msg()} (the answer begins: ${answer_start(body)})')
86+ }
87+ if err := data.error_text {
88+ return error('info lookup failed: ${err}')
89+ }
90+ return data.results
91+}
92+
93+// pkgbuild_lookup finds name in the pkgbuild repos, tried in config order:
94+// the first one that has the package is the one it builds from. it answers
95+// the record, the repo's site with no trailing slash (so a clone url joins
96+// with exactly one), and the name the config gives the repo; the site is
97+// empty when no repo holds the name
98+fn pkgbuild_lookup(name string) !(PackagePkgbuild, string, string) {
99+ for repo in pkgbuild_repos() {
100+ site := repo.servers[0].trim_right('/')
101+ infos := get_pkgbuild_info(site, [name])!
102+ if infos.len > 0 {
103+ return infos[0], site, repo.name
104+ }
105+ }
106+ return PackagePkgbuild{}, '', ''
107+}
108+
109+// pkgbuild_has names whether any pkgbuild repo holds name
110+fn pkgbuild_has(name string) !bool {
111+ _, site, _ := pkgbuild_lookup(name)!
112+ return site != ''
113+}
@@ -0,0 +1,570 @@
1+module main
2+
3+import alpm
4+import os
5+import time
6+import vmakepkg
7+
8+// PkgbuildNode is one pkgbuild package in build order: the repo packages it needs first,
9+// then itself. site is the pkgbuild repo the package came from, repo the
10+// name the config gives it
11+struct PkgbuildNode {
12+ info PackagePkgbuild
13+ site string
14+ repo string
15+ repo_deps []string
16+ // wanted are the dependency strings that put the node in the plan, as
17+ // the packages that need it spell them; the target has none. they are
18+ // what tells, once earlier builds are installed, whether this one is
19+ // still needed
20+ wanted []string
21+}
22+
23+// PkgbuildResolver walks the dependencies of a pkgbuild package. a dependency that is
24+// installed or in the repos is used as it is; one that is neither is looked up
25+// in the pkgbuild repo and placed before the package that needs it
26+struct PkgbuildResolver {
27+mut:
28+ handle &alpm.Handle
29+ installed &alpm.List
30+ sync_dbs &alpm.List
31+ // visiting holds the names on the branch being walked, so a cycle is a
32+ // named error instead of a node silently skipped; done holds the ones
33+ // whose nodes are already in, so they are never built twice
34+ visiting map[string]bool
35+ done map[string]bool
36+ nodes []PkgbuildNode
37+ // wanted gathers, by node name, every dependency string that led to the
38+ // node, the later ones too: a node is planned once and wanted often
39+ wanted map[string][]string
40+}
41+
42+// planned is the plan as it stands: the nodes in build order, each with
43+// everything that wanted it
44+fn (r &PkgbuildResolver) planned() []PkgbuildNode {
45+ return r.nodes.map(PkgbuildNode{
46+ ...it
47+ wanted: r.wanted[it.info.name].clone()
48+ })
49+}
50+
51+fn (mut r PkgbuildResolver) visit(name string) ! {
52+ if r.done[name] {
53+ return
54+ }
55+ if r.visiting[name] {
56+ return error('circular pkgbuild dependency: ${name} is walked as its own dependency')
57+ }
58+ r.visiting[name] = true
59+ defer {
60+ r.visiting.delete(name)
61+ }
62+ pkg_info, site, from := pkgbuild_lookup(name)!
63+ if site == '' {
64+ return error('"${name}" is not in the repos or the pkgbuild repo')
65+ }
66+ mut repo := []string{}
67+ mut deps := []string{}
68+ deps << pkg_info.depends
69+ deps << pkg_info.make_depends
70+ // makepkg runs check() by default, so what it needs is needed before
71+ // the build is queued, not found missing inside it
72+ deps << pkg_info.check_depends
73+ for dep in deps {
74+ if p := r.handle.resolve_dep(r.installed, r.sync_dbs, dep) {
75+ if p.get_origin() == .syncdb {
76+ repo << p.get_name()
77+ }
78+ continue
79+ }
80+ if dep !in r.wanted[dep_name(dep)] {
81+ r.wanted[dep_name(dep)] << dep
82+ }
83+ r.visit(dep_name(dep))!
84+ }
85+ r.nodes << PkgbuildNode{
86+ info: pkg_info
87+ site: site
88+ repo: from
89+ repo_deps: repo
90+ }
91+ // only a node that arrived in the plan counts as done: one whose walk
92+ // failed wants reporting when it is reached again
93+ r.done[name] = true
94+}
95+
96+// dep_name strips a version constraint: 'glibc>=2.27' is 'glibc'
97+fn dep_name(dep string) string {
98+ return dep.trim_space().all_before('<').all_before('>').all_before('=').trim_space()
99+}
100+
101+// pkgbuild_root is the dir every build lives under. the configured dir is
102+// taken under the invoking user's home when it is relative, because makepkg
103+// runs as that user
104+fn pkgbuild_root(user string) !string {
105+ if pkgbuild_dir.starts_with('/') {
106+ return pkgbuild_dir
107+ }
108+ return os.join_path(user_home(user)!, pkgbuild_dir)
109+}
110+
111+// pkgbuild_build_dir is where a package is cloned and built
112+fn pkgbuild_build_dir(user string, base string) !string {
113+ // the base is the rpc's answer, and the dir it names is removed before
114+ // the clone: only one plain path component may stand here
115+ if base == '' || base in ['.', '..'] || base.contains('/') || base.starts_with('-') {
116+ return error('the pkgbuild repo answered a package base that is not a plain name: "${base}"')
117+ }
118+ return '${pkgbuild_root(user)!}/${base}'
119+}
120+
121+// makepkg_line is the shell line a build runs in its dir: the dir quoted as
122+// one word, then the configured build command — config text passed through
123+// the shell on purpose, trusted as far as the config it comes from, and
124+// reviewed by the user beside everything else a pkgbuild runs
125+fn makepkg_line(dir string) string {
126+ return 'cd ${vmakepkg.shell_quote(dir)} && ${pkgbuild_makepkg}'
127+}
128+
129+// run_process runs a command, its arguments reaching it one by one with no
130+// shell in between to quote wrong, and answers its exit code. with capture
131+// its stdout comes back as text, and its stderr is passed on as it arrives:
132+// both pipes are drained while the child lives, so one that fills the
133+// stderr pipe never waits on a reader that is itself waiting on stdout.
134+// without capture the terminal is the child's own
135+fn run_process(argv []string, capture bool) !(string, int) {
136+ exe := os.find_abs_path_of_executable(argv[0]) or {
137+ return error('${argv[0]} is needed, but it was not found')
138+ }
139+ mut process := os.new_process(exe)
140+ process.set_args(argv[1..])
141+ mut out := ''
142+ if capture {
143+ process.set_redirect_stdio()
144+ process.run()
145+ for process.is_alive() {
146+ mut idle := true
147+ if process.is_pending(.stdout) {
148+ out += process.stdout_read()
149+ idle = false
150+ }
151+ if process.is_pending(.stderr) {
152+ eprint(process.stderr_read())
153+ idle = false
154+ }
155+ if idle {
156+ time.sleep(2 * time.millisecond)
157+ }
158+ }
159+ out += process.stdout_slurp()
160+ eprint(process.stderr_slurp())
161+ }
162+ process.wait()
163+ code := process.code
164+ process.close()
165+ return out, code
166+}
167+
168+// as_user runs a command as the invoking user, through runuser
169+fn as_user(user string, args []string, capture bool) !string {
170+ mut cmd := ['runuser', '-u', user, '--']
171+ cmd << args
172+ out, code := run_process(cmd, capture) or {
173+ return error('${cmd[0]} is needed to run this as ${user}, but it was not found')
174+ }
175+ if code != 0 {
176+ return error('${args[0]} failed as user ${user} (exit ${code})')
177+ }
178+ return out
179+}
180+
181+// output_as_user runs a command as the invoking user, as run_as_user does,
182+// and returns what it printed on stdout
183+fn output_as_user(user string, args []string) !string {
184+ return as_user(user, args, true)
185+}
186+
187+// run_as_user runs a command as the invoking user, with the terminal passed on
188+fn run_as_user(user string, args []string) ! {
189+ as_user(user, args, false)!
190+}
191+
192+// ReviewFile is one file a build runs, shown whole before it is built.
193+// generated marks a file vpac wrote from a PKGBUILD.lip or a PKGBUILD.vsh
194+struct ReviewFile {
195+ name string
196+ text string
197+ generated bool
198+}
199+
200+// ReviewEvent is what a build runs, shown before the question that builds
201+// it: the warnings about where it comes from, its files, and the names in
202+// its dir
203+struct ReviewEvent {
204+ kind string = 'review' @[json: 'type']
205+ package string
206+mut:
207+ files []ReviewFile
208+ listing []string
209+ warnings []string
210+}
211+
212+// read_review collects a PKGBUILD dir's review: the PKGBUILD, every .install
213+// script and the list of files that make up the package
214+fn read_review(package string, dir string) !ReviewEvent {
215+ mut parts := [ReviewFile{
216+ name: 'PKGBUILD'
217+ text: os.read_file('${dir}/PKGBUILD')!
218+ }]
219+ mut names := os.ls(dir)!
220+ names.sort()
221+ mut listing := []string{}
222+ for f in names {
223+ if f == '.git' {
224+ continue
225+ }
226+ if f.ends_with('.install') {
227+ parts << ReviewFile{
228+ name: f
229+ text: os.read_file('${dir}/${f}')!
230+ }
231+ }
232+ listing << f
233+ }
234+ return ReviewEvent{
235+ package: package
236+ files: parts
237+ listing: listing
238+ }
239+}
240+
241+// show_review shows a review: on a terminal the warnings, the title, every
242+// file under its name and the files in the package; a frontend gets it as
243+// one event
244+fn show_review(r ReviewEvent, title string) {
245+ if ipc_on() {
246+ emit(ReviewEvent{
247+ ...r
248+ warnings: r.warnings.map(it.trim_space())
249+ })
250+ return
251+ }
252+ println(review_text(r, title))
253+}
254+
255+// review_text is a review for the terminal: the warnings, the title, every
256+// file under its name, and the files in the package
257+fn review_text(r ReviewEvent, title string) string {
258+ mut out := r.warnings.map(warning(it))
259+ if title != '' {
260+ out << heading(title)
261+ }
262+ for f in r.files {
263+ out << heading(if f.generated && f.name == 'PKGBUILD' {
264+ 'PKGBUILD the build runs'
265+ } else {
266+ f.name
267+ })
268+ out << f.text
269+ }
270+ if r.listing.len > 0 {
271+ out << heading('files in the package')
272+ out << r.listing.join(' ')
273+ }
274+ return out.join('\n')
275+}
276+
277+// build_phase tells a frontend a build runs; a terminal sees makepkg's own
278+// output, which goes to the frontend's log
279+fn build_phase(name string, state string) {
280+ if ipc_on() {
281+ emit(PhaseEvent{
282+ text: 'building ${name}'
283+ state: state
284+ })
285+ }
286+}
287+
288+// built_packages lists the archives a build produced, as makepkg names them
289+// itself: the build command with --packagelist answers the files this
290+// PKGBUILD's version packs to, wherever PKGDEST puts them and whatever PKGEXT
291+// is. a name pattern over the build dir missed an uncompressed .pkg.tar and
292+// another PKGDEST, and took an older build's archive a pulled checkout
293+// carried — of two, the directory's order chose which was installed
294+fn built_packages(user string, dir string) ![]string {
295+ out := output_as_user(user, ['sh', '-c', '${makepkg_line(dir)} --packagelist'])!
296+ return packagelist_files(out)
297+}
298+
299+// packagelist_files are the paths --packagelist printed that the build did
300+// produce: it names every package the PKGBUILD can make (a debug package
301+// among them) whether built or not, so only the files that are there count
302+fn packagelist_files(output string) []string {
303+ return output.split_into_lines().map(it.trim_space()).filter(it.starts_with('/')
304+ && os.is_file(it))
305+}
306+
307+// archives_in lists the package archives a build dir holds, whatever version
308+// or build made them: what clean asks of a build, to keep one that holds an
309+// installed package's archive. an uncompressed .pkg.tar is one too
310+fn archives_in(dir string) ![]string {
311+ mut out := []string{}
312+ for f in os.ls(dir)! {
313+ if is_pkg_archive(f) {
314+ out << '${dir}/${f}'
315+ }
316+ }
317+ return out
318+}
319+
320+// pkgbuild_warnings are what the pkgbuild repo knows of a package that a
321+// review wants beside the files: who keeps it, how many vouch for it, and
322+// whether it was flagged
323+fn pkgbuild_warnings(info PackagePkgbuild) []string {
324+ maintainer := info.maintainer or { 'none (orphaned)' }
325+ mut out := ['maintainer: ${maintainer}, votes: ${info.num_votes}']
326+ if info.out_of_date != none {
327+ out << 'flagged as out of date'
328+ }
329+ return out
330+}
331+
332+// review_and_build asks its way to a build: whether the package is to come
333+// from the pkgbuild repo at all (no by default), then whether its pkgbuild
334+// is to be read first (yes by default), then the build's own question, asked
335+// whether or not the review was read, so the build can still be declined.
336+// searched says the repos were looked in before, which a -b target's never
337+// were. only then does it install the repo packages the build needs, and
338+// build. returns the archives; a no to a question is a BuildDeclined, which
339+// is the user's answer and not a failure of the build
340+fn review_and_build(mut ui TransUI, user string, node PkgbuildNode, config ConfigInstall, searched bool) ![]string {
341+ name := node.info.name
342+ base := node.info.package_base
343+ dir := pkgbuild_build_dir(user, base)!
344+ ask := !config.no_pkgbuild_confirm
345+ // --noconfirm would take the first question's preset, which is no: the
346+ // refusal says so before anything is cloned
347+ if config.noconfirm && ask {
348+ return error('pkgbuild packages are asked about: drop --noconfirm, or pass --nopkgbuildconfirm, to build ${name}')
349+ }
350+ ui.pause()
351+ // the display is paused for the questions, the clone and the review; the
352+ // run leaves it paused-through for the build, and syncs on the way out
353+ defer { ui.sync() }
354+ if searched {
355+ warn('${name} was not found in the repos')
356+ }
357+ if ask && !ui.noyes('install ${name} from the pkgbuild repo (${node.repo})?') {
358+ return BuildDeclined{}
359+ }
360+ run_as_user(user, ['mkdir', '-p', pkgbuild_root(user)!])!
361+ run_as_user(user, ['rm', '-rf', dir])!
362+ run_as_user(user, ['git', 'clone', '--depth', '${pkgbuild_depth}', '${node.site}/${base}.git',
363+ dir])!
364+
365+ // with --nopkgbuildconfirm nothing is asked, and the review is still
366+ // shown: the record of what was built stays in the output
367+ if !ask || ui.yesno('review the pkgbuild?') {
368+ mut review := read_review(name, dir)!
369+ review.warnings = pkgbuild_warnings(node.info)
370+ show_review(review, 'review ${name}')
371+ }
372+ prompt := if node.repo_deps.len > 0 {
373+ 'build and install ${name}, after installing its repo dependencies ${node.repo_deps.join(', ')}?'
374+ } else {
375+ 'build and install ${name}?'
376+ }
377+ if ask && !ui.yesno(prompt) {
378+ return BuildDeclined{}
379+ }
380+ if node.repo_deps.len > 0 {
381+ install_repo_deps(node.repo_deps)!
382+ ui.sync()
383+ }
384+ build_phase(name, 'start')
385+ run_as_user(user, ['sh', '-c', makepkg_line(dir)])!
386+ build_phase(name, 'done')
387+ return built_packages(user, dir)!
388+}
389+
390+// BuildDeclined is review_and_build's answer when the user said no
391+struct BuildDeclined {
392+ Error
393+}
394+
395+fn (e BuildDeclined) msg() string {
396+ return 'the build was declined'
397+}
398+
399+// local_now opens the installed packages as they are at this moment, on a
400+// handle of its own that the caller releases. the run's handle read the
401+// local db when the run began, and every build since was installed through
402+// another one (install's): its list is the past, and what is planned, asked
403+// and skipped from here on is decided on the present
404+fn local_now() !(&alpm.Handle, &alpm.List) {
405+ handle := alpm.initialize(root_path, db_path) or {
406+ return error('could not read the local database: ${err.msg()}')
407+ }
408+ pkgs := local_pkgcache(handle) or {
409+ handle.release() or { went_on('release the alpm handle', err) }
410+ return err
411+ }
412+ return handle, pkgs
413+}
414+
415+// NodeStep is what is left to do for a node once the installed packages
416+// are read again: nothing (skip, and why), or the build, with the repo
417+// packages it still needs first
418+struct NodeStep {
419+ skip bool
420+ why string
421+ repo_deps []string
422+}
423+
424+// node_step decides a node against the installed packages as they are now.
425+// a dependency node is dropped when everything that wanted it is satisfied
426+// by what is installed — an earlier build of this run that provides it, a
427+// split package that came with its sibling — and never merely because a
428+// package of its name is there at some version. the target is only ever
429+// skipped by --needed, at the very version it would install. the repo
430+// dependencies are the ones still missing
431+fn node_step(installed &alpm.List, node PkgbuildNode, needed bool, is_target bool) NodeStep {
432+ name := node.info.name
433+ if !is_target && node.wanted.len > 0
434+ && node.wanted.all(installed.find_satisfier(it) != none) {
435+ return NodeStep{
436+ skip: true
437+ why: '${name} is satisfied by what is installed now, not built'
438+ }
439+ }
440+ if is_target && needed {
441+ if local := installed.pkg_find(name) {
442+ if alpm.pkg_vercmp(local.get_version(), node.info.version) == 0 {
443+ return NodeStep{
444+ skip: true
445+ why: '${name}-${node.info.version} is up to date, skipped'
446+ }
447+ }
448+ }
449+ }
450+ return NodeStep{
451+ repo_deps: node.repo_deps.filter(installed.pkg_find(it) == none)
452+ }
453+}
454+
455+// node_step_now is node_step on the local db read this moment
456+fn node_step_now(node PkgbuildNode, needed bool, is_target bool) !NodeStep {
457+ view, installed := local_now()!
458+ defer { view.release() or { went_on('release the alpm handle', err) } }
459+ return node_step(installed, node, needed, is_target)
460+}
461+
462+// install_repo_deps installs the repo packages a build needs, as
463+// dependencies, through an install of its own: a fresh handle, so the
464+// transaction is checked against the packages installed now and not against
465+// what the run's handle read before the earlier builds went in. the
466+// pkgbuild's questions were the go-ahead for the build and what it needs,
467+// so the listing is shown and taken as --noconfirm takes it; nothing beyond
468+// the named packages and what they depend on is upgraded along
469+fn install_repo_deps(names []string) ! {
470+ if names.len == 0 {
471+ return
472+ }
473+ install(ConfigInstall{
474+ query: names
475+ noconfirm: true
476+ asdeps: true
477+ no_upgrade_deps: true
478+ }) or { return error('the build dependencies ${names.join(', ')} were not installed: ${err.msg()}') }
479+}
480+
481+// built_install_config is the install of what a pkgbuild built, as the outer
482+// command line asked for it: the archives are the targets, a dependency
483+// node is installed as a dependency whatever the target's reason is, and
484+// what was said of the transaction (ignores, overwrites, the dependency
485+// checks, the timeout) holds for this one as well. what belongs to the
486+// outer run alone — the pkgbuild flags, --needed, --print, --download-only —
487+// stays behind
488+fn built_install_config(config ConfigInstall, archives []string, is_target bool) ConfigInstall {
489+ return ConfigInstall{
490+ query: archives
491+ noconfirm: config.noconfirm
492+ asdeps: if is_target { config.asdeps } else { true }
493+ asexplicit: is_target && config.asexplicit
494+ dbonly: config.dbonly
495+ nodeps: config.nodeps
496+ nodeps_level: config.nodeps_level
497+ overwrite: config.overwrite
498+ assume_installed: config.assume_installed
499+ ignore: config.ignore
500+ ignoregroup: config.ignoregroup
501+ no_upgrade_deps: config.no_upgrade_deps
502+ disable_timeout: config.disable_timeout
503+ }
504+}
505+
506+// pkgbuild_plan resolves target into its build plan, dependencies first,
507+// against the local db read this moment and the handle's sync dbs
508+fn pkgbuild_plan(handle &alpm.Handle, target string) ![]PkgbuildNode {
509+ view, installed := local_now()!
510+ defer { view.release() or { went_on('release the alpm handle', err) } }
511+ mut r := PkgbuildResolver{
512+ // the caller's handle outlives the plan: it is only read here
513+ handle: unsafe { handle }
514+ installed: installed
515+ sync_dbs: handle.get_syncdbs()!
516+ }
517+ r.visit(target)!
518+ return r.planned()
519+}
520+
521+// pkgbuild_install builds an AUR package and the AUR packages it needs, reviewing
522+// each one, then installs what was built
523+fn pkgbuild_install(mut ui TransUI, mut handle &alpm.Handle, config ConfigInstall, target string) ! {
524+ user := invoker_user()!
525+ // the plan is resolved against the installed packages as they are now:
526+ // an earlier target of this run may have been built and installed since
527+ // the handle read them. the sync dbs are the handle's, which no install
528+ // changes
529+ nodes := pkgbuild_plan(handle, target)!
530+
531+ for i, planned in nodes {
532+ // the nodes come dependencies first: the last one is the target
533+ is_target := i == nodes.len - 1
534+ // and each node is decided when its turn comes, after everything
535+ // before it was installed
536+ step := node_step_now(planned, config.needed, is_target)!
537+ if step.skip {
538+ // warn speaks both a terminal's and a frontend's language, the
539+ // way an install's own --needed does
540+ warn(step.why)
541+ continue
542+ }
543+ node := PkgbuildNode{
544+ ...planned
545+ repo_deps: step.repo_deps
546+ }
547+ archives := review_and_build(mut ui, user, node, config, !(is_target
548+ && config.pkgbuild)) or {
549+ if err is BuildDeclined {
550+ // a no is a quiet stop: nothing after this node can be built
551+ // without it, and nothing went wrong
552+ advise('${node.info.name} was declined, nothing more is built')
553+ return
554+ }
555+ return err
556+ }
557+ if archives.len == 0 {
558+ return error('${node.info.name} was not built')
559+ }
560+ // a pkgbuild dependency is installed as a dependency, the way the
561+ // repo ones are; the target takes --asdeps or --asexplicit. the
562+ // whole of what came out of the pkgbuild goes into one install, so a
563+ // split package set lands as one transaction, with its ordering, its
564+ // hooks and its prompt, instead of one apiece
565+ install(built_install_config(config, archives, is_target))!
566+ }
567+ // everything built was installed by install() above, which already
568+ // reports "installed: <package>"; provenance comes from the question
569+ // asked before the build
570+}
@@ -0,0 +1,339 @@
1+module main
2+
3+import os
4+import testdb
5+
6+fn test_dep_name() {
7+ cases := {
8+ 'glibc': 'glibc'
9+ 'glibc>=2.27': 'glibc'
10+ 'foo<1.0': 'foo'
11+ 'foo<=1.0': 'foo'
12+ 'foo=1.0-2': 'foo'
13+ 'foo>1:2.0': 'foo'
14+ 'gcc-libs': 'gcc-libs'
15+ 'python>=3.12': 'python'
16+ 'libfoo.so=1-64': 'libfoo.so'
17+ // stray spaces, as a published dependency list occasionally spells
18+ ' glibc >=2.27 ': 'glibc'
19+ ' glibc ': 'glibc'
20+ 'git >2.0': 'git'
21+ }
22+ for dep, want in cases {
23+ assert dep_name(dep) == want, dep
24+ }
25+}
26+
27+fn test_review() ! {
28+ old := color_flag
29+ defer { color_flag = old }
30+ color_flag = 'never'
31+ dir := os.join_path(os.vtmp_dir(), 'vpac_test_review_${os.getpid()}')
32+ os.mkdir_all(os.join_path(dir, '.git'))!
33+ defer { os.rmdir_all(dir) or {} }
34+ os.write_file(os.join_path(dir, 'PKGBUILD'), 'pkgname=foo\n')!
35+ os.write_file(os.join_path(dir, 'foo.install'), 'post_install() { :; }')!
36+ os.write_file(os.join_path(dir, 'a.patch'), '')!
37+
38+ // the PKGBUILD first, then the .install scripts, then every name but .git
39+ mut r := read_review('foo', dir)!
40+ assert r.files.map(it.name) == ['PKGBUILD', 'foo.install']
41+ assert r.listing == ['PKGBUILD', 'a.patch', 'foo.install']
42+ r.warnings = pkgbuild_warnings(PackagePkgbuild{ name: 'foo', maintainer: 'me', num_votes: 1 })
43+ assert review_text(r, 'review foo') == [
44+ 'warning: maintainer: me, votes: 1',
45+ 'review foo',
46+ 'PKGBUILD',
47+ 'pkgname=foo\n',
48+ 'foo.install',
49+ 'post_install() { :; }',
50+ 'files in the package',
51+ 'PKGBUILD a.patch foo.install',
52+ ].join('\n')
53+
54+ // a generated package shows its source, then what was generated from it
55+ g := generated_review('foo', 'PKGBUILD.lip', '(lip)', 'pkgname=foo', 'foo.install', 'x')
56+ assert review_text(g, '') == 'PKGBUILD.lip\n(lip)\nPKGBUILD the build runs\npkgname=foo\nfoo.install\nx'
57+ assert generated_review('foo', 'PKGBUILD.vsh', 'v', 'p', 'foo.install', '').files.len == 2
58+}
59+
60+fn test_makepkg_line() ! {
61+ // the dir is one word to the shell whatever it is called; the build
62+ // command is the config's text, run in it
63+ dir := os.join_path(os.vtmp_dir(), "vpac test's \$dir `x` ${os.getpid()}")
64+ os.mkdir_all(dir)!
65+ defer { os.rmdir_all(dir) or {} }
66+ saved := pkgbuild_makepkg
67+ defer { pkgbuild_makepkg = saved }
68+ pkgbuild_makepkg = 'pwd -P'
69+ res := os.exec(['sh', '-c', makepkg_line(dir)])
70+ assert res.exit_code == 0, res.output
71+ assert res.output.trim_right('\n') == os.real_path(dir)
72+ // the default is makepkg's own, forcing a rebuild of what is there
73+ reset_config()
74+ assert makepkg_line('/x').ends_with(' && makepkg -f')
75+}
76+
77+fn test_build_dir_takes_a_plain_base_only() ! {
78+ // the dir is removed before the clone, so a base that climbs out of the
79+ // build root is refused before any path is made of it
80+ saved := pkgbuild_dir
81+ defer { pkgbuild_dir = saved }
82+ pkgbuild_dir = '/var/tmp/vpac-builds'
83+ assert pkgbuild_build_dir('u', 'foo-git')! == '/var/tmp/vpac-builds/foo-git'
84+ for bad in ['', '.', '..', '../x', 'a/b', '/etc', '-rf'] {
85+ if d := pkgbuild_build_dir('u', bad) {
86+ assert false, 'accepted "${bad}" as ${d}'
87+ }
88+ }
89+}
90+
91+fn test_packagelist_files() ! {
92+ dir := os.join_path(os.vtmp_dir(), 'vpac_test_pkglist_${os.getpid()}')
93+ os.mkdir_all(dir)!
94+ defer { os.rmdir_all(dir) or {} }
95+ built := os.join_path(dir, 'foo-1.0-1-any.pkg.tar')
96+ os.write_file(built, '')!
97+ // makepkg names every package it can make, built or not: a debug package
98+ // that was not made, and blank or odd lines, are not archives
99+ out := '${built}\n${dir}/foo-debug-1.0-1-any.pkg.tar\n\n ${built} \nwarning: x\n'
100+ assert packagelist_files(out) == [built, built]
101+}
102+
103+fn test_archives_in() ! {
104+ dir := os.join_path(os.vtmp_dir(), 'vpac_test_archives_in_${os.getpid()}')
105+ os.mkdir_all(dir)!
106+ defer { os.rmdir_all(dir) or {} }
107+ 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',
108+ 'PKGBUILD', 'notes.tar'] {
109+ os.write_file(os.join_path(dir, f), '')!
110+ }
111+ mut got := archives_in(dir)!.map(os.base(it))
112+ got.sort()
113+ // an uncompressed archive counts, a signature and other files do not
114+ assert got == ['bar-2-1-x86_64.pkg.tar.zst', 'foo-1.0-1-any.pkg.tar']
115+}
116+
117+fn test_makepkg_packagelist_names_what_is_built() ! {
118+ if !os.exists_in_system_path('makepkg') {
119+ // no makepkg on this system: the assumption cannot be checked here
120+ return
121+ }
122+ if os.geteuid() == 0 {
123+ // makepkg refuses root
124+ return
125+ }
126+ dir := os.join_path(os.vtmp_dir(), 'vpac_test_packagelist_${os.getpid()}')
127+ out_dir := os.join_path(dir, 'out')
128+ os.mkdir_all(out_dir)!
129+ defer { os.rmdir_all(dir) or {} }
130+ os.write_file(os.join_path(dir, 'PKGBUILD'), [
131+ 'pkgbase=split',
132+ 'pkgname=(split-a split-b)',
133+ 'pkgver=1.0',
134+ 'pkgrel=1',
135+ "arch=('any')",
136+ 'package_split-a() { :; }',
137+ 'package_split-b() { :; }',
138+ ].join('\n') + '\n')!
139+ // an archive an older build left in the checkout: not this build's
140+ os.write_file(os.join_path(dir, 'split-a-0.9-1-any.pkg.tar.zst'), '')!
141+ saved := pkgbuild_makepkg
142+ defer { pkgbuild_makepkg = saved }
143+ pkgbuild_makepkg = 'makepkg -f'
144+ // the line built_packages runs, as this user rather than through runuser:
145+ // PKGDEST and PKGEXT as a makepkg.conf would set them
146+ res := os.exec(['env', 'PKGDEST=${out_dir}', 'PKGEXT=.pkg.tar', 'sh', '-c',
147+ '${makepkg_line(dir)} --packagelist'])
148+ assert res.exit_code == 0, res.output
149+ listed := res.output.split_into_lines().map(it.trim_space()).filter(it.starts_with('/'))
150+ assert listed == ['${out_dir}/split-a-1.0-1-any.pkg.tar', '${out_dir}/split-b-1.0-1-any.pkg.tar'], res.output
151+ // nothing built yet: nothing to install, the stale archive not among it
152+ assert packagelist_files(res.output) == []
153+ // built: exactly this version's two, from PKGDEST, uncompressed
154+ for f in listed {
155+ os.write_file(f, '')!
156+ }
157+ assert packagelist_files(res.output) == listed
158+}
159+
160+fn test_run_process_drains_both_pipes() ! {
161+ // more on stderr than a pipe holds, before stdout says anything: a
162+ // reader of stdout alone would wait on a child that waits on it
163+ out, code := run_process(['sh', '-c', 'head -c 300000 /dev/zero >&2; echo ok; exit 3'],
164+ true)!
165+ assert out == 'ok\n'
166+ assert code == 3
167+ _, plain := run_process(['true'], false)!
168+ assert plain == 0
169+ if _, _ := run_process(['vpac-no-such-tool'], false) {
170+ assert false
171+ }
172+}
173+
174+fn test_built_install_config_carries_the_command_line() {
175+ outer := ConfigInstall{
176+ noconfirm: true
177+ asexplicit: true
178+ dbonly: true
179+ nodeps: true
180+ nodeps_level: 2
181+ overwrite: ['usr/*']
182+ assume_installed: ['x=1']
183+ ignore: ['held']
184+ ignoregroup: ['grp']
185+ no_upgrade_deps: true
186+ disable_timeout: true
187+ pkgbuild: true
188+ no_pkgbuild_confirm: true
189+ needed: true
190+ query: ['the-target']
191+ }
192+ target := built_install_config(outer, ['/b/a.pkg.tar.zst', '/b/b.pkg.tar.zst'], true)
193+ // the archives are the targets, not the name that was asked for
194+ assert target.query == ['/b/a.pkg.tar.zst', '/b/b.pkg.tar.zst']
195+ assert target.asexplicit && !target.asdeps
196+ assert target.ignore == ['held'] && target.ignoregroup == ['grp']
197+ assert target.no_upgrade_deps && target.disable_timeout && target.noconfirm
198+ assert target.dbonly && target.nodeps && target.nodeps_level == 2
199+ assert target.overwrite == ['usr/*'] && target.assume_installed == ['x=1']
200+ // the outer run's own flags stay behind: an archive is not looked up in
201+ // the pkgbuild repo, and --needed was settled before the build
202+ assert !target.pkgbuild && !target.no_pkgbuild_confirm && !target.needed
203+ // a dependency node is a dependency whatever the target was to be
204+ dep := built_install_config(outer, ['/b/dep.pkg.tar.zst'], false)
205+ assert dep.asdeps && !dep.asexplicit
206+ assert dep.ignore == ['held'] && dep.no_upgrade_deps
207+ // and nothing appears that the command line did not say
208+ plain := built_install_config(ConfigInstall{}, [], true)
209+ assert plain == ConfigInstall{}
210+}
211+
212+// node_db writes a local db for the node decisions and points the config at it
213+fn node_db(name string, pkgs []testdb.Pkg) !string {
214+ tmp := os.join_path(os.vtmp_dir(), 'vpac_test_node_${name}_${os.getpid()}')
215+ os.rmdir_all(tmp) or {}
216+ os.mkdir_all(os.join_path(tmp, 'root'))!
217+ testdb.write_local(os.join_path(tmp, 'db'), pkgs)!
218+ root_path = os.join_path(tmp, 'root') + '/'
219+ db_path = os.join_path(tmp, 'db') + '/'
220+ return tmp
221+}
222+
223+fn node_of(name string, version string, wanted []string, repo_deps []string) PkgbuildNode {
224+ return PkgbuildNode{
225+ info: PackagePkgbuild{
226+ name: name
227+ package_base: name
228+ version: version
229+ }
230+ wanted: wanted
231+ repo_deps: repo_deps
232+ }
233+}
234+
235+fn test_node_step_is_decided_on_what_is_installed_now() ! {
236+ saved_root, saved_db := root_path, db_path
237+ tmp := node_db('step', [
238+ testdb.Pkg{
239+ name: 'lib'
240+ version: '1.0-1'
241+ },
242+ testdb.Pkg{
243+ name: 'impl'
244+ version: '3.0-1'
245+ provides: ['virt=3']
246+ },
247+ ])!
248+ defer {
249+ root_path, db_path = saved_root, saved_db
250+ os.rmdir_all(tmp) or {}
251+ }
252+ // a dependency node everything wanted is satisfied for is not built:
253+ // by its own name, by a version it meets, by something that provides it
254+ for wanted in [['lib'], ['lib>=1.0'], ['lib', 'lib<2'], ['virt'], ['virt>=3', 'virt']] {
255+ name := dep_name(wanted[0])
256+ step := node_step_now(node_of(name, '9-1', wanted, []), false, false)!
257+ assert step.skip, '${wanted} was still to build'
258+ assert step.why.contains('installed now'), step.why
259+ }
260+ // one requirement of several that is not met keeps the build
261+ for wanted in [['lib>=2'], ['lib', 'lib>=2'], ['virt=4'], ['gone'], ['lib', 'gone']] {
262+ step := node_step_now(node_of(dep_name(wanted[0]), '9-1', wanted, []), false, false)!
263+ assert !step.skip, '${wanted} was skipped'
264+ }
265+ // a package of the name at the node's very version does not skip a
266+ // dependency node whose requirement it does not meet, with or without
267+ // --needed: the name being there is not the requirement being met
268+ for needed in [false, true] {
269+ same := node_step_now(node_of('lib', '1.0-1', ['lib>=2'], []), needed, false)!
270+ assert !same.skip
271+ }
272+ // the target is never dropped for being satisfied: it was asked for.
273+ // only --needed skips it, and only at the version it would install
274+ assert !node_step_now(node_of('lib', '1.0-1', [], []), false, true)!.skip
275+ assert !node_step_now(node_of('lib', '1.0-1', ['lib'], []), false, true)!.skip
276+ up := node_step_now(node_of('lib', '1.0-1', [], []), true, true)!
277+ assert up.skip && up.why == 'lib-1.0-1 is up to date, skipped'
278+ assert !node_step_now(node_of('lib', '1.0-2', [], []), true, true)!.skip
279+ assert !node_step_now(node_of('lib', '0.9-1', [], []), true, true)!.skip
280+ assert !node_step_now(node_of('absent', '1.0-1', [], []), true, true)!.skip
281+ // a node nothing wanted and that is no target (never planned so, but
282+ // the rule is spelled) is built
283+ assert !node_step_now(node_of('lib', '1.0-1', [], []), false, false)!.skip
284+ // the repo dependencies left are the ones not installed, in order;
285+ // a provider under another name does not count as the package
286+ deps := node_step_now(node_of('app', '1-1', [], ['new', 'lib', 'virt', 'other']), false,
287+ true)!
288+ assert deps.repo_deps == ['new', 'virt', 'other']
289+ assert node_step_now(node_of('app', '1-1', [], []), false, true)!.repo_deps.len == 0
290+ // a skipped node asks for no repo dependencies
291+ assert node_step_now(node_of('lib', '9-1', ['lib'], ['new']), false, false)!.repo_deps.len == 0
292+}
293+
294+fn test_local_now_sees_what_an_older_handle_does_not() ! {
295+ saved_root, saved_db := root_path, db_path
296+ tmp := node_db('fresh', [testdb.Pkg{
297+ name: 'first'
298+ }])!
299+ defer {
300+ root_path, db_path = saved_root, saved_db
301+ os.rmdir_all(tmp) or {}
302+ }
303+ // the run's handle reads the local db once
304+ old_handle, old_pkgs := local_now()!
305+ defer { old_handle.release() or {} }
306+ assert old_pkgs.pkg_find('first') != none
307+ // a build's install goes in through another handle: here, written
308+ testdb.write_local(os.join_path(tmp, 'db'), [
309+ testdb.Pkg{
310+ name: 'built'
311+ version: '2.0-1'
312+ provides: ['virt=2']
313+ },
314+ ])!
315+ // the old list is the past: the staleness the plan must not be made on
316+ assert old_pkgs.pkg_find('built') == none
317+ assert old_pkgs.find_satisfier('virt') == none
318+ // a view opened now has it, and a node waiting for it is dropped
319+ view, now := local_now()!
320+ assert now.pkg_find('built') != none && now.pkg_find('first') != none
321+ assert now.find_satisfier('virt>=2') != none
322+ view.release()!
323+ assert node_step(old_pkgs, node_of('built', '2.0-1', ['virt'], []), false, false).skip == false
324+ assert node_step_now(node_of('built', '2.0-1', ['virt'], []), false, false)!.skip
325+ // an empty local db is a view of nothing, not an error
326+ os.rmdir_all(os.join_path(tmp, 'db', 'local'))!
327+ testdb.write_local(os.join_path(tmp, 'db'), [])!
328+ e_view, empty := local_now()!
329+ assert empty.pkg_find('first') == none
330+ e_view.release()!
331+ assert !node_step_now(node_of('x', '1-1', ['x'], ['dep']), false, false)!.skip
332+ // a db that is not there is an error, with nothing left open
333+ db_path = os.join_path(tmp, 'nowhere') + '/'
334+ if _, _ := local_now() {
335+ assert false, 'a missing db opened'
336+ }
337+ // nothing to install asks for no transaction at all
338+ install_repo_deps([])!
339+}
@@ -0,0 +1,173 @@
1+@[has_globals]
2+module main
3+
4+import os
5+import vmakepkg
6+
7+// root_provider is how vpac gets root: the config's (options :root "..."),
8+// sudo unless it says otherwise. vpac re-runs itself through it with the
9+// same arguments, so it gives the same pipes and exit status. it is a
10+// command line of the user's own: any program that runs the words after it
11+// as root (doas, run0, "sudo -A"), its own arguments parted by spaces. two
12+// are known by name, since they take the command another way: su wants one
13+// shell line after -c, and pkexec — which asks through the desktop's polkit
14+// agent, what a frontend without a terminal (--ui ipc) needs — must be told
15+// to stay in the working dir
16+__global root_provider = 'sudo'
17+
18+// env_invoker is how the root process learns who asked, so pkgbuild builds can run
19+// as that user. the provider may drop the environment, so it is passed through
20+// env, which every provider runs
21+const env_invoker = 'VPAC_INVOKER'
22+
23+// env_v hands the root process the invoker's own v compiler: PKGBUILD.vsh
24+// packages run through it, and the provider's sanitized path does not know
25+// where the user keeps theirs
26+const env_v = 'VPAC_V'
27+
28+// shell_words spells a command as the one line su -c hands root's shell:
29+// every word quoted whole, so the shell reads back exactly these words —
30+// the arguments are the user's, and nothing in them may become syntax
31+fn shell_words(words []string) string {
32+ return words.map(vmakepkg.shell_quote).join(' ')
33+}
34+
35+// can_write tells whether this user may write path, or create it when it does
36+// not exist yet
37+fn can_write(path string) bool {
38+ target := if os.exists(path) { path } else { os.dir(path) }
39+ return os.is_writable(target)
40+}
41+
42+// root_argv is the words handed to the root provider after its own name:
43+// the provider's own arguments, then env carrying envs, then vpac and its
44+// arguments
45+fn root_argv(provider []string, envs []string, exe string, args []string) []string {
46+ mut run := ['env']
47+ run << envs
48+ run << exe
49+ run << args
50+ mut out := provider[1..].clone()
51+ match os.base(provider[0]) {
52+ 'su' {
53+ out << ['-c', shell_words(run)]
54+ }
55+ 'pkexec' {
56+ // pkexec starts in root's home otherwise, and a relative target
57+ // (a package file, a repo dir) is relative to where vpac was run
58+ out << '--keep-cwd'
59+ out << run
60+ }
61+ else {
62+ out << run
63+ }
64+ }
65+ return out
66+}
67+
68+// reexec_as_root replaces this process with vpac running as root through the
69+// root provider. it only returns on error, and not when already root
70+fn reexec_as_root(args []string) ! {
71+ if os.geteuid() == 0 {
72+ return
73+ }
74+ invoker := current_user()!
75+ words := root_provider.fields()
76+ if words.len == 0 {
77+ return error('config: options :root names no command to get root with')
78+ }
79+ provider := os.find_abs_path_of_executable(words[0]) or {
80+ return error('${words[0]} is needed to run this as root, but it was not found: name another with (options :root "...") in the config')
81+ }
82+ // the compiler rides along, exactly like the invoker does
83+ vbin := os.find_abs_path_of_executable('v') or { '' }
84+ mut envs := ['${env_invoker}=${invoker}']
85+ if vbin != '' {
86+ envs << '${env_v}=${vbin}'
87+ }
88+ // os.execvp spells argv[0] out of cmdpath itself, so the list handed
89+ // here is the words after the program name, and the process list shows
90+ // the provider correctly spelled rather than one word short
91+ os.execvp(provider, root_argv(words, envs, os.executable(), args))!
92+}
93+
94+#include <pwd.h>
95+
96+struct C.passwd {
97+ pw_name &char
98+ pw_uid u32
99+ pw_dir &char
100+}
101+
102+fn C.getpwnam(name &char) &C.passwd
103+
104+fn C.getpwuid(uid u32) &C.passwd
105+
106+// current_user is the user this process runs as, named from its real uid:
107+// the user doas, sudo and pkexec report as their caller too. getlogin(3),
108+// which os.loginname is, answers the session's login instead — the user
109+// before an su, or nobody without a login session (a frontend started by a
110+// service) — and a build would land in another user's home, or nowhere
111+fn current_user() !string {
112+ uid := os.getuid()
113+ pw := C.getpwuid(u32(uid))
114+ if pw == unsafe { nil } || pw.pw_name == unsafe { nil } {
115+ return error('could not tell which user is running vpac: uid ${uid} is not in the password database')
116+ }
117+ // getpwuid hands out a static buffer: the name is copied out of it
118+ return unsafe { cstring_to_vstring(pw.pw_name) }
119+}
120+
121+// user_uid is a user's uid from the password database, none when there is
122+// no such user
123+fn user_uid(user string) ?u32 {
124+ pw := C.getpwnam(&char(user.str))
125+ if pw == unsafe { nil } {
126+ return none
127+ }
128+ return pw.pw_uid
129+}
130+
131+// invoker_of checks the user the escalation passed on before root builds
132+// as it: a user of the password database, and not one with root's uid. root
133+// is told by uid, not by name, since an alias of uid 0 is root to runuser
134+// and to every file a build or a .vsh generator touches. the name comes from
135+// vpac's own re-execution; the check keeps a stray or hand-set one from
136+// aiming the builds at root or at nobody
137+fn invoker_of(user string) !string {
138+ if user == '' {
139+ return error('pkgbuild packages are built as your user: run vpac as your user, it asks for root itself')
140+ }
141+ uid := user_uid(user) or {
142+ return error('the invoking user "${user}" (${env_invoker}) is not in the password database')
143+ }
144+ if uid == 0 {
145+ 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')
146+ }
147+ return user
148+}
149+
150+// user_home is a user's home dir from the password database, as getent
151+// passwd finds it: through nss, so a home outside /home (/home2, an ldap
152+// account) is right. the invoker's $HOME is not asked: the root process
153+// would then list and size a path the user can set to anything
154+fn user_home(user string) !string {
155+ pw := C.getpwnam(&char(user.str))
156+ if pw == unsafe { nil } || pw.pw_dir == unsafe { nil } {
157+ return error('no home directory for user ${user} in the password database')
158+ }
159+ // getpwnam hands out a static buffer: the path is copied out of it
160+ return unsafe { cstring_to_vstring(pw.pw_dir) }
161+}
162+
163+// invoker_user is who asked for this run: the user the escalation passed
164+// on, or, in a run that never escalated (a --print preview), the user
165+// running it
166+fn invoker_user() !string {
167+ if os.geteuid() != 0 {
168+ // the same answer reexec_as_root passes on: a user that cannot be
169+ // told is an error, not an empty user to build under
170+ return current_user()
171+ }
172+ return invoker_of(os.getenv(env_invoker))
173+}
@@ -0,0 +1,119 @@
1+module main
2+
3+import os
4+
5+// id_un is the running user as coreutils' id names it: by the real uid, the
6+// way the escalation tools name their caller
7+fn id_un() string {
8+ res := os.exec(['id', '-un'])
9+ assert res.exit_code == 0, 'id -un failed: ${res.output}'
10+ return res.output.trim_space()
11+}
12+
13+fn test_current_user_is_the_real_uid() {
14+ // getlogin(3) would answer the session's login, which differs after an
15+ // su and is absent without a login session; the real uid always names
16+ // the user running vpac
17+ assert current_user()! == id_un()
18+}
19+
20+fn test_invoker_user_unescalated_is_the_running_user() {
21+ if os.geteuid() == 0 {
22+ // root reads the invoker from the escalation instead
23+ return
24+ }
25+ assert invoker_user()! == id_un()
26+}
27+
28+fn test_invoker_of_accepts_a_user_of_the_password_database() {
29+ me := current_user()!
30+ if os.getuid() == 0 {
31+ // a root test run has no unprivileged user of its own to accept
32+ return
33+ }
34+ assert invoker_of(me)! == me
35+}
36+
37+fn test_invoker_of_rejects_root_by_uid() {
38+ // root is turned away through its uid, the same check that turns away
39+ // any alias of uid 0: the name 'root' is not special-cased
40+ invoker_of('root') or {
41+ assert err.msg().contains('not as root')
42+ assert err.msg().contains('uid 0')
43+ return
44+ }
45+ assert false, 'root accepted as the invoker'
46+}
47+
48+fn test_invoker_of_rejects_an_unknown_user() {
49+ name := 'vpac-no-such-user-${os.getpid()}'
50+ invoker_of(name) or {
51+ assert err.msg().contains('not in the password database')
52+ assert err.msg().contains(name)
53+ return
54+ }
55+ assert false, 'an unknown user accepted as the invoker'
56+}
57+
58+fn test_invoker_of_rejects_an_empty_name() {
59+ invoker_of('') or {
60+ assert err.msg().contains('run vpac as your user')
61+ return
62+ }
63+ assert false, 'an empty invoker accepted'
64+}
65+
66+fn test_user_uid() {
67+ assert user_uid('root')? == 0
68+ assert user_uid(current_user()!)? == u32(os.getuid())
69+ if _ := user_uid('vpac-no-such-user-${os.getpid()}') {
70+ assert false, 'an unknown user has a uid'
71+ }
72+}
73+
74+fn test_user_home_matches_the_password_database() {
75+ // getent passwd reads through nss, as getpwnam does: field 6 is the home
76+ me := current_user()!
77+ res := os.exec(['getent', 'passwd', me])
78+ if res.exit_code != 0 {
79+ // no getent on this system: nothing to compare against
80+ return
81+ }
82+ fields := res.output.trim_space().split(':')
83+ assert fields.len >= 6
84+ assert user_home(me)! == fields[5]
85+ if _ := user_home('vpac-no-such-user-${os.getpid()}') {
86+ assert false, 'an unknown user has a home'
87+ }
88+}
89+
90+fn test_shell_words_reads_back_as_the_words() {
91+ // what su -c gives root's shell: the words come back one for one, with
92+ // nothing in them expanded or run
93+ words := ['env', 'VPAC_INVOKER=me', '/usr/bin/vpac', 'i', "it's", '$(id)', '`id`', 'a b', 'x;y',
94+ '--eval=(define x "q")', '']
95+ line := os.exec(['sh', '-c',
96+ 'set -- ' + shell_words(words) + '; for w in "$@"; do printf "[%s]" "$w"; done'])
97+ assert line.exit_code == 0, line.output
98+ assert line.output == words.map('[${it}]').join('')
99+}
100+
101+// the provider's own arguments come first; su takes the run as one quoted
102+// shell line, pkexec is kept in the working dir, and a command vpac does
103+// not know is handed the words as sudo is
104+fn test_root_argv() {
105+ envs := ['VPAC_INVOKER=me']
106+ args := ['i', 'a b']
107+ run := ['env', 'VPAC_INVOKER=me', '/usr/bin/vpac', 'i', 'a b']
108+ assert root_argv(['sudo'], envs, '/usr/bin/vpac', args) == run
109+ mut custom := ['-A', '--']
110+ custom << run
111+ assert root_argv(['/opt/bin/myroot', '-A', '--'], envs, '/usr/bin/vpac', args) == custom
112+ mut pk := ['--keep-cwd']
113+ pk << run
114+ assert root_argv(['pkexec'], envs, '/usr/bin/vpac', args) == pk
115+ su := root_argv(['/usr/bin/su', '-l'], envs, '/usr/bin/vpac', args)
116+ assert su[..2] == ['-l', '-c']
117+ assert su.len == 3
118+ assert su[2].contains("'a b'"), su[2]
119+}
@@ -0,0 +1,247 @@
1+module main
2+
3+import os
4+import strconv
5+
6+// Prompter is the one way vpac asks the user anything: a yes or no
7+// question, the go-ahead of a transaction, a pick among numbered choices.
8+// every prompt of every command goes through the one its TransUI carries
9+// (ui.yesno, ui.noyes, ui.proceed, ui.choose), so a second frontend answers
10+// them all by bringing its own. the terminal is the default.
11+// noconfirm is --noconfirm, the policy every prompter honours: each question
12+// is still shown, and its default taken without waiting for an answer, so an
13+// unattended run never blocks
14+interface Prompter {
15+mut:
16+ noconfirm bool
17+ // confirm asks a yes or no question; preset is what an empty answer takes
18+ confirm(msg string, preset bool) bool
19+ // proceed asks for the go-ahead of a transaction: pacman's 'Proceed with
20+ // installation? [Y/n]', where an empty answer is yes. noconfirm gives it
21+ proceed(msg string) bool
22+ // choose asks for one of the choices and returns its index; the first is
23+ // the preset. the terminal has listed them already, and asks a number
24+ choose(msg string, choices []string) int
25+ // pick asks for any number of the choices and returns which, one bool
26+ // per choice; all of them is the preset. the terminal has listed them
27+ // already, and asks for numbers and ranges
28+ pick(msg string, count int) []bool
29+}
30+
31+// TermPrompter asks on the terminal, following pacman's question() and
32+// select_question(). every prompt goes to stderr, the noconfirm echo too, so
33+// piped output (install -p, search -q) carries only results; pacman prints
34+// the noconfirm echo on stdout, which mixes it into such output
35+struct TermPrompter {
36+mut:
37+ noconfirm bool
38+}
39+
40+// StdinEnd is what stdin_line answers once stdin has nothing left
41+struct StdinEnd {
42+ Error
43+}
44+
45+fn (e StdinEnd) msg() string {
46+ return 'end of input'
47+}
48+
49+// stdin_line reads one line from stdin, without its newline; a last line
50+// that has none is a line too, as pacman's fgets gives it. the end of input
51+// is a StdinEnd, and a read error (stdin closed, or a directory) an error of
52+// its own: a prompt takes both as no, the way pacman's question() takes the
53+// NULL fgets answers to both, while a reader of a whole list must not take
54+// a cut for its end. os.get_raw_line panics on the read error, and keeps the
55+// newline, which a caller then has to tell an empty answer from the end by
56+fn stdin_line() !string {
57+ mut buf := &u8(unsafe { nil })
58+ mut size := uint(0)
59+ n := C.getline(voidptr(&buf), voidptr(&size), C.stdin)
60+ // getline allocates with libc's malloc, even when it fails
61+ defer {
62+ unsafe { C.free(buf) }
63+ }
64+ if n < 0 {
65+ if C.ferror(C.stdin) != 0 {
66+ return error('could not read stdin: ${os.posix_get_error_msg(C.errno)}')
67+ }
68+ return StdinEnd{}
69+ }
70+ // the line is cloned out of getline's buffer either way: a plain slice
71+ // would still point into what the defer frees
72+ line := unsafe { tos(buf, n) }
73+ return if line.ends_with('\n') { line[..line.len - 1].clone() } else { line.clone() }
74+}
75+
76+// the answer labels of a question, the default in bold
77+fn q_yes_no() string {
78+ return '[' + erole('default', 'Y') + '/n]'
79+}
80+
81+fn q_no_yes() string {
82+ return '[y/' + erole('default', 'N') + ']'
83+}
84+
85+// confirm follows pacman's question(): an empty answer takes the preset,
86+// y/yes is yes, and anything else is no — the end of input and a stdin that
87+// cannot be read too, whatever the preset, so an unattended run that meant
88+// no answer never says yes. with noconfirm the question is printed and the
89+// preset taken without reading stdin
90+fn (mut p TermPrompter) confirm(msg string, preset bool) bool {
91+ label := if preset { q_yes_no() } else { q_no_yes() }
92+ os.flush()
93+ if p.noconfirm {
94+ eprintln(erole('prompt', '${msg} ${label}'))
95+ return preset
96+ }
97+ eprint(erole('prompt', '${msg} ${label} '))
98+ line := stdin_line() or { return false }
99+ return match line.trim_space().to_lower() {
100+ '' { preset }
101+ 'y', 'yes' { true }
102+ else { false }
103+ }
104+}
105+
106+// proceed is confirm with a yes preset; with noconfirm the echo says the
107+// yes came from the flag
108+fn (mut p TermPrompter) proceed(msg string) bool {
109+ if p.noconfirm {
110+ os.flush()
111+ eprintln(erole('prompt', '${msg} ${q_yes_no()} (yes, --noconfirm)'))
112+ return true
113+ }
114+ return p.confirm(msg, true)
115+}
116+
117+// choose follows pacman's select_question(): it asks for a number from 1 to
118+// the count of choices, where an empty answer and end of input (or a stdin
119+// that cannot be read) take the first, and an answer that is not one of the
120+// numbers asks again. with noconfirm the question is printed and the first
121+// taken without reading stdin. end of input is safe to default here: the
122+// transaction's own 'proceed?' comes after and takes end of input as no
123+fn (mut p TermPrompter) choose(msg string, choices []string) int {
124+ count := choices.len
125+ label := '[1-${count}, default ' + erole('default', '1') + ']'
126+ os.flush()
127+ if p.noconfirm {
128+ eprintln(erole('prompt', '${msg} ${label}'))
129+ return 0
130+ }
131+ for {
132+ eprint(erole('prompt', '${msg} ${label} '))
133+ answer := (stdin_line() or { return 0 }).trim_space()
134+ if answer == '' {
135+ return 0
136+ }
137+ n := strconv.atoi(answer) or { 0 }
138+ if n >= 1 && n <= count {
139+ return n - 1
140+ }
141+ eprintln('invalid number: ${answer}')
142+ }
143+}
144+
145+// parse_selection reads an answer to pick the way pacman's
146+// multiselect_parse does: numbers and ranges (2-4) parted by spaces or
147+// commas, a leading ^ leaving one out. everything starts selected; an answer
148+// whose first word selects starts from nothing instead, so '2 5' is those
149+// two and '^3' is all but the third
150+fn parse_selection(answer string, count int) ![]bool {
151+ mut picked := []bool{len: count, init: true}
152+ words := answer.replace(',', ' ').fields()
153+ for i, word in words {
154+ mut text := word
155+ include := !text.starts_with('^')
156+ if !include {
157+ text = text[1..]
158+ } else if i == 0 {
159+ picked = []bool{len: count}
160+ }
161+ // a range's dash is looked for past the first byte, as pacman does
162+ mut first := text
163+ mut last := ?string(none)
164+ if text.len > 1 {
165+ if dash := text.index_after('-', 1) {
166+ first = text[..dash]
167+ last = text[dash + 1..]
168+ }
169+ }
170+ start := selection_index(first, 1, count)!
171+ mut end := start
172+ if upto := last {
173+ end = selection_index(upto, start, count)!
174+ }
175+ for n in start .. end + 1 {
176+ picked[n - 1] = include
177+ }
178+ }
179+ return picked
180+}
181+
182+// selection_index is one number of a selection, within its bounds
183+fn selection_index(text string, min int, max int) !int {
184+ n := strconv.atoi(text) or { return error('invalid number: ${text}') }
185+ if n < min || n > max {
186+ return error('invalid value: ${n} is not between ${min} and ${max}')
187+ }
188+ return n
189+}
190+
191+// pick follows pacman's multiselect_question(): an empty answer takes them
192+// all, an answer that does not parse asks again. with noconfirm the
193+// question is printed and all taken. end of input, or a stdin that cannot be
194+// read, selects nothing: pacman fails the target there, and nothing chosen
195+// is the same refusal without the abort
196+fn (mut p TermPrompter) pick(msg string, count int) []bool {
197+ label := '(default=' + erole('default', 'all') + '):'
198+ os.flush()
199+ if p.noconfirm {
200+ eprintln(erole('prompt', '${msg} ${label}'))
201+ return []bool{len: count, init: true}
202+ }
203+ for {
204+ eprint(erole('prompt', '${msg} ${label} '))
205+ answer := (stdin_line() or { return []bool{len: count} }).trim_space()
206+ if answer == '' {
207+ return []bool{len: count, init: true}
208+ }
209+ return parse_selection(answer, count) or {
210+ eprintln(err.msg())
211+ continue
212+ }
213+ }
214+ return []bool{len: count}
215+}
216+
217+// yesno asks a question whose empty answer is yes. the live display is
218+// paused first, as for every prompt: a redraw would erase the question and
219+// leave the program waiting on one nobody sees
220+fn (mut ui TransUI) yesno(msg string) bool {
221+ ui.pause()
222+ return ui.prompt.confirm(msg, true)
223+}
224+
225+// noyes asks a question whose empty answer is no
226+fn (mut ui TransUI) noyes(msg string) bool {
227+ ui.pause()
228+ return ui.prompt.confirm(msg, false)
229+}
230+
231+// proceed asks for the go-ahead of a transaction
232+fn (mut ui TransUI) proceed(msg string) bool {
233+ ui.pause()
234+ return ui.prompt.proceed(msg)
235+}
236+
237+// choose asks for one of the choices and returns its index
238+fn (mut ui TransUI) choose(msg string, choices []string) int {
239+ ui.pause()
240+ return ui.prompt.choose(msg, choices)
241+}
242+
243+// pick asks for any number of count choices, already listed
244+fn (mut ui TransUI) pick(msg string, count int) []bool {
245+ ui.pause()
246+ return ui.prompt.pick(msg, count)
247+}
@@ -0,0 +1,512 @@
1+module main
2+
3+import json2
4+import os
5+
6+#include <stdio_ext.h>
7+#include <fcntl.h>
8+
9+fn C.__fpurge(stream &C.FILE)
10+
11+fn C.clearerr(stream &C.FILE)
12+
13+// Scripted is a second frontend's prompter in miniature: it answers every
14+// question the same, and keeps what it was asked
15+struct Scripted {
16+mut:
17+ noconfirm bool
18+ yes bool
19+ asked []string
20+}
21+
22+fn (mut p Scripted) confirm(msg string, _ bool) bool {
23+ p.asked << msg
24+ return p.yes
25+}
26+
27+fn (mut p Scripted) proceed(msg string) bool {
28+ p.asked << msg
29+ return p.yes
30+}
31+
32+fn (mut p Scripted) choose(msg string, choices []string) int {
33+ p.asked << msg
34+ return choices.len - 1
35+}
36+
37+fn (mut p Scripted) pick(msg string, count int) []bool {
38+ p.asked << msg
39+ return []bool{len: count, init: p.yes}
40+}
41+
42+fn test_parse_selection_as_pacman() ! {
43+ // the first word selecting starts from nothing; ranges and commas
44+ assert parse_selection('2 4', 5)! == [false, true, false, true, false]
45+ assert parse_selection('1-3,5', 5)! == [true, true, true, false, true]
46+ // a first word leaving out starts from everything
47+ assert parse_selection('^2', 3)! == [true, false, true]
48+ assert parse_selection('^1-2', 3)! == [false, false, true]
49+ // later words add to or take from what stands
50+ assert parse_selection('1-4 ^3', 4)! == [true, true, false, true]
51+ for bad in ['0', '6', 'x', '3-2', '2-9', '1-'] {
52+ if _ := parse_selection(bad, 5) {
53+ assert false, '"${bad}" was taken'
54+ }
55+ }
56+}
57+
58+fn test_select_answer_is_a_list_of_indices() ! {
59+ assert parse_select_answer('{"id": 3, "answer": [0, 2]}', 3, 3)! == [true, false, true]
60+ assert parse_select_answer('{"id": 3, "answer": []}', 3, 3)! == [false, false, false]
61+ for bad in ['{"id": 3, "answer": true}', '{"id": 3, "answer": [3]}', '{"id": 3, "answer": [0.5]}',
62+ '{"id": 2, "answer": [0]}', 'noise'] {
63+ if _ := parse_select_answer(bad, 3, 3) {
64+ assert false, '${bad} was taken'
65+ }
66+ }
67+}
68+
69+fn test_noconfirm_takes_the_defaults() {
70+ // the questions go to stderr; stdin is never read, so none of these blocks
71+ mut ui := new_trans_ui(noconfirm: true)
72+ assert ui.yesno('a?')
73+ assert !ui.noyes('b?')
74+ assert ui.proceed('proceed?')
75+ assert ui.choose('which one?', ['a', 'b', 'c']) == 0
76+ assert ui.pick('which ones?', 3) == [true, true, true]
77+}
78+
79+fn test_policy_through_the_interface() {
80+ mut ui := new_trans_ui()
81+ assert !ui.prompt.noconfirm
82+ // a mode may flip the policy for one listing, through the interface,
83+ // whichever prompter is behind it
84+ ui.prompt.noconfirm = true
85+ assert ui.proceed('proceed?')
86+}
87+
88+fn test_every_prompt_reaches_the_prompter() ! {
89+ mut ui := new_trans_ui()
90+ ui.prompt = Scripted{
91+ yes: true
92+ }
93+ assert did_you_mean(mut ui, 'zshh', ['zsh', 'bash'])! == 'zsh'
94+ assert ui.choose('which one?', ['a', 'b', 'c']) == 2
95+ assert ui.proceed('proceed?')
96+ // nothing near the query: the error comes without a question
97+ if _ := did_you_mean(mut ui, 'qqqqqq', ['zsh']) {
98+ assert false
99+ }
100+ s := ui.prompt as Scripted
101+ assert s.asked.len == 3
102+ assert s.asked[1..] == ['which one?', 'proceed?']
103+
104+ ui.prompt = Scripted{
105+ yes: false
106+ }
107+ if _ := did_you_mean(mut ui, 'zshh', ['zsh']) {
108+ assert false
109+ }
110+}
111+
112+// StdinSource is what a scripted stdin reads: the text given, a stdin that
113+// is closed, or a directory, which every read fails on
114+enum StdinSource {
115+ text
116+ closed
117+ directory
118+}
119+
120+// Scripted run is what on_stdin hands back: the answers the prompts gave,
121+// what they wrote to stderr, and the ipc channel's lines
122+struct ScriptedRun {
123+ answers []int
124+ stderr string
125+ channel []string
126+}
127+
128+// reset_stdin drops what stdio buffered of the stdin before, and its end of
129+// file mark, so one script's leftovers never reach the next
130+fn reset_stdin() {
131+ C.__fpurge(C.stdin)
132+ C.clearerr(C.stdin)
133+}
134+
135+// on_stdin runs ask with fd 0 reading from source, fd 2 and the ipc channel
136+// each written to a file, then puts all three back. it is the real stdin
137+// that is read, through stdio as the prompters read it, so what the libc
138+// and the line reader make of an end or a failure is what is tested
139+fn on_stdin(source StdinSource, text string, ask fn () []int) !ScriptedRun {
140+ dir := os.join_path(os.vtmp_dir(), 'vpac_test_prompt_${os.getpid()}')
141+ os.mkdir_all(dir)!
142+ defer { os.rmdir_all(dir) or {} }
143+ os.write_file(os.join_path(dir, 'stdin'), text)!
144+ mut in_file := os.open(os.join_path(dir, 'stdin'))!
145+ defer { in_file.close() }
146+ mut err_file := os.create(os.join_path(dir, 'stderr'))!
147+ mut chan_file := os.create(os.join_path(dir, 'channel'))!
148+ defer {
149+ err_file.close()
150+ chan_file.close()
151+ }
152+ dir_fd := C.open(&char(dir.str), C.O_RDONLY)
153+ saved_in := C.dup(0)
154+ saved_err := C.dup(2)
155+ // whatever was opened is closed again on every way out, the failed
156+ // setup's included: a descriptor left behind would be the next
157+ // script's stdin by number
158+ defer {
159+ for fd in [dir_fd, saved_in, saved_err] {
160+ if fd >= 0 {
161+ C.close(fd)
162+ }
163+ }
164+ }
165+ if dir_fd < 0 || saved_in < 0 || saved_err < 0 {
166+ return error('could not set the scripted stdin up')
167+ }
168+ saved_ipc := ipc_fd
169+ reset_stdin()
170+ // dup2 answers the new descriptor, never 0, on success
171+ wired_in := match source {
172+ .text { C.dup2(in_file.fd, 0) >= 0 }
173+ .closed { C.close(0) == 0 }
174+ .directory { C.dup2(dir_fd, 0) >= 0 }
175+ }
176+ wired_err := C.dup2(err_file.fd, 2) >= 0
177+ mut answers := []int{}
178+ if wired_in && wired_err {
179+ ipc_fd = chan_file.fd
180+ answers = ask()
181+ ipc_fd = saved_ipc
182+ }
183+ // the real stdin and stderr come back whether or not the script ran
184+ back_in := C.dup2(saved_in, 0) >= 0
185+ back_err := C.dup2(saved_err, 2) >= 0
186+ reset_stdin()
187+ if !wired_in || !wired_err {
188+ return error('could not point stdin or stderr at the script')
189+ }
190+ if !back_in || !back_err {
191+ return error('could not put stdin or stderr back after the script')
192+ }
193+ err_file.flush()
194+ chan_file.flush()
195+ return ScriptedRun{
196+ answers: answers
197+ stderr: os.read_file(os.join_path(dir, 'stderr'))!
198+ channel: os.read_lines(os.join_path(dir, 'channel'))!
199+ }
200+}
201+
202+fn yn(b bool) int {
203+ return if b { 1 } else { 0 }
204+}
205+
206+// confirm_both asks one question on the script with a yes preset, and the
207+// same on the same script with a no preset
208+fn confirm_both(text string) ![]int {
209+ yes := on_stdin(.text, text, fn () []int {
210+ mut p := TermPrompter{}
211+ return [yn(p.confirm('a?', true))]
212+ })!
213+ no := on_stdin(.text, text, fn () []int {
214+ mut p := TermPrompter{}
215+ return [yn(p.confirm('a?', false))]
216+ })!
217+ return [yes.answers[0], no.answers[0]]
218+}
219+
220+fn test_term_confirm_reads_the_answer_on_stdin() ! {
221+ // [with a yes preset, with a no preset], as pacman's question() answers
222+ for text, want in {
223+ // end of input is no, whatever the preset
224+ '': [0, 0]
225+ // an empty answer, blanks or not, takes the preset
226+ '\n': [1, 0]
227+ ' \t \n': [1, 0]
228+ 'y\n': [1, 1]
229+ 'Y\n': [1, 1]
230+ 'yes\n': [1, 1]
231+ ' YeS \n': [1, 1]
232+ 'n\n': [0, 0]
233+ 'no\n': [0, 0]
234+ // anything else is no, even with a yes preset
235+ 'maybe\n': [0, 0]
236+ 'yess\n': [0, 0]
237+ // a last line without its newline is an answer, as fgets reads it
238+ 'y': [1, 1]
239+ 'n': [0, 0]
240+ } {
241+ assert confirm_both(text)! == want, 'stdin ${text}'
242+ }
243+}
244+
245+fn test_term_confirm_unreadable_stdin_is_no() ! {
246+ // a closed stdin, or one that is a directory, fails the read: no answer
247+ // comes, so the question is no — no panic, and no yes from the preset
248+ for source in [StdinSource.closed, .directory] {
249+ run := on_stdin(source, '', fn () []int {
250+ mut p := TermPrompter{}
251+ return [yn(p.confirm('a?', true)), yn(p.proceed('go?')),
252+ p.choose('which?', ['x', 'y', 'z'])]
253+ })!
254+ assert run.answers == [0, 0, 0], '${source}'
255+ // the questions were still put
256+ assert run.stderr.contains('a?') && run.stderr.contains('go?')
257+ }
258+}
259+
260+fn test_term_prompts_take_one_line_each() ! {
261+ // each question reads its own line, no more; the end comes after
262+ run := on_stdin(.text, 'y\nn\n\n2\n', fn () []int {
263+ mut p := TermPrompter{}
264+ return [yn(p.confirm('one?', false)), yn(p.confirm('two?', true)),
265+ yn(p.confirm('three?', true)), p.choose('four?', ['a', 'b']), yn(p.confirm('five?', true))]
266+ })!
267+ assert run.answers == [1, 0, 1, 1, 0]
268+ // the prompts go to stderr, in order, with their answer labels
269+ for q in ['one?', 'two?', 'three?', 'four?', 'five?'] {
270+ assert run.stderr.contains(q)
271+ }
272+ assert run.stderr.index('one?')? < run.stderr.index('five?')?
273+}
274+
275+fn test_term_proceed_end_of_input_is_no() ! {
276+ // the go-ahead has a yes preset, which an empty answer takes, but the end
277+ // of input never gives it
278+ for text, want in {
279+ '': 0
280+ '\n': 1
281+ 'n\n': 0
282+ 'yes': 1
283+ } {
284+ run := on_stdin(.text, text, fn () []int {
285+ mut p := TermPrompter{}
286+ return [yn(p.proceed('proceed?'))]
287+ })!
288+ assert run.answers == [want], 'stdin ${text}'
289+ }
290+}
291+
292+fn test_term_choose_reads_a_number() ! {
293+ for text, want in {
294+ '2\n': 1
295+ ' 3 \n': 2
296+ // an empty answer and the end of input take the first
297+ '\n': 0
298+ '': 0
299+ // what is not a number of the list asks again
300+ 'x\n9\n0\n3\n': 2
301+ '-1\n2\n': 1
302+ // and the end of input after it takes the first
303+ 'x\n': 0
304+ } {
305+ run := on_stdin(.text, text, fn () []int {
306+ mut p := TermPrompter{}
307+ return [p.choose('which?', ['a', 'b', 'c'])]
308+ })!
309+ assert run.answers == [want], 'stdin ${text}'
310+ // every answer that is not a number of the list is said, and the
311+ // question asked again: once more than the bad answers before the
312+ // good one, or before the input ended
313+ bad := text.split('\n').filter(it.trim_space() in ['x', '9', '0', '-1'])
314+ for b in bad {
315+ assert run.stderr.contains('invalid number: ${b}'), 'stdin ${text}: ${run.stderr}'
316+ }
317+ assert run.stderr.count('which?') == bad.len + 1, 'stdin ${text}: ${run.stderr}'
318+ }
319+}
320+
321+fn test_term_noconfirm_leaves_stdin_unread() ! {
322+ // --noconfirm shows each question and takes its default; the answer on
323+ // stdin is still there for the first question that does read it
324+ run := on_stdin(.text, '3\n', fn () []int {
325+ mut quiet := TermPrompter{
326+ noconfirm: true
327+ }
328+ mut asks := TermPrompter{}
329+ return [yn(quiet.confirm('a?', false)), yn(quiet.proceed('go?')),
330+ quiet.choose('which?', ['a', 'b', 'c']), asks.choose('again?', ['a', 'b', 'c'])]
331+ })!
332+ assert run.answers == [0, 1, 0, 2]
333+ assert run.stderr.contains('(yes, --noconfirm)')
334+}
335+
336+fn test_stdin_line() ! {
337+ // a line comes without its newline, an empty line as '', a last line
338+ // without a newline whole; then the end, a StdinEnd. an unreadable stdin
339+ // is an error of its own, not the end
340+ run := on_stdin(.text, 'one\n\nlast', fn () []int {
341+ mut got := []int{}
342+ for want in ['one', '', 'last'] {
343+ line := stdin_line() or { return [-1] }
344+ got << yn(line == want)
345+ }
346+ stdin_line() or { got << yn(err is StdinEnd) }
347+ return got
348+ })!
349+ assert run.answers == [1, 1, 1, 1]
350+ for source in [StdinSource.closed, .directory] {
351+ failed := on_stdin(source, '', fn () []int {
352+ stdin_line() or {
353+ return [yn(err !is StdinEnd), yn(err.msg().starts_with('could not read stdin'))]
354+ }
355+ return [-1]
356+ })!
357+ assert failed.answers == [1, 1], '${source}'
358+ }
359+}
360+
361+fn test_stdin_line_outlives_the_read_buffer() ! {
362+ // a line is the caller's own copy: getline's buffer is freed on the way
363+ // out, and the next read (same length, so the allocator hands the same
364+ // block back) must not show through a line already returned. lines with
365+ // and without the newline, an empty one, and a long one that makes
366+ // getline grow its buffer
367+ long := 'x'.repeat(5000)
368+ run := on_stdin(.text, 'aaaa\nbbbb\n\n${long}\ncccc', fn [long] () []int {
369+ mut lines := []string{}
370+ for _ in 0 .. 5 {
371+ lines << stdin_line() or { return [-1] }
372+ // churn the heap between reads, as a prompt's own work does
373+ mut junk := []string{}
374+ for i in 0 .. 64 {
375+ junk << 'zzzz${i}'.repeat(1 + i % 7)
376+ }
377+ }
378+ return [yn(lines == ['aaaa', 'bbbb', '', long, 'cccc']), lines[3].len]
379+ })!
380+ assert run.answers == [1, 5000]
381+}
382+
383+fn test_stdin_text() ! {
384+ run := on_stdin(.text, 'https://a.example/\nhttps://b.example/\n', fn () []int {
385+ text := stdin_text() or { return [-1] }
386+ return [yn(text == 'https://a.example/\nhttps://b.example/')]
387+ })!
388+ assert run.answers == [1]
389+ // a read that fails is an error, not an empty list
390+ failed := on_stdin(.directory, '', fn () []int {
391+ stdin_text() or { return [yn(err.msg().contains('could not read stdin'))] }
392+ return [-1]
393+ })!
394+ assert failed.answers == [1]
395+}
396+
397+// ipc_events decodes the channel's lines, every one a whole json object
398+fn ipc_events(lines []string) ![]map[string]json2.Any {
399+ mut out := []map[string]json2.Any{}
400+ for line in lines {
401+ out << json2.decode[json2.Any](line)!.as_map()
402+ }
403+ return out
404+}
405+
406+fn test_ipc_prompter_reads_answers_on_stdin() ! {
407+ run := on_stdin(.text, '{"id": 1, "answer": true}\n{"id": 2, "answer": 2}\n', fn () []int {
408+ mut p := IpcPrompter{}
409+ return [yn(p.confirm('a?', false)), p.choose('which?', ['x', 'y', 'z'])]
410+ })!
411+ assert run.answers == [1, 2]
412+ events := ipc_events(run.channel)!
413+ assert events.len == 2
414+ assert events[0]['type']!.str() == 'question'
415+ assert events[0]['question']!.str() == 'confirm'
416+ assert events[0]['id']!.int() == 1
417+ assert events[1]['question']!.str() == 'choose'
418+ assert events[1]['id']!.int() == 2
419+}
420+
421+fn test_ipc_prompter_invalid_lines_keep_the_question() ! {
422+ // noise, an empty line and another question's answer are each an invalid
423+ // event; the question stays, and the next valid line answers it
424+ run := on_stdin(.text, 'garbage\n\n{"id": 9, "answer": true}\n{"id": 1, "answer": false}\n', fn () []int {
425+ mut p := IpcPrompter{}
426+ return [yn(p.confirm('a?', true))]
427+ })!
428+ assert run.answers == [0]
429+ events := ipc_events(run.channel)!
430+ assert events.map(it['type']!.str()) == ['question', 'invalid', 'invalid', 'invalid']
431+ for e in events[1..] {
432+ assert e['id']!.int() == 1
433+ }
434+}
435+
436+fn test_ipc_prompter_end_of_input() ! {
437+ // the end of input, and a stdin that cannot be read, answer as on a
438+ // terminal: no, and the first choice — no panic
439+ for source in [StdinSource.text, .closed, .directory] {
440+ run := on_stdin(source, '', fn () []int {
441+ mut p := IpcPrompter{}
442+ return [yn(p.confirm('a?', true)), yn(p.proceed('go?')), p.choose('which?', [
443+ 'x',
444+ 'y',
445+ ])]
446+ })!
447+ assert run.answers == [0, 0, 0], '${source}'
448+ assert ipc_events(run.channel)!.len == 3
449+ }
450+}
451+
452+fn test_ipc_prompter_noconfirm_answers_in_the_event() ! {
453+ run := on_stdin(.text, '{"id": 1, "answer": false}\n', fn () []int {
454+ mut p := IpcPrompter{
455+ noconfirm: true
456+ }
457+ return [yn(p.confirm('a?', true))]
458+ })!
459+ assert run.answers == [1]
460+ events := ipc_events(run.channel)!
461+ assert events.len == 1
462+ assert events[0]['answer']!.bool() == true
463+}
464+
465+fn test_verbose_log_says_what_a_run_went_on_from() ! {
466+ saved_flag, saved_cfg, saved_kind := verbose_flag, cfg_verbose, ui_kind
467+ defer {
468+ verbose_flag, cfg_verbose, ui_kind = saved_flag, saved_cfg, saved_kind
469+ }
470+ fail := fn () []int {
471+ went_on('release the alpm handle', error('the handle is not there'))
472+ went_on('remove the temp dir /tmp/x', error(''))
473+ return []
474+ }
475+ // without --verbose a housekeeping failure stays as quiet as it was:
476+ // nothing on stderr, nothing on the channel
477+ verbose_flag, cfg_verbose, ui_kind = false, false, 'tty'
478+ quiet := on_stdin(.text, '', fail)!
479+ assert quiet.stderr == '' && quiet.channel.len == 0
480+ ui_kind = 'ipc'
481+ quiet_ipc := on_stdin(.text, '', fail)!
482+ assert quiet_ipc.stderr == '' && quiet_ipc.channel.len == 0
483+ // the flag and the config's option each turn it on, alone
484+ for flag in [true, false] {
485+ verbose_flag, cfg_verbose, ui_kind = flag, !flag, 'tty'
486+ said := on_stdin(.text, '', fail)!
487+ // a terminal gets it on stderr, marked, the reason after the what;
488+ // a failure with no text of its own still names what failed
489+ 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
490+ assert said.channel.len == 0
491+ // a frontend gets a message event marked verbose, and a warning for
492+ // a reader that knows no verbose mark; stderr stays clean
493+ ui_kind = 'ipc'
494+ told := on_stdin(.text, '', fail)!
495+ assert told.stderr == '', told.stderr
496+ events := ipc_events(told.channel)!
497+ assert events.len == 2
498+ assert events[0]['type']!.str() == 'message'
499+ assert events[0]['text']!.str() == 'could not release the alpm handle: the handle is not there'
500+ assert events[0]['verbose']!.bool() && events[0]['warning']!.bool()
501+ }
502+ // an ordinary warning never carries the mark, verbose on or not
503+ verbose_flag, ui_kind = true, 'ipc'
504+ plain := on_stdin(.text, '', fn () []int {
505+ warn('a real warning')
506+ return []
507+ })!
508+ assert 'verbose' !in ipc_events(plain.channel)![0]
509+ assert verbose_on()
510+ verbose_flag, cfg_verbose = false, false
511+ assert !verbose_on()
512+}
@@ -0,0 +1,454 @@
1+module main
2+
3+import alpm
4+import os
5+
6+// a target is a local package file if a file with that name exists,
7+// like pacman's -U handling
8+fn is_local_pkg_file(path string) bool {
9+ return os.exists(path) && os.is_file(path)
10+}
11+
12+// FileTarget is a package archive an install loads from disk: one named on
13+// the command line, or one a url fetched into the cache
14+struct FileTarget {
15+ path string
16+ fetched bool
17+}
18+
19+// load_file_target loads an archive at the signature level pacman's -U
20+// gives it: the local file level for a file named, the remote file level
21+// for one fetched. the load is the only check a file package gets —
22+// libalpm's integrity pass at commit skips one loaded from a file as valid
23+// already — so a level of 0 here would let a bad signature beside the
24+// archive install unread
25+fn load_file_target(handle &alpm.Handle, t FileTarget) !&alpm.Package {
26+ origin := if t.fetched { 'remote' } else { 'local' }
27+ got := if t.fetched {
28+ handle.option_get_remote_file_siglevel()
29+ } else {
30+ handle.option_get_local_file_siglevel()
31+ }
32+ level := got or { return error('could not read the ${origin} file signature level') }
33+ return handle.pkg_load(t.path, 1, int(level)) or {
34+ return error('failed to load ${t.path}: ${err.msg()}')
35+ }
36+}
37+
38+// find_repo_pkg looks a name up in the sync dbs, in order
39+fn find_repo_pkg(dbs []&alpm.DB, name string) ?&alpm.Package {
40+ for db in dbs {
41+ if p := db.get_pkg(name) {
42+ return p
43+ }
44+ }
45+ return none
46+}
47+
48+// add_pkg_once adds a package unless one with its name is already in the list
49+fn add_pkg_once(mut pkgs []&alpm.Package, pkg &alpm.Package) {
50+ if pkgs.any(it.get_name() == pkg.get_name()) {
51+ return
52+ }
53+ pkgs << pkg
54+}
55+
56+// expand_group adds the member packages of a sync group to the transaction:
57+// members already installed at the sync version are skipped, and of the rest
58+// the user picks, as pacman's -S asks about a group (ask is false for a
59+// --print preview, and once another target failed: nothing installs then,
60+// so there is nothing to choose). it answers whether the name was a group at
61+// all, and how many members went in. a group with nothing left to install
62+// is said, not passed over in silence: it is still a target that resolved
63+fn expand_group(mut pkgs []&alpm.Package, mut ui TransUI, handle &alpm.Handle, dbs []&alpm.DB, name string, ask bool) (bool, int) {
64+ found, members := sync_group_members(dbs, name)
65+ if !found {
66+ return false, 0
67+ }
68+ mut news := []GroupMember{}
69+ for m in members {
70+ if local := handle.find_local_pkg(m.pkg.get_name()) {
71+ if alpm.pkg_vercmp(local.get_version(), m.pkg.get_version()) >= 0 {
72+ continue
73+ }
74+ }
75+ news << m
76+ }
77+ if news.len == 0 {
78+ // --print's output is the list alone
79+ if !ui.print_only {
80+ ui.pause()
81+ report('group ${name}: every member is installed and up to date')
82+ }
83+ return true, 0
84+ }
85+ chosen := select_members(mut ui, name, news, ask)
86+ for m in chosen {
87+ add_pkg_once(mut pkgs, m.pkg)
88+ }
89+ return true, chosen.len
90+}
91+
92+// skip_up_to_date is --needed: a target installed at the version it would
93+// install is left out, with pacman's warning. libalpm's needed flag does the
94+// same inside add_pkg, warning through its log; here the targets are left
95+// out before they reach the transaction, so its listing never shows them
96+fn skip_up_to_date(handle &alpm.Handle, pkgs []&alpm.Package) []&alpm.Package {
97+ mut out := []&alpm.Package{}
98+ for pkg in pkgs {
99+ if local := handle.find_local_pkg(pkg.get_name()) {
100+ if alpm.pkg_vercmp(local.get_version(), pkg.get_version()) == 0 {
101+ warn('${pkg.get_name()}-${pkg.get_version()} is up to date, skipped')
102+ continue
103+ }
104+ }
105+ out << pkg
106+ }
107+ return out
108+}
109+
110+// walk_upgrade_deps adds the outdated dependencies of the targets and
111+// everything that hangs off them to the transaction, with libalpm's provider
112+// questions answered silently on the way: these walks look the dependencies
113+// up only to decide what to upgrade with, and the provider question that
114+// counts comes again in the prepare. the walking window is this function's
115+// whole body, so its defer is exactly as wide as the walks
116+fn walk_upgrade_deps(mut ui TransUI, handle &alpm.Handle, mut pkgs []&alpm.Package, mut added map[string]bool) ! {
117+ ui.walking = true
118+ defer { ui.walking = false }
119+ sync_dbs := handle.get_syncdbs()!
120+ mut upgrades := []&alpm.Package{}
121+ upgrades << pkgs
122+ for pkg in pkgs {
123+ for dep in handle.outdated_deps(sync_dbs, pkg) {
124+ upgrades << dep
125+ }
126+ }
127+ for p in upgrades {
128+ if p.get_name() !in added {
129+ handle.add_pkg(p)!
130+ added[p.get_name()] = true
131+ }
132+ }
133+ // with nothing installed nothing can break, and the binding's
134+ // broken_dependents takes libalpm's NULL for an empty local db as an
135+ // error: it is asked only when some package is installed
136+ if local_pkgcache(handle)! == unsafe { nil } {
137+ return
138+ }
139+ for extra in handle.broken_dependents(upgrades, sync_dbs)! {
140+ if extra.get_name() !in added {
141+ handle.add_pkg(extra)!
142+ added[extra.get_name()] = true
143+ }
144+ }
145+}
146+
147+// install_reason is the reason --asdeps or --asexplicit asks for, if any
148+fn install_reason(config ConfigInstall) ?alpm.PackageReason {
149+ if config.asdeps {
150+ return .depend
151+ }
152+ if config.asexplicit {
153+ return .explicit
154+ }
155+ return none
156+}
157+
158+// mark_installed gives the installed targets the reason --asdeps or
159+// --asexplicit asks for. libalpm's alldeps and allexplicit flags would reach
160+// every package of the transaction, the outdated dependencies vpac upgrades
161+// along with the targets too, so the reason is set on the targets alone once
162+// they are in, under the db lock as pacman's -D does it
163+fn mark_installed(handle &alpm.Handle, names []string, reason alpm.PackageReason) ! {
164+ trans_begin(handle, alpm.trans_flag_0)!
165+ defer { trans_cleanup(handle) }
166+ for name in names {
167+ pkg := handle.find_local_pkg(name) or { continue }
168+ if pkg.get_reason() != reason {
169+ pkg.set_reason(reason)!
170+ }
171+ }
172+}
173+
174+// install_pkgs prepares one transaction for all the packages. with the default
175+// it also adds the outdated dependencies of each one, then lists everything the
176+// transaction touches and asks before committing. it returns false when the user
177+// declines
178+fn install_pkgs(handle &alpm.Handle, mut ui TransUI, mut pkgs []&alpm.Package, config ConfigInstall) !bool {
179+ mut s := ui.spinner(text: 'preparing transaction')
180+ s.start()
181+ defer { stop_spinner(mut s) }
182+
183+ mut flags := dep_check_flag(config.nodeps, config.nodeps_level) | print_flags(config.print_only)
184+ if config.download_only {
185+ flags |= .download_only
186+ }
187+ if config.dbonly {
188+ flags |= .db_only
189+ }
190+ trans_begin(handle, flags)!
191+ mut added := map[string]bool{}
192+ for pkg in pkgs {
193+ handle.add_pkg(pkg)!
194+ added[pkg.get_name()] = true
195+ }
196+ if !config.no_upgrade_deps {
197+ walk_upgrade_deps(mut ui, handle, mut pkgs, mut added)!
198+ }
199+
200+ trans_prepare_checked(handle) or {
201+ return error(prepare_error(handle, err.msg(), config.no_upgrade_deps))
202+ }
203+ // every result print below needs the render thread gone
204+ end_frame(mut ui, mut s)
205+ // --print stops here: the transaction is listed with the archive names,
206+ // and nothing is downloaded or installed
207+ if config.print_only {
208+ if ipc_on() {
209+ mut preview := trans_listing(handle, handle.trans_get_add().pkgs(), .install)
210+ preview.preview = true
211+ emit(preview)
212+ return false
213+ }
214+ for pkg in handle.trans_get_add().pkgs() {
215+ file := pkg.get_filename()
216+ println(if file == '' { pkg.get_name() } else { file })
217+ }
218+ return false
219+ }
220+ // every transaction is listed and confirmed before it may go: the default
221+ // pulls in upgrades beyond the targets, --no-upgrade-deps still installs
222+ // the ones it names, and pacman's -S asks in both cases. packages the
223+ // transaction removes, such as a conflicting one, are listed too
224+ removals := handle.trans_get_remove().pkgs()
225+ if removals.len > 0 {
226+ ui.show_packages('${removals.len} packages to remove:', removals)
227+ }
228+ if !trans_confirm(mut ui, handle, handle.trans_get_add().pkgs(), .install) {
229+ return false
230+ }
231+
232+ mut commit := ui.spinner(
233+ text: if config.download_only {
234+ 'downloading packages'
235+ } else {
236+ 'installing packages'
237+ }
238+ )
239+ commit.start()
240+ defer { stop_spinner(mut commit) }
241+ trans_commit(handle)!
242+ stop_spinner(mut commit)
243+ return true
244+}
245+
246+// install installs the targets. URLs are downloaded first. local files and repo
247+// packages go into one transaction, confirmed once. names in neither the repos
248+// nor the pkgbuild repo are offered the closest repo name. pkgbuild packages are built one at a
249+// time, after that transaction. a target nothing resolves is reported and
250+// the rest are still looked up, so every bad one is named in one run; then
251+// nothing installs, as pacman's -S stops after its target errors
252+fn install(config ConfigInstall) ! {
253+ need_query(config.query, 'package')!
254+ if config.asdeps && config.asexplicit {
255+ return error('--asdeps and --asexplicit contradict each other: pick one')
256+ }
257+ // a --print preview asks nothing and takes no lock, as pacman's
258+ mut ui := new_trans_ui(noconfirm: config.noconfirm || config.print_only)
259+ if !config.print_only {
260+ check_ask_db_lock(mut ui)
261+ }
262+
263+ // the timeout option is read when the handle is made, so it is set first
264+ if config.disable_timeout {
265+ cfg_disable_timeout = true
266+ }
267+ ui.print_only = config.print_only
268+ ui.download_only = config.download_only
269+ // one handle for the whole install: a url target is fetched through it,
270+ // drawing on the same display and asking through the same prompter as
271+ // the transaction's own downloads
272+ mut handle := init_handle(ui)!
273+ defer { handle.release() or { went_on('release the alpm handle', err) } }
274+ defer { ui.stop() }
275+ defer { trans_cleanup(handle) }
276+ trans_options(config).apply(handle)!
277+
278+ mut file_targets := []FileTarget{}
279+ mut names := []string{}
280+ for target in config.query {
281+ if is_url(target) {
282+ if config.print_only {
283+ // a url target is printed as it is; nothing is fetched. the
284+ // same message event a build plan goes out as carries this
285+ // line on both a terminal and a frontend
286+ report('would fetch ${target}')
287+ continue
288+ }
289+ file_targets << FileTarget{
290+ path: fetch_target_url(mut ui, handle, target)!
291+ fetched: true
292+ }
293+ } else if is_local_pkg_file(target) {
294+ file_targets << FileTarget{
295+ path: target
296+ }
297+ } else {
298+ names << target
299+ }
300+ }
301+
302+ mut s := ui.spinner(text: 'getting dbs and updating em')
303+ s.start()
304+ defer { stop_spinner(mut s) }
305+
306+ dbs := init_repos(mut handle)!
307+ if names.len > 0 {
308+ check_sync_fresh(mut ui, mut handle)!
309+ }
310+
311+ mut pkgs := []&alpm.Package{}
312+ for f in file_targets {
313+ add_pkg_once(mut pkgs, load_file_target(handle, f)!)
314+ }
315+ mut pkgbuild := []string{}
316+ mut missed := 0
317+ mut groups := map[string]bool{}
318+ for name in names {
319+ if config.pkgbuild {
320+ pkgbuild << name
321+ continue
322+ }
323+ // repo/name looks in that repo alone, for the package and the group
324+ target := parse_target(name)
325+ scoped := scope_dbs(dbs, target.repo) or {
326+ target_error(err.msg())
327+ missed++
328+ continue
329+ }
330+ if p := find_sync_target(handle, scoped, target.name, target.repo != '') {
331+ add_pkg_once(mut pkgs, p)
332+ continue
333+ }
334+ // a group named twice is asked about once
335+ if groups[name] {
336+ continue
337+ }
338+ // a group installs the members picked of the ones that are not
339+ // installed at the sync version already
340+ found, _ := expand_group(mut pkgs, mut ui, handle, scoped, target.name, !config.print_only
341+ && missed == 0)
342+ if found {
343+ groups[name] = true
344+ continue
345+ }
346+ // a repo named is the whole search: the pkgbuild repos are no
347+ // fallback for it
348+ if target.repo != '' {
349+ target_error('target not found in ${target.repo}: ${target.name}')
350+ missed++
351+ continue
352+ }
353+ pkgbuild << name
354+ }
355+ stop_spinner(mut s)
356+ if config.needed {
357+ pkgs = skip_up_to_date(handle, pkgs)
358+ }
359+
360+ mut pkgbuild_builds := []string{}
361+ if config.pkgbuild && pkgbuild_repos().len == 0 {
362+ return error('no pkgbuild repo in the config: add (repo :name "aur" :type "pkgbuild" :src "https://aur.archlinux.org")')
363+ }
364+ for name in pkgbuild {
365+ if config.pkgbuild {
366+ pkgbuild_builds << name
367+ continue
368+ }
369+ // nothing in the repos: the pkgbuild repos are next, and they review
370+ // before they build
371+ in_the_repos := pkgbuild_has(name) or { return err }
372+ if in_the_repos {
373+ pkgbuild_builds << name
374+ continue
375+ }
376+ // the pkgbuild db is not the only source: a typo of a package that is
377+ // only installed gets its proposal too
378+ fixed := did_you_mean(mut ui, name, all_names(handle, dbs)) or {
379+ target_error('"${name}" is not in the repos or the pkgbuild repo')
380+ missed++
381+ continue
382+ }
383+ // the accepted suggestion goes the same way the typo would have: a
384+ // pkgbuild package from its repo, a repo package into the
385+ // transaction, and a name nothing carries is the miss it is
386+ fixed_found := pkgbuild_has(fixed) or { return err }
387+ if fixed_found {
388+ pkgbuild_builds << fixed
389+ continue
390+ }
391+ if p := find_repo_pkg(dbs, fixed) {
392+ add_pkg_once(mut pkgs, p)
393+ } else {
394+ target_error('"${fixed}" is not in the repos or the pkgbuild repo')
395+ missed++
396+ }
397+ }
398+ // the bad targets are all named by now; pacman installs nothing then
399+ if missed > 0 {
400+ return
401+ }
402+
403+ if config.download_only && pkgbuild_builds.len > 0 {
404+ return error('download-only does not build pkgbuild packages')
405+ }
406+
407+ if pkgs.len == 0 && pkgbuild_builds.len == 0 {
408+ // --print's output is the list alone
409+ if !config.print_only {
410+ report('there is nothing to do')
411+ }
412+ return
413+ }
414+
415+ if pkgs.len > 0 {
416+ // the names are read before the commit, which may free the packages
417+ targets := pkgs.map(it.get_name())
418+ done := targets.map(name_style(it))
419+ committed := install_pkgs(handle, mut ui, mut pkgs, config)!
420+ // not the defer's work done twice: the pkgbuild installs below begin
421+ // transactions of their own on this handle, so this one is closed
422+ // here, and the defer has nothing left to close when it runs
423+ trans_cleanup(handle)
424+ if !committed {
425+ // --print listed the repo part; the build plan is still listed
426+ if config.print_only {
427+ for name in pkgbuild_builds {
428+ report('would build ${name}')
429+ }
430+ }
431+ return
432+ }
433+ if !config.download_only {
434+ if reason := install_reason(config) {
435+ mark_installed(handle, targets, reason)!
436+ }
437+ }
438+ print_done(mut ui, if config.download_only {
439+ 'downloaded:'
440+ } else {
441+ 'installed:'
442+ }, done)
443+ }
444+ // --print lists the build plan and stops
445+ if config.print_only {
446+ for name in pkgbuild_builds {
447+ report('would build ${name}')
448+ }
449+ return
450+ }
451+ for target in pkgbuild_builds {
452+ pkgbuild_install(mut ui, mut handle, config, target)!
453+ }
454+}
@@ -0,0 +1,173 @@
1+module main
2+
3+import alpm
4+import os
5+
6+fn test_install_reason() {
7+ assert install_reason(ConfigInstall{}) == none
8+ assert install_reason(ConfigInstall{ asdeps: true }) or { panic('none') } == .depend
9+ assert install_reason(ConfigInstall{ asexplicit: true }) or { panic('none') } == .explicit
10+}
11+
12+// reason_db writes a libalpm local db with two packages, one of each reason
13+fn reason_db(dbpath string) ! {
14+ local := os.join_path(dbpath, 'local')
15+ os.mkdir_all(local)!
16+ os.write_file(os.join_path(local, 'ALPM_DB_VERSION'), '9\n')!
17+ for name, reason in {
18+ 'dep': 1
19+ 'top': 0
20+ } {
21+ dir := os.join_path(local, '${name}-1.0-1')
22+ os.mkdir_all(dir)!
23+ os.write_file(os.join_path(dir, 'desc'), '%NAME%\n${name}\n\n%VERSION%\n1.0-1\n\n%REASON%\n${reason}\n\n')!
24+ os.write_file(os.join_path(dir, 'files'), '%FILES%\n\n')!
25+ }
26+}
27+
28+fn local_reason(root string, dbpath string, name string) !alpm.PackageReason {
29+ handle := alpm.initialize(root, dbpath)!
30+ defer { handle.release() or {} }
31+ pkg := handle.find_local_pkg(name) or { return error('${name} is not installed') }
32+ return pkg.get_reason()
33+}
34+
35+fn test_mark_installed() ! {
36+ tmp := os.join_path(os.vtmp_dir(), 'vpac_test_remote_${os.getpid()}')
37+ root := os.join_path(tmp, 'root') + '/'
38+ dbpath := os.join_path(tmp, 'db') + '/'
39+ os.mkdir_all(root)!
40+ reason_db(dbpath)!
41+ defer { os.rmdir_all(tmp) or {} }
42+
43+ handle := alpm.initialize(root, dbpath)!
44+ // --asexplicit on the dependency, --asdeps on the top package; a name
45+ // that is not installed (a target that failed) is passed over
46+ mark_installed(handle, ['dep', 'missing'], .explicit)!
47+ mark_installed(handle, ['top'], .depend)!
48+ handle.release()!
49+ // the lock is gone again, and a fresh handle reads the new reasons back
50+ // from disk
51+ assert !os.exists(os.join_path(tmp, 'db', 'db.lck'))
52+ assert local_reason(root, dbpath, 'dep')! == .explicit
53+ assert local_reason(root, dbpath, 'top')! == .depend
54+}
55+
56+// SigFixture is a package archive with no signature beside it yet, and the
57+// root, db and keyring dirs a handle needs, all under one temp dir
58+struct SigFixture {
59+ tmp string
60+ pkg string
61+}
62+
63+// sig_fixture writes foo-1.0-1-any.pkg.tar, a one-entry archive libalpm
64+// loads as a package: its .PKGINFO
65+fn sig_fixture(name string) !SigFixture {
66+ tmp := os.join_path(os.vtmp_dir(), 'vpac_test_sig_${name}_${os.getpid()}')
67+ os.rmdir_all(tmp) or {}
68+ for d in ['root', 'db/local', 'gpg', 'cache', 'src'] {
69+ os.mkdir_all(os.join_path(tmp, d))!
70+ }
71+ os.write_file(os.join_path(tmp, 'db/local/ALPM_DB_VERSION'), '9\n')!
72+ os.write_file(os.join_path(tmp, 'src/.PKGINFO'), 'pkgname = foo\npkgbase = foo\npkgver = 1.0-1\narch = any\nsize = 0\n')!
73+ pkg := os.join_path(tmp, 'foo-1.0-1-any.pkg.tar')
74+ res := os.exec(['tar', '-cf', pkg, '-C', os.join_path(tmp, 'src'), '.PKGINFO'])
75+ if res.exit_code != 0 {
76+ return error('tar failed: ${res.output}')
77+ }
78+ return SigFixture{
79+ tmp: tmp
80+ pkg: pkg
81+ }
82+}
83+
84+// handle opens the fixture's root with its own keyring dir, so the gpg a
85+// signature check starts reads and writes nothing outside the fixture
86+fn (fx SigFixture) handle(local alpm.SigLevel, remote alpm.SigLevel) !&alpm.Handle {
87+ handle := alpm.initialize(os.join_path(fx.tmp, 'root') + '/', os.join_path(fx.tmp, 'db') + '/')!
88+ handle.option_set_gpgdir(os.join_path(fx.tmp, 'gpg') + '/')!
89+ handle.option_set_local_file_siglevel(local)!
90+ handle.option_set_remote_file_siglevel(remote)!
91+ return handle
92+}
93+
94+// loads tells whether the fixture's archive loads as t's origin
95+fn loads(handle &alpm.Handle, path string, fetched bool) bool {
96+ pkg := load_file_target(handle, FileTarget{
97+ path: path
98+ fetched: fetched
99+ }) or { return false }
100+ pkg.free_pkg() or {}
101+ return true
102+}
103+
104+const sig_optional = alpm.SigLevel.package | .package_optional
105+const sig_required = alpm.SigLevel.package
106+
107+fn test_load_file_target_verifies_a_signature_beside_the_archive() ! {
108+ fx := sig_fixture('present')!
109+ defer { os.rmdir_all(fx.tmp) or {} }
110+ handle := fx.handle(sig_optional, sig_optional)!
111+ defer { handle.release() or {} }
112+ // optional: an unsigned archive is taken as it is
113+ assert loads(handle, fx.pkg, false)
114+ assert loads(handle, fx.pkg, true)
115+ // a signature beside it is read and must hold. libalpm checks a file
116+ // package at its load only, so a load at level 0 installed this one
117+ os.write_file(fx.pkg + '.sig', 'not a signature')!
118+ for fetched in [false, true] {
119+ load_file_target(handle, FileTarget{ path: fx.pkg, fetched: fetched }) or {
120+ assert err.msg().starts_with('failed to load ${fx.pkg}: ')
121+ assert err.msg().contains('signature'), err.msg()
122+ continue
123+ }
124+ assert false, 'a corrupt signature loaded (fetched: ${fetched})'
125+ }
126+}
127+
128+fn test_load_file_target_takes_the_level_of_its_origin() ! {
129+ fx := sig_fixture('origin')!
130+ defer { os.rmdir_all(fx.tmp) or {} }
131+ // a file named takes the local level, a fetched one the remote level, as
132+ // pacman's -U loads them: the unsigned archive fails where its origin's
133+ // level requires a signature, and only there
134+ local_strict := fx.handle(sig_required, sig_optional)!
135+ assert !loads(local_strict, fx.pkg, false)
136+ assert loads(local_strict, fx.pkg, true)
137+ local_strict.release()!
138+ remote_strict := fx.handle(sig_optional, sig_required)!
139+ assert loads(remote_strict, fx.pkg, false)
140+ assert !loads(remote_strict, fx.pkg, true)
141+ remote_strict.release()!
142+}
143+
144+fn test_init_handle_checks_file_targets_at_the_configured_level() ! {
145+ // the whole way vpac opens a handle for an install: the configured level
146+ // (the default here, pacman's) reaches both kinds of file target
147+ fx := sig_fixture('config')!
148+ defer { os.rmdir_all(fx.tmp) or {} }
149+ saved_root, saved_db, saved_gpg := root_path, db_path, cfg_gpgdir
150+ saved_cache, saved_user, saved_level := cfg_cachedirs.clone(), download_user, cfg_siglevel
151+ saved_hooks := cfg_hookdirs.clone()
152+ cfg_hookdirs = []string{}
153+ defer {
154+ root_path, db_path, cfg_gpgdir = saved_root, saved_db, saved_gpg
155+ cfg_cachedirs = saved_cache.clone()
156+ cfg_hookdirs = saved_hooks.clone()
157+ download_user, cfg_siglevel = saved_user, saved_level
158+ }
159+ root_path = os.join_path(fx.tmp, 'root') + '/'
160+ db_path = os.join_path(fx.tmp, 'db') + '/'
161+ cfg_gpgdir = os.join_path(fx.tmp, 'gpg') + '/'
162+ cfg_cachedirs = [os.join_path(fx.tmp, 'cache') + '/']
163+ // the sandbox user need not exist where the tests run
164+ download_user = ''
165+ ui := new_trans_ui()
166+ handle := init_handle(ui)!
167+ defer { handle.release() or {} }
168+ assert loads(handle, fx.pkg, false)
169+ assert loads(handle, fx.pkg, true)
170+ os.write_file(fx.pkg + '.sig', 'not a signature')!
171+ assert !loads(handle, fx.pkg, false)
172+ assert !loads(handle, fx.pkg, true)
173+}
@@ -0,0 +1,172 @@
1+module main
2+
3+import alpm
4+
5+// local_group_pkgs are the installed members of a group, pacman -R's
6+// fallback for a target that is no package: the local db's own group
7+fn local_group_pkgs(handle &alpm.Handle, name string) []&alpm.Package {
8+ localdb := handle.get_localdb() or { return []&alpm.Package{} }
9+ group := localdb.get_group(name) or { return []&alpm.Package{} }
10+ return group.packages.pkgs()
11+}
12+
13+// recurse_flags is pacman's -s: once takes the dependencies the removal
14+// leaves unneeded, twice (-ss, or --recursive with -s) the ones that were
15+// installed explicitly too
16+fn recurse_flags(recursive bool, level int) alpm.TransFlag {
17+ n := level + if recursive { 1 } else { 0 }
18+ return if n >= 2 {
19+ alpm.TransFlag.recurse | .recurse_all
20+ } else if n == 1 {
21+ alpm.TransFlag.recurse
22+ } else {
23+ alpm.trans_flag_0
24+ }
25+}
26+
27+// remove removes the targets in one transaction, confirmed once
28+fn remove(config ConfigRemove) ! {
29+ need_query(config.query, 'package')!
30+ // a --print preview asks nothing and takes no lock, as pacman's
31+ mut ui := new_trans_ui(noconfirm: config.noconfirm || config.print_only)
32+ ui.print_only = config.print_only
33+ if !config.print_only {
34+ check_ask_db_lock(mut ui)
35+ }
36+
37+ mut handle := init_handle(ui)!
38+ defer { handle.release() or { went_on('release the alpm handle', err) } }
39+ defer { ui.stop() }
40+ defer { trans_cleanup(handle) }
41+ TransOptions{
42+ assume_installed: config.assume_installed
43+ }.apply(handle)!
44+
45+ mut s := ui.spinner(text: 'preparing removal')
46+ s.start()
47+ defer { stop_spinner(mut s) }
48+
49+ mut pkgcache := local_pkgcache(handle)!
50+
51+ // every target is found before the transaction starts, so an unknown
52+ // name removes nothing: each bad one is reported and the rest still
53+ // looked up, and then the run stops, as pacman's -R does. a target is a
54+ // package, what satisfies its version constraint, or a group of the
55+ // local db
56+ mut pkgs := []&alpm.Package{}
57+ mut missed := 0
58+ for target in config.query {
59+ name := local_target_name(target)
60+ if pkg := find_local_target(pkgcache, name, false) {
61+ add_pkg_once(mut pkgs, pkg)
62+ continue
63+ }
64+ members := local_group_pkgs(handle, name)
65+ if members.len > 0 {
66+ for pkg in members {
67+ add_pkg_once(mut pkgs, pkg)
68+ }
69+ continue
70+ }
71+ stop_spinner(mut s)
72+ fixed := did_you_mean(mut ui, name, pkg_names(pkgcache.pkgs())) or {
73+ target_error(err.msg())
74+ missed++
75+ continue
76+ }
77+ pkg := pkgcache.pkg_find(fixed) or {
78+ target_error('unknown package: "${fixed}"')
79+ missed++
80+ continue
81+ }
82+ add_pkg_once(mut pkgs, pkg)
83+ }
84+ stop_spinner(mut s)
85+ if missed > 0 {
86+ return
87+ }
88+
89+ // the config can hold a package: refuse before anything is staged
90+ check_hold(pkgs.map(it.get_name()))!
91+
92+ // recursive takes the dependencies that the removal leaves unneeded too, as
93+ // pacman's -Rs does. they are listed with the packages and confirmed once
94+ mut flags := dep_check_flag(config.nodeps, config.nodeps_level) | print_flags(config.print_only) | recurse_flags(config.recursive,
95+ config.recursive_level)
96+ // pacman's -Ru: a target something still requires is left out by
97+ // libalpm instead of failing the removal
98+ if config.unneeded {
99+ flags |= .unneeded
100+ }
101+ if config.cascade {
102+ flags |= .cascade
103+ }
104+ if config.nosave {
105+ flags |= .no_save
106+ }
107+ if config.dbonly {
108+ flags |= .db_only
109+ }
110+ trans_begin(handle, flags)!
111+ for pkg in pkgs {
112+ handle.remove_pkg(pkg)!
113+ }
114+
115+ trans_prepare_checked(handle)!
116+
117+ victims := handle.trans_get_remove().pkgs()
118+ if victims.len == 0 {
119+ // -u left every target where it is needed: pacman's answer, and no
120+ // failure
121+ if config.unneeded {
122+ end_frame(mut ui, mut s)
123+ if !config.print_only {
124+ report('there is nothing to do')
125+ }
126+ return
127+ }
128+ return error('nothing to do')
129+ }
130+
131+ // --print stops here: what the removal takes is listed the way pacman's
132+ // -Rp lists it, name-version, and nothing is removed
133+ if config.print_only {
134+ end_frame(mut ui, mut s)
135+ if ipc_on() {
136+ mut preview := trans_listing(handle, victims, .remove)
137+ preview.preview = true
138+ emit(preview)
139+ return
140+ }
141+ for pkg in victims {
142+ println('${pkg.get_name()}-${pkg.get_version()}')
143+ }
144+ return
145+ }
146+
147+ // the transaction is the truth of what goes: recursive and cascade pull
148+ // packages in beyond the targets, and the hold list counts for them too
149+ check_hold(victims.map(it.get_name()))!
150+
151+ if !trans_confirm(mut ui, handle, victims, .remove) {
152+ return
153+ }
154+
155+ // the names are read before the commit, which frees the removed packages
156+ // with -u a target may have stayed: the ones that go are the ones named
157+ going := victims.map(it.get_name())
158+ mut done := []string{}
159+ for pkg in pkgs {
160+ if pkg.get_name() in going {
161+ done << name_style(pkg.get_name())
162+ }
163+ }
164+
165+ mut s2 := ui.spinner(text: 'removing packages')
166+ s2.start()
167+ defer { stop_spinner(mut s2) }
168+ trans_commit(handle)!
169+ stop_spinner(mut s2)
170+
171+ print_done(mut ui, 'removed:', done)
172+}
@@ -0,0 +1,363 @@
1+module main
2+
3+import alpm
4+import strings
5+
6+// terms_match is the classic match: every term is in the name or in the
7+// description, case ignored. no terms match everything, as pacman's -Ss
8+// with no target lists everything
9+fn terms_match(name string, desc string, terms []string) bool {
10+ n, d := name.to_lower(), desc.to_lower()
11+ for term in terms {
12+ t := term.to_lower()
13+ if !n.contains(t) && !d.contains(t) {
14+ return false
15+ }
16+ }
17+ return true
18+}
19+
20+// match_classic is the classic match of a libalpm package
21+fn match_classic(pkg &alpm.Package, config ConfigSearch) bool {
22+ return terms_match(pkg.get_name(), pkg.get_desc(), config.query)
23+}
24+
25+fn jw_if_match(config ConfigSearch, needle string, haystack string) ?f64 {
26+ score := strings.jaro_winkler_similarity(needle, haystack)
27+ if score >= config.thold {
28+ return score
29+ }
30+ return none
31+}
32+
33+// match_fuzzy_name needs every term to match the name, and scores the name by
34+// the average of the terms
35+fn match_fuzzy_name(pkg &alpm.Package, config ConfigSearch) ?f64 {
36+ if config.query.len == 0 {
37+ return none
38+ }
39+ name := pkg.get_name().to_lower()
40+ mut total := 0.0
41+ for term in config.query {
42+ score := jw_if_match(config, term.to_lower(), name) or { return none }
43+ total += score
44+ }
45+ return total / f64(config.query.len)
46+}
47+
48+// fuzzy_desc_hit is true when one word of the description matches the term
49+fn fuzzy_desc_hit(config ConfigSearch, term string, words []string) bool {
50+ for h in words {
51+ if _ := jw_if_match(config, term, h) {
52+ return true
53+ }
54+ }
55+ return false
56+}
57+
58+fn match_fuzzy_desc(pkg &alpm.Package, config ConfigSearch) bool {
59+ if config.query.len == 0 {
60+ return false
61+ }
62+ words := pkg.get_desc().to_lower().split(' ').filter(|word| word.runes().len > 1)
63+ for term in config.query {
64+ if !fuzzy_desc_hit(config, term.to_lower(), words) {
65+ return false
66+ }
67+ }
68+ return true
69+}
70+
71+struct Scored {
72+ pkg &alpm.Package
73+ score f64
74+}
75+
76+fn build_matches(pkgs []&alpm.Package, config ConfigSearch) []&alpm.Package {
77+ return if config.fuzzy {
78+ mut m_name := []Scored{cap: pkgs.len}
79+ for pkg in pkgs {
80+ if s := match_fuzzy_name(pkg, config) {
81+ m_name << Scored{pkg, s}
82+ }
83+ }
84+ // strong name matches lead; desc-only matches trail them. a package
85+ // listed for its name is not listed again for its description: the
86+ // names matched are a set, one lookup per package instead of a scan
87+ // of the matches (one call reads one db, where names are unique)
88+ m_name.sort(a.score > b.score)
89+ m_name_pkg := m_name.map(|pkg| pkg.pkg)
90+ mut by_name := map[string]bool{}
91+ for pkg in m_name_pkg {
92+ by_name[pkg.get_name()] = true
93+ }
94+ m_desc_pkg := pkgs.filter(|pkg| !by_name[pkg.get_name()] && match_fuzzy_desc(pkg, config))
95+ // one new list, the name matches then the description ones: neither
96+ // of the two it is made of is written to
97+ mut matches := []&alpm.Package{cap: m_name_pkg.len + m_desc_pkg.len}
98+ matches << m_name_pkg
99+ matches << m_desc_pkg
100+ matches
101+ } else {
102+ pkgs.filter(|pkg| match_classic(pkg, config))
103+ }
104+}
105+
106+// pkgbuild_matches is the classic match for AUR results, which only have a name and
107+// a description
108+fn pkgbuild_matches(pkg PackagePkgbuild, terms []string) bool {
109+ return terms_match(pkg.name, pkg.description, terms)
110+}
111+
112+// filtered is true when a filter flag asks for installed packages with a property
113+fn (config ConfigSearch) filtered() bool {
114+ return config.deps || config.explicit || config.foreign || config.native
115+ || config.unrequired || config.upgrades
116+}
117+
118+// GroupRef is one group of a db, as the bare group listing collects it: a
119+// sync db's, or the local db's (repo 'local') with -l
120+struct GroupRef {
121+ repo string
122+ name string
123+}
124+
125+// group_source is how a listing names a db: the local one is 'local', as
126+// the installed packages are everywhere else
127+fn group_source(handle &alpm.Handle, db &alpm.DB) string {
128+ if localdb := handle.get_localdb() {
129+ if voidptr(localdb) == voidptr(db) {
130+ return 'local'
131+ }
132+ }
133+ return db.get_name()
134+}
135+
136+// sync_groups lists every group of the dbs, db by db
137+fn sync_groups(handle &alpm.Handle, dbs []&alpm.DB) []GroupRef {
138+ mut out := []GroupRef{}
139+ for db in dbs {
140+ mut node := db.get_groupcache() or { continue }
141+ for node != unsafe { nil } {
142+ if group := node.get_group() {
143+ out << GroupRef{group_source(handle, db), group.get_name()}
144+ }
145+ node = node.next
146+ }
147+ }
148+ return out
149+}
150+
151+// scope_repo narrows a search to one repo when its first name is one, like
152+// 'vpac s -r extra zsh': the dbs left, and the query without the repo
153+fn scope_repo(dbs []&alpm.DB, query []string) ([]&alpm.DB, []string) {
154+ if query.len > 1 && dbs.any(it.get_name() == query[0]) {
155+ return dbs.filter(it.get_name() == query[0]), query[1..]
156+ }
157+ return dbs, query
158+}
159+
160+// collect_group_members lists the members of the named groups of dbs: the
161+// sync dbs, or the local db for pacman's -Qg. the filters look at the
162+// installed packages: a member that is not installed cannot pass them, and
163+// sync_dbs is what the sync-comparing ones compare with
164+fn collect_group_members(mut listing Listing, handle &alpm.Handle, dbs []&alpm.DB, sync_dbs []&alpm.DB, config ConfigSearch) ! {
165+ for name in config.query {
166+ mut found := false
167+ // a group several dbs carry lists each member once, from the first
168+ // db that has it, as alpm_find_group_pkgs does
169+ mut seen := map[string]bool{}
170+ for db in dbs {
171+ group := db.get_group(name) or { continue }
172+ found = true
173+ for pkg in group.packages.pkgs() {
174+ if seen[pkg.get_name()] {
175+ continue
176+ }
177+ seen[pkg.get_name()] = true
178+ local := handle.find_local_pkg(pkg.get_name())
179+ if config.installed && local == none {
180+ continue
181+ }
182+ if config.filtered() {
183+ l := local or { continue }
184+ if !pkg_matches_filter(l, config, sync_dbs) {
185+ continue
186+ }
187+ }
188+ listing.add_member(pkg, group_source(handle, db), name)
189+ }
190+ }
191+ // as pacman's -Sg: one missing group fails the run, the rest list
192+ if !found {
193+ target_error('group "${name}" not found')
194+ }
195+ }
196+}
197+
198+// collect_search lists the matches of the query: the installed packages, the
199+// sync dbs and the pkgbuild repos, each when the config asks for it
200+fn collect_search(mut listing Listing, mut ui TransUI, mut handle &alpm.Handle, config ConfigSearch) ! {
201+ if config.local {
202+ mut pkgcache := local_pkgcache(handle)!
203+
204+ sync_dbs := filter_sync_dbs(mut ui, mut handle, config)!
205+ installed := pkgcache.pkgs().filter(|pkg| pkg_matches_filter(pkg, config, sync_dbs))
206+ for pkg in build_matches(installed, config) {
207+ listing.add_pkg(pkg, 'local')
208+ }
209+ }
210+
211+ if config.remote {
212+ mut scope := config
213+ dbs, query := scope_repo(init_repos(mut handle)!, config.query)
214+ scope.query = query
215+ if scope.sync_dbs {
216+ check_ask_db_lock(mut ui)
217+ update_repos(mut handle, false)!
218+ } else {
219+ check_sync_fresh(mut ui, mut handle)!
220+ }
221+
222+ for db in dbs {
223+ mut pkgcache := pkgcache_of(handle, db)!
224+ for pkg in build_matches(pkgcache.pkgs(), scope) {
225+ if scope.installed && handle.find_local_pkg(pkg.get_name()) == none {
226+ continue
227+ }
228+ listing.add_pkg(pkg, db.get_name())
229+ }
230+ }
231+ }
232+
233+ if config.pkgbuild {
234+ mut brepos := pkgbuild_repos()
235+ if brepos.len == 0 {
236+ return error('no pkgbuild repo in the config: add (repo :name "aur" :type "pkgbuild" :src "https://aur.archlinux.org")')
237+ }
238+ // a first name that is a pkgbuild repo narrows the search to it
239+ mut bquery := config.query.clone()
240+ if bquery.len > 1 {
241+ known := brepos.map(it.name)
242+ if bquery[0] in known {
243+ brepos = brepos.filter(it.name == bquery[0])
244+ bquery = bquery[1..]
245+ }
246+ }
247+ // each pkgbuild repo is searched on its own site, and its results
248+ // carry the repo's name
249+ needle := if bquery.len > 0 { bquery[0] } else { '' }
250+ rest := if bquery.len > 1 { bquery[1..] } else { []string{} }
251+ for repo in brepos {
252+ pkgs := get_pkgbuild_packages(repo.servers[0].trim_right('/'), needle) or { return err }
253+ for pkg in pkgs {
254+ if pkgbuild_matches(pkg, rest) {
255+ if config.installed && handle.find_local_pkg(pkg.name) == none {
256+ continue
257+ }
258+ listing.add_pkgbuild(pkg, repo.name)
259+ }
260+ }
261+ }
262+ }
263+}
264+
265+// search collects the matches, then prints them. a search that fails part
266+// way prints no partial table, but its quiet listing still names what was
267+// found before the error, the way a stream of names does
268+fn search(config ConfigSearch) ! {
269+ if config.filtered() && !config.groups && (config.remote || config.pkgbuild) {
270+ return error('the filters only apply to installed packages: use them with -l, not -r or -a')
271+ }
272+ // the groups are the installed packages' or the sync dbs', pacman's -Qg
273+ // or -Sg: asked for both, one of the two would be dropped without a word
274+ if config.groups && config.local && config.remote {
275+ return error('search -g lists the groups of the installed packages (-l) or of the sync dbs (-r), not both at once')
276+ }
277+ mut ui := new_trans_ui(noconfirm: config.noconfirm)
278+ mut handle := init_handle(ui)!
279+ defer { handle.release() or { went_on('release the alpm handle', err) } }
280+ defer { ui.stop() }
281+
282+ fields := parse_fields(config.fields, cfg_search_fields)!
283+ mut listing := Listing{
284+ mode: if config.quiet { PrintMode.minimal } else { PrintMode.default }
285+ fields: fields
286+ }
287+
288+ if config.groups {
289+ mut scope := config
290+ mut dbs := []&alpm.DB{}
291+ mut sync_dbs := []&alpm.DB{}
292+ if config.local {
293+ // pacman's -Qg: the groups of the installed packages, read from
294+ // the local db. the sync dbs come in only for a filter that
295+ // compares with them
296+ dbs << handle.get_localdb() or {
297+ return error('could not open the local database: ${err.msg()}')
298+ }
299+ sync_dbs = filter_sync_dbs(mut ui, mut handle, scope)!
300+ } else {
301+ // the same repo scoping narrows the group listing
302+ scoped, query := scope_repo(init_repos(mut handle)!, config.query)
303+ dbs = scoped.clone()
304+ scope.query = query.clone()
305+ // the sync-comparing filters (--native, --foreign, --upgrades) reach
306+ // into these dbs through pkg_matches_filter, so they run the same
307+ // freshness check the installed-package listing does. the dbs are
308+ // registered above already, and libalpm refuses a second
309+ // registration, so the check is all that is left of
310+ // filter_sync_dbs here
311+ if scope.foreign || scope.native || scope.upgrades {
312+ check_sync_fresh(mut ui, mut handle)!
313+ }
314+ sync_dbs = dbs.clone()
315+ }
316+ if scope.query.len == 0 && config.groups_level >= 2 {
317+ // -gg: every group with its members, pacman's 'group package'
318+ // lines; each group is listed once, whichever dbs carry it
319+ mut names := []string{}
320+ for g in sync_groups(handle, dbs) {
321+ if g.name !in names {
322+ names << g.name
323+ }
324+ }
325+ scope.query = names
326+ collect_group_members(mut listing, handle, dbs, sync_dbs, scope)!
327+ if ipc_on() || config.quiet {
328+ listing.print()
329+ } else {
330+ for e in listing.entries {
331+ println('${e.group} ${name_style(e.name)}')
332+ }
333+ }
334+ return
335+ }
336+ if scope.query.len == 0 {
337+ // no names: every group of every db, one line each
338+ groups := sync_groups(handle, dbs)
339+ if ipc_on() {
340+ emit(GroupsEvent{
341+ groups: groups
342+ })
343+ return
344+ }
345+ for g in groups {
346+ println(table_text([row(g.repo, g.name)], ' ', ' '))
347+ }
348+ return
349+ }
350+ collect_group_members(mut listing, handle, dbs, sync_dbs, scope) or {
351+ listing.print_found()
352+ return err
353+ }
354+ listing.print()
355+ return
356+ }
357+
358+ collect_search(mut listing, mut ui, mut handle, config) or {
359+ listing.print_found()
360+ return err
361+ }
362+ listing.print()
363+}
@@ -0,0 +1,38 @@
1+module main
2+
3+fn test_terms_match_edges() {
4+ // every term must be somewhere, in the name or in the description
5+ assert terms_match('zsh', 'a shell', ['zsh'])
6+ assert terms_match('zsh', 'a shell', ['shell'])
7+ assert terms_match('zsh', 'a shell', ['zsh', 'shell'])
8+ assert !terms_match('zsh', 'a shell', ['zsh', 'editor'])
9+ assert !terms_match('zsh', 'a shell', ['bash'])
10+ // case is ignored on both sides
11+ assert terms_match('Zsh', 'A Shell', ['zSH', 'sHELL'])
12+ // a term is a substring, not a word, and may span nothing but itself
13+ assert terms_match('zsh-completions', '', ['sh-comp'])
14+ assert !terms_match('zsh', 'a shell', ['zsh shell'])
15+ // no terms match everything, as a bare pacman -Ss lists everything; an
16+ // empty term is in every text
17+ assert terms_match('zsh', 'a shell', [])
18+ assert terms_match('', '', [])
19+ assert terms_match('zsh', '', [''])
20+ // nothing to look in matches no real term
21+ assert !terms_match('', '', ['x'])
22+ // multibyte text is matched as text
23+ assert terms_match('grüße', 'ein Paket', ['üß'])
24+}
25+
26+fn test_pkgbuild_matches_as_the_classic_match() {
27+ pkg := PackagePkgbuild{
28+ name: 'yay-bin'
29+ description: 'Yet another yogurt'
30+ }
31+ assert pkgbuild_matches(pkg, ['yay'])
32+ assert pkgbuild_matches(pkg, ['YOGURT', 'bin'])
33+ assert !pkgbuild_matches(pkg, ['yay', 'paru'])
34+ assert pkgbuild_matches(pkg, [])
35+ // a record with no description still matches by its name
36+ assert pkgbuild_matches(PackagePkgbuild{ name: 'paru' }, ['par'])
37+ assert !pkgbuild_matches(PackagePkgbuild{ name: 'paru' }, ['helper'])
38+}
@@ -0,0 +1,140 @@
1+@[has_globals]
2+module main
3+
4+import term
5+
6+// color_flag is --color: 'auto' styles a terminal only, 'always' and
7+// 'never' decide for every stream, as pacman's --color does
8+__global color_flag = 'auto'
9+// color_given is whether the command line spelled a --color: the config's
10+// (options :color) is the default only when it did not
11+__global color_given = false
12+
13+// color_on is whether a stream gets styled: stdout, or stderr with err
14+fn color_on(err bool) bool {
15+ return match color_flag {
16+ 'always' { true }
17+ 'never' { false }
18+ else {
19+ if err { term.can_show_color_on_stderr() } else { term.can_show_color_on_stdout() }
20+ }
21+ }
22+}
23+
24+// style_names are the styles a theme may name, (color :role [...]): the
25+// terminal's attributes and its sixteen colors
26+const style_names = ['none', 'bold', 'dim', 'italic', 'underline', 'reverse', 'black', 'red', 'green',
27+ 'yellow', 'blue', 'magenta', 'cyan', 'white', 'gray', 'bright_black', 'bright_red', 'bright_green',
28+ 'bright_yellow', 'bright_blue', 'bright_magenta', 'bright_cyan', 'bright_white']
29+
30+// apply_style wraps text in one named style; a name outside style_names is
31+// refused by the config before it gets here
32+fn apply_style(name string, s string) string {
33+ return match name {
34+ 'bold' { term.bold(s) }
35+ 'dim' { term.dim(s) }
36+ 'italic' { term.italic(s) }
37+ 'underline' { term.underline(s) }
38+ 'reverse' { term.inverse(s) }
39+ 'black' { term.black(s) }
40+ 'red' { term.red(s) }
41+ 'green' { term.green(s) }
42+ 'yellow' { term.yellow(s) }
43+ 'blue' { term.blue(s) }
44+ 'magenta' { term.magenta(s) }
45+ 'cyan' { term.cyan(s) }
46+ 'white' { term.white(s) }
47+ 'gray' { term.gray(s) }
48+ 'bright_black' { term.bright_black(s) }
49+ 'bright_red' { term.bright_red(s) }
50+ 'bright_green' { term.bright_green(s) }
51+ 'bright_yellow' { term.bright_yellow(s) }
52+ 'bright_blue' { term.bright_blue(s) }
53+ 'bright_magenta' { term.bright_magenta(s) }
54+ 'bright_cyan' { term.bright_cyan(s) }
55+ 'bright_white' { term.bright_white(s) }
56+ else { s }
57+ }
58+}
59+
60+// default_theme is what every role wears unless the config's (color ...)
61+// form dresses it otherwise: the roles are the keys that form takes
62+fn default_theme() map[string][]string {
63+ return {
64+ 'heading': ['bold']
65+ 'title': ['bright_blue']
66+ 'source': ['bright_blue']
67+ 'name': ['bold']
68+ 'version': ['bright_green']
69+ 'branch': ['bright_blue']
70+ 'old': ['red']
71+ 'success': ['bold']
72+ 'warning': ['bold', 'bright_yellow']
73+ 'error': ['bold', 'red']
74+ 'prompt': ['bright_white']
75+ 'default': ['bold']
76+ }
77+}
78+
79+__global theme = default_theme()
80+
81+// themed wraps text in a role's styles, whether or not the stream is styled
82+fn themed(role string, s string) string {
83+ mut out := s
84+ for name in theme[role] or { []string{} } {
85+ out = apply_style(name, out)
86+ }
87+ return out
88+}
89+
90+// role styles text bound for stdout as a role of the theme, erole text
91+// bound for stderr
92+fn role(name string, s string) string {
93+ return if color_on(false) { themed(name, s) } else { s }
94+}
95+
96+fn erole(name string, s string) string {
97+ return if color_on(true) { themed(name, s) } else { s }
98+}
99+
100+fn heading(s string) string {
101+ return role('heading', s)
102+}
103+
104+fn bold_heading(s string) string {
105+ return role('title', s)
106+}
107+
108+fn source_style(s string) string {
109+ return role('source', s)
110+}
111+
112+fn name_style(s string) string {
113+ return role('name', s)
114+}
115+
116+fn version_style(s string) string {
117+ return role('version', s)
118+}
119+
120+fn branch_style(s string) string {
121+ return role('branch', s)
122+}
123+
124+fn old_style(s string) string {
125+ return role('old', s)
126+}
127+
128+fn success(s string) string {
129+ return role('success', s)
130+}
131+
132+// warning goes to either stream, so it is styled only when both would be
133+fn warning(s string) string {
134+ prefix := 'warning: '
135+ return if color_on(false) && color_on(true) {
136+ themed('warning', prefix) + s
137+ } else {
138+ prefix + s
139+ }
140+}
@@ -0,0 +1,24 @@
1+module main
2+
3+import term
4+
5+fn test_color_flag() {
6+ old := color_flag
7+ defer { color_flag = old }
8+
9+ color_flag = 'always'
10+ assert color_on(false) && color_on(true)
11+ assert heading('x') == term.bold('x')
12+ assert erole('old', 'x') == term.red('x')
13+ assert warning('w').contains('\x1b[')
14+ assert q_no_yes() == '[y/' + term.bold('N') + ']'
15+
16+ color_flag = 'never'
17+ assert !color_on(false) && !color_on(true)
18+ assert heading('x') == 'x'
19+ assert version_style('1.0-1') == '1.0-1'
20+ assert erole('old', 'x') == 'x'
21+ assert warning('w') == 'warning: w'
22+ assert q_yes_no() == '[Y/n]'
23+ assert error_text('e') == 'error: e'
24+}
@@ -0,0 +1,72 @@
1+@[has_globals]
2+module main
3+
4+import alpm
5+import strings
6+
7+// suggest_thold is how close a name must be to be suggested. it is the fuzzy
8+// search measure, a little stricter, since the user is asked about the answer
9+// (options :suggest) sets it
10+__global suggest_thold = 0.85
11+
12+// closest_name is the name nearest to query, when it is near enough: a score
13+// at the threshold counts, and ties fall to the name scanned first, which is
14+// the order the names came in, the config's db order among them
15+fn closest_name(query string, names []string) ?string {
16+ q := query.to_lower()
17+ mut best := ''
18+ mut best_score := 0.0
19+ for name in names {
20+ score := strings.jaro_winkler_similarity(q, name.to_lower())
21+ if score > best_score {
22+ best = name
23+ best_score = score
24+ }
25+ }
26+ if best_score >= suggest_thold {
27+ return best
28+ }
29+ return none
30+}
31+
32+// did_you_mean handles a query that matched no package. it asks about the
33+// nearest name, and returns it when the user says yes. otherwise, and when no
34+// name is near, it is the unknown package error. the question goes through
35+// the ui, which pauses a live display first
36+fn did_you_mean(mut ui TransUI, query string, names []string) !string {
37+ name := closest_name(query, names) or {
38+ return error('unknown package: "${query}"')
39+ }
40+ if ui.noyes('did you mean ${name_style(name)}?') {
41+ return name
42+ }
43+ return error('unknown package: "${query}"')
44+}
45+
46+fn pkg_names(pkgs []&alpm.Package) []string {
47+ return pkgs.map(it.get_name())
48+}
49+
50+// sync_names lists the names of the packages in the sync dbs
51+fn sync_names(dbs []&alpm.DB) []string {
52+ mut names := []string{}
53+ for db in dbs {
54+ mut pkgcache := db.get_pkgcache() or { continue }
55+ names << pkg_names(pkgcache.pkgs())
56+ }
57+ return names
58+}
59+
60+// all_names lists the names of the installed packages and of the sync dbs
61+fn all_names(handle &alpm.Handle, dbs []&alpm.DB) []string {
62+ mut names := local_names(handle)
63+ names << sync_names(dbs)
64+ return names
65+}
66+
67+// local_names lists the names of the installed packages
68+fn local_names(handle &alpm.Handle) []string {
69+ localdb := handle.get_localdb() or { return []string{} }
70+ mut pkgcache := localdb.get_pkgcache() or { return []string{} }
71+ return pkg_names(pkgcache.pkgs())
72+}
@@ -0,0 +1,20 @@
1+module main
2+
3+fn test_closest_name() ! {
4+ names := ['thunderbird', 'linux-lts', 'linux-lts-developer-edition']
5+ // a typo finds its name, the name as it is listed
6+ assert closest_name('fireffox', names)? == 'linux-lts'
7+ assert closest_name('linux-lts', names)? == 'linux-lts'
8+ // case does not count
9+ assert closest_name('FireFox', names)? == 'linux-lts'
10+ // nothing near enough: no suggestion at all
11+ if got := closest_name('xyzzy', names) {
12+ assert false, 'suggested ${got}'
13+ }
14+ if got := closest_name('linux-lts', []string{}) {
15+ assert false, 'suggested ${got} from nothing'
16+ }
17+ // a tie falls to the name met first: the config's db order decides
18+ assert closest_name('zshrc', ['zshra', 'zshrb'])? == 'zshra'
19+ assert closest_name('zshrc', ['zshrb', 'zshra'])? == 'zshrb'
20+}
@@ -0,0 +1,123 @@
1+module main
2+
3+import encoding.utf8
4+import encoding.utf8.east_asian
5+
6+// vpac's own table printer, ported from divilib.fmt: rows of cells, every
7+// column padded to its widest value, two spaces apart, like pkgin's listings.
8+// the widths are the printed widths, so styled values (bold names, colored
9+// versions) line up with the color sequences counted as zero
10+pub struct Cell {
11+ value string
12+}
13+
14+pub struct Row {
15+pub mut:
16+ cols []Cell
17+}
18+
19+// cell makes one column of a row
20+fn cell(value string) Cell {
21+ return Cell{
22+ value: value
23+ }
24+}
25+
26+fn row(cols ...string) Row {
27+ mut out := []Cell{}
28+ for c in cols {
29+ out << cell(c)
30+ }
31+ return Row{
32+ cols: out
33+ }
34+}
35+
36+// kv is a key/value row, the key in bold
37+fn kv(key string, value string) Row {
38+ return Row{
39+ cols: [cell(name_style(key)), cell(value)]
40+ }
41+}
42+
43+// visible_width is the printed width of a string in terminal cells: ANSI
44+// escape sequences count as nothing, and a wide character (CJK, fullwidth
45+// forms) as two, by its Unicode East Asian Width. ambiguous ones count as
46+// one, the way terminals outside East Asian locales draw them. the \x1b form
47+// and the \e033 form divilib used are both handled
48+fn visible_width(input string) int {
49+ mut result := 0
50+ mut i := 0
51+ for i < input.len {
52+ // the length of the sequence marker, and by extension the whole
53+ // sequence, is searched to the terminating byte in the ASCII range.
54+ // the bytes of a multibyte character are never in that range
55+ mut seq := 0
56+ if input[i] == 0x1b && i + 1 < input.len && input[i + 1] == `[` {
57+ seq = 2
58+ } else if input[i] == `\\` && i + 4 < input.len && input[i + 1] == `0`
59+ && input[i + 2] == `3` && input[i + 3] == `3` && input[i + 4] == `[` {
60+ seq = 5
61+ }
62+ if seq > 0 {
63+ i += seq
64+ for i < input.len && !(input[i] >= 0x40 && input[i] <= 0x7e) {
65+ i++
66+ }
67+ if i < input.len {
68+ i++
69+ }
70+ continue
71+ }
72+ if input[i] < 0x80 {
73+ result++
74+ i++
75+ continue
76+ }
77+ result += match east_asian.east_asian_width_property_at(input, i) {
78+ .full, .wide { 2 }
79+ else { 1 }
80+ }
81+ // a broken sequence advances by one byte, so the loop always ends
82+ _, n := utf8.decode_rune_at(input, i)
83+ i += n
84+ }
85+ return result
86+}
87+
88+// table_text renders the rows: columns padded to their widest value, the
89+// first line of every row starting with indent and the columns separated by
90+// sep. the last column is padded too, and the trailing spaces are trimmed
91+// straight away
92+fn table_text(rows []Row, indent string, sep string) string {
93+ if rows.len == 0 {
94+ return ''
95+ }
96+ mut col_count := 0
97+ for r in rows {
98+ if r.cols.len > col_count {
99+ col_count = r.cols.len
100+ }
101+ }
102+ mut widths := []int{len: col_count, init: 0}
103+ for r in rows {
104+ for i, c in r.cols {
105+ w := visible_width(c.value)
106+ if widths[i] < w {
107+ widths[i] = w
108+ }
109+ }
110+ }
111+ mut out := []string{}
112+ for r in rows {
113+ mut line := indent
114+ for i, c in r.cols {
115+ line += c.value
116+ if i < r.cols.len - 1 {
117+ line += ' '.repeat(widths[i] - visible_width(c.value)) + sep
118+ }
119+ }
120+ out << line
121+ }
122+ return out.join('\n')
123+}
@@ -0,0 +1,178 @@
1+module main
2+
3+import alpm
4+
5+// Target is a target as the command line spells it, parted the way pacman's
6+// process_target parts one: 'repo/name' names the db to look in, and a bare
7+// name looks everywhere. the name may be a dependency string ('bash>=5') or
8+// something a package provides ('sh')
9+struct Target {
10+ repo string
11+ name string
12+}
13+
14+// parse_target splits the db off a target. a slash that leads is no prefix,
15+// as in pacman; one that ends the target leaves an empty name, which
16+// nothing is called
17+fn parse_target(target string) Target {
18+ slash := target.index('/') or { -1 }
19+ if slash <= 0 {
20+ return Target{
21+ name: target
22+ }
23+ }
24+ return Target{
25+ repo: target[..slash]
26+ name: target[slash + 1..]
27+ }
28+}
29+
30+// local_target_name is a target of a mode that reads the installed packages
31+// alone: pacman's -R and -Q take 'local/' off and nothing else
32+fn local_target_name(target string) string {
33+ if target.starts_with('local/') && target.len > 6 {
34+ return target[6..]
35+ }
36+ return target
37+}
38+
39+// scope_dbs is the sync dbs a target is looked up in: all of them, or the
40+// one its prefix names. the prefix is a scope, not decoration: a name the
41+// config does not carry is pacman's 'database not found', never a search of
42+// everything with the prefix dropped
43+fn scope_dbs(dbs []&alpm.DB, repo string) ![]&alpm.DB {
44+ if repo == '' {
45+ return dbs
46+ }
47+ scoped := dbs.filter(it.get_name() == repo)
48+ if scoped.len == 0 {
49+ return error('database not found: ${repo}')
50+ }
51+ return scoped
52+}
53+
54+// has_constraint is whether a target asks for a version: a dependency
55+// string with one of libalpm's operators
56+fn has_constraint(name string) bool {
57+ return name.contains_any('<>=')
58+}
59+
60+// find_local_target finds an installed package by name. a version
61+// constraint is answered by what satisfies it; providers says a bare name
62+// may be something a package provides too, which the modes that only read
63+// take and the ones that write do not: 'vpac r sh' must not come to mean
64+// bash
65+fn find_local_target(pkgcache &alpm.List, name string, providers bool) ?&alpm.Package {
66+ if p := pkgcache.pkg_find(name) {
67+ return p
68+ }
69+ if providers || has_constraint(name) {
70+ return pkgcache.find_satisfier(name)
71+ }
72+ return none
73+}
74+
75+// find_sync_target finds a target in the dbs given, already scoped: the
76+// package of that name, or else what libalpm resolves the dependency string
77+// to, as pacman's process_targname asks alpm_find_dbs_satisfier — a version
78+// constraint, or a provider, with libalpm's own questions about ignored
79+// packages and several providers. named says the db was named with the
80+// target, which makes it one to install from for this lookup whatever its
81+// usage, as in pacman
82+fn find_sync_target(handle &alpm.Handle, dbs []&alpm.DB, name string, named bool) ?&alpm.Package {
83+ if name == '' {
84+ return none
85+ }
86+ if p := find_repo_pkg(dbs, name) {
87+ return p
88+ }
89+ mut list := unsafe { &alpm.List(nil) }
90+ for db in dbs {
91+ list = list.add(db)
92+ }
93+ defer { list.free() }
94+ if !named {
95+ return handle.find_dbs_satisfier(list, name)
96+ }
97+ mut restore := map[int]alpm.DBUsage{}
98+ for i, db in dbs {
99+ usage := db.get_usage() or { continue }
100+ if !usage.has(.install) {
101+ db.set_usage(usage | .install) or { continue }
102+ restore[i] = usage
103+ }
104+ }
105+ found := handle.find_dbs_satisfier(list, name)
106+ for i, usage in restore {
107+ dbs[i].set_usage(usage) or {
108+ warn('could not put the usage of ${dbs[i].get_name()} back: ${err.msg()}')
109+ }
110+ }
111+ return found
112+}
113+
114+// GroupMember is one package of a sync group, with the db that carries it
115+struct GroupMember {
116+ repo string
117+ pkg &alpm.Package
118+}
119+
120+// sync_group_members are the packages of a group across the dbs, in db
121+// order; a name a later db repeats is the earlier db's, as libalpm's
122+// alpm_find_group_pkgs has it. found says a db had the group at all
123+fn sync_group_members(dbs []&alpm.DB, name string) (bool, []GroupMember) {
124+ mut found := false
125+ mut out := []GroupMember{}
126+ mut seen := map[string]bool{}
127+ for db in dbs {
128+ group := db.get_group(name) or { continue }
129+ found = true
130+ for pkg in group.packages.pkgs() {
131+ if seen[pkg.get_name()] {
132+ continue
133+ }
134+ seen[pkg.get_name()] = true
135+ out << GroupMember{
136+ repo: db.get_name()
137+ pkg: pkg
138+ }
139+ }
140+ }
141+ return found, out
142+}
143+
144+// select_members asks which members of a group go in, pacman's
145+// multiselect: the members are listed numbered, on stderr with the question
146+// they lead into (a frontend gets them as a listing), and the answer picks
147+// among them. a --print preview lists and asks nothing: every member
148+fn select_members(mut ui TransUI, group string, members []GroupMember, ask bool) []GroupMember {
149+ if !ask || members.len == 0 {
150+ return members
151+ }
152+ ui.pause()
153+ if ipc_on() {
154+ mut listing := Listing{
155+ fields: ['source', 'name', 'version']
156+ }
157+ for m in members {
158+ listing.add_member(m.pkg, m.repo, group)
159+ }
160+ listing.print()
161+ } else {
162+ count := if members.len == 1 { '1 member' } else { '${members.len} members' }
163+ eprintln(erole('heading', '${count} in group ${group}:'))
164+ mut rows := []Row{}
165+ for i, m in members {
166+ rows << row('${i + 1})', m.repo, m.pkg.get_name(), m.pkg.get_version())
167+ }
168+ eprintln(table_text(rows, ' ', ' '))
169+ }
170+ picked := ui.pick('enter a selection', members.len)
171+ mut out := []GroupMember{}
172+ for i, m in members {
173+ if picked[i] {
174+ out << m
175+ }
176+ }
177+ return out
178+}
@@ -0,0 +1,60 @@
1+module testdb
2+
3+import os
4+
5+// testdb writes libalpm local dbs for the tests: every test file is a
6+// binary of its own, so a writer they share lives in a module they import
7+// and vpac itself never does — it is in no build of the program.
8+
9+// Pkg is one installed package of a written db: what its desc says, and the
10+// entries of its file list (directories with their trailing slash, as
11+// libalpm keeps them)
12+pub struct Pkg {
13+pub:
14+ name string
15+ version string = '1.0-1'
16+ reason int // 0 explicit, 1 a dependency
17+ depends []string
18+ optdepends []string
19+ provides []string
20+ conflicts []string
21+ groups []string
22+ files []string
23+ // no_files leaves the file list out altogether, a broken entry
24+ no_files bool
25+}
26+
27+// desc is the text of a package's desc file: the sections that have
28+// something to say, in libalpm's spelling
29+pub fn (p Pkg) desc() string {
30+ mut out := '%NAME%\n${p.name}\n\n%VERSION%\n${p.version}\n\n%ARCH%\nany\n\n%REASON%\n${p.reason}\n\n'
31+ for key, items in {
32+ 'DEPENDS': p.depends
33+ 'OPTDEPENDS': p.optdepends
34+ 'PROVIDES': p.provides
35+ 'CONFLICTS': p.conflicts
36+ 'GROUPS': p.groups
37+ } {
38+ if items.len > 0 {
39+ out += '%${key}%\n${items.join('\n')}\n\n'
40+ }
41+ }
42+ return out
43+}
44+
45+// write_local lays out a local db (version 9) under dbpath: the version
46+// file, and one dir per package, named name-version, with its desc and its
47+// file list. it adds to a db that is there; no packages write an empty one
48+pub fn write_local(dbpath string, pkgs []Pkg) ! {
49+ local := os.join_path(dbpath, 'local')
50+ os.mkdir_all(local)!
51+ os.write_file(os.join_path(local, 'ALPM_DB_VERSION'), '9\n')!
52+ for p in pkgs {
53+ dir := os.join_path(local, '${p.name}-${p.version}')
54+ os.mkdir_all(dir)!
55+ os.write_file(os.join_path(dir, 'desc'), p.desc())!
56+ if !p.no_files {
57+ os.write_file(os.join_path(dir, 'files'), '%FILES%\n${p.files.join('\n')}\n\n')!
58+ }
59+ }
60+}
@@ -0,0 +1,56 @@
1+module testdb
2+
3+import os
4+
5+fn test_desc_says_only_what_there_is() {
6+ bare := Pkg{
7+ name: 'bare'
8+ }
9+ assert bare.desc() == '%NAME%\nbare\n\n%VERSION%\n1.0-1\n\n%ARCH%\nany\n\n%REASON%\n0\n\n'
10+ full := Pkg{
11+ name: 'full'
12+ version: '2:3.0-4'
13+ reason: 1
14+ depends: ['a>=1', 'b']
15+ optdepends: ['c: for more']
16+ provides: ['virt=2']
17+ conflicts: ['rival']
18+ groups: ['g1', 'g2']
19+ }.desc()
20+ assert full.contains('%VERSION%\n2:3.0-4\n\n') && full.contains('%REASON%\n1\n\n')
21+ assert full.contains('%DEPENDS%\na>=1\nb\n\n')
22+ assert full.contains('%OPTDEPENDS%\nc: for more\n\n')
23+ assert full.contains('%PROVIDES%\nvirt=2\n\n') && full.contains('%CONFLICTS%\nrival\n\n')
24+ assert full.contains('%GROUPS%\ng1\ng2\n\n')
25+ // every section ends in its blank line, the last one too
26+ assert full.ends_with('\n\n')
27+}
28+
29+fn test_write_local_edges() ! {
30+ db := os.join_path(os.vtmp_dir(), 'vpac_testdb_${os.getpid()}')
31+ defer { os.rmdir_all(db) or {} }
32+ // no packages: an empty db, which is a version file and nothing else
33+ write_local(db, [])!
34+ assert os.ls(os.join_path(db, 'local'))! == ['ALPM_DB_VERSION']
35+ assert os.read_file(os.join_path(db, 'local', 'ALPM_DB_VERSION'))! == '9\n'
36+ write_local(db, [Pkg{
37+ name: 'a'
38+ files: ['usr/', 'usr/bin/', 'usr/bin/a']
39+ }, Pkg{
40+ name: 'broken'
41+ version: '2-1'
42+ no_files: true
43+ }])!
44+ assert os.read_file(os.join_path(db, 'local', 'a-1.0-1', 'files'))! == '%FILES%\nusr/\nusr/bin/\nusr/bin/a\n\n'
45+ assert os.exists(os.join_path(db, 'local', 'broken-2-1', 'desc'))
46+ assert !os.exists(os.join_path(db, 'local', 'broken-2-1', 'files'))
47+ // a second write adds to the db and leaves what was there
48+ write_local(db, [Pkg{
49+ name: 'later'
50+ }])!
51+ mut names := os.ls(os.join_path(db, 'local'))!
52+ names.sort()
53+ assert names == ['ALPM_DB_VERSION', 'a-1.0-1', 'broken-2-1', 'later-1.0-1']
54+ // a package with no files has a file list, empty
55+ assert os.read_file(os.join_path(db, 'local', 'later-1.0-1', 'files'))! == '%FILES%\n\n\n'
56+}
@@ -0,0 +1,324 @@
1+@[has_globals]
2+module main
3+
4+import alpm
5+import os
6+import sync.stdatomic
7+import v.profiler
8+
9+fn C._exit(status int)
10+
11+// set while this process has an open transaction: txn_locked when it holds
12+// the db lock, txn_unlocked for a --print preview's, which takes none. it
13+// makes trans_cleanup release once, however many paths reach it
14+const txn_open = stdatomic.new_atomic(i64(0))
15+
16+const txn_locked = i64(1)
17+const txn_unlocked = i64(2)
18+
19+// interrupt_handle is the handle a transaction runs on, published for the
20+// signal handler (as its address) from before libalpm takes the db lock
21+// until after it let go of it. the handler hands it to alpm_unlock, which
22+// removes the lock only while this handle holds it (its lockfd), as pacman's
23+// soft_interrupt_handler does: there is no moment where the lock is taken
24+// and the handler does not know it, and a lock held by someone else — or by
25+// nobody, a --print preview's transaction — is never touched
26+const interrupt_handle = stdatomic.new_atomic(u64(0))
27+
28+// split_list reads a repeatable option the way pacman reads its lists: each
29+// value may hold several, comma separated
30+fn split_list(values []string) []string {
31+ mut out := []string{}
32+ for value in values {
33+ for item in value.split(',') {
34+ s := item.trim_space()
35+ if s != '' {
36+ out << s
37+ }
38+ }
39+ }
40+ return out
41+}
42+
43+// dep_check_flag is pacman's -d: once (or --nodeps) skips the version checks
44+// of the dependencies, twice (-dd, or --nodeps with -d) skips the
45+// dependency checks altogether
46+fn dep_check_flag(nodeps bool, level int) alpm.TransFlag {
47+ n := level + if nodeps { 1 } else { 0 }
48+ return if n >= 2 {
49+ alpm.TransFlag.no_deps
50+ } else if n == 1 {
51+ alpm.TransFlag.no_depversion
52+ } else {
53+ alpm.trans_flag_0
54+ }
55+}
56+
57+// TransOptions are the handle options a command line adds for one run, on
58+// top of the config's: pacman's --overwrite, --ignore, --ignoregroup and
59+// --assume-installed, every one a repeatable comma separated list
60+struct TransOptions {
61+ overwrite []string
62+ ignore []string
63+ ignoregroup []string
64+ assume_installed []string
65+}
66+
67+fn (o TransOptions) apply(handle &alpm.Handle) ! {
68+ for glob in split_list(o.overwrite) {
69+ handle.option_add_overwrite_file(glob)!
70+ }
71+ for name in split_list(o.ignore) {
72+ handle.option_add_ignore_pkg(name)!
73+ }
74+ for group in split_list(o.ignoregroup) {
75+ handle.option_add_ignore_group(group)!
76+ }
77+ for spec in split_list(o.assume_installed) {
78+ // libalpm parses any text into a dependency, '=1' into one with no
79+ // name, which would assume nothing: a spec names its package
80+ dep := alpm.dep_from_string(spec)
81+ if dep == unsafe { nil } || dep.get_name() == '' {
82+ if dep != unsafe { nil } {
83+ dep.free()
84+ }
85+ return error('--assume-installed: "${spec}" names no package, write it like name=version')
86+ }
87+ // libalpm keeps its own copy, as pacman relies on
88+ handle.option_add_assumeinstalled(dep) or {
89+ dep.free()
90+ return err
91+ }
92+ dep.free()
93+ }
94+}
95+
96+// trans_begin initializes a transaction. pair it with
97+// `defer { trans_cleanup(handle) }` so every exit path releases it
98+fn trans_begin(handle &alpm.Handle, flags alpm.TransFlag) ! {
99+ // published first: trans_init takes the lock, and a signal right after
100+ // it must find the handle that holds it
101+ publish_for_interrupt(handle)
102+ handle.trans_init(flags) or {
103+ withdraw_from_interrupt()
104+ return err
105+ }
106+ mut open := txn_open
107+ open.store(if flags.has(.nolock) { txn_unlocked } else { txn_locked })
108+}
109+
110+// publish_for_interrupt makes handle the one the signal handler unlocks
111+fn publish_for_interrupt(handle &alpm.Handle) {
112+ mut published := interrupt_handle
113+ published.store(u64(voidptr(handle)))
114+}
115+
116+// withdraw_from_interrupt leaves the signal handler no handle: the lock is
117+// gone, and the handle may be released next
118+fn withdraw_from_interrupt() {
119+ mut published := interrupt_handle
120+ published.store(0)
121+}
122+
123+// print_flags are what a --print preview adds to its transaction, as
124+// pacman's --print does: no db lock, so it needs no root and never waits on
125+// a running transaction, and no conflict checks, so a preview lists the
126+// packages even when a conflict question would come up
127+fn print_flags(print_only bool) alpm.TransFlag {
128+ return if print_only {
129+ alpm.TransFlag.nolock | .no_conflicts
130+ } else {
131+ alpm.trans_flag_0
132+ }
133+}
134+
135+// trans_cleanup releases an open transaction, which is what removes the db
136+// lock. like pacman's cleanup: label, it runs on success, decline and error.
137+// a release that does not go through is said (the lock and the transaction
138+// state would hang behind it); it still counts as closed, or the defers of
139+// a rollback would try again
140+fn trans_cleanup(handle &alpm.Handle) {
141+ mut open := txn_open
142+ if open.load() != 0 {
143+ handle.trans_release() or {
144+ warn('failed to release the transaction: ${err.msg()}')
145+ }
146+ open.store(0)
147+ }
148+ withdraw_from_interrupt()
149+}
150+
151+// prepare_problem_lines words a failed prepare by what libalpm's errno says
152+// its problems are, as pacman's sync_prepare_execute tells them apart: a
153+// missing or broken dependency, a conflict between two packages, a package
154+// of the wrong architecture, and anything else under libalpm's own text
155+fn prepare_problem_lines(kind alpm.Errno, problems []alpm.DepProblem) []string {
156+ mut lines := []string{}
157+ match kind {
158+ .unsatisfied_deps {
159+ lines << 'could not satisfy dependencies:'
160+ for p in problems {
161+ lines << if p.causing == '' {
162+ " unable to satisfy dependency '${p.depend}' required by ${p.target}"
163+ } else {
164+ " ${p.causing} breaks dependency '${p.depend}' required by ${p.target}"
165+ }
166+ }
167+ }
168+ .conflicting_deps {
169+ lines << 'unresolvable package conflicts:'
170+ for p in problems {
171+ // the reason is only said when it is news: not one of the
172+ // two names again
173+ lines << if p.depend == '' || p.depend == p.target || p.depend == p.causing {
174+ ' ${p.target} and ${p.causing} are in conflict'
175+ } else {
176+ ' ${p.target} and ${p.causing} are in conflict (${p.depend})'
177+ }
178+ }
179+ }
180+ .pkg_invalid_arch {
181+ lines << '${kind.strerror()}:'
182+ for p in problems {
183+ lines << ' package ${p.target} does not have a valid architecture'
184+ }
185+ }
186+ else {
187+ lines << '${kind.strerror()}:'
188+ for p in problems {
189+ lines << ' ' + [p.target, p.depend, p.causing].filter(it != '').join(' ')
190+ }
191+ }
192+ }
193+ return lines
194+}
195+
196+// trans_prepare_checked prepares a transaction. when packages would break it,
197+// the error lists each problem the way pacman does
198+fn trans_prepare_checked(handle &alpm.Handle) ! {
199+ problems, failure := handle.trans_prepare_problems()
200+ if err := failure {
201+ if problems.len == 0 {
202+ return err
203+ }
204+ // the errno is still the prepare's: nothing called libalpm since
205+ return error(prepare_problem_lines(handle.errno(), problems).join('\n'))
206+ }
207+}
208+
209+// runs the commit phase of a prepared transaction. the transaction must
210+// already have been begun and prepared.
211+fn trans_commit(handle &alpm.Handle) ! {
212+ handle.trans_commit()!
213+ trans_cleanup(handle)
214+}
215+
216+// on_interrupt is pacman's soft_interrupt_handler: a killed run removes the
217+// db lock it holds, so it does not wedge the next run. alpm_unlock decides
218+// whether it holds one, from libalpm's own state, and does only close and
219+// unlink — async-signal-safe, no allocation. the transaction is not
220+// interrupted cleanly (no alpm_trans_interrupt here: the run ends at once),
221+// but the lock is never left behind
222+fn on_interrupt(sig os.Signal) {
223+ mut published := interrupt_handle
224+ h := published.load()
225+ if h != 0 {
226+ C.alpm_unlock(unsafe { &alpm.Handle(voidptr(h)) })
227+ }
228+ C._exit(128 + int(sig))
229+}
230+
231+// install_interrupt_handlers runs after load_config, at which point db_path
232+// is final: the handler gets the one path it may ever need, cut once here,
233+// and never allocates
234+fn install_interrupt_handlers() {
235+ for sig in [os.Signal.int, .hup, .term, .abrt] {
236+ os.signal_opt(sig, on_interrupt) or { went_on('install the handler of signal ${int(sig)}', err) }
237+ }
238+}
239+
240+enum TransAction {
241+ remove
242+ install
243+ upgrade
244+ autoremove
245+}
246+
247+// trans_listing collects what a prepared transaction does: every package,
248+// with the installed version an install or upgrade replaces, and the sizes
249+fn trans_listing(handle &alpm.Handle, pkgs []&alpm.Package, action TransAction) TransactionEvent {
250+ mut out := []TransPkg{}
251+ mut download := i64(0)
252+ mut install_size := i64(0)
253+ for pkg in pkgs {
254+ name := pkg.get_name()
255+ removing := action == .remove || action == .autoremove
256+ mut old := ''
257+ if !removing {
258+ if installed := handle.find_local_pkg(name) {
259+ old = installed.get_version()
260+ }
261+ }
262+ out << TransPkg{
263+ name: name
264+ version: pkg.get_version()
265+ old_version: old
266+ download_size: if removing { 0 } else { pkg.download_size() }
267+ installed_size: pkg.get_isize()
268+ }
269+ download += out.last().download_size
270+ install_size += out.last().installed_size
271+ }
272+ return TransactionEvent{
273+ action: action.str()
274+ packages: out
275+ download_size: download
276+ installed_size: install_size
277+ }
278+}
279+
280+// print_trans_listing shows a transaction the way pkgin does, with the sizes
281+// for anything that downloads
282+fn print_trans_listing(t TransactionEvent) {
283+ header := match t.action {
284+ 'remove' { 'packages to delete' }
285+ 'install' { 'packages to be installed' }
286+ 'upgrade' { 'packages to be upgraded' }
287+ else { 'packages to be autoremoved' }
288+ }
289+ removing := t.action in ['remove', 'autoremove']
290+ mut rows := []Row{}
291+ for p in t.packages {
292+ if removing {
293+ rows << row(name_style(p.name), version_style(p.version))
294+ } else if p.old_version != '' {
295+ // old version, arrow, new version: a new dependency has no old one
296+ rows << row(name_style(p.name), old_style(p.old_version), '->', version_style(p.version))
297+ } else {
298+ rows << row(name_style(p.name), '', '', version_style(p.version))
299+ }
300+ }
301+ println(heading('${t.packages.len} ${header}:'))
302+ println(table_text(rows, ' ', ' '))
303+ if !removing {
304+ sizes := [
305+ row('to download', profiler.format_bytes(u64(t.download_size))),
306+ row('to install', profiler.format_bytes(u64(t.installed_size))),
307+ ]
308+ println(table_text(sizes, ' ', ' '))
309+ }
310+}
311+
312+// trans_confirm lists a prepared transaction and asks 'proceed? [Y/n]',
313+// where enter is yes, as pacman's 'Proceed with installation?'. a frontend
314+// gets the listing as a transaction event before the question
315+fn trans_confirm(mut ui TransUI, handle &alpm.Handle, pkgs []&alpm.Package, action TransAction) bool {
316+ ui.pause()
317+ listing := trans_listing(handle, pkgs, action)
318+ if ipc_on() {
319+ emit(listing)
320+ } else {
321+ print_trans_listing(listing)
322+ }
323+ return ui.proceed('proceed?')
324+}
@@ -0,0 +1,283 @@
1+module main
2+
3+import alpm
4+import json2
5+import os
6+
7+fn test_split_list() {
8+ // repeatable and comma separated, as pacman reads --ignore and friends
9+ assert split_list([]) == []
10+ assert split_list(['a']) == ['a']
11+ assert split_list(['a,b', 'c']) == ['a', 'b', 'c']
12+ assert split_list([' a , b ', ',,', '']) == ['a', 'b']
13+ assert split_list(['/usr/*,/etc/*']) == ['/usr/*', '/etc/*']
14+}
15+
16+fn test_dep_check_flag() {
17+ // pacman's -d skips the version checks, -dd every dependency check;
18+ // --nodeps is one -d
19+ assert dep_check_flag(false, 0) == alpm.trans_flag_0
20+ assert dep_check_flag(true, 0) == alpm.TransFlag.no_depversion
21+ assert dep_check_flag(false, 1) == alpm.TransFlag.no_depversion
22+ assert dep_check_flag(false, 2) == alpm.TransFlag.no_deps
23+ assert dep_check_flag(true, 1) == alpm.TransFlag.no_deps
24+ assert dep_check_flag(false, 3) == alpm.TransFlag.no_deps
25+}
26+
27+// trans_sandbox opens a handle on an empty temp db, and points the ipc
28+// channel at a file, so what the lifecycle says can be read back
29+fn trans_sandbox(name string) !(string, &alpm.Handle) {
30+ tmp := os.join_path(os.vtmp_dir(), 'vpac_test_trans_${name}_${os.getpid()}')
31+ os.rmdir_all(tmp) or {}
32+ os.mkdir_all(os.join_path(tmp, 'root'))!
33+ os.mkdir_all(os.join_path(tmp, 'db', 'local'))!
34+ os.write_file(os.join_path(tmp, 'db', 'local', 'ALPM_DB_VERSION'), '9\n')!
35+ handle := alpm.initialize(os.join_path(tmp, 'root') + '/', os.join_path(tmp, 'db') + '/')!
36+ return tmp, handle
37+}
38+
39+// said runs f with --ui ipc on and the channel in a file, and returns the
40+// texts of the messages f sent
41+fn said(tmp string, f fn ()) ![]string {
42+ path := os.join_path(tmp, 'channel')
43+ mut file := os.create(path)!
44+ saved_kind, saved_fd := ui_kind, ipc_fd
45+ ui_kind, ipc_fd = 'ipc', file.fd
46+ f()
47+ ui_kind, ipc_fd = saved_kind, saved_fd
48+ file.close()
49+ mut out := []string{}
50+ for line in os.read_lines(path)! {
51+ out << json2.decode[json2.Any](line)!.as_map()['text'] or { json2.Any('') }.str()
52+ }
53+ return out
54+}
55+
56+fn test_trans_cleanup_releases_once() ! {
57+ tmp, handle := trans_sandbox('once')!
58+ defer { os.rmdir_all(tmp) or {} }
59+ defer { handle.release() or {} }
60+ lpath := os.join_path(tmp, 'db', 'db.lck')
61+ trans_begin(handle, alpm.trans_flag_0)!
62+ assert os.exists(lpath)
63+ msgs := said(tmp, fn [handle] () {
64+ trans_cleanup(handle)
65+ // a second cleanup — a defer after an explicit one — is a no-op,
66+ // not a release libalpm would refuse
67+ trans_cleanup(handle)
68+ })!
69+ assert msgs.len == 0
70+ assert !os.exists(lpath)
71+ mut open := txn_open
72+ assert open.load() == 0
73+}
74+
75+fn test_trans_cleanup_failure_is_said_and_counts_as_closed() ! {
76+ tmp, handle := trans_sandbox('failure')!
77+ defer { os.rmdir_all(tmp) or {} }
78+ defer { handle.release() or {} }
79+ // the process believes in a transaction libalpm does not have: the
80+ // release fails, the way it would after libalpm dropped it
81+ mut open := txn_open
82+ open.store(txn_locked)
83+ msgs := said(tmp, fn [handle] () {
84+ trans_cleanup(handle)
85+ trans_cleanup(handle)
86+ })!
87+ // said once, and closed: the second cleanup did not try again
88+ assert msgs.len == 1
89+ assert msgs[0].starts_with('failed to release the transaction: ')
90+ assert open.load() == 0
91+}
92+
93+fn test_trans_commit_releases() ! {
94+ // a committed transaction lets go of the lock through the commit's own
95+ // cleanup, and leaves the deferred one nothing to do. an empty one would
96+ // not do: libalpm's prepare returns early on nothing and its commit then
97+ // refuses as not prepared, so a package is really removed
98+ tmp, handle := trans_sandbox('commit')!
99+ defer { os.rmdir_all(tmp) or {} }
100+ defer { handle.release() or {} }
101+ entry := os.join_path(tmp, 'db', 'local', 'gone-1.0-1')
102+ os.mkdir_all(entry)!
103+ os.write_file(os.join_path(entry, 'desc'), '%NAME%\ngone\n\n%VERSION%\n1.0-1\n\n')!
104+ os.write_file(os.join_path(entry, 'files'), '%FILES%\n\n')!
105+ trans_begin(handle, alpm.trans_flag_0)!
106+ handle.remove_pkg(handle.find_local_pkg('gone') or { return error('gone is not installed') })!
107+ trans_prepare_checked(handle)!
108+ trans_commit(handle)!
109+ assert !os.exists(os.join_path(tmp, 'db', 'db.lck'))
110+ assert !os.exists(entry)
111+ mut open := txn_open
112+ assert open.load() == 0
113+ msgs := said(tmp, fn [handle] () {
114+ trans_cleanup(handle)
115+ })!
116+ assert msgs.len == 0
117+}
118+
119+fn test_trans_options_of_install_and_upgrade() ! {
120+ // the same four flags, read the same way from either command line
121+ want := TransOptions{
122+ overwrite: ['/usr/*']
123+ ignore: ['a,b']
124+ ignoregroup: ['g']
125+ assume_installed: ['sh=5']
126+ }
127+ assert trans_options(ConfigInstall{
128+ overwrite: ['/usr/*']
129+ ignore: ['a,b']
130+ ignoregroup: ['g']
131+ assume_installed: ['sh=5']
132+ }) == want
133+ assert trans_options(ConfigUpgrade{
134+ overwrite: ['/usr/*']
135+ ignore: ['a,b']
136+ ignoregroup: ['g']
137+ assume_installed: ['sh=5']
138+ }) == want
139+ // and they reach the handle a transaction runs on, lists split
140+ tmp, handle := trans_sandbox('options')!
141+ defer { os.rmdir_all(tmp) or {} }
142+ defer { handle.release() or {} }
143+ want.apply(handle)!
144+ mut ignored := handle.option_get_ignore_pkgs()
145+ assert ignored.strs() == ['a', 'b']
146+ mut overwrite := handle.option_get_overwrite_files()
147+ assert overwrite.strs() == ['/usr/*']
148+ // a spec that names no package is said, rather than assuming nothing
149+ for spec in ['=', '=1.0', '>=2'] {
150+ TransOptions{
151+ assume_installed: [spec]
152+ }.apply(handle) or {
153+ assert err.msg().contains('names no package'), err.msg()
154+ continue
155+ }
156+ assert false, '--assume-installed ${spec} was taken'
157+ }
158+}
159+
160+// killed_child forks, lets the child take the db lock of the sandbox the
161+// way take describes, and kills it with SIGTERM through the installed
162+// handler; it returns the child's exit status. the child runs V code — the
163+// handlers' installation and take, a trans_begin in the tests here — on its
164+// copy of the test's memory, and only ever leaves through _exit (the
165+// handler's, or the 98 and 99 of a failure), so no defer, no atexit and no
166+// test-runner report of the parent's runs a second time in it
167+fn killed_child(handle &alpm.Handle, take fn (&alpm.Handle)) int {
168+ pid := C.fork()
169+ if pid == 0 {
170+ install_interrupt_handlers()
171+ take(handle)
172+ C.kill(C.getpid(), 15)
173+ // the handler exits; reaching here is the failure
174+ C._exit(99)
175+ }
176+ mut status := 0
177+ C.waitpid(pid, &status, 0)
178+ return (status >> 8) & 0xff
179+}
180+
181+fn test_interrupt_lets_go_of_the_lock() ! {
182+ tmp, handle := trans_sandbox('interrupt')!
183+ defer { os.rmdir_all(tmp) or {} }
184+ defer { handle.release() or {} }
185+ lpath := os.join_path(tmp, 'db', 'db.lck')
186+ // a transaction is open, the lock held: the killed run removes it
187+ status := killed_child(handle, fn (h &alpm.Handle) {
188+ trans_begin(h, alpm.trans_flag_0) or { C._exit(98) }
189+ })
190+ assert status == 128 + 15
191+ assert !os.exists(lpath)
192+}
193+
194+fn test_interrupt_right_after_the_lock_is_taken() ! {
195+ tmp, handle := trans_sandbox('interrupt_window')!
196+ defer { os.rmdir_all(tmp) or {} }
197+ defer { handle.release() or {} }
198+ lpath := os.join_path(tmp, 'db', 'db.lck')
199+ // the signal lands between libalpm taking the lock and vpac recording
200+ // the transaction: the handle was published before, so the lock goes
201+ status := killed_child(handle, fn (h &alpm.Handle) {
202+ publish_for_interrupt(h)
203+ h.trans_init(alpm.trans_flag_0) or { C._exit(98) }
204+ })
205+ assert status == 128 + 15
206+ assert !os.exists(lpath)
207+}
208+
209+fn test_interrupt_leaves_a_lock_it_does_not_hold() ! {
210+ tmp, handle := trans_sandbox('interrupt_other')!
211+ defer { os.rmdir_all(tmp) or {} }
212+ defer { handle.release() or {} }
213+ lpath := os.join_path(tmp, 'db', 'db.lck')
214+ // another process holds the lock, and this run only previews (--print
215+ // takes none): the killed run leaves the other's lock alone
216+ os.write_file(lpath, '')!
217+ status := killed_child(handle, fn (h &alpm.Handle) {
218+ trans_begin(h, print_flags(true)) or { C._exit(98) }
219+ })
220+ assert status == 128 + 15
221+ assert os.exists(lpath)
222+}
223+
224+fn test_trans_publishes_its_handle_while_open() ! {
225+ tmp, handle := trans_sandbox('publish')!
226+ defer { os.rmdir_all(tmp) or {} }
227+ defer { handle.release() or {} }
228+ mut published := interrupt_handle
229+ assert published.load() == 0
230+ trans_begin(handle, alpm.trans_flag_0)!
231+ assert published.load() == u64(voidptr(handle))
232+ trans_cleanup(handle)
233+ assert published.load() == 0
234+ // a begin that fails publishes nothing past its failure: the lock is
235+ // someone else's here
236+ os.write_file(os.join_path(tmp, 'db', 'db.lck'), '')!
237+ if _ := trans_begin(handle, alpm.trans_flag_0) {
238+ assert false, 'a held lock was taken'
239+ }
240+ assert published.load() == 0
241+}
242+
243+// a failed prepare is worded by its kind, pacman's three shapes and
244+// libalpm's own text for the rest
245+fn test_prepare_problem_lines() {
246+ dep := prepare_problem_lines(.unsatisfied_deps, [
247+ alpm.DepProblem{
248+ target: 'user'
249+ depend: 'lib<2.0'
250+ causing: 'lib'
251+ },
252+ alpm.DepProblem{
253+ target: 'app'
254+ depend: 'gone'
255+ },
256+ ])
257+ assert dep == ['could not satisfy dependencies:',
258+ " lib breaks dependency 'lib<2.0' required by user",
259+ " unable to satisfy dependency 'gone' required by app"]
260+ conflict := prepare_problem_lines(.conflicting_deps, [
261+ alpm.DepProblem{
262+ target: 'p1'
263+ depend: 'p2'
264+ causing: 'p2'
265+ },
266+ alpm.DepProblem{
267+ target: 'p1'
268+ depend: 'virt<2'
269+ causing: 'p3'
270+ },
271+ ])
272+ assert conflict == ['unresolvable package conflicts:', ' p1 and p2 are in conflict',
273+ ' p1 and p3 are in conflict (virt<2)']
274+ wrong_arch := prepare_problem_lines(.pkg_invalid_arch, [alpm.DepProblem{
275+ target: 'foo-1.0-1-riscv64'
276+ }])
277+ assert wrong_arch.len == 2
278+ assert wrong_arch[1] == ' package foo-1.0-1-riscv64 does not have a valid architecture'
279+ other := prepare_problem_lines(.trans_dup_target, [alpm.DepProblem{
280+ target: 'foo'
281+ }])
282+ assert other.len == 2 && other[1] == ' foo'
283+}
@@ -0,0 +1,937 @@
1+@[has_globals]
2+module main
3+
4+import alpm
5+import sync
6+import time
7+import x.progress
8+
9+#include "@VMODROOT/src/alpm_log.h"
10+
11+fn C.vpac_set_alpm_log(handle &alpm.Handle, ctx voidptr) int
12+
13+// ALPM_LOG_ERROR: the one level the log callback tells apart, the other one
14+// it passes being a warning (alpm_log.h)
15+const alpm_log_error = 1
16+
17+// ProgressCfg is how the live display draws, the config's (progress ...) and
18+// (spinner ...) forms. style is the bar graphic, 'classic' or 'block', and
19+// parts holds the pieces of it the config respelled (start, end, fill,
20+// head, empty), the style's own standing for the rest. frames empty is the
21+// display's own spinner
22+struct ProgressCfg {
23+mut:
24+ style string = 'classic'
25+ parts map[string]string
26+ length int = 30
27+ percent bool = true
28+ eta bool = true
29+ elapsed bool
30+ rate bool = true
31+ delay int = 50
32+ frames []string
33+ interval int = 80
34+ done string = '✓'
35+ timed bool
36+}
37+
38+__global cfg_progress = ProgressCfg{}
39+
40+// spinner_sets are the frame sets (spinner :frames) knows by name
41+const spinner_sets = ['dots', 'braille', 'line', 'arrows', 'circle', 'quarters', 'grow', 'bounce',
42+ 'pulse', 'ellipsis', 'earth', 'moon']
43+
44+// spinner_frames_named is a frame set by its name, none for a name outside
45+// spinner_sets
46+fn spinner_frames_named(name string) ?[]string {
47+ return match name {
48+ 'dots' { progress.spinner_dots() }
49+ 'braille' { progress.spinner_braille() }
50+ 'line' { progress.spinner_line() }
51+ 'arrows' { progress.spinner_arrows() }
52+ 'circle' { progress.spinner_circle() }
53+ 'quarters' { progress.spinner_quarters() }
54+ 'grow' { progress.spinner_grow() }
55+ 'bounce' { progress.spinner_bounce() }
56+ 'pulse' { progress.spinner_pulse() }
57+ 'ellipsis' { progress.spinner_ellipsis() }
58+ 'earth' { progress.spinner_earth() }
59+ 'moon' { progress.spinner_moon() }
60+ else { none }
61+ }
62+}
63+
64+// part_rune is one cell of a bar graphic as the config spelled it: the
65+// first rune, or fallback for a part it left alone or emptied
66+fn part_rune(name string, fallback rune) rune {
67+ text := cfg_progress.parts[name] or { return fallback }
68+ runes := text.runes()
69+ return if runes.len > 0 { runes[0] } else { fallback }
70+}
71+
72+// bar_style is the bar graphic the config draws
73+fn bar_style() progress.Style {
74+ if cfg_progress.style == 'block' {
75+ d := progress.BlockStyle{}
76+ return progress.BlockStyle{
77+ start: cfg_progress.parts['start'] or { d.start }
78+ end: cfg_progress.parts['end'] or { d.end }
79+ fill: part_rune('fill', d.fill)
80+ empty: part_rune('empty', d.empty)
81+ }
82+ }
83+ d := progress.ClassicStyle{}
84+ return progress.ClassicStyle{
85+ start: cfg_progress.parts['start'] or { d.start }
86+ end: cfg_progress.parts['end'] or { d.end }
87+ fill: part_rune('fill', d.fill)
88+ // an emptied head is no head: the bar ends in its fill
89+ head: if 'head' in cfg_progress.parts { part_rune('head', 0) } else { d.head }
90+ empty: part_rune('empty', d.empty)
91+ }
92+}
93+
94+// bar_opts dresses a bar the config's way: what a caller asks of its bar
95+// stays, and the rate is shown only where the caller has one to show
96+fn bar_opts(o progress.BarOptions) progress.BarOptions {
97+ return progress.BarOptions{
98+ ...o
99+ style: bar_style()
100+ length: cfg_progress.length
101+ show_percent: cfg_progress.percent
102+ show_left: cfg_progress.eta
103+ show_elapsed: cfg_progress.elapsed
104+ show_rate: o.show_rate && cfg_progress.rate
105+ }
106+}
107+
108+// spinner_opts dresses a spinner the config's way
109+fn spinner_opts(o progress.SpinnerOptions) progress.SpinnerOptions {
110+ return progress.SpinnerOptions{
111+ ...o
112+ frames: if cfg_progress.frames.len > 0 {
113+ cfg_progress.frames.clone()
114+ } else {
115+ o.frames.clone()
116+ }
117+ interval: cfg_progress.interval * time.millisecond
118+ done_frame: cfg_progress.done
119+ show_elapsed: cfg_progress.timed
120+ }
121+}
122+
123+// TransUI is a command's user interface: the shared progress display (one
124+// MultiBar that holds spinners for the command phases, download bars fed by
125+// alpm's dlcb and transaction phase bars fed by alpm's progresscb) and the
126+// prompter every question goes through, libalpm's own included. It is passed
127+// to alpm as the callback context. under --ui ipc there is no MultiBar: the
128+// same calls send events (Phase, Meter, the callbacks)
129+// every ui-bearing function spells its ui `mut ui TransUI`, the way it does
130+// for the _locked helpers: TransUI is @[heap], and a mut value parameter of
131+// one writes through, so the ui handed to a mode and the one its helpers
132+// reach are the same struct. only init_handle takes the reference spelled
133+// out, since it hands the pointer itself to libalpm
134+@[heap]
135+struct TransUI {
136+mut:
137+ mb &progress.MultiBar = unsafe { nil }
138+ // mu guards the fields below against libalpm's download callbacks: with
139+ // parallel downloads on, dlcb arrives on several threads at once, and
140+ // progresscb may join it. every method here takes mu before it touches
141+ // state other callbacks or threads can see, and the _locked helpers
142+ // below it are reached only with the mutex held. the bars and the
143+ // multibar are drawn thread-safely by x.progress itself
144+ mu &sync.Mutex = sync.new_mutex()
145+ dbars map[string]&progress.Bar
146+ pbar &progress.Bar = unsafe { nil }
147+ pkey int
148+ // dpad is the width every download bar reserves for its name, so all
149+ // bars start at the same X coordinate; grows to the longest name seen
150+ dpad int
151+ // prompt asks the user; its noconfirm is --noconfirm, which every
152+ // command that asks anything passes to new_trans_ui
153+ prompt Prompter
154+ // print_only (--print) answers every question silently, as pacman's
155+ // --print does, so the listing on stdout stays clean
156+ print_only bool
157+ // download_only (install -w) fetches an ignored package without asking
158+ download_only bool
159+ // walking is set while install looks dependencies up for itself: the
160+ // questions libalpm raises then are answered as --print answers them
161+ walking bool
162+ // dlast is what each download last reported under --ui ipc, so an event
163+ // goes out as the percent moves or the time passes (download_due), not
164+ // for every chunk; plast is the last progress event, which libalpm may
165+ // send twice
166+ dlast map[string]DownloadSent
167+ plast ProgressEvent
168+}
169+
170+// TransUIOptions are what a command tells its TransUI
171+@[params]
172+struct TransUIOptions {
173+ // noconfirm is --noconfirm: every prompt takes its default unasked
174+ noconfirm bool
175+}
176+
177+// new_trans_ui makes a command's TransUI, with the prompter of the frontend
178+// --ui chose
179+fn new_trans_ui(o TransUIOptions) &TransUI {
180+ return &TransUI{
181+ dbars: {}
182+ prompt: if ipc_on() {
183+ Prompter(IpcPrompter{
184+ noconfirm: o.noconfirm
185+ })
186+ } else {
187+ Prompter(TermPrompter{
188+ noconfirm: o.noconfirm
189+ })
190+ }
191+ }
192+}
193+
194+// group returns the live MultiBar, starting a new one if the previous one was
195+// paused for a prompt. the alpm callbacks reach the display through this
196+// struct, so they always draw on the current MultiBar
197+fn (mut ui TransUI) group() &progress.MultiBar {
198+ ui.mu.lock()
199+ defer { ui.mu.unlock() }
200+ return ui.group_locked()
201+}
202+
203+// group_locked is group, with the ui's mutex already held: download bars and
204+// the lazy creation of the MultiBar must not race
205+fn (mut ui TransUI) group_locked() &progress.MultiBar {
206+ if ui.mb == unsafe { nil } {
207+ // the cursor stays visible: confirmation prompts are asked on a
208+ // running display otherwise, and a hidden cursor makes them look dead
209+ ui.mb = progress.MultiBar.new(
210+ hide_cursor: false
211+ delay: cfg_progress.delay * time.millisecond
212+ )
213+ }
214+ return ui.mb
215+}
216+
217+// Phase is a step a command shows while it works: a spinner on a terminal,
218+// phase events under --ui ipc
219+@[heap]
220+struct Phase {
221+mut:
222+ spinner &progress.Spinner = unsafe { nil }
223+ text string
224+ started bool
225+ done bool
226+}
227+
228+fn (mut ui TransUI) spinner(opts progress.SpinnerOptions) &Phase {
229+ if ipc_on() {
230+ return &Phase{
231+ text: opts.text
232+ }
233+ }
234+ return &Phase{
235+ spinner: ui.group().add_spinner(spinner_opts(opts))
236+ text: opts.text
237+ }
238+}
239+
240+fn (mut p Phase) start() {
241+ if p.spinner != unsafe { nil } {
242+ p.spinner.start()
243+ return
244+ }
245+ p.started = true
246+ emit(PhaseEvent{
247+ text: p.text
248+ state: 'start'
249+ })
250+}
251+
252+// set_text renames the step; a running one reports the new name as a start
253+fn (mut p Phase) set_text(text string) {
254+ p.text = text
255+ if p.spinner != unsafe { nil } {
256+ p.spinner.set_text(text)
257+ return
258+ }
259+ if p.started && !p.done {
260+ emit(PhaseEvent{
261+ text: text
262+ state: 'start'
263+ })
264+ }
265+}
266+
267+fn (p &Phase) is_done() bool {
268+ if p.spinner != unsafe { nil } {
269+ return p.spinner.is_done()
270+ }
271+ return p.done
272+}
273+
274+fn (mut p Phase) finish() {
275+ if p.spinner != unsafe { nil } {
276+ p.spinner.finish()
277+ return
278+ }
279+ if p.done {
280+ return
281+ }
282+ p.done = true
283+ if p.started {
284+ emit(PhaseEvent{
285+ text: p.text
286+ state: 'done'
287+ })
288+ }
289+}
290+
291+// Meter is a counted step: a bar on a terminal, progress events under
292+// --ui ipc, one each time the percent moves
293+@[heap]
294+struct Meter {
295+mut:
296+ bar &progress.Bar = unsafe { nil }
297+ text string
298+ total i64
299+ count i64
300+ percent int = -1
301+}
302+
303+fn (mut ui TransUI) meter(total i64, text string) &Meter {
304+ if ipc_on() {
305+ return &Meter{
306+ text: text
307+ total: total
308+ }
309+ }
310+ return &Meter{
311+ bar: ui.group().add_bar(total, bar_opts(text: text + ' '))
312+ text: text
313+ total: total
314+ }
315+}
316+
317+fn (mut m Meter) start() {
318+ if m.bar != unsafe { nil } {
319+ m.bar.start()
320+ return
321+ }
322+ m.add(0)
323+}
324+
325+fn (mut m Meter) add(n i64) {
326+ if m.bar != unsafe { nil } {
327+ m.bar.add(n)
328+ return
329+ }
330+ m.count += n
331+ pct := if m.total > 0 { int(m.count * 100 / m.total) } else { 100 }
332+ if pct != m.percent {
333+ m.percent = pct
334+ emit(ProgressEvent{
335+ op: m.text
336+ percent: pct
337+ current: int(m.count)
338+ total: int(m.total)
339+ })
340+ }
341+}
342+
343+// pause stops the live display before a confirmation prompt. the render
344+// thread must be gone before the prompt is written, otherwise its redraw can
345+// erase the prompt and leave the program waiting on a question nobody sees
346+fn (mut ui TransUI) pause() {
347+ ui.mu.lock()
348+ defer { ui.mu.unlock() }
349+ if ui.mb != unsafe { nil } {
350+ ui.mb.stop()
351+ ui.mb = unsafe { nil }
352+ }
353+ ui.pbar = unsafe { nil }
354+ ui.dbars = map[string]&progress.Bar{}
355+ ui.dpad = 0
356+ ui.dlast = map[string]DownloadSent{}
357+ ui.plast = ProgressEvent{}
358+}
359+
360+// stop ends the live display, the run over. reached with the ui's mutex,
361+// like every touch of the display's fields: a download callback creating a
362+// bar on another thread must not race the stop that tears it down
363+fn (mut ui TransUI) stop() {
364+ ui.mu.lock()
365+ defer { ui.mu.unlock() }
366+ if ui.mb != unsafe { nil } {
367+ ui.mb.stop()
368+ }
369+}
370+
371+// sync asks the live display to paint right away: the finished frame of a
372+// spinner that just stopped is otherwise drawn by the next tick, which lands
373+// behind the result line the caller is about to print
374+fn (mut ui TransUI) sync() {
375+ if ui.mb != unsafe { nil } {
376+ ui.mb.flush()
377+ }
378+}
379+
380+// stop_spinner finishes a spinner that is still running, so a command that
381+// fails or asks a question does not leave it turning on screen
382+fn stop_spinner(mut s Phase) {
383+ if !s.is_done() {
384+ s.finish()
385+ }
386+}
387+
388+// end_frame is the stop a spinner window needs before plain printlns: the
389+// finished frame goes out right away, and the render thread is stopped.
390+// stopping the spinner alone leaves the thread drawing, and a further tick
391+// lands right inside the lines that follow (the report of verify showed it).
392+// the writes that are safe beside a live frame are the group's own println
393+// and the prompts, which reach it through ui.pause
394+fn end_frame(mut ui TransUI, mut s Phase) {
395+ stop_spinner(mut s)
396+ ui.sync()
397+ ui.pause()
398+}
399+
400+// print_done is the transaction result line, e.g. "removed: <packages>".
401+// every command that commits a transaction reports through it
402+fn print_done(mut ui TransUI, label string, names []string) {
403+ if ipc_on() {
404+ emit(DoneEvent{
405+ action: label.trim_right(':')
406+ packages: names
407+ })
408+ return
409+ }
410+ ui.sync()
411+ ui.group().println('${success(label)} ${names.join(' ')}')
412+}
413+
414+// say is a result line printed beside the live display, a message event
415+// under --ui ipc
416+fn (mut ui TransUI) say(text string) {
417+ if ipc_on() {
418+ emit(MessageEvent{
419+ text: text
420+ })
421+ return
422+ }
423+ ui.group().println(text)
424+}
425+
426+// warn is a warning printed beside the live display, as say prints a result
427+// line: above the bars a download may still draw, never through them. under
428+// --ui ipc it is the warning message event warn() sends
429+fn (mut ui TransUI) warn(text string) {
430+ if ipc_on() {
431+ warn(text)
432+ return
433+ }
434+ ui.group().println(warning(text))
435+}
436+
437+// show_packages lists packages under a heading, the way a transaction shows
438+// the ones it removes or skips: name and version
439+fn (mut ui TransUI) show_packages(title string, pkgs []&alpm.Package) {
440+ if ipc_on() {
441+ emit(PackagesEvent{
442+ title: title.trim_right(':')
443+ packages: pkgs.map(TransPkg{
444+ name: it.get_name()
445+ version: it.get_version()
446+ })
447+ })
448+ return
449+ }
450+ println(heading(title))
451+ println(table_text(pkgs.map(row(name_style(it.get_name()), version_style(it.get_version()))),
452+ ' ', ' '))
453+}
454+
455+fn safe_vstring(p &u8) string {
456+ return if p == unsafe { nil } { '' } else { unsafe { p.vstring() } }
457+}
458+
459+// download_text pads a download bar's text to the shared name column: every
460+// bar reserves the same cells for its name (as wide as the longest name seen
461+// so far, plus the trailing space), so all bars sit at the same X coordinate
462+// whatever their filenames' lengths. when a longer name arrives later, the
463+// column widens and the running bars are re-padded in place (set_text is
464+// thread-safe); finished bars are left alone, their lines are already printed
465+// reached only with the ui's mutex held, from download_bar
466+fn (mut ui TransUI) download_text_locked(name string) string {
467+ if name.len + 1 > ui.dpad {
468+ ui.dpad = name.len + 1
469+ }
470+ for key, mut bar in ui.dbars {
471+ if bar.is_done() {
472+ continue
473+ }
474+ bar.set_text(key + ' '.repeat(ui.dpad - key.len))
475+ }
476+ return name + ' '.repeat(ui.dpad - name.len)
477+}
478+
479+// download_bar returns the display bar of one download, created on the file's
480+// first event, when its size is known; the shown group starts with it
481+// libalpm runs its dlcb on the parallel download threads, so the shared
482+// state is reached with the ui's mutex, and never the drawing itself
483+fn (mut ui TransUI) download_bar(name string, total i64, on_end string, show_rate bool) &progress.Bar {
484+ ui.mu.lock()
485+ defer { ui.mu.unlock() }
486+ bar := ui.dbars[name] or {
487+ mb := ui.group_locked()
488+ b := mb.add_bar(total, bar_opts(
489+ text: ui.download_text_locked(name)
490+ show_rate: show_rate
491+ rate_unit: progress.RateUnit.bytes_iec()
492+ on_end: on_end
493+ ))
494+ ui.dbars[name] = b
495+ mb.start()
496+ b
497+ }
498+ return bar
499+}
500+
501+fn cb_download(ctx voidptr, filename &u8, event alpm.DownloadEventType, data voidptr) {
502+ mut ui := &TransUI(ctx)
503+ name := safe_vstring(filename)
504+ if ipc_on() {
505+ ipc_download(mut ui, name, event, data)
506+ return
507+ }
508+ match event {
509+ .init {
510+ // the bar is created at the first progress event, when the
511+ // download size is known
512+ }
513+ .progress {
514+ p := unsafe { &alpm.DownloadEventProgress(data) }
515+ // libalpm runs this callback on its parallel download threads:
516+ // the shared display state is reached through the ui's mutex, the
517+ // drawing itself is x.progress's to keep thread-safe
518+ bar := ui.download_bar(name, p.total, '', true)
519+ bar.set(p.downloaded)
520+ }
521+ .retry {
522+ // libalpm moves on to the next mirror: a download that starts over
523+ // starts its bar over, as pacman's dload_retry_event does, and one
524+ // that resumes keeps its place
525+ r := unsafe { &alpm.DownloadEventRetry(data) }
526+ if r.resume == 0 {
527+ ui.restart_download_bar(name)
528+ }
529+ }
530+ .completed {
531+ c := unsafe { &alpm.DownloadEventCompleted(data) }
532+ // libalpm's result: 1 means the local copy met the time condition
533+ // and nothing was fetched, 0 a finished download, -1 an error. a
534+ // download can finish before its first progress event, so the bar
535+ // may not exist yet; only result 1 is labelled up to date
536+ on_end := if c.result == 1 { '${name} is up to date' } else { '' }
537+ bar := ui.download_bar(name, c.total, on_end, false)
538+ bar.set(c.total)
539+ }
540+ }
541+}
542+
543+// restart_download_bar puts a download's bar back at nothing, when libalpm
544+// starts the file over from another mirror. a bar not drawn yet has nothing
545+// to restart
546+fn (mut ui TransUI) restart_download_bar(name string) {
547+ ui.mu.lock()
548+ defer { ui.mu.unlock() }
549+ mut bar := ui.dbars[name] or { return }
550+ bar.set(0)
551+}
552+
553+// DownloadSent is what a download last reported under --ui ipc: its percent,
554+// and when, in the monotonic clock's nanoseconds
555+struct DownloadSent {
556+ percent int
557+ at i64
558+}
559+
560+// download_beat is the longest a download in progress goes without an
561+// event: a large file on a slow line moves a percent in minutes, and a
562+// frontend's rate would stand still that long
563+const download_beat = i64(250 * time.millisecond)
564+
565+// download_due tells whether a progress report goes out: the first one of a
566+// download, then each time the percent moves or a beat has passed
567+fn download_due(last ?DownloadSent, percent int, now i64) bool {
568+ sent := last or { return true }
569+ return percent != sent.percent || now - sent.at >= download_beat
570+}
571+
572+// ipc_download reports a download as events: as its percent moves or a beat
573+// passes, once more when libalpm retries it from the next mirror, and once
574+// when it is done. the dlcb arrives on libalpm's parallel download threads,
575+// so the dedupe table is reached with the ui's mutex, and the event goes out
576+// once the lock is gone
577+fn ipc_download(mut ui TransUI, name string, event alpm.DownloadEventType, data voidptr) {
578+ match event {
579+ .progress {
580+ p := unsafe { &alpm.DownloadEventProgress(data) }
581+ pct := if p.total > 0 { int(p.downloaded * 100 / p.total) } else { 0 }
582+ now := time.sys_mono_now()
583+ ui.mu.lock()
584+ if !download_due(ui.dlast[name] or { none }, pct, i64(now)) {
585+ ui.mu.unlock()
586+ return
587+ }
588+ ui.dlast[name] = DownloadSent{
589+ percent: pct
590+ at: i64(now)
591+ }
592+ ui.mu.unlock()
593+ emit(DownloadEvent{
594+ file: name
595+ downloaded: p.downloaded
596+ total: p.total
597+ })
598+ }
599+ .retry {
600+ r := unsafe { &alpm.DownloadEventRetry(data) }
601+ // what was reported is history: the next progress goes out
602+ ui.mu.lock()
603+ ui.dlast.delete(name)
604+ ui.mu.unlock()
605+ emit(DownloadEvent{
606+ file: name
607+ retry: true
608+ resume: r.resume != 0
609+ })
610+ }
611+ .completed {
612+ c := unsafe { &alpm.DownloadEventCompleted(data) }
613+ emit(DownloadEvent{
614+ file: name
615+ downloaded: c.total
616+ total: c.total
617+ done: true
618+ result: int(c.result)
619+ })
620+ }
621+ else {}
622+ }
623+}
624+
625+fn progress_verb(kind alpm.Progress) string {
626+ return match kind {
627+ .add_start { 'installing' }
628+ .upgrade_start { 'upgrading' }
629+ .downgrade_start { 'downgrading' }
630+ .reinstall_start { 'reinstalling' }
631+ .remove_start { 'removing' }
632+ .conflicts_start { 'checking for file conflicts' }
633+ .diskspace_start { 'checking available disk space' }
634+ .integrity_start { 'checking package integrity' }
635+ .load_start { 'loading package files' }
636+ .keyring_start { 'checking keys in keyring' }
637+ }
638+}
639+
640+fn cb_progress(ctx voidptr, kind alpm.Progress, pkgname &u8, percent i32, howmany uint, current uint) {
641+ mut ui := &TransUI(ctx)
642+ verb := progress_verb(kind)
643+ name := safe_vstring(pkgname)
644+ // pacman draws one bar per package for the package phases (the text is
645+ // '(current/howmany) verb name' and the percent restarts for each
646+ // package), and a single bar per whole-transaction check phase
647+ // (conflicts, diskspace, integrity, load, keyring). libalpm also sends
648+ // the final 100% event with a different `current`, so the phase bars
649+ // must not be keyed on it.
650+ pkg_wise := match kind {
651+ .add_start, .upgrade_start, .downgrade_start, .reinstall_start, .remove_start {
652+ true
653+ }
654+ else {
655+ false
656+ }
657+ }
658+ if ipc_on() {
659+ ev := ProgressEvent{
660+ op: verb
661+ pkg: if pkg_wise { name } else { '' }
662+ percent: int(percent)
663+ current: int(current)
664+ total: int(howmany)
665+ }
666+ // plast guards the repeats; the shared state is touched holding the
667+ // ui's mutex, and the event goes out with the lock gone
668+ ui.mu.lock()
669+ dup := ev == ui.plast
670+ if !dup {
671+ ui.plast = ev
672+ }
673+ ui.mu.unlock()
674+ if !dup {
675+ emit(ev)
676+ }
677+ return
678+ }
679+ // the key pairs the phase with the package the progress belongs to: the
680+ // bar restarts when either changes. 1000003 is prime; a collision would
681+ // need a transaction packaging over a million files in one phase
682+ pkey := if pkg_wise { int(kind) * 1000003 + int(current) } else { int(kind) }
683+ text := if !pkg_wise || name == '' {
684+ '${verb} '
685+ } else {
686+ '(${int(current)}/${int(howmany)}) ${verb} ${name} '
687+ }
688+ ui.mu.lock()
689+ defer { ui.mu.unlock() }
690+ if ui.pbar == unsafe { nil } || ui.pkey != pkey {
691+ ui.pkey = pkey
692+ ui.pbar = ui.group_locked().add_bar(100, bar_opts(text: text))
693+ ui.group_locked().start()
694+ }
695+ ui.pbar.set_text(text)
696+ ui.pbar.set(i64(percent))
697+}
698+
699+// cb_question asks libalpm's questions the way pacman's frontend does, with
700+// pacman's defaults: yes to installing an ignored package, replacing a
701+// package, deleting a corrupted package file and importing a missing key; no
702+// to removing a conflicting package and to skipping packages whose
703+// dependencies cannot be resolved; the first of several providers. libalpm
704+// presets every answer to 0 before it asks, so a question left unanswered is
705+// a no, which is not pacman's default for half of them. the live display is
706+// paused first so it cannot draw over the listings, and every question goes
707+// through the ui's prompter, whose --noconfirm prints each one and takes its
708+// default. all of it follows pacman's cb_question in src/pacman/callback.c
709+fn cb_question(ctx voidptr, q &alpm.Question) {
710+ mut ui := &TransUI(ctx)
711+ kind := unsafe { q.type_ }
712+ // --print lists the transaction and asks nothing: an ignored package and
713+ // a replacement stay in the list, every other question is a no, and a
714+ // provider is the first. install's own dependency walks answer the same
715+ if ui.print_only || ui.walking {
716+ set_answer(q, flag_answer(kind in [.install_ignorepkg, .replace_pkg]))
717+ return
718+ }
719+ ui.pause()
720+ answer := match kind {
721+ .install_ignorepkg {
722+ pkg := unsafe { q.install_ignorepkg.pkg }
723+ // a download installs nothing, so the ignored package is fetched
724+ if ui.download_only {
725+ i32(1)
726+ } else {
727+ flag_answer(ui.yesno('${pkg.get_name()} is ignored. install it anyway?'))
728+ }
729+ }
730+ .replace_pkg {
731+ r := unsafe { q.replace }
732+ old := r.oldpkg.get_name()
733+ flag_answer(ui.yesno('replace ${old} with ${r.newdb.get_name()}/${r.newpkg.get_name()}?'))
734+ }
735+ .conflict_pkg {
736+ conflict := unsafe { q.conflict.conflict }
737+ kept := conflict.package1.get_name()
738+ removed := conflict.package2.get_name()
739+ flag_answer(ui.noyes('${kept} conflicts with ${removed}. remove ${removed}?'))
740+ }
741+ .corrupted_pkg {
742+ c := unsafe { q.corrupted }
743+ path := safe_vstring(c.filepath)
744+ flag_answer(ui.yesno('${path} is corrupted (${c.reason.strerror()}). delete it?'))
745+ }
746+ .remove_pkgs {
747+ // a sysupgrade whose packages have unresolvable dependencies:
748+ // skipping them lets the rest of the upgrade go on
749+ mut list := unsafe { q.remove_pkgs.packages }
750+ pkgs := list.pkgs()
751+ noun := if pkgs.len == 1 { 'package' } else { 'packages' }
752+ ui.show_packages('${pkgs.len} ${noun} cannot be upgraded, their dependencies cannot be resolved:',
753+ pkgs)
754+ flag_answer(ui.noyes('skip them for this upgrade?'))
755+ }
756+ .select_provider {
757+ sp := unsafe { q.select_provider }
758+ mut list := sp.providers
759+ providers := list.pkgs()
760+ title := '${providers.len} providers for ${sp.depend.compute_string()}:'
761+ // a frontend gets them as the choices; the terminal lists them as
762+ // numbered rows first, and those are built only for it
763+ choices := providers.map(provider_choice(it))
764+ if !ipc_on() {
765+ println(heading(title))
766+ println(table_text(provider_rows(providers), ' ', ' '))
767+ }
768+ i32(ui.choose(if ipc_on() { title.trim_right(':') } else { 'which one?' }, choices))
769+ }
770+ .import_key {
771+ k := unsafe { q.import_key }
772+ fingerprint := safe_vstring(k.fingerprint)
773+ // the uid is unknown for a db signature
774+ uid := safe_vstring(k.uid)
775+ key := if uid == '' { fingerprint } else { '${fingerprint}, "${uid}"' }
776+ flag_answer(ui.yesno('import pgp key ${key}?'))
777+ }
778+ }
779+ set_answer(q, answer)
780+}
781+
782+// provider_choice is a provider as a frontend's choice: repo/name version
783+fn provider_choice(pkg &alpm.Package) string {
784+ repo := if db := pkg.get_db() { db.get_name() + '/' } else { '' }
785+ return '${repo}${pkg.get_name()} ${pkg.get_version()}'
786+}
787+
788+// provider_rows are the providers numbered for the terminal's listing, the
789+// number the choose question asks for
790+fn provider_rows(providers []&alpm.Package) []Row {
791+ mut rows := []Row{}
792+ for i, pkg in providers {
793+ styled := if db := pkg.get_db() { source_style(db.get_name()) + '/' } else { '' }
794+ rows << row('${i + 1})', styled + name_style(pkg.get_name()), version_style(pkg.get_version()))
795+ }
796+ return rows
797+}
798+
799+// alpm_log_line is libalpm's log callback, its V half: alpm_log.h formats
800+// each error and warning libalpm says, and it is said to the user as
801+// pacman's cb_log says it. vpac's own dependency walks (ui.walking) look
802+// things up the transaction's prepare looks up again; what they would say
803+// is said then, once
804+@[export: 'vpac_log_line']
805+fn alpm_log_line(ctx voidptr, level int, text &char) {
806+ if ctx == unsafe { nil } || text == unsafe { nil } {
807+ return
808+ }
809+ mut ui := unsafe { &TransUI(ctx) }
810+ if ui.walking {
811+ return
812+ }
813+ msg := unsafe { cstring_to_vstring(text) }.trim_space()
814+ if msg == '' {
815+ return
816+ }
817+ ui.alpm_said(level == alpm_log_error, msg)
818+}
819+
820+// alpm_said is a line libalpm logged: printed above any live bars (which
821+// hold it while they draw, as pacman buffers during progress), or a message
822+// event a frontend reads as a warning, an error flagged as one
823+fn (mut ui TransUI) alpm_said(is_error bool, text string) {
824+ if ipc_on() {
825+ emit(MessageEvent{
826+ text: text
827+ warning: true
828+ error: is_error
829+ })
830+ return
831+ }
832+ line := if is_error { error_text(text) } else { warning(text) }
833+ ui.mu.lock()
834+ defer { ui.mu.unlock() }
835+ if ui.mb != unsafe { nil } {
836+ ui.mb.println(line)
837+ } else {
838+ eprintln(line)
839+ }
840+}
841+
842+// set_answer writes a question's answer. every question struct keeps its
843+// answer right after the type, which is what libalpm's alpm_question_any_t
844+// exposes
845+fn set_answer(q &alpm.Question, answer i32) {
846+ unsafe {
847+ mut any := &alpm.QuestionAny(q)
848+ any.answer = answer
849+ }
850+}
851+
852+fn flag_answer(yes bool) i32 {
853+ return if yes { 1 } else { 0 }
854+}
855+
856+// init_handle initializes alpm and attaches the progress display callbacks
857+// and the configured parallel download count
858+fn init_handle(ui &TransUI) !&alpm.Handle {
859+ handle := alpm.initialize(root_path, db_path) or {
860+ return error('failed to initialize alpm')
861+ }
862+ handle.option_set_dlcb(cb_download, voidptr(ui))!
863+ handle.option_set_progresscb(cb_progress, voidptr(ui))!
864+ handle.option_set_questioncb(cb_question, voidptr(ui))!
865+ // libalpm's errors and warnings, which it says through this alone
866+ if C.vpac_set_alpm_log(handle, voidptr(ui)) != 0 {
867+ return error('could not set the log callback: ${handle.error().msg()}')
868+ }
869+ // the freshly calloc'd handle verifies nothing: pacman defaults to
870+ // checking signature levels, so the configured level is made the
871+ // handle's default for every db registered later, and for local and
872+ // remote files the transaction loads (libalpm tells the two apart as
873+ // pacman's SigLevel does; RemoteFileSigLevel follows SigLevel when it
874+ // is not named). a file is checked at its load only, at the level of its
875+ // origin (load_file_target); the remote level also decides whether a
876+ // url's .sig is fetched, and the url install warns by it
877+ handle.option_set_default_siglevel(cfg_siglevel)!
878+ handle.option_set_local_file_siglevel(cfg_siglevel)!
879+ handle.option_set_remote_file_siglevel(cfg_siglevel)!
880+ // pacman's frontend sets these from the config; without a cache dir
881+ // libalpm falls back to /tmp for downloads
882+ for dir in cfg_cachedirs {
883+ handle.option_add_cachedir(dir)!
884+ }
885+ // pacman's Architecture: without one libalpm's check_arch passes every
886+ // package, whatever it was built for
887+ handle.option_add_architecture(arch)!
888+ // libalpm's own hook dir (under the root) is on the handle already;
889+ // these are the config's, pacman's HookDir
890+ for dir in cfg_hookdirs {
891+ handle.option_add_hookdir(dir)!
892+ }
893+ if cfg_logfile != '' {
894+ handle.option_set_logfile(cfg_logfile)!
895+ }
896+ if cfg_syslog {
897+ handle.option_set_usesyslog(1)!
898+ }
899+ if cfg_gpgdir != '' {
900+ handle.option_set_gpgdir(cfg_gpgdir)!
901+ }
902+ // the ignored packages are libalpm's to skip on upgrades, with a question
903+ // for the user at the start of one
904+ for name in cfg_ignore {
905+ handle.option_add_ignore_pkg(name)!
906+ }
907+ for group in cfg_ignore_groups {
908+ handle.option_add_ignore_group(group)!
909+ }
910+ // pacman.conf's NoUpgrade and NoExtract: globs of files an upgrade keeps
911+ // (writing .pacnew beside them) and files an install never writes
912+ for glob in cfg_noupgrade {
913+ handle.option_add_noupgrade(glob)!
914+ }
915+ for glob in cfg_noextract {
916+ handle.option_add_no_extract(glob)!
917+ }
918+ if cfg_disable_timeout {
919+ handle.option_set_disable_dl_timeout(1)!
920+ }
921+ // pacman's DownloadUser: downloads run as this user, sandboxed. an empty
922+ // one is pacman without DownloadUser, downloads as root, unsandboxed
923+ if download_user != '' {
924+ handle.option_set_sandboxuser(download_user) or {
925+ return error('problem setting the download user "${download_user}" (user does not exist)')
926+ }
927+ }
928+ // pacman's DisableSandboxFilesystem and DisableSandboxSyscalls: the
929+ // downloader and the extraction run without either part of libalpm's
930+ // sandbox. the installed libalpm has these two, not a whole-sandbox switch
931+ if cfg_disable_sandbox {
932+ handle.option_set_disable_sandbox_filesystem(1)!
933+ handle.option_set_disable_sandbox_syscalls(1)!
934+ }
935+ handle.option_set_parallel_downloads(u32(parallel_downloads))!
936+ return handle
937+}
@@ -0,0 +1,120 @@
1+module main
2+
3+import alpm
4+import json2
5+import os
6+
7+fn test_restart_download_bar() {
8+ mut ui := new_trans_ui()
9+ defer { ui.stop() }
10+ mut bar := ui.download_bar('a.pkg', 100, '', true)
11+ bar.set(60)
12+ assert bar.value() == 60
13+ // libalpm starts the file over from the next mirror: so does the bar
14+ ui.restart_download_bar('a.pkg')
15+ assert bar.value() == 0
16+ // a file with no bar drawn yet has nothing to restart, and gets no bar
17+ ui.restart_download_bar('b.pkg')
18+ assert 'b.pkg' !in ui.dbars
19+}
20+
21+fn test_download_retry_through_the_callback() {
22+ // the callback libalpm calls: a retry that starts over resets the bar,
23+ // one that resumes leaves it where it was
24+ mut ui := new_trans_ui()
25+ defer { ui.stop() }
26+ mut p := alpm.DownloadEventProgress{
27+ downloaded: 40
28+ total: 100
29+ }
30+ cb_download(voidptr(ui), c'a.pkg', .progress, voidptr(&p))
31+ mut bar := ui.dbars['a.pkg'] or { panic('no bar for a.pkg') }
32+ assert bar.value() == 40
33+ mut resume := alpm.DownloadEventRetry{
34+ resume: 1
35+ }
36+ cb_download(voidptr(ui), c'a.pkg', .retry, voidptr(&resume))
37+ assert bar.value() == 40
38+ mut over := alpm.DownloadEventRetry{
39+ resume: 0
40+ }
41+ cb_download(voidptr(ui), c'a.pkg', .retry, voidptr(&over))
42+ assert bar.value() == 0
43+}
44+
45+fn test_stop_twice_is_one_stop() {
46+ // rank stops the display before it prints and again in its defer: the
47+ // second stop finds nothing left to do
48+ mut ui := new_trans_ui()
49+ mut m := ui.meter(3, 'probing')
50+ m.start()
51+ m.add(3)
52+ ui.stop()
53+ ui.stop()
54+ // and a ui that never drew stops just as well
55+ mut quiet := new_trans_ui()
56+ quiet.stop()
57+ quiet.stop()
58+}
59+
60+fn test_stop_spinner_twice_is_one_finish() {
61+ // a mode stops its spinner before a prompt or a print, and its defer
62+ // stops it again on every way out
63+ mut ui := new_trans_ui()
64+ defer { ui.stop() }
65+ mut s := ui.spinner(text: 'working')
66+ s.start()
67+ stop_spinner(mut s)
68+ assert s.is_done()
69+ stop_spinner(mut s)
70+ assert s.is_done()
71+}
72+
73+fn test_phase_finishes_once_under_a_frontend() ! {
74+ // under --ui ipc a phase is events: the second finish sends no second
75+ // done, and a phase that never started sends nothing at all
76+ path := os.join_path(os.vtmp_dir(), 'vpac_test_phase_${os.getpid()}')
77+ mut f := os.create(path)!
78+ defer { os.rm(path) or {} }
79+ saved_kind, saved_fd := ui_kind, ipc_fd
80+ ui_kind, ipc_fd = 'ipc', f.fd
81+ mut ui := new_trans_ui()
82+ mut s := ui.spinner(text: 'working')
83+ s.start()
84+ stop_spinner(mut s)
85+ stop_spinner(mut s)
86+ mut never := ui.spinner(text: 'skipped')
87+ stop_spinner(mut never)
88+ ui.stop()
89+ ui_kind, ipc_fd = saved_kind, saved_fd
90+ f.close()
91+ states := os.read_lines(path)!.map(json2.decode[json2.Any](it)!.as_map()['state']!.str())
92+ assert states == ['start', 'done']
93+}
94+
95+fn test_alpm_log_line() ! {
96+ path := os.join_path(os.vtmp_dir(), 'vpac_test_alpmlog_${os.getpid()}')
97+ mut f := os.create(path)!
98+ defer { os.rm(path) or {} }
99+ saved_kind, saved_fd := ui_kind, ipc_fd
100+ ui_kind, ipc_fd = 'ipc', f.fd
101+ mut ui := new_trans_ui()
102+ // vpac's own walk looks up what the prepare looks up again: said once,
103+ // then, not during the walk
104+ ui.walking = true
105+ alpm_log_line(voidptr(ui), 2, c'during the walk\n')
106+ ui.walking = false
107+ // libalpm's lines end in a newline, which the event does not carry
108+ alpm_log_line(voidptr(ui), 2, c'a warning\n')
109+ alpm_log_line(voidptr(ui), alpm_log_error, c'an error\n')
110+ // nothing to say, or no ui to say it on: nothing
111+ alpm_log_line(voidptr(ui), 2, c' \n')
112+ alpm_log_line(unsafe { nil }, 2, c'no ui')
113+ ui_kind, ipc_fd = saved_kind, saved_fd
114+ f.close()
115+ events := os.read_lines(path)!.map(json2.decode[json2.Any](it)!.as_map())
116+ assert events.map(it['text']!.str()) == ['a warning', 'an error']
117+ assert events.all(it['warning']!.bool())
118+ assert 'error' !in events[0]
119+ assert events[1]['error']!.bool()
120+}
@@ -0,0 +1,106 @@
1+module main
2+
3+fn upgrade(config ConfigUpgrade) ! {
4+ // a --print preview asks nothing and takes no lock, as pacman's
5+ mut ui := new_trans_ui(noconfirm: config.noconfirm || config.print_only)
6+ ui.print_only = config.print_only
7+ if !config.print_only {
8+ check_ask_db_lock(mut ui)
9+ }
10+
11+ if config.disable_timeout {
12+ cfg_disable_timeout = true
13+ }
14+ mut handle := init_handle(ui)!
15+ defer { handle.release() or { went_on('release the alpm handle', err) } }
16+ defer { ui.stop() }
17+ defer { trans_cleanup(handle) }
18+ trans_options(config).apply(handle)!
19+
20+ mut s := ui.spinner(text: 'getting dbs and updating em')
21+ s.start()
22+ defer { stop_spinner(mut s) }
23+
24+ init_repos(mut handle)!
25+ if config.sync_dbs {
26+ update_repos(mut handle, false)!
27+ } else {
28+ check_sync_fresh(mut ui, mut handle)!
29+ }
30+
31+ // a fresh one shows in either case: the set_text would land on the old
32+ // spinner's frame when the prompt above paused it, and here the old one
33+ // is finished with its work anyway
34+ stop_spinner(mut s)
35+ mut look := ui.spinner(text: 'looking for upgrades')
36+ look.start()
37+ defer { stop_spinner(mut look) }
38+ mut flags := dep_check_flag(config.nodeps, config.nodeps_level) | print_flags(config.print_only)
39+ if config.download_only {
40+ flags |= .download_only
41+ }
42+ if config.dbonly {
43+ flags |= .db_only
44+ }
45+ trans_begin(handle, flags)!
46+ // pacman's -Suu: a local package newer than the sync one goes down to it
47+ handle.sync_sysupgrade(config.downgrade || config.sysupgrade_level >= 2)!
48+
49+ trans_prepare_checked(handle)!
50+
51+ targets := handle.trans_get_add().pkgs()
52+
53+ end_frame(mut ui, mut look)
54+
55+ if targets.len == 0 {
56+ // --print's output is the list alone
57+ if !config.print_only {
58+ report('nothing to upgrade.')
59+ }
60+ return
61+ }
62+
63+ // --print stops here: the upgrade is listed with the archive names, as
64+ // install's --print lists a transaction, and nothing is downloaded
65+ if config.print_only {
66+ if ipc_on() {
67+ mut preview := trans_listing(handle, targets, .upgrade)
68+ preview.preview = true
69+ emit(preview)
70+ return
71+ }
72+ for pkg in targets {
73+ file := pkg.get_filename()
74+ println(if file == '' { pkg.get_name() } else { file })
75+ }
76+ return
77+ }
78+
79+ // what the upgrade removes on the way — a replaced or conflicting
80+ // package — is listed before the question, as install lists its own
81+ removals := handle.trans_get_remove().pkgs()
82+ if removals.len > 0 {
83+ ui.show_packages('${removals.len} packages to remove:', removals)
84+ }
85+ if !trans_confirm(mut ui, handle, targets, .upgrade) {
86+ return
87+ }
88+ names := targets.map(it.get_name())
89+
90+ mut s2 := ui.spinner(
91+ text: if config.download_only { 'downloading the upgrades' } else { 'upgrading system' }
92+ )
93+ s2.start()
94+ defer { stop_spinner(mut s2) }
95+ trans_commit(handle)!
96+ stop_spinner(mut s2)
97+ // a frontend learns what changed as from every transaction: a done event
98+ if ipc_on() {
99+ emit(DoneEvent{
100+ action: if config.download_only { 'downloaded' } else { 'upgraded' }
101+ packages: names
102+ })
103+ return
104+ }
105+ ui.say(if config.download_only { 'upgrades downloaded' } else { 'system upgraded' })
106+}
@@ -0,0 +1,17 @@
1+module main
2+
3+import alpm
4+
5+// prepare_error explains a failed transaction when the upgrade of outdated
6+// dependencies was switched off. a dependency too old for a target is not
7+// the cause then: libalpm's prepare pulls the newer one in by itself. what
8+// fails is the other direction — an installed package that needs the very
9+// version this transaction replaces — which the walk (broken_dependents)
10+// would have upgraded along. the hint goes on a line of its own, below the
11+// broken dependencies prepare listed
12+fn prepare_error(handle &alpm.Handle, msg string, no_upgrade_deps bool) string {
13+ if no_upgrade_deps && handle.errno() == .unsatisfied_deps {
14+ return '${msg}\nwithout --no-upgrade-deps, the installed packages this breaks are upgraded along with it when the repos have a version that fits'
15+ }
16+ return msg
17+}
@@ -0,0 +1,93 @@
1+module main
2+
3+import alpm
4+
5+#include <stdlib.h>
6+
7+// is_url reports whether an install target is a URL rather than a name or
8+// path. like pacman, anything with a scheme is one: libalpm's fetcher, curl,
9+// knows which schemes it can fetch (file://, ftps://, ...). the scheme is
10+// spelled the RFC writes it — a letter, then letters, digits, '.', '+', '-',
11+// closed by '://' — so a path with a stray '://', which is a legal file
12+// name, keeps being a path
13+fn is_url(target string) bool {
14+ n := target.index('://') or { return false }
15+ scheme := target[..n]
16+ // a scheme opens with a letter, whatever follows
17+ if scheme.len < 1 || !(scheme[0] >= `a` && scheme[0] <= `z`) && !(scheme[0] >= `A` && scheme[0] <= `Z`) {
18+ return false
19+ }
20+ for c in scheme[1..] {
21+ match c {
22+ `a`...`z`, `A`...`Z`, `0`...`9`, `.`, `+`, `-` {
23+ continue
24+ }
25+ else {
26+ return false
27+ }
28+ }
29+ }
30+ return true
31+}
32+
33+// fetch_url downloads a package from a URL into the cache with libalpm, so the
34+// download user and the progress bars are the same as for repo packages
35+fn fetch_url(handle &alpm.Handle, url string) !string {
36+ // libalpm appends to the head of the list, so it needs the address of the head
37+ mut urls := &alpm.List(unsafe { nil })
38+ url_head := &urls
39+ url_head.append_strdup(url)
40+ defer {
41+ // the strdup'd urls are ours: inner first, then the list
42+ urls.free_inner(fn (p voidptr) {
43+ unsafe { C.free(p) }
44+ })
45+ urls.free()
46+ }
47+ mut fetched := handle.fetch_pkgurl(urls)!
48+ defer {
49+ // libalpm strdup'd the fetched paths: them and their list are ours
50+ // to free the same way
51+ fetched.free_inner(fn (p voidptr) {
52+ unsafe { C.free(p) }
53+ })
54+ fetched.free()
55+ }
56+ // strs() wraps the C strings without copying them (vstring), and the
57+ // defer above frees them: the path leaves as a copy, or the install
58+ // would load whatever libalpm puts in that memory next
59+ paths := fetched.strs()
60+ if paths.len == 0 {
61+ return error('nothing was downloaded from ${url}')
62+ }
63+ return paths[0].clone()
64+}
65+
66+// url_trust_warning is what a url install is warned of, by the remote file
67+// signature level its archive is loaded at: libalpm fetches the .sig beside
68+// the url when the level checks packages, and the load verifies it. none
69+// when the level requires a signature, which leaves nothing to warn of
70+fn url_trust_warning(target string, level alpm.SigLevel) ?string {
71+ if !level.has(.package) {
72+ return '${target}: package signatures are not checked'
73+ }
74+ if level.has(.package_optional) {
75+ return '${target}: the signature is checked only if the server offers one'
76+ }
77+ return none
78+}
79+
80+// fetch_target_url downloads a package archive named by a URL through the
81+// install's own handle: the download draws on the install's display, and
82+// whatever libalpm asks on the way goes through the install's prompter. the
83+// warning before it says what the remote file signature level will check.
84+// it returns the cached file, installed then with the other targets
85+fn fetch_target_url(mut ui TransUI, handle &alpm.Handle, target string) !string {
86+ level := handle.option_get_remote_file_siglevel() or {
87+ return error('could not read the remote file signature level')
88+ }
89+ if note := url_trust_warning(target, level) {
90+ ui.warn(note)
91+ }
92+ return fetch_url(handle, target)!
93+}
@@ -0,0 +1,44 @@
1+module main
2+
3+import alpm
4+
5+fn test_is_url() {
6+ for url in ['https://example.org/foo-1-1-any.pkg.tar.zst', 'http://x/y', 'ftp://x/y',
7+ 'file:///srv/pkgs/foo-1-1-any.pkg.tar.zst', 'ftps://x/y'] {
8+ assert is_url(url), url
9+ }
10+ for target in ['zsh', 'extra/zsh', './foo-1-1-any.pkg.tar.zst', '/tmp/foo.pkg.tar.zst', 'zsh>=5'] {
11+ assert !is_url(target), target
12+ }
13+ // the scheme is spelled as RFC 3986 says: a letter first, then letters,
14+ // digits and '.', '+' or '-', closed by '://'. a path with a stray '://'
15+ // in its name keeps being a path, and a text with '//' walk-in where a
16+ // scheme-opening should be keeps being one too
17+ assert is_url('a+b-c.d://host/x')
18+ // dots are legal letters of a scheme, so a dotted one is one ('file:',
19+ // 'ssh:' say it); a leading '-', an inner space or an opening digit do
20+ // not, and '://' without a scheme before it does not
21+ assert is_url('path.y.tar://')
22+ assert !is_url('-lead://host/x')
23+ assert !is_url('we ird://host/x')
24+ assert !is_url('://host/x')
25+ assert !is_url('9bad://host/x')
26+}
27+
28+fn test_url_trust_warning() {
29+ url := 'https://example.org/foo-1-1-any.pkg.tar.zst'
30+ // no package check: the warning says so
31+ none_level := url_trust_warning(url, alpm.SigLevel.database) or { '' }
32+ assert none_level.contains('not checked')
33+ assert none_level.starts_with(url)
34+ // optional: the .sig is read when the server offers one, not otherwise
35+ optional := url_trust_warning(url, alpm.SigLevel.package | .package_optional) or { '' }
36+ assert optional.contains('only if the server offers one')
37+ // required: the load refuses an unsigned package, nothing to warn of
38+ if note := url_trust_warning(url, alpm.SigLevel.package) {
39+ assert false, 'a required signature was warned of: ${note}'
40+ }
41+ if note := url_trust_warning(url, alpm.SigLevel.package | .database) {
42+ assert false, 'a required signature was warned of: ${note}'
43+ }
44+}
@@ -0,0 +1,201 @@
1+module main
2+
3+import alpm
4+import os
5+
6+// backups_of lists the backup entries of a package: the config files whose
7+// expected md5 the db records
8+fn backups_of(pkg &alpm.Package) []&alpm.Backup {
9+ mut out := []&alpm.Backup{}
10+ mut node := pkg.get_backup()
11+ for node != unsafe { nil } {
12+ if b := node.get_backup() {
13+ out << b
14+ }
15+ node = node.next
16+ }
17+ return out
18+}
19+
20+// stat_denied: the stat failed not because the file is missing but because
21+// this run may not look at it. the errno is compared by the names errno.h
22+// gives it on this system, not by the strerror text, whose wording — and
23+// language — is whatever the system says, nor by a number posix never fixed
24+fn stat_denied(err IError) bool {
25+ return err.code() == C.EPERM || err.code() == C.EACCES
26+}
27+
28+// VerifyLine is one line of a check's report, the file check's and the full
29+// (mtree) check's alike. problem is whether it counts against the package; a
30+// note does not: a modified backup file, a file this user may not read. the
31+// lines are held until the spinner is gone, because an println during the
32+// spin would be drawn under the running frame
33+struct VerifyLine {
34+ problem bool
35+ text string
36+}
37+
38+// verify_levels are how deep the checks go: the db level, -D counted (--db
39+// one), and the file level, -k counted (--checksums one, --full two). there
40+// are two of each, as in pacman, where -kkk is -kk and -Dkkk is -Dkk: more
41+// letters are the deepest level, not a level of their own
42+fn verify_levels(c ConfigVerify) (int, int) {
43+ db := c.db_level + if c.db { 1 } else { 0 }
44+ file := c.checksums_level + (if c.checksums { 1 } else { 0 }) + (if c.full { 2 } else { 0 })
45+ return if db > 2 { 2 } else { db }, if file > 2 { 2 } else { file }
46+}
47+
48+// verify checks the files of installed packages the way pacman's -Qk does:
49+// every file in the db is on disk, of the type the db says, and with -k the
50+// backed up config files are not modified. it reports only the packages with
51+// problems, and returns how many there are: main exits 1 when any are
52+fn verify(config ConfigVerify) !int {
53+ mut ui := new_trans_ui()
54+ // the configured handle: -kk needs the NoExtract globs
55+ mut handle := init_handle(ui)!
56+ defer { handle.release() or { went_on('release the alpm handle', err) } }
57+ defer { ui.stop() }
58+
59+ mut pkgcache := local_pkgcache(handle)!
60+
61+ // -D and -DD check the databases, pacman's -Dk and -Dkk, and no files
62+ db_level, level := verify_levels(config)
63+ if db_level > 0 {
64+ // a db error is reported as a failed target, which main counts
65+ verify_db(mut handle, db_level)!
66+ return 0
67+ }
68+
69+ mut pkgs := pkgcache.pkgs()
70+ if config.query.len > 0 {
71+ // a target is a name, a versioned dependency or something provided,
72+ // as pacman's -Qk resolves it; one that names nothing installed is
73+ // reported and counted, and the rest are checked
74+ pkgs = []&alpm.Package{}
75+ for target in config.query {
76+ pkg := find_local_target(pkgcache, local_target_name(target), true) or {
77+ target_error('package "${target}" was not found')
78+ continue
79+ }
80+ add_pkg_once(mut pkgs, pkg)
81+ }
82+ if pkgs.len == 0 {
83+ return error('no one of the named packages is installed')
84+ }
85+ }
86+
87+ mut s := ui.spinner(text: 'checking packages')
88+ s.start()
89+ defer { stop_spinner(mut s) }
90+
91+ mut lines := []VerifyLine{}
92+ mut bad := 0
93+ for pkg in pkgs {
94+ // -kk: every file against the mtree, which covers the backup files too
95+ if level >= 2 {
96+ altered, found := verify_pkg_full(handle, pkg)
97+ lines << found
98+ if altered > 0 {
99+ bad++
100+ }
101+ continue
102+ }
103+ mut problems := 0
104+ // one name → expected md5 per package: the per-file check reads the
105+ // map instead of walking the backup list again for every file
106+ mut backups := map[string]string{}
107+ if level >= 1 {
108+ for b in backups_of(pkg) {
109+ backups[b.get_name()] = b.get_hash()
110+ }
111+ }
112+ for name in pkg.get_files().names() {
113+ path := '${root_path}${name}'
114+ // pacman's check_file_exists: lstat with the trailing slash
115+ // dropped (its llstat), so a link — broken or not — is there as
116+ // itself, and a directory the db lists that is now a link is
117+ // that link, not the directory it points at
118+ st := os.lstat(if name.ends_with('/') { path.trim_right('/') } else { path }) or {
119+ // a file NoExtract kept off the disk is not missing, and is not
120+ // said, as in pacman
121+ if handle.option_match_no_extract(name) {
122+ continue
123+ }
124+ // a stat denied by permissions is not the file missing, and it
125+ // would drown the run in noise; noted but not counted (upstream
126+ // pacman counts it). the errno comes along on the error, so
127+ // the reading does not lean on strerror's wording
128+ if stat_denied(err) {
129+ lines << VerifyLine{false, '${pkg.get_name()}: warning: ${path} (${err.msg()})'}
130+ } else {
131+ problems++
132+ lines << VerifyLine{true, '${pkg.get_name()}: missing ${path}'}
133+ }
134+ continue
135+ }
136+ // the db records directories with a trailing slash; anything else
137+ // on disk where it says one, or a directory where it says a file,
138+ // is pacman's file type mismatch. a link where the db says a file
139+ // is the file a package may well ship as a link
140+ kind := st.get_filetype()
141+ wants_dir := name.ends_with('/')
142+ if (kind == .directory) != wants_dir {
143+ problems++
144+ what := match kind {
145+ .directory { 'a directory' }
146+ .symbolic_link { 'a link' }
147+ else { 'a file' }
148+ }
149+ lines << VerifyLine{true, '${pkg.get_name()}: ${path} is ${what}, the db says ${if wants_dir {
150+ 'a directory'
151+ } else {
152+ 'a file'
153+ }}'}
154+ continue
155+ }
156+ // the checksums read regular files: a link's target is not the
157+ // package's file
158+ if kind == .symbolic_link {
159+ continue
160+ }
161+ if level >= 1 && !wants_dir {
162+ if hash := backups[name] {
163+ // a checksum that libalpm cannot calculate counts as a
164+ // problem, as pacman's "failed to calculate" does
165+ md5 := alpm.compute_md5sum(path) or {
166+ lines << VerifyLine{true, '${pkg.get_name()}: ${path} (failed to calculate MD5 checksum)'}
167+ problems++
168+ continue
169+ }
170+ if md5 != hash {
171+ problems++
172+ lines << VerifyLine{true, '${pkg.get_name()}: modified ${path}'}
173+ }
174+ }
175+ }
176+ }
177+ if problems > 0 {
178+ bad++
179+ }
180+ }
181+ end_frame(mut ui, mut s)
182+ if ipc_on() {
183+ emit(VerifyEvent{
184+ lines: lines
185+ bad: bad
186+ })
187+ return bad
188+ }
189+ // now that the frame is stopped, the report prints plainly, one line
190+ // beside the next
191+ for l in lines {
192+ println(l.text)
193+ }
194+ if bad == 0 {
195+ println('no problems found')
196+ return 0
197+ }
198+ noun := if bad == 1 { '1 package with problems' } else { '${bad} packages with problems' }
199+ println(noun)
200+ return bad
201+}
@@ -0,0 +1,290 @@
1+module main
2+
3+import alpm
4+import crypto.sha256
5+import os
6+
7+#flag -larchive
8+#include <archive.h>
9+#include <archive_entry.h>
10+
11+// libalpm reads a package's mtree for us; these are the libarchive accessors
12+// pacman's -Qkk reads each entry with
13+fn C.archive_entry_pathname(entry &C.Archive_entry) &char
14+fn C.archive_entry_filetype(entry &C.Archive_entry) u32
15+fn C.archive_entry_mode(entry &C.Archive_entry) u32
16+fn C.archive_entry_uid(entry &C.Archive_entry) i64
17+fn C.archive_entry_gid(entry &C.Archive_entry) i64
18+fn C.archive_entry_mtime(entry &C.Archive_entry) i64
19+fn C.archive_entry_size(entry &C.Archive_entry) i64
20+fn C.archive_entry_symlink(entry &C.Archive_entry) &char
21+fn C.archive_entry_digest(entry &C.Archive_entry, kind int) &u8
22+
23+// the binding's mtree_next hands the entry to its own parameter, so the
24+// caller never sees it: libalpm is called directly
25+fn C.alpm_pkg_mtree_next(pkg &alpm.Package, archive &C.Archive, entry &&C.Archive_entry) int
26+
27+fn C.archive_error_string(archive &C.Archive) &char
28+
29+const ae_ifmt = u32(0o170000)
30+const ae_ifreg = u32(0o100000)
31+const ae_ifdir = u32(0o040000)
32+const ae_iflnk = u32(0o120000)
33+// the mode bits pacman compares: permissions, setuid, setgid and sticky
34+const mode_bits = u32(0o7777)
35+
36+// MtreeEntry is what a package's mtree records of one of its files
37+struct MtreeEntry {
38+ path string // as in the mtree, './' stripped
39+ kind u32 // ae_ifreg, ae_ifdir or ae_iflnk
40+ mode u32
41+ uid i64
42+ gid i64
43+ mtime i64
44+ size i64
45+ symlink string
46+ sha256 string // hex, empty when the mtree has none
47+}
48+
49+// mtree_entries reads a package's mtree. an error is a broken one: libalpm's
50+// mtree reader hands an entry over at 0, answers 1 at the mtree's end and
51+// anything else for entries beyond reading, so the loop tells the end and a
52+// read failure apart — pacman's own loop stops at anything that is not 0,
53+// which reports a partial mtree as a complete one. the second value is
54+// whether the package carries an mtree file at all (packages built before
55+// mtrees existed do not; that is not an error)
56+fn mtree_entries(pkg &alpm.Package) !([]MtreeEntry, bool) {
57+ archive := pkg.mtree_open()
58+ if archive == unsafe { nil } {
59+ // libalpm answers nil both for no mtree file and for one libarchive
60+ // cannot open; it tells them apart by the file being there, and so
61+ // does this: a corrupt mtree is the package's problem, not a package
62+ // built before mtrees (pacman's check.c leaves this as a TODO)
63+ handle := pkg.get_handle()
64+ // the reason is read first: libalpm's package getters clear it
65+ reason := handle.error().msg()
66+ mtfile := os.join_path(handle.option_get_dbpath(), 'local', '${pkg.get_name()}-${pkg.get_version()}',
67+ 'mtree')
68+ if os.exists(mtfile) {
69+ return error('the mtree file cannot be read (${reason}): ${mtfile}')
70+ }
71+ return []MtreeEntry{}, false
72+ }
73+ mut out := []MtreeEntry{}
74+ mut entry := &C.Archive_entry(unsafe { nil })
75+ for {
76+ ret := C.alpm_pkg_mtree_next(pkg, archive, &entry)
77+ if ret != 0 {
78+ if ret != 1 {
79+ // the read's reason is libarchive's, kept on the archive:
80+ // libalpm passes the status through and sets no error of its
81+ // own. it is taken before the close frees the archive, and a
82+ // close that fails too rides along rather than going unsaid
83+ read_err := error('reading the mtree failed: ${mtree_reason(pkg, archive)}')
84+ pkg.mtree_close(archive) or {
85+ return error('${read_err.msg()} (closing it failed too: ${err.msg()})')
86+ }
87+ return read_err
88+ }
89+ break
90+ }
91+ mut path := unsafe { cstring_to_vstring(C.archive_entry_pathname(entry)) }
92+ if path.starts_with('./') {
93+ path = path[2..]
94+ }
95+ link := C.archive_entry_symlink(entry)
96+ out << MtreeEntry{
97+ path: path
98+ kind: C.archive_entry_filetype(entry)
99+ mode: C.archive_entry_mode(entry) & mode_bits
100+ uid: C.archive_entry_uid(entry)
101+ gid: C.archive_entry_gid(entry)
102+ mtime: C.archive_entry_mtime(entry)
103+ size: C.archive_entry_size(entry)
104+ symlink: if link == unsafe { nil } { '' } else { unsafe { cstring_to_vstring(link) } }
105+ sha256: digest_hex(C.archive_entry_digest(entry, C.ARCHIVE_ENTRY_DIGEST_SHA256))
106+ }
107+ }
108+ pkg.mtree_close(archive) or {
109+ // the close is the read's last word; the entries fail with it
110+ return error('opening the mtree of ${pkg.get_name()} failed to close it: ${err.msg()}')
111+ }
112+ return out, true
113+}
114+
115+// mtree_reason is why an mtree read stopped: libarchive's message on the
116+// archive, or libalpm's error when libarchive kept none
117+fn mtree_reason(pkg &alpm.Package, archive &C.Archive) string {
118+ msg := C.archive_error_string(archive)
119+ if msg != unsafe { nil } {
120+ text := unsafe { cstring_to_vstring(msg) }
121+ if text != '' {
122+ return text
123+ }
124+ }
125+ return pkg.get_handle().error().msg()
126+}
127+
128+// digest_hex is a 32 byte sha256 digest as hex, empty when it is all zero:
129+// libarchive leaves it so when the mtree records none
130+fn digest_hex(d &u8) string {
131+ if d == unsafe { nil } {
132+ return ''
133+ }
134+ bytes := unsafe { d.vbytes(32) }.clone()
135+ return if bytes.all(it == 0) { '' } else { bytes.hex() }
136+}
137+
138+// file_sha256 hashes a file in chunks, so a large one is never read whole.
139+// the read names end of input as its own error (os.Eof); a failure to read
140+// anything else is the caller's news — a digest of the part that came out
141+// would pass itself off as the whole file's
142+fn file_sha256(path string) !string {
143+ mut f := os.open(path)!
144+ defer { f.close() }
145+ mut d := sha256.new()
146+ mut buf := []u8{len: 65536}
147+ for {
148+ n := f.read(mut buf) or {
149+ // end of input is a chunking loop's end, not a failure
150+ if err is os.Eof {
151+ break
152+ }
153+ return err
154+ }
155+ if n == 0 {
156+ break
157+ }
158+ d.write(buf[..n])!
159+ }
160+ return d.sum([]).hex()
161+}
162+
163+// check_file_full compares one file on disk with its mtree entry, the way
164+// pacman's -Qkk does: the type first, then owner, group and mode, the target
165+// of a link, and for anything that is not a directory the mtime, and for a
166+// regular file the size and the sha256. a backup file is expected to change
167+// in time, size and content, so those only make a note for it
168+fn check_file_full(path string, e MtreeEntry, backup bool) []VerifyLine {
169+ st := os.lstat(path) or {
170+ // a stat denied by permissions is not a missing file, as in the
171+ // fast check. the errno comes along on the error, so the reading
172+ // does not lean on strerror's wording
173+ if stat_denied(err) {
174+ return [VerifyLine{false, '${path} (${err.msg()})'}]
175+ }
176+ return [VerifyLine{true, '${path} (missing)'}]
177+ }
178+ kind := st.mode & ae_ifmt
179+ if kind != e.kind {
180+ return [VerifyLine{true, '${path} (file type mismatch)'}]
181+ }
182+ mut out := []VerifyLine{}
183+ if i64(st.uid) != e.uid {
184+ out << VerifyLine{true, '${path} (UID mismatch)'}
185+ }
186+ if i64(st.gid) != e.gid {
187+ out << VerifyLine{true, '${path} (GID mismatch)'}
188+ }
189+ if st.mode & mode_bits != e.mode {
190+ out << VerifyLine{true, '${path} (permissions mismatch)'}
191+ }
192+ if kind == ae_iflnk {
193+ // a link that cannot be read is its own finding, as pacman's
194+ // check_symlink says it, not a target that differs
195+ if target := os.readlink(path) {
196+ if target != e.symlink {
197+ out << VerifyLine{true, '${path} (symlink path mismatch)'}
198+ }
199+ } else {
200+ out << VerifyLine{true, '${path} (unable to read symlink contents: ${err.msg()})'}
201+ }
202+ }
203+ // a backup file's changes are the user's: they are noted, not counted
204+ note := fn [backup, path] (what string) VerifyLine {
205+ return if backup {
206+ VerifyLine{false, 'backup file ${path} (${what})'}
207+ } else {
208+ VerifyLine{true, '${path} (${what})'}
209+ }
210+ }
211+ if kind != ae_ifdir && st.mtime != e.mtime {
212+ out << note('modification time mismatch')
213+ }
214+ if kind == ae_ifreg {
215+ if i64(st.size) != e.size {
216+ out << note('size mismatch')
217+ }
218+ if e.sha256 == '' {
219+ out << VerifyLine{true, '${path} (SHA256 checksum information not available)'}
220+ } else if sum := file_sha256(path) {
221+ if sum != e.sha256 {
222+ out << note('SHA256 checksum mismatch')
223+ }
224+ } else {
225+ // unverified counts as altered, as pacman's "failed to calculate"
226+ // does: run as root to read the root-only files
227+ out << VerifyLine{true, '${path} (cannot read: ${err.msg()})'}
228+ }
229+ }
230+ return out
231+}
232+
233+// verify_pkg_full is pacman's -Qkk for one package: every entry of its
234+// mtree against the disk. the .INSTALL and .CHANGELOG entries are the db's
235+// own copies; the other dot entries describe the package, not its files.
236+// the report is held and handed back with the number of altered files: the
237+// caller prints it after its spinner stops, since an inline println would
238+// draw under the running frame
239+fn verify_pkg_full(handle &alpm.Handle, pkg &alpm.Package) (int, []VerifyLine) {
240+ name := pkg.get_name()
241+ mut lines := []VerifyLine{}
242+ // a broken mtree is that package's verdict; the check goes on
243+ entries, has_mtree := mtree_entries(pkg) or {
244+ lines << VerifyLine{true, '${name}: ${err.msg()}'}
245+ return 1, lines
246+ }
247+ if !has_mtree {
248+ lines << VerifyLine{false, '${name}: no mtree file'}
249+ return 0, lines
250+ }
251+ backups := backups_of(pkg).map(it.get_name())
252+ mut altered := 0
253+ for e in entries {
254+ path := if e.path.starts_with('.') {
255+ dbfile := match e.path {
256+ '.INSTALL' { 'install' }
257+ '.CHANGELOG' { 'changelog' }
258+ else { '' }
259+ }
260+ if dbfile == '' {
261+ continue
262+ }
263+ // the db the mtree was read from: the handle's, not the global
264+ os.join_path(handle.option_get_dbpath(), 'local', '${name}-${pkg.get_version()}',
265+ dbfile)
266+ } else {
267+ '${root_path}${e.path}'
268+ }
269+ if e.kind !in [ae_ifreg, ae_ifdir, ae_iflnk] {
270+ lines << VerifyLine{false, '${name}: warning: ${path} (file type not recognized)'}
271+ continue
272+ }
273+ // a file NoExtract kept off the disk is not missing
274+ if !os.exists(path) && !os.is_link(path) && handle.option_match_no_extract(e.path) {
275+ continue
276+ }
277+ findings := check_file_full(path, e, e.path in backups)
278+ for f in findings {
279+ lines << VerifyLine{f.problem, if f.problem {
280+ '${name}: ${f.text}'
281+ } else {
282+ '${name}: note: ${f.text}'
283+ }}
284+ }
285+ if findings.any(it.problem) {
286+ altered++
287+ }
288+ }
289+ return altered, lines
290+}
@@ -0,0 +1,211 @@
1+module main
2+
3+import alpm
4+import crypto.sha256
5+import encoding.base64
6+import os
7+
8+// a file on disk and the mtree entry that matches it exactly
9+fn full_fixture(dir string) !(string, MtreeEntry) {
10+ path := os.join_path(dir, 'f')
11+ os.write_file(path, 'hello\n')!
12+ os.chmod(path, 0o644)!
13+ os.utime(path, 1700000000, 1700000000)!
14+ st := os.lstat(path)!
15+ return path, MtreeEntry{
16+ path: 'f'
17+ kind: ae_ifreg
18+ mode: 0o644
19+ uid: i64(st.uid)
20+ gid: i64(st.gid)
21+ mtime: 1700000000
22+ size: 6
23+ sha256: sha256.hexhash('hello\n')
24+ }
25+}
26+
27+fn texts(findings []VerifyLine) []string {
28+ return findings.map(if it.problem {
29+ it.text.all_after('(')
30+ } else {
31+ 'note ${it.text.all_after('(')}'
32+ })
33+}
34+
35+fn test_check_file_full() ! {
36+ tmp := os.join_path(os.vtmp_dir(), 'vpac_test_verify_${os.getpid()}')
37+ os.mkdir_all(tmp)!
38+ defer { os.rmdir_all(tmp) or {} }
39+ path, e := full_fixture(tmp)!
40+
41+ assert check_file_full(path, e, false) == []
42+ assert texts(check_file_full(path, MtreeEntry{ ...e, size: 7 }, false)) == ['size mismatch)']
43+ assert texts(check_file_full(path, MtreeEntry{ ...e, sha256: '00'.repeat(32) }, false)) == [
44+ 'SHA256 checksum mismatch)',
45+ ]
46+ assert texts(check_file_full(path, MtreeEntry{ ...e, mtime: 1 }, false)) == [
47+ 'modification time mismatch)',
48+ ]
49+ assert texts(check_file_full(path, MtreeEntry{ ...e, mode: 0o600 }, false)) == [
50+ 'permissions mismatch)',
51+ ]
52+ assert texts(check_file_full(path, MtreeEntry{ ...e, uid: e.uid + 1 }, false)) == [
53+ 'UID mismatch)',
54+ ]
55+ assert texts(check_file_full(path, MtreeEntry{ ...e, sha256: '' }, false)) == [
56+ 'SHA256 checksum information not available)',
57+ ]
58+ // the wrong type stops the checks there
59+ assert texts(check_file_full(path, MtreeEntry{ ...e, kind: ae_ifdir, size: 0 }, false)) == [
60+ 'file type mismatch)',
61+ ]
62+ assert texts(check_file_full(os.join_path(tmp, 'gone'), e, false)) == ['missing)']
63+
64+ // a backup file may change in time, size and content: notes, no problem
65+ changed := MtreeEntry{
66+ ...e
67+ mtime: 1
68+ size: 99
69+ sha256: '00'.repeat(32)
70+ }
71+ findings := check_file_full(path, changed, true)
72+ assert !findings.any(it.problem)
73+ assert texts(findings) == ['note modification time mismatch)', 'note size mismatch)',
74+ 'note SHA256 checksum mismatch)']
75+ // but not in mode
76+ assert texts(check_file_full(path, MtreeEntry{ ...e, mode: 0o600 }, true)) == [
77+ 'permissions mismatch)',
78+ ]
79+}
80+
81+fn test_check_file_full_symlink() ! {
82+ tmp := os.join_path(os.vtmp_dir(), 'vpac_test_verify_link_${os.getpid()}')
83+ os.mkdir_all(tmp)!
84+ defer { os.rmdir_all(tmp) or {} }
85+ link := os.join_path(tmp, 'l')
86+ os.symlink('f', link)!
87+ st := os.lstat(link)!
88+ e := MtreeEntry{
89+ path: 'l'
90+ kind: ae_iflnk
91+ mode: st.mode & mode_bits
92+ uid: i64(st.uid)
93+ gid: i64(st.gid)
94+ mtime: st.mtime
95+ symlink: 'f'
96+ }
97+ // a link is checked as a link: its target need not exist
98+ assert check_file_full(link, e, false) == []
99+ assert texts(check_file_full(link, MtreeEntry{ ...e, symlink: 'g' }, false)) == [
100+ 'symlink path mismatch)',
101+ ]
102+}
103+
104+fn test_digest_hex() {
105+ zero := []u8{len: 32}
106+ assert digest_hex(zero.data) == ''
107+ mut d := []u8{len: 32}
108+ d[0] = 0xab
109+ d[31] = 0x01
110+ assert digest_hex(d.data) == 'ab' + '00'.repeat(30) + '01'
111+ assert digest_hex(unsafe { nil }) == ''
112+}
113+
114+fn test_file_sha256() ! {
115+ tmp := os.join_path(os.vtmp_dir(), 'vpac_test_sha_${os.getpid()}')
116+ os.mkdir_all(tmp)!
117+ defer { os.rmdir_all(tmp) or {} }
118+ // larger than one 64 KiB chunk
119+ data := 'abcdefgh'.repeat(20000)
120+ path := os.join_path(tmp, 'big')
121+ os.write_file(path, data)!
122+ assert file_sha256(path)! == sha256.hexhash(data)
123+ assert file_sha256(os.join_path(tmp, 'nope')) or { 'error' } == 'error'
124+}
125+
126+// a read that fails never comes back as the partial file's digest: a
127+// truncated hash would pass itself off as the whole file's
128+fn test_file_sha256_read_failure() ! {
129+ tmp := os.join_path(os.vtmp_dir(), 'vpac_test_sha_deny_${os.getpid()}')
130+ os.mkdir_all(tmp)!
131+ defer { os.rmdir_all(tmp) or {} }
132+ if sum := file_sha256(tmp) {
133+ assert false, 'a directory hashed as "${sum[0..8]}…"'
134+ } else {
135+ assert err.msg() != '', err.msg()
136+ }
137+}
138+
139+// mtree_pkg installs one package in a temp local db with the given gzipped
140+// mtree text, and returns the handle and the package libalpm loads for it
141+fn mtree_pkg(tmp string, name string, mtree []u8) !(&alpm.Handle, &alpm.Package) {
142+ entry := os.join_path(tmp, 'db', 'local', '${name}-1.0-1')
143+ os.mkdir_all(entry)!
144+ os.mkdir_all(os.join_path(tmp, 'root'))!
145+ os.write_file(os.join_path(tmp, 'db', 'local', 'ALPM_DB_VERSION'), '9\n')!
146+ os.write_file(os.join_path(entry, 'desc'), '%NAME%\n${name}\n\n%VERSION%\n1.0-1\n\n')!
147+ os.write_file(os.join_path(entry, 'files'), '%FILES%\n\n')!
148+ if mtree.len > 0 {
149+ os.write_file_array(os.join_path(entry, 'mtree'), mtree)!
150+ }
151+ handle := alpm.initialize(os.join_path(tmp, 'root') + '/', os.join_path(tmp, 'db') + '/')!
152+ pkg := handle.find_local_pkg(name) or { return error('${name} is not installed') }
153+ return handle, pkg
154+}
155+
156+// gzipped is text compressed the way package mtrees ship
157+fn gzipped(text string) ![]u8 {
158+ res := os.exec(['sh', '-c', 'printf %s "\$0" | gzip -9 | base64 -w0', text])
159+ if res.exit_code != 0 {
160+ return error('gzip failed: ${res.output}')
161+ }
162+ return base64.decode(res.output.trim_space())
163+}
164+
165+fn test_verify_pkg_full_broken_mtree() ! {
166+ tmp := os.join_path(os.vtmp_dir(), 'vpac_test_mtree_${os.getpid()}')
167+ os.rmdir_all(tmp) or {}
168+ defer { os.rmdir_all(tmp) or {} }
169+ whole := gzipped('#mtree\n/set type=file uid=0 gid=0 mode=644\n./usr time=1.0 type=dir\n')!
170+ // cut off inside the compressed stream: the read fails part way, and
171+ // that failure — libalpm's reason — is the package's verdict, not a
172+ // package without an mtree
173+ handle, pkg := mtree_pkg(tmp, 'broken', whole[..whole.len / 2])!
174+ defer { handle.release() or {} }
175+ altered, lines := verify_pkg_full(handle, pkg)
176+ assert altered == 1, lines.str()
177+ assert lines.len == 1
178+ assert lines[0].problem
179+ assert lines[0].text.starts_with('broken: the mtree file cannot be read (libarchive error): '), lines[0].text
180+ assert lines[0].text.ends_with('/local/broken-1.0-1/mtree'), lines[0].text
181+}
182+
183+fn test_verify_pkg_full_no_mtree() ! {
184+ tmp := os.join_path(os.vtmp_dir(), 'vpac_test_nomtree_${os.getpid()}')
185+ os.rmdir_all(tmp) or {}
186+ defer { os.rmdir_all(tmp) or {} }
187+ // a package built before mtrees existed: noted, not a problem
188+ handle, pkg := mtree_pkg(tmp, 'old', [])!
189+ defer { handle.release() or {} }
190+ altered, lines := verify_pkg_full(handle, pkg)
191+ assert altered == 0
192+ assert lines.map(it.text) == ['old: no mtree file']
193+ assert !lines[0].problem
194+}
195+
196+fn test_verify_pkg_full_mtree_read_failure() ! {
197+ tmp := os.join_path(os.vtmp_dir(), 'vpac_test_mtree_read_${os.getpid()}')
198+ os.rmdir_all(tmp) or {}
199+ defer { os.rmdir_all(tmp) or {} }
200+ // the mtree opens, and an entry of it is not one: the read stops part
201+ // way, and the package's verdict carries libarchive's own reason
202+ handle, pkg := mtree_pkg(tmp, 'midway', gzipped('#mtree\n./a type=bogus\n')!)!
203+ defer { handle.release() or {} }
204+ altered, lines := verify_pkg_full(handle, pkg)
205+ assert altered == 1, lines.str()
206+ assert lines.len == 1
207+ assert lines[0].problem
208+ assert lines[0].text.starts_with('midway: reading the mtree failed: '), lines[0].text
209+ reason := lines[0].text.all_after('failed: ')
210+ assert reason != '' && reason != 'unexpected error', lines[0].text
211+}
@@ -0,0 +1,45 @@
1+module main
2+
3+struct LevelCase {
4+ c ConfigVerify
5+ db int
6+ file int
7+}
8+
9+fn test_verify_levels() {
10+ for t in [
11+ LevelCase{ConfigVerify{}, 0, 0},
12+ LevelCase{ConfigVerify{
13+ checksums_level: 1
14+ }, 0, 1},
15+ LevelCase{ConfigVerify{
16+ checksums: true
17+ }, 0, 1},
18+ LevelCase{ConfigVerify{
19+ checksums_level: 2
20+ }, 0, 2},
21+ LevelCase{ConfigVerify{
22+ full: true
23+ }, 0, 2},
24+ // more letters are the deepest level, as pacman's -kkk is -kk
25+ LevelCase{ConfigVerify{
26+ checksums_level: 3
27+ }, 0, 2},
28+ LevelCase{ConfigVerify{
29+ checksums: true
30+ full: true
31+ }, 0, 2},
32+ LevelCase{ConfigVerify{
33+ db: true
34+ }, 1, 0},
35+ LevelCase{ConfigVerify{
36+ db_level: 2
37+ }, 2, 0},
38+ LevelCase{ConfigVerify{
39+ db_level: 4
40+ }, 2, 0},
41+ ] {
42+ db, file := verify_levels(t.c)
43+ assert db == t.db && file == t.file, '${t.c}'
44+ }
45+}
@@ -0,0 +1,8 @@
1+Module {
2+ name: 'vpac'
3+ description: 'an alpm frontend written in V'
4+ version: '0.0.0'
5+ license: 'GPLv3'
6+ base_url: 'src'
7+ dependencies: ['alpm.v', 'blip']
8+}
@@ -0,0 +1,939 @@
1+// vmakepkg holds the build side of blip PKGBUILD.lip files and V-script
2+// PKGBUILD.vsh files. vpac is its one user: the build mode (vpac b) and the
3+// --lip-run entry the generated PKGBUILDs call back through; the rest of
4+// the repo reaches it only by running vpac:
5+//
6+// (defpkgbuild foobar ...) lives under pkgs/<name>/PKGBUILD.lip or inside
7+// an arbitrary repo a build was pointed at, and this module:
8+// 1. validates the form and reads it out as a struct value,
9+// 2. lip_generate turns it into a PKGBUILD (plus a <base>.install when
10+// hooks are written) whose phase functions call the runner binary back
11+// with --lip-run, so the lambdas never become shell,
12+// 3. lip_run_phase is the runner: it loads the lip and runs one phase in
13+// a machine where (run) (glob) (pkgdir) (srcdir) (startdir) (this-pkg)
14+// and (git-desc) exist.
15+// makepkg keeps everything else: sources, checksums, PGP, fakeroot, lint,
16+// packaging. unknown options and checksum counts come out of makepkg's own
17+// mouth, since the generated file is a real PKGBUILD.
18+module vmakepkg
19+
20+import os
21+import blip.vlib.blip
22+import blip.vlib.blip.machine
23+import blip.vlib.blip.host
24+import blip.vlib.blip.printer
25+
26+// ----------------------------------------------------------------- lip pkgs
27+//
28+// PKGBUILD.lip files under pkgs/ describe a package in blip:
29+//
30+// (defpkgbuild foobar
31+// ;; — identity —
32+// :pkgname "foobar" ; or '("foo" "bar") for split
33+// :pkgver "2.5" ; or (lambda () ...) for VCS
34+// :pkgrel 2 ; bump on every change
35+// ;; :epoch 1 ; only to break version ties
36+// :pkgdesc "Text editor for X11"
37+// :arch '(:x86-64) ; or '(:any)
38+// :url "https://example.com/foobar/"
39+// :license "Apache-2.0 WITH LLVM-exception" ; one SPDX expression
40+// ;; — dependencies —
41+// :depends '("glibc" "foobar>=1.8.0")
42+// :makedepends '("git")
43+// :checkdepends '("cmocka")
44+// :optdepends '("cups: printing support")
45+// ;; — relations —
46+// :provides '("foobar.so") ; the pkgname itself is implied
47+// :conflicts '("foobar-git")
48+// ;; — packaging —
49+// :backup '("etc/foobar.conf") ; relative, no leading slash
50+// :options '(:no-strip :docs) ; :no-x becomes !x for makepkg
51+// ;; — sources & integrity —
52+// :source '("foobar-2.5.tar.gz::https://example.com/2.5.tar.gz")
53+// :validpgpkeys '("3B2C6CE3A0FE1EC1D41E39A5F5A0A1B3C9D8E7F6")
54+// :b2sums '("...")
55+// ;; — build phases, as code —
56+// :prepare
57+// (lambda ()
58+// (run "sed -i 's|/opt|/usr|' src/config.h"))
59+// :build
60+// (lambda ()
61+// (run "cmake -B build -DCMAKE_INSTALL_PREFIX=/usr")
62+// (run "cmake --build build"))
63+// :check
64+// (lambda ()
65+// (run "ctest --test-dir build"))
66+// :package
67+// (lambda ()
68+// (run "cmake --install build DESTDIR=$pkgdir")
69+// ;; blip logic instead of fragile shell; for-each comes with the runner:
70+// (for-each (lambda (doc)
71+// (run "install -Dm644 ~A ~A/doc/foobar/~A" doc (pkgdir) doc))
72+// (glob "docs/*.html"))
73+// (run "install -Dm644 LICENSE ~A/usr/share/licenses/foobar/LICENSE" (pkgdir)))
74+// ;; — .install hooks, inline; no separate .install file —
75+// :post-install
76+// (lambda (newver)
77+// (echo "Optional: run foobar-setup to configure autosave"))
78+// :post-upgrade
79+// (lambda (newver oldver)
80+// (echo (format "from ~a to ~a" oldver newver))
81+// (run "systemctl try-restart foobar.service")))
82+//
83+// the build translates that into a real PKGBUILD (and a <base>.install when
84+// hooks are written) in a fresh work dir, where makepkg keeps everything as
85+// usual.
86+const lip_list_keys = [
87+ 'pkgname',
88+ 'arch',
89+ 'license',
90+ 'depends',
91+ 'makedepends',
92+ 'checkdepends',
93+ 'optdepends',
94+ 'provides',
95+ 'conflicts',
96+ 'backup',
97+ 'options',
98+ 'source',
99+ 'validpgpkeys',
100+ 'b2sums',
101+ 'sha256sums',
102+]
103+
104+const lip_phases = ['prepare', 'build', 'check', 'package']
105+
106+const lip_hooks = ['pre-install', 'post-install', 'pre-upgrade', 'post-upgrade', 'pre-remove',
107+ 'post-remove']
108+
109+// lip_hook_arity is the versions pacman hands a .install scriptlet: the new
110+// version for installs and removes, new and then old for upgrades
111+fn lip_hook_arity(hook string) int {
112+ if hook in ['pre-upgrade', 'post-upgrade'] {
113+ return 2
114+ }
115+ return 1
116+}
117+
118+// lip_fn_name spells a hook as its .install function name: dashes are valid
119+// in a keyword, underscores are the .install convention
120+fn lip_fn_name(hook string) string {
121+ return hook.replace('-', '_')
122+}
123+
124+// shell_quote wraps a value for the shell as one word, whatever it holds:
125+// single quotes around it, each quote inside closed, escaped and reopened.
126+// the one quoting vpac and the generated PKGBUILDs both use
127+pub fn shell_quote(s string) string {
128+ return "'" + s.replace("'", "'\\''") + "'"
129+}
130+
131+// lip_tag_name is for error text: 'a keyword' reads better than a dump of the
132+// tag enum
133+fn lip_tag_name(t blip.Tag) string {
134+ return match t {
135+ .nil { 'nil' }
136+ .boolean { 'a boolean' }
137+ .integer { 'an integer' }
138+ .float { 'a float' }
139+ .rune { 'a character' }
140+ .string { 'a string' }
141+ .symbol { 'a symbol' }
142+ .keyword { 'a keyword' }
143+ .pair { 'a list' }
144+ .emptylist { 'an empty list' }
145+ .vector { 'a vector' }
146+ .array { 'an array' }
147+ .table { 'a table' }
148+ .buffer { 'a buffer' }
149+ .closure { 'a lambda' }
150+ .primitive { 'a primitive' }
151+ else { 'a struct' }
152+ }
153+}
154+
155+// lip_items_of reads one plain item ("glibc", :any) or a list of them out of
156+// a value: a quoted list '("a" "b"), or a vector ["a" "b"]. lone keywords are
157+// allowed as items, matching the arch and options spellings, and the same
158+// reader takes a single item so a license does not have to hide in a list
159+fn lip_items_of(v blip.Value, what string) ![]string {
160+ mut out := []string{}
161+ match v.tag {
162+ .string, .keyword, .symbol {
163+ out << v.as_string()
164+ }
165+ .emptylist {}
166+ .vector, .array {
167+ for item in v.as_vector().data {
168+ match item.tag {
169+ .string, .keyword, .symbol {
170+ out << item.as_string()
171+ }
172+ else {
173+ return error('pkgbuild :${what}: items must be strings or keywords, not ${lip_tag_name(item.tag)}')
174+ }
175+ }
176+ }
177+ }
178+ .pair {
179+ mut cur := v
180+ for cur.tag == .pair {
181+ p := cur.as_pair()
182+ match p.car.tag {
183+ .string, .keyword, .symbol {
184+ out << p.car.as_string()
185+ }
186+ else {
187+ return error('pkgbuild :${what}: items must be strings or keywords, not ${lip_tag_name(p.car.tag)}')
188+ }
189+ }
190+ cur = p.cdr
191+ }
192+ // a proper list ends in (): a dotted tail is an item the walk
193+ // above would drop without a word
194+ if cur.tag != .emptylist {
195+ return error('pkgbuild :${what}: a list ends in (), not in a dotted ${lip_tag_name(cur.tag)}')
196+ }
197+ }
198+ else {
199+ return error('pkgbuild :${what} must be a string or a quoted list')
200+ }
201+ }
202+ return out
203+}
204+
205+// lip_arch spells arches the way makepkg reads them: :x86-64 is x86_64 in the
206+// generated head, :any and everything else pass through
207+fn lip_arch(a string) string {
208+ if a == 'x86-64' {
209+ return 'x86_64'
210+ }
211+ return a
212+}
213+
214+// lip_option spells one of :options' entries the way makepkg's options array
215+// wants it: makepkg spells disabled options with a ! in front, and the lip's
216+// keyword for that is no-, so :no-strip becomes !strip; an enabled option and
217+// anything already in makepkg's own spelling pass through
218+fn lip_option(keyword string) string {
219+ if keyword.starts_with('no-') {
220+ return '!' + keyword[3..]
221+ }
222+ return keyword
223+}
224+
225+// lip_hex checks a checksum body: full hex for its own length, or SKIP, so a
226+// bad sum is named in the lip, not somewhere inside makepkg's diagnosis
227+fn lip_hex(s string, len int, what string) ! {
228+ if s == 'SKIP' {
229+ return
230+ }
231+ if s.len != len {
232+ return error('${what}: ${s} is ${s.len} characters; ${what} entries are ${len} hex characters or SKIP')
233+ }
234+ for c in s {
235+ if !c.is_hex_digit() {
236+ return error('${what}: ${s} has a character that is not hex (${c.ascii_str()})')
237+ }
238+ }
239+}
240+
241+// lip_key40 checks a PGP fingerprint: the full 40 uppercase hex characters
242+fn lip_key40(s string, i int) ! {
243+ if s.len != 40 {
244+ return error('validpgpkeys: entry ${i} is ${s.len} characters; fingerprints are 40: the full uppercase one')
245+ }
246+ for c in s {
247+ if !c.is_hex_digit() {
248+ return error('validpgpkeys: entry ${i} has a character that is not hex (${c.ascii_str()})')
249+ }
250+ if c >= `a` && c <= `f` {
251+ return error('validpgpkeys: entry ${i} is lowercase hex (${c.ascii_str()}); uppercase fingerprints only')
252+ }
253+ }
254+}
255+
256+// prim_defpkgbuild validates one (defpkgbuild ...) form and hands back a
257+// struct value: the scalars checked, the list keys normalised, and the phase
258+// and hook lambdas kept as the closures they evaluated to. the generator and
259+// the runner both read out of that one value. one (defpkgbuild ...) per file
260+// is checked by lip_defpkg_count when the file loads
261+fn prim_defpkgbuild(args []blip.Value) !blip.Value {
262+ if args.len == 0 {
263+ return error('pkgbuild: (defpkgbuild name ...) needs the name')
264+ }
265+ // the name can be the bare symbol (the format's spelling, pre-bound to
266+ // its own string by the loader), a quoted symbol, or a string
267+ if args[0].tag !in [.string, .symbol] {
268+ return error('pkgbuild: the name is a symbol or a string, not ${lip_tag_name(args[0].tag)}')
269+ }
270+ pkgbase_name := args[0].as_string()
271+ if (args.len - 1) % 2 != 0 {
272+ return error('pkgbuild: :key and value come in pairs')
273+ }
274+ mut fields := []string{}
275+ mut vals := map[string]blip.Value{}
276+ fields << 'name'
277+ vals['name'] = blip.string(pkgbase_name)
278+ mut i := 1
279+ for i < args.len {
280+ kv := args[i]
281+ if kv.tag != .keyword {
282+ return error('pkgbuild: expected a :key, got ${printer.write(kv)}')
283+ }
284+ key := kv.as_string()
285+ val := args[i + 1]
286+ if key in fields {
287+ return error('pkgbuild :${key} is set twice')
288+ }
289+ if key in lip_list_keys {
290+ mut items := lip_items_of(val, key)!
291+ match key {
292+ 'pkgname' {
293+ if items.len == 0 {
294+ return error('pkgbuild :pkgname must not be empty')
295+ }
296+ for it in items {
297+ if it.contains(' ') {
298+ return error('pkgbuild :pkgname: "${it}" has whitespace in it')
299+ }
300+ }
301+ }
302+ 'arch' {
303+ if items.len == 0 {
304+ return error('pkgbuild :arch must not be empty')
305+ }
306+ for j, it in items {
307+ items[j] = lip_arch(it)
308+ }
309+ }
310+ 'validpgpkeys' {
311+ for j, it in items {
312+ lip_key40(it, j)!
313+ }
314+ }
315+ 'b2sums' {
316+ for it in items {
317+ lip_hex(it, 128, 'b2sums')!
318+ }
319+ }
320+ 'sha256sums' {
321+ for it in items {
322+ lip_hex(it, 64, 'sha256sums')!
323+ }
324+ }
325+ 'backup' {
326+ for it in items {
327+ if it.starts_with('/') {
328+ return error('pkgbuild :backup: "${it}" is absolute; backup paths are relative, no leading slash')
329+ }
330+ }
331+ }
332+ else {}
333+ }
334+ mut item_vals := []blip.Value{}
335+ for it in items {
336+ item_vals << blip.string(it)
337+ }
338+ fields << key
339+ vals[key] = blip.list_from(item_vals)
340+ i += 2
341+ continue
342+ }
343+ if key in lip_phases || key in lip_hooks {
344+ if val.tag != .closure {
345+ return error('pkgbuild :${key} must be a (lambda ...); makepkg runs it as a function')
346+ }
347+ p := val.as_closure()
348+ arity := if key in lip_hooks { lip_hook_arity(key) } else { 0 }
349+ if p.params.len != arity {
350+ return error('pkgbuild :${key} takes ${arity} parameter${if arity == 1 {
351+ ''
352+ } else {
353+ 's'
354+ }}, not ${p.params.len}')
355+ }
356+ fields << key
357+ vals[key] = val
358+ i += 2
359+ continue
360+ }
361+ match key {
362+ 'pkgver' {
363+ // a static version is written verbatim; a lambda is the pkgver()
364+ // makepkg runs after the sources are unpacked, for VCS packages
365+ if val.tag != .string && val.tag != .closure {
366+ return error('pkgbuild :pkgver must be a string or a (lambda ...)')
367+ }
368+ fields << key
369+ vals[key] = val
370+ }
371+ 'pkgrel', 'epoch' {
372+ if val.tag != .integer {
373+ return error('pkgbuild :${key} must be an integer')
374+ }
375+ if key == 'epoch' && val.as_int() < 0 {
376+ return error('pkgbuild :epoch is negative; 0 means absent')
377+ }
378+ fields << key
379+ vals[key] = val
380+ }
381+ 'pkgdesc', 'url' {
382+ if val.tag != .string {
383+ return error('pkgbuild :${key} must be a string')
384+ }
385+ fields << key
386+ vals[key] = val
387+ }
388+ else {
389+ // the keys makepkg knows, in the lip's spelling; anything else
390+ // is an error here, where the lip names it
391+ return error('pkgbuild has no key :${key}')
392+ }
393+ }
394+ i += 2
395+ }
396+ // the fields makepkg refuses to do without. build is not one: makepkg
397+ // runs build() only when the PKGBUILD has one (a data package, the split
398+ // smoke package, has none); package is, the one phase every package runs
399+ for req in ['pkgname', 'pkgver', 'pkgrel', 'pkgdesc', 'arch', 'package'] {
400+ if req !in fields {
401+ return error('pkgbuild: :${req} is required')
402+ }
403+ }
404+ return blip.struct_value('pkgbuild', fields, vals)
405+}
406+
407+// prim_run replaces every ~a in the format with the next argument —
408+// shell-quoted, so a path with spaces survives — and hands the line to the
409+// runner's own run helper
410+fn prim_run(args []blip.Value) !blip.Value {
411+ run(lip_fmt(args)!)!
412+ return blip.nil_value()
413+}
414+
415+// prim_glob spills the pattern into a blip vector, sorted, empty when nothing
416+// matches: the loop in the format example iterates it directly
417+fn prim_glob(args []blip.Value) !blip.Value {
418+ if args.len != 1 || args[0].tag != .string {
419+ return error('(glob pattern) takes one string pattern')
420+ }
421+ matches := glob(args[0].as_string())!
422+ mut out := []blip.Value{}
423+ for m in matches {
424+ out << blip.string(m)
425+ }
426+ return blip.vector(out)
427+}
428+
429+// prim_pkgdir is (pkgdir): the directory makepkg is filling, which the
430+// generated function exports for the phase
431+fn prim_pkgdir(_ []blip.Value) !blip.Value {
432+ p := os.getenv('VPAC_PKGDIR')
433+ if p == '' {
434+ return error('(pkgdir): only a value inside a pkgbuild phase; let the built PKGBUILD call it')
435+ }
436+ return blip.string(p)
437+}
438+
439+fn prim_srcdir(_ []blip.Value) !blip.Value {
440+ p := os.getenv('VPAC_SRCDIR')
441+ if p == '' {
442+ return error('(srcdir): only a value inside a pkgbuild phase; let the built PKGBUILD call it')
443+ }
444+ return blip.string(p)
445+}
446+
447+fn prim_startdir(_ []blip.Value) !blip.Value {
448+ p := os.getenv('VPAC_STARTDIR')
449+ if p == '' {
450+ return error('(startdir): only a value inside a pkgbuild phase; let the built PKGBUILD call it')
451+ }
452+ return blip.string(p)
453+}
454+
455+// prim_this_pkg is (this-pkg): the name a split lambda runs under — makepkg
456+// rebinds pkgname for every split while packaging
457+fn prim_this_pkg(_ []blip.Value) !blip.Value {
458+ p := os.getenv('VPAC_PKGNAME')
459+ if p == '' {
460+ return error('(this-pkg): only a value inside a pkgbuild phase; let the built PKGBUILD call it')
461+ }
462+ return blip.string(p)
463+}
464+
465+// prim_git_desc is (git-desc pattern fallback?): git describe in the cwd the
466+// phase runs under ($srcdir, where makepkg runs its phases). the fallback
467+// comes out verbatim when describe finds nothing, so a young tree still has a
468+// version before its first tag
469+fn prim_git_desc(args []blip.Value) !blip.Value {
470+ if args.len == 0 || args.len > 2 || args[0].tag != .string {
471+ return error('(git-desc pattern fallback?) takes a string pattern and an optional string fallback')
472+ }
473+ pattern := args[0].as_string()
474+ mut fallback := ''
475+ if args.len == 2 {
476+ if args[1].tag != .string {
477+ return error('(git-desc ...): the fallback must be a string')
478+ }
479+ fallback = args[1].as_string()
480+ }
481+ return blip.string(git_desc(pattern, fallback)!)
482+}
483+
484+// lip_fmt renders the format for run: every ~a takes the next argument,
485+// shell-quoted, which is what the command needs to survive a path with
486+// spaces. echo needs none of it: blip's own echo prints plainly, and a hook
487+// that wants interpolation echoes (format "..." ~a)
488+fn lip_fmt(args []blip.Value) !string {
489+ if args.len == 0 || args[0].tag != .string {
490+ return error('run: the first argument is the format string')
491+ }
492+ // both spellings of the placeholder are welcome; blip's own format uses
493+ // the lowercase one
494+ fmt_text := args[0].as_string().replace('~A', '~a')
495+ parts := fmt_text.split('~a')
496+ if parts.len - 1 != args.len - 1 {
497+ return error('run: the format has ${parts.len - 1} ~a for ${args.len - 1} argument${if args.len - 1 == 1 {
498+ ''
499+ } else {
500+ 's'
501+ }}')
502+ }
503+ mut out := parts[0]
504+ mut j := 1
505+ for j < args.len {
506+ arg := args[j]
507+ mut rendered := ''
508+ match arg.tag {
509+ .string {
510+ rendered = arg.as_string()
511+ }
512+ .integer {
513+ rendered = arg.as_int().str()
514+ }
515+ else {
516+ 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')
517+ }
518+ }
519+ rendered = shell_quote(rendered)
520+ out += rendered
521+ out += parts[j]
522+ j++
523+ }
524+ return out
525+}
526+
527+// lip_new_machine builds a machine with the pkgbuild prims registered
528+// (defpkgbuild among them). the bare package name is spelled the file's own
529+// way: the loader pre-binds it before the file loads, prim arg or not
530+fn lip_new_machine() !&machine.Machine {
531+ mut m := machine.new_standalone(&host.ConsoleHost{})
532+ m.prims['defpkgbuild'] = prim_defpkgbuild
533+ m.prims['run'] = prim_run
534+ m.prims['glob'] = prim_glob
535+ m.prims['pkgdir'] = prim_pkgdir
536+ m.prims['srcdir'] = prim_srcdir
537+ m.prims['startdir'] = prim_startdir
538+ m.prims['this-pkg'] = prim_this_pkg
539+ m.prims['git-desc'] = prim_git_desc
540+ return m
541+}
542+
543+// lip_delim is true for a byte that ends a symbol: space, a bracket, or a
544+// comment's or string's opening
545+fn lip_delim(c u8) bool {
546+ return c in [` `, `\t`, `\n`, `\r`, `(`, `)`, `[`, `]`, `{`, `}`, `;`, `"`]
547+}
548+
549+// lip_defpkg_forms finds the (defpkgbuild ...) forms in a lip's real text,
550+// blip's own spelling of comments and strings applied: `;` ends a line's
551+// text, `#|` opens a block comment nested to its `|#`, and a double-quoted
552+// string hides its contents, so `(defpkgbuild` named in one does not count.
553+// in code the form only opens at a word boundary, so a symbol with a longer
554+// name or one quoted into a string is not a second build of the package.
555+// each form is answered as the offset just past its `(defpkgbuild`
556+fn lip_defpkg_forms(src string) []int {
557+ mut forms := []int{}
558+ mut i := 0
559+ for i < src.len {
560+ c := src[i]
561+ if c == `;` {
562+ for i < src.len && src[i] != `\n` {
563+ i++
564+ }
565+ continue
566+ }
567+ if c == `#` && i + 1 < src.len && src[i + 1] == `|` {
568+ mut level := 1
569+ i += 2
570+ for i < src.len && level > 0 {
571+ if src[i] == `#` && i + 1 < src.len && src[i + 1] == `|` {
572+ level++
573+ i += 2
574+ } else if src[i] == `|` && i + 1 < src.len && src[i + 1] == `#` {
575+ level--
576+ i += 2
577+ } else {
578+ i++
579+ }
580+ }
581+ continue
582+ }
583+ if c == `"` {
584+ i++
585+ for i < src.len {
586+ if src[i] == `\\` && i + 1 < src.len {
587+ i += 2
588+ continue
589+ }
590+ if src[i] == `"` {
591+ i++
592+ break
593+ }
594+ i++
595+ }
596+ continue
597+ }
598+ if c == `(` && src[i + 1..].starts_with('defpkgbuild') {
599+ after := i + 1 + 'defpkgbuild'.len
600+ // the symbol ends at space, bracket or end: a same-named text
601+ // inside a bigger symbol name does not open a form
602+ if after >= src.len || lip_delim(src[after]) {
603+ forms << after
604+ }
605+ i = after
606+ continue
607+ }
608+ i++
609+ }
610+ return forms
611+}
612+
613+// lip_defpkg_name reads the (defpkgbuild name ...) symbol out of the file
614+// text. the machine evaluates a bare symbol, so the runner and the generator
615+// pre-bind the name under it before the file loads: the file keeps spelling
616+// the package bare, the format's own way. the form is found the way
617+// lip_defpkg_count finds it, so one named in a comment or a string binds
618+// nothing, and the name runs to the symbol's end, whatever a package name
619+// may hold (a dot, a plus, an at)
620+fn lip_defpkg_name(lip string) string {
621+ src := os.read_file(lip) or { return '' }
622+ forms := lip_defpkg_forms(src)
623+ if forms.len == 0 {
624+ return ''
625+ }
626+ mut j := forms[0]
627+ for j < src.len && src[j] in [` `, `\n`, `\r`, `\t`] {
628+ j++
629+ }
630+ // a quoted or string spelling needs no trick
631+ if j >= src.len || src[j] == `'` || src[j] == `"` {
632+ return ''
633+ }
634+ mut end := j
635+ for end < src.len && !lip_delim(src[end]) {
636+ end++
637+ }
638+ return src[j..end]
639+}
640+
641+// lip_defpkg_count counts the (defpkgbuild ...) forms in a lip's real text
642+fn lip_defpkg_count(path string) !int {
643+ return lip_defpkg_forms(os.read_file(path)!).len
644+}
645+
646+// lip_load_in loads one lip into a machine that already has the prims, with
647+// the pre-bound name, and checks the last form is the defpkgbuild struct
648+fn lip_load_in(mut m machine.Machine, path string) !blip.Value {
649+ // a lip that cannot be read fails here, with the read's own reason: the
650+ // one-form check is never skipped on the way to a load that reads it
651+ count := lip_defpkg_count(path) or { return error('${path}: ${err.msg()}') }
652+ if count > 1 {
653+ return error('${path}: one (defpkgbuild ...) form per file, not ${count}')
654+ }
655+ name := lip_defpkg_name(path)
656+ if name != '' {
657+ m.envs.define(m.globals, name, blip.string(name))
658+ }
659+ v := m.load(path)!
660+ if v.tag != .struct_ {
661+ return error('${path}: the last form must be a (defpkgbuild ...)')
662+ }
663+ return v
664+}
665+
666+// lip_load evaluates a PKGBUILD.lip and returns the struct the defpkgbuild
667+// prim ran it into: the last form's value
668+pub fn lip_load(path string) !blip.Value {
669+ mut m := lip_new_machine()!
670+ return lip_load_in(mut m, path)!
671+}
672+
673+// lip_make is the one-liner callers want: load the lip, hand back everything
674+// the generated package needs (the PKGBUILD text, the .install when hooks
675+// exist, and whether pkgver floats)
676+pub fn lip_make(lip string, runner string) !LipBet {
677+ meta := lip_load(lip)!
678+ return lip_generate(meta, runner, lip, .lip)!
679+}
680+
681+// lip_run_phase is --lip-run <lip> <phase> [args...]: it loads the lip, wires
682+// the phase's closure under a fresh name, and calls it with the remaining
683+// arguments as the parameters. pkgver's result is the version, printed for
684+// makepkg's call to read; every other phase's result falls on the floor. a
685+// failure is nonzero, which fails the makepkg phase like a plain script would
686+pub fn lip_run_phase(lip string, phase string, params []string) ! {
687+ mut m := lip_new_machine()!
688+ // load on this machine, not lip_load's: the bootstrap macro has to be
689+ // in the machine that runs the file, with its phases
690+ meta := lip_load_in(mut m, lip)!
691+ s := meta.as_struct()
692+ if !s.has(phase) {
693+ return error('${lip}: the pkgbuild has no :${phase}')
694+ }
695+ cb := s.get(phase)
696+ if cb.tag != .closure {
697+ return error('${lip}: :${phase} is not a (lambda ...)')
698+ }
699+ name := m.fresh('PKG-RUN')
700+ m.envs.define(m.globals, name, cb)
701+ mut arg_nodes := []blip.NodeId{}
702+ for arg in params {
703+ arg_nodes << m.string_node(arg)
704+ }
705+ call := m.call_node(m.sym_node(name), arg_nodes)
706+ res := m.run([call])!
707+ if phase == 'pkgver' {
708+ if res.tag != .string {
709+ return error('pkgver: the lambda ran into ${lip_tag_name(res.tag)}, not a version string')
710+ }
711+ println(res.as_string())
712+ }
713+}
714+
715+// lip_array_line writes a makepkg array: one quoted entry per line, in the
716+// order the lip declared them
717+fn lip_array_line(name string, items []string) string {
718+ mut out := '${name}=('
719+ for it in items {
720+ out += '\n ${shell_quote(it)}'
721+ }
722+ out += '\n)'
723+ return out
724+}
725+
726+// LipKind says which file the phases live in: a lip runs through this
727+// binary's runner, a PKGBUILD.vsh runs through v itself
728+pub enum LipKind {
729+ lip
730+ vsh
731+}
732+
733+// delegate_line is the one bash line a phase wrapper hands the work to, per
734+// kind, with makepkg's own state exported for the runner
735+fn delegate_line(kind LipKind, phase string, extra string) string {
736+ call := if kind == .lip {
737+ '"\$VPAC_BLIP_RUN" --lip-run "\$VPAC_PKG_LIP" ${phase}'
738+ } else {
739+ '"\$VPAC_VSH_RUN" run "\$VPAC_PKG_VSH" ${phase}'
740+ }
741+ return ' export VPAC_PKGDIR="\$pkgdir" VPAC_SRCDIR="\$srcdir" VPAC_STARTDIR="\$startdir" VPAC_PKGNAME="\$pkgname" VPAC_PKGVER="\$pkgver"
742+ ${call}${extra}'
743+}
744+
745+// lip_phase_fn writes one makepkg function that hands the phase to the
746+// runner. makepkg's own pkgdir, srcdir and startdir are readonly in its
747+// shell, so the wrapper exports fresh VPAC_ spellings instead: the runner's
748+// host primitives read those, and (run) re-exposes makepkg's spellings to
749+// every command it passes to sh, so the raw $pkgdir of a phase body keeps
750+// meaning exactly what makepkg says
751+fn lip_phase_fn(fn_name string, phase string, kind LipKind) string {
752+ return '${fn_name}() {
753+${delegate_line(kind, phase, '')}
754+}'
755+}
756+
757+// lip_pkgver_fn writes pkgver() for VCS packages: makepkg captures its stdout
758+// as the new version, and runs it from $srcdir like the other phases
759+fn lip_pkgver_fn(kind LipKind) string {
760+ return 'pkgver() {
761+${delegate_line(kind, 'pkgver', '')}
762+}'
763+}
764+
765+// lip_hook_fn writes one .install function: pacman passes the versions, the
766+// runner takes them as the lambda's parameters. libalpm sources the .install
767+// at install time in a shell of its own, where nothing of the PKGBUILD's —
768+// its VPAC_ variables, makepkg's pkgdir and srcdir — exists, so the runner
769+// and the script are written into the function as they were at the build,
770+// and the package's name is the one thing of makepkg's state handed on. a
771+// runner or a script that is gone by then is said and fails the scriptlet,
772+// where an empty command would have been a silent 127
773+fn lip_hook_fn(hook string, kind LipKind, runner string, script_path string, pkgname string) string {
774+ argv := lip_hook_arity(hook)
775+ mut args := ''
776+ if argv > 0 {
777+ args = ' "\$1"'
778+ }
779+ if argv > 1 {
780+ args += ' "\$2"'
781+ }
782+ r := shell_quote(runner)
783+ s := shell_quote(script_path)
784+ call := if kind == .lip { '${r} --lip-run ${s} ${hook}' } else { '${r} run ${s} ${hook}' }
785+ gone := shell_quote('${pkgname}: the ${hook} hook needs ${runner} and ${script_path}, and one of them is gone')
786+ return '${lip_fn_name(hook)}() {
787+ if [ ! -x ${r} ] || [ ! -r ${s} ]; then
788+ echo ${gone} >&2
789+ return 1
790+ fi
791+ VPAC_PKGNAME=${shell_quote(pkgname)} ${call}${args}
792+}'
793+}
794+
795+// LipBet is one generated package: the PKGBUILD, the .install when hooks are
796+// there, and the base the files follow
797+pub struct LipBet {
798+pub mut:
799+ text string
800+ install string
801+ dynamic bool
802+ base string
803+}
804+
805+// lip_generate turns the defpkgbuild struct into the PKGBUILD text (and into
806+// a .install when hooks are written), pointing at this binary and at the
807+// original lip, wherever they were when the package was built
808+fn lip_generate(meta blip.Value, runner string, script_path string, kind LipKind) !LipBet {
809+ s := meta.as_struct()
810+ mut names := []string{}
811+ if s.has('pkgname') {
812+ names = lip_items_of(s.get('pkgname'), 'pkgname')!
813+ }
814+ pkgbase := names[0]
815+ mut dynamic := false
816+ pkgver := if s.has('pkgver') {
817+ v := s.get('pkgver')
818+ if v.tag == .string {
819+ v.as_string()
820+ } else {
821+ dynamic = true
822+ '0'
823+ }
824+ } else {
825+ // the entry holds the pkgver function for vsh scripts, so the head
826+ // gets the same 0 placeholder and pkgver() wrapper a lambda would
827+ dynamic = true
828+ '0'
829+ }
830+ rel := s.get('pkgrel').as_int()
831+ mut out := []string{}
832+ head_label := if kind == .lip {
833+ 'from the lip; the lip is the source'
834+ } else {
835+ 'from PKGBUILD.vsh; the script is the source'
836+ }
837+ out << '# Generated by the vpac build ${head_label}'
838+ if kind == .lip {
839+ out << 'VPAC_BLIP_RUN=${shell_quote(runner)}'
840+ out << 'VPAC_PKG_LIP=${shell_quote(script_path)}'
841+ } else {
842+ out << 'VPAC_VSH_RUN=${shell_quote(runner)}'
843+ out << 'VPAC_PKG_VSH=${shell_quote(script_path)}'
844+ }
845+ out << ''
846+ if names.len > 1 {
847+ out << 'pkgbase=${shell_quote(pkgbase)}'
848+ }
849+ if names.len == 1 {
850+ out << 'pkgname=${shell_quote(pkgbase)}'
851+ } else {
852+ out << lip_array_line('pkgname', names)
853+ }
854+ out << 'pkgver=${shell_quote(pkgver)}'
855+ out << 'pkgrel=${rel}'
856+ if s.has('epoch') && s.get('epoch').as_int() > 0 {
857+ out << 'epoch=${s.get('epoch').as_int()}'
858+ }
859+ pkgdesc := s.get('pkgdesc').as_string()
860+ out << 'pkgdesc=${shell_quote(pkgdesc)}'
861+ arches := lip_items_of(s.get('arch'), 'arch')!
862+ out << lip_array_line('arch', arches)
863+ for opt in ['url', 'license'] {
864+ if s.has(opt) {
865+ items := lip_items_of(s.get(opt), opt)!
866+ if opt == 'license' || items.len > 1 {
867+ // makepkg says license must be an array: one entry or many
868+ out << lip_array_line(opt, items)
869+ } else {
870+ out << '${opt}=${shell_quote(items[0])}'
871+ }
872+ }
873+ }
874+ for k in ['depends', 'makedepends', 'checkdepends', 'optdepends', 'provides', 'conflicts',
875+ 'backup', 'options', 'source', 'validpgpkeys'] {
876+ if s.has(k) {
877+ items := lip_items_of(s.get(k), k)!
878+ // the lip spells a disabled option :no-x, makepkg spells !x; a
879+ // PKGBUILD.vsh's spec holds makepkg's own spelling already
880+ worded := if kind == .lip && k == 'options' { items.map(lip_option) } else { items }
881+ out << lip_array_line(k, worded)
882+ }
883+ }
884+ for k in ['b2sums', 'sha256sums'] {
885+ if s.has(k) {
886+ out << lip_array_line(k, lip_items_of(s.get(k), k)!)
887+ }
888+ }
889+ mut has_hooks := false
890+ for h in lip_hooks {
891+ if s.has(h) {
892+ has_hooks = true
893+ }
894+ }
895+ mut install_name := ''
896+ if has_hooks {
897+ install_name = '${pkgbase}.install'
898+ out << 'install=${shell_quote(install_name)}'
899+ }
900+ out << ''
901+ out << "# the phases run as the runner's own code above, nothing here is shell logic"
902+ if dynamic {
903+ out << lip_pkgver_fn(kind)
904+ }
905+ for ph in lip_phases {
906+ if ph == 'package' {
907+ continue
908+ }
909+ if s.has(ph) {
910+ out << lip_phase_fn(ph, ph, kind)
911+ }
912+ }
913+ // a shared :package lambda runs once per split: makepkg rebinds pkgname
914+ // on the way through, so (this-pkg) says which split is being packed
915+ for name in names {
916+ fn_name := if names.len == 1 { 'package' } else { 'package_${name}' }
917+ out << lip_phase_fn(fn_name, 'package', kind)
918+ }
919+ // the hooks are inline in the lip, and live in the package the world
920+ // sees, as pacman's own .install contract expects
921+ mut install := ''
922+ if has_hooks {
923+ mut lines := []string{}
924+ lines << '#!/bin/sh'
925+ lines << '# Generated by the vpac build: the hooks are the source, run through the runner'
926+ for h in lip_hooks {
927+ if s.has(h) {
928+ lines << lip_hook_fn(h, kind, runner, script_path, pkgbase)
929+ }
930+ }
931+ install = lines.join('\n') + '\n'
932+ }
933+ return LipBet{
934+ text: out.join('\n') + '\n'
935+ install: install
936+ dynamic: dynamic
937+ base: pkgbase
938+ }
939+}
@@ -0,0 +1,396 @@
1+module vmakepkg
2+
3+import os
4+
5+// the generated head's spellings, checked against makepkg
6+fn test_lip_arch() {
7+ assert lip_arch('x86-64') == 'x86_64'
8+ assert lip_arch('any') == 'any'
9+ assert lip_arch('x86') == 'x86'
10+}
11+
12+fn test_lip_option() {
13+ assert lip_option('no-strip') == '!strip'
14+ assert lip_option('docs') == 'docs'
15+ assert lip_option('zipman') == 'zipman'
16+ assert lip_option('no-docs') == '!docs'
17+}
18+
19+fn test_lip_hook_arity() {
20+ assert lip_hook_arity('pre-install') == 1
21+ assert lip_hook_arity('post-remove') == 1
22+ assert lip_hook_arity('pre-upgrade') == 2
23+ assert lip_hook_arity('post-upgrade') == 2
24+}
25+
26+fn test_lip_fn_name() {
27+ assert lip_fn_name('pre-install') == 'pre_install'
28+}
29+
30+fn test_shell_quote() {
31+ assert shell_quote("a 'b' c") == "'a '\\''b'\\'' c'"
32+ assert shell_quote('plain') == "'plain'"
33+}
34+
35+fn test_shell_quote_round_trips_through_sh() {
36+ // the property that matters: whatever the value holds, a shell reads it
37+ // back as the one word it was — no expansion, no split, no command
38+ for value in ["it's", '\$HOME', '`id`', '\$(id)', 'a b\tc', 'semi;colon', 'new\nline', 'back\\slash',
39+ '"double"', "'", "''", '*', '-n', '', 'ünï'] {
40+ res := os.exec(['sh', '-c', 'printf %s ' + shell_quote(value)])
41+ assert res.exit_code == 0, value
42+ assert res.output == value, value
43+ }
44+}
45+
46+// lip_make turns one lip into the PKGBUILD (and the .install) makepkg runs:
47+// its head is the head a real PKGBUILD spells, its phases delegate to the
48+// runner, and pkgver stays a static one when the lip's is
49+fn test_lip_make_golden() ! {
50+ dir := os.join_path(os.vtmp_dir(), 'vpac_lip_make_golden_${os.getpid()}')
51+ os.mkdir_all(dir)!
52+ defer {
53+ os.rmdir_all(dir) or {}
54+ }
55+ lip := os.join_path(dir, 'tiny.lip')
56+ lines := [
57+ '(defpkgbuild tiny',
58+ ' :pkgname "tiny"',
59+ ' :pkgver "1.0"',
60+ ' :pkgrel 3',
61+ ' :pkgdesc "tiny golden package"',
62+ " :arch '(:any)",
63+ ' :depends \'("bash")',
64+ " :options '(:no-strip :docs)",
65+ ' :build',
66+ ' (lambda () (run "true"))',
67+ ' :package',
68+ ' (lambda () (run "true"))',
69+ ' :post-install',
70+ ' (lambda (newver) (echo "done")))',
71+ ]
72+ os.write_file(lip, lines.join('\n'))!
73+
74+ bb := lip_make(lip, '/vpac/runner')!
75+ assert bb.base == 'tiny'
76+ assert bb.dynamic == false
77+ // the identity, spelled the way makepkg reads it
78+ assert bb.text.contains("pkgname='tiny'")
79+ assert bb.text.contains("pkgver='1.0'")
80+ assert bb.text.contains('pkgrel=3')
81+ assert bb.text.contains("pkgdesc='tiny golden package'")
82+ assert bb.text.contains("arch=(\n 'any'\n)")
83+ // lists carry one quoted entry a line, and the lip's :no-x becomes
84+ // makepkg's !x
85+ assert bb.text.contains('depends=(') && bb.text.contains(" 'bash'")
86+ assert bb.text.contains("options=(\n '!strip'\n 'docs'\n)")
87+ // the phases call this binary back with the lip they came from
88+ assert bb.text.contains("VPAC_BLIP_RUN='/vpac/runner'")
89+ assert bb.text.contains("VPAC_PKG_LIP='${lip}'")
90+ assert bb.text.contains('build() {\n export')
91+ assert bb.text.contains('package() {\n export')
92+ // a static pkgver runs no pkgver()
93+ assert !bb.text.contains('pkgver()')
94+ // the hooks are the .install the head names, run through the runner
95+ assert bb.install.starts_with('#!/bin/sh')
96+ assert bb.text.contains("install='tiny.install'")
97+ // libalpm sources the .install in a shell of its own: the runner and
98+ // the lip stand in it literally, nothing is read from the PKGBUILD's
99+ // variables, and a missing one is said
100+ assert bb.install.contains("VPAC_PKGNAME='tiny' '/vpac/runner' --lip-run '${lip}' post-install \"\$1\"\n"), bb.install
101+ assert bb.install.contains("if [ ! -x '/vpac/runner' ] || [ ! -r '${lip}' ]; then")
102+ assert !bb.install.contains('\$VPAC_') && !bb.install.contains('\$pkgdir')
103+ // and the function is sh that runs: with no runner there it fails aloud
104+ install_file := os.join_path(dir, 'tiny.install')
105+ os.write_file(install_file, bb.install)!
106+ hook := os.exec(['sh', '-c', '. "\$0"; post_install 1.0 2>&1', install_file])
107+ assert hook.exit_code == 1 && hook.output.contains('one of them is gone'), hook.output
108+}
109+
110+// a pkgver lambda makes the package a VCS one: pkgver() is generated for
111+// makepkg to call, and the head carries the placeholder it replaces
112+fn test_lip_make_dynamic_pkgver() ! {
113+ dir := os.join_path(os.vtmp_dir(), 'vpac_lip_make_dyn_${os.getpid()}')
114+ os.mkdir_all(dir)!
115+ defer {
116+ os.rmdir_all(dir) or {}
117+ }
118+ lip := os.join_path(dir, 'tiny.lip')
119+ lines := [
120+ '(defpkgbuild tiny',
121+ ' :pkgname "tiny"',
122+ ' :pkgver (lambda () "unused")',
123+ ' :pkgrel 1',
124+ ' :pkgdesc "tiny vcs package"',
125+ " :arch '(:any)",
126+ ' :build',
127+ ' (lambda () (run "true"))',
128+ ' :package',
129+ ' (lambda () (run "true")))',
130+ ]
131+ os.write_file(lip, lines.join('\n'))!
132+ bb := lip_make(lip, '/vpac/runner')!
133+ assert bb.dynamic
134+ assert bb.text.contains("pkgver='0'")
135+ assert bb.text.contains('pkgver() {\n export')
136+}
137+
138+// lip_defpkg_count counts real (defpkgbuild ...) forms: comments of either
139+// kind stay out, block comments stay out, a string's mention of the form
140+// stays out, and a longer symbol whose name begins equally is no form
141+fn test_lip_defpkg_count() {
142+ dir := os.join_path(os.vtmp_dir(), 'vpac_lip_count_${os.getpid()}')
143+ os.mkdir_all(dir)!
144+ defer {
145+ os.rmdir_all(dir) or {}
146+ }
147+ p := os.join_path(dir, 'count.lip')
148+ os.write_file(p, '(defpkgbuild foo\n)')!
149+ assert lip_defpkg_count(p)! == 1
150+ os.write_file(p, '(defpkgbuild foo\n)\n(defpkgbuild bar\n)')!
151+ assert lip_defpkg_count(p)! == 2
152+ os.write_file(p, ';; a comment names (defpkgbuild x)\n(defpkgbuild foo\n)')!
153+ assert lip_defpkg_count(p)! == 1
154+ os.write_file(p, '(defpkgbuild foo ; inline ends the text (defpkgbuild y)\n)')!
155+ assert lip_defpkg_count(p)! == 1
156+ os.write_file(p, '#| (defpkgbuild z) reduces the block |#\n(defpkgbuild foo\n)')!
157+ assert lip_defpkg_count(p)! == 1
158+ // a string's mention of the form stays out: the ('no form counts') text
159+ // spells one whole (defpkgbuild ...) inside a string
160+ os.write_file(p, '(defpkgbuild foo\n :defpkgdesc "the string names (defpkgbuild x) whole"\n)')!
161+ assert lip_defpkg_count(p)! == 1
162+ os.write_file(p, '(defpkg-build foo\n)')!
163+ assert lip_defpkg_count(p)! == 0
164+ os.write_file(p, '(defpkgbuildy foo\n)')!
165+ assert lip_defpkg_count(p)! == 0
166+}
167+
168+// the name pre-bound is the real form's: one named in a comment or a string
169+// before it binds nothing, and the name runs to the symbol's end
170+fn test_lip_defpkg_name() {
171+ dir := os.join_path(os.vtmp_dir(), 'vpac_lip_name_${os.getpid()}')
172+ os.mkdir_all(dir)!
173+ defer {
174+ os.rmdir_all(dir) or {}
175+ }
176+ p := os.join_path(dir, 'name.lip')
177+ os.write_file(p, '(defpkgbuild foo-bar\n)')!
178+ assert lip_defpkg_name(p) == 'foo-bar'
179+ os.write_file(p, ';; write (defpkgbuild wrong ...) below\n#| (defpkgbuild also-wrong) |#\n(defpkgbuild right\n)')!
180+ assert lip_defpkg_name(p) == 'right'
181+ os.write_file(p, '(defpkgbuild lib.so+x@1)')!
182+ assert lip_defpkg_name(p) == 'lib.so+x@1'
183+ os.write_file(p, '(defpkgbuild "quoted"\n)')!
184+ assert lip_defpkg_name(p) == ''
185+ os.write_file(p, ';; no form at all')!
186+ assert lip_defpkg_name(p) == ''
187+}
188+
189+fn test_lip_load_unreadable() ! {
190+ dir := os.join_path(os.vtmp_dir(), 'vpac_lip_unreadable_${os.getpid()}')
191+ os.mkdir_all(dir)!
192+ defer {
193+ os.rmdir_all(dir) or {}
194+ }
195+ // no file at all, and a directory where the file should be: each fails
196+ // with the read's reason and the path, not a later, other complaint
197+ for p in [os.join_path(dir, 'missing.lip'), dir] {
198+ lip_load(p) or {
199+ assert err.msg().starts_with('${p}: '), err.msg()
200+ assert !err.msg().contains('defpkgbuild'), err.msg()
201+ continue
202+ }
203+ assert false, '${p} loaded'
204+ }
205+ // two forms in a readable file are still the one-form error
206+ two := os.join_path(dir, 'two.lip')
207+ os.write_file(two, '(defpkgbuild foo\n)\n(defpkgbuild bar\n)')!
208+ lip_load(two) or {
209+ assert err.msg().contains('one (defpkgbuild ...) form per file, not 2'), err.msg()
210+ return
211+ }
212+ assert false, 'two forms loaded'
213+}
214+
215+// read_items reads what lip_items_of makes of a blip expression's value
216+fn read_items(src string) ![]string {
217+ mut m := lip_new_machine()!
218+ return lip_items_of(m.run_str(src)!, 'depends')!
219+}
220+
221+fn test_lip_items_of_every_spelling() ! {
222+ // one item, as a string, a keyword or a symbol
223+ assert read_items('"glibc"')! == ['glibc']
224+ assert read_items(':any')! == ['any']
225+ assert read_items("'zsh")! == ['zsh']
226+ // a quoted list, a vector, and the empty one
227+ assert read_items('\'("a" "b" :c)')! == ['a', 'b', 'c']
228+ assert read_items('["a" "b" :c]')! == ['a', 'b', 'c']
229+ assert read_items("'()")! == []string{}
230+ assert read_items('[]')! == []string{}
231+ // a list's items are plain: a number among them is said, in both kinds
232+ for src in ['\'("a" 1)', '["a" 1]'] {
233+ read_items(src) or {
234+ assert err.msg().contains('items must be strings or keywords'), err.msg()
235+ continue
236+ }
237+ assert false, '${src} was read'
238+ }
239+ // a dotted tail is no list: its last item would be dropped silently.
240+ // blip's reader has no dotted syntax ('.' is a symbol), so cons makes one
241+ read_items('(cons "a" "b")') or {
242+ assert err.msg().contains('a list ends in ()'), err.msg()
243+ return
244+ }
245+ assert false, 'a dotted list was read'
246+}
247+
248+fn test_lip_vector_lists_reach_the_pkgbuild() ! {
249+ dir := os.join_path(os.vtmp_dir(), 'vpac_lip_vector_${os.getpid()}')
250+ os.mkdir_all(dir)!
251+ defer {
252+ os.rmdir_all(dir) or {}
253+ }
254+ // the lists spelled as vectors, where the golden lip quotes them
255+ lip := os.join_path(dir, 'vec.lip')
256+ lines := [
257+ '(defpkgbuild vec',
258+ ' :pkgname "vec"',
259+ ' :pkgver "1.0"',
260+ ' :pkgrel 1',
261+ ' :pkgdesc "vector lists"',
262+ ' :arch [:any]',
263+ ' :depends ["glibc" "zsh"]',
264+ ' :license ["MIT"]',
265+ ' :build (lambda () (run "true"))',
266+ ' :package (lambda () (run "true")))',
267+ ]
268+ os.write_file(lip, lines.join('\n'))!
269+ bb := lip_make(lip, '/vpac/runner')!
270+ // the generator writes an array an item a line
271+ assert bb.text.contains("depends=(\n 'glibc'\n 'zsh'\n)"), bb.text
272+ assert bb.text.contains("arch=(\n 'any'\n)"), bb.text
273+ assert bb.text.contains("license=(\n 'MIT'\n)"), bb.text
274+}
275+
276+// valid_lip is a lip every field of which is right; the corpus below breaks
277+// one thing at a time
278+const valid_lip = ['(defpkgbuild corpus', ' :pkgname "corpus"', ' :pkgver "1.0"', ' :pkgrel 1',
279+ ' :pkgdesc "a corpus base"', " :arch '(:any)", ' :build (lambda () (run "true"))',
280+ ' :package (lambda () (run "true")))']
281+
282+// LipCase is a lip broken one way, and what the validator says about it
283+struct LipCase {
284+ what string
285+ text string
286+ says string
287+}
288+
289+// broken replaces the line of valid_lip that starts with key's spelling, or
290+// appends extra before the closing parenthesis when key is ''
291+fn broken(key string, line string) string {
292+ mut lines := valid_lip.clone()
293+ if key == '' {
294+ // the last line ends in defpkgbuild's own ')': the new line takes it
295+ last := lines[lines.len - 1]
296+ lines[lines.len - 1] = last[..last.len - 1]
297+ lines << line + ')'
298+ return lines.join('\n')
299+ }
300+ for i, l in lines {
301+ if l.trim_space().starts_with(':${key} ') {
302+ lines[i] = line
303+ if i == lines.len - 1 {
304+ lines[i] += ')'
305+ }
306+ }
307+ }
308+ return lines.join('\n')
309+}
310+
311+fn test_lip_validation_corpus() ! {
312+ dir := os.join_path(os.vtmp_dir(), 'vpac_lip_corpus_${os.getpid()}')
313+ os.mkdir_all(dir)!
314+ defer {
315+ os.rmdir_all(dir) or {}
316+ }
317+ // the base itself is good
318+ base := os.join_path(dir, 'base.lip')
319+ os.write_file(base, valid_lip.join('\n'))!
320+ lip_make(base, '/vpac/runner')!
321+
322+ hex64 := 'ab'.repeat(32)
323+ for c in [
324+ LipCase{'no name', '(defpkgbuild)', 'needs the name'},
325+ LipCase{'a number for a name', valid_lip.join('\n').replace('(defpkgbuild corpus', '(defpkgbuild 7'), 'the name is a symbol or a string, not'},
326+ LipCase{'a key without its value', broken('', ' :url'), ':key and value come in pairs'},
327+ LipCase{'a value where a key goes', broken('', ' "stray" "pair"'), 'expected a :key, got "stray"'},
328+ LipCase{'a key twice', broken('', ' :pkgrel 2'), ':pkgrel is set twice'},
329+ LipCase{'an empty name list', broken('pkgname', " :pkgname '()"), ':pkgname must not be empty'},
330+ LipCase{'a name with a space', broken('pkgname', ' :pkgname "cor pus"'), 'has whitespace in it'},
331+ LipCase{'no arch', broken('arch', " :arch '()"), ':arch must not be empty'},
332+ LipCase{'a short b2sum', broken('', ' :b2sums \'("abc")'), 'b2sums: abc is 3 characters; b2sums entries are 128 hex characters or SKIP'},
333+ LipCase{'a sha256 that is not hex', broken('', ' :sha256sums \'("${'zz'.repeat(32)}")'), 'has a character that is not hex (z)'},
334+ LipCase{'a short fingerprint', broken('', ' :validpgpkeys \'("ABCDEF")'), 'validpgpkeys: entry 0 is 6 characters'},
335+ LipCase{'a lowercase fingerprint', broken('', ' :validpgpkeys \'("${'ab'.repeat(20)}")'), 'uppercase fingerprints only'},
336+ LipCase{'an absolute backup', broken('', ' :backup \'("/etc/x.conf")'), 'is absolute; backup paths are relative'},
337+ LipCase{'a phase that is no lambda', broken('build', ' :build "make"'), ':build must be a (lambda ...)'},
338+ LipCase{'a phase with a parameter', broken('build', ' :build (lambda (x) (run "true"))'), ':build takes 0 parameters, not 1'},
339+ LipCase{'a hook with no version', broken('', ' :post-install (lambda () (run "true"))'), ':post-install takes 1 parameter, not 0'},
340+ LipCase{'an upgrade hook with one version', broken('', ' :post-upgrade (lambda (new) (run "true"))'), ':post-upgrade takes 2 parameters, not 1'},
341+ LipCase{'a pkgver that is a number', broken('pkgver', ' :pkgver 3'), ':pkgver must be a string or a (lambda ...)'},
342+ LipCase{'a pkgrel in quotes', broken('pkgrel', ' :pkgrel "1"'), ':pkgrel must be an integer'},
343+ LipCase{'a negative epoch', broken('', ' :epoch -1'), 'epoch is negative'},
344+ LipCase{'a pkgdesc that is a number', broken('pkgdesc', ' :pkgdesc 5'), ':pkgdesc must be a string'},
345+ LipCase{'an unknown key', broken('', ' :pkgdescription "x"'), 'has no key :pkgdescription'},
346+ LipCase{'a dotted list', broken('', ' :depends (cons "a" "b")'), 'a list ends in ()'},
347+ LipCase{'no pkgdesc', broken('pkgdesc', ''), ':pkgdesc is required'},
348+ LipCase{'no package', broken('package', ' :url "https://example.org"'), ':package is required'},
349+ ] {
350+ p := os.join_path(dir, 'case.lip')
351+ os.write_file(p, c.text)!
352+ lip_make(p, '/vpac/runner') or {
353+ assert err.msg().contains(c.says), '${c.what}: ${err.msg()}'
354+ continue
355+ }
356+ assert false, '${c.what} was taken:\n${c.text}'
357+ }
358+ // the right lengths and SKIP pass
359+ ok := os.join_path(dir, 'sums.lip')
360+ os.write_file(ok, broken('', ' :sha256sums \'("${hex64}" "SKIP")'))!
361+ lip_make(ok, '/vpac/runner')!
362+}
363+
364+fn test_lip_make_split_golden() ! {
365+ // the split smoke package: two pkgnames, one shared package lambda that
366+ // asks (this-pkg) which split it runs for
367+ lip := os.join_path(@VMODROOT, 'pkgs', 'lipsplit', 'PKGBUILD.lip')
368+ bb := lip_make(lip, '/vpac/runner')!
369+ assert bb.base == 'lipsplit'
370+ assert bb.text.contains("pkgbase='lipsplit'"), bb.text
371+ assert bb.text.contains("pkgname=(\n 'lipsplit'\n 'lipsplit-doc'\n)"), bb.text
372+ // one package function per split, named as makepkg calls it
373+ // (package_$pkgname, the hyphen and all), each running the shared lambda
374+ for name in ['lipsplit', 'lipsplit-doc'] {
375+ assert bb.text.contains('package_${name}() {'), bb.text
376+ }
377+ assert !bb.text.contains('\npackage() {'), bb.text
378+ // no build phase in the lip: none in the PKGBUILD, which makepkg allows
379+ assert !bb.text.contains('build() {'), bb.text
380+ assert bb.install == ''
381+}
382+
383+fn test_lip_without_a_build_phase() ! {
384+ // a data package: no :build, as makepkg allows; the PKGBUILD gets no
385+ // build() wrapper, and still its package()
386+ dir := os.join_path(os.vtmp_dir(), 'vpac_lip_nobuild_${os.getpid()}')
387+ os.mkdir_all(dir)!
388+ defer {
389+ os.rmdir_all(dir) or {}
390+ }
391+ p := os.join_path(dir, 'data.lip')
392+ os.write_file(p, broken('build', ''))!
393+ bb := lip_make(p, '/vpac/runner')!
394+ assert !bb.text.contains('build() {'), bb.text
395+ assert bb.text.contains('package() {'), bb.text
396+}
@@ -0,0 +1,461 @@
1+module vmakepkg
2+
3+import os
4+import blip.vlib.blip
5+
6+// ------------------------------------------------------------ PKGBUILD.vsh
7+//
8+// PKGBUILD.vsh is the same package written as a plain V script, with the
9+// phases as ordinary V functions:
10+//
11+// import vmakepkg
12+// import os
13+//
14+// fn spec() !vmakepkg.Spec {
15+// return vmakepkg.Spec{
16+// pkgname: 'foobar'
17+// pkgver: '2.5'
18+// pkgrel: 2
19+// pkgdesc: 'Text editor for X11'
20+// arch: ['x86_64']
21+// url: 'https://example.com/foobar/'
22+// license: 'Apache-2.0'
23+// depends: ['glibc']
24+// options: ['!strip' 'docs']
25+// source: ['foobar-2.5.tar.gz::https://example.com/2.5.tar.gz']
26+// b2sums: ['...']
27+// hooks: ['post-install']
28+// }
29+// }
30+//
31+// fn build() ! {
32+// vmakepkg.run('cmake -B build -DCMAKE_INSTALL_PREFIX=/usr')!
33+// vmakepkg.run('cmake --build build')!
34+// }
35+//
36+// fn package() ! {
37+// vmakepkg.run('cmake --install build DESTDIR=' + vmakepkg.pkgdir()!)!
38+// }
39+//
40+// fn post_install(v []string) ! {
41+// println('hint: run foobar-setup once')
42+// }
43+//
44+// vmakepkg.vsh_entry(
45+// spec: spec
46+// build: build
47+// package: package
48+// hooks: {'post-install': post_install}
49+// ) or { eprintln(err); exit(1) }
50+//
51+// `v run PKGBUILD.vsh generate` writes the PKGBUILD (and the .install
52+// beside the script), with the same head validation and phase wrappers the
53+// lip format gets, delegating to `v run PKGBUILD.vsh <phase>`. a
54+// `pkgver: fn () string` in the entry makes it a VCS package the same way a
55+// pkgver lambda does for the lip.
56+//
57+// the writers for the phases are the runners' own helpers: vmakepkg.run
58+// shells a line out with makepkg's spellings restored, vmakepkg.pkgdir and
59+// friends read the values makepkg exported for the running phase.
60+
61+// Spec is a vsh package's head, the same fields the lip format reads
62+pub struct Spec {
63+pub mut:
64+ pkgname string
65+ pkgnames []string
66+ pkgver string
67+ pkgrel i64
68+ epoch i64
69+ pkgdesc string
70+ arch []string
71+ url string
72+ license string
73+ depends []string
74+ makedepends []string
75+ checkdepends []string
76+ optdepends []string
77+ provides []string
78+ conflicts []string
79+ backup []string
80+ options []string
81+ source []string
82+ validpgpkeys []string
83+ b2sums []string
84+ sha256sums []string
85+ hooks []string
86+}
87+
88+// spec_names reads pkgname from a spec: the bare name or the split list.
89+// both spellings together are one intent, so the same name is not repeated,
90+// the order of first mention kept
91+fn spec_names(s &Spec) ![]string {
92+ mut named := []string{}
93+ if s.pkgname != '' {
94+ named << s.pkgname
95+ }
96+ named << s.pkgnames
97+ mut out := []string{}
98+ for it in named {
99+ if it in out {
100+ continue
101+ }
102+ out << it
103+ }
104+ if out.len == 0 {
105+ return error('pkgbuild: :pkgname is required')
106+ }
107+ for it in out {
108+ if it.contains(' ') {
109+ return error('pkgbuild :pkgname: "${it}" has whitespace in it')
110+ }
111+ }
112+ return out
113+}
114+
115+// lip_list wraps string items into a blip list, the shape the head reader
116+// walks for the array fields
117+fn lip_list(items []string) blip.Value {
118+ mut out := []blip.Value{}
119+ for it in items {
120+ out << blip.string(it)
121+ }
122+ return blip.list_from(out)
123+}
124+
125+// spec_meta hands the spec to the same head the lip format walks, as one
126+// struct value: the lists normalised, the sums and fingerprints checked, and
127+// the phases and hooks the script carries named, so lip_generate tells one
128+// truth about both kinds. `have` says which phases and hooks the entry
129+// carries, since the head only prints wrappers the script can answer
130+fn spec_meta(s &Spec, have map[string]bool) !blip.Value {
131+ mut vals := map[string]blip.Value{}
132+ names := spec_names(s)!
133+ // name is the pkgbase, the canonical first of the names: for a
134+ // split-only spec the bare pkgname spelling is empty and this is what
135+ // carries one
136+ vals['name'] = blip.string(names[0])
137+ vals['pkgname'] = lip_list(names)
138+ if s.pkgver != '' {
139+ vals['pkgver'] = blip.string(s.pkgver)
140+ }
141+ vals['pkgrel'] = blip.integer(s.pkgrel)
142+ // as the lip's :epoch: 0 means absent, and a negative one is a mistake
143+ // to say, not an epoch to leave out
144+ if s.epoch < 0 {
145+ return error('pkgbuild :epoch is negative; 0 means absent')
146+ }
147+ if s.epoch > 0 {
148+ vals['epoch'] = blip.integer(s.epoch)
149+ }
150+ if s.pkgdesc == '' {
151+ return error('pkgbuild: :pkgdesc is required')
152+ }
153+ vals['pkgdesc'] = blip.string(s.pkgdesc)
154+ if s.arch.len == 0 {
155+ return error('pkgbuild: :arch is required')
156+ }
157+ mut arches := []string{}
158+ for a in s.arch {
159+ arches << lip_arch(a)
160+ }
161+ vals['arch'] = lip_list(arches)
162+ if s.url != '' {
163+ vals['url'] = blip.string(s.url)
164+ }
165+ if s.license != '' {
166+ vals['license'] = blip.string(s.license)
167+ }
168+ map2 := {
169+ 'depends': s.depends
170+ 'makedepends': s.makedepends
171+ 'checkdepends': s.checkdepends
172+ 'optdepends': s.optdepends
173+ 'provides': s.provides
174+ 'conflicts': s.conflicts
175+ 'options': s.options
176+ 'source': s.source
177+ }
178+ for key, items in map2 {
179+ if items.len > 0 {
180+ vals[key] = lip_list(items)
181+ }
182+ }
183+ if s.backup.len > 0 {
184+ for b in s.backup {
185+ if b.starts_with('/') {
186+ return error('pkgbuild :backup: "${b}" is absolute; backup paths are relative, no leading slash')
187+ }
188+ }
189+ vals['backup'] = lip_list(s.backup)
190+ }
191+ if s.validpgpkeys.len > 0 {
192+ for i, k in s.validpgpkeys {
193+ lip_key40(k, i)!
194+ }
195+ vals['validpgpkeys'] = lip_list(s.validpgpkeys)
196+ }
197+ if s.b2sums.len > 0 {
198+ for it in s.b2sums {
199+ lip_hex(it, 128, 'b2sums')!
200+ }
201+ vals['b2sums'] = lip_list(s.b2sums)
202+ }
203+ if s.sha256sums.len > 0 {
204+ for it in s.sha256sums {
205+ lip_hex(it, 64, 'sha256sums')!
206+ }
207+ vals['sha256sums'] = lip_list(s.sha256sums)
208+ }
209+ for phase in ['prepare', 'build', 'check', 'package', 'pkgver'] {
210+ if have[phase] {
211+ vals[phase] = blip.nil_value()
212+ }
213+ }
214+ for h in s.hooks {
215+ if h !in lip_hooks {
216+ return error('pkgbuild hooks: :${h} is not a hook makepkg knows')
217+ }
218+ if !have[h] {
219+ return error('pkgbuild hooks: the entry holds no ${h} body')
220+ }
221+ vals[h] = blip.nil_value()
222+ }
223+ return blip.struct_value('pkgbuild', vals.keys(), vals)
224+}
225+
226+// lip_make_from_spec generates the PKGBUILD (and a .install when hooks are
227+// carried) from a PKGBUILD.vsh's spec and its entry's phase inventory,
228+// delegating the phases to `v run` against the script itself
229+pub fn lip_make_from_spec(s &Spec, runner string, script_path string, have map[string]bool) !LipBet {
230+ meta := spec_meta(s, have)!
231+ return lip_generate(meta, runner, script_path, .vsh)!
232+}
233+
234+// run shells one line out with sh, carrying makepkg's spellings of its state
235+// into the child shell, like the runner's (run) does from the lip side: the
236+// phase exported them for this process under the VPAC_ names
237+pub fn run(cmd string) ! {
238+ // the names reach the shell as env's arguments and the line as sh's: no
239+ // quoting stands between them and the child. the line itself is shell,
240+ // as the script writes it
241+ mut args := ['env']
242+ pairs := [['pkgdir', 'VPAC_PKGDIR'], ['srcdir', 'VPAC_SRCDIR'], ['startdir', 'VPAC_STARTDIR'],
243+ ['pkgname', 'VPAC_PKGNAME'], ['pkgver', 'VPAC_PKGVER']]
244+ for pair in pairs {
245+ v := os.getenv(pair[1])
246+ if v != '' {
247+ args << '${pair[0]}=${v}'
248+ }
249+ }
250+ args << ['sh', '-c', cmd]
251+ res := os.system_args(args)
252+ if res != 0 {
253+ return error('run: exit code ${res} from: ${cmd}')
254+ }
255+}
256+
257+// pkgdir is the directory makepkg is filling during the package phase, the
258+// value of $pkgdir, exported for the phase as VPAC_PKGDIR
259+pub fn pkgdir() !string {
260+ p := os.getenv('VPAC_PKGDIR')
261+ if p == '' {
262+ return error('pkgdir: the runner only exports it inside a makepkg phase')
263+ }
264+ return p
265+}
266+
267+// srcdir is where the sources were unpacked, $srcdir
268+pub fn srcdir() !string {
269+ p := os.getenv('VPAC_SRCDIR')
270+ if p == '' {
271+ return error('srcdir: the runner only exports it inside a makepkg phase')
272+ }
273+ return p
274+}
275+
276+// startdir is the build script's own directory, $startdir
277+pub fn startdir() !string {
278+ p := os.getenv('VPAC_STARTDIR')
279+ if p == '' {
280+ return error('startdir: the runner only exports it inside a makepkg phase')
281+ }
282+ return p
283+}
284+
285+// this_pkg is the split a shared package function is packing right now,
286+// $pkgname, exported for the phase as VPAC_PKGNAME
287+pub fn this_pkg() !string {
288+ p := os.getenv('VPAC_PKGNAME')
289+ if p == '' {
290+ return error('this_pkg: the runner only exports it inside a makepkg phase')
291+ }
292+ return p
293+}
294+
295+// glob spills one pattern into a sorted list of matches, empty when nothing
296+// matches
297+pub fn glob(pattern string) ![]string {
298+ return os.glob(pattern)!
299+}
300+
301+// git_desc runs git describe in the cwd the phase runs under (srcdir, where
302+// makepkg runs its phases); the fallback comes out verbatim when describe
303+// finds nothing, so a young tree still has a version before its first tag
304+pub fn git_desc(pattern string, fallback string) !string {
305+ res := os.exec(['git', '--no-pager', 'describe', '--long', '--tags', '--match', pattern])
306+ if res.exit_code != 0 {
307+ if fallback != '' {
308+ return fallback
309+ }
310+ return error('git-desc: git describe failed for ${pattern}: ${res.output.trim_space()}')
311+ }
312+ return res.output.trim_space()
313+}
314+
315+// VshEntry is what a PKGBUILD.vsh hands to vsh_entry: the spec, the phase
316+// functions, and the hooks by name. generate needs the spec, and makepkg
317+// needs package (build only when the package has one, as makepkg's build()):
318+// the entry says so if the script leaves one out
319+@[params]
320+pub struct VshEntry {
321+pub mut:
322+ spec ?fn () !Spec
323+ pkgver ?fn () string
324+ prepare ?fn () !
325+ build ?fn () !
326+ check ?fn () !
327+ package ?fn () !
328+ hooks map[string]fn ([]string) !
329+}
330+
331+// vsh_entry is the PKGBUILD.vsh runner, the script's one last line: with the
332+// generate argument it writes the PKGBUILD and the .install beside the
333+// script, and otherwise it runs one phase with the arguments pacman or the
334+// phase wrapper hands it. a failing phase exits nonzero, the way a makepkg
335+// phase would
336+pub fn vsh_entry(e VshEntry) ! {
337+ // VPAC_VSH_PATH carries the script's own path: `v run` does not say which
338+ // script called in a way the writer can trust
339+ vsh_run(e, os.args#[1..], os.getenv('VPAC_VSH_PATH'))!
340+}
341+
342+// vsh_run is vsh_entry with the command line and the script's path handed
343+// in: args are what follows the script's name, the phase first
344+fn vsh_run(e VshEntry, args []string, script_path string) ! {
345+ phase := if args.len > 0 { args[0] } else { '' }
346+ match phase {
347+ 'generate' {
348+ if script_path == '' {
349+ return error("generate: VPAC_VSH_PATH must hold the script's path")
350+ }
351+ spec := e.spec or { return error('pkgbuild: a :spec is required') }
352+ s := spec()!
353+ // build is optional, as makepkg's build() is; package is not
354+ if e.package == none {
355+ return error('pkgbuild: a :package phase is required')
356+ }
357+ if e.pkgver == none && s.pkgver == '' {
358+ return error('pkgbuild: :pkgver is required')
359+ }
360+ for h in s.hooks {
361+ if h !in e.hooks {
362+ return error('pkgbuild hooks: the entry holds no ${h} body')
363+ }
364+ }
365+ // hooks in the entry that the spec does not list stay a typo
366+ for name in e.hooks.keys() {
367+ if name !in s.hooks {
368+ return error('pkgbuild hooks: the spec does not list :${name}')
369+ }
370+ }
371+ mut have := map[string]bool{}
372+ if e.prepare != none {
373+ have['prepare'] = true
374+ }
375+ if e.pkgver != none {
376+ have['pkgver'] = true
377+ }
378+ for hook in e.hooks.keys() {
379+ have[hook] = true
380+ }
381+ if e.build != none {
382+ have['build'] = true
383+ }
384+ if e.check != none {
385+ have['check'] = true
386+ }
387+ // package is makepkg's ground truth, so its wrapper always lands
388+ have['package'] = true
389+ // the runner the wrappers bake is the persistent v, not this
390+ // process's temp binary: the root side carries it as VPAC_V
391+ vpath := if os.getenv('VPAC_V') != '' {
392+ os.getenv('VPAC_V')
393+ } else {
394+ os.find_abs_path_of_executable('v') or {
395+ return error('generate: the v compiler is not in the path')
396+ }
397+ }
398+ bb := lip_make_from_spec(s, vpath, script_path, have)!
399+ out_dir := os.dir(script_path)
400+ os.write_file('${out_dir}/PKGBUILD', bb.text)!
401+ if bb.install != '' {
402+ os.write_file('${out_dir}/${bb.base}.install', bb.install)!
403+ }
404+ mut wrote := '${out_dir}/PKGBUILD'
405+ if bb.install != '' {
406+ wrote += ' and ${bb.base}.install'
407+ }
408+ println('wrote ${wrote}')
409+ }
410+ 'pkgver' {
411+ if f := e.pkgver {
412+ out := f()
413+ if out == '' {
414+ return error('pkgver: it returned an empty version')
415+ }
416+ println(out)
417+ } else {
418+ return error('pkgver: the entry holds no pkgver function')
419+ }
420+ }
421+ 'prepare' {
422+ if f := e.prepare {
423+ f()!
424+ } else {
425+ return error('prepare: the entry holds no prepare function')
426+ }
427+ }
428+ 'build' {
429+ if f := e.build {
430+ f()!
431+ } else {
432+ return error('build: the entry holds no build function')
433+ }
434+ }
435+ 'check' {
436+ if f := e.check {
437+ f()!
438+ } else {
439+ return error('check: the entry holds no check function')
440+ }
441+ }
442+ 'package' {
443+ if f := e.package {
444+ f()!
445+ } else {
446+ return error('package: the entry holds no package function')
447+ }
448+ }
449+ else {
450+ // no argument: the usage, not a call that lost its phase quietly
451+ if phase == '' {
452+ return error('vsh: give an argument: generate to write the PKGBUILD, or one of the phases (build, check, package, pkgver) or hooks')
453+ }
454+ if phase in e.hooks {
455+ e.hooks[phase](args[1..])!
456+ return
457+ }
458+ return error('vsh: "${phase}" is neither generate, a phase, nor a hook')
459+ }
460+ }
461+}
@@ -0,0 +1,358 @@
1+module vmakepkg
2+
3+import os
4+
5+// spec_names is the bare pkgname or the split list: both spellings together
6+// name one intent, so nothing is named twice, and the first mention's place
7+// is kept
8+fn test_spec_names() ! {
9+ // the usual spellings, alone and split
10+ assert spec_names(&Spec{ pkgname: 'foobar' })! == ['foobar']
11+ assert spec_names(&Spec{ pkgnames: ['foo', 'bar'] })! == ['foo', 'bar']
12+ // a bare name repeated in the split list is one name
13+ assert spec_names(&Spec{ pkgname: 'foo', pkgnames: ['foo', 'bar'] })! == ['foo', 'bar']
14+ // and a split list of repeats is one each, in first-mention order
15+ assert spec_names(&Spec{ pkgnames: ['a', 'b', 'a', 'c', 'b'] })! == ['a', 'b', 'c']
16+ // white space in a name is a mistake the lip format refuses too
17+ if _ := spec_names(&Spec{ pkgname: 'foo bar' }) {
18+ assert false, 'a name with whitespace was taken'
19+ } else {
20+ assert err.msg().contains('whitespace'), err.msg()
21+ }
22+}
23+
24+// no name at all is no package
25+fn test_spec_names_requires_a_name() {
26+ if _ := spec_names(&Spec{ pkgnames: []string{} }) {
27+ assert false, 'a nameless spec was taken'
28+ } else {
29+ assert err.msg().contains('pkgname is required'), err.msg()
30+ }
31+}
32+
33+// spec_meta's name is the pkgbase, the first of the canonical names: for a
34+// split-only spec the bare pkgname spelling is empty, and this is what
35+// carries one
36+fn test_spec_meta_name_is_the_pkgbase() ! {
37+ mut s := Spec{
38+ pkgnames: ['pkg-a', 'pkg-b']
39+ pkgver: '2.5'
40+ pkgrel: 2
41+ pkgdesc: 'a split package'
42+ arch: ['any']
43+ }
44+ have := map[string]bool{
45+ 'build': true
46+ 'package': true
47+ }
48+ meta := spec_meta(&s, have)!
49+ st := meta.as_struct()
50+ // the head walks a list for :pkgname; name stays the base
51+ names := lip_items_of(st.get('pkgname'), 'pkgname')!
52+ assert names == ['pkg-a', 'pkg-b']
53+ assert st.get('name').as_string() == 'pkg-a'
54+}
55+
56+// Calls records which of an entry's functions ran, with what
57+@[heap]
58+struct Calls {
59+mut:
60+ ran []string
61+ args []string
62+}
63+
64+// recording_entry is an entry whose every phase and hook records itself;
65+// fail names the one phase that fails instead
66+fn recording_entry(mut c Calls, fail string) VshEntry {
67+ return VshEntry{
68+ spec: fn () !Spec {
69+ return Spec{
70+ pkgname: 'rec'
71+ pkgver: '1.0'
72+ pkgrel: 1
73+ pkgdesc: 'records its phases'
74+ arch: ['any']
75+ hooks: ['post-install']
76+ }
77+ }
78+ prepare: fn [mut c, fail] () ! {
79+ c.ran << 'prepare'
80+ if fail == 'prepare' {
81+ return error('prepare broke')
82+ }
83+ }
84+ build: fn [mut c, fail] () ! {
85+ c.ran << 'build'
86+ if fail == 'build' {
87+ return error('build broke')
88+ }
89+ }
90+ check: fn [mut c] () ! {
91+ c.ran << 'check'
92+ }
93+ package: fn [mut c] () ! {
94+ c.ran << 'package'
95+ }
96+ hooks: {
97+ 'post-install': fn [mut c] (args []string) ! {
98+ c.ran << 'post-install'
99+ c.args << args
100+ }
101+ }
102+ }
103+}
104+
105+fn test_vsh_run_dispatches_every_phase() ! {
106+ for phase in ['prepare', 'build', 'check', 'package'] {
107+ mut c := &Calls{}
108+ vsh_run(recording_entry(mut c, ''), [phase], '')!
109+ // the phase asked for, and nothing else
110+ assert c.ran == [phase]
111+ }
112+ // a hook takes the arguments after its name, as pacman hands them
113+ mut c := &Calls{}
114+ vsh_run(recording_entry(mut c, ''), ['post-install', '1.0-1', '0.9-1'], '')!
115+ assert c.ran == ['post-install']
116+ assert c.args == ['1.0-1', '0.9-1']
117+}
118+
119+fn test_vsh_run_phase_failures() {
120+ // a failing phase fails the run, so makepkg stops as it would
121+ mut c := &Calls{}
122+ vsh_run(recording_entry(mut c, 'build'), ['build'], '') or {
123+ assert err.msg() == 'build broke'
124+ assert c.ran == ['build']
125+ return
126+ }
127+ assert false, 'a failing build passed'
128+}
129+
130+fn test_vsh_run_missing_and_unknown() {
131+ // a phase the entry holds no function for, a name that is nothing, and
132+ // no name at all: each says so, nothing runs
133+ empty := VshEntry{}
134+ for phase, says in {
135+ 'prepare': 'prepare: the entry holds no prepare function'
136+ 'build': 'build: the entry holds no build function'
137+ 'check': 'check: the entry holds no check function'
138+ 'package': 'package: the entry holds no package function'
139+ 'pkgver': 'pkgver: the entry holds no pkgver function'
140+ 'post-remove': 'vsh: "post-remove" is neither generate, a phase, nor a hook'
141+ '': 'vsh: give an argument'
142+ } {
143+ args := if phase == '' { []string{} } else { [phase] }
144+ vsh_run(empty, args, '') or {
145+ assert err.msg().starts_with(says), err.msg()
146+ continue
147+ }
148+ assert false, '${phase} ran on an empty entry'
149+ }
150+}
151+
152+fn test_vsh_run_pkgver() ! {
153+ // pkgver prints the version the function computes; an empty one is a
154+ // mistake makepkg would turn into a broken package name
155+ out := capture_stdout(fn () ! {
156+ vsh_run(VshEntry{
157+ pkgver: fn () string {
158+ return '2.1.r3.gabc'
159+ }
160+ }, ['pkgver'], '')!
161+ })!
162+ assert out == '2.1.r3.gabc\n'
163+ vsh_run(VshEntry{
164+ pkgver: fn () string {
165+ return ''
166+ }
167+ }, ['pkgver'], '') or {
168+ assert err.msg() == 'pkgver: it returned an empty version'
169+ return
170+ }
171+ assert false, 'an empty pkgver passed'
172+}
173+
174+fn test_vsh_run_generate() ! {
175+ dir := os.join_path(os.vtmp_dir(), 'vpac_vsh_generate_${os.getpid()}')
176+ os.mkdir_all(dir)!
177+ defer { os.rmdir_all(dir) or {} }
178+ script := os.join_path(dir, 'PKGBUILD.vsh')
179+ os.write_file(script, '// the script')!
180+ saved := os.getenv('VPAC_V')
181+ defer { os.setenv('VPAC_V', saved, true) }
182+ os.setenv('VPAC_V', '/usr/bin/v', true)
183+ mut c := &Calls{}
184+ entry := recording_entry(mut c, '')
185+ // generate writes the PKGBUILD, and the .install its hooks need, beside
186+ // the script, and runs no phase
187+ capture_stdout(fn [entry, script] () ! {
188+ vsh_run(entry, ['generate'], script)!
189+ })!
190+ assert c.ran.len == 0
191+ pkgbuild := os.read_file(os.join_path(dir, 'PKGBUILD'))!
192+ assert pkgbuild.contains("pkgname='rec'"), pkgbuild
193+ for phase in ['prepare', 'build', 'check', 'package'] {
194+ assert pkgbuild.contains('${phase}() {'), phase
195+ }
196+ assert os.exists(os.join_path(dir, 'rec.install'))
197+ // without the script's path there is nowhere to write
198+ vsh_run(entry, ['generate'], '') or {
199+ assert err.msg().contains('VPAC_VSH_PATH')
200+ return
201+ }
202+ assert false, 'generate ran without a script path'
203+}
204+
205+// BadEntry is an entry generate refuses, and what it says
206+struct BadEntry {
207+ e VshEntry
208+ says string
209+}
210+
211+fn test_vsh_run_generate_checks_the_entry() ! {
212+ dir := os.join_path(os.vtmp_dir(), 'vpac_vsh_generate_bad_${os.getpid()}')
213+ os.mkdir_all(dir)!
214+ defer { os.rmdir_all(dir) or {} }
215+ script := os.join_path(dir, 'PKGBUILD.vsh')
216+ saved := os.getenv('VPAC_V')
217+ defer { os.setenv('VPAC_V', saved, true) }
218+ os.setenv('VPAC_V', '/usr/bin/v', true)
219+ spec := fn () !Spec {
220+ return Spec{
221+ pkgname: 'bad'
222+ pkgver: '1.0'
223+ pkgrel: 1
224+ pkgdesc: 'missing parts'
225+ arch: ['any']
226+ }
227+ }
228+ listed := fn () !Spec {
229+ return Spec{
230+ pkgname: 'bad'
231+ pkgver: '1.0'
232+ pkgrel: 1
233+ pkgdesc: 'a hook with no body'
234+ arch: ['any']
235+ hooks: ['post-install']
236+ }
237+ }
238+ nop := fn () ! {}
239+ hook := fn (_ []string) ! {}
240+ for t in [
241+ BadEntry{VshEntry{
242+ build: nop
243+ package: nop
244+ }, 'a :spec is required'},
245+ BadEntry{VshEntry{
246+ spec: spec
247+ build: nop
248+ }, 'a :package phase is required'},
249+ BadEntry{VshEntry{
250+ spec: spec
251+ build: nop
252+ package: nop
253+ hooks: {
254+ 'post-install': hook
255+ }
256+ }, 'the spec does not list :post-install'},
257+ BadEntry{VshEntry{
258+ spec: listed
259+ build: nop
260+ package: nop
261+ }, 'the entry holds no post-install body'},
262+ ] {
263+ vsh_run(t.e, ['generate'], script) or {
264+ assert err.msg().contains(t.says), err.msg()
265+ continue
266+ }
267+ assert false, 'generate took an entry it should refuse: ${t.says}'
268+ }
269+ // and it wrote nothing for any of them
270+ assert !os.exists(os.join_path(dir, 'PKGBUILD'))
271+}
272+
273+// capture_stdout runs f with fd 1 going to a file, and returns what came
274+fn capture_stdout(f fn () !) !string {
275+ path := os.join_path(os.vtmp_dir(), 'vpac_vsh_out_${os.getpid()}')
276+ mut file := os.create(path)!
277+ defer { os.rm(path) or {} }
278+ saved := C.dup(1)
279+ if saved < 0 {
280+ return error('could not save stdout')
281+ }
282+ C.fflush(C.stdout)
283+ C.dup2(file.fd, 1)
284+ mut failure := ''
285+ f() or { failure = err.msg() }
286+ C.fflush(C.stdout)
287+ C.dup2(saved, 1)
288+ C.close(saved)
289+ file.close()
290+ if failure != '' {
291+ return error(failure)
292+ }
293+ return os.read_file(path)!
294+}
295+
296+fn test_vsh_run_generate_without_build() ! {
297+ // no build phase, as makepkg allows: the PKGBUILD has no build() and
298+ // still its package()
299+ dir := os.join_path(os.vtmp_dir(), 'vpac_vsh_nobuild_${os.getpid()}')
300+ os.mkdir_all(dir)!
301+ defer { os.rmdir_all(dir) or {} }
302+ script := os.join_path(dir, 'PKGBUILD.vsh')
303+ saved := os.getenv('VPAC_V')
304+ defer { os.setenv('VPAC_V', saved, true) }
305+ os.setenv('VPAC_V', '/usr/bin/v', true)
306+ entry := VshEntry{
307+ spec: fn () !Spec {
308+ return Spec{
309+ pkgname: 'data'
310+ pkgver: '1.0'
311+ pkgrel: 1
312+ pkgdesc: 'files only'
313+ arch: ['any']
314+ }
315+ }
316+ package: fn () ! {}
317+ }
318+ capture_stdout(fn [entry, script] () ! {
319+ vsh_run(entry, ['generate'], script)!
320+ })!
321+ pkgbuild := os.read_file(os.join_path(dir, 'PKGBUILD'))!
322+ assert !pkgbuild.contains('build() {'), pkgbuild
323+ assert pkgbuild.contains('package() {'), pkgbuild
324+}
325+
326+fn test_spec_epoch_edges() ! {
327+ base := Spec{
328+ pkgname: 'ep'
329+ pkgver: '1.0'
330+ pkgrel: 1
331+ pkgdesc: 'epochs'
332+ arch: ['any']
333+ }
334+ have := {
335+ 'package': true
336+ }
337+ // absent and 0 are the same: no epoch in the head
338+ zero := spec_meta(&base, have)!
339+ assert !zero.as_struct().has('epoch')
340+ // a positive one is carried as it is
341+ three := spec_meta(&Spec{
342+ ...base
343+ epoch: 3
344+ }, have)!
345+ assert three.as_struct().get('epoch').as_int() == 3
346+ // a negative one is said, as the lip's :epoch says it, not dropped
347+ for bad in [-1, -100] {
348+ if _ := spec_meta(&Spec{
349+ ...base
350+ epoch: bad
351+ }, have)
352+ {
353+ assert false, 'epoch ${bad} was taken'
354+ } else {
355+ assert err.msg() == 'pkgbuild :epoch is negative; 0 means absent', err.msg()
356+ }
357+ }
358+}