finish transition to Vile
@@ -2,8 +2,7 @@
22
33for agents landing in this repository cold.
44
5-vpac is a package manager written in V on top of the native `alpm` engine
6-in alpm.v, which follows pacman/libalpm behavior. it is a frontend of its own — its own listings, prompts,
5+vpac is a package manager written in V on top of the native `nspkg` engine, which follows pacman/libalpm behavior. it is a frontend of its own — its own listings, prompts,
76progress drawing, and a json event protocol for other frontends — with a
87config file of its own, and two package sources beyond the sync dbs: the
98pkgbuild repos and arbitrary git repos built with vpac itself.
@@ -17,16 +16,16 @@ src/cli.v argument parsing and mode dispatch. modes: s q w n m b i r u
1716 l o d c t a k v f (search info which deptest mark build
1817 install remove upgrade files owner orphans clean tree
1918 autoremove rank verify find).
20-src/config.v the configuration. the forms (path pkg network rank pkgbuild
19+src/config.v the configuration. Vile assignments such as network-connections = 3 use the forms (path pkg network rank pkgbuild
2120 options search clean tree color progress spinner
22- mirrorlist repo) are read from a blip file, /etc/vpac.d/config.lip by
21+ mirrorlist repo) are read by stutter through Vile, /etc/vpac.d/config.vile by
2322 default, and every setting keeps a __global here.
2423src/trans.v transaction begin/prepare/commit/cleanup and the interrupt
2524 handler. src/db.v holds the db paths, repo registration and
2625 freshness; src/db_check.v is verify's -D modes.
2726src/ipc.v --ui ipc: the event protocol (one json object per line) and
2827 the prompter a frontend answers questions with.
29-src/ui.v the shared progress display and callback wiring for alpm.v;
28+src/ui.v the shared progress display and callback wiring for nspkg;
3029 src/prompt.v the terminal's side of every question.
3130(the rest of src/)
3231 one file per command. install is remote.v, and remove.v
@@ -35,11 +34,10 @@ src/ui.v the shared progress display and callback wiring for alpm.v;
3534 verify_full.v check the disk; pkgbuild.v pkgbuild_install.v
3635 build_repo.v mirrors.v privilege.v are the network- and
3736 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
37+vmakepkg/ builds PKGBUILD.vile, PKGBUILD.scm and PKGBUILD.vsh directly
38+ as the invoking user. native phases pass literal argv and native
39+ .NSPKG-HOOK executables run inside the nspkg transaction root.
40+pkgs/ tiny packages vpac itself builds as smoke tests of the
4341 vmakepkg formats.
4442src/*_test.v, vmakepkg/*_test.v the tests.
4543src/testdb/ a module only the tests import: the one writer of libalpm
@@ -49,16 +47,19 @@ src/testdb/ a module only the tests import: the one writer of libalpm
4947
5048## the cross-references, and the rule about them
5149
52-the binary uses the native V module `alpm` (a file that begins `module alpm`),
53-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
50+the binary uses the native V module `nspkg` (a file that begins `module nspkg`),
51+evaluates its config through `stutter` and package recipes through `vile.scheme`,
52+and reuses this repo's own `vmakepkg`. Vile and stutter are local development
53+checkouts, not released modules. Vile needs a V development toolchain with
54+its arena APIs. these dependencies live outside the repository: on a machine,
55+V finds them under its module
5656directory (typically ~/.vmodules), often as symlinks to checkouts beside vpac.
57-the native backend uses libarchive, curl, GPGME/GnuPG, seccomp on Linux and libc;
58-production builds have no libalpm header or link dependency. alpm.v keeps its C
57+the native backend uses libarchive, GPGME/GnuPG, seccomp on Linux and libc.
58+its downloader uses V by default and libcurl with `-d nspkg_libcurl`;
59+production builds have no libalpm header or link dependency. nspkg keeps its C
5960reference under tests/coracle; never substitute it for the production backend.
6061
61-- if a build cannot resolve `alpm`, `blip` or `vmakepkg`, find where those
62+- if a build cannot resolve `nspkg`, `vile`, `stutter` or `vmakepkg`, find where those
6263 checkouts are on this machine (ask, or look in V's module directory) —
6364 never stub a missing module or patch a module cache to make it work.
6465- parity questions ("what does pacman do?", "is this libalpm behavior?") are
@@ -91,9 +92,9 @@ reference under tests/coracle; never substitute it for the production backend.
9192 pacman or posix cross-reference, the data's shape — not what the line does.
9293 when you change behavior, move the comment with it.
9394- error discipline: no panics behind doors a user walks through; every
94- alpm call's error is handled; a housekeeping failure the run goes on
95+ nspkg call's error is handled; a housekeeping failure the run goes on
9596 from (a handle's release, a temp dir's removal) is not `or {}` but
96- `or { went_on('release the alpm handle', err) }`, which --verbose says;
97+ `or { went_on('release the nspkg handle', err) }`, which --verbose says;
9798 ?T (may be none) and !T (may fail) are unwrapped with their own syntax
9899 and are not interchangeable.
99100- identifiers snake_case, files named for their one concern. the formatter
@@ -132,17 +133,16 @@ reference under tests/coracle; never substitute it for the production backend.
132133 event whose shape a reader must know about bumps it. once ipc_start ran,
133134 plain prints never touch stdout — they are led to stderr, so the channel
134135 stays whole json lines.
135-- the config can hold packages (pkg :hold): the check runs on the targets
136+- the config can hold packages (pkg #:hold): the check runs on the targets
136137 and again on the transaction's final victim set, after prepare.
137138- modes that change the system re-execute themselves as root through the
138- root provider (the config's options :root: sudo by default, any command
139+ root provider (the config's options #:root: sudo by default, any command
139140 that runs its arguments as root; su and pkexec are known by name),
140141 carrying the config and the invoker's name across (VPAC_INVOKER, VPAC_V).
141142 pkgbuild builds and
142- the build mode run as that invoking user, never as root. --lip-run is vpac
143- internal: the entry generated PKGBUILDs call back through, not a mode.
144-- read-only modes may open a lean alpm.initialize handle; anything that
145- writes goes through init_handle so alpm's callbacks and the
143+ the build mode run as that invoking user, never as root. native Scheme and Vile phases run through vpac’s internal --recipe-run entry.
144+- read-only modes may open a lean nspkg.initialize handle; anything that
145+ writes goes through init_handle so nspkg's callbacks and the
146146 configured siglevel, cachedirs, ignores and parallelism attach.
147147
148148## the issue tracker
@@ -1,6 +1,6 @@
11## introduction
22
3-[vpac](https://vpac.vorelabs.dev/) is a *versatile* package manager using [alpm](https://git.vorelabs.dev/vorelabs/alpm), following pacman/libalpm behavior.
3+[vpac](https://vpac.vorelabs.dev/) is a *versatile* package manager using [nspkg](https://git.vorelabs.dev/vorelabs/alpm), following pacman/libalpm behavior.
44
55## features
66
@@ -12,17 +12,15 @@ vpac not only posses full pacman parity, but also extends on top of it:
1212- 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`)
1313- file lookup in the sync file dbs (`vpac f`), with regular expressions too
1414- a json event protocol for other frontends (`--ui ipc`)
15-- config file, written in [blip](https://git.vorelabs.dev/vorelabs/blip), that allows for powerful configuration
15+- configuration programs evaluated by Vile
1616
1717## installation
1818
19-> WARNING: broken as of now due to blip introducting breaking changes. vpac is currently being migrated over to a more fit lisp dialect.
20-
2119#### prerequisites
2220
2321[V](https://vlang.io/) (latest git),
24-[alpm](https://git.vorelabs.dev/vorelabs/alpm),
25-[blip](https://git.vorelabs.dev/vorelabs/blip)
22+[nspkg](https://gitly.divio.city/me/nspkg),
23+[stutter](https://gitly.divio.city/me/stutter)
2624
2725
2826```sh
@@ -30,7 +28,7 @@ vpac not only posses full pacman parity, but also extends on top of it:
3028git clone https://git.vorelabs.dev/vorelabs/vpac
3129cd vpac
3230
33-# asks a few questions, writes /etc/vpac.d/config.lip
31+# asks a few questions, writes /etc/vpac.d/config.vile
3432./install.vsh
3533
3634# builds vpac into ./vpac
@@ -43,36 +41,25 @@ ln -sf $PWD/vpac /usr/local/bin/vpac
41vpac k -w
142
243# search the sync databases
3-vpac s -r linux-lts
44+vpac s -r gcc
445
546```
647
748`install.vsh` also asks whether to keep vpac's database, cache, keys and hooks
849in pacman's directories, whether to add the distro's repo of 32-bit libraries
9-(`multilib` on arch, `lib32` on artix), and whether to turn alpm.v's download
50+(`multilib` on arch, `lib32` on artix), and whether to turn nspkg's download
1051sandbox off.
1152
12-answer no to the first only if you mean to keep vpac's state apart from
53+answer no to the pacman paths question if you mean to keep vpac's state apart from
1354pacman's: a separate database does not know the packages pacman installed.
1455
15-`v test src` and `v test vmakepkg` run the test suites.
16-
1756## docs
1857
19-see the [wiki](https://git.vorelabs.dev/vorelabs/vpac/wiki)
58+in the process of being reworked
2059
2160## coming soon
2261
2362- drop-in pacman shim
2463- configuration profils
2564- state snapshots
26-- extended flake-like makepkg
27-
28-## state
29-
30-an honest assessment of vpac's state:
31-
32-- [X] fully independent from upstream libalpm
33-- [X] good enough to keep along pacman
34-- [ ] can fully replace pacman
35-- [ ] can be installed on any compatible OS
65+- extended flake-like functionality
@@ -4,8 +4,8 @@ import os
44import term
55
66// install.vsh sets vpac's config up for a new user: it asks a few questions,
7-// then writes /etc/vpac.d/config.lip and the mirror file the config requires,
8-// /etc/vpac.d/mirrors/<os>.lip. the config stays in /etc/vpac.d whatever the
7+// then writes /etc/vpac.d/config.vile and the mirror file the config requires,
8+// /etc/vpac.d/mirrors/<os>.vile. the config stays in /etc/vpac.d whatever the
99// answers: the pacman choice only picks where the db, cache, keys, hooks and
1010// log live. VPAC_ETC writes the two files into another directory instead, a
1111// trial that needs no root and makes no directory outside it. the binary is
@@ -14,7 +14,7 @@ import term
1414const default_etc = '/etc/vpac.d'
1515
1616// distro is an os the config is written for: its name, which is also the rank
17-// name (mirrors/<name>.lip defines mirrors-<name>), its repos, and the url its
17+// name (mirrors/<name>.vile defines mirrors-<name>), its repos, and the url its
1818// mirrors start from, with the $repo and $arch placeholders left in it
1919struct Distro {
2020 name string
@@ -46,6 +46,9 @@ fn distros() []Distro {
4646 src: 'https://mirror.cachyos.org/repo/\$arch/\$repo'
4747 lib32: ''
4848 },
49+ Distro{
50+ name: 'vinix'
51+ },
4952 ]
5053}
5154
@@ -105,11 +108,11 @@ fn main() {
105108fn run() ! {
106109 trial := os.getenv('VPAC_ETC') != ''
107110 etc := if trial { os.getenv('VPAC_ETC') } else { default_etc }
108- config := os.join_path(etc, 'config.lip')
111+ config := os.join_path(etc, 'config.vile')
109112 mut replace := false
110113 if os.exists(config) {
111114 println('${config} exists.')
112- keep := ask_yes('replace it? the old file is kept as config.lip.old', false)!
115+ keep := ask_yes('replace it? the old file is kept as config.vile.old', false)!
113116 if !keep {
114117 println('kept ${config}: nothing changed')
115118 return
@@ -117,20 +120,26 @@ fn run() ! {
117120 replace = true
118121 }
119122
123+ detected := detect_distro()
124+ share_pacman := detected != 'vinix' && found('pacman')
125+ && ask_yes("pacman is installed: keep vpac's db, cache, keys, hooks and log in pacman's directories?", true)!
126+ distro := ask_choice('configure vpac for which os', distros().map(it.name), detected)!
127+ d := distro_named(distro)
128+ vinix := distro == 'vinix'
120129 mut paths := own_paths()
121- if found('pacman') {
122- if ask_yes("pacman is installed: keep vpac's db, cache, keys, hooks and log in pacman's directories?", true)! {
123- paths = pacman_paths()
124- } else {
125- println("note: vpac's own db starts empty and does not see the packages pacman installed")
130+ if vinix {
131+ paths = Paths{
132+ ...paths
133+ db: '/var/lib/vpac/db/'
126134 }
135+ println('Vinix uses /var/lib/vpac/root for payloads and /var/lib/vpac/db for its database.')
136+ } else if share_pacman {
137+ paths = pacman_paths()
127138 } else {
128- 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")
139+ println("using vpac's own directories and package database")
129140 }
130141
131- distro := ask_choice('mirrors for which os', distros().map(it.name), detect_distro())!
132- d := distro_named(distro)
133- aur := ask_yes('add the AUR as a pkgbuild repo', true)!
142+ aur := !vinix && ask_yes('add the AUR as a pkgbuild repo', true)!
134143 mut lib32 := false
135144 if d.lib32 != '' {
136145 // pacman.conf ships multilib commented out, so off is the default here too
@@ -140,7 +149,10 @@ fn run() ! {
140149 root := ask_choice('the command vpac gets root with', providers, root_default())!
141150 parallel := ask_count('parallel downloads', 3, 1)!
142151 color := ask_choice('color output', ['auto', 'always', 'never'], 'auto')!
143- sandbox := ask_yes("turn libalpm's sandbox off for downloads and extraction (pacman's DisableSandbox)", false)!
152+ if vinix {
153+ println('Vinix lacks Landlock. Choose yes below to fetch packages and repository databases with the privileges of the vpac process.')
154+ }
155+ sandbox := ask_yes("turn off nspkg's download sandbox (pacman's DisableSandbox)", false)!
144156
145157 // the root command runs when the files are written to /etc: the same one
146158 // the config names for vpac's own escalation
@@ -159,8 +171,8 @@ fn run() ! {
159171 sandbox: sandbox
160172 arch: os.uname().machine
161173 }
162- mirror := os.join_path(etc, 'mirrors', '${d.name}.lip')
163- write_mirror := !os.exists(mirror)
174+ mirror := os.join_path(etc, 'mirrors', '${d.name}.vile')
175+ write_mirror := d.src != '' && !os.exists(mirror)
164176
165177 // the files are staged in a temp dir and then moved into place, so the
166178 // root command only copies
@@ -169,14 +181,22 @@ fn run() ! {
169181 defer {
170182 os.rmdir_all(stage) or { eprintln('install: could not remove ${stage}: ${err}') }
171183 }
172- staged_config := os.join_path(stage, 'config.lip')
173- staged_mirror := os.join_path(stage, 'mirrors', '${d.name}.lip')
184+ staged_config := os.join_path(stage, 'config.vile')
185+ staged_mirror := os.join_path(stage, 'mirrors', '${d.name}.vile')
174186 os.write_file(staged_config, config_text(a, paths, d))!
175- os.write_file(staged_mirror, mirror_text(d))!
187+ if write_mirror {
188+ os.write_file(staged_mirror, mirror_text(d))!
189+ }
176190
177- mut cmds := ['mkdir -p ${sh_quote(etc)} ${sh_quote(os.join_path(etc, 'mirrors'))}']
191+ mut cmds := ['mkdir -p ${sh_quote(etc)}']
192+ if write_mirror {
193+ cmds << 'mkdir -p ${sh_quote(os.join_path(etc, 'mirrors'))}'
194+ }
178195 if !trial {
179196 cmds << 'mkdir -p ${sh_quote(paths.db)} ${sh_quote(paths.cache)} ${sh_quote(paths.gpg)} ${sh_quote(paths.hook)}'
197+ if vinix {
198+ cmds << 'mkdir -p /var/lib/vpac/root'
199+ }
180200 }
181201 if replace {
182202 cmds << 'cp -f ${sh_quote(config)} ${sh_quote(config + '.old')}'
@@ -195,14 +215,19 @@ fn run() ! {
195215 println('wrote ${config}')
196216 if write_mirror {
197217 println('wrote ${mirror}: one default url, which vpac k -w ranks')
198- } else {
218+ } else if d.src != '' {
199219 println('kept ${mirror}: it is already there')
200220 }
201221 println('')
202222 println('next:')
203- println(term.bold(' v . -o vpac ') + ' build vpac')
223+ build := if vinix { 'v -prod -cc gcc -o vpac .' } else { 'v . -o vpac' }
224+ println(term.bold(' ${build}') + ' build vpac')
204225 println(term.bold(' ln -sf $PWD/vpac /usr/local/bin') + ' symlink vpac to /usr/local/bin/vpac')
205- println(term.bold(' vpac k -w ') + ' rank the ${d.name} mirrors into ${mirror}')
226+ if vinix {
227+ println(' Import and trust your package signing key in ${paths.gpg} before installing a signed local package.')
228+ } else {
229+ println(term.bold(' vpac k -w ') + ' rank the ${d.name} mirrors into ${mirror}')
230+ }
206231}
207232
208233// distro_named is the distro with the name, or the first one when none has it
@@ -321,54 +346,36 @@ fn ask_count(question string, default int, min int) !int {
321346 return default
322347}
323348
324-// config_text is the one config file: every form a user is likely to want,
325-// with the mirror file of the distro required beside it
349+// The mirror file supplies the servers shared by the distro's repositories.
326350fn config_text(a Answers, p Paths, d Distro) string {
327351 mut repos := []string{}
328352 for name in d.repos {
329- repos << '(repo\n :name "${name}"\n :src mirrors-${d.name})'
353+ repos << 'sync-repo("${name}", mirrors-${d.name})'
330354 }
331- if a.lib32 {
332- repos << '(repo\n :name "${d.lib32}"\n :src mirrors-${d.name})'
355+ if a.lib32 { repos << 'sync-repo("${d.lib32}", mirrors-${d.name})' }
356+ if a.aur { repos << 'pkgbuild-repo("aur", "https://aur.archlinux.org")' }
357+ vinix := d.name == 'vinix'
358+ mut lines := ['; vpac configuration']
359+ if d.src != '' { lines << 'load("mirrors/${d.name}.vile")' }
360+ root := if vinix { '/var/lib/vpac/root/' } else { '/' }
361+ hold := if vinix { '[]' } else { '["pacman", "glibc"]' }
362+ user := if vinix { 'nobody' } else { 'alpm' }
363+ lines << ['', 'path-root = "${root}"', 'path-db = "${p.db}"', 'path-log = "${p.log}"',
364+ 'path-gpg = "${p.gpg}"', 'path-cache = ["${p.cache}"]', 'path-hook = ["${p.hook}"]', '',
365+ 'pkg-arch = "${a.arch}"', 'pkg-hold = ${hold}', '', 'network-connections = ${a.parallel}',
366+ 'network-protocols = ["https"]', 'network-user = "${user}"']
367+ if a.sandbox { lines << 'network-disable-sandbox = true' }
368+ if vinix {
369+ lines << 'network-siglevel = ["package", "database"]'
370+ lines << r'pkgbuild-makepkg = "PACMAN=/opt/vpac/fakeroot/bin/vpac-query PATH=/opt/vpac/fakeroot/bin:$PATH makepkg -f --sign"'
333371 }
334- if a.aur {
335- repos << '(repo\n :name "aur"\n :type "pkgbuild"\n :src "https://aur.archlinux.org")'
372+ lines << ['', 'options-root = "${a.root}"', 'options-color = "${a.color}"', '']
373+ if repos.len > 0 {
374+ lines << 'repositories = list(' + '\n ' + repos.join(',\n ') + '\n)'
336375 }
337- return '; vpac config, written by install.vsh: edit it by hand, or run install.vsh again.
338-(require "mirrors/${d.name}.lip")
339-
340-(path
341- :root "/"
342- :db "${p.db}"
343- :log "${p.log}"
344- :gpg "${p.gpg}"
345- :cache ["${p.cache}"]
346- :hook ["${p.hook}"])
347-
348-(pkg
349- :arch "${a.arch}"
350- :hold ["pacman" "glibc"])
351-
352-(network
353- :parallel ${a.parallel}
354- :protocols ["https"]
355- :user "alpm"' +
356- if a.sandbox { ' :disable-sandbox true' } else { '' } +
357- ')
358-
359-(options
360- :root "${a.root}"
361- :color "${a.color}")
362-
363-${repos.join('\n\n')}
364-'
376+ return lines.join('\n') + '\n'
365377}
366378
367-// mirror_text is a mirror file as rank writes one: mirrors-<os> is defined
368-// and holds the urls, here the distro's one url until the ranking replaces it
369379fn mirror_text(d Distro) string {
370- return '; mirrors for ${d.name}, the default until vpac k -w ranks them
371-(unless (defined? mirrors-${d.name}) (define mirrors-${d.name} []))
372-(array-append! mirrors-${d.name} ["${d.src}"])
373-'
380+ return '; mirrors for ${d.name}, the default until vpac k -w ranks them\nmirrors-${d.name} := ["${d.src}"]\n'
374381}
@@ -1,35 +0,0 @@
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))))
@@ -1,2 +0,0 @@
1-#!/bin/bash
2-echo "just, from the lip pipeline"
@@ -1 +0,0 @@
1-the lipsmoke readme
@@ -1,15 +0,0 @@
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,13 @@
1+(defpkgbuild schemesplit
2+ #:pkgname '("schemesplit" "schemesplit-doc")
3+ #:pkgver "3.2"
4+ #:pkgrel 1
5+ #:pkgdesc "a split package built from one Scheme recipe"
6+ #:arch '(#:any)
7+ #:license "MIT"
8+ #:source '("shared.txt")
9+ #:b2sums '("f7d65eb3c70eddb9257e9539ab502e85fa754f5a7389631fd3171d944dc6fa466f73f525feaa8e83f5126a29e77fdf4774b3e27f99c4da23a86e7bda5041b92f")
10+ #:package
11+ (lambda ()
12+ (run "install" "-Dm644" "shared.txt"
13+ (string-append (pkgdir) "/root-of-" (this-pkg)))))
@@ -0,0 +1,36 @@
1+defpkgbuild(vilesmoke,
2+ #:pkgname, "vilesmoke",
3+ #:pkgver, "1.0",
4+ #:pkgrel, 1,
5+ #:pkgdesc, "a smoke test for native Vile package recipes",
6+ #:arch, [#:x86-64, #:aarch64, #:riscv64],
7+ #:url, "https://example.org/vilesmoke",
8+ #:license, "MIT",
9+ #:makedepends, ["gcc"],
10+ #:source, ["vilesmoke.c", "readme.txt"],
11+ #:b2sums, ["733e536662bcac5fd7546b3611511e4b5a5443b193dff30a7858f12d7ab478e7613a51de2bbade418c8eefbb192b956460a3a91f2f9613582a11fe707217efb0",
12+ "6879484c83ae728a6f6a342867f9c254b6c5c3402821aa02bb460ee898c8f5045e5cec1a0c707f4667e4045a0b3d4cbac47d01cd6ac486153caa3d59c97faf9b"],
13+
14+ #:build, fn() {
15+ run("cc", "-o", "vilesmoke", "vilesmoke.c")
16+ display("vilesmoke: build finished")
17+ newline()
18+ },
19+ #:package, fn() {
20+ run("install", "-Dm755", "vilesmoke", string-append(pkgdir(), "/usr/bin/vilesmoke"))
21+ for-each(fn(doc) {
22+ run("install", "-Dm644", doc, string-append(pkgdir(), "/usr/share/doc/vilesmoke/", doc))
23+ }, glob("*.txt"))
24+ display("vilesmoke: package finished")
25+ newline()
26+ },
27+
28+ ; nspkg passes the version being installed to each hook.
29+ #:pre-install, fn(newver) {
30+ display(string-append("vilesmoke: pre-installing ", newver))
31+ newline()
32+ },
33+ #:post-install, fn(newver) {
34+ display(string-append("vilesmoke: installed ", newver, ", run vilesmoke for a hello"))
35+ newline()
36+ })
@@ -0,0 +1 @@
1+the vilesmoke readme
@@ -0,0 +1,6 @@
1+#include <stdio.h>
2+
3+int main(void) {
4+ puts("hello from the Vile recipe");
5+ return 0;
6+}
@@ -1,33 +1,31 @@
11#!/usr/bin/env v
22
33// 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
4+// functions, and vsh_entry dispatches the compiled recipe
55import vmakepkg
66import os
77
88fn spec() !vmakepkg.Spec {
99 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',
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: [os.uname().machine]
15+ url: 'https://example.org/vshsmoke'
16+ license: 'MIT'
17+ makedepends: ['gcc']
18+ source: ['vshsmoke.c', 'readme.txt']
19+ b2sums: [
20+ '61e646216ee8f398f9fcc605a573954e5f5e9fafc0dfd583352203eed7081c8540127f7e879079f71a654b3efef6f79b1604fec7ea28056363c8a7a899a6fa8a',
2121 '1645d573e1441b363804b7f6e1bbd71b87ee87027d0110be97bc8de7e2682d391ae0812770de7c218d0018ee3f4ad6607039019ed7b3c814963ecae80b12f77d',
2222 ]
23- hooks: ['post-install']
23+ hooks: ['post-install']
2424 }
2525}
2626
2727fn 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')!
28+ vmakepkg.run(['cc', '-o', 'vshsmoke', 'vshsmoke.c'])!
3129 println('vshsmoke: build finished')
3230}
3331
@@ -35,10 +33,10 @@ fn package() ! {
3533 pd := vmakepkg.pkgdir()!
3634 mut docs := []string{}
3735 // 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')!
36+ vmakepkg.run(['install', '-Dm755', 'vshsmoke', os.join_path(pd, 'usr/bin/vshsmoke')])!
3937 for doc in vmakepkg.glob('*.txt')! {
4038 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)}')!
39+ vmakepkg.run(['install', '-Dm644', doc, os.join_path(pd, 'usr/share/doc/vshsmoke', name)])!
4240 docs << doc
4341 }
4442 println('vshsmoke: package finished (${docs.len} docs unpacked alongside)')
@@ -0,0 +1,6 @@
1+#include <stdio.h>
2+
3+int main(void) {
4+ puts("vsh smoke ok");
5+ return 0;
6+}
@@ -1,2 +0,0 @@
1-#!/bin/bash
2-echo "vsh smoke ok"
@@ -1,6 +1,6 @@
11module main
22
3-import alpm
3+import nspkg
44
55// mirrors pacman's -Rns $(pacman -Qtdq) idiom: remove every orphaned
66// package, letting the transaction pull in the dependencies that become
@@ -10,7 +10,7 @@ fn autoremove(config ConfigAutoRemove) ! {
1010 check_ask_db_lock(mut ui)
1111
1212 mut handle := init_handle(ui)!
13- defer { handle.release() or { went_on('release the alpm handle', err) } }
13+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
1414 defer { ui.stop() }
1515 defer { trans_cleanup(handle) }
1616
@@ -31,7 +31,7 @@ fn autoremove(config ConfigAutoRemove) ! {
3131 check_hold(orphs.map(it.get_name()))!
3232
3333 s.set_text('preparing removal')
34- trans_begin(handle, alpm.TransFlag.recurse | alpm.TransFlag.no_save)!
34+ trans_begin(handle, nspkg.TransFlag.recurse | nspkg.TransFlag.no_save)!
3535 for pkg in orphs {
3636 handle.remove_pkg(pkg)!
3737 }
@@ -1,16 +1,10 @@
11module main
22
33import crypto.sha256
4-import vmakepkg
54import os
65
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.
6+// a local checkout or git repository is reviewed, built as the invoking
7+// user, then installed as one transaction, including split packages.
148struct ConfigBuild {
159pub mut:
1610 show_help bool @[long: help; short: h]
@@ -19,89 +13,6 @@ pub mut:
1913 query []string @[tail]
2014}
2115
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-
10516// pull_dir copies a local repo into its build dir as the building user: a
10617// root-owned copy would stop makepkg from touching anything
10718fn pull_dir(user string, src string, dst string) ! {
@@ -110,30 +21,6 @@ fn pull_dir(user string, src string, dst string) ! {
11021 run_as_user(user, ['cp', '-R', src, dst])!
11122}
11223
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-
13724// repo_name is the name a repo goes by: the last part of its path or url,
13825// without a .git suffix. an scp-style git address (user@host:path) counts
13926// from after the colon. empty when the target names nothing, like / or .
@@ -173,6 +60,45 @@ fn repo_work_dir(user string, target string) !(string, string) {
17360 return name, pkgbuild_build_dir(user, '${name}-${sha256.hexhash(source)[..8]}')!
17461}
17562
63+fn build_recipe_name(dir string) !string {
64+ for name in ['PKGBUILD.vile', 'PKGBUILD.scm', 'PKGBUILD.vsh', 'PKGBUILD'] {
65+ if os.is_file(os.join_path(dir, name)) {
66+ return name
67+ }
68+ }
69+ return error('${dir} has no PKGBUILD, PKGBUILD.vile, PKGBUILD.scm or PKGBUILD.vsh')
70+}
71+
72+fn recipe_review(user string, base string, dir string, source_name string) !ReviewEvent {
73+ if source_name == 'PKGBUILD' { return read_review(base, dir) }
74+ source := output_as_user(user, ['cat', '--', os.join_path(dir, source_name)])!
75+ return ReviewEvent{ package: base, files: [ReviewFile{ name: source_name, text: source }] }
76+}
77+
78+fn build_archives(user string, work_dir string, source_name string) ![]string {
79+ if source_name == 'PKGBUILD' {
80+ run_makepkg(user, work_dir)!
81+ return built_packages(user, work_dir)
82+ }
83+ mut archives := []string{}
84+ recipe := os.join_path(work_dir, source_name)
85+
86+ manifest := os.join_path(work_dir, '.vpac-packages')
87+ mut args := ['env', 'VPAC_MAKEPKG_ROOT=' + root_path, 'VPAC_MAKEPKG_DB=' + db_path]
88+ if os.getenv(env_v) != '' { args << 'VPAC_V=' + os.getenv(env_v) }
89+ args << [os.executable(), '--native-build', recipe, manifest]
90+ if '--sign' in pkgbuild_makepkg.fields() { args << '--sign' }
91+ run_as_user(user, args)!
92+ paths := output_as_user(user, ['cat', '--', manifest])!
93+ for path in paths.trim_right('\n').split_into_lines() {
94+ if !path.ends_with('.pkg.tar.zst') || !os.real_path(path).starts_with(os.real_path(work_dir) + '/') {
95+ return error('invalid native package output: ${path}')
96+ }
97+ archives << path
98+ }
99+ return archives
100+}
101+
176102// build_repo_target pulls one target, reviews it, builds and installs it.
177103// a target is an existing directory (a checkout, taken as the repo stands)
178104// or a git url to clone; bare names belong to the pkgbuild repos, which the
@@ -191,7 +117,7 @@ fn build_repo_target(config ConfigBuild, target string, mut ui TransUI) ! {
191117 } else if is_git_url(target) {
192118 // git is the one tool a clone cannot happen without: an absent one is
193119 // said plainly, below user's name, before anything pulls
194- run_as_user(user, ['sh', '-c', 'git --version >/dev/null']) or {
120+ output_as_user(user, ['git', '--version']) or {
195121 return error('git is needed to clone ${target} as user ${user}, but it was not found (or failed): ${err.msg()}')
196122 }
197123 run_as_user(user, ['rm', '-rf', work_dir])!
@@ -199,83 +125,17 @@ fn build_repo_target(config ConfigBuild, target string, mut ui TransUI) ! {
199125 } else {
200126 return error('b: "${target}" is neither a directory nor a git url; pkgbuild repos are covered by vpac i --pkgbuild ${target}')
201127 }
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')
128+ source_name := build_recipe_name(work_dir)!
129+ review := recipe_review(user, base, work_dir, source_name)!
130+ show_review(review, if source_name == 'PKGBUILD' { 'review ${base}' } else { '' })
131+ if ask && !ui.noyes('build and install ${base}?') {
132+ return
269133 }
270134 build_phase(base, 'start')
271- run_as_user(user, ['sh', '-c', makepkg_line(work_dir)])!
135+ archives := build_archives(user, work_dir, source_name)!
272136 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)!
277137 if archives.len == 0 {
278- return error('b: makepkg built nothing for ${base} that its --packagelist names')
138+ return error('b: no package archives produced for ${base}')
279139 }
280140 install(ConfigInstall{
281141 query: archives
@@ -2,6 +2,19 @@ module main
22
33import os
44
5+fn test_build_recipe_precedence() ! {
6+ dir := os.join_path(os.vtmp_dir(), 'vpac_recipe_choice_${os.getpid()}')
7+ os.mkdir_all(dir)!
8+ defer { os.rmdir_all(dir) or { went_on('remove the test recipes', err) } }
9+ if _ := build_recipe_name(dir) {
10+ assert false, 'an empty directory has no recipe'
11+ }
12+ for name in ['PKGBUILD', 'PKGBUILD.vsh', 'PKGBUILD.scm', 'PKGBUILD.vile'] {
13+ os.write_file(os.join_path(dir, name), '')!
14+ assert build_recipe_name(dir)! == name
15+ }
16+}
17+
518fn test_repo_name() {
619 // the last part of the path or url, without a .git suffix. trim_right
720 // would have cut a set of characters: digit came out as d, gist as gis
@@ -89,64 +102,6 @@ fn test_repo_work_dir_directories() ! {
89102 assert dot_name == 'mything'
90103}
91104
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-
150105fn test_build_refuses_noconfirm_alone() {
151106 // the build question's preset is no: --noconfirm alone would build
152107 // nothing and exit clean, so it is refused before anything is pulled
@@ -1,6 +1,6 @@
11module main
22
3-import alpm
3+import nspkg
44import os
55import v.profiler
66
@@ -149,7 +149,7 @@ fn paccache_keep(keep_n int, files []string, keep_prefixes []string) map[string]
149149 mut gg := groups[name]
150150 // newest first, using the same vercmp as pacman
151151 gg.sort_with_compare(fn (a &CacheFile, b &CacheFile) int {
152- return alpm.pkg_vercmp(b.version, a.version)
152+ return nspkg.pkg_vercmp(b.version, a.version)
153153 })
154154 for i, cf in gg {
155155 if i < keep_n {
@@ -281,7 +281,7 @@ fn clean_event(to_remove []string, total u64, builds BuildClean, dbs []string, p
281281fn clean(config ConfigClean) ! {
282282 mut ui := new_trans_ui(noconfirm: config.noconfirm)
283283 mut handle := init_handle(ui)!
284- defer { handle.release() or { went_on('release the alpm handle', err) } }
284+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
285285 defer { ui.stop() }
286286
287287 mut pkgcache := local_pkgcache(handle)!
@@ -264,7 +264,7 @@ fn need_query(query []string, what string) ! {
264264}
265265
266266// scan_globals collects vpac's own flags, wherever they stand in the command
267-// line: --config chooses the config file, --eval extends the config with blip
267+// line: --config chooses the config file, --eval extends the config with
268268// code run after it. both repeatable, both also usable as --flag=value. the
269269// flags are stripped from the args (the program name stays first, the mode
270270// second), so a mode never sees them; escalation still gets the original
@@ -305,7 +305,7 @@ fn scan_globals(args []string) !(string, []string, []string) {
305305 } else if arg.starts_with('--eval=') {
306306 expr := arg.all_after('=')
307307 if expr == '' {
308- return error('--eval needs blip code')
308+ return error('--eval needs config code')
309309 }
310310 evals << expr
311311 i++
@@ -401,7 +401,7 @@ type ModeConfig = ConfigAutoRemove
401401 | ConfigWhich
402402
403403// mode_flags reads a mode's flags into its struct, then lays the config's
404-// options under them: a flag the config turns on (options :noconfirm true)
404+// options under them: a flag the config turns on (options #:noconfirm #t)
405405// is on for every mode that has it, as if it stood on the command line.
406406// the command line can only add to that; --eval turns one off for a run.
407407// an option the mode's struct has no field for is an error
@@ -476,7 +476,7 @@ fn parse_mode(args []string) !ModeConfig {
476476 if !flag_given(once, 'thold', 't') {
477477 c.thold = cfg_search_thold
478478 } else if c.thold < 0.0 || c.thold > 1.0 {
479- // the config's (search :thold) is held to the same range
479+ // the config's (search #:thold) is held to the same range
480480 return error('--thold must be between 0 and 1, not ${c.thold}')
481481 }
482482 c.unrequired_level = level
@@ -556,7 +556,7 @@ fn parse_mode(args []string) !ModeConfig {
556556 if !flag_given(args, 'top', 'n') {
557557 c.top = rank_top
558558 } else if c.top < 1 {
559- // the config's (rank :top) is held to the same floor
559+ // the config's (rank #:top) is held to the same floor
560560 return error('--top must be at least 1, not ${c.top}')
561561 }
562562 ModeConfig(c)
@@ -667,12 +667,26 @@ fn run_mode(c ModeConfig) !int {
667667}
668668
669669fn main() {
670- // --lip-run <lip> <phase> [args...] is what a PKGBUILD generated from a
671- // PKGBUILD.lip calls back (vpac b): it runs one phase of the lip. it is no
672- // mode, reads no config and never needs root
673- if os.args.len > 3 && os.args[1] == '--lip-run' {
674- vmakepkg.lip_run_phase(os.args[2], os.args[3], os.args[4..]) or {
675- eprintln(error_text('lip: ${err.msg()}'))
670+ if os.args.len > 1 && os.args[1] == '--makepkg-query' {
671+ code := makepkg_query(os.args[2..]) or { print_err(err.msg()) }
672+ exit(code)
673+ }
674+ if os.args.len > 1 && os.args[1] == '--package-hook' {
675+ vmakepkg.package_hook(os.args[2..]) or { print_err(err.msg()) }
676+ return
677+ }
678+ if os.args.len > 1 && os.args[1] == '--native-build' {
679+ if os.args.len !in [4, 5] || (os.args.len == 5 && os.args[4] != '--sign') {
680+ print_err('native build expects a recipe, an output list and optional --sign')
681+ }
682+ archives := vmakepkg.native_build(os.args[2], os.args.len == 5) or { print_err(err.msg()) }
683+ os.write_file(os.args[3], archives.join('\n') + '\n') or { print_err(err.msg()) }
684+ return
685+ }
686+ // recipe workers start without loading the system config.
687+ if os.args.len > 3 && os.args[1] == '--recipe-run' {
688+ vmakepkg.recipe_run_phase(os.args[2], os.args[3], os.args[4..]) or {
689+ eprintln(error_text('recipe: ${err.msg()}'))
676690 exit(1)
677691 }
678692 exit(0)
@@ -1,9 +1,9 @@
11module main
22
3-import alpm
3+import nspkg
44import os
55
6-// --eval takes its blip from the next argument or from =; an empty one is
6+// --eval takes its scheme from the next argument or from =; an empty one is
77// refused like an empty --config or --color value is
88fn test_scan_globals_eval() ! {
99 mut chosen := ''
@@ -14,8 +14,8 @@ fn test_scan_globals_eval() ! {
1414 assert evals == ['(define x 1)']
1515 assert rest == ['vpac', 's', 'zsh']
1616
17- chosen, evals, rest = scan_globals(['vpac', '--eval=(define x 2)', '--config=other.lip', 's'])!
18- assert chosen == 'other.lip'
17+ chosen, evals, rest = scan_globals(['vpac', '--eval=(define x 2)', '--config=other.scm', 's'])!
18+ assert chosen == 'other.scm'
1919 assert evals == ['(define x 2)']
2020 assert rest == ['vpac', 's']
2121
@@ -86,9 +86,9 @@ fn test_scan_globals_settles_the_ui_before_failing() {
8686fn test_doubled_flags_count() ! {
8787 r := parse_mode(['vpac', 'r', '-ss', '-u', 'foo'])! as ConfigRemove
8888 assert r.recursive_level == 2 && r.unneeded && r.query == ['foo']
89- assert recurse_flags(r.recursive, r.recursive_level) == alpm.TransFlag.recurse | .recurse_all
89+ assert recurse_flags(r.recursive, r.recursive_level) == nspkg.TransFlag.recurse | .recurse_all
9090 one := parse_mode(['vpac', 'r', '--recursive', 'foo'])! as ConfigRemove
91- assert recurse_flags(one.recursive, one.recursive_level) == alpm.TransFlag.recurse
91+ assert recurse_flags(one.recursive, one.recursive_level) == nspkg.TransFlag.recurse
9292
9393 c := parse_mode(['vpac', 'c', '-cc'])! as ConfigClean
9494 assert c.level == 2 && !c.keep_current
@@ -268,15 +268,15 @@ fn test_needs_root_for_rank_follows_the_file() ! {
268268 // printing a ranking writes nothing
269269 assert !needs_root(ConfigRank{ query: [os_name] })!
270270 // -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] })!
271+ assert !needs_root(ConfigRank{ output: os.join_path(tmp, 'new.scm'), query: [os_name] })!
272+ os.write_file(os.join_path(tmp, 'there.scm'), '')!
273+ assert !needs_root(ConfigRank{ output: os.join_path(tmp, 'there.scm'), query: [os_name] })!
274274 // one it may not is root's: an existing read-only file, a new file in
275275 // 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] })!
276+ os.chmod(os.join_path(tmp, 'there.scm'), 0o444)!
277+ assert needs_root(ConfigRank{ output: os.join_path(tmp, 'there.scm'), query: [os_name] })!
278+ assert needs_root(ConfigRank{ output: os.join_path(tmp, 'ro', 'new.scm'), query: [os_name] })!
279+ assert needs_root(ConfigRank{ output: os.join_path(tmp, 'gone', 'new.scm'), query: [os_name] })!
280280 // -w writes the config's mirror file: the rank dir decides, and -o,
281281 // when both are given, is the file that is written
282282 rank_dir = tmp
@@ -285,7 +285,7 @@ fn test_needs_root_for_rank_follows_the_file() ! {
285285 assert needs_root(ConfigRank{ write: true, query: [os_name] })!
286286 assert !needs_root(ConfigRank{
287287 write: true
288- output: os.join_path(tmp, 'new.lip')
288+ output: os.join_path(tmp, 'new.scm')
289289 query: [os_name]
290290 })!
291291 // an os the ranker does not know is an error before any escalation
@@ -2,16 +2,18 @@
22module main
33
44import os
5-import blip.vlib.blip
6-import blip.vlib.blip.machine
7-import alpm
5+import vile.scheme
6+import stutter
7+import nspkg
88
9-// config_path is the file read at startup, written in blip: a lisp dialect
9+// config_path is the file read at startup, evaluated by Vile
1010// embedded from V. the file is required, since the config carries parts of
1111// vpac (the repos, for one); a setting no form of it names keeps the
1212// default its __global is declared with below, which reset_config puts
1313// back before every load
14-pub const config_path = '/etc/vpac.d/config.lip'
14+pub const config_path = '/etc/vpac.d/config.vile'
15+
16+__global config_vile = true
1517
1618// the settings below were consts until the config existed. root_path and
1719// db_path are joined onto file names directly, so they keep a trailing slash
@@ -25,8 +27,8 @@ __global parallel_downloads = 3
2527__global rank_parallel = 0
2628__global rank_timeout = 10
2729// 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+// where it builds is path #:build. the build command is the system's makepkg,
31+// which ships in the pacman package with the libalpm vpac runs on; #:makepkg
3032// names another
3133// the build command is trusted text: it is spelled whole into a shell that
3234// runs it in the cloned dir, first as the building user and through the
@@ -42,7 +44,7 @@ __global download_user = 'alpm'
4244__global cfg_cachedirs = ['/var/cache/pacman/pkg/']
4345// pacman's default HookDir, beside the system one libalpm adds by itself
4446__global cfg_hookdirs = ['/etc/pacman.d/hooks/']
45-// where pkgbuild packages are cloned and built (path :build): a relative
47+// where pkgbuild packages are cloned and built (path #:build): a relative
4648// dir is taken under the invoking user's home, because makepkg runs as that user
4749__global pkgbuild_dir = '.cache/vpac/pkgbuild'
4850__global cfg_logfile = ''
@@ -56,8 +58,8 @@ __global cfg_protocols = ['https']
5658// checked against. libalpm's freshly calloc'd handle verifies nothing, so
5759// vpac defaults to pacman's shipped SigLevel: a package and a database
5860// 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+// fails. override with (network #:siglevel #(...))
62+__global cfg_siglevel = nspkg.SigLevel.package | .package_optional | .database | .database_optional
6163__global cfg_hold = []string{}
6264__global cfg_ignore = []string{}
6365// the rest of pacman.conf's [options]: groups ignored as cfg_ignore's packages
@@ -69,7 +71,7 @@ __global cfg_disable_timeout = false
6971// pacman.conf's DisableSandboxFilesystem and DisableSandboxSyscalls: libalpm
7072// sandboxes its downloads and extracts, and this turns both parts off
7173__global cfg_disable_sandbox = false
72-// pacman.conf's UseSyslog: libalpm logs to syslog too, (path :syslog true)
74+// pacman.conf's UseSyslog: libalpm logs to syslog too, (path #:syslog #t)
7375__global cfg_syslog = false
7476// cfg_repos holds the repos the config defines
7577__global cfg_repos = []CfgRepo{}
@@ -82,45 +84,49 @@ struct CfgRepo {
8284 kind string
8385 servers []string
8486 // what the db is used for, as pacman.conf's Usage; every use by default
85- usage alpm.DBUsage = alpm.db_usage_all
87+ usage nspkg.DBUsage = nspkg.db_usage_all
8688}
8789
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
90+// config forms accept scheme keywords as well as stutter's quoted symbols.
91+fn config_keyword_args(form string, args []scheme.Value) !([]string, []scheme.Value) {
92+ mut normalized := args.clone()
93+ for i := 0; i < normalized.len; i += 2 {
94+ if normalized[i].kind() == .keyword {
95+ normalized[i] = scheme.symbol(normalized[i].keyword_name()!)!
96+ }
97+ }
98+ return stutter.keyword_args(form, normalized)
9999}
100100
101-fn (h &QuietConfigHost) host_load(path string) !string {
102- return os.read_file(path)
101+// mirror files can extend a binding without requiring the config to seed it.
102+fn prim_defined(mut vm scheme.VM, args []scheme.Value) !scheme.Value {
103+ scheme.check_arity('defined?', args.len, 1, 1)!
104+ name := args[0].symbol_name()!
105+ value := vm.lookup(name) or {
106+ if err.msg().starts_with('unbound variable ') { return scheme.boolean(false) }
107+ return err
108+ }
109+ return scheme.boolean(value.kind() != .uninitialized)
103110}
104111
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,
112+// usage_of reads a repo's #:usage, pacman.conf's Usage: one or more of sync,
107113// 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)! }
114+fn usage_of(v scheme.Value, what string) !nspkg.DBUsage {
115+ names := match v.kind() {
116+ .string { [v.as_string()!] }
117+ else { stutter.strs_of(v, what)! }
112118 }
113119 if names.len == 0 {
114120 return error('config: ${what} needs at least one of sync, search, install, upgrade, all')
115121 }
116- mut usage := unsafe { alpm.DBUsage(0) }
122+ mut usage := unsafe { nspkg.DBUsage(0) }
117123 for name in names {
118124 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 }
125+ 'sync' { nspkg.DBUsage.sync }
126+ 'search' { nspkg.DBUsage.search }
127+ 'install' { nspkg.DBUsage.install }
128+ 'upgrade' { nspkg.DBUsage.upgrade }
129+ 'all' { nspkg.db_usage_all }
124130 else {
125131 return error('config: ${what} takes sync, search, install, upgrade and all, not "${name}"')
126132 }
@@ -129,101 +135,32 @@ fn usage_of(v blip.Value, what string) !alpm.DBUsage {
129135 return usage
130136}
131137
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
138+// siglevel_names are the names (network #:siglevel) accepts, mapped onto
202139// libalpm's SigLevel bits, plus what each one means
203140const 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
141+ 'package': nspkg.SigLevel.package
142+ 'package_optional': nspkg.SigLevel.package_optional
143+ 'package_marginal_ok': nspkg.SigLevel.package_marginal_ok
144+ 'package_unknown_ok': nspkg.SigLevel.package_unknown_ok
145+ 'database': nspkg.SigLevel.database
146+ 'database_optional': nspkg.SigLevel.database_optional
147+ 'database_marginal_ok': nspkg.SigLevel.database_marginal_ok
148+ 'database_unknown_ok': nspkg.SigLevel.database_unknown_ok
212149}
213150
214151// 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)! }
152+// of names, e.g. (network #:siglevel #("package" "database_optional"))
153+fn siglevel_of(v scheme.Value, what string) !nspkg.SigLevel {
154+ names := match v.kind() {
155+ .string { [v.as_string()!] }
156+ else { stutter.strs_of(v, what)! }
220157 }
221158 // an empty one verifies nothing: libalpm would take the silent answer
222159 // as handing everything over unsigned, which nobody ever means
223160 if names.len == 0 {
224161 return error('config: ${what} needs at least one of: ${siglevel_names.keys().join(', ')}')
225162 }
226- mut level := unsafe { alpm.SigLevel(0) }
163+ mut level := unsafe { nspkg.SigLevel(0) }
227164 for name in names {
228165 key := name.to_lower()
229166 bit := siglevel_names[key] or {
@@ -234,245 +171,212 @@ fn siglevel_of(v blip.Value, what string) !alpm.SigLevel {
234171 return level
235172}
236173
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-
270174// 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)!
175+// and #:syslog true for pacman.conf's UseSyslog
176+fn prim_path(mut _vm scheme.VM, args []scheme.Value) !scheme.Value {
177+ keys, values := config_keyword_args('path', args)!
274178 mut i := 0
275179 for i < keys.len {
276180 match keys[i] {
277181 'root' {
278- root_path = dir_path('path :root', str_of(values[i], 'path :root')!)!
182+ root_path = stutter.dir_path('path #:root', stutter.str_of(values[i], 'path #:root')!)!
279183 }
280184 'db' {
281- db_path = dir_path('path :db', str_of(values[i], 'path :db')!)!
185+ db_path = stutter.dir_path('path #:db', stutter.str_of(values[i], 'path #:db')!)!
282186 }
283187 'log' {
284- cfg_logfile = str_of(values[i], 'path :log')!
188+ cfg_logfile = stutter.str_of(values[i], 'path #:log')!
285189 }
286190 'syslog' {
287- cfg_syslog = bool_of(values[i], 'path :syslog')!
191+ cfg_syslog = stutter.bool_of(values[i], 'path #:syslog')!
288192 }
289193 'gpg' {
290- cfg_gpgdir = dir_path('path :gpg', str_of(values[i], 'path :gpg')!)!
194+ cfg_gpgdir = stutter.dir_path('path #:gpg', stutter.str_of(values[i], 'path #:gpg')!)!
291195 }
292196 'cache' {
293- dirs := strs_of(values[i], 'path :cache')!
197+ dirs := stutter.strs_of(values[i], 'path #:cache')!
294198 cfg_cachedirs = []string{}
295199 for dir in dirs {
296- cfg_cachedirs << dir_path('path :cache', dir)!
200+ cfg_cachedirs << stutter.dir_path('path #:cache', dir)!
297201 }
298202 }
299203 'hook' {
300- dirs := strs_of(values[i], 'path :hook')!
204+ dirs := stutter.strs_of(values[i], 'path #:hook')!
301205 cfg_hookdirs = []string{}
302206 for dir in dirs {
303- cfg_hookdirs << dir_path('path :hook', dir)!
207+ cfg_hookdirs << stutter.dir_path('path #:hook', dir)!
304208 }
305209 }
306210 'build' {
307- d := str_of(values[i], 'path :build')!
211+ d := stutter.str_of(values[i], 'path #:build')!
308212 if d == '' {
309- return error('config: path :build must not be empty')
213+ return error('config: path #:build must not be empty')
310214 }
311215 pkgbuild_dir = d
312216 }
313217 else {
314- return error('config: path has no key :${keys[i]}')
218+ return error('config: path has no key #:${keys[i]}')
315219 }
316220 }
317221 i++
318222 }
319- return blip.nil_value()
223+ return scheme.nil_value()
320224}
321225
322226// 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)!
227+// IgnoreGroup, NoUpgrade and NoExtract as #:ignoregroup, #:noupgrade and
228+// #:noextract, each a list, e.g. (pkg #:noextract #("usr/share/doc/*"))
229+fn prim_pkg(mut _vm scheme.VM, args []scheme.Value) !scheme.Value {
230+ keys, values := config_keyword_args('pkg', args)!
327231 mut i := 0
328232 for i < keys.len {
329233 match keys[i] {
330234 'arch' {
331- a := str_of(values[i], 'pkg :arch')!
235+ a := stutter.str_of(values[i], 'pkg #:arch')!
332236 // it fills the $arch of every server url and is the one
333237 // architecture libalpm installs for: one plain word
334238 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')
239+ return error('config: pkg #:arch must be one plain word, such as x86_64')
336240 }
337241 arch = a
338242 }
339243 'hold' {
340- cfg_hold = strs_of(values[i], 'pkg :hold')!
244+ cfg_hold = stutter.strs_of(values[i], 'pkg #:hold')!
341245 }
342246 'ignore' {
343- cfg_ignore = strs_of(values[i], 'pkg :ignore')!
247+ cfg_ignore = stutter.strs_of(values[i], 'pkg #:ignore')!
344248 }
345249 'ignoregroup' {
346- cfg_ignore_groups = strs_of(values[i], 'pkg :ignoregroup')!
250+ cfg_ignore_groups = stutter.strs_of(values[i], 'pkg #:ignoregroup')!
347251 }
348252 'noupgrade' {
349- cfg_noupgrade = strs_of(values[i], 'pkg :noupgrade')!
253+ cfg_noupgrade = stutter.strs_of(values[i], 'pkg #:noupgrade')!
350254 }
351255 'noextract' {
352- cfg_noextract = strs_of(values[i], 'pkg :noextract')!
256+ cfg_noextract = stutter.strs_of(values[i], 'pkg #:noextract')!
353257 }
354258 else {
355- return error('config: pkg has no key :${keys[i]}')
259+ return error('config: pkg has no key #:${keys[i]}')
356260 }
357261 }
358262 i++
359263 }
360- return blip.nil_value()
264+ return scheme.nil_value()
361265}
362266
363267// 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)!
268+// siglevel, #:disable-timeout true for pacman.conf's DisableDownloadTimeout, and
269+// #:disable-sandbox true for its DisableSandbox
270+fn prim_network(mut _vm scheme.VM, args []scheme.Value) !scheme.Value {
271+ keys, values := config_keyword_args('network', args)!
368272 mut i := 0
369273 for i < keys.len {
370274 match keys[i] {
371275 'parallel' {
372- n := int_of(values[i], 'network :parallel')!
276+ n := stutter.int_of(values[i], 'network #:parallel')!
373277 if n < 1 {
374- return error('config: network :parallel must be at least 1')
278+ return error('config: network #:parallel must be at least 1')
375279 }
376280 parallel_downloads = n
377281 }
378282 'protocols' {
379- protos := strs_of(values[i], 'network :protocols')!
283+ protos := stutter.strs_of(values[i], 'network #:protocols')!
380284 if protos.len == 0 {
381- return error('config: network :protocols needs at least one, https or http')
285+ return error('config: network #:protocols needs at least one, https or http')
382286 }
383287 // a scheme no mirror is listed under would filter every
384288 // mirror out without a word
385289 for proto in protos {
386290 if proto !in ['https', 'http'] {
387- return error('config: network :protocols takes https and http, not "${proto}"')
291+ return error('config: network #:protocols takes https and http, not "${proto}"')
388292 }
389293 }
390294 cfg_protocols = protos.clone()
391295 }
392296 'user' {
393- download_user = str_of(values[i], 'network :user')!
297+ download_user = stutter.str_of(values[i], 'network #:user')!
394298 }
395299 'siglevel' {
396- cfg_siglevel = siglevel_of(values[i], 'network :siglevel')!
300+ cfg_siglevel = siglevel_of(values[i], 'network #:siglevel')!
397301 }
398302 'disable-timeout' {
399- cfg_disable_timeout = bool_of(values[i], 'network :disable-timeout')!
303+ cfg_disable_timeout = stutter.bool_of(values[i], 'network #:disable-timeout')!
400304 }
401305 'disable-sandbox' {
402- cfg_disable_sandbox = bool_of(values[i], 'network :disable-sandbox')!
306+ cfg_disable_sandbox = stutter.bool_of(values[i], 'network #:disable-sandbox')!
403307 }
404308 else {
405- return error('config: network has no key :${keys[i]}')
309+ return error('config: network has no key #:${keys[i]}')
406310 }
407311 }
408312 i++
409313 }
410- return blip.nil_value()
314+ return scheme.nil_value()
411315}
412316
413317// prim_rank is the config's (rank ...) form: parallel and timeout for the
414318// 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)!
319+// the rank form does not set its own. #:top is how many mirrors are answered,
320+// #:completion (0 to 1) and #:max-delay (seconds) what a mirror must report to
321+// be probed, #:candidates how many get the speed test, #:retest how many of
322+// the fastest are timed twice, #:dir where rank -w writes
323+fn prim_rank(mut _vm scheme.VM, args []scheme.Value) !scheme.Value {
324+ keys, values := config_keyword_args('rank', args)!
421325 mut i := 0
422326 for i < keys.len {
423327 match keys[i] {
424328 'parallel' {
425- n := int_of(values[i], 'rank :parallel')!
329+ n := stutter.int_of(values[i], 'rank #:parallel')!
426330 if n < 1 {
427- return error('config: rank :parallel must be at least 1')
331+ return error('config: rank #:parallel must be at least 1')
428332 }
429333 rank_parallel = n
430334 }
431335 'timeout' {
432- n := int_of(values[i], 'rank :timeout')!
336+ n := stutter.int_of(values[i], 'rank #:timeout')!
433337 if n < 1 {
434- return error('config: rank :timeout must be at least 1')
338+ return error('config: rank #:timeout must be at least 1')
435339 }
436340 rank_timeout = n
437341 }
438342 'top' {
439- rank_top = count_of(values[i], 'rank :top', 1)!
343+ rank_top = stutter.count_of(values[i], 'rank #:top', 1)!
440344 }
441345 'dir' {
442- d := str_of(values[i], 'rank :dir')!
346+ d := stutter.str_of(values[i], 'rank #:dir')!
443347 if !d.starts_with('/') {
444- return error('config: rank :dir must be an absolute path')
348+ return error('config: rank #:dir must be an absolute path')
445349 }
446350 rank_dir = d.trim_right('/')
447351 }
448352 'candidates' {
449- rank_speed_candidates = count_of(values[i], 'rank :candidates', 1)!
353+ rank_speed_candidates = stutter.count_of(values[i], 'rank #:candidates', 1)!
450354 }
451355 'retest' {
452- rank_retest = count_of(values[i], 'rank :retest', 0)!
356+ rank_retest = stutter.count_of(values[i], 'rank #:retest', 0)!
453357 }
454358 'completion' {
455- rank_min_completion = ratio_of(values[i], 'rank :completion')!
359+ rank_min_completion = stutter.ratio_of(values[i], 'rank #:completion')!
456360 }
457361 'max-delay' {
458- rank_max_delay = i64(count_of(values[i], 'rank :max-delay', 0)!)
362+ rank_max_delay = i64(stutter.count_of(values[i], 'rank #:max-delay', 0)!)
459363 }
460364 else {
461- return error('config: rank has no key :${keys[i]}')
365+ return error('config: rank has no key #:${keys[i]}')
462366 }
463367 }
464368 i++
465369 }
466- return blip.nil_value()
370+ return scheme.nil_value()
467371}
468372
469373// prim_repo is the config's (repo ...) form: a repo's name, its type ('sync',
470374// or 'pkgbuild', a site to build from) and the mirrors it is fetched
471375// from, with $repo and $arch left as placeholders
472-// :usage is pacman.conf's Usage: a list of sync, search, install, upgrade
376+// #:usage is pacman.conf's Usage: a list of sync, search, install, upgrade
473377// 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)!
378+fn prim_repo(mut _vm scheme.VM, args []scheme.Value) !scheme.Value {
379+ keys, values := config_keyword_args('repo', args)!
476380 mut repo := CfgRepo{
477381 kind: 'sync'
478382 }
@@ -480,16 +384,16 @@ fn prim_repo(args []blip.Value) !blip.Value {
480384 for i < keys.len {
481385 match keys[i] {
482386 'name' {
483- rname := str_of(values[i], 'repo :name')!
387+ rname := stutter.str_of(values[i], 'repo #:name')!
484388 repo = CfgRepo{
485389 ...repo
486390 name: rname
487391 }
488392 }
489393 'type' {
490- rkind := str_of(values[i], 'repo :type')!
394+ rkind := stutter.str_of(values[i], 'repo #:type')!
491395 if rkind !in ['sync', 'pkgbuild'] {
492- return error("config: repo :type is 'sync' or 'pkgbuild', not '${rkind}'")
396+ return error("config: repo #:type is 'sync' or 'pkgbuild', not '${rkind}'")
493397 }
494398 repo = CfgRepo{
495399 ...repo
@@ -497,13 +401,13 @@ fn prim_repo(args []blip.Value) !blip.Value {
497401 }
498402 }
499403 'src' {
500- rservers := strs_of(values[i], 'repo :src')!
404+ rservers := stutter.strs_of(values[i], 'repo #:src')!
501405 if rservers.len == 0 {
502- return error('config: repo :src needs at least one url')
406+ return error('config: repo #:src needs at least one url')
503407 }
504408 for server in rservers {
505409 if server == '' {
506- return error('config: repo :src has an empty url in it')
410+ return error('config: repo #:src has an empty url in it')
507411 }
508412 }
509413 repo = CfgRepo{
@@ -512,20 +416,20 @@ fn prim_repo(args []blip.Value) !blip.Value {
512416 }
513417 }
514418 'usage' {
515- rusage := usage_of(values[i], 'repo :usage')!
419+ rusage := usage_of(values[i], 'repo #:usage')!
516420 repo = CfgRepo{
517421 ...repo
518422 usage: rusage
519423 }
520424 }
521425 else {
522- return error('config: repo has no key :${keys[i]}')
426+ return error('config: repo has no key #:${keys[i]}')
523427 }
524428 }
525429 i++
526430 }
527431 if repo.name == '' {
528- return error('config: repo needs a :name')
432+ return error('config: repo needs a #:name')
529433 }
530434 // libalpm refuses a second db of a name, and 'local' is its own db's:
531435 // said here, by name, instead of late and from inside a mode
@@ -536,13 +440,13 @@ fn prim_repo(args []blip.Value) !blip.Value {
536440 return error('config: repo ${repo.name} is defined twice')
537441 }
538442 if repo.kind == 'sync' && repo.servers.len == 0 {
539- return error('config: a sync repo takes at least one :src')
443+ return error('config: a sync repo takes at least one #:src')
540444 }
541445 if repo.kind == 'pkgbuild' && repo.servers.len != 1 {
542- return error('config: a pkgbuild repo takes one :src, the site to build from')
446+ return error('config: a pkgbuild repo takes one #:src, the site to build from')
543447 }
544448 cfg_repos << repo
545- return blip.nil_value()
449+ return scheme.nil_value()
546450}
547451
548452// pkgbuild_repos are the configured pkgbuild repos, in config order. the
@@ -553,36 +457,36 @@ fn pkgbuild_repos() []CfgRepo {
553457
554458// prim_pkgbuild is the config's (pkgbuild ...) form: makepkg, depth, and
555459// 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)!
460+// build happens is path #:build
461+fn prim_pkgbuild(mut _vm scheme.VM, args []scheme.Value) !scheme.Value {
462+ keys, values := config_keyword_args('pkgbuild', args)!
559463 mut i := 0
560464 for i < keys.len {
561465 match keys[i] {
562466 'makepkg' {
563- m := str_of(values[i], 'pkgbuild :makepkg')!
467+ m := stutter.str_of(values[i], 'pkgbuild #:makepkg')!
564468 if m == '' {
565- return error('config: pkgbuild :makepkg must not be empty')
469+ return error('config: pkgbuild #:makepkg must not be empty')
566470 }
567471 pkgbuild_makepkg = m
568472 }
569473 'depth' {
570- n := int_of(values[i], 'pkgbuild :depth')!
474+ n := stutter.int_of(values[i], 'pkgbuild #:depth')!
571475 if n < 1 {
572- return error('config: pkgbuild :depth must be at least 1')
476+ return error('config: pkgbuild #:depth must be at least 1')
573477 }
574478 pkgbuild_depth = n
575479 }
576480 'timeout' {
577- pkgbuild_rpc_timeout = count_of(values[i], 'pkgbuild :timeout', 1)!
481+ pkgbuild_rpc_timeout = stutter.count_of(values[i], 'pkgbuild #:timeout', 1)!
578482 }
579483 else {
580- return error('config: pkgbuild has no key :${keys[i]}')
484+ return error('config: pkgbuild has no key #:${keys[i]}')
581485 }
582486 }
583487 i++
584488 }
585- return blip.nil_value()
489+ return scheme.nil_value()
586490}
587491
588492// option_flags are the mode flags (options ...) can turn on for every run,
@@ -600,7 +504,7 @@ const option_flags = {
600504}
601505
602506// opt_flags holds the fields of option_flags the config turned on;
603-// opt_color is options :color, empty when the config names none
507+// opt_color is options #:color, empty when the config names none
604508__global opt_flags = map[string]bool{}
605509__global opt_color = ''
606510
@@ -610,43 +514,43 @@ __global opt_color = ''
610514// sync-age, the hours after which the sync dbs are called stale (0: never);
611515// suggest, how close (0 to 1) a name must be to be offered for a typo; and
612516// 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)!
517+fn prim_options(mut _vm scheme.VM, args []scheme.Value) !scheme.Value {
518+ keys, values := config_keyword_args('options', args)!
615519 mut i := 0
616520 for i < keys.len {
617521 match keys[i] {
618522 'root' {
619- r := str_of(values[i], 'options :root')!
523+ r := stutter.str_of(values[i], 'options #:root')!
620524 if r.trim_space() == '' {
621- return error('config: options :root must not be empty')
525+ return error('config: options #:root must not be empty')
622526 }
623527 root_provider = r
624528 }
625529 'color' {
626- c := str_of(values[i], 'options :color')!
530+ c := stutter.str_of(values[i], 'options #:color')!
627531 if c !in ['auto', 'always', 'never'] {
628- return error('config: options :color takes auto, always or never, not "${c}"')
532+ return error('config: options #:color takes auto, always or never, not "${c}"')
629533 }
630534 opt_color = c
631535 }
632536 'sync-age' {
633537 // hours; 0 never warns
634- sync_max_age = i64(count_of(values[i], 'options :sync-age', 0)!) * 3600
538+ sync_max_age = i64(stutter.count_of(values[i], 'options #:sync-age', 0)!) * 3600
635539 }
636540 'suggest' {
637- suggest_thold = ratio_of(values[i], 'options :suggest')!
541+ suggest_thold = stutter.ratio_of(values[i], 'options #:suggest')!
638542 }
639543 'verbose' {
640544 // the verbose log for every run, as --verbose for one
641- cfg_verbose = bool_of(values[i], 'options :verbose')!
545+ cfg_verbose = stutter.bool_of(values[i], 'options #:verbose')!
642546 }
643547 else {
644548 field := option_flags[keys[i]] or {
645- return error('config: options has no key :${keys[i]}')
549+ return error('config: options has no key #:${keys[i]}')
646550 }
647551 // only what is on is held: a false takes back an earlier
648552 // true (an --eval over the file) and leaves no entry behind
649- if bool_of(values[i], 'options :${keys[i]}')! {
553+ if stutter.bool_of(values[i], 'options #:${keys[i]}')! {
650554 opt_flags[field] = true
651555 } else {
652556 opt_flags.delete(field)
@@ -655,105 +559,105 @@ fn prim_options(args []blip.Value) !blip.Value {
655559 }
656560 i++
657561 }
658- return blip.nil_value()
562+ return scheme.nil_value()
659563}
660564
661565// prim_search is the config's (search ...) form: fields, the columns of a
662566// 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)!
567+fn prim_search(mut _vm scheme.VM, args []scheme.Value) !scheme.Value {
568+ keys, values := config_keyword_args('search', args)!
665569 mut i := 0
666570 for i < keys.len {
667571 match keys[i] {
668572 'fields' {
669- names := strs_of(values[i], 'search :fields')!
573+ names := stutter.strs_of(values[i], 'search #:fields')!
670574 if names.len == 0 {
671- return error('config: search :fields needs at least one field')
575+ return error('config: search #:fields needs at least one field')
672576 }
673577 cfg_search_fields = parse_fields(names.join(','), []string{}) or {
674- return error('config: search :fields: ${err.msg()}')
578+ return error('config: search #:fields: ${err.msg()}')
675579 }
676580 }
677581 'thold' {
678- cfg_search_thold = ratio_of(values[i], 'search :thold')!
582+ cfg_search_thold = stutter.ratio_of(values[i], 'search #:thold')!
679583 }
680584 else {
681- return error('config: search has no key :${keys[i]}')
585+ return error('config: search has no key #:${keys[i]}')
682586 }
683587 }
684588 i++
685589 }
686- return blip.nil_value()
590+ return scheme.nil_value()
687591}
688592
689593// prim_clean is the config's (clean ...) form: keep, the versions of every
690594// package the cache keeps when -k names none
691-fn prim_clean(args []blip.Value) !blip.Value {
692- keys, values := keyword_args('clean', args)!
595+fn prim_clean(mut _vm scheme.VM, args []scheme.Value) !scheme.Value {
596+ keys, values := config_keyword_args('clean', args)!
693597 mut i := 0
694598 for i < keys.len {
695599 match keys[i] {
696600 'keep' {
697- cfg_clean_keep = count_of(values[i], 'clean :keep', 0)!
601+ cfg_clean_keep = stutter.count_of(values[i], 'clean #:keep', 0)!
698602 }
699603 else {
700- return error('config: clean has no key :${keys[i]}')
604+ return error('config: clean has no key #:${keys[i]}')
701605 }
702606 }
703607 i++
704608 }
705- return blip.nil_value()
609+ return scheme.nil_value()
706610}
707611
708612// prim_tree is the config's (tree ...) form: depth, how deep a tree is
709613// drawn when -d names none
710-fn prim_tree(args []blip.Value) !blip.Value {
711- keys, values := keyword_args('tree', args)!
614+fn prim_tree(mut _vm scheme.VM, args []scheme.Value) !scheme.Value {
615+ keys, values := config_keyword_args('tree', args)!
712616 mut i := 0
713617 for i < keys.len {
714618 match keys[i] {
715619 'depth' {
716- cfg_tree_depth = count_of(values[i], 'tree :depth', 0)!
620+ cfg_tree_depth = stutter.count_of(values[i], 'tree #:depth', 0)!
717621 }
718622 else {
719- return error('config: tree has no key :${keys[i]}')
623+ return error('config: tree has no key #:${keys[i]}')
720624 }
721625 }
722626 i++
723627 }
724- return blip.nil_value()
628+ return scheme.nil_value()
725629}
726630
727631// prim_color is the config's (color ...) form, the theme: each key is a role
728632// 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)!
633+// style_names, e.g. (color #:version "cyan" #:warning #("bold" "magenta"))
634+fn prim_color(mut _vm scheme.VM, args []scheme.Value) !scheme.Value {
635+ keys, values := config_keyword_args('color', args)!
732636 mut i := 0
733637 for i < keys.len {
734638 if keys[i] !in theme {
735- return error('config: color has no role :${keys[i]}, the roles are: ${default_theme().keys().join(', ')}')
639+ return error('config: color has no role #:${keys[i]}, the roles are: ${default_theme().keys().join(', ')}')
736640 }
737- styles := strs_of(values[i], 'color :${keys[i]}')!
641+ styles := stutter.strs_of(values[i], 'color #:${keys[i]}')!
738642 for style in styles {
739643 if style !in style_names {
740- return error('config: color :${keys[i]} takes ${style_names.join(', ')}, not "${style}"')
644+ return error('config: color #:${keys[i]} takes ${style_names.join(', ')}, not "${style}"')
741645 }
742646 }
743647 theme[keys[i]] = styles.clone()
744648 i++
745649 }
746- return blip.nil_value()
650+ return scheme.nil_value()
747651}
748652
749653// 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
654+// ranker, new or one of its own redefined. #:name is what rank is asked for
655+// (and what /etc/os-release is matched against), #:repo the repo whose db the
656+// speed test pulls, and the mirrors come from one of #:status, a mirror
657+// status json api as arch publishes, or #:list, a Server = mirrorlist at a
754658// url or an absolute path
755-fn prim_mirrorlist(args []blip.Value) !blip.Value {
756- keys, values := keyword_args('mirrorlist', args)!
659+fn prim_mirrorlist(mut _vm scheme.VM, args []scheme.Value) !scheme.Value {
660+ keys, values := config_keyword_args('mirrorlist', args)!
757661 mut name := ''
758662 mut status := ''
759663 mut list := ''
@@ -761,121 +665,110 @@ fn prim_mirrorlist(args []blip.Value) !blip.Value {
761665 mut i := 0
762666 for i < keys.len {
763667 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]}') }
668+ 'name' { name = stutter.str_of(values[i], 'mirrorlist #:name')! }
669+ 'status' { status = stutter.str_of(values[i], 'mirrorlist #:status')! }
670+ 'list' { list = stutter.str_of(values[i], 'mirrorlist #:list')! }
671+ 'repo' { repo = stutter.str_of(values[i], 'mirrorlist #:repo')! }
672+ else { return error('config: mirrorlist has no key #:${keys[i]}') }
769673 }
770674 i++
771675 }
772676 if name == '' || name.contains('/') || name.starts_with('.') || name.starts_with('-')
773677 || name.fields().len != 1 || name.fields()[0] != name {
774- return error('config: mirrorlist needs a :name, one plain word')
678+ return error('config: mirrorlist needs a #:name, one plain word')
775679 }
776680 if repo == '' {
777- return error('config: mirrorlist ${name} needs a :repo, the repo whose db is timed')
681+ return error('config: mirrorlist ${name} needs a #:repo, the repo whose db is timed')
778682 }
779683 if (status == '') == (list == '') {
780- return error('config: mirrorlist ${name} takes one of :status and :list')
684+ return error('config: mirrorlist ${name} takes one of #:status and #:list')
781685 }
782686 if status != '' && !status.starts_with('https://') && !status.starts_with('http://') {
783- return error('config: mirrorlist ${name} :status must be an http or https url')
687+ return error('config: mirrorlist ${name} #:status must be an http or https url')
784688 }
785689 if list != '' && !list.starts_with('https://') && !list.starts_with('http://')
786690 && !list.starts_with('/') {
787- return error('config: mirrorlist ${name} :list must be a url or an absolute path')
691+ return error('config: mirrorlist ${name} #:list must be a url or an absolute path')
788692 }
789693 rank_oses[name] = RankOs{
790694 status_json: status
791695 mirrorlist: list
792696 repo: repo
793697 }
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
698+ return scheme.nil_value()
806699}
807700
808701// prim_progress is the config's (progress ...) form, the bars: style
809702// ('classic' or 'block'); the graphic's pieces start, end, fill, head and
810703// empty; length in cells (0 fills the terminal); percent, eta, elapsed and
811704// 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)!
705+fn prim_progress(mut _vm scheme.VM, args []scheme.Value) !scheme.Value {
706+ keys, values := config_keyword_args('progress', args)!
814707 mut i := 0
815708 for i < keys.len {
816- what := 'progress :${keys[i]}'
709+ what := 'progress #:${keys[i]}'
817710 match keys[i] {
818711 'style' {
819- s := str_of(values[i], what)!
712+ s := stutter.str_of(values[i], what)!
820713 if s !in ['classic', 'block'] {
821714 return error('config: ${what} is classic or block, not "${s}"')
822715 }
823716 cfg_progress.style = s
824717 }
825718 'start', 'end' {
826- cfg_progress.parts[keys[i]] = str_of(values[i], what)!
719+ cfg_progress.parts[keys[i]] = stutter.str_of(values[i], what)!
827720 }
828721 'fill', 'empty' {
829- cfg_progress.parts[keys[i]] = cell_of(values[i], what, false)!
722+ cfg_progress.parts[keys[i]] = stutter.cell_of(values[i], what, false)!
830723 }
831724 'head' {
832- cfg_progress.parts[keys[i]] = cell_of(values[i], what, true)!
725+ cfg_progress.parts[keys[i]] = stutter.cell_of(values[i], what, true)!
833726 }
834727 'length' {
835- cfg_progress.length = count_of(values[i], what, 0)!
728+ cfg_progress.length = stutter.count_of(values[i], what, 0)!
836729 }
837730 'percent' {
838- cfg_progress.percent = bool_of(values[i], what)!
731+ cfg_progress.percent = stutter.bool_of(values[i], what)!
839732 }
840733 'eta' {
841- cfg_progress.eta = bool_of(values[i], what)!
734+ cfg_progress.eta = stutter.bool_of(values[i], what)!
842735 }
843736 'elapsed' {
844- cfg_progress.elapsed = bool_of(values[i], what)!
737+ cfg_progress.elapsed = stutter.bool_of(values[i], what)!
845738 }
846739 'rate' {
847- cfg_progress.rate = bool_of(values[i], what)!
740+ cfg_progress.rate = stutter.bool_of(values[i], what)!
848741 }
849742 'delay' {
850- cfg_progress.delay = count_of(values[i], what, 1)!
743+ cfg_progress.delay = stutter.count_of(values[i], what, 1)!
851744 }
852745 else {
853- return error('config: progress has no key :${keys[i]}')
746+ return error('config: progress has no key #:${keys[i]}')
854747 }
855748 }
856749 i++
857750 }
858- return blip.nil_value()
751+ return scheme.nil_value()
859752}
860753
861754// prim_spinner is the config's (spinner ...) form: frames, a set by name
862755// (spinner_sets) or a list of frames of one's own; interval, the
863756// milliseconds a frame stays; done, what a finished step shows in place of
864757// 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)!
758+fn prim_spinner(mut _vm scheme.VM, args []scheme.Value) !scheme.Value {
759+ keys, values := config_keyword_args('spinner', args)!
867760 mut i := 0
868761 for i < keys.len {
869- what := 'spinner :${keys[i]}'
762+ what := 'spinner #:${keys[i]}'
870763 match keys[i] {
871764 'frames' {
872- if values[i].tag == .string {
873- name := values[i].as_string()
765+ if values[i].kind() == .string {
766+ name := values[i].as_string()!
874767 cfg_progress.frames = spinner_frames_named(name) or {
875768 return error('config: ${what} knows ${spinner_sets.join(', ')}, not "${name}"; a list gives frames of your own')
876769 }
877770 } else {
878- frames := strs_of(values[i], what)!
771+ frames := stutter.strs_of(values[i], what)!
879772 if frames.len == 0 {
880773 return error('config: ${what} needs at least one frame')
881774 }
@@ -883,45 +776,21 @@ fn prim_spinner(args []blip.Value) !blip.Value {
883776 }
884777 }
885778 'interval' {
886- cfg_progress.interval = count_of(values[i], what, 1)!
779+ cfg_progress.interval = stutter.count_of(values[i], what, 1)!
887780 }
888781 'done' {
889- cfg_progress.done = str_of(values[i], what)!
782+ cfg_progress.done = stutter.str_of(values[i], what)!
890783 }
891784 'elapsed' {
892- cfg_progress.timed = bool_of(values[i], what)!
785+ cfg_progress.timed = stutter.bool_of(values[i], what)!
893786 }
894787 else {
895- return error('config: spinner has no key :${keys[i]}')
788+ return error('config: spinner has no key #:${keys[i]}')
896789 }
897790 }
898791 i++
899792 }
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]
793+ return scheme.nil_value()
925794}
926795
927796// reset_config puts every config global back at its declared default, the
@@ -930,6 +799,7 @@ fn prim_array_append(args []blip.Value) !blip.Value {
930799// new file does not name; a failed load can leave values behind, and the
931800// next load starts clean again
932801fn reset_config() {
802+ config_vile = true
933803 root_path = '/'
934804 root_provider = 'sudo'
935805 opt_flags = map[string]bool{}
@@ -965,7 +835,7 @@ fn reset_config() {
965835 cfg_logfile = ''
966836 cfg_gpgdir = '/etc/pacman.d/gnupg/'
967837 cfg_protocols = ['https']
968- cfg_siglevel = alpm.SigLevel.package | .package_optional | .database | .database_optional
838+ cfg_siglevel = nspkg.SigLevel.package | .package_optional | .database | .database_optional
969839 cfg_hold = []string{}
970840 cfg_ignore = []string{}
971841 cfg_ignore_groups = []string{}
@@ -986,32 +856,52 @@ fn reset_config() {
986856// vpac, because running on silently could act on the wrong database
987857fn load_config(chosen string, evals []string) ! {
988858 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()}')
859+ old_path := os.join_path(os.dir(config_path), 'config.scm')
860+ path := if chosen != '' {
861+ chosen
862+ } else if !os.exists(config_path) && os.is_file(old_path) {
863+ old_path
864+ } else {
865+ config_path
866+ }
867+ config_vile = os.file_ext(path) == '.vile'
868+ mut reader := stutter.Config{
869+ name: 'vpac'
870+ syntax: if config_vile { .vile } else { .scheme }
871+ path: path
872+ default_path: config_path
873+ required: true
874+ max_steps: 100_000_000
875+ primitives: {
876+ 'defined?': prim_defined
877+ 'path': prim_path
878+ 'pkg': prim_pkg
879+ 'network': prim_network
880+ 'rank': prim_rank
881+ 'pkgbuild': prim_pkgbuild
882+ 'options': prim_options
883+ 'search': prim_search
884+ 'clean': prim_clean
885+ 'tree': prim_tree
886+ 'color': prim_color
887+ 'mirrorlist': prim_mirrorlist
888+ 'progress': prim_progress
889+ 'spinner': prim_spinner
890+ 'repo': prim_repo
891+ }
892+ }.reader()!
893+ if config_vile { bind_config_settings(mut reader.machine)! }
894+ reader.load()!
895+ for source in evals {
896+ // Parenthesized command-line overrides have always been Scheme, including
897+ // for Vile files. An assignment uses the same syntax as the file.
898+ if config_vile && source.trim_space().starts_with('(') {
899+ reader.machine.eval(source) or {
900+ if scheme.is_control_transfer(err) { return err }
901+ return error('<vpac --eval>: ${err.msg()}')
902+ }
903+ } else {
904+ reader.eval(source, '<vpac --eval>')!
1015905 }
1016906 }
1017907}
@@ -1021,7 +911,7 @@ fn load_config(chosen string, evals []string) ! {
1021911fn check_hold(names []string) ! {
1022912 for name in names {
1023913 if name in cfg_hold {
1024- return error('${name} is held by the config: remove it from pkg :hold first')
914+ return error('${name} is held by the config: remove it from pkg #:hold first')
1025915 }
1026916 }
1027917}
@@ -0,0 +1,145 @@
1+module main
2+
3+import vile.scheme
4+
5+fn config_strings(values []string) scheme.Value {
6+ return scheme.list(values.map(scheme.string_value(it)))
7+}
8+
9+// Bind the actual defaults so an assignment can refer to the current value.
10+fn bind_config_settings(mut vm scheme.VM) ! {
11+ vm.eval($embed_file('config_objects.scm').to_string())!
12+ vm.register('vpac-repositories!', replace_config_repositories)!
13+ vm.register('vpac-update-bindings!', update_config_bindings)!
14+ mut settings := {
15+ 'repositories': scheme.nil_value()
16+ 'path-root': scheme.string_value(root_path)
17+ 'path-db': scheme.string_value(db_path)
18+ 'path-log': scheme.string_value(cfg_logfile)
19+ 'path-gpg': scheme.string_value(cfg_gpgdir)
20+ 'path-syslog': scheme.boolean(cfg_syslog)
21+ 'path-cache': config_strings(cfg_cachedirs)
22+ 'path-hook': config_strings(cfg_hookdirs)
23+ 'path-build': scheme.string_value(pkgbuild_dir)
24+ 'pkg-arch': scheme.string_value(arch)
25+ 'pkg-hold': config_strings(cfg_hold)
26+ 'pkg-ignore': config_strings(cfg_ignore)
27+ 'pkg-ignoregroup': config_strings(cfg_ignore_groups)
28+ 'pkg-noupgrade': config_strings(cfg_noupgrade)
29+ 'pkg-noextract': config_strings(cfg_noextract)
30+ 'network-connections': scheme.integer(parallel_downloads)
31+ 'network-protocols': config_strings(cfg_protocols)
32+ 'network-user': scheme.string_value(download_user)
33+ 'network-siglevel': config_strings(siglevel_names.keys().filter(cfg_siglevel.has(siglevel_names[it])))
34+ 'network-disable-timeout': scheme.boolean(cfg_disable_timeout)
35+ 'network-disable-sandbox': scheme.boolean(cfg_disable_sandbox)
36+ 'rank-parallel': scheme.integer(rank_parallel)
37+ 'rank-timeout': scheme.integer(rank_timeout)
38+ 'rank-top': scheme.integer(rank_top)
39+ 'rank-dir': scheme.string_value(rank_dir)
40+ 'rank-candidates': scheme.integer(rank_speed_candidates)
41+ 'rank-retest': scheme.integer(rank_retest)
42+ 'rank-completion': scheme.real(rank_min_completion)
43+ 'rank-max-delay': scheme.integer(rank_max_delay)
44+ 'pkgbuild-makepkg': scheme.string_value(pkgbuild_makepkg)
45+ 'pkgbuild-depth': scheme.integer(pkgbuild_depth)
46+ 'pkgbuild-timeout': scheme.integer(pkgbuild_rpc_timeout)
47+ 'options-root': scheme.string_value(root_provider)
48+ 'options-color': scheme.string_value(opt_color)
49+ 'options-sync-age': scheme.integer(sync_max_age / 3600)
50+ 'options-suggest': scheme.real(suggest_thold)
51+ 'options-verbose': scheme.boolean(cfg_verbose)
52+ 'search-fields': config_strings(cfg_search_fields)
53+ 'search-thold': scheme.real(cfg_search_thold)
54+ 'clean-keep': scheme.integer(cfg_clean_keep)
55+ 'tree-depth': scheme.integer(cfg_tree_depth)
56+ 'progress-style': scheme.string_value(cfg_progress.style)
57+ 'progress-length': scheme.integer(cfg_progress.length)
58+ 'progress-percent': scheme.boolean(cfg_progress.percent)
59+ 'progress-eta': scheme.boolean(cfg_progress.eta)
60+ 'progress-elapsed': scheme.boolean(cfg_progress.elapsed)
61+ 'progress-rate': scheme.boolean(cfg_progress.rate)
62+ 'progress-delay': scheme.integer(cfg_progress.delay)
63+ 'spinner-frames': config_strings(cfg_progress.frames)
64+ 'spinner-interval': scheme.integer(cfg_progress.interval)
65+ 'spinner-done': scheme.string_value(cfg_progress.done)
66+ 'spinner-elapsed': scheme.boolean(cfg_progress.timed)
67+ }
68+ for key, flag in option_flags { settings['options-${key}'] = scheme.boolean(opt_flags[flag]) }
69+ for role, styles in theme { settings['color-${role}'] = config_strings(styles) }
70+ for part in ['start', 'end', 'fill', 'head', 'empty'] {
71+ settings['progress-${part}'] = scheme.string_value(cfg_progress.parts[part])
72+ }
73+ mut rules := []string{cap: settings.len}
74+ mut groups := {
75+ 'repo': true
76+ }
77+ for name, value in settings {
78+ vm.define(name, value)!
79+ group := if name == 'repositories' { 'vpac-repositories!' } else { name.all_before('-') }
80+ key := if name == 'network-connections' { 'parallel' } else { name.all_after('-') }
81+ rules << '(${name} ${group} ${key})'
82+ if name != 'repositories' { groups[group] = true }
83+ }
84+ for group in groups.keys() {
85+ vm.eval("(vpac-set! ${group} (vpac-group ${group} '${group}))")!
86+ }
87+ vm.eval('(vpac-settings set! ' + rules.join(' ') + ')')!
88+}
89+
90+// Group calls in existing Vile files and Scheme overrides share the bindings
91+// that subsequent assignments read. Run the group's own validation first.
92+fn update_config_bindings(mut vm scheme.VM, args []scheme.Value) !scheme.Value {
93+ scheme.check_arity('vpac-update-bindings!', args.len, 2, 2)!
94+ group := args[0].symbol_name()!
95+ keys, values := config_keyword_args(group, args[1].list_items()!)!
96+ if group == 'repo' {
97+ mut fields := map[string]scheme.Value{}
98+ for i, key in keys { fields[key] = values[i] }
99+ kind := fields['type'] or { scheme.string_value('sync') }
100+ constructor := if kind.as_string()! == 'pkgbuild' {
101+ 'pkgbuild-repo'
102+ } else {
103+ 'sync-repo'
104+ }
105+ usage := fields['usage'] or { scheme.string_value('all') }
106+ repo := vm.call(vm.lookup(constructor)!, [fields['name'], fields['src'], usage])!
107+ current := vm.lookup('repositories')!
108+ mut entries := if current.kind() == .vector {
109+ current.vector_items()!
110+ } else {
111+ current.list_items()!
112+ }
113+ entries << repo
114+ vm.define('repositories', scheme.list(entries))!
115+ return scheme.nil_value()
116+ }
117+ for i, key in keys {
118+ name := if group == 'network' && key == 'parallel' {
119+ 'network-connections'
120+ } else {
121+ '${group}-${key}'
122+ }
123+ vm.define(name, values[i])!
124+ }
125+ return scheme.nil_value()
126+}
127+
128+// Reassigning repositories replaces the ordered set. Keep the previous set if
129+// a config catches a validation error and continues evaluating.
130+fn replace_config_repositories(mut vm scheme.VM, args []scheme.Value) !scheme.Value {
131+ scheme.check_arity('repositories', args.len, 2, 2)!
132+ value := args[1]
133+ repos := if value.kind() == .vector { value.vector_items()! } else { value.list_items()! }
134+ register := vm.lookup('register-repo!')!
135+ previous := cfg_repos.clone()
136+ cfg_repos = []CfgRepo{}
137+ for repo in repos {
138+ vm.call(register, [repo]) or {
139+ cfg_repos = previous.clone()
140+ return err
141+ }
142+ }
143+ vm.define('repositories', value)!
144+ return scheme.nil_value()
145+}
@@ -0,0 +1,35 @@
1+; Vile's assignment reader emits set!. Keep its ordinary lexical and accessor
2+; semantics for targets other than the application settings.
3+(import (rename (only (scheme base) set!) (set! vpac-set!)))
4+(define-syntax vpac-settings
5+ (syntax-rules ()
6+ ((_ assign (name group key) ...)
7+ (define-syntax assign
8+ (syntax-rules (name ...)
9+ ((_ name expr) (group 'key expr)) ...
10+ ((_ target expr) (vpac-set! target expr)))))))
11+
12+(define (vpac-group apply-settings group)
13+ (lambda args
14+ (apply apply-settings args)
15+ (vpac-update-bindings! group args)))
16+
17+(define true #t)
18+(define false #f)
19+
20+(define-class <repository> ()
21+ (name #:init-keyword #:name)
22+ (source #:init-keyword #:source)
23+ (usage #:init-keyword #:usage #:init-value "all"))
24+(define-class <sync-repository> (<repository>))
25+(define-class <pkgbuild-repository> (<repository>))
26+
27+(define* (sync-repo name servers #:optional (usage "all"))
28+ (make <sync-repository> #:name name #:source servers #:usage usage))
29+(define* (pkgbuild-repo name site #:optional (usage "all"))
30+ (make <pkgbuild-repository> #:name name #:source site #:usage usage))
31+(define vpac-native-repo repo)
32+(define-method (register-repo! (r <sync-repository>))
33+ (vpac-native-repo #:name (slot-ref r 'name) #:src (slot-ref r 'source) #:usage (slot-ref r 'usage)))
34+(define-method (register-repo! (r <pkgbuild-repository>))
35+ (vpac-native-repo #:name (slot-ref r 'name) #:src (slot-ref r 'source) #:type "pkgbuild" #:usage (slot-ref r 'usage)))
@@ -11,14 +11,65 @@ fn config_tmp(name string) !string {
1111 return tmp
1212}
1313
14+fn test_config_scheme_load_and_eval_share_bindings() ! {
15+ tmp := config_tmp('scheme_load')!
16+ defer {
17+ reset_config()
18+ os.rmdir_all(tmp) or { went_on('remove the test config', err) }
19+ }
20+ os.mkdir_all(os.join_path(tmp, 'parts'))!
21+ os.write_file(os.join_path(tmp, 'parts', 'network.scm'), '(define parallel 6)\n(network #:parallel parallel)')!
22+ cfg := os.join_path(tmp, 'config.scm')
23+ os.write_file(cfg, '(load "parts/network.scm")\n(pkg #:hold (list "glibc" "pacman"))')!
24+ load_config(cfg, ['(network #:parallel (+ parallel 1))'])!
25+ assert parallel_downloads == 7
26+ assert cfg_hold == ['glibc', 'pacman']
27+}
28+
29+fn test_config_vile_assignments_and_repositories() ! {
30+ tmp := config_tmp('vile')!
31+ defer {
32+ reset_config()
33+ os.rmdir_all(tmp) or { went_on('remove the test config', err) }
34+ }
35+ cfg := os.join_path(tmp, 'config.vile')
36+ os.write_file(os.join_path(tmp, 'mirrors.vile'), 'servers := ["https://example.org/repo"]')!
37+ os.write_file(cfg, 'load("mirrors.vile")
38+network-connections = 123
39+network-disable-timeout = true
40+options-color = "never"
41+rank-parallel = network-connections
42+repositories = list(sync-repo("core", servers, ["search"]), pkgbuild-repo("aur", "https://aur.example"))
43+')!
44+ load_config(cfg, ['network-connections = network-connections + 1'])!
45+ assert parallel_downloads == 124 && rank_parallel == 123
46+ assert cfg_disable_timeout && opt_color == 'never'
47+ assert cfg_repos.map(it.name) == ['core', 'aur']
48+ assert cfg_repos[0].servers == ['https://example.org/repo']
49+ assert cfg_repos[0].usage == .search && cfg_repos[1].kind == 'pkgbuild'
50+ assert rank_write_target('arch').ends_with('/arch.vile')
51+ load_config(cfg, ['(network #:parallel 5)', 'network-connections = network-connections + 2'])!
52+ assert parallel_downloads == 7
53+ load_config(cfg, ['repositories = list(sync-repo("other", servers))'])!
54+ assert cfg_repos.map(it.name) == ['other']
55+ load_config(cfg, ['(repo #:name "extra" #:src "file:///extra")',
56+ 'repositories = append(repositories, list(sync-repo("other", servers)))'])!
57+ assert cfg_repos.map(it.name) == ['core', 'aur', 'extra', 'other']
58+ for bad in ['network-connections = 0', 'network-connetions = 8',
59+ 'repositories = list(sync-repo("local", servers))'] {
60+ load_config(cfg, [bad]) or { continue }
61+ assert false, 'accepted invalid setting: ${bad}'
62+ }
63+}
64+
1465fn test_config_options() ! {
1566 tmp := config_tmp('options')!
1667 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')!
68+ cfg := os.join_path(tmp, 'config.scm')
69+ os.write_file(cfg, '(path #:db "${tmp}/db/")\n' +
70+ '(pkg #:ignoregroup #("kde-applications") #:noupgrade #("etc/foo.conf") #:noextract #("usr/share/doc/*" "usr/share/man/*"))\n' +
71+ '(path #:syslog #t)\n' + '(network #:disable-timeout #t #:disable-sandbox #t)\n' + r'(repo #:name "core" #:src #("https://example.org/$repo") #:usage #("sync" "Search"))' +
72+ '\n' + r'(repo #:name "extra" #:src #("https://example.org/$repo"))' + '\n')!
2273 load_config(cfg, [])!
2374
2475 assert cfg_ignore_groups == ['kde-applications']
@@ -57,8 +108,8 @@ fn test_config_disable_sandbox_defaults_on() ! {
57108 os.rmdir_all(tmp) or {}
58109 reset_config()
59110 }
60- cfg := os.join_path(tmp, 'config.lip')
61- os.write_file(cfg, '(network :parallel 2)\n')!
111+ cfg := os.join_path(tmp, 'config.scm')
112+ os.write_file(cfg, '(network #:parallel 2)\n')!
62113 load_config(cfg, [])!
63114 assert !cfg_disable_sandbox
64115 ui := new_trans_ui()
@@ -67,7 +118,7 @@ fn test_config_disable_sandbox_defaults_on() ! {
67118 assert !handle.option_get_disable_sandbox_filesystem()
68119 assert !handle.option_get_disable_sandbox_syscalls()
69120 // a false written out is the same as leaving it out
70- os.write_file(cfg, '(network :disable-sandbox false)\n')!
121+ os.write_file(cfg, '(network #:disable-sandbox #f)\n')!
71122 load_config(cfg, [])!
72123 assert !cfg_disable_sandbox
73124}
@@ -75,52 +126,52 @@ fn test_config_disable_sandbox_defaults_on() ! {
75126fn test_config_rejects_bad_values() ! {
76127 tmp := config_tmp('bad')!
77128 defer { os.rmdir_all(tmp) or {} }
78- cfg := os.join_path(tmp, 'config.lip')
129+ cfg := os.join_path(tmp, 'config.scm')
79130 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'
131+ '(repo #:name "x" #:usage #("sometimes"))': 'takes sync, search, install, upgrade and all'
132+ '(repo #:name "x" #:usage #())': 'needs at least one'
133+ '(network #:disable-timeout "yes")': 'must be #t or #f'
134+ '(network #:disable-sandbox "yes")': 'must be #t or #f'
84135 // an empty one verifies nothing, and a list of no protocols accepts
85136 // 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"'
137+ '(network #:siglevel #())': 'needs at least one of'
138+ '(network #:protocols #())': 'needs at least one'
139+ '(network #:protocols #("ftp"))': 'takes https and http'
140+ '(network #:protocols #("https" "HTTPS"))': 'takes https and http'
141+ '(pkg #:arch "")': 'must be one plain word'
142+ '(pkg #:arch "x86 64")': 'must be one plain word'
143+ '(pkg #:arch " x86_64")': 'must be one plain word'
144+ '(pkg #:arch "a/b")': 'must be one plain word'
145+ '(repo #:name "local" #:src #("http://x"))': 'cannot be named local'
146+ '(repo #:name "x" #:src #("http://x")) (repo #:name "x" #:src #("http://y"))': 'is defined twice'
147+ '(repo #:name "x" #:src #("http://x")) (repo #:name "x" #:type "pkgbuild" #:src #("http://y"))': 'is defined twice'
148+ '(mirrorlist #:name "my os" #:repo "core" #:status "https://x")': 'one plain word'
149+ '(mirrorlist #:name "os\t" #:repo "core" #:status "https://x")': 'one plain word'
150+ '(repo #:name "x" #:src #())': 'needs at least one url'
151+ '(repo #:name "x" #:src "")': 'has an empty url in it'
152+ '(repo #:name "x" #:type "sync")': 'takes at least one #:src'
153+ '(options #:root " ")': 'must not be empty'
154+ '(options #:colour "always")': 'has no key #:colour'
155+ '(options #:color "sometimes")': 'takes auto, always or never'
156+ '(options #:noconfirm "yes")': 'must be #t or #f'
157+ '(options #:suggest 2)': 'between 0 and 1'
158+ '(options #:sync-age -1)': 'at least 0'
159+ '(search #:fields #("nope"))': 'unknown field'
160+ '(search #:thold "high")': 'must be a number'
161+ '(rank #:top 0)': 'at least 1'
162+ '(pkgbuild #:timeout 0)': 'at least 1'
163+ '(color #:nope "red")': 'has no role #:nope'
164+ '(progress #:style "round")': 'classic or block'
165+ '(progress #:fill "==")': 'must be one character'
166+ '(progress #:empty "")': 'must be one character'
167+ '(spinner #:frames "nope")': 'not "nope"'
168+ '(spinner #:frames #())': 'at least one frame'
169+ '(mirrorlist #:name "x" #:repo "core")': 'one of #:status and #:list'
170+ '(mirrorlist #:name "x" #:list "/m")': 'needs a #:repo'
171+ '(mirrorlist #:name "a/b" #:list "/m" #:repo "c")': 'one plain word'
172+ '(mirrorlist #:name "x" #:status "/m" #:repo "c")': 'http or https url'
173+ '(rank #:dir "mirrors")': 'absolute path'
174+ '(color #:name "pink")': 'not "pink"'
124175 } {
125176 os.write_file(cfg, form + '\n')!
126177 if _ := load_config(cfg, []) {
@@ -130,7 +181,7 @@ fn test_config_rejects_bad_values() ! {
130181 }
131182 }
132183 // a list may be a single string, as everywhere in the config
133- os.write_file(cfg, '(pkg :noupgrade "etc/foo.conf")\n')!
184+ os.write_file(cfg, '(pkg #:noupgrade "etc/foo.conf")\n')!
134185 load_config(cfg, [])!
135186 assert cfg_noupgrade == ['etc/foo.conf']
136187}
@@ -141,9 +192,9 @@ fn test_config_rejects_bad_values() ! {
141192fn test_config_resets_between_loads() ! {
142193 tmp := config_tmp('reset')!
143194 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')!
195+ cfg := os.join_path(tmp, 'config.scm')
196+ os.write_file(cfg, '(repo #:name "one" #:src #("https://one.example/$repo"))\n
197+(network #:parallel 5 #:siglevel #("package" "database"))\n(pkg #:hold #("glibc") #:ignore #("flatpak"))\n(options #:root "doas -n")\n')!
147198 load_config(cfg, [])!
148199 assert root_provider == 'doas -n'
149200 assert cfg_repos.map(it.name) == ['one']
@@ -153,7 +204,7 @@ fn test_config_resets_between_loads() ! {
153204 assert cfg_ignore == ['flatpak']
154205 assert cfg_disable_timeout == false
155206
156- os.write_file(cfg, '(repo :name "two" :src "https://two.example/$repo")\n')!
207+ os.write_file(cfg, '(repo #:name "two" #:src "https://two.example/$repo")\n')!
157208 load_config(cfg, [])!
158209 assert cfg_repos.map(it.name) == ['two']
159210 assert cfg_repos.len == 1
@@ -182,24 +233,24 @@ fn test_check_hold() {
182233}
183234
184235// 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;
236+// #:gpg checks signatures against the system keyring, not root's ~/.gnupg;
186237// a named one overrides it for its load only
187238fn test_config_gpgdir_default() ! {
188239 tmp := config_tmp('gpgdir')!
189240 defer { os.rmdir_all(tmp) or {} }
190- cfg := os.join_path(tmp, 'config.lip')
241+ cfg := os.join_path(tmp, 'config.scm')
191242 saved := cfg_gpgdir
192243 defer { cfg_gpgdir = saved }
193244
194- os.write_file(cfg, '(network :parallel 2)\n')!
245+ os.write_file(cfg, '(network #:parallel 2)\n')!
195246 load_config(cfg, [])!
196247 assert cfg_gpgdir == '/etc/pacman.d/gnupg/'
197248
198- os.write_file(cfg, '(path :gpg "${tmp}/keys")\n')!
249+ os.write_file(cfg, '(path #:gpg "${tmp}/keys")\n')!
199250 load_config(cfg, [])!
200251 assert cfg_gpgdir == '${tmp}/keys/'
201252
202- os.write_file(cfg, '(network :parallel 2)\n')!
253+ os.write_file(cfg, '(network #:parallel 2)\n')!
203254 load_config(cfg, [])!
204255 assert cfg_gpgdir == '/etc/pacman.d/gnupg/'
205256}
@@ -233,8 +284,8 @@ fn test_config_options_set_mode_flags() ! {
233284 os.rmdir_all(tmp) or {}
234285 reset_config()
235286 }
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')!
287+ cfg := os.join_path(tmp, 'config.scm')
288+ os.write_file(cfg, '(options #:noconfirm #t #:needed #t #:nopkgbuildconfirm #t #:no-upgrade-deps #t #:color "never")\n')!
238289 load_config(cfg, [])!
239290 assert opt_color == 'never'
240291 install_mode := parse_mode(['vpac', 'i', 'foo'])!
@@ -251,7 +302,7 @@ fn test_config_options_set_mode_flags() ! {
251302 } else {
252303 assert false
253304 }
254- load_config(cfg, ['(options :noconfirm false)'])!
305+ load_config(cfg, ['(options #:noconfirm #f)'])!
255306 again := parse_mode(['vpac', 'i', 'foo'])!
256307 if again is ConfigInstall {
257308 assert !again.noconfirm && again.needed
@@ -271,12 +322,12 @@ fn test_config_tunables() ! {
271322 color_flag = old_color
272323 reset_config()
273324 }
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')!
325+ cfg := os.join_path(tmp, 'config.scm')
326+ os.write_file(cfg, '(options #:sync-age 0 #:suggest 0.5 #:fuzzy #t)\n' +
327+ '(search #:fields #("name" "version") #:thold 0.7)\n' +
328+ '(rank #:top 3 #:candidates 12 #:retest 0 #:completion 0.9 #:max-delay 3600)\n' +
329+ '(pkgbuild #:timeout 30)\n(clean #:keep 2)\n(tree #:depth 4)\n' +
330+ '(color #:version "cyan" #:warning #("bold" "magenta") #:name "none")\n')!
280331 load_config(cfg, [])!
281332 assert sync_max_age == 0
282333 assert suggest_thold == 0.5
@@ -327,7 +378,7 @@ fn test_config_tunables() ! {
327378 assert name_style('n') == 'n'
328379 assert warning('w').starts_with('\x1b[')
329380
330- os.write_file(cfg, '(path :db "${tmp}/db/")\n')!
381+ os.write_file(cfg, '(path #:db "${tmp}/db/")\n')!
331382 load_config(cfg, [])!
332383 assert sync_max_age == 24 * 60 * 60
333384 assert cfg_search_fields == search_default_fields
@@ -346,12 +397,12 @@ fn test_config_display_and_mirrorlists() ! {
346397 }
347398 list := os.join_path(tmp, 'mirrorlist')
348399 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')!
400+ cfg := os.join_path(tmp, 'config.scm')
401+ os.write_file(cfg, '(progress #:style "classic" #:start "|" #:end "|" #:fill "#" #:head "" #:empty "." #:length 12 #:percent #f #:eta #f #:elapsed #t #:rate #f #:delay 100)\n' +
402+ '(spinner #:frames #("a" "b") #:interval 200 #:done "ok" #:elapsed #t)\n' +
403+ '(mirrorlist #:name "myos" #:list "${list}" #:repo "main")\n' +
404+ '(mirrorlist #:name "arch" #:status "https://example.org/status.json" #:repo "core")\n' +
405+ '(rank #:dir "${tmp}/ranked/")\n')!
355406 load_config(cfg, [])!
356407
357408 bar := bar_opts(text: 'x', show_rate: true)
@@ -374,15 +425,15 @@ fn test_config_display_and_mirrorlists() ! {
374425 assert 'artix' in rank_oses
375426 mirrors := fetch_mirrorlist(rank_oses['myos'])!
376427 assert mirrors.len == 2, mirrors.str()
377- assert rank_write_target('myos') == '${tmp}/ranked/myos.lip'
428+ assert rank_write_target('myos') == '${tmp}/ranked/myos.scm'
378429
379- os.write_file(cfg, '(spinner :frames "line")\n(progress :style "block")\n')!
430+ os.write_file(cfg, '(spinner #:frames "line")\n(progress #:style "block")\n')!
380431 load_config(cfg, [])!
381432 assert cfg_progress.frames == progress.spinner_line()
382433 assert bar_opts(text: 'x').style is progress.BlockStyle
383434 assert bar_opts(text: 'x').length == 30
384435 assert 'myos' !in rank_oses
385- assert rank_write_target('arch') == '/etc/vpac.d/mirrors/arch.lip'
436+ assert rank_write_target('arch') == '/etc/vpac.d/mirrors/arch.scm'
386437}
387438
388439// an option the config turns off holds no entry: only what is on is kept,
@@ -393,20 +444,20 @@ fn test_config_options_hold_only_what_is_on() ! {
393444 os.rmdir_all(tmp) or {}
394445 reset_config()
395446 }
396- cfg := os.join_path(tmp, 'config.lip')
397- os.write_file(cfg, '(options :noconfirm false :needed true)\n')!
447+ cfg := os.join_path(tmp, 'config.scm')
448+ os.write_file(cfg, '(options #:noconfirm #f #:needed #t)\n')!
398449 load_config(cfg, [])!
399450 assert 'noconfirm' !in opt_flags
400451 assert opt_flags == {
401452 'needed': true
402453 }
403454 // a later form, as an --eval is, turns it off again and leaves nothing
404- load_config(cfg, ['(options :needed false)'])!
455+ load_config(cfg, ['(options #:needed #f)'])!
405456 assert opt_flags.len == 0
406457 mode := parse_mode(['vpac', 'i', 'foo'])! as ConfigInstall
407458 assert !mode.needed && !mode.noconfirm
408459 // the key of the flag nothing read is gone with the flag
409- for form in ['(options :upgrade-deps true)', '(options :verbose "yes")'] {
460+ for form in ['(options #:upgrade-deps #t)', '(options #:verbose "yes")'] {
410461 os.write_file(cfg, form + '\n')!
411462 if _ := load_config(cfg, []) {
412463 assert false, '${form} was accepted'
@@ -414,7 +465,7 @@ fn test_config_options_hold_only_what_is_on() ! {
414465 }
415466}
416467
417-// options :verbose turns the verbose log on for every run, and a load that
468+// options #:verbose turns the verbose log on for every run, and a load that
418469// does not name it turns it off again: it is the config's, reset with it
419470fn test_config_verbose_is_reset_with_the_config() ! {
420471 tmp := config_tmp('verbose')!
@@ -425,14 +476,14 @@ fn test_config_verbose_is_reset_with_the_config() ! {
425476 reset_config()
426477 }
427478 verbose_flag = false
428- cfg := os.join_path(tmp, 'config.lip')
429- os.write_file(cfg, '(options :verbose true)\n')!
479+ cfg := os.join_path(tmp, 'config.scm')
480+ os.write_file(cfg, '(options #:verbose #t)\n')!
430481 load_config(cfg, [])!
431482 assert cfg_verbose && verbose_on()
432483 // an --eval after the file takes it back for a run
433- load_config(cfg, ['(options :verbose false)'])!
484+ load_config(cfg, ['(options #:verbose #f)'])!
434485 assert !cfg_verbose && !verbose_on()
435- os.write_file(cfg, '(options :color "never")\n')!
486+ os.write_file(cfg, '(options #:color "never")\n')!
436487 load_config(cfg, [])!
437488 assert !cfg_verbose
438489 // the command line's flag is not the config's to reset
@@ -1,11 +1,11 @@
11@[has_globals]
22module main
33
4-import alpm
4+import nspkg
55import os
66import time
77
8-// arch and the download user are configurable through config.lip
8+// arch and the download user are configurable through the config
99
1010// pkgcache_of is a db's package list. libalpm hands an empty db's list over
1111// as NULL, the NULL it answers an error with too: alpm_db_get_pkgcache
@@ -13,18 +13,18 @@ import time
1313// an empty list here — a nil one, which every list reader takes as such
1414// (pkgs, pkg_find, find_satisfier) — never a failure: a fresh root has no
1515// package installed, and pacman finds nothing in it rather than failing
16-fn pkgcache_of(handle &alpm.Handle, db &alpm.DB) !&alpm.List {
16+fn pkgcache_of(handle &nspkg.Handle, db &nspkg.DB) !&nspkg.List {
1717 return db.get_pkgcache() or {
1818 e := handle.errno()
1919 if e != .ok {
2020 return error('could not read the packages of ${db.get_name()}: ${e.strerror()}')
2121 }
22- unsafe { &alpm.List(nil) }
22+ unsafe { &nspkg.List(nil) }
2323 }
2424}
2525
2626// local_pkgcache is the installed packages' list, as pkgcache_of reads one
27-fn local_pkgcache(handle &alpm.Handle) !&alpm.List {
27+fn local_pkgcache(handle &nspkg.Handle) !&nspkg.List {
2828 localdb := handle.get_localdb() or { return error('could not open the local database: ${err.msg()}') }
2929 return pkgcache_of(handle, localdb)
3030}
@@ -65,11 +65,11 @@ fn check_ask_db_lock(mut ui TransUI) {
6565// init_repo registers one sync db under its name and mirrors; the arch comes
6666// from the config, so the parameter is named a to keep the global visible
6767// 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
68+// `mut handle nspkg.Handle`, which is already the caller's pointer: spelled
69+// `mut handle &nspkg.Handle` the same body hands libalpm a pointer one level
7070// off, and alpm_db_update crashes on it (tried for the review's sake, and
7171// 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 {
72+fn init_repo(mut handle nspkg.Handle, repo string, servers []string, a string, usage nspkg.DBUsage) !&nspkg.DB {
7373 // the siglevel is the configured one (pacman's default without config):
7474 // libalpm's own default is 0, which verifies nothing
7575 db := handle.register_syncdb(repo, int(cfg_siglevel))!
@@ -83,7 +83,7 @@ fn init_repo(mut handle alpm.Handle, repo string, servers []string, a string, us
8383// a sync db counts as synced if its file is this recent, or if vpac updated
8484// the dbs this recently. libalpm sets the file time from the mirror, so an
8585// 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
86+// (options #:sync-age hours) sets it; 0 never calls a db stale
8787__global sync_max_age = i64(24 * 60 * 60)
8888
8989// sync_stamp is a function because db_path is configurable
@@ -91,7 +91,7 @@ fn sync_stamp() string {
9191 return db_path + 'sync/vpac.synced'
9292}
9393
94-fn update_repos(mut handle alpm.Handle, force bool) ! {
94+fn update_repos(mut handle nspkg.Handle, force bool) ! {
9595 // one db_update call: libalpm itself updates only the stale dbs, and
9696 // "up to date" (returned as 1) is an answer, not an error. whatever it
9797 // did, the dbs are known current now, so the stamp is written
@@ -106,7 +106,7 @@ fn update_repos(mut handle alpm.Handle, force bool) ! {
106106// stale_sync_dbs lists the sync dbs not synced within sync_max_age. a sync
107107// db listing that fails is said: an empty answer would read as 'fresh
108108// enough', and it never was
109-fn stale_sync_dbs(handle &alpm.Handle) []string {
109+fn stale_sync_dbs(handle &nspkg.Handle) []string {
110110 dbs := handle.get_syncdbs() or {
111111 warn('could not list the sync databases: ${err.msg()}')
112112 return []string{}
@@ -130,7 +130,7 @@ fn stale_sync_dbs(handle &alpm.Handle) []string {
130130// only root can update them, so anyone else gets the warning and carries on,
131131// and so does a --print preview, which changes nothing. the warning goes to
132132// stderr, so it stays out of piped results
133-fn check_sync_fresh(mut ui TransUI, mut handle &alpm.Handle) ! {
133+fn check_sync_fresh(mut ui TransUI, mut handle &nspkg.Handle) ! {
134134 stale := stale_sync_dbs(handle)
135135 if stale.len == 0 {
136136 return
@@ -155,8 +155,8 @@ fn check_sync_fresh(mut ui TransUI, mut handle &alpm.Handle) ! {
155155// config lists them. the pkgbuild repo is not a sync db: it is built from,
156156// not downloaded. urls keep the $repo and $arch placeholders for libalpm to
157157// substitute
158-fn init_repos(mut handle alpm.Handle) ![]&alpm.DB {
159- mut dbs := []&alpm.DB{}
158+fn init_repos(mut handle nspkg.Handle) ![]&nspkg.DB {
159+ mut dbs := []&nspkg.DB{}
160160 for repo in cfg_repos {
161161 if repo.kind == 'pkgbuild' {
162162 continue
@@ -1,6 +1,6 @@
11module main
22
3-import alpm
3+import nspkg
44import os
55
66// pacman's -Dk and -Dkk, as vpac v -D and -DD. every check returns the
@@ -29,7 +29,7 @@ fn db_local_files(dbpath string) ![]string {
2929
3030// db_missing_deps: every dependency of the packages, satisfied among the
3131// packages themselves
32-fn db_missing_deps(handle &alpm.Handle, pkgs &alpm.List) []string {
32+fn db_missing_deps(handle &nspkg.Handle, pkgs &nspkg.List) []string {
3333 mut out := []string{}
3434 mut head := handle.checkdeps(unsafe { nil }, unsafe { nil }, pkgs, 0)
3535 defer {
@@ -37,7 +37,7 @@ fn db_missing_deps(handle &alpm.Handle, pkgs &alpm.List) []string {
3737 // inner first, then the list, as pacman's check_db_missing_deps does
3838 head.free_inner(fn (p voidptr) {
3939 unsafe {
40- miss := &alpm.DepMissing(p)
40+ miss := &nspkg.DepMissing(p)
4141 miss.free()
4242 }
4343 })
@@ -46,7 +46,7 @@ fn db_missing_deps(handle &alpm.Handle, pkgs &alpm.List) []string {
4646 // node walks to nil; the head is what lives
4747 mut node := head
4848 for node != unsafe { nil } {
49- miss := unsafe { &alpm.DepMissing(node.data) }
49+ miss := unsafe { &nspkg.DepMissing(node.data) }
5050 target := unsafe { cstring_to_vstring(miss.target) }
5151 out << "missing '${miss.depend.compute_string()}' dependency for '${target}'"
5252 node = node.next
@@ -55,7 +55,7 @@ fn db_missing_deps(handle &alpm.Handle, pkgs &alpm.List) []string {
5555}
5656
5757// db_package_conflicts: no two installed packages conflict
58-fn db_package_conflicts(handle &alpm.Handle, pkgs &alpm.List) []string {
58+fn db_package_conflicts(handle &nspkg.Handle, pkgs &nspkg.List) []string {
5959 mut out := []string{}
6060 mut head := handle.checkconflicts(pkgs)
6161 defer {
@@ -63,7 +63,7 @@ fn db_package_conflicts(handle &alpm.Handle, pkgs &alpm.List) []string {
6363 // check_db_local_package_conflicts does: inner, then the list
6464 head.free_inner(fn (p voidptr) {
6565 unsafe {
66- conf := &alpm.Conflict(p)
66+ conf := &nspkg.Conflict(p)
6767 conf.free()
6868 }
6969 })
@@ -72,7 +72,7 @@ fn db_package_conflicts(handle &alpm.Handle, pkgs &alpm.List) []string {
7272 // node walks to nil; the head is what lives
7373 mut node := head
7474 for node != unsafe { nil } {
75- c := unsafe { &alpm.Conflict(node.data) }
75+ c := unsafe { &nspkg.Conflict(node.data) }
7676 out << "'${c.package1.get_name()}' conflicts with '${c.package2.get_name()}'"
7777 node = node.next
7878 }
@@ -81,7 +81,7 @@ fn db_package_conflicts(handle &alpm.Handle, pkgs &alpm.List) []string {
8181
8282// db_filelist_conflicts: no file, directories aside, belongs to two
8383// packages. every pair of owners is reported, in file order
84-fn db_filelist_conflicts(pkgs []&alpm.Package) []string {
84+fn db_filelist_conflicts(pkgs []&nspkg.Package) []string {
8585 // the owners of every file seen so far, so a third package that shares
8686 // one clashes with both of the ones before it
8787 mut owners := map[string][]string{}
@@ -109,7 +109,7 @@ fn db_filelist_conflicts(pkgs []&alpm.Package) []string {
109109// check_db_local is -Dk: the local db's files, then its packages'
110110// dependencies, conflicts and shared files. the checks accumulate: each one
111111// speaks for itself, and none hides the later ones behind an early return
112-fn check_db_local(handle &alpm.Handle, dbpath string) ![]string {
112+fn check_db_local(handle &nspkg.Handle, dbpath string) ![]string {
113113 mut out := db_local_files(dbpath)!
114114 mut pkgcache := local_pkgcache(handle)!
115115 out << db_missing_deps(handle, pkgcache)
@@ -121,8 +121,8 @@ fn check_db_local(handle &alpm.Handle, dbpath string) ![]string {
121121// check_db_sync is -Dkk: every sync package's dependencies, satisfied
122122// across all the sync dbs. a cache that cannot be read has the db say so;
123123// 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 })
124+fn check_db_sync(handle &nspkg.Handle) ![]string {
125+ mut all := &nspkg.List(unsafe { nil })
126126 mut syncdbs := handle.get_syncdbs()!
127127 for db in syncdbs.dbs() {
128128 // a cache that cannot be read is named, so its unchecked packages
@@ -141,7 +141,7 @@ fn check_db_sync(handle &alpm.Handle) ![]string {
141141
142142// verify_db is vpac v -D (level 1) and -DD (level 2). each error is a failed
143143// target, so vpac exits 1 when there is any
144-fn verify_db(mut handle &alpm.Handle, level int) ! {
144+fn verify_db(mut handle &nspkg.Handle, level int) ! {
145145 errors := if level >= 2 {
146146 init_repos(mut handle)!
147147 check_db_sync(handle)!
@@ -1,6 +1,6 @@
11module main
22
3-import alpm
3+import nspkg
44import os
55import testdb
66
@@ -46,7 +46,7 @@ fn test_check_db_local() ! {
4646 files: ['usr/', 'usr/share/shared']
4747 },
4848 ])!
49- handle := alpm.initialize(os.join_path(tmp, 'root') + '/', dbpath)!
49+ handle := nspkg.initialize(os.join_path(tmp, 'root') + '/', dbpath)!
5050 defer { handle.release() or {} }
5151 errors := check_db_local(handle, dbpath)!
5252 // a dependency nothing provides, one whose version does not match, two
@@ -74,7 +74,7 @@ fn test_check_db_local_clean() ! {
7474 files: ['usr/', 'usr/lib/lib.so']
7575 },
7676 ])!
77- handle := alpm.initialize(os.join_path(tmp, 'root') + '/', dbpath)!
77+ handle := nspkg.initialize(os.join_path(tmp, 'root') + '/', dbpath)!
7878 defer { handle.release() or {} }
7979 assert check_db_local(handle, dbpath)! == []
8080}
@@ -3,7 +3,7 @@ module main
33import os
44
55// 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
6+// setup. the nspkg binding once wrote its SigLevel bits as masks where a V
77// flag enum takes positions, and libalpm got 6 instead of 3075: no package
88// or database signature was ever checked
99fn test_default_siglevel_reaches_libalpm() ! {
@@ -47,7 +47,7 @@ fn test_default_siglevel_reaches_libalpm() ! {
4747 assert int(usage) == 1 | 2
4848}
4949
50-// every name the config's (network :siglevel ...) takes is libalpm's bit
50+// every name the config's (network #:siglevel ...) takes is libalpm's bit
5151fn test_siglevel_names() {
5252 want := {
5353 'package': 1 << 0
@@ -1,6 +1,6 @@
11module main
22
3-import alpm
3+import nspkg
44
55struct ConfigDeptest {
66pub mut:
@@ -10,7 +10,7 @@ pub mut:
1010
1111// unsatisfied_deps are the dependencies no installed package satisfies, in
1212// the order and the spelling they were given
13-fn unsatisfied_deps(pkgcache &alpm.List, deps []string) []string {
13+fn unsatisfied_deps(pkgcache &nspkg.List, deps []string) []string {
1414 mut out := []string{}
1515 for dep in deps {
1616 if _ := pkgcache.find_satisfier(dep) {
@@ -26,8 +26,8 @@ fn unsatisfied_deps(pkgcache &alpm.List, deps []string) []string {
2626// makepkg tells apart from a failure. it changes nothing, so it needs no root
2727fn deptest(config ConfigDeptest) ![]string {
2828 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) } }
29+ handle := nspkg.initialize(root_path, db_path) or { return err }
30+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
3131 pkgcache := local_pkgcache(handle)!
3232 missing := unsatisfied_deps(pkgcache, config.query)
3333 if ipc_on() {
@@ -1,6 +1,6 @@
11module main
22
3-import alpm
3+import nspkg
44import os
55
66fn test_unsatisfied_deps() ! {
@@ -18,7 +18,7 @@ fn test_unsatisfied_deps() ! {
1818 os.mkdir_all(dir)!
1919 os.write_file(os.join_path(dir, 'desc'), '%NAME%\n${name}\n\n%VERSION%\n5.9-1\n\n${extra}')!
2020 }
21- handle := alpm.initialize(os.join_path(tmp, 'root') + '/', os.join_path(tmp, 'db') + '/')!
21+ handle := nspkg.initialize(os.join_path(tmp, 'root') + '/', os.join_path(tmp, 'db') + '/')!
2222 defer { handle.release() or {} }
2323 pkgcache := handle.get_localdb()!.get_pkgcache() or { return error('empty db') }
2424
@@ -1,6 +1,6 @@
11module main
22
3-import alpm
3+import nspkg
44import v.profiler
55
66// DepTracer walks the dependency graph straight from libalpm: the local db
@@ -11,10 +11,10 @@ import v.profiler
1111// among them never touches the sync dbs
1212struct DepTracer {
1313mut:
14- handle &alpm.Handle
14+ handle &nspkg.Handle
1515 ui &TransUI
1616 lookup &InfoLookup
17- installed &alpm.List
17+ installed &nspkg.List
1818 sync_lost bool
1919 reverse bool
2020 optional bool
@@ -26,7 +26,7 @@ mut:
2626// nothing provides (pkg is nil then, and dep is how it was asked for). tag
2727// marks an optional dependency
2828struct TreeNode {
29- pkg &alpm.Package = unsafe { nil }
29+ pkg &nspkg.Package = unsafe { nil }
3030 dep string
3131 tag string
3232}
@@ -42,7 +42,7 @@ struct TreeBranch {
4242
4343// tree_label is the name and version, then the size: what the package takes
4444// on disk when installed, or what it downloads when it is only in the repos
45-fn tree_label(pkg &alpm.Package) string {
45+fn tree_label(pkg &nspkg.Package) string {
4646 label := '${name_style(pkg.get_name())} ${version_style(pkg.get_version())}'
4747 if pkg.get_origin() == .syncdb {
4848 return '${label} (${profiler.format_bytes(u64(pkg.download_size()))} to download)'
@@ -89,7 +89,7 @@ fn (mut t DepTracer) dep_node(depstring string, tag string) TreeNode {
8989}
9090
9191// children are what the package depends on, or with -r what requires it
92-fn (mut t DepTracer) children(pkg &alpm.Package) []TreeNode {
92+fn (mut t DepTracer) children(pkg &nspkg.Package) []TreeNode {
9393 mut nodes := []TreeNode{}
9494 if t.reverse {
9595 for name in pkg.compute_required_by() {
@@ -178,7 +178,7 @@ fn tree(config ConfigTree) ! {
178178 need_query(config.query, 'package')!
179179 mut ui := new_trans_ui(noconfirm: config.noconfirm)
180180 mut handle := init_handle(ui)!
181- defer { handle.release() or { went_on('release the alpm handle', err) } }
181+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
182182 defer { ui.stop() }
183183
184184 // the roots are found as info finds its targets: installed first, then
@@ -1,7 +1,7 @@
11@[has_globals]
22module main
33
4-import alpm
4+import nspkg
55import time
66import v.profiler
77
@@ -15,13 +15,13 @@ const pkg_field_names = ['source', 'name', 'version', 'description', 'arch', 'ur
1515// search_default_fields are the columns of a search unless --fields says otherwise
1616const search_default_fields = ['source', 'name', 'version', 'description']
1717
18-// cfg_search_fields are the columns the config asks for, (search :fields):
18+// cfg_search_fields are the columns the config asks for, (search #:fields):
1919// search_default_fields unless it says otherwise. cfg_search_thold is the
20-// fuzzy search's threshold when --thold names none, (search :thold)
20+// fuzzy search's threshold when --thold names none, (search #:thold)
2121__global cfg_search_fields = ['source', 'name', 'version', 'description']
2222__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
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
2525// is drawn; 0 leaves each to the mode
2626__global cfg_clean_keep = 0
2727__global cfg_tree_depth = 0
@@ -50,13 +50,13 @@ fn parse_fields(spec string, defaults []string) ![]string {
5050// borrowed pointer, and strs() walks it without writing to it — the mut
5151// binding is only the mutable receiver the method spells, never a write to
5252// the C list
53-fn strs_text(list &alpm.List) string {
53+fn strs_text(list &nspkg.List) string {
5454 mut l := unsafe { list }
5555 return l.strs().join(', ')
5656}
5757
58-// pkg_source is where an alpm package comes from: 'local', or the sync repo
59-fn pkg_source(pkg &alpm.Package) string {
58+// pkg_source is where an nspkg package comes from: 'local', or the sync repo
59+fn pkg_source(pkg &nspkg.Package) string {
6060 origin := pkg.get_origin()
6161 if origin == .file {
6262 return 'file'
@@ -71,7 +71,7 @@ fn pkg_source(pkg &alpm.Package) string {
7171// pkg_field_items gives a field's value as separate items, for the fields that
7272// wrap their lists across lines. none for the fields whose value is one piece
7373// of text
74-fn pkg_field_items(pkg &alpm.Package, field string) ?[]string {
74+fn pkg_field_items(pkg &nspkg.Package, field string) ?[]string {
7575 return match field {
7676 'licenses' {
7777 pkg.get_licenses().strs()
@@ -112,7 +112,7 @@ fn pkg_field_items(pkg &alpm.Package, field string) ?[]string {
112112// optdepend_text is one line of the optional deps: name, then its reason. an
113113// installed package marks the deps the local db satisfies, as pacman's -Qi
114114// does; a sync package's list stays bare, like pacman's -Si
115-fn optdepend_text(d alpm.Depend, pkg &alpm.Package) string {
115+fn optdepend_text(d nspkg.Depend, pkg &nspkg.Package) string {
116116 name := d.get_name()
117117 desc := d.get_desc()
118118 text := if desc == '' { name } else { '${name}: ${desc}' }
@@ -130,9 +130,9 @@ fn optdepend_text(d alpm.Depend, pkg &alpm.Package) string {
130130 return text
131131}
132132
133-// pkg_field is one field of an alpm package. '' when the field does not apply,
133+// pkg_field is one field of an nspkg package. '' when the field does not apply,
134134// such as the install fields of a package that is not installed
135-fn pkg_field(pkg &alpm.Package, source string, field string) string {
135+fn pkg_field(pkg &nspkg.Package, source string, field string) string {
136136 sync := pkg.get_origin() == .syncdb
137137 return match field {
138138 'source' {
@@ -1,6 +1,6 @@
11module main
22
3-import alpm
3+import nspkg
44import os
55
66fn files(config ConfigFiles) ! {
@@ -8,8 +8,8 @@ fn files(config ConfigFiles) ! {
88 // no display: the ui is there for the did-you-mean question
99 mut ui := new_trans_ui(noconfirm: config.noconfirm)
1010 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) } }
11+ mut handle := nspkg.initialize(root_path, db_path) or { return err }
12+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
1313
1414 mut pkgcache := local_pkgcache(handle)!
1515
@@ -39,7 +39,7 @@ fn files(config ConfigFiles) ! {
3939}
4040
4141// pkg_paths are the files of an installed package, as paths under the root
42-fn pkg_paths(pkg &alpm.Package) []string {
42+fn pkg_paths(pkg &nspkg.Package) []string {
4343 return pkg.get_files().names().map('${root_path}${it}')
4444}
4545
@@ -56,8 +56,8 @@ struct OwnerQuery {
5656// exact match as alpm_filelist_contains makes it. a file has one owner and
5757// the walk stops there; a directory is shared, and every owner answers, as
5858// in pacman
59-fn file_owners(pkgs []&alpm.Package, q OwnerQuery) []&alpm.Package {
60- mut out := []&alpm.Package{}
59+fn file_owners(pkgs []&nspkg.Package, q OwnerQuery) []&nspkg.Package {
60+ mut out := []&nspkg.Package{}
6161 for pkg in pkgs {
6262 if pkg.get_files().contains(q.rel) != none {
6363 out << pkg
@@ -180,8 +180,8 @@ fn realpath(path string) ?string {
180180
181181fn owner(config ConfigOwner) ! {
182182 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) } }
183+ mut handle := nspkg.initialize(root_path, db_path) or { return err }
184+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
185185
186186 mut pkgcache := local_pkgcache(handle)!
187187
@@ -1,6 +1,6 @@
11module main
22
3-import alpm
3+import nspkg
44import os
55import testdb
66
@@ -204,7 +204,7 @@ fn test_file_owners() ! {
204204 'coreutils': ['usr/', 'usr/bin/', 'usr/bin/ls', 'usr/share/', 'usr/share/man/']
205205 'zsh': ['usr/', 'usr/bin/', 'usr/bin/zsh', 'usr/share/', 'usr/share/man/']
206206 })!
207- handle := alpm.initialize(os.join_path(tmp, 'root') + '/', os.join_path(tmp, 'db') + '/')!
207+ handle := nspkg.initialize(os.join_path(tmp, 'root') + '/', os.join_path(tmp, 'db') + '/')!
208208 defer { handle.release() or {} }
209209 mut localdb := handle.get_localdb()!
210210 mut pkgcache := localdb.get_pkgcache() or { return error('the test db has no pkgcache') }
@@ -1,12 +1,12 @@
11module main
22
3-import alpm
3+import nspkg
44
55// filter_sync_dbs loads the sync dbs when a filter compares the installed
66// 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 {
7+fn filter_sync_dbs(mut ui TransUI, mut handle &nspkg.Handle, config ConfigSearch) ![]&nspkg.DB {
88 if !(config.foreign || config.native || config.upgrades) {
9- return []&alpm.DB{}
9+ return []&nspkg.DB{}
1010 }
1111 dbs := init_repos(mut handle)!
1212 check_sync_fresh(mut ui, mut handle)!
@@ -15,7 +15,7 @@ fn filter_sync_dbs(mut ui TransUI, mut handle &alpm.Handle, config ConfigSearch)
1515
1616// pkg_matches_filter is true when an installed package passes every filter
1717// given, the way pacman's -Q filters combine
18-fn pkg_matches_filter(pkg &alpm.Package, config ConfigSearch, sync_dbs []&alpm.DB) bool {
18+fn pkg_matches_filter(pkg &nspkg.Package, config ConfigSearch, sync_dbs []&nspkg.DB) bool {
1919 reason := pkg.get_reason()
2020 if config.deps && reason != .depend {
2121 return false
@@ -39,7 +39,7 @@ fn pkg_matches_filter(pkg &alpm.Package, config ConfigSearch, sync_dbs []&alpm.D
3939 }
4040 if config.upgrades {
4141 newer := sync_pkg or { return false }
42- if alpm.pkg_vercmp(pkg.get_version(), newer.get_version()) >= 0 {
42+ if nspkg.pkg_vercmp(pkg.get_version(), newer.get_version()) >= 0 {
4343 return false
4444 }
4545 }
@@ -1,6 +1,6 @@
11module main
22
3-import alpm
3+import nspkg
44
55#include <regex.h>
66
@@ -66,7 +66,7 @@ fn find(config ConfigFind) ! {
6666
6767 mut ui := new_trans_ui(noconfirm: config.noconfirm)
6868 mut handle := find_handle(mut ui, config.refresh)!
69- defer { handle.release() or { went_on('release the alpm handle', err) } }
69+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
7070 defer { ui.stop() }
7171
7272 dbs := init_repos(mut handle)!
@@ -103,16 +103,22 @@ fn find(config ConfigFind) ! {
103103// find_handle opens the handle the file dbs are read through, with their
104104// .files extension. a refresh downloads, as root: it takes the full handle,
105105// 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 {
106+// timeout and progress, as pacman -Fy's does. a cached file database
107+// still needs the configured keyring to verify its signature
108+fn find_handle(mut ui TransUI, refresh bool) !&nspkg.Handle {
109109 handle := if refresh {
110110 init_handle(ui)!
111111 } else {
112- alpm.initialize(root_path, db_path) or { return err }
112+ nspkg.initialize(root_path, db_path) or { return err }
113+ }
114+ if !refresh && cfg_gpgdir != '' {
115+ handle.option_set_gpgdir(cfg_gpgdir) or {
116+ handle.release() or { went_on('release the nspkg handle', err) }
117+ return err
118+ }
113119 }
114120 handle.option_set_dbext('.files') or {
115- handle.release() or { went_on('release the alpm handle', err) }
121+ handle.release() or { went_on('release the nspkg handle', err) }
116122 return err
117123 }
118124 return handle
@@ -120,14 +126,14 @@ fn find_handle(mut ui TransUI, refresh bool) !&alpm.Handle {
120126
121127// FileCache is one file db loaded: the db, for its name, and its package cache
122128struct FileCache {
123- db &alpm.DB
124- cache &alpm.List
129+ db &nspkg.DB
130+ cache &nspkg.List
125131}
126132
127133// find_caches loads the file db package caches the named repos ask for, with
128134// a name in the error, because a missing .files file is the one thing a first
129135// run trips over. an empty filter loads them all
130-fn find_caches(dbs []&alpm.DB, filter []string) ![]FileCache {
136+fn find_caches(dbs []&nspkg.DB, filter []string) ![]FileCache {
131137 mut out := []FileCache{}
132138 for db in dbs {
133139 if filter.len > 0 && db.get_name() !in filter {
@@ -189,13 +195,13 @@ fn owner_index(caches []FileCache) OwnerIndex {
189195struct OwnerIndex {
190196mut:
191197 refs map[string][]OwnerRef
192- pkgs []&alpm.Package
198+ pkgs []&nspkg.Package
193199}
194200
195201// owner_matches answers whether a file db entry provides the path. directories
196202// in a filelist carry a trailing slash, so the query, given without its own,
197203// is tried both ways
198-fn owner_matches(pkg &alpm.Package, rel string) bool {
204+fn owner_matches(pkg &nspkg.Package, rel string) bool {
199205 return pkg.get_files().contains(rel) != none
200206 || pkg.get_files().contains(rel + '/') != none
201207}
@@ -209,20 +215,20 @@ struct OwnerHit {
209215 listed bool
210216mut:
211217 repos []string
212- pkgs []&alpm.Package
218+ pkgs []&nspkg.Package
213219 files [][]string
214220}
215221
216222// machine_line is pacman's --machinereadable line: repo, package, version
217223// and path, parted by NUL bytes
218-fn machine_line(repo string, pkg &alpm.Package, file string) string {
224+fn machine_line(repo string, pkg &nspkg.Package, file string) string {
219225 return [repo, pkg.get_name(), pkg.get_version(), file].join('\0')
220226}
221227
222228// find_owner answers which repo package provides a path, pacman's -Fo. the
223229// paths are relative to root, with or without the leading slash, and every
224230// path given is searched
225-fn find_owner(mut ui TransUI, dbs []&alpm.DB, filter []string, config ConfigFind) ! {
231+fn find_owner(mut ui TransUI, dbs []&nspkg.DB, filter []string, config ConfigFind) ! {
226232 // -x: every expression compiles before anything is searched, and a bad
227233 // one stops the run once all of them are named, as in pacman
228234 mut patterns := []FilePattern{}
@@ -301,7 +307,7 @@ fn find_owner(mut ui TransUI, dbs []&alpm.DB, filter []string, config ConfigFind
301307 continue
302308 }
303309 if config.query.len > 1 {
304- // alpm's own lookup matches the file and every directory on
310+ // nspkg's own lookup matches the file and every directory on
305311 // the way to it, which is what pacman's -Fo does; the index
306312 // answers in the same order the walk would
307313 for ref in index.refs[rel] {
@@ -312,7 +318,7 @@ fn find_owner(mut ui TransUI, dbs []&alpm.DB, filter []string, config ConfigFind
312318 } else {
313319 for fc in caches {
314320 for pkg in fc.cache.pkgs() {
315- // alpm's own lookup matches the file and every directory
321+ // nspkg's own lookup matches the file and every directory
316322 // on the way to it, which is what pacman's -Fo does
317323 if owner_matches(pkg, rel) {
318324 hit.repos << fc.db.get_name()
@@ -392,7 +398,7 @@ fn find_owner(mut ui TransUI, dbs []&alpm.DB, filter []string, config ConfigFind
392398}
393399
394400// 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) ! {
401+fn find_list(mut ui TransUI, dbs []&nspkg.DB, filter []string, config ConfigFind) ! {
396402 mut s := ui.spinner(text: 'searching file databases')
397403 // quiet pipes its results: no spinner to glue a finished line onto them
398404 plain := config.quiet || config.machinereadable
@@ -418,15 +424,15 @@ fn find_list(mut ui TransUI, dbs []&alpm.DB, filter []string, config ConfigFind)
418424 continue
419425 }
420426 // 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)
427+ // answer as none instead of a sentinel &nspkg.Package
428+ mut pkg := ?&nspkg.Package(none)
423429 mut repo := ''
424430 for fc in caches {
425431 if want_repo != '' && fc.db.get_name() != want_repo {
426432 continue
427433 }
428434 if p := fc.cache.pkg_find(name) {
429- pkg = ?&alpm.Package(p)
435+ pkg = ?&nspkg.Package(p)
430436 repo = fc.db.get_name()
431437 break
432438 }
@@ -1,6 +1,6 @@
11module main
22
3-import alpm
3+import nspkg
44import term
55
66enum PrintMode {
@@ -41,7 +41,7 @@ fn field_cell(field string, value string) Cell {
4141 }
4242}
4343
44-fn (mut l Listing) add_pkg(pkg &alpm.Package, source string) {
44+fn (mut l Listing) add_pkg(pkg &nspkg.Package, source string) {
4545 l.entries << ListEntry{
4646 name: pkg.get_name()
4747 values: if l.mode == .minimal {
@@ -53,7 +53,7 @@ fn (mut l Listing) add_pkg(pkg &alpm.Package, source string) {
5353}
5454
5555// 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) {
56+fn (mut l Listing) add_member(pkg &nspkg.Package, source string, group string) {
5757 l.add_pkg(pkg, source)
5858 last := l.entries.pop()
5959 l.entries << ListEntry{
@@ -130,7 +130,7 @@ fn listing_row(fields []string, e ListEntry) Row {
130130// the same reason as a frontend reads it. every reason is named in both, no
131131// else: one libalpm adds fails the build here, rather than reading as
132132// 'unknown' in one spelling and something else in the other
133-pub fn reason_to_str(reason alpm.PackageReason) string {
133+pub fn reason_to_str(reason nspkg.PackageReason) string {
134134 return match reason {
135135 .explicit { 'explicitly installed' }
136136 .depend { 'installed as a dependency' }
@@ -138,7 +138,7 @@ pub fn reason_to_str(reason alpm.PackageReason) string {
138138 }
139139}
140140
141-pub fn validation_to_str(validation alpm.PkgValidation) string {
141+pub fn validation_to_str(validation nspkg.PkgValidation) string {
142142 if validation == .unknown {
143143 return 'unknown'
144144 }
@@ -146,19 +146,19 @@ pub fn validation_to_str(validation alpm.PkgValidation) string {
146146 return 'none'
147147 }
148148 mut parts := []string{}
149- if int(validation) & int(alpm.PkgValidation.md5sum) != 0 {
149+ if int(validation) & int(nspkg.PkgValidation.md5sum) != 0 {
150150 parts << 'MD5 checksum'
151151 }
152- if int(validation) & int(alpm.PkgValidation.sha256sum) != 0 {
152+ if int(validation) & int(nspkg.PkgValidation.sha256sum) != 0 {
153153 parts << 'SHA-256 checksum'
154154 }
155- if int(validation) & int(alpm.PkgValidation.signature) != 0 {
155+ if int(validation) & int(nspkg.PkgValidation.signature) != 0 {
156156 parts << 'signature'
157157 }
158158 return parts.join(', ')
159159}
160160
161-fn depends_text(deps &alpm.List) string {
161+fn depends_text(deps &nspkg.List) string {
162162 mut d := unsafe { deps }
163163 return d.depends().map(|dep| dep.compute_string()).join(', ')
164164}
@@ -200,7 +200,7 @@ fn wrap_items(items []string, avail int) []string {
200200// info_fields collects what info shows of a package: the fields asked for,
201201// in order. an empty one is left out unless the fields were named on the
202202// command line (explicit)
203-fn info_fields(pkg &alpm.Package, fields []string, explicit bool) []InfoField {
203+fn info_fields(pkg &nspkg.Package, fields []string, explicit bool) []InfoField {
204204 source := pkg_source(pkg)
205205 mut out := []InfoField{}
206206 for f in fields {
@@ -62,18 +62,18 @@ fn test_reason_spellings() ! {
6262 // every reason in both spellings, and the frontend's key is a word mark
6363 // reads back as that reason
6464 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']
65+ nspkg.PackageReason.explicit: ['explicit', 'explicitly installed']
66+ nspkg.PackageReason.depend: ['depend', 'installed as a dependency']
67+ nspkg.PackageReason.unknown: ['unknown', 'unknown']
6868 } {
6969 assert [reason_key(reason), reason_to_str(reason)] == want
7070 assert parse_reason(reason_key(reason))! == reason
7171 }
7272 for short, reason in {
73- 'e': alpm.PackageReason.explicit
74- 'dep': alpm.PackageReason.depend
75- 'dependency': alpm.PackageReason.depend
76- 'u': alpm.PackageReason.unknown
73+ 'e': nspkg.PackageReason.explicit
74+ 'dep': nspkg.PackageReason.depend
75+ 'dependency': nspkg.PackageReason.depend
76+ 'u': nspkg.PackageReason.unknown
7777 } {
7878 assert parse_reason(short)! == reason
7979 }
@@ -1,9 +1,9 @@
11module main
22
3-import alpm
4-import alpm.tests.archivefixtures
5-import alpm.tests.httpfixtures
6-import alpm.tests.signaturefixtures
3+import nspkg
4+import nspkg.tests.archivefixtures
5+import nspkg.tests.httpfixtures
6+import nspkg.tests.signaturefixtures
77import crypto.sha256
88import encoding.base64
99import json2
@@ -50,14 +50,14 @@ fn test_prepare_conflict_keeps_its_error_kind_after_copying_names() ! {
5050 defer { os.rmdir_all(s.tmp) or { went_on('remove the test system', err) } }
5151 testdb.write_local(s.path('db'), [testdb.Pkg{ name: 'old', conflicts: ['new'] }])!
5252 s.publish([FakePkg{ name: 'new' }])!
53- handle := alpm.initialize(s.path('root'), s.path('db'))!
54- defer { handle.release() or { went_on('release the alpm handle', err) } }
53+ handle := nspkg.initialize(s.path('root'), s.path('db'))!
54+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
5555 db := handle.register_syncdb('core', 0)!
5656 trans_begin(handle, .nolock)!
5757 defer { trans_cleanup(handle) }
5858 handle.add_pkg(db.get_pkg('new') or { return error('missing new package') })!
5959 trans_prepare_checked(handle) or {
60- assert err.code() == int(alpm.Errno.conflicting_deps)
60+ assert err.code() == int(nspkg.Errno.conflicting_deps)
6161 assert err.msg().contains('unresolvable package conflicts:')
6262 assert err.msg().contains('new and old are in conflict')
6363 return
@@ -223,7 +223,7 @@ fn tar(out string, dir string, entries []string) ! {
223223// installed is the local db's name to version, read the way the next
224224// command would read it: a fresh handle
225225fn (s FakeSystem) installed() !map[string]string {
226- handle := alpm.initialize(s.path('root') + '/', s.path('db') + '/')!
226+ handle := nspkg.initialize(s.path('root') + '/', s.path('db') + '/')!
227227 defer { handle.release() or {} }
228228 // an empty db is no packages; one that cannot be read is an error, not
229229 // 'nothing installed' (pkgcache_of tells the two apart by libalpm's errno)
@@ -235,8 +235,8 @@ fn (s FakeSystem) installed() !map[string]string {
235235 return out
236236}
237237
238-fn (s FakeSystem) reason_of(name string) !alpm.PackageReason {
239- handle := alpm.initialize(s.path('root') + '/', s.path('db') + '/')!
238+fn (s FakeSystem) reason_of(name string) !nspkg.PackageReason {
239+ handle := nspkg.initialize(s.path('root') + '/', s.path('db') + '/')!
240240 defer { handle.release() or {} }
241241 return (handle.find_local_pkg(name) or { return error('${name} is not installed') }).get_reason()
242242}
@@ -635,7 +635,7 @@ fn test_an_empty_system_is_no_error() ! {
635635fn test_pkgcache_of() ! {
636636 s := fake_system('pkgcache')!
637637 defer { os.rmdir_all(s.tmp) or {} }
638- handle := alpm.initialize(s.path('root') + '/', s.path('db') + '/')!
638+ handle := nspkg.initialize(s.path('root') + '/', s.path('db') + '/')!
639639 // empty: a nil list, which reads as no packages
640640 mut empty := local_pkgcache(handle)!
641641 assert empty == unsafe { nil }
@@ -644,7 +644,7 @@ fn test_pkgcache_of() ! {
644644 handle.release()!
645645
646646 s.install_local(foo('1.0-1', 'one'))!
647- full_handle := alpm.initialize(s.path('root') + '/', s.path('db') + '/')!
647+ full_handle := nspkg.initialize(s.path('root') + '/', s.path('db') + '/')!
648648 mut full := local_pkgcache(full_handle)!
649649 assert full.pkgs().map(it.get_name()) == ['foo']
650650 full_handle.release()!
@@ -655,7 +655,7 @@ fn test_pkgcache_of() ! {
655655 }
656656 // a db libalpm cannot read is still an error, with libalpm's reason. the
657657 // handle opens first: libalpm reads the packages only when asked
658- broken := alpm.initialize(s.path('root') + '/', s.path('db') + '/')!
658+ broken := nspkg.initialize(s.path('root') + '/', s.path('db') + '/')!
659659 defer { broken.release() or {} }
660660 os.chmod(s.path('db/local'), 0)!
661661 defer { os.chmod(s.path('db/local'), 0o755) or {} }
@@ -760,6 +760,9 @@ fn test_find_refresh_takes_the_full_handle() ! {
760760 }
761761 read := find_handle(mut ui, false)!
762762 defer { read.release() or {} }
763+ if read.option_get_gpgdir() != refresh.option_get_gpgdir() {
764+ return error('a cached file database must use the same keyring as a refresh')
765+ }
763766 if read.option_get_dbext() != '.files' {
764767 return error('a lookup reads ${read.option_get_dbext()}')
765768 }
@@ -1116,6 +1119,34 @@ fn providers_of(run FrontendRun) map[string][]string {
11161119 return out
11171120}
11181121
1122+fn test_find_verifies_cached_files_with_the_configured_keyring() ! {
1123+ s := with_file_dbs('findsigned', [FakePkg{
1124+ name: 'probe'
1125+ files: { 'usr/bin/probe': 'fixture' }
1126+ }])!
1127+ defer { os.rmdir_all(s.tmp) or {} }
1128+ ring := signaturefixtures.create(s.path('gpg'))!
1129+ defer { signaturefixtures.cleanup(ring.path) or {} }
1130+ ring.trust(ring.fingerprint, 6)!
1131+ path := s.path('db/sync/core.files')
1132+ ring.sign(path, [ring.fingerprint], false)!
1133+ lookup := fn () ! {
1134+ cfg_siglevel = .database
1135+ find(ConfigFind{ query: ['usr/bin/probe'] })!
1136+ }
1137+ valid := s.run('', lookup)!
1138+ assert valid.err == '', valid.err
1139+ assert providers_of(valid)['usr/bin/probe']! == ['probe']
1140+
1141+ other := s.path('different-content')
1142+ os.write_file(other, 'different content')!
1143+ ring.sign(other, [ring.fingerprint], false)!
1144+ os.cp(other + '.sig', path + '.sig')!
1145+ invalid := s.run('', lookup)!
1146+ assert invalid.err.contains('invalid or corrupted database'), invalid.err
1147+ assert invalid.of('provides').len == 0
1148+}
1149+
11191150fn test_find_owner_index_answers_as_the_walk() ! {
11201151 s := with_file_dbs('findowner', [
11211152 FakePkg{
@@ -1746,7 +1777,7 @@ fn test_needed_group_queries_deliver_skip_warnings() ! {
17461777 mut ui := new_trans_ui()
17471778 defer { ui.stop() }
17481779 mut handle := init_handle(ui)!
1749- defer { handle.release() or { went_on('release the alpm handle', err) } }
1780+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
17501781 init_repos(mut handle)!
17511782 handle.trans_init(.needed | .nolock)!
17521783 defer { handle.trans_release() or { went_on('release the test transaction', err) } }
@@ -1986,8 +2017,8 @@ fn test_package_info_preserves_metadata_and_archive_read_failure_kinds() ! {
19862017 assert run.of('info').len == 1
19872018 errors := target_errors(run)
19882019 assert errors.len == 2
1989- assert errors[0].contains(alpm.Errno.pkg_invalid.strerror())
1990- assert errors[1].contains(alpm.Errno.libarchive.strerror())
2020+ assert errors[0].contains(nspkg.Errno.pkg_invalid.strerror())
2021+ assert errors[1].contains(nspkg.Errno.libarchive.strerror())
19912022 messages := run.of('message').filter(it['text']!.str().starts_with('missing package metadata in ') || it['text']!.str().starts_with('error while reading package '))
19922023 assert messages.len == 2
19932024 assert messages[0]['text']!.str() == 'missing package metadata in ${missing}'
@@ -2012,7 +2043,7 @@ fn test_bad_package_mtree_falls_back_without_rejecting_the_archive() ! {
20122043 run := s.run('', fn [path] () ! {
20132044 mut ui := new_trans_ui()
20142045 handle := init_handle(ui)!
2015- defer { handle.release() or { went_on('release the alpm handle', err) } }
2046+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
20162047 defer { ui.stop() }
20172048 pkg := handle.pkg_load(path, 1, 0)!
20182049 defer { pkg.free_pkg() or { went_on('free the test package', err) } }
@@ -2035,7 +2066,7 @@ fn test_raw_signature_failure_reaches_the_frontend_before_its_target_error() ! {
20352066 run := s.run('', fn [path] () ! {
20362067 mut ui := new_trans_ui()
20372068 handle := init_handle(ui)!
2038- defer { handle.release() or { went_on('release the alpm handle', err) } }
2069+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
20392070 defer { ui.stop() }
20402071 pkg := handle.pkg_load(path, 0, 0)!
20412072 defer { pkg.free_pkg() or { went_on('free the test package', err) } }
@@ -2057,7 +2088,7 @@ fn test_raw_signature_failure_reaches_the_frontend_before_its_target_error() ! {
20572088 assert ordered[0]['warning']!.bool() && !(ordered[0]['error'] or { json2.Any(false) }).bool()
20582089 assert ordered[1]['type']!.str() == 'message'
20592090 assert ordered[2]['type']!.str() == 'error'
2060- assert target_errors(run) == ['signature check failed: ' + alpm.Errno.gpgme.strerror()]
2091+ assert target_errors(run) == ['signature check failed: ' + nspkg.Errno.gpgme.strerror()]
20612092 assert os.read_bytes(path)! == bytes
20622093 assert os.read_file(path + '.sig')! == ''
20632094 assert !s.lock_left()
@@ -2076,7 +2107,7 @@ fn test_signature_context_allocation_error_reaches_frontends_and_allows_a_retry(
20762107 run := s.run('', fn [path] () ! {
20772108 mut ui := new_trans_ui()
20782109 handle := init_handle(ui)!
2079- defer { handle.release() or { went_on('release the alpm handle', err) } }
2110+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
20802111 defer { ui.stop() }
20812112 pkg := handle.pkg_load(path, 0, 0)!
20822113 defer { pkg.free_pkg() or { went_on('free the test package', err) } }
@@ -2106,7 +2137,7 @@ fn test_signature_context_allocation_error_reaches_frontends_and_allows_a_retry(
21062137 assert messages[0]['warning']!.bool() && messages[0]['error']!.bool()
21072138 ordered := run.events.filter(it['type']!.str() in ['message', 'error'])
21082139 assert ordered.map(it['type']!.str()) == ['message', 'error']
2109- assert target_errors(run) == ['signature check failed: ' + alpm.Errno.gpgme.strerror()]
2140+ assert target_errors(run) == ['signature check failed: ' + nspkg.Errno.gpgme.strerror()]
21102141 assert os.read_bytes(path)! == bytes
21112142 assert os.read_bytes(path + '.sig')! == sig
21122143 assert !s.lock_left()
@@ -2129,7 +2160,7 @@ fn test_package_load_still_verifies_after_a_failed_preliminary_key_lookup() ! {
21292160 run := s.run('', fn [path, tampered] () ! {
21302161 mut ui := new_trans_ui()
21312162 handle := init_handle(ui)!
2132- defer { handle.release() or { went_on('release the alpm handle', err) } }
2163+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
21332164 defer { ui.stop() }
21342165 mut state := unsafe { frontend_signature_fault }
21352166 saved_remaining, saved_failures := state.remaining, state.failures
@@ -2176,14 +2207,18 @@ fn test_missing_keyring_warns_frontends_once_across_repeated_signature_checks()
21762207 run := s.run('', fn [path] () ! {
21772208 mut ui := new_trans_ui()
21782209 handle := init_handle(ui)!
2179- defer { handle.release() or { went_on('release the alpm handle', err) } }
2210+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
21802211 defer { ui.stop() }
21812212 pkg := handle.pkg_load(path, 0, 0)!
21822213 defer { pkg.free_pkg() or { went_on('free the test package', err) } }
21832214 for attempt in 0 .. 2 {
21842215 result := pkg.check_pgp_signature() or { return error('could not inspect the unknown-key signature') }
21852216 defer { result.cleanup() or { went_on('clean up the signature result', err) } }
2186- check(handle.errno() == if attempt == 0 { alpm.Errno.not_a_file } else { alpm.Errno.ok }, 'keyring warning retains the source error state')!
2217+ check(handle.errno() == if attempt == 0 {
2218+ nspkg.Errno.not_a_file
2219+ } else {
2220+ nspkg.Errno.ok
2221+ }, 'keyring warning retains the source error state')!
21872222 check(result.count == 1 && unsafe { result.results[0].status == .key_unknown }, 'missing key is reported without importing it')!
21882223 }
21892224 })!
@@ -2213,7 +2248,7 @@ fn test_modern_keybox_verifies_without_a_false_missing_keyring_warning() ! {
22132248 run := s.run('', fn [path] () ! {
22142249 mut ui := new_trans_ui()
22152250 handle := init_handle(ui)!
2216- defer { handle.release() or { went_on('release the alpm handle', err) } }
2251+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
22172252 defer { ui.stop() }
22182253 pkg := handle.pkg_load(path, 0, 0)!
22192254 defer { pkg.free_pkg() or { went_on('free the test package', err) } }
@@ -2246,7 +2281,7 @@ fn test_issuer_extraction_errors_reach_frontends_and_preserve_the_previous_errno
22462281 run := s.run('', fn [prior, data, identifier] () ! {
22472282 mut ui := new_trans_ui()
22482283 handle := init_handle(ui)!
2249- defer { handle.release() or { went_on('release the alpm handle', err) } }
2284+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
22502285 defer { ui.stop() }
22512286 if prior {
22522287 if _ := handle.register_syncdb('', 0) {
@@ -2302,7 +2337,7 @@ fn test_embedded_signature_verifies_the_recorded_file_without_a_package_cache()
23022337 defer { os.chdir(previous) or { went_on('restore the test directory', err) } }
23032338 mut ui := new_trans_ui()
23042339 handle := init_handle(ui)!
2305- defer { handle.release() or { went_on('release the alpm handle', err) } }
2340+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
23062341 defer { ui.stop() }
23072342 handle.option_set_gpgdir(home)!
23082343 handle.option_set_cachedirs(unsafe { nil })!
@@ -2331,7 +2366,7 @@ fn test_database_signature_requirement_reaches_frontends() ! {
23312366 run := s.run('', fn [level] () ! {
23322367 mut ui := new_trans_ui()
23332368 handle := init_handle(ui)!
2334- defer { handle.release() or { went_on('release the alpm handle', err) } }
2369+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
23352370 defer { ui.stop() }
23362371 db := handle.register_syncdb('core', level)!
23372372 if level == 1024 {
@@ -2374,7 +2409,7 @@ fn test_database_marginal_trust_policy_reports_its_reason() ! {
23742409 run := s.run('', fn [home, level] () ! {
23752410 mut ui := new_trans_ui()
23762411 handle := init_handle(ui)!
2377- defer { handle.release() or { went_on('release the alpm handle', err) } }
2412+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
23782413 defer { ui.stop() }
23792414 handle.option_set_gpgdir(home)!
23802415 db := handle.register_syncdb('core', level)!
@@ -2412,7 +2447,7 @@ fn test_declined_database_key_import_is_reported_without_importing_the_key() ! {
24122447 run := s.run('{"id": 1, "answer": false}\n', fn [home] () ! {
24132448 mut ui := new_trans_ui()
24142449 handle := init_handle(ui)!
2415- defer { handle.release() or { went_on('release the alpm handle', err) } }
2450+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
24162451 defer { ui.stop() }
24172452 handle.option_set_gpgdir(home)!
24182453 db := handle.register_syncdb('core', 1024)!
@@ -2469,7 +2504,7 @@ fn test_failed_remote_key_lookup_reaches_frontends_after_the_import_question() !
24692504 run := s.run('{"id": 1, "answer": true}\n', fn [home] () ! {
24702505 mut ui := new_trans_ui()
24712506 handle := init_handle(ui)!
2472- defer { handle.release() or { went_on('release the alpm handle', err) } }
2507+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
24732508 defer { ui.stop() }
24742509 handle.option_set_gpgdir(home)!
24752510 db := handle.register_syncdb('core', 1024)!
@@ -2604,7 +2639,7 @@ mut:
26042639 closed bool
26052640}
26062641
2607-fn local_cache_read_fault_log(context voidptr, level alpm.LogLevel, message &u8) {
2642+fn local_cache_read_fault_log(context voidptr, level nspkg.LogLevel, message &u8) {
26082643 mut fault := unsafe { &LocalCacheReadFault(context) }
26092644 if fault.closed || !level.has(.function) { return }
26102645 if unsafe { cstring_to_vstring(message) } != 'loading package data for app : level=0x1\n' {
@@ -2633,7 +2668,7 @@ fn test_local_cache_read_failure_is_reported_and_can_be_retried() ! {
26332668 run := s.run('', fn [fault] () ! {
26342669 mut ui := new_trans_ui()
26352670 handle := init_handle(ui)!
2636- defer { handle.release() or { went_on('release the alpm handle', err) } }
2671+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
26372672 defer { ui.stop() }
26382673 handle.option_set_logcb_line(local_cache_read_fault_log, fault)!
26392674 mut failed := false
@@ -2663,11 +2698,11 @@ fn test_local_database_file_reports_an_open_error_without_replacing_it() ! {
26632698 os.write_file(path, 'keep this file')!
26642699 run := s.run('', fn () ! {
26652700 info(ConfigInfo{ fields: 'name', query: ['local/app'] }) or {
2666- check(err.code() == int(alpm.Errno.db_open), 'initialization error kind is preserved')!
2701+ check(err.code() == int(nspkg.Errno.db_open), 'initialization error kind is preserved')!
26672702 return err
26682703 }
26692704 })!
2670- assert run.err.contains(alpm.Errno.db_open.strerror()), run.err
2705+ assert run.err.contains(nspkg.Errno.db_open.strerror()), run.err
26712706 assert run.of('info').len == 0
26722707 assert os.read_file(path)! == 'keep this file'
26732708 assert !s.lock_left()
@@ -2683,7 +2718,7 @@ fn test_empty_database_creation_does_not_reopen_a_write_only_version_file() ! {
26832718 defer { C.umask(prior) }
26842719 mut ui := new_trans_ui()
26852720 handle := init_handle(ui)!
2686- defer { handle.release() or { went_on('release the alpm handle', err) } }
2721+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
26872722 defer { ui.stop() }
26882723 packages := local_pkgcache(handle)!
26892724 check(packages.pkgs().len == 0, 'new local database is empty')!
@@ -2720,10 +2755,10 @@ fn test_repository_cache_preserves_initial_and_cached_failure_kinds() ! {
27202755 run := s.run('', fn () ! {
27212756 mut ui := new_trans_ui()
27222757 handle := init_handle(ui)!
2723- defer { handle.release() or { went_on('release the alpm handle', err) } }
2758+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
27242759 defer { ui.stop() }
27252760 db := handle.register_syncdb('core', 0)!
2726- for kind in [alpm.Errno.db_open, .db_invalid] {
2761+ for kind in [nspkg.Errno.db_open, .db_invalid] {
27272762 if _ := pkgcache_of(handle, db) {
27282763 return error('accepted a corrupt repository')
27292764 } else {
@@ -2735,9 +2770,9 @@ fn test_repository_cache_preserves_initial_and_cached_failure_kinds() ! {
27352770 assert run.err == '' && run.failed == 2, run.err
27362771 errors := target_errors(run)
27372772 assert errors.len == 2
2738- assert errors[0].contains(alpm.Errno.db_open.strerror())
2739- assert errors[1].contains(alpm.Errno.db_invalid.strerror())
2740- assert !errors[1].contains(alpm.Errno.db_invalid_sig.strerror())
2773+ assert errors[0].contains(nspkg.Errno.db_open.strerror())
2774+ assert errors[1].contains(nspkg.Errno.db_invalid.strerror())
2775+ assert !errors[1].contains(nspkg.Errno.db_invalid_sig.strerror())
27412776 assert run.of('message').any(it['text']!.str().starts_with('could not open file ' + path + ':'))
27422777 assert os.read_file(path)! == text
27432778 assert !s.lock_left()
@@ -2755,7 +2790,7 @@ fn test_repository_read_retry_recovers_packages_and_groups() ! {
27552790 run := s.run('', fn [path, good] () ! {
27562791 mut ui := new_trans_ui()
27572792 handle := init_handle(ui)!
2758- defer { handle.release() or { went_on('release the alpm handle', err) } }
2793+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
27592794 defer { ui.stop() }
27602795 db := handle.register_syncdb('core', 0)!
27612796 if _ := pkgcache_of(handle, db) {
@@ -2793,7 +2828,7 @@ fn test_sync_metadata_warnings_and_final_newline_reach_frontends() ! {
27932828 run := s.run('', fn () ! {
27942829 mut ui := new_trans_ui()
27952830 handle := init_handle(ui)!
2796- defer { handle.release() or { went_on('release the alpm handle', err) } }
2831+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
27972832 defer { ui.stop() }
27982833 db := handle.register_syncdb('core', 0)!
27992834 packages := pkgcache_of(handle, db)!
@@ -2828,7 +2863,7 @@ fn test_sync_metadata_errors_report_each_bad_entry_without_a_partial_cache() ! {
28282863 run := s.run('', fn () ! {
28292864 mut ui := new_trans_ui()
28302865 handle := init_handle(ui)!
2831- defer { handle.release() or { went_on('release the alpm handle', err) } }
2866+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
28322867 defer { ui.stop() }
28332868 db := handle.register_syncdb('core', 0)!
28342869 if _ := pkgcache_of(handle, db) {
@@ -3150,10 +3185,10 @@ fn test_pkgbuild_upgrade_pass_picks_the_foreign_newer_ones() ! {
31503185 }
31513186 }) or { return error('at install_local aurpkg: ${err.msg()}') }
31523187 s.publish([foo('2.0-1', 'two')]) or { return error('at publish: ${err.msg()}') }
3153- mut handle := alpm.initialize(s.path('root') + '/', s.path('db') + '/') or {
3188+ mut handle := nspkg.initialize(s.path('root') + '/', s.path('db') + '/') or {
31543189 return error('at initialize: ${err.msg()}')
31553190 }
3156- defer { handle.release() or { went_on('release the alpm handle', err) } }
3191+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
31573192 cfg_repos = [CfgRepo{
31583193 name: 'core'
31593194 kind: 'sync'
@@ -3337,7 +3372,7 @@ fn test_targets_resolve_by_scope_version_and_provision() ! {
33373372 check(find_sync_target(handle, dbs, 'svirt', false) != none, 'sync provision')!
33383373 check(find_sync_target(handle, dbs, 'svirt=4', false) == none, 'sync provision, wrong version')!
33393374 check(find_sync_target(handle, dbs, '', false) == none, 'sync empty name')!
3340- check(find_sync_target(handle, []&alpm.DB{}, 'app', false) == none, 'no dbs')!
3375+ check(find_sync_target(handle, []&nspkg.DB{}, 'app', false) == none, 'no dbs')!
33413376 // a db not for installing answers a provision only when it was
33423377 // named with the target, and its usage is put back after
33433378 dbs[0].set_usage(.sync | .search)!
@@ -3398,7 +3433,7 @@ fn test_filters_combine_as_pacmans_query_filters() ! {
33983433 check(pass(ConfigSearch{ upgrades: true, foreign: true }) == [], 'upgrades of foreign')!
33993434 // with no sync dbs to compare with, everything is foreign
34003435 none_synced := local.pkgs().filter(pkg_matches_filter(it, ConfigSearch{ native: true },
3401- []&alpm.DB{}))
3436+ []&nspkg.DB{}))
34023437 check(none_synced.len == 0, 'native with no sync dbs')!
34033438 // the filters that need no sync data never load it
34043439 check(filter_sync_dbs(mut ui, mut handle, ConfigSearch{ explicit: true, unrequired: true })!.len == 0,
@@ -295,7 +295,7 @@ const help_modes = [
295295 usage: '[options] [os]'
296296 options: [
297297 HelpFlag{'-n, --top <n>', 'show the n fastest mirrors (default 10)'},
298- HelpFlag{'-w, --write', 'write the ranking to <os>.lip in the mirrors dir (/etc/vpac.d/mirrors), as root if needed'},
298+ HelpFlag{'-w, --write', 'write the ranking to the config’s mirror file in the mirrors dir (/etc/vpac.d/mirrors), as root if needed'},
299299 HelpFlag{'-m, --mirrorlist', 'print the result as mirrorlist Server lines'},
300300 HelpFlag{'-o, --output <file>', 'write the Server lines to a file, as root if needed'},
301301 HelpFlag{'--stdin', 'rank the mirrors listed on stdin, instead of the os mirror list'},
@@ -417,7 +417,7 @@ fn help_text() string {
417417 mut out := []string{}
418418 out << bold_heading('usage') + ' vpac [flags] <mode> [options] [args]'
419419 out << ' --config <file> read this config instead of ${config_path}'
420- out << ' --eval <blip> run blip after the config, extending it for this run'
420+ out << ' --eval <code> evaluate an override in the config file’s syntax'
421421 out << ' --color <when> auto, always or never: auto styles a terminal only'
422422 out << ' --ui <kind> tty, or ipc: json lines on stdout, answers on stdin'
423423 out << ' --verbose say the housekeeping failures a run otherwise goes on from'
@@ -1,19 +1,19 @@
11module main
22
3-import alpm
3+import nspkg
44
55// InfoLookup is how info and tree find their targets: the installed
66// packages first, then the sync dbs, which are only set up — and asked
77// about their freshness — by the first target that needs them
88struct InfoLookup {
99mut:
10- installed &alpm.List
11- dbs []&alpm.DB
10+ installed &nspkg.List
11+ dbs []&nspkg.DB
1212 synced bool
1313}
1414
1515// 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 {
16+fn (mut l InfoLookup) sync_dbs(mut ui TransUI, mut handle &nspkg.Handle) ![]&nspkg.DB {
1717 if !l.synced {
1818 l.dbs = init_repos(mut handle)!
1919 check_sync_fresh(mut ui, mut handle)!
@@ -28,14 +28,14 @@ fn (mut l InfoLookup) sync_dbs(mut ui TransUI, mut handle &alpm.Handle) ![]&alpm
2828// may be a dependency string or something provided. what misses gets the
2929// nearest name of the same scope offered; an error is the target's own,
3030// 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 {
31+fn (mut l InfoLookup) find(mut ui TransUI, mut handle &nspkg.Handle, raw string) !&nspkg.Package {
3232 target := parse_target(raw)
3333 if target.repo in ['', 'local'] {
3434 if p := find_local_target(l.installed, target.name, true) {
3535 return p
3636 }
3737 }
38- mut scoped := []&alpm.DB{}
38+ mut scoped := []&nspkg.DB{}
3939 if target.repo != 'local' {
4040 scoped = scope_dbs(l.sync_dbs(mut ui, mut handle)!, target.repo)!
4141 if p := find_sync_target(handle, scoped, target.name, target.repo != '') {
@@ -61,7 +61,7 @@ fn info(config ConfigInfo) ! {
6161 fields := parse_fields(config.fields, pkg_field_names)!
6262 mut ui := new_trans_ui(noconfirm: config.noconfirm)
6363 mut handle := init_handle(ui)!
64- defer { handle.release() or { went_on('release the alpm handle', err) } }
64+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
6565 defer { ui.stop() }
6666
6767 // package archives on disk are shown directly, pacman's -Qp: loaded, not
@@ -90,7 +90,7 @@ fn info(config ConfigInfo) ! {
9090// show_pkg is one target's answer: its changelog with -c, its fields
9191// otherwise. it says whether anything was shown, which is what the blank
9292// line before the next one goes by
93-fn show_pkg(pkg &alpm.Package, config ConfigInfo, fields []string, first bool) bool {
93+fn show_pkg(pkg &nspkg.Package, config ConfigInfo, fields []string, first bool) bool {
9494 if config.changelog {
9595 return show_changelog(pkg, first)
9696 }
@@ -117,7 +117,7 @@ fn show_info(fields []InfoField, first bool) {
117117// hands it out (an fread into the buffer, 0 at its end). none when the
118118// package carries none: libalpm has one for an installed package and for a
119119// package file, never for a sync db's entry
120-fn pkg_changelog(pkg &alpm.Package) ?string {
120+fn pkg_changelog(pkg &nspkg.Package) ?string {
121121 fp := pkg.changelog_open()
122122 if fp == unsafe { nil } {
123123 return none
@@ -140,7 +140,7 @@ fn pkg_changelog(pkg &alpm.Package) ?string {
140140// show_changelog is pacman's -Qc: the heading, then the changelog as the
141141// package carries it. a package without one is said and shows nothing,
142142// which pacman does not count as a failure either
143-fn show_changelog(pkg &alpm.Package, first bool) bool {
143+fn show_changelog(pkg &nspkg.Package, first bool) bool {
144144 text := pkg_changelog(pkg) or {
145145 warn('no changelog available for ${pkg.get_name()}')
146146 return false
@@ -164,7 +164,7 @@ fn show_changelog(pkg &alpm.Package, first bool) bool {
164164// the way pacman's query loads one: whole, with no signature asked for,
165165// since nothing of it is installed. one that does not load is its own
166166// target's error, and the rest are still shown
167-fn info_files(handle &alpm.Handle, config ConfigInfo, fields []string) {
167+fn info_files(handle &nspkg.Handle, config ConfigInfo, fields []string) {
168168 mut printed := 0
169169 for path in config.query {
170170 pkg := handle.pkg_load(path, 1, 0) or {
@@ -183,7 +183,7 @@ fn which(config ConfigWhich) ! {
183183 need_query(config.query, 'dependency')!
184184 ui := new_trans_ui()
185185 mut handle := init_handle(ui)!
186- defer { handle.release() or { went_on('release the alpm handle', err) } }
186+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
187187 defer { ui.stop() }
188188
189189 mut pkgcache := local_pkgcache(handle)!
@@ -99,7 +99,7 @@ fn emit[T](event T) {
9999// channel_write writes the whole line on the channel, and answers whether it
100100// went out, through write(2)
101101fn channel_write(line string) bool {
102- return channel_write_to(ipc_fd, line, sys_write)
102+ return channel_write_to(ipc_fd, line, ipc_write)
103103}
104104
105105// WriteFn is write(2) as channel_write_to calls it: what it wrote, and the
@@ -107,7 +107,7 @@ fn channel_write(line string) bool {
107107// interruptions and the stalls no real channel produces on demand
108108type WriteFn = fn (fd int, buf voidptr, n int) (int, int)
109109
110-fn sys_write(fd int, buf voidptr, n int) (int, int) {
110+fn ipc_write(fd int, buf voidptr, n int) (int, int) {
111111 written := int(C.write(fd, buf, n))
112112 return written, if written < 0 { C.errno } else { 0 }
113113}
@@ -481,7 +481,7 @@ fn warn(text string) {
481481}
482482
483483// 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
484+// (options #:verbose #t): either turns the verbose log on. the config's is
485485// reset with the config; the flag is the command line's and stays
486486__global verbose_flag = false
487487__global cfg_verbose = false
@@ -1,6 +1,6 @@
11module main
22
3-import alpm
3+import nspkg
44import json2
55import os
66
@@ -172,14 +172,14 @@ fn downloads_said(feed fn (mut ui TransUI)) ![]map[string]json2.Any {
172172
173173fn test_ipc_download_retry() ! {
174174 events := downloads_said(fn (mut ui TransUI) {
175- mut p := alpm.DownloadEventProgress{
175+ mut p := nspkg.DownloadEventProgress{
176176 downloaded: 50
177177 total: 100
178178 }
179179 ipc_download(mut ui, 'a.pkg', .progress, voidptr(&p))
180180 // the same percent right after: held back
181181 ipc_download(mut ui, 'a.pkg', .progress, voidptr(&p))
182- mut r := alpm.DownloadEventRetry{
182+ mut r := nspkg.DownloadEventRetry{
183183 resume: 0
184184 }
185185 ipc_download(mut ui, 'a.pkg', .retry, voidptr(&r))
@@ -187,11 +187,11 @@ fn test_ipc_download_retry() ! {
187187 // whatever the percent last said
188188 p.downloaded = 0
189189 ipc_download(mut ui, 'a.pkg', .progress, voidptr(&p))
190- mut r2 := alpm.DownloadEventRetry{
190+ mut r2 := nspkg.DownloadEventRetry{
191191 resume: 1
192192 }
193193 ipc_download(mut ui, 'a.pkg', .retry, voidptr(&r2))
194- mut c := alpm.DownloadEventCompleted{
194+ mut c := nspkg.DownloadEventCompleted{
195195 total: 100
196196 result: 0
197197 }
@@ -210,11 +210,11 @@ fn test_ipc_download_retry() ! {
210210
211211fn test_ipc_download_dedupes_per_file() ! {
212212 events := downloads_said(fn (mut ui TransUI) {
213- mut a := alpm.DownloadEventProgress{
213+ mut a := nspkg.DownloadEventProgress{
214214 downloaded: 10
215215 total: 100
216216 }
217- mut b := alpm.DownloadEventProgress{
217+ mut b := nspkg.DownloadEventProgress{
218218 downloaded: 10
219219 total: 100
220220 }
@@ -1,7 +1,7 @@
11@[has_globals]
22module main
33
4-import blip.vlib.blip.printer
4+import vile.scheme
55import json2
66import net.http
77import os
@@ -12,15 +12,15 @@ import time
1212// repo database for speed, and rank by speed. the oses the ranker knows are
1313// in rank_oses; the protocols to rank come from the config
1414
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,
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,
1717// how many of the lowest latencies get the speed test, how many of the
1818// fastest are timed again, and how many are answered when -n names none
1919__global rank_min_completion = 1.0
2020__global rank_max_delay = i64(86400)
2121
2222// 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
23+// #:parallel when it sets one, else the network's #:parallel
2424fn rank_parallelism() int {
2525 return if rank_parallel > 0 { rank_parallel } else { parallel_downloads }
2626}
@@ -59,7 +59,7 @@ fn default_rank_oses() map[string]RankOs {
5959
6060// rank_oses are the oses the ranker knows: the defaults, and every one the
6161// config's (mirrorlist ...) form defines or redefines. rank_dir is where a
62-// ranking is written for the config to require, (rank :dir)
62+// ranking is written for the config to require, (rank #:dir)
6363__global rank_oses = default_rank_oses()
6464__global rank_dir = '/etc/vpac.d/mirrors'
6565
@@ -79,7 +79,7 @@ fn rank_os_name(query []string) !string {
7979 }
8080 if query.len == 1 {
8181 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')
82+ return error('the ranker knows ${rank_os_names()}, not "${query[0]}": define it with (mirrorlist #:name ...) in the config')
8383 }
8484 return query[0]
8585 }
@@ -100,12 +100,13 @@ fn rank_os_name(query []string) !string {
100100 return candidate
101101 }
102102 }
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')
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')
104104}
105105
106106// rank_write_target is where a ranked os is written for the config to require
107107fn rank_write_target(os_name string) string {
108- return os.join_path(rank_dir, '${os_name}.lip')
108+ extension := if config_vile { 'vile' } else { 'scm' }
109+ return os.join_path(rank_dir, '${os_name}.${extension}')
109110}
110111
111112struct StatusMirror {
@@ -480,25 +481,26 @@ fn sync_age(last_sync string) string {
480481 return '${hours}h ago'
481482}
482483
483-// mirrors_lip is the blip file of the ranked urls: mirrors/<os>.lip defines
484-// mirrors-<os>, the way repos.lip expects. each url is a string literal
485-// escaped by blip's own printer: the urls come from the network and the file
486-// is config that vpac runs as root, so a quote in a url must stay inside its
487-// string
488-fn mirrors_lip(os_name string, urls []string, date string) string {
489- var := 'mirrors-${os_name}'
490- mut content := '; mirrors for ${os_name}, ranked by vpac k -w on ${date}\n'
491- content += '(unless (defined? ${var}) (define ${var} []))\n'
492- content += '(array-append! ${var} [${urls.map(printer.quote_string(it)).join(' ')}])\n'
493- return content
484+// Both readers accept bar-escaped identifiers. Keep punctuation in custom
485+// mirror names and quotes in downloaded URLs inside their respective literals.
486+fn ranked_mirrors(os_name string, urls []string, date string, native bool) !string {
487+ name := '|mirrors-' + os_name.replace('\\', '\\\\').replace('|', '\\|') + '|'
488+ header := '; mirrors for ${os_name}, ranked by vpac k -w on ${date}\n'
489+ mut quoted := []string{}
490+ for url in urls { quoted << scheme.write(scheme.string_value(url))! }
491+ if native {
492+ prior := "if(defined?('${name})) { if(vector?(${name})) { vector->list(${name}) } else { ${name} } } else { list() }"
493+ return header + '${name} := append(${prior}, list(' + quoted.join(', ') + '))\n'
494+ }
495+ return header + "(define ${name} (append (if (defined? '${name}) (if (vector? ${name}) (vector->list ${name}) ${name}) (list)) (list ${quoted.join(' ')})))\n"
494496}
495497
496-// write_config_mirrors writes the ranked urls as the blip file the config
498+// write_config_mirrors writes the ranked urls as the scheme file the config
497499// requires
498500fn write_config_mirrors(os_name string, urls []string) !string {
499501 target := rank_write_target(os_name)
500502 os.mkdir_all(os.dir(target))!
501- os.write_file(target, mirrors_lip(os_name, urls, time.now().custom_format('YYYY-MM-DD')))!
503+ os.write_file(target, ranked_mirrors(os_name, urls, time.now().custom_format('YYYY-MM-DD'), config_vile)!)!
502504 return target
503505}
504506
@@ -1,24 +1,28 @@
11@[has_globals]
22module main
33
4-import blip.vlib.blip.machine
4+import vile.scheme
55import net
6+import os
67import sync
78import time
89
9-// mirrors_machine is a blip machine set up the way load_config sets one up,
10+// mirrors_machine is a scheme machine set up the way load_config sets one up,
1011// for what a mirrors file needs
11-fn mirrors_machine() &machine.Machine {
12- mut m := machine.new_standalone(&QuietConfigHost{})
13- m.prims['array-append!'] = prim_array_append
12+fn mirrors_machine() !&scheme.VM {
13+ mut m := scheme.new_with_options(max_steps: 100_000_000)!
14+ m.register('defined?', prim_defined)!
1415 return m
1516}
1617
17-fn mirrors_read(mut m machine.Machine, var string) ![]string {
18- return m.run_str(var)!.as_vector().data.map(it.as_string())
18+fn mirrors_read(mut m scheme.VM, var string) ![]string {
19+ items := m.lookup(var)!.list_items()!
20+ mut urls := []string{}
21+ for item in items { urls << item.as_string()! }
22+ return urls
1923}
2024
21-fn test_mirrors_lip_round_trip() ! {
25+fn test_ranked_mirror_files_round_trip() ! {
2226 urls := [
2327 'https://ok.example/' + r'$repo/os/$arch',
2428 'https://quote.example/a"b',
@@ -26,32 +30,50 @@ fn test_mirrors_lip_round_trip() ! {
2630 'https://newline.example/a\nb',
2731 'https://tab.example/a\tb',
2832 // closes its string and the form, then defines something
29- 'https://x.example/"]) (define pwned 1) (array-append! mirrors-arch ["',
33+ 'https://x.example/")) (define pwned 1) (append mirrors-arch (list "',
3034 ]
31- text := mirrors_lip('arch', urls, '2026-11-08')
32- assert text.starts_with('; mirrors for arch, ranked by vpac k -w on 2026-11-08\n')
33- mut m := mirrors_machine()
34- m.run_str(text)!
35- assert mirrors_read(mut m, 'mirrors-arch')! == urls
36- if _ := m.run_str('pwned') {
37- assert false, 'a url ran as code'
35+ for native in [false, true] {
36+ text := ranked_mirrors('arch', urls, '2026-11-08', native)!
37+ assert text.starts_with('; mirrors for arch, ranked by vpac k -w on 2026-11-08\n')
38+ mut m := mirrors_machine()!
39+ if native { m.eval_alt(text)! } else { m.eval(text)! }
40+ assert mirrors_read(mut m, 'mirrors-arch')! == urls
41+ if _ := m.eval('pwned') {
42+ assert false, 'a url ran as code'
43+ }
3844 }
3945}
4046
41-fn test_mirrors_lip_appends() ! {
47+fn test_mirrors_scm_appends() ! {
4248 // the file adds to a list the config may have started already
43- mut m := mirrors_machine()
44- m.run_str('(define mirrors-arch ["https://first.example/"])')!
45- m.run_str(mirrors_lip('arch', ['https://second.example/'], 'today'))!
49+ mut m := mirrors_machine()!
50+ m.eval('(define mirrors-arch #("https://first.example/"))')!
51+ m.eval(ranked_mirrors('arch', ['https://second.example/'], 'today', false)!)!
4652 assert mirrors_read(mut m, 'mirrors-arch')! == ['https://first.example/', 'https://second.example/']
4753}
4854
49-fn test_mirrors_lip_empty() ! {
50- mut m := mirrors_machine()
51- m.run_str(mirrors_lip('artix', [], 'today'))!
55+fn test_mirrors_scm_empty() ! {
56+ mut m := mirrors_machine()!
57+ m.eval(ranked_mirrors('artix', [], 'today', false)!)!
5258 assert mirrors_read(mut m, 'mirrors-artix')!.len == 0
5359}
5460
61+fn test_ranked_mirrors_load_from_config() ! {
62+ dir := os.join_path(os.vtmp_dir(), 'vpac_ranked_config_${os.getpid()}')
63+ os.mkdir_all(dir)!
64+ defer {
65+ reset_config()
66+ os.rmdir_all(dir) or { went_on('remove the test config', err) }
67+ }
68+ urls := ['https://one.example/\$repo/os/\$arch', 'https://two.example/\$repo/os/\$arch']
69+ os.write_file(os.join_path(dir, 'mirrors.scm'), ranked_mirrors('artix', urls, 'today', false)!)!
70+ path := os.join_path(dir, 'config.scm')
71+ os.write_file(path, '(load "mirrors.scm")\n(repo #:name "system" #:src mirrors-artix)')!
72+ load_config(path, [])!
73+ assert cfg_repos.len == 1
74+ assert cfg_repos[0].servers == urls
75+}
76+
5577// ProbeTally is what a fake probe records across the batch's threads: how
5678// many ran at once, at the most, and which mirrors it was handed
5779@[heap]
@@ -1,6 +1,6 @@
11module main
22
3-import alpm
3+import nspkg
44
55// mark sets the install reason of installed packages, pacman's -D --asdeps
66// and --asexplicit. every target is found first; one that names nothing is
@@ -13,7 +13,7 @@ fn mark(config ConfigMark) ! {
1313 mut ui := new_trans_ui(noconfirm: config.noconfirm)
1414 check_ask_db_lock(mut ui)
1515 mut handle := init_handle(ui)!
16- defer { handle.release() or { went_on('release the alpm handle', err) } }
16+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
1717 defer { ui.stop() }
1818 defer { trans_cleanup(handle) }
1919
@@ -21,7 +21,7 @@ fn mark(config ConfigMark) ! {
2121
2222 reason := parse_reason(config.reason)!
2323
24- mut pkgs := []&alpm.Package{}
24+ mut pkgs := []&nspkg.Package{}
2525 for target in config.query {
2626 mut name := local_target_name(target)
2727 pkg := find_local_target(pkgcache, name, false) or {
@@ -40,7 +40,7 @@ fn mark(config ConfigMark) ! {
4040 return
4141 }
4242
43- trans_begin(handle, alpm.trans_flag_0)!
43+ trans_begin(handle, nspkg.trans_flag_0)!
4444 // each reason is written to the db as it is set, so a failure leaves the
4545 // ones before it changed: the error names them, so the run is truthful
4646 // about what it did and did not do
@@ -69,7 +69,7 @@ fn mark(config ConfigMark) ! {
6969
7070// reason_key is an install reason as a frontend reads it, and the word
7171// mark takes for it (parse_reason); every reason named, as reason_to_str
72-fn reason_key(reason alpm.PackageReason) string {
72+fn reason_key(reason nspkg.PackageReason) string {
7373 return match reason {
7474 .explicit { 'explicit' }
7575 .depend { 'depend' }
@@ -78,11 +78,11 @@ fn reason_key(reason alpm.PackageReason) string {
7878}
7979
8080// parse_reason reads mark's --reason: a reason's key, or a short form of it
81-fn parse_reason(text string) !alpm.PackageReason {
81+fn parse_reason(text string) !nspkg.PackageReason {
8282 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 }
83+ 'e', 'ex', 'explicit' { nspkg.PackageReason.explicit }
84+ 'd', 'dep', 'depend', 'dependency' { nspkg.PackageReason.depend }
85+ 'u', 'un', 'unknown' { nspkg.PackageReason.unknown }
8686 else { error('unknown reason: "${text}"') }
8787 }
8888}
@@ -1,6 +1,6 @@
11module main
22
3-import alpm
3+import nspkg
44
55// orphan_pkgs are the installed dependencies that nothing kept reaches through
66// its dependencies. the kept packages are the explicitly installed ones and the
@@ -12,7 +12,7 @@ import alpm
1212// a dependency reaches every installed package that satisfies it, not the
1313// first one alone: pacman's compute_requiredby counts a requirer for each
1414// provider, so two providers of one virtual name are both kept
15-fn orphan_pkgs(mut pkgcache alpm.List, optional_too bool) []&alpm.Package {
15+fn orphan_pkgs(mut pkgcache nspkg.List, optional_too bool) []&nspkg.Package {
1616 installed := pkgcache.pkgs()
1717 // who could answer for a name: the package called it, and every one
1818 // that provides it, by its place in installed; the version is libalpm's to compare, below
@@ -26,7 +26,7 @@ fn orphan_pkgs(mut pkgcache alpm.List, optional_too bool) []&alpm.Package {
2626 }
2727 }
2828 mut reached := map[string]bool{}
29- mut queue := []&alpm.Package{}
29+ mut queue := []&nspkg.Package{}
3030 for pkg in installed {
3131 if pkg.get_reason() != .depend || (!optional_too && pkg.compute_optional_for().len > 0) {
3232 reached[pkg.get_name()] = true
@@ -45,7 +45,7 @@ fn orphan_pkgs(mut pkgcache alpm.List, optional_too bool) []&alpm.Package {
4545 }
4646 // a list of the one candidate, for alpm_find_satisfier's
4747 // version and provision comparison
48- one := &alpm.List(unsafe { nil }).add(voidptr(cand))
48+ one := &nspkg.List(unsafe { nil }).add(voidptr(cand))
4949 satisfied := one.find_satisfier(depstring) != none
5050 one.free()
5151 if satisfied {
@@ -59,8 +59,8 @@ fn orphan_pkgs(mut pkgcache alpm.List, optional_too bool) []&alpm.Package {
5959}
6060
6161fn 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) } }
62+ mut handle := nspkg.initialize(root_path, db_path) or { return err }
63+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
6464
6565 mut pkgcache := local_pkgcache(handle)!
6666
@@ -1,6 +1,6 @@
11module main
22
3-import alpm
3+import nspkg
44import os
55import testdb
66
@@ -82,7 +82,7 @@ fn test_orphan_pkgs() ! {
8282 },
8383 ])!
8484
85- handle := alpm.initialize(os.join_path(tmp, 'root') + '/', os.join_path(tmp, 'db') + '/')!
85+ handle := nspkg.initialize(os.join_path(tmp, 'root') + '/', os.join_path(tmp, 'db') + '/')!
8686 defer { handle.release() or {} }
8787 localdb := handle.get_localdb()!
8888 mut pkgcache := localdb.get_pkgcache() or { return error('the fake local db has no packages') }
@@ -38,7 +38,7 @@ pub mut:
3838// pkgbuild_rpc_timeout is how long one rpc request may take, for the search
3939// and the info lookups of the pkgbuild repos. a stall would otherwise hang
4040// the search under a proxy's silent wall
41-// (pkgbuild :timeout) sets it, in seconds
41+// (pkgbuild #:timeout) sets it, in seconds
4242__global pkgbuild_rpc_timeout = 10
4343
4444// pkgbuild_rpc fetches one url and reads its answer: timed, and demanding an
@@ -1,6 +1,6 @@
11module main
22
3-import alpm
3+import nspkg
44import os
55import time
66import vmakepkg
@@ -25,9 +25,9 @@ struct PkgbuildNode {
2525// in the pkgbuild repo and placed before the package that needs it
2626struct PkgbuildResolver {
2727mut:
28- handle &alpm.Handle
29- installed &alpm.List
30- sync_dbs &alpm.List
28+ handle &nspkg.Handle
29+ installed &nspkg.List
30+ sync_dbs &nspkg.List
3131 // visiting holds the names on the branch being walked, so a cycle is a
3232 // named error instead of a node silently skipped; done holds the ones
3333 // whose nodes are already in, so they are never built twice
@@ -123,7 +123,66 @@ fn pkgbuild_build_dir(user string, base string) !string {
123123// the shell on purpose, trusted as far as the config it comes from, and
124124// reviewed by the user beside everything else a pkgbuild runs
125125fn makepkg_line(dir string) string {
126- return 'cd ${vmakepkg.shell_quote(dir)} && ${pkgbuild_makepkg}'
126+ cd := 'cd ${vmakepkg.shell_quote(dir)} && '
127+ if os.uname().sysname.to_lower() == 'vinix' {
128+ return cd + 'export VPAC_MAKEPKG_EXE=${vmakepkg.shell_quote(os.executable())} VPAC_MAKEPKG_ROOT=${vmakepkg.shell_quote(root_path)} VPAC_MAKEPKG_DB=${vmakepkg.shell_quote(db_path)} && ' +
129+ pkgbuild_makepkg
130+ }
131+ return cd + pkgbuild_makepkg
132+}
133+
134+// makepkg's bash helpers open process substitutions through /dev/fd.
135+// Vinix supplies the descriptors in procfs and recreates /dev at boot.
136+fn run_makepkg(user string, dir string) ! {
137+ if os.uname().sysname.to_lower() == 'vinix' {
138+ // makepkg queries the local database as the builder, including on first use.
139+ handle := nspkg.initialize(root_path, db_path)!
140+ handle.release()!
141+ if !os.is_dir('/dev/fd') {
142+ os.symlink('/proc/self/fd', '/dev/fd') or {
143+ if !os.is_dir('/dev/fd') {
144+ return error('makepkg needs /dev/fd linked to /proc/self/fd: ${err}')
145+ }
146+ }
147+ }
148+ }
149+ run_as_user(user, ['sh', '-c', makepkg_line(dir)])!
150+}
151+
152+// makepkg reads these pacman queries to check dependencies and write .BUILDINFO.
153+// use the same local package cache as the transaction that installs the build.
154+fn makepkg_query(args []string) !int {
155+ if args.len == 0 {
156+ return error('makepkg did not specify a database query')
157+ }
158+ handle := nspkg.initialize(os.getenv('VPAC_MAKEPKG_ROOT'), os.getenv('VPAC_MAKEPKG_DB'))!
159+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
160+ cache := local_pkgcache(handle)!
161+ match args[0] {
162+ '-T' {
163+ missing := unsatisfied_deps(cache, args[1..])
164+ for dep in missing {
165+ println(dep)
166+ }
167+ if missing.len > 0 {
168+ return 127
169+ }
170+ }
171+ '-Qi', '-Qq' {
172+ if args.len != 1 {
173+ return error('makepkg expected a query for all installed packages')
174+ }
175+ for pkg in cache.pkgs() {
176+ if args[0] == '-Qq' {
177+ println(pkg.get_name())
178+ } else {
179+ println('Name : ${pkg.get_name()}\nVersion : ${pkg.get_version()}\nArchitecture : ${pkg.get_arch()}')
180+ }
181+ }
182+ }
183+ else { return error('unsupported makepkg database query: ${args[0]}') }
184+ }
185+ return 0
127186}
128187
129188// run_process runs a command, its arguments reaching it one by one with no
@@ -190,7 +249,7 @@ fn run_as_user(user string, args []string) ! {
190249}
191250
192251// 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
252+// keep the generated field in the IPC review event for existing frontends.
194253struct ReviewFile {
195254 name string
196255 text string
@@ -260,11 +319,7 @@ fn review_text(r ReviewEvent, title string) string {
260319 out << heading(title)
261320 }
262321 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- })
322+ out << heading(f.name)
268323 out << f.text
269324 }
270325 if r.listing.len > 0 {
@@ -312,6 +367,11 @@ fn archives_in(dir string) ![]string {
312367 for f in os.ls(dir)! {
313368 if is_pkg_archive(f) {
314369 out << '${dir}/${f}'
370+ } else if f.starts_with('.vpac-') && os.is_dir('${dir}/${f}') && !os.is_link('${dir}/${f}') {
371+ // completed native archives live beside this build's src and pkg directories.
372+ for name in os.ls('${dir}/${f}')! {
373+ if is_pkg_archive(name) { out << os.join_path(dir, f, name) }
374+ }
315375 }
316376 }
317377 return out
@@ -371,8 +431,9 @@ fn review_and_build(mut ui TransUI, user string, node PkgbuildNode, config Confi
371431
372432 // with --nopkgbuildconfirm nothing is asked, and the review is still
373433 // shown: the record of what was built stays in the output
434+ source_name := build_recipe_name(dir)!
374435 if !ask || ui.yesno('review the pkgbuild?') {
375- mut review := read_review(name, dir)!
436+ mut review := recipe_review(user, name, dir, source_name)!
376437 review.warnings = pkgbuild_warnings(node.info)
377438 show_review(review, 'review ${name}')
378439 }
@@ -389,9 +450,9 @@ fn review_and_build(mut ui TransUI, user string, node PkgbuildNode, config Confi
389450 ui.sync()
390451 }
391452 build_phase(name, 'start')
392- run_as_user(user, ['sh', '-c', makepkg_line(dir)])!
453+ archives := build_archives(user, dir, source_name)!
393454 build_phase(name, 'done')
394- return built_packages(user, dir)!
455+ return archives
395456}
396457
397458// BuildDeclined is review_and_build's answer when the user said no
@@ -408,12 +469,12 @@ fn (e BuildDeclined) msg() string {
408469// local db when the run began, and every build since was installed through
409470// another one (install's): its list is the past, and what is planned, asked
410471// and skipped from here on is decided on the present
411-fn local_now() !(&alpm.Handle, &alpm.List) {
412- handle := alpm.initialize(root_path, db_path) or {
472+fn local_now() !(&nspkg.Handle, &nspkg.List) {
473+ handle := nspkg.initialize(root_path, db_path) or {
413474 return error('could not read the local database: ${err.msg()}')
414475 }
415476 pkgs := local_pkgcache(handle) or {
416- handle.release() or { went_on('release the alpm handle', err) }
477+ handle.release() or { went_on('release the nspkg handle', err) }
417478 return err
418479 }
419480 return handle, pkgs
@@ -435,7 +496,7 @@ struct NodeStep {
435496// package of its name is there at some version. the target is only ever
436497// skipped by --needed, at the very version it would install. the repo
437498// dependencies are the ones still missing
438-fn node_step(installed &alpm.List, node PkgbuildNode, needed bool, is_target bool) NodeStep {
499+fn node_step(installed &nspkg.List, node PkgbuildNode, needed bool, is_target bool) NodeStep {
439500 name := node.info.name
440501 if !is_target && node.wanted.len > 0
441502 && node.wanted.all(installed.find_satisfier(it) != none) {
@@ -446,7 +507,7 @@ fn node_step(installed &alpm.List, node PkgbuildNode, needed bool, is_target boo
446507 }
447508 if is_target && needed {
448509 if local := installed.pkg_find(name) {
449- if alpm.pkg_vercmp(local.get_version(), node.info.version) == 0 {
510+ if nspkg.pkg_vercmp(local.get_version(), node.info.version) == 0 {
450511 return NodeStep{
451512 skip: true
452513 why: '${name}-${node.info.version} is up to date, skipped'
@@ -462,7 +523,7 @@ fn node_step(installed &alpm.List, node PkgbuildNode, needed bool, is_target boo
462523// node_step_now is node_step on the local db read this moment
463524fn node_step_now(node PkgbuildNode, needed bool, is_target bool) !NodeStep {
464525 view, installed := local_now()!
465- defer { view.release() or { went_on('release the alpm handle', err) } }
526+ defer { view.release() or { went_on('release the nspkg handle', err) } }
466527 return node_step(installed, node, needed, is_target)
467528}
468529
@@ -512,9 +573,9 @@ fn built_install_config(config ConfigInstall, archives []string, is_target bool)
512573
513574// pkgbuild_plan resolves target into its build plan, dependencies first,
514575// against the local db read this moment and the handle's sync dbs
515-fn pkgbuild_plan(handle &alpm.Handle, target string) ![]PkgbuildNode {
576+fn pkgbuild_plan(handle &nspkg.Handle, target string) ![]PkgbuildNode {
516577 view, installed := local_now()!
517- defer { view.release() or { went_on('release the alpm handle', err) } }
578+ defer { view.release() or { went_on('release the nspkg handle', err) } }
518579 mut r := PkgbuildResolver{
519580 // the caller's handle outlives the plan: it is only read here
520581 handle: unsafe { handle }
@@ -528,7 +589,7 @@ fn pkgbuild_plan(handle &alpm.Handle, target string) ![]PkgbuildNode {
528589// pkgbuild_install builds an AUR package and the AUR packages it needs, reviewing
529590// each one, then installs what was built. the gate is the first question's
530591// word, the caller's to write — the generic install question when it is empty
531-fn pkgbuild_install(mut ui TransUI, mut handle &alpm.Handle, config ConfigInstall, target string, gate string) ! {
592+fn pkgbuild_install(mut ui TransUI, mut handle &nspkg.Handle, config ConfigInstall, target string, gate string) ! {
532593 user := invoker_user()!
533594 // the plan is resolved against the installed packages as they are now:
534595 // an earlier target of this run may have been built and installed since
@@ -50,11 +50,6 @@ fn test_review() ! {
5050 'files in the package',
5151 'PKGBUILD a.patch foo.install',
5252 ].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
5853}
5954
6055fn test_makepkg_line() ! {
@@ -108,10 +103,13 @@ fn test_archives_in() ! {
108103 'PKGBUILD', 'notes.tar'] {
109104 os.write_file(os.join_path(dir, f), '')!
110105 }
106+ native := os.join_path(dir, '.vpac-private')
107+ os.mkdir(native)!
108+ os.write_file(os.join_path(native, 'split-2-1-any.pkg.tar.zst'), '')!
111109 mut got := archives_in(dir)!.map(os.base(it))
112110 got.sort()
113111 // 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']
112+ assert got == ['bar-2-1-x86_64.pkg.tar.zst', 'foo-1.0-1-any.pkg.tar', 'split-2-1-any.pkg.tar.zst']
115113}
116114
117115fn test_makepkg_packagelist_names_what_is_built() ! {
@@ -4,7 +4,7 @@ module main
44import os
55import vmakepkg
66
7-// root_provider is how vpac gets root: the config's (options :root "..."),
7+// root_provider is how vpac gets root: the config's (options #:root "..."),
88// sudo unless it says otherwise. vpac re-runs itself through it with the
99// same arguments, so it gives the same pipes and exit status. it is a
1010// command line of the user's own: any program that runs the words after it
@@ -74,10 +74,10 @@ fn reexec_as_root(args []string) ! {
7474 invoker := current_user()!
7575 words := root_provider.fields()
7676 if words.len == 0 {
77- return error('config: options :root names no command to get root with')
77+ return error('config: options #:root names no command to get root with')
7878 }
7979 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')
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')
8181 }
8282 // the compiler rides along, exactly like the invoker does
8383 vbin := os.find_abs_path_of_executable('v') or { '' }
@@ -468,7 +468,7 @@ fn test_verbose_log_says_what_a_run_went_on_from() ! {
468468 verbose_flag, cfg_verbose, ui_kind = saved_flag, saved_cfg, saved_kind
469469 }
470470 fail := fn () []int {
471- went_on('release the alpm handle', error('the handle is not there'))
471+ went_on('release the nspkg handle', error('the handle is not there'))
472472 went_on('remove the temp dir /tmp/x', error(''))
473473 return []
474474 }
@@ -486,7 +486,7 @@ fn test_verbose_log_says_what_a_run_went_on_from() ! {
486486 said := on_stdin(.text, '', fail)!
487487 // a terminal gets it on stderr, marked, the reason after the what;
488488 // 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
489+ assert said.stderr == 'verbose: could not release the nspkg handle: the handle is not there\nverbose: could not remove the temp dir /tmp/x: \n', said.stderr
490490 assert said.channel.len == 0
491491 // a frontend gets a message event marked verbose, and a warning for
492492 // a reader that knows no verbose mark; stderr stays clean
@@ -496,7 +496,7 @@ fn test_verbose_log_says_what_a_run_went_on_from() ! {
496496 events := ipc_events(told.channel)!
497497 assert events.len == 2
498498 assert events[0]['type']!.str() == 'message'
499- assert events[0]['text']!.str() == 'could not release the alpm handle: the handle is not there'
499+ assert events[0]['text']!.str() == 'could not release the nspkg handle: the handle is not there'
500500 assert events[0]['verbose']!.bool() && events[0]['warning']!.bool()
501501 }
502502 // an ordinary warning never carries the mark, verbose on or not
@@ -1,6 +1,6 @@
11module main
22
3-import alpm
3+import nspkg
44import os
55
66// a target is a local package file if a file with that name exists,
@@ -22,7 +22,7 @@ struct FileTarget {
2222// libalpm's integrity pass at commit skips one loaded from a file as valid
2323// already — so a level of 0 here would let a bad signature beside the
2424// archive install unread
25-fn load_file_target(handle &alpm.Handle, t FileTarget) !&alpm.Package {
25+fn load_file_target(handle &nspkg.Handle, t FileTarget) !&nspkg.Package {
2626 origin := if t.fetched { 'remote' } else { 'local' }
2727 got := if t.fetched {
2828 handle.option_get_remote_file_siglevel()
@@ -36,7 +36,7 @@ fn load_file_target(handle &alpm.Handle, t FileTarget) !&alpm.Package {
3636}
3737
3838// 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 {
39+fn find_repo_pkg(dbs []&nspkg.DB, name string) ?&nspkg.Package {
4040 for db in dbs {
4141 if p := db.get_pkg(name) {
4242 return p
@@ -46,7 +46,7 @@ fn find_repo_pkg(dbs []&alpm.DB, name string) ?&alpm.Package {
4646}
4747
4848// 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) {
49+fn add_pkg_once(mut pkgs []&nspkg.Package, pkg &nspkg.Package) {
5050 if pkgs.any(it.get_name() == pkg.get_name()) {
5151 return
5252 }
@@ -60,7 +60,7 @@ fn add_pkg_once(mut pkgs []&alpm.Package, pkg &alpm.Package) {
6060// so there is nothing to choose). it answers whether the name was a group at
6161// all, and how many members went in. a group with nothing left to install
6262// 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) {
63+fn expand_group(mut pkgs []&nspkg.Package, mut ui TransUI, handle &nspkg.Handle, dbs []&nspkg.DB, name string, ask bool) (bool, int) {
6464 found, members := sync_group_members(dbs, name)
6565 if !found {
6666 return false, 0
@@ -68,7 +68,7 @@ fn expand_group(mut pkgs []&alpm.Package, mut ui TransUI, handle &alpm.Handle, d
6868 mut news := []GroupMember{}
6969 for m in members {
7070 if local := handle.find_local_pkg(m.pkg.get_name()) {
71- if alpm.pkg_vercmp(local.get_version(), m.pkg.get_version()) >= 0 {
71+ if nspkg.pkg_vercmp(local.get_version(), m.pkg.get_version()) >= 0 {
7272 continue
7373 }
7474 }
@@ -93,11 +93,11 @@ fn expand_group(mut pkgs []&alpm.Package, mut ui TransUI, handle &alpm.Handle, d
9393// install is left out, with pacman's warning. libalpm's needed flag does the
9494// same inside add_pkg, warning through its log; here the targets are left
9595// 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{}
96+fn skip_up_to_date(handle &nspkg.Handle, pkgs []&nspkg.Package) []&nspkg.Package {
97+ mut out := []&nspkg.Package{}
9898 for pkg in pkgs {
9999 if local := handle.find_local_pkg(pkg.get_name()) {
100- if alpm.pkg_vercmp(local.get_version(), pkg.get_version()) == 0 {
100+ if nspkg.pkg_vercmp(local.get_version(), pkg.get_version()) == 0 {
101101 warn('${pkg.get_name()}-${pkg.get_version()} is up to date, skipped')
102102 continue
103103 }
@@ -113,11 +113,11 @@ fn skip_up_to_date(handle &alpm.Handle, pkgs []&alpm.Package) []&alpm.Package {
113113// up only to decide what to upgrade with, and the provider question that
114114// counts comes again in the prepare. the walking window is this function's
115115// 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) ! {
116+fn walk_upgrade_deps(mut ui TransUI, handle &nspkg.Handle, mut pkgs []&nspkg.Package, mut added map[string]bool) ! {
117117 ui.walking = true
118118 defer { ui.walking = false }
119119 sync_dbs := handle.get_syncdbs()!
120- mut upgrades := []&alpm.Package{}
120+ mut upgrades := []&nspkg.Package{}
121121 upgrades << pkgs
122122 for pkg in pkgs {
123123 for dep in handle.outdated_deps(sync_dbs, pkg) {
@@ -145,7 +145,7 @@ fn walk_upgrade_deps(mut ui TransUI, handle &alpm.Handle, mut pkgs []&alpm.Packa
145145}
146146
147147// install_reason is the reason --asdeps or --asexplicit asks for, if any
148-fn install_reason(config ConfigInstall) ?alpm.PackageReason {
148+fn install_reason(config ConfigInstall) ?nspkg.PackageReason {
149149 if config.asdeps {
150150 return .depend
151151 }
@@ -160,8 +160,8 @@ fn install_reason(config ConfigInstall) ?alpm.PackageReason {
160160// every package of the transaction, the outdated dependencies vpac upgrades
161161// along with the targets too, so the reason is set on the targets alone once
162162// 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)!
163+fn mark_installed(handle &nspkg.Handle, names []string, reason nspkg.PackageReason) ! {
164+ trans_begin(handle, nspkg.trans_flag_0)!
165165 defer { trans_cleanup(handle) }
166166 for name in names {
167167 pkg := handle.find_local_pkg(name) or { continue }
@@ -175,7 +175,7 @@ fn mark_installed(handle &alpm.Handle, names []string, reason alpm.PackageReason
175175// it also adds the outdated dependencies of each one, then lists everything the
176176// transaction touches and asks before committing. it returns false when the user
177177// declines
178-fn install_pkgs(handle &alpm.Handle, mut ui TransUI, mut pkgs []&alpm.Package, config ConfigInstall) !bool {
178+fn install_pkgs(handle &nspkg.Handle, mut ui TransUI, mut pkgs []&nspkg.Package, config ConfigInstall) !bool {
179179 mut s := ui.spinner(text: 'preparing transaction')
180180 s.start()
181181 defer { stop_spinner(mut s) }
@@ -270,7 +270,7 @@ fn install(config ConfigInstall) ! {
270270 // drawing on the same display and asking through the same prompter as
271271 // the transaction's own downloads
272272 mut handle := init_handle(ui)!
273- defer { handle.release() or { went_on('release the alpm handle', err) } }
273+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
274274 defer { ui.stop() }
275275 defer { trans_cleanup(handle) }
276276 trans_options(config).apply(handle)!
@@ -308,7 +308,7 @@ fn install(config ConfigInstall) ! {
308308 check_sync_fresh(mut ui, mut handle)!
309309 }
310310
311- mut pkgs := []&alpm.Package{}
311+ mut pkgs := []&nspkg.Package{}
312312 for f in file_targets {
313313 add_pkg_once(mut pkgs, load_file_target(handle, f)!)
314314 }
@@ -359,7 +359,7 @@ fn install(config ConfigInstall) ! {
359359
360360 mut pkgbuild_builds := []string{}
361361 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")')
362+ return error('no pkgbuild repo in the config: add (repo #:name "aur" #:type "pkgbuild" #:src "https://aur.archlinux.org")')
363363 }
364364 for name in pkgbuild {
365365 if config.pkgbuild {
@@ -1,6 +1,6 @@
11module main
22
3-import alpm
3+import nspkg
44import os
55
66fn test_install_reason() {
@@ -25,8 +25,8 @@ fn reason_db(dbpath string) ! {
2525 }
2626}
2727
28-fn local_reason(root string, dbpath string, name string) !alpm.PackageReason {
29- handle := alpm.initialize(root, dbpath)!
28+fn local_reason(root string, dbpath string, name string) !nspkg.PackageReason {
29+ handle := nspkg.initialize(root, dbpath)!
3030 defer { handle.release() or {} }
3131 pkg := handle.find_local_pkg(name) or { return error('${name} is not installed') }
3232 return pkg.get_reason()
@@ -40,7 +40,7 @@ fn test_mark_installed() ! {
4040 reason_db(dbpath)!
4141 defer { os.rmdir_all(tmp) or {} }
4242
43- handle := alpm.initialize(root, dbpath)!
43+ handle := nspkg.initialize(root, dbpath)!
4444 // --asexplicit on the dependency, --asdeps on the top package; a name
4545 // that is not installed (a target that failed) is passed over
4646 mark_installed(handle, ['dep', 'missing'], .explicit)!
@@ -83,8 +83,8 @@ fn sig_fixture(name string) !SigFixture {
8383
8484// handle opens the fixture's root with its own keyring dir, so the gpg a
8585// 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') + '/')!
86+fn (fx SigFixture) handle(local nspkg.SigLevel, remote nspkg.SigLevel) !&nspkg.Handle {
87+ handle := nspkg.initialize(os.join_path(fx.tmp, 'root') + '/', os.join_path(fx.tmp, 'db') + '/')!
8888 handle.option_set_gpgdir(os.join_path(fx.tmp, 'gpg') + '/')!
8989 handle.option_set_local_file_siglevel(local)!
9090 handle.option_set_remote_file_siglevel(remote)!
@@ -92,7 +92,7 @@ fn (fx SigFixture) handle(local alpm.SigLevel, remote alpm.SigLevel) !&alpm.Hand
9292}
9393
9494// loads tells whether the fixture's archive loads as t's origin
95-fn loads(handle &alpm.Handle, path string, fetched bool) bool {
95+fn loads(handle &nspkg.Handle, path string, fetched bool) bool {
9696 pkg := load_file_target(handle, FileTarget{
9797 path: path
9898 fetched: fetched
@@ -101,8 +101,8 @@ fn loads(handle &alpm.Handle, path string, fetched bool) bool {
101101 return true
102102}
103103
104-const sig_optional = alpm.SigLevel.package | .package_optional
105-const sig_required = alpm.SigLevel.package
104+const sig_optional = nspkg.SigLevel.package | .package_optional
105+const sig_required = nspkg.SigLevel.package
106106
107107fn test_load_file_target_verifies_a_signature_beside_the_archive() ! {
108108 fx := sig_fixture('present')!
@@ -1,26 +1,26 @@
11module main
22
3-import alpm
3+import nspkg
44
55// local_group_pkgs are the installed members of a group, pacman -R's
66// 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{} }
7+fn local_group_pkgs(handle &nspkg.Handle, name string) []&nspkg.Package {
8+ localdb := handle.get_localdb() or { return []&nspkg.Package{} }
9+ group := localdb.get_group(name) or { return []&nspkg.Package{} }
1010 return group.packages.pkgs()
1111}
1212
1313// recurse_flags is pacman's -s: once takes the dependencies the removal
1414// leaves unneeded, twice (-ss, or --recursive with -s) the ones that were
1515// installed explicitly too
16-fn recurse_flags(recursive bool, level int) alpm.TransFlag {
16+fn recurse_flags(recursive bool, level int) nspkg.TransFlag {
1717 n := level + if recursive { 1 } else { 0 }
1818 return if n >= 2 {
19- alpm.TransFlag.recurse | .recurse_all
19+ nspkg.TransFlag.recurse | .recurse_all
2020 } else if n == 1 {
21- alpm.TransFlag.recurse
21+ nspkg.TransFlag.recurse
2222 } else {
23- alpm.trans_flag_0
23+ nspkg.trans_flag_0
2424 }
2525}
2626
@@ -35,7 +35,7 @@ fn remove(config ConfigRemove) ! {
3535 }
3636
3737 mut handle := init_handle(ui)!
38- defer { handle.release() or { went_on('release the alpm handle', err) } }
38+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
3939 defer { ui.stop() }
4040 defer { trans_cleanup(handle) }
4141 TransOptions{
@@ -53,7 +53,7 @@ fn remove(config ConfigRemove) ! {
5353 // looked up, and then the run stops, as pacman's -R does. a target is a
5454 // package, what satisfies its version constraint, or a group of the
5555 // local db
56- mut pkgs := []&alpm.Package{}
56+ mut pkgs := []&nspkg.Package{}
5757 mut missed := 0
5858 for target in config.query {
5959 name := local_target_name(target)
@@ -1,6 +1,6 @@
11module main
22
3-import alpm
3+import nspkg
44import strings
55
66// terms_match is the classic match: every term is in the name or in the
@@ -18,7 +18,7 @@ fn terms_match(name string, desc string, terms []string) bool {
1818}
1919
2020// match_classic is the classic match of a libalpm package
21-fn match_classic(pkg &alpm.Package, config ConfigSearch) bool {
21+fn match_classic(pkg &nspkg.Package, config ConfigSearch) bool {
2222 return terms_match(pkg.get_name(), pkg.get_desc(), config.query)
2323}
2424
@@ -32,7 +32,7 @@ fn jw_if_match(config ConfigSearch, needle string, haystack string) ?f64 {
3232
3333// match_fuzzy_name needs every term to match the name, and scores the name by
3434// the average of the terms
35-fn match_fuzzy_name(pkg &alpm.Package, config ConfigSearch) ?f64 {
35+fn match_fuzzy_name(pkg &nspkg.Package, config ConfigSearch) ?f64 {
3636 if config.query.len == 0 {
3737 return none
3838 }
@@ -55,7 +55,7 @@ fn fuzzy_desc_hit(config ConfigSearch, term string, words []string) bool {
5555 return false
5656}
5757
58-fn match_fuzzy_desc(pkg &alpm.Package, config ConfigSearch) bool {
58+fn match_fuzzy_desc(pkg &nspkg.Package, config ConfigSearch) bool {
5959 if config.query.len == 0 {
6060 return false
6161 }
@@ -69,11 +69,11 @@ fn match_fuzzy_desc(pkg &alpm.Package, config ConfigSearch) bool {
6969}
7070
7171struct Scored {
72- pkg &alpm.Package
72+ pkg &nspkg.Package
7373 score f64
7474}
7575
76-fn build_matches(pkgs []&alpm.Package, config ConfigSearch) []&alpm.Package {
76+fn build_matches(pkgs []&nspkg.Package, config ConfigSearch) []&nspkg.Package {
7777 return if config.fuzzy {
7878 mut m_name := []Scored{cap: pkgs.len}
7979 for pkg in pkgs {
@@ -94,7 +94,7 @@ fn build_matches(pkgs []&alpm.Package, config ConfigSearch) []&alpm.Package {
9494 m_desc_pkg := pkgs.filter(|pkg| !by_name[pkg.get_name()] && match_fuzzy_desc(pkg, config))
9595 // one new list, the name matches then the description ones: neither
9696 // of the two it is made of is written to
97- mut matches := []&alpm.Package{cap: m_name_pkg.len + m_desc_pkg.len}
97+ mut matches := []&nspkg.Package{cap: m_name_pkg.len + m_desc_pkg.len}
9898 matches << m_name_pkg
9999 matches << m_desc_pkg
100100 matches
@@ -124,7 +124,7 @@ struct GroupRef {
124124
125125// group_source is how a listing names a db: the local one is 'local', as
126126// the installed packages are everywhere else
127-fn group_source(handle &alpm.Handle, db &alpm.DB) string {
127+fn group_source(handle &nspkg.Handle, db &nspkg.DB) string {
128128 if localdb := handle.get_localdb() {
129129 if voidptr(localdb) == voidptr(db) {
130130 return 'local'
@@ -134,7 +134,7 @@ fn group_source(handle &alpm.Handle, db &alpm.DB) string {
134134}
135135
136136// sync_groups lists every group of the dbs, db by db
137-fn sync_groups(handle &alpm.Handle, dbs []&alpm.DB) []GroupRef {
137+fn sync_groups(handle &nspkg.Handle, dbs []&nspkg.DB) []GroupRef {
138138 mut out := []GroupRef{}
139139 for db in dbs {
140140 mut node := db.get_groupcache() or { continue }
@@ -150,7 +150,7 @@ fn sync_groups(handle &alpm.Handle, dbs []&alpm.DB) []GroupRef {
150150
151151// scope_repo narrows a search to one repo when its first name is one, like
152152// '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) {
153+fn scope_repo(dbs []&nspkg.DB, query []string) ([]&nspkg.DB, []string) {
154154 if query.len > 1 && dbs.any(it.get_name() == query[0]) {
155155 return dbs.filter(it.get_name() == query[0]), query[1..]
156156 }
@@ -161,7 +161,7 @@ fn scope_repo(dbs []&alpm.DB, query []string) ([]&alpm.DB, []string) {
161161// sync dbs, or the local db for pacman's -Qg. the filters look at the
162162// installed packages: a member that is not installed cannot pass them, and
163163// 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) ! {
164+fn collect_group_members(mut listing Listing, handle &nspkg.Handle, dbs []&nspkg.DB, sync_dbs []&nspkg.DB, config ConfigSearch) ! {
165165 for name in config.query {
166166 mut found := false
167167 // a group several dbs carry lists each member once, from the first
@@ -197,7 +197,7 @@ fn collect_group_members(mut listing Listing, handle &alpm.Handle, dbs []&alpm.D
197197
198198// collect_search lists the matches of the query: the installed packages, the
199199// 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) ! {
200+fn collect_search(mut listing Listing, mut ui TransUI, mut handle &nspkg.Handle, config ConfigSearch) ! {
201201 if config.local {
202202 mut pkgcache := local_pkgcache(handle)!
203203
@@ -233,7 +233,7 @@ fn collect_search(mut listing Listing, mut ui TransUI, mut handle &alpm.Handle,
233233 if config.pkgbuild {
234234 mut brepos := pkgbuild_repos()
235235 if brepos.len == 0 {
236- return error('no pkgbuild repo in the config: add (repo :name "aur" :type "pkgbuild" :src "https://aur.archlinux.org")')
236+ return error('no pkgbuild repo in the config: add (repo #:name "aur" #:type "pkgbuild" #:src "https://aur.archlinux.org")')
237237 }
238238 // a first name that is a pkgbuild repo narrows the search to it
239239 mut bquery := config.query.clone()
@@ -276,7 +276,7 @@ fn search(config ConfigSearch) ! {
276276 }
277277 mut ui := new_trans_ui(noconfirm: config.noconfirm)
278278 mut handle := init_handle(ui)!
279- defer { handle.release() or { went_on('release the alpm handle', err) } }
279+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
280280 defer { ui.stop() }
281281
282282 fields := parse_fields(config.fields, cfg_search_fields)!
@@ -287,8 +287,8 @@ fn search(config ConfigSearch) ! {
287287
288288 if config.groups {
289289 mut scope := config
290- mut dbs := []&alpm.DB{}
291- mut sync_dbs := []&alpm.DB{}
290+ mut dbs := []&nspkg.DB{}
291+ mut sync_dbs := []&nspkg.DB{}
292292 if config.local {
293293 // pacman's -Qg: the groups of the installed packages, read from
294294 // the local db. the sync dbs come in only for a filter that
@@ -7,7 +7,7 @@ import term
77// 'never' decide for every stream, as pacman's --color does
88__global color_flag = 'auto'
99// color_given is whether the command line spelled a --color: the config's
10-// (options :color) is the default only when it did not
10+// (options #:color) is the default only when it did not
1111__global color_given = false
1212
1313// color_on is whether a stream gets styled: stdout, or stderr with err
@@ -21,7 +21,7 @@ fn color_on(err bool) bool {
2121 }
2222}
2323
24-// style_names are the styles a theme may name, (color :role [...]): the
24+// style_names are the styles a theme may name, (color #:role #(...)): the
2525// terminal's attributes and its sixteen colors
2626const style_names = ['none', 'bold', 'dim', 'italic', 'underline', 'reverse', 'black', 'red', 'green',
2727 'yellow', 'blue', 'magenta', 'cyan', 'white', 'gray', 'bright_black', 'bright_red', 'bright_green',
@@ -1,12 +1,12 @@
11@[has_globals]
22module main
33
4-import alpm
4+import nspkg
55import strings
66
77// suggest_thold is how close a name must be to be suggested. it is the fuzzy
88// search measure, a little stricter, since the user is asked about the answer
9-// (options :suggest) sets it
9+// (options #:suggest) sets it
1010__global suggest_thold = 0.85
1111
1212// closest_name is the name nearest to query, when it is near enough: a score
@@ -43,12 +43,12 @@ fn did_you_mean(mut ui TransUI, query string, names []string) !string {
4343 return error('unknown package: "${query}"')
4444}
4545
46-fn pkg_names(pkgs []&alpm.Package) []string {
46+fn pkg_names(pkgs []&nspkg.Package) []string {
4747 return pkgs.map(it.get_name())
4848}
4949
5050// sync_names lists the names of the packages in the sync dbs
51-fn sync_names(dbs []&alpm.DB) []string {
51+fn sync_names(dbs []&nspkg.DB) []string {
5252 mut names := []string{}
5353 for db in dbs {
5454 mut pkgcache := db.get_pkgcache() or { continue }
@@ -58,14 +58,14 @@ fn sync_names(dbs []&alpm.DB) []string {
5858}
5959
6060// 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 {
61+fn all_names(handle &nspkg.Handle, dbs []&nspkg.DB) []string {
6262 mut names := local_names(handle)
6363 names << sync_names(dbs)
6464 return names
6565}
6666
6767// local_names lists the names of the installed packages
68-fn local_names(handle &alpm.Handle) []string {
68+fn local_names(handle &nspkg.Handle) []string {
6969 localdb := handle.get_localdb() or { return []string{} }
7070 mut pkgcache := localdb.get_pkgcache() or { return []string{} }
7171 return pkg_names(pkgcache.pkgs())
@@ -1,6 +1,6 @@
11module main
22
3-import alpm
3+import nspkg
44
55// Target is a target as the command line spells it, parted the way pacman's
66// process_target parts one: 'repo/name' names the db to look in, and a bare
@@ -40,7 +40,7 @@ fn local_target_name(target string) string {
4040// one its prefix names. the prefix is a scope, not decoration: a name the
4141// config does not carry is pacman's 'database not found', never a search of
4242// everything with the prefix dropped
43-fn scope_dbs(dbs []&alpm.DB, repo string) ![]&alpm.DB {
43+fn scope_dbs(dbs []&nspkg.DB, repo string) ![]&nspkg.DB {
4444 if repo == '' {
4545 return dbs
4646 }
@@ -62,7 +62,7 @@ fn has_constraint(name string) bool {
6262// may be something a package provides too, which the modes that only read
6363// take and the ones that write do not: 'vpac r sh' must not come to mean
6464// bash
65-fn find_local_target(pkgcache &alpm.List, name string, providers bool) ?&alpm.Package {
65+fn find_local_target(pkgcache &nspkg.List, name string, providers bool) ?&nspkg.Package {
6666 if p := pkgcache.pkg_find(name) {
6767 return p
6868 }
@@ -79,14 +79,14 @@ fn find_local_target(pkgcache &alpm.List, name string, providers bool) ?&alpm.Pa
7979// packages and several providers. named says the db was named with the
8080// target, which makes it one to install from for this lookup whatever its
8181// usage, as in pacman
82-fn find_sync_target(handle &alpm.Handle, dbs []&alpm.DB, name string, named bool) ?&alpm.Package {
82+fn find_sync_target(handle &nspkg.Handle, dbs []&nspkg.DB, name string, named bool) ?&nspkg.Package {
8383 if name == '' {
8484 return none
8585 }
8686 if p := find_repo_pkg(dbs, name) {
8787 return p
8888 }
89- mut list := unsafe { &alpm.List(nil) }
89+ mut list := unsafe { &nspkg.List(nil) }
9090 for db in dbs {
9191 list = list.add(db)
9292 }
@@ -94,7 +94,7 @@ fn find_sync_target(handle &alpm.Handle, dbs []&alpm.DB, name string, named bool
9494 if !named {
9595 return handle.find_dbs_satisfier(list, name)
9696 }
97- mut restore := map[int]alpm.DBUsage{}
97+ mut restore := map[int]nspkg.DBUsage{}
9898 for i, db in dbs {
9999 usage := db.get_usage() or { continue }
100100 if !usage.has(.install) {
@@ -114,13 +114,13 @@ fn find_sync_target(handle &alpm.Handle, dbs []&alpm.DB, name string, named bool
114114// GroupMember is one package of a sync group, with the db that carries it
115115struct GroupMember {
116116 repo string
117- pkg &alpm.Package
117+ pkg &nspkg.Package
118118}
119119
120120// sync_group_members are the packages of a group across the dbs, in db
121121// order; a name a later db repeats is the earlier db's, as libalpm's
122122// 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) {
123+fn sync_group_members(dbs []&nspkg.DB, name string) (bool, []GroupMember) {
124124 mut found := false
125125 mut out := []GroupMember{}
126126 mut seen := map[string]bool{}
@@ -1,7 +1,7 @@
11@[has_globals]
22module main
33
4-import alpm
4+import nspkg
55import os
66import sync.stdatomic
77import v.profiler
@@ -17,7 +17,7 @@ const txn_locked = i64(1)
1717const txn_unlocked = i64(2)
1818
1919// interrupt_handle is the handle a transaction runs on, published for the
20-// signal handler (as its address) from before alpm takes the db lock
20+// signal handler (as its address) from before nspkg takes the db lock
2121// until after it let go of it. the handler calls its async unlock, which
2222// removes the lock only while this handle holds it (its lockfd), as pacman's
2323// soft_interrupt_handler does: there is no moment where the lock is taken
@@ -43,14 +43,14 @@ fn split_list(values []string) []string {
4343// dep_check_flag is pacman's -d: once (or --nodeps) skips the version checks
4444// of the dependencies, twice (-dd, or --nodeps with -d) skips the
4545// dependency checks altogether
46-fn dep_check_flag(nodeps bool, level int) alpm.TransFlag {
46+fn dep_check_flag(nodeps bool, level int) nspkg.TransFlag {
4747 n := level + if nodeps { 1 } else { 0 }
4848 return if n >= 2 {
49- alpm.TransFlag.no_deps
49+ nspkg.TransFlag.no_deps
5050 } else if n == 1 {
51- alpm.TransFlag.no_depversion
51+ nspkg.TransFlag.no_depversion
5252 } else {
53- alpm.trans_flag_0
53+ nspkg.trans_flag_0
5454 }
5555}
5656
@@ -64,7 +64,7 @@ struct TransOptions {
6464 assume_installed []string
6565}
6666
67-fn (o TransOptions) apply(handle &alpm.Handle) ! {
67+fn (o TransOptions) apply(handle &nspkg.Handle) ! {
6868 for glob in split_list(o.overwrite) {
6969 handle.option_add_overwrite_file(glob)!
7070 }
@@ -77,7 +77,7 @@ fn (o TransOptions) apply(handle &alpm.Handle) ! {
7777 for spec in split_list(o.assume_installed) {
7878 // libalpm parses any text into a dependency, '=1' into one with no
7979 // name, which would assume nothing: a spec names its package
80- dep := alpm.dep_from_string(spec)
80+ dep := nspkg.dep_from_string(spec)
8181 if dep == unsafe { nil } || dep.get_name() == '' {
8282 if dep != unsafe { nil } {
8383 dep.free()
@@ -95,7 +95,7 @@ fn (o TransOptions) apply(handle &alpm.Handle) ! {
9595
9696// trans_begin initializes a transaction. pair it with
9797// `defer { trans_cleanup(handle) }` so every exit path releases it
98-fn trans_begin(handle &alpm.Handle, flags alpm.TransFlag) ! {
98+fn trans_begin(handle &nspkg.Handle, flags nspkg.TransFlag) ! {
9999 // published first: trans_init takes the lock, and a signal right after
100100 // it must find the handle that holds it
101101 publish_for_interrupt(handle)
@@ -108,7 +108,7 @@ fn trans_begin(handle &alpm.Handle, flags alpm.TransFlag) ! {
108108}
109109
110110// publish_for_interrupt makes handle the one the signal handler unlocks
111-fn publish_for_interrupt(handle &alpm.Handle) {
111+fn publish_for_interrupt(handle &nspkg.Handle) {
112112 mut published := interrupt_handle
113113 published.store(u64(voidptr(handle)))
114114}
@@ -124,11 +124,11 @@ fn withdraw_from_interrupt() {
124124// pacman's --print does: no db lock, so it needs no root and never waits on
125125// a running transaction, and no conflict checks, so a preview lists the
126126// packages even when a conflict question would come up
127-fn print_flags(print_only bool) alpm.TransFlag {
127+fn print_flags(print_only bool) nspkg.TransFlag {
128128 return if print_only {
129- alpm.TransFlag.nolock | .no_conflicts
129+ nspkg.TransFlag.nolock | .no_conflicts
130130 } else {
131- alpm.trans_flag_0
131+ nspkg.trans_flag_0
132132 }
133133}
134134
@@ -137,7 +137,7 @@ fn print_flags(print_only bool) alpm.TransFlag {
137137// a release that does not go through is said (the lock and the transaction
138138// state would hang behind it); it still counts as closed, or the defers of
139139// a rollback would try again
140-fn trans_cleanup(handle &alpm.Handle) {
140+fn trans_cleanup(handle &nspkg.Handle) {
141141 mut open := txn_open
142142 if open.load() != 0 {
143143 handle.trans_release() or {
@@ -152,7 +152,7 @@ fn trans_cleanup(handle &alpm.Handle) {
152152// its problems are, as pacman's sync_prepare_execute tells them apart: a
153153// missing or broken dependency, a conflict between two packages, a package
154154// of the wrong architecture, and anything else under libalpm's own text
155-fn prepare_problem_lines(kind alpm.Errno, problems []alpm.DepProblem) []string {
155+fn prepare_problem_lines(kind nspkg.Errno, problems []nspkg.DepProblem) []string {
156156 mut lines := []string{}
157157 match kind {
158158 .unsatisfied_deps {
@@ -195,21 +195,21 @@ fn prepare_problem_lines(kind alpm.Errno, problems []alpm.DepProblem) []string {
195195
196196// trans_prepare_checked prepares a transaction. when packages would break it,
197197// the error lists each problem the way pacman does
198-fn trans_prepare_checked(handle &alpm.Handle) ! {
198+fn trans_prepare_checked(handle &nspkg.Handle) ! {
199199 problems, failure := handle.trans_prepare_problems()
200200 if err := failure {
201201 if problems.len == 0 {
202202 return err
203203 }
204204 // copying conflict package names can reset the handle's mutable errno.
205- kind := unsafe { alpm.Errno(err.code()) }
205+ kind := unsafe { nspkg.Errno(err.code()) }
206206 return error_with_code(prepare_problem_lines(kind, problems).join('\n'), err.code())
207207 }
208208}
209209
210210// runs the commit phase of a prepared transaction. the transaction must
211211// already have been begun and prepared.
212-fn trans_commit(handle &alpm.Handle) ! {
212+fn trans_commit(handle &nspkg.Handle) ! {
213213 handle.trans_commit()!
214214 trans_cleanup(handle)
215215}
@@ -224,7 +224,7 @@ fn on_interrupt(sig os.Signal) {
224224 mut published := interrupt_handle
225225 h := published.load()
226226 if h != 0 {
227- handle := unsafe { &alpm.Handle(voidptr(h)) }
227+ handle := unsafe { &nspkg.Handle(voidptr(h)) }
228228 handle.unlock_async()
229229 }
230230 C._exit(128 + int(sig))
@@ -248,7 +248,7 @@ enum TransAction {
248248
249249// trans_listing collects what a prepared transaction does: every package,
250250// with the installed version an install or upgrade replaces, and the sizes
251-fn trans_listing(handle &alpm.Handle, pkgs []&alpm.Package, action TransAction) TransactionEvent {
251+fn trans_listing(handle &nspkg.Handle, pkgs []&nspkg.Package, action TransAction) TransactionEvent {
252252 mut out := []TransPkg{}
253253 mut download := i64(0)
254254 mut install_size := i64(0)
@@ -314,7 +314,7 @@ fn print_trans_listing(t TransactionEvent) {
314314// trans_confirm lists a prepared transaction and asks 'proceed? [Y/n]',
315315// where enter is yes, as pacman's 'Proceed with installation?'. a frontend
316316// gets the listing as a transaction event before the question
317-fn trans_confirm(mut ui TransUI, handle &alpm.Handle, pkgs []&alpm.Package, action TransAction) bool {
317+fn trans_confirm(mut ui TransUI, handle &nspkg.Handle, pkgs []&nspkg.Package, action TransAction) bool {
318318 ui.pause()
319319 listing := trans_listing(handle, pkgs, action)
320320 if ipc_on() {
@@ -1,6 +1,6 @@
11module main
22
3-import alpm
3+import nspkg
44import json2
55import os
66
@@ -16,23 +16,23 @@ fn test_split_list() {
1616fn test_dep_check_flag() {
1717 // pacman's -d skips the version checks, -dd every dependency check;
1818 // --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
19+ assert dep_check_flag(false, 0) == nspkg.trans_flag_0
20+ assert dep_check_flag(true, 0) == nspkg.TransFlag.no_depversion
21+ assert dep_check_flag(false, 1) == nspkg.TransFlag.no_depversion
22+ assert dep_check_flag(false, 2) == nspkg.TransFlag.no_deps
23+ assert dep_check_flag(true, 1) == nspkg.TransFlag.no_deps
24+ assert dep_check_flag(false, 3) == nspkg.TransFlag.no_deps
2525}
2626
2727// trans_sandbox opens a handle on an empty temp db, and points the ipc
2828// channel at a file, so what the lifecycle says can be read back
29-fn trans_sandbox(name string) !(string, &alpm.Handle) {
29+fn trans_sandbox(name string) !(string, &nspkg.Handle) {
3030 tmp := os.join_path(os.vtmp_dir(), 'vpac_test_trans_${name}_${os.getpid()}')
3131 os.rmdir_all(tmp) or {}
3232 os.mkdir_all(os.join_path(tmp, 'root'))!
3333 os.mkdir_all(os.join_path(tmp, 'db', 'local'))!
3434 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') + '/')!
35+ handle := nspkg.initialize(os.join_path(tmp, 'root') + '/', os.join_path(tmp, 'db') + '/')!
3636 return tmp, handle
3737}
3838
@@ -58,7 +58,7 @@ fn test_trans_cleanup_releases_once() ! {
5858 defer { os.rmdir_all(tmp) or {} }
5959 defer { handle.release() or {} }
6060 lpath := os.join_path(tmp, 'db', 'db.lck')
61- trans_begin(handle, alpm.trans_flag_0)!
61+ trans_begin(handle, nspkg.trans_flag_0)!
6262 assert os.exists(lpath)
6363 msgs := said(tmp, fn [handle] () {
6464 trans_cleanup(handle)
@@ -102,7 +102,7 @@ fn test_trans_commit_releases() ! {
102102 os.mkdir_all(entry)!
103103 os.write_file(os.join_path(entry, 'desc'), '%NAME%\ngone\n\n%VERSION%\n1.0-1\n\n')!
104104 os.write_file(os.join_path(entry, 'files'), '%FILES%\n\n')!
105- trans_begin(handle, alpm.trans_flag_0)!
105+ trans_begin(handle, nspkg.trans_flag_0)!
106106 handle.remove_pkg(handle.find_local_pkg('gone') or { return error('gone is not installed') })!
107107 trans_prepare_checked(handle)!
108108 trans_commit(handle)!
@@ -164,7 +164,7 @@ fn test_trans_options_of_install_and_upgrade() ! {
164164// copy of the test's memory, and only ever leaves through _exit (the
165165// handler's, or the 98 and 99 of a failure), so no defer, no atexit and no
166166// 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 {
167+fn killed_child(handle &nspkg.Handle, take fn (&nspkg.Handle)) int {
168168 pid := C.fork()
169169 if pid == 0 {
170170 install_interrupt_handlers()
@@ -184,8 +184,8 @@ fn test_interrupt_lets_go_of_the_lock() ! {
184184 defer { handle.release() or {} }
185185 lpath := os.join_path(tmp, 'db', 'db.lck')
186186 // 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) }
187+ status := killed_child(handle, fn (h &nspkg.Handle) {
188+ trans_begin(h, nspkg.trans_flag_0) or { C._exit(98) }
189189 })
190190 assert status == 128 + 15
191191 assert !os.exists(lpath)
@@ -198,9 +198,9 @@ fn test_interrupt_right_after_the_lock_is_taken() ! {
198198 lpath := os.join_path(tmp, 'db', 'db.lck')
199199 // the signal lands between libalpm taking the lock and vpac recording
200200 // the transaction: the handle was published before, so the lock goes
201- status := killed_child(handle, fn (h &alpm.Handle) {
201+ status := killed_child(handle, fn (h &nspkg.Handle) {
202202 publish_for_interrupt(h)
203- h.trans_init(alpm.trans_flag_0) or { C._exit(98) }
203+ h.trans_init(nspkg.trans_flag_0) or { C._exit(98) }
204204 })
205205 assert status == 128 + 15
206206 assert !os.exists(lpath)
@@ -214,7 +214,7 @@ fn test_interrupt_leaves_a_lock_it_does_not_hold() ! {
214214 // another process holds the lock, and this run only previews (--print
215215 // takes none): the killed run leaves the other's lock alone
216216 os.write_file(lpath, '')!
217- status := killed_child(handle, fn (h &alpm.Handle) {
217+ status := killed_child(handle, fn (h &nspkg.Handle) {
218218 trans_begin(h, print_flags(true)) or { C._exit(98) }
219219 })
220220 assert status == 128 + 15
@@ -227,14 +227,14 @@ fn test_trans_publishes_its_handle_while_open() ! {
227227 defer { handle.release() or {} }
228228 mut published := interrupt_handle
229229 assert published.load() == 0
230- trans_begin(handle, alpm.trans_flag_0)!
230+ trans_begin(handle, nspkg.trans_flag_0)!
231231 assert published.load() == u64(voidptr(handle))
232232 trans_cleanup(handle)
233233 assert published.load() == 0
234234 // a begin that fails publishes nothing past its failure: the lock is
235235 // someone else's here
236236 os.write_file(os.join_path(tmp, 'db', 'db.lck'), '')!
237- if _ := trans_begin(handle, alpm.trans_flag_0) {
237+ if _ := trans_begin(handle, nspkg.trans_flag_0) {
238238 assert false, 'a held lock was taken'
239239 }
240240 assert published.load() == 0
@@ -244,12 +244,12 @@ fn test_trans_publishes_its_handle_while_open() ! {
244244// libalpm's own text for the rest
245245fn test_prepare_problem_lines() {
246246 dep := prepare_problem_lines(.unsatisfied_deps, [
247- alpm.DepProblem{
247+ nspkg.DepProblem{
248248 target: 'user'
249249 depend: 'lib<2.0'
250250 causing: 'lib'
251251 },
252- alpm.DepProblem{
252+ nspkg.DepProblem{
253253 target: 'app'
254254 depend: 'gone'
255255 },
@@ -258,12 +258,12 @@ fn test_prepare_problem_lines() {
258258 " lib breaks dependency 'lib<2.0' required by user",
259259 " unable to satisfy dependency 'gone' required by app"]
260260 conflict := prepare_problem_lines(.conflicting_deps, [
261- alpm.DepProblem{
261+ nspkg.DepProblem{
262262 target: 'p1'
263263 depend: 'p2'
264264 causing: 'p2'
265265 },
266- alpm.DepProblem{
266+ nspkg.DepProblem{
267267 target: 'p1'
268268 depend: 'virt<2'
269269 causing: 'p3'
@@ -271,12 +271,12 @@ fn test_prepare_problem_lines() {
271271 ])
272272 assert conflict == ['unresolvable package conflicts:', ' p1 and p2 are in conflict',
273273 ' p1 and p3 are in conflict (virt<2)']
274- wrong_arch := prepare_problem_lines(.pkg_invalid_arch, [alpm.DepProblem{
274+ wrong_arch := prepare_problem_lines(.pkg_invalid_arch, [nspkg.DepProblem{
275275 target: 'foo-1.0-1-riscv64'
276276 }])
277277 assert wrong_arch.len == 2
278278 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{
279+ other := prepare_problem_lines(.trans_dup_target, [nspkg.DepProblem{
280280 target: 'foo'
281281 }])
282282 assert other.len == 2 && other[1] == ' foo'
@@ -1,14 +1,14 @@
11@[has_globals]
22module main
33
4-import alpm
4+import nspkg
55import sync
66import time
77import x.progress
88
99// ALPM_LOG_ERROR: the one level the log callback tells apart, the other one
1010// it passes being a warning
11-const alpm_log_error = 1
11+const nspkg_log_error = 1
1212
1313// ProgressCfg is how the live display draws, the config's (progress ...) and
1414// (spinner ...) forms. style is the bar graphic, 'classic' or 'block', and
@@ -33,7 +33,7 @@ mut:
3333
3434__global cfg_progress = ProgressCfg{}
3535
36-// spinner_sets are the frame sets (spinner :frames) knows by name
36+// spinner_sets are the frame sets (spinner #:frames) knows by name
3737const spinner_sets = ['dots', 'braille', 'line', 'arrows', 'circle', 'quarters', 'grow', 'bounce',
3838 'pulse', 'ellipsis', 'earth', 'moon']
3939
@@ -118,9 +118,9 @@ fn spinner_opts(o progress.SpinnerOptions) progress.SpinnerOptions {
118118
119119// TransUI is a command's user interface: the shared progress display (one
120120// MultiBar that holds spinners for the command phases, download bars fed by
121-// alpm's dlcb and transaction phase bars fed by alpm's progresscb) and the
121+// nspkg's dlcb and transaction phase bars fed by nspkg's progresscb) and the
122122// prompter every question goes through, libalpm's own included. It is passed
123-// to alpm as the callback context. under --ui ipc there is no MultiBar: the
123+// to nspkg as the callback context. under --ui ipc there is no MultiBar: the
124124// same calls send events (Phase, Meter, the callbacks)
125125// every ui-bearing function spells its ui `mut ui TransUI`, the way it does
126126// for the _locked helpers: TransUI is @[heap], and a mut value parameter of
@@ -131,12 +131,8 @@ fn spinner_opts(o progress.SpinnerOptions) progress.SpinnerOptions {
131131struct TransUI {
132132mut:
133133 mb &progress.MultiBar = unsafe { nil }
134- // mu guards the fields below against libalpm's download callbacks: with
135- // parallel downloads on, dlcb arrives on several threads at once, and
136- // progresscb may join it. every method here takes mu before it touches
137- // state other callbacks or threads can see, and the _locked helpers
138- // below it are reached only with the mutex held. the bars and the
139- // multibar are drawn thread-safely by x.progress itself
134+ // nspkg delivers download events on the calling thread. mu guards the
135+ // display state shared with the UI; _locked helpers run with it held.
140136 mu &sync.Mutex = sync.new_mutex()
141137 dbars map[string]&progress.Bar
142138 pbar &progress.Bar = unsafe { nil }
@@ -194,7 +190,7 @@ fn new_trans_ui(o TransUIOptions) &TransUI {
194190}
195191
196192// group returns the live MultiBar, starting a new one if the previous one was
197-// paused for a prompt. the alpm callbacks reach the display through this
193+// paused for a prompt. the nspkg callbacks reach the display through this
198194// struct, so they always draw on the current MultiBar
199195fn (mut ui TransUI) group() &progress.MultiBar {
200196 ui.mu.lock()
@@ -438,7 +434,7 @@ fn (mut ui TransUI) warn(text string) {
438434
439435// show_packages lists packages under a heading, the way a transaction shows
440436// the ones it removes or skips: name and version
441-fn (mut ui TransUI) show_packages(title string, pkgs []&alpm.Package) {
437+fn (mut ui TransUI) show_packages(title string, pkgs []&nspkg.Package) {
442438 if ipc_on() {
443439 emit(PackagesEvent{
444440 title: title.trim_right(':')
@@ -480,8 +476,6 @@ fn (mut ui TransUI) download_text_locked(name string) string {
480476
481477// download_bar returns the display bar of one download, created on the file's
482478// first event, when its size is known; the shown group starts with it
483-// libalpm runs its dlcb on the parallel download threads, so the shared
484-// state is reached with the ui's mutex, and never the drawing itself
485479fn (mut ui TransUI) download_bar(name string, total i64, on_end string, show_rate bool) &progress.Bar {
486480 ui.mu.lock()
487481 defer { ui.mu.unlock() }
@@ -500,7 +494,7 @@ fn (mut ui TransUI) download_bar(name string, total i64, on_end string, show_rat
500494 return bar
501495}
502496
503-fn cb_download(ctx voidptr, filename &u8, event alpm.DownloadEventType, data voidptr) {
497+fn cb_download(ctx voidptr, filename &u8, event nspkg.DownloadEventType, data voidptr) {
504498 mut ui := &TransUI(ctx)
505499 name := safe_vstring(filename)
506500 if ipc_on() {
@@ -513,10 +507,7 @@ fn cb_download(ctx voidptr, filename &u8, event alpm.DownloadEventType, data voi
513507 // download size is known
514508 }
515509 .progress {
516- p := unsafe { &alpm.DownloadEventProgress(data) }
517- // libalpm runs this callback on its parallel download threads:
518- // the shared display state is reached through the ui's mutex, the
519- // drawing itself is x.progress's to keep thread-safe
510+ p := unsafe { &nspkg.DownloadEventProgress(data) }
520511 bar := ui.download_bar(name, p.total, '', true)
521512 bar.set(p.downloaded)
522513 }
@@ -524,13 +515,13 @@ fn cb_download(ctx voidptr, filename &u8, event alpm.DownloadEventType, data voi
524515 // libalpm moves on to the next mirror: a download that starts over
525516 // starts its bar over, as pacman's dload_retry_event does, and one
526517 // that resumes keeps its place
527- r := unsafe { &alpm.DownloadEventRetry(data) }
518+ r := unsafe { &nspkg.DownloadEventRetry(data) }
528519 if r.resume == 0 {
529520 ui.restart_download_bar(name)
530521 }
531522 }
532523 .completed {
533- c := unsafe { &alpm.DownloadEventCompleted(data) }
524+ c := unsafe { &nspkg.DownloadEventCompleted(data) }
534525 // libalpm's result: 1 means the local copy met the time condition
535526 // and nothing was fetched, 0 a finished download, -1 an error. a
536527 // download can finish before its first progress event, so the bar
@@ -562,7 +553,7 @@ fn (mut ui TransUI) download_ended(name string, failed bool) {
562553 ui.dfails.delete(name)
563554 ui.mu.unlock()
564555 if held != '' && failed {
565- ui.alpm_said(true, held)
556+ ui.nspkg_said(true, held)
566557 }
567558}
568559
@@ -586,14 +577,11 @@ fn download_due(last ?DownloadSent, percent int, now i64) bool {
586577}
587578
588579// ipc_download reports a download as events: as its percent moves or a beat
589-// passes, once more when libalpm retries it from the next mirror, and once
590-// when it is done. the dlcb arrives on libalpm's parallel download threads,
591-// so the dedupe table is reached with the ui's mutex, and the event goes out
592-// once the lock is gone
593-fn ipc_download(mut ui TransUI, name string, event alpm.DownloadEventType, data voidptr) {
580+// passes, when nspkg retries on the next mirror, and when the download ends
581+fn ipc_download(mut ui TransUI, name string, event nspkg.DownloadEventType, data voidptr) {
594582 match event {
595583 .progress {
596- p := unsafe { &alpm.DownloadEventProgress(data) }
584+ p := unsafe { &nspkg.DownloadEventProgress(data) }
597585 pct := if p.total > 0 { int(p.downloaded * 100 / p.total) } else { 0 }
598586 now := time.sys_mono_now()
599587 ui.mu.lock()
@@ -613,7 +601,7 @@ fn ipc_download(mut ui TransUI, name string, event alpm.DownloadEventType, data
613601 })
614602 }
615603 .retry {
616- r := unsafe { &alpm.DownloadEventRetry(data) }
604+ r := unsafe { &nspkg.DownloadEventRetry(data) }
617605 // what was reported is history: the next progress goes out
618606 ui.mu.lock()
619607 ui.dlast.delete(name)
@@ -625,7 +613,7 @@ fn ipc_download(mut ui TransUI, name string, event alpm.DownloadEventType, data
625613 })
626614 }
627615 .completed {
628- c := unsafe { &alpm.DownloadEventCompleted(data) }
616+ c := unsafe { &nspkg.DownloadEventCompleted(data) }
629617 // the error goes out before the completed event, the order a
630618 // frontend reads a failure in
631619 ui.download_ended(name, c.result == -1)
@@ -641,7 +629,7 @@ fn ipc_download(mut ui TransUI, name string, event alpm.DownloadEventType, data
641629 }
642630}
643631
644-fn progress_verb(kind alpm.Progress) string {
632+fn progress_verb(kind nspkg.Progress) string {
645633 return match kind {
646634 .add_start { 'installing' }
647635 .upgrade_start { 'upgrading' }
@@ -656,7 +644,7 @@ fn progress_verb(kind alpm.Progress) string {
656644 }
657645}
658646
659-fn cb_progress(ctx voidptr, kind alpm.Progress, pkgname &u8, percent i32, howmany uint, current uint) {
647+fn cb_progress(ctx voidptr, kind nspkg.Progress, pkgname &u8, percent i32, howmany uint, current uint) {
660648 mut ui := &TransUI(ctx)
661649 verb := progress_verb(kind)
662650 name := safe_vstring(pkgname)
@@ -725,7 +713,7 @@ fn cb_progress(ctx voidptr, kind alpm.Progress, pkgname &u8, percent i32, howman
725713// paused first so it cannot draw over the listings, and every question goes
726714// through the ui's prompter, whose --noconfirm prints each one and takes its
727715// default. all of it follows pacman's cb_question in src/pacman/callback.c
728-fn cb_question(ctx voidptr, q &alpm.Question) {
716+fn cb_question(ctx voidptr, q &nspkg.Question) {
729717 mut ui := &TransUI(ctx)
730718 kind := unsafe { q.type_ }
731719 // --print lists the transaction and asks nothing: an ignored package and
@@ -799,14 +787,14 @@ fn cb_question(ctx voidptr, q &alpm.Question) {
799787}
800788
801789// provider_choice is a provider as a frontend's choice: repo/name version
802-fn provider_choice(pkg &alpm.Package) string {
790+fn provider_choice(pkg &nspkg.Package) string {
803791 repo := if db := pkg.get_db() { db.get_name() + '/' } else { '' }
804792 return '${repo}${pkg.get_name()} ${pkg.get_version()}'
805793}
806794
807795// provider_rows are the providers numbered for the terminal's listing, the
808796// number the choose question asks for
809-fn provider_rows(providers []&alpm.Package) []Row {
797+fn provider_rows(providers []&nspkg.Package) []Row {
810798 mut rows := []Row{}
811799 for i, pkg in providers {
812800 styled := if db := pkg.get_db() { source_style(db.get_name()) + '/' } else { '' }
@@ -815,16 +803,16 @@ fn provider_rows(providers []&alpm.Package) []Row {
815803 return rows
816804}
817805
818-fn cb_log_line(ctx voidptr, level alpm.LogLevel, text &u8) {
806+fn cb_log_line(ctx voidptr, level nspkg.LogLevel, text &u8) {
819807 if !level.has(.error) && !level.has(.warning) { return }
820- alpm_log_line(ctx, int(level), unsafe { &char(text) })
808+ nspkg_log_line(ctx, int(level), unsafe { &char(text) })
821809}
822810
823-// alpm formats each error and warning, and it is said to the user as
811+// nspkg formats each error and warning, and it is said to the user as
824812// pacman's cb_log says it. vpac's own dependency walks (ui.walking) look
825813// things up the transaction's prepare looks up again; what they would say
826814// is said then, once
827-fn alpm_log_line(ctx voidptr, level int, text &char) {
815+fn nspkg_log_line(ctx voidptr, level int, text &char) {
828816 if ctx == unsafe { nil } || text == unsafe { nil } {
829817 return
830818 }
@@ -840,20 +828,20 @@ fn alpm_log_line(ctx voidptr, level int, text &char) {
840828 // knows a later mirror serves the file: without --verbose it is held
841829 // until the download ends, and said as an error only when no mirror
842830 // served it (download_ended)
843- if level == alpm_log_error && msg.starts_with("failed retrieving file '") && !verbose_on() {
831+ if level == nspkg_log_error && msg.starts_with("failed retrieving file '") && !verbose_on() {
844832 file := msg.all_after("failed retrieving file '").all_before("'")
845833 ui.mu.lock()
846834 ui.dfails[file] = msg
847835 ui.mu.unlock()
848836 return
849837 }
850- ui.alpm_said(level == alpm_log_error, msg)
838+ ui.nspkg_said(level == nspkg_log_error, msg)
851839}
852840
853-// alpm_said is a line libalpm logged: printed above any live bars (which
841+// nspkg_said is a line libalpm logged: printed above any live bars (which
854842// hold it while they draw, as pacman buffers during progress), or a message
855843// event a frontend reads as a warning, an error flagged as one
856-fn (mut ui TransUI) alpm_said(is_error bool, text string) {
844+fn (mut ui TransUI) nspkg_said(is_error bool, text string) {
857845 if ipc_on() {
858846 emit(MessageEvent{
859847 text: text
@@ -875,9 +863,9 @@ fn (mut ui TransUI) alpm_said(is_error bool, text string) {
875863// set_answer writes a question's answer. every question struct keeps its
876864// answer right after the type, which is what libalpm's alpm_question_any_t
877865// exposes
878-fn set_answer(q &alpm.Question, answer i32) {
866+fn set_answer(q &nspkg.Question, answer i32) {
879867 unsafe {
880- mut any := &alpm.QuestionAny(q)
868+ mut any := &nspkg.QuestionAny(q)
881869 any.answer = answer
882870 }
883871}
@@ -886,11 +874,11 @@ fn flag_answer(yes bool) i32 {
886874 return if yes { 1 } else { 0 }
887875}
888876
889-// init_handle initializes alpm and attaches the progress display callbacks
877+// init_handle initializes nspkg and attaches the progress display callbacks
890878// and the configured parallel download count
891-fn init_handle(ui &TransUI) !&alpm.Handle {
892- handle := alpm.initialize(root_path, db_path) or {
893- return error_with_code('failed to initialize alpm: ${err.msg()}', err.code())
879+fn init_handle(ui &TransUI) !&nspkg.Handle {
880+ handle := nspkg.initialize(root_path, db_path) or {
881+ return error_with_code('failed to initialize nspkg: ${err.msg()}', err.code())
894882 }
895883 handle.option_set_dlcb(cb_download, voidptr(ui))!
896884 handle.option_set_progresscb(cb_progress, voidptr(ui))!
@@ -956,9 +944,7 @@ fn init_handle(ui &TransUI) !&alpm.Handle {
956944 return error('problem setting the download user "${download_user}" (user does not exist)')
957945 }
958946 }
959- // pacman's DisableSandboxFilesystem and DisableSandboxSyscalls: the
960- // downloader and the extraction run without either part of libalpm's
961- // sandbox. the installed libalpm has these two, not a whole-sandbox switch
947+ // vpac maps its download sandbox switch to both nspkg restrictions.
962948 if cfg_disable_sandbox {
963949 handle.option_set_disable_sandbox_filesystem(1)!
964950 handle.option_set_disable_sandbox_syscalls(1)!
@@ -1,6 +1,6 @@
11module main
22
3-import alpm
3+import nspkg
44import json2
55import os
66
@@ -23,19 +23,19 @@ fn test_download_retry_through_the_callback() {
2323 // one that resumes leaves it where it was
2424 mut ui := new_trans_ui()
2525 defer { ui.stop() }
26- mut p := alpm.DownloadEventProgress{
26+ mut p := nspkg.DownloadEventProgress{
2727 downloaded: 40
2828 total: 100
2929 }
3030 cb_download(voidptr(ui), c'a.pkg', .progress, voidptr(&p))
3131 mut bar := ui.dbars['a.pkg'] or { panic('no bar for a.pkg') }
3232 assert bar.value() == 40
33- mut resume := alpm.DownloadEventRetry{
33+ mut resume := nspkg.DownloadEventRetry{
3434 resume: 1
3535 }
3636 cb_download(voidptr(ui), c'a.pkg', .retry, voidptr(&resume))
3737 assert bar.value() == 40
38- mut over := alpm.DownloadEventRetry{
38+ mut over := nspkg.DownloadEventRetry{
3939 resume: 0
4040 }
4141 cb_download(voidptr(ui), c'a.pkg', .retry, voidptr(&over))
@@ -92,7 +92,7 @@ fn test_phase_finishes_once_under_a_frontend() ! {
9292 assert states == ['start', 'done']
9393}
9494
95-fn test_alpm_log_line() ! {
95+fn test_nspkg_log_line() ! {
9696 path := os.join_path(os.vtmp_dir(), 'vpac_test_alpmlog_${os.getpid()}')
9797 mut f := os.create(path)!
9898 defer { os.rm(path) or {} }
@@ -102,14 +102,14 @@ fn test_alpm_log_line() ! {
102102 // vpac's own walk looks up what the prepare looks up again: said once,
103103 // then, not during the walk
104104 ui.walking = true
105- alpm_log_line(voidptr(ui), 2, c'during the walk\n')
105+ nspkg_log_line(voidptr(ui), 2, c'during the walk\n')
106106 ui.walking = false
107107 // 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')
108+ nspkg_log_line(voidptr(ui), 2, c'a warning\n')
109+ nspkg_log_line(voidptr(ui), nspkg_log_error, c'an error\n')
110110 // 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')
111+ nspkg_log_line(voidptr(ui), 2, c' \n')
112+ nspkg_log_line(unsafe { nil }, 2, c'no ui')
113113 ui_kind, ipc_fd = saved_kind, saved_fd
114114 f.close()
115115 events := os.read_lines(path)!.map(json2.decode[json2.Any](it)!.as_map())
@@ -1,4 +1,4 @@
1-import alpm
1+import nspkg
22
33fn upgrade(config ConfigUpgrade) ! {
44 // a build installs what it makes: download-only has nothing a pkgbuild
@@ -23,7 +23,7 @@ fn upgrade(config ConfigUpgrade) ! {
2323 cfg_disable_timeout = true
2424 }
2525 mut handle := init_handle(ui)!
26- defer { handle.release() or { went_on('release the alpm handle', err) } }
26+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
2727 defer { ui.stop() }
2828 defer { trans_cleanup(handle) }
2929 trans_options(config).apply(handle)!
@@ -141,13 +141,13 @@ fn upgrade(config ConfigUpgrade) ! {
141141// foreign_pkgs lists the locally installed packages the sync dbs do not
142142// carry, the held and ignored ones left out: the sync upgrade just did its
143143// part around them, and the pkgbuild repos are what could have the rest
144-fn foreign_pkgs(handle &alpm.Handle) ![]&alpm.Package {
144+fn foreign_pkgs(handle &nspkg.Handle) ![]&nspkg.Package {
145145 sync := handle.get_syncdbs()!
146146 dbs := sync.dbs()
147147 localdb := handle.get_localdb() or {
148148 return error('could not open the local database: ${err.msg()}')
149149 }
150- mut out := []&alpm.Package{}
150+ mut out := []&nspkg.Package{}
151151 cache := pkgcache_of(handle, localdb)!
152152 for pkg in cache.pkgs() {
153153 if find_repo_pkg(dbs, pkg.get_name()) == none && handle.pkg_should_ignore(pkg) == 0 {
@@ -169,11 +169,11 @@ struct PkgbuildUpgrade {
169169// foreign_upgrades keeps the foreign packages a record would upgrade: the
170170// record's version must come after the installed one — never a downgrade.
171171// it answers the records, each with the version it would upgrade from
172-fn foreign_upgrades(foreign []&alpm.Package, found map[string]PackagePkgbuild) []PkgbuildUpgrade {
172+fn foreign_upgrades(foreign []&nspkg.Package, found map[string]PackagePkgbuild) []PkgbuildUpgrade {
173173 mut out := []PkgbuildUpgrade{}
174174 for pkg in foreign {
175175 rec := found[pkg.get_name()] or { continue }
176- if alpm.pkg_vercmp(pkg.get_version(), rec.version) >= 0 {
176+ if nspkg.pkg_vercmp(pkg.get_version(), rec.version) >= 0 {
177177 continue
178178 }
179179 out << PkgbuildUpgrade{
@@ -188,7 +188,7 @@ fn foreign_upgrades(foreign []&alpm.Package, found map[string]PackagePkgbuild) [
188188// names, batched per repo in the config's order — the first repo that holds
189189// a name is the one it would build from, as pkgbuild_lookup tries them one
190190// name at a time — and keeps the records that would upgrade
191-fn pkgbuild_upgrade_candidates(mut ui TransUI, repos []CfgRepo, foreign []&alpm.Package) ![]PkgbuildUpgrade {
191+fn pkgbuild_upgrade_candidates(mut ui TransUI, repos []CfgRepo, foreign []&nspkg.Package) ![]PkgbuildUpgrade {
192192 mut left := foreign.map(it.get_name())
193193 mut found := map[string]PackagePkgbuild{}
194194 mut repo_of := map[string]string{}
@@ -246,7 +246,7 @@ fn upgrade_pkgbuild_config(config ConfigUpgrade) ConfigInstall {
246246// build — and builds and installs the accepted ones. a declined package
247247// stops the pass, as a declined build stops an install. it answers the names
248248// that were upgraded
249-fn upgrade_pkgbuilds(mut ui TransUI, mut handle &alpm.Handle, config ConfigUpgrade) ![]string {
249+fn upgrade_pkgbuilds(mut ui TransUI, mut handle &nspkg.Handle, config ConfigUpgrade) ![]string {
250250 repos := pkgbuild_repos()
251251 if repos.len == 0 {
252252 warn('no pkgbuild repo in the config: the pkgbuild pass has nothing to query')
@@ -266,11 +266,11 @@ fn upgrade_pkgbuilds(mut ui TransUI, mut handle &alpm.Handle, config ConfigUpgra
266266 // is a stop, the way a declined build stops an install
267267 view, installed := local_now()!
268268 built := if local := installed.pkg_find(u.info.name) {
269- alpm.pkg_vercmp(local.get_version(), u.info.version) >= 0
269+ nspkg.pkg_vercmp(local.get_version(), u.info.version) >= 0
270270 } else {
271271 false
272272 }
273- view.release() or { went_on('release the alpm handle', err) }
273+ view.release() or { went_on('release the nspkg handle', err) }
274274 if !built {
275275 advise('${u.info.name} was declined, the pass stops')
276276 return upgraded
@@ -1,6 +1,6 @@
11module main
22
3-import alpm
3+import nspkg
44
55// prepare_error explains a failed transaction when the upgrade of outdated
66// dependencies was switched off. a dependency too old for a target is not
@@ -9,7 +9,7 @@ import alpm
99// version this transaction replaces — which the walk (broken_dependents)
1010// would have upgraded along. the hint goes on a line of its own, below the
1111// broken dependencies prepare listed
12-fn prepare_error(handle &alpm.Handle, msg string, no_upgrade_deps bool) string {
12+fn prepare_error(handle &nspkg.Handle, msg string, no_upgrade_deps bool) string {
1313 if no_upgrade_deps && handle.errno() == .unsatisfied_deps {
1414 return '${msg}\nwithout --no-upgrade-deps, the installed packages this breaks are upgraded along with it when the repos have a version that fits'
1515 }
@@ -1,12 +1,12 @@
11module main
22
3-import alpm
3+import nspkg
44
55#include <stdlib.h>
66
77// 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
8+// path. like pacman, anything with a scheme is one: the selected nspkg downloader
9+// decides which schemes it supports. the scheme is
1010// spelled the RFC writes it — a letter, then letters, digits, '.', '+', '-',
1111// closed by '://' — so a path with a stray '://', which is a legal file
1212// name, keeps being a path
@@ -32,9 +32,9 @@ fn is_url(target string) bool {
3232
3333// fetch_url downloads a package from a URL into the cache with libalpm, so the
3434// download user and the progress bars are the same as for repo packages
35-fn fetch_url(handle &alpm.Handle, url string) !string {
35+fn fetch_url(handle &nspkg.Handle, url string) !string {
3636 // libalpm appends to the head of the list, so it needs the address of the head
37- mut urls := &alpm.List(unsafe { nil })
37+ mut urls := &nspkg.List(unsafe { nil })
3838 url_head := &urls
3939 url_head.append_strdup(url)
4040 defer {
@@ -67,7 +67,7 @@ fn fetch_url(handle &alpm.Handle, url string) !string {
6767// signature level its archive is loaded at: libalpm fetches the .sig beside
6868// the url when the level checks packages, and the load verifies it. none
6969// when the level requires a signature, which leaves nothing to warn of
70-fn url_trust_warning(target string, level alpm.SigLevel) ?string {
70+fn url_trust_warning(target string, level nspkg.SigLevel) ?string {
7171 if !level.has(.package) {
7272 return '${target}: package signatures are not checked'
7373 }
@@ -82,7 +82,7 @@ fn url_trust_warning(target string, level alpm.SigLevel) ?string {
8282// whatever libalpm asks on the way goes through the install's prompter. the
8383// warning before it says what the remote file signature level will check.
8484// 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 {
85+fn fetch_target_url(mut ui TransUI, handle &nspkg.Handle, target string) !string {
8686 level := handle.option_get_remote_file_siglevel() or {
8787 return error('could not read the remote file signature level')
8888 }
@@ -1,6 +1,6 @@
11module main
22
3-import alpm
3+import nspkg
44
55fn test_is_url() {
66 for url in ['https://example.org/foo-1-1-any.pkg.tar.zst', 'http://x/y', 'ftp://x/y',
@@ -28,17 +28,17 @@ fn test_is_url() {
2828fn test_url_trust_warning() {
2929 url := 'https://example.org/foo-1-1-any.pkg.tar.zst'
3030 // no package check: the warning says so
31- none_level := url_trust_warning(url, alpm.SigLevel.database) or { '' }
31+ none_level := url_trust_warning(url, nspkg.SigLevel.database) or { '' }
3232 assert none_level.contains('not checked')
3333 assert none_level.starts_with(url)
3434 // optional: the .sig is read when the server offers one, not otherwise
35- optional := url_trust_warning(url, alpm.SigLevel.package | .package_optional) or { '' }
35+ optional := url_trust_warning(url, nspkg.SigLevel.package | .package_optional) or { '' }
3636 assert optional.contains('only if the server offers one')
3737 // required: the load refuses an unsigned package, nothing to warn of
38- if note := url_trust_warning(url, alpm.SigLevel.package) {
38+ if note := url_trust_warning(url, nspkg.SigLevel.package) {
3939 assert false, 'a required signature was warned of: ${note}'
4040 }
41- if note := url_trust_warning(url, alpm.SigLevel.package | .database) {
41+ if note := url_trust_warning(url, nspkg.SigLevel.package | .database) {
4242 assert false, 'a required signature was warned of: ${note}'
4343 }
4444}
@@ -1,12 +1,12 @@
11module main
22
3-import alpm
3+import nspkg
44import os
55
66// backups_of lists the backup entries of a package: the config files whose
77// expected md5 the db records
8-fn backups_of(pkg &alpm.Package) []&alpm.Backup {
9- mut out := []&alpm.Backup{}
8+fn backups_of(pkg &nspkg.Package) []&nspkg.Backup {
9+ mut out := []&nspkg.Backup{}
1010 mut node := pkg.get_backup()
1111 for node != unsafe { nil } {
1212 if b := node.get_backup() {
@@ -53,7 +53,7 @@ fn verify(config ConfigVerify) !int {
5353 mut ui := new_trans_ui()
5454 // the configured handle: -kk needs the NoExtract globs
5555 mut handle := init_handle(ui)!
56- defer { handle.release() or { went_on('release the alpm handle', err) } }
56+ defer { handle.release() or { went_on('release the nspkg handle', err) } }
5757 defer { ui.stop() }
5858
5959 mut pkgcache := local_pkgcache(handle)!
@@ -71,7 +71,7 @@ fn verify(config ConfigVerify) !int {
7171 // a target is a name, a versioned dependency or something provided,
7272 // as pacman's -Qk resolves it; one that names nothing installed is
7373 // reported and counted, and the rest are checked
74- pkgs = []&alpm.Package{}
74+ pkgs = []&nspkg.Package{}
7575 for target in config.query {
7676 pkg := find_local_target(pkgcache, local_target_name(target), true) or {
7777 target_error('package "${target}" was not found')
@@ -162,7 +162,7 @@ fn verify(config ConfigVerify) !int {
162162 if hash := backups[name] {
163163 // a checksum that libalpm cannot calculate counts as a
164164 // problem, as pacman's "failed to calculate" does
165- md5 := alpm.compute_md5sum(path) or {
165+ md5 := nspkg.compute_md5sum(path) or {
166166 lines << VerifyLine{true, '${pkg.get_name()}: ${path} (failed to calculate MD5 checksum)'}
167167 problems++
168168 continue
@@ -1,6 +1,6 @@
11module main
22
3-import alpm
3+import nspkg
44import crypto.sha256
55import os
66
@@ -47,7 +47,7 @@ struct MtreeEntry {
4747// which reports a partial mtree as a complete one. the second value is
4848// whether the package carries an mtree file at all (packages built before
4949// mtrees existed do not; that is not an error)
50-fn mtree_entries(pkg &alpm.Package) !([]MtreeEntry, bool) {
50+fn mtree_entries(pkg &nspkg.Package) !([]MtreeEntry, bool) {
5151 archive := pkg.mtree_open()
5252 if archive == unsafe { nil } {
5353 // libalpm answers nil both for no mtree file and for one libarchive
@@ -210,7 +210,7 @@ fn check_file_full(path string, e MtreeEntry, backup bool) []VerifyLine {
210210// the report is held and handed back with the number of altered files: the
211211// caller prints it after its spinner stops, since an inline println would
212212// draw under the running frame
213-fn verify_pkg_full(handle &alpm.Handle, pkg &alpm.Package) (int, []VerifyLine) {
213+fn verify_pkg_full(handle &nspkg.Handle, pkg &nspkg.Package) (int, []VerifyLine) {
214214 name := pkg.get_name()
215215 mut lines := []VerifyLine{}
216216 // a broken mtree is that package's verdict; the check goes on
@@ -1,6 +1,6 @@
11module main
22
3-import alpm
3+import nspkg
44import crypto.sha256
55import encoding.base64
66import os
@@ -138,7 +138,7 @@ fn test_file_sha256_read_failure() ! {
138138
139139// mtree_pkg installs one package in a temp local db with the given gzipped
140140// 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) {
141+fn mtree_pkg(tmp string, name string, mtree []u8) !(&nspkg.Handle, &nspkg.Package) {
142142 entry := os.join_path(tmp, 'db', 'local', '${name}-1.0-1')
143143 os.mkdir_all(entry)!
144144 os.mkdir_all(os.join_path(tmp, 'root'))!
@@ -148,7 +148,7 @@ fn mtree_pkg(tmp string, name string, mtree []u8) !(&alpm.Handle, &alpm.Package)
148148 if mtree.len > 0 {
149149 os.write_file_array(os.join_path(entry, 'mtree'), mtree)!
150150 }
151- handle := alpm.initialize(os.join_path(tmp, 'root') + '/', os.join_path(tmp, 'db') + '/')!
151+ handle := nspkg.initialize(os.join_path(tmp, 'root') + '/', os.join_path(tmp, 'db') + '/')!
152152 pkg := handle.find_local_pkg(name) or { return error('${name} is not installed') }
153153 return handle, pkg
154154}
@@ -1,8 +1,8 @@
11Module {
22 name: 'vpac'
3- description: 'an alpm frontend written in V'
3+ description: 'a frontend for nspkg written in V'
44 version: '0.0.0'
55 license: 'GPLv3'
66 base_url: 'src'
7- dependencies: ['alpm.v', 'blip']
7+ dependencies: ['nspkg', 'vile', 'stutter']
88}
@@ -1,939 +0,0 @@
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-}
@@ -1,396 +0,0 @@
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,39 @@
1+module vmakepkg
2+
3+import vile.scheme
4+
5+// all three recipe formats use the same metadata fields.
6+pub struct PackageMeta {
7+ values map[string]scheme.Value
8+}
9+
10+pub fn (m PackageMeta) has(key string) bool {
11+ return key in m.values
12+}
13+
14+pub fn (m PackageMeta) get(key string) scheme.Value {
15+ return m.values[key]
16+}
17+
18+fn package_meta(value scheme.Value) !PackageMeta {
19+ fields := value.record_fields()!
20+ if fields.len != 2 { return error('pkgbuild: invalid metadata record') }
21+ keys := fields[0].vector_items()!
22+ values := fields[1].vector_items()!
23+ if keys.len != values.len {
24+ return error('pkgbuild: metadata keys and values differ in length')
25+ }
26+ mut result := map[string]scheme.Value{}
27+ for i, key in keys {
28+ name := key.as_string()!
29+ if name in result { return error('pkgbuild #:${name} is set twice') }
30+ result[name] = values[i]
31+ }
32+ for name in ['name', 'pkgname', 'pkgver', 'pkgrel', 'pkgdesc', 'arch', 'package'] {
33+ if name !in result { return error('pkgbuild: #:${name} is required') }
34+ }
35+ if recipe_items_of(result['pkgname'], 'pkgname')!.len == 0 {
36+ return error('pkgbuild #:pkgname must not be empty')
37+ }
38+ return PackageMeta{ values: result }
39+}
@@ -0,0 +1,106 @@
1+module vmakepkg
2+
3+import os
4+import time
5+
6+fn pkginfo_field(mut lines []string, key string, values []string) ! {
7+ for value in values {
8+ if value.bytes().any(it in [u8(0), 10, 13]) {
9+ return error('invalid newline or NUL in package field ${key}')
10+ }
11+ lines << '${key} = ${value}'
12+ }
13+}
14+
15+fn payload_size(dir string) !u64 {
16+ mut size := u64(0)
17+ for name in os.ls(dir)! {
18+ path := os.join_path(dir, name)
19+ st := os.lstat(path)!
20+ if st.mode & 0o170000 == 0o040000 {
21+ size += payload_size(path)!
22+ } else {
23+ size += st.size
24+ }
25+ }
26+ return size
27+}
28+
29+fn native_archive(desc NativeRecipe, name string, version string, pkg_arch string, pkg string, path string, hook string, recipe string) ! {
30+ spec := desc.spec
31+ mut payload := os.ls(pkg)!
32+ payload.sort()
33+ if payload.any(it.starts_with('.')) {
34+ return error('hidden top-level package members are reserved for package metadata')
35+ }
36+ mut lines := []string{}
37+ date := if os.getenv('SOURCE_DATE_EPOCH') != '' {
38+ os.getenv('SOURCE_DATE_EPOCH')
39+ } else {
40+ time.now().unix().str()
41+ }
42+ packager := os.getenv_opt('PACKAGER') or { 'vpac' }
43+ for key, values in {
44+ 'pkgname': [name]
45+ 'pkgbase': [spec.pkgnames[0]]
46+ 'pkgver': [version]
47+ 'pkgdesc': [spec.pkgdesc]
48+ 'arch': [pkg_arch]
49+ 'builddate': [date]
50+ 'packager': [packager]
51+ 'size': [payload_size(pkg)!.str()]
52+ 'license': desc.licenses
53+ 'url': [spec.url].filter(it != '')
54+ 'depend': spec.depends
55+ 'makedepend': spec.makedepends
56+ 'checkdepend': spec.checkdepends
57+ 'optdepend': spec.optdepends
58+ 'conflict': spec.conflicts
59+ 'provides': spec.provides
60+ 'backup': spec.backup
61+ } {
62+ pkginfo_field(mut lines, key, values)!
63+ }
64+ os.write_file(os.join_path(pkg, '.PKGINFO'), lines.join('\n') + '\n')!
65+ digest, _ := file_digests(recipe)!
66+ mut build := []string{}
67+ for key, value in {
68+ 'format': '2'
69+ 'pkgname': name
70+ 'pkgbase': spec.pkgnames[0]
71+ 'pkgver': version
72+ 'pkgarch': pkg_arch
73+ 'pkgbuild_sha256sum': digest
74+ 'packager': packager
75+ 'builddate': date
76+ 'builddir': os.dir(pkg)
77+ 'startdir': os.dir(recipe)
78+ 'buildtool': 'vpac'
79+ 'buildtoolver': '1'
80+ } {
81+ pkginfo_field(mut build, key, [value])!
82+ }
83+ os.write_file(os.join_path(pkg, '.BUILDINFO'), build.join('\n') + '\n')!
84+ mut members := ['.PKGINFO', '.BUILDINFO']
85+ if hook != '' {
86+ os.cp(hook, os.join_path(pkg, '.NSPKG-HOOK'))!
87+ os.chmod(os.join_path(pkg, '.NSPKG-HOOK'), 0o755)!
88+ members << '.NSPKG-HOOK'
89+ }
90+ members << payload
91+ // a NUL list preserves every payload filename and bounds the argument list.
92+ list := path + '.files'
93+ os.write_file(list, members.join('\x00') + '\x00')!
94+ defer { os.rm(list) or { eprintln('remove archive file list: ${err}') } }
95+ common := ['--uid', '0', '--gid', '0', '--uname', 'root', '--gname', 'root', '-C', pkg, '--null',
96+ '-T', list]
97+ mut mtree := ['bsdtar', '-czf', os.join_path(pkg, '.MTREE'), '--format=mtree',
98+ '--options=!all,use-set,type,uid,gid,mode,time,size,sha256,link']
99+ mtree << common
100+ run(mtree)!
101+ members.insert(1, '.MTREE')
102+ os.write_file(list, members.join('\x00') + '\x00')!
103+ mut tar := ['bsdtar', '-cf', path, '--zstd', '--format=pax']
104+ tar << common
105+ run(tar)!
106+}
@@ -0,0 +1,149 @@
1+module vmakepkg
2+
3+import json2
4+import os
5+
6+fn C.mkdtemp(&char) &char
7+
8+fn private_dir(parent string) !string {
9+ path := os.join_path(parent, '.vpac-XXXXXX').clone()
10+ if C.mkdtemp(&char(path.str)) == unsafe { nil } { return os.last_error() }
11+ return path
12+}
13+
14+fn command_output(argv []string) !string {
15+ result := os.exec(argv)
16+ if result.exit_code != 0 {
17+ return error('${argv[0]} exited with status ${result.exit_code}: ${result.output.trim_space()}')
18+ }
19+ return result.output.trim_space()
20+}
21+
22+fn filename_part(value string) bool {
23+ return value.len > 0 && value !in ['.', '..'] && !value.starts_with('-')
24+ && value.bytes().all(it.is_alnum() || it in [`@`, `_`, `+`, `.`, `-`])
25+}
26+
27+// the builder has a fresh private working directory per invocation. the caller
28+// receives the completed split set only after every archive and signature exists.
29+pub fn native_build(path string, sign bool) ![]string {
30+ if os.geteuid() == 0 { return error('native package builds require an unprivileged user') }
31+ recipe := os.abs_path(path)
32+ if os.base(recipe) !in ['PKGBUILD.scm', 'PKGBUILD.vile', 'PKGBUILD.vsh'] {
33+ return error('native build expects PKGBUILD.scm, PKGBUILD.vile or PKGBUILD.vsh')
34+ }
35+ start := os.dir(recipe)
36+ work := private_dir(start)!
37+ mut complete := false
38+ defer {
39+ if !complete {
40+ os.rmdir_all(work) or { eprintln('remove incomplete build: ${err}') }
41+ }
42+ }
43+ src := os.join_path(work, 'src')
44+ os.mkdir(src)!
45+ mut runner := [os.executable(), '--recipe-run', recipe]
46+ mut desc := NativeRecipe{}
47+ if os.file_ext(recipe) == '.vsh' {
48+ mut compiler := os.getenv('VPAC_V')
49+ if compiler == '' { compiler = 'v' }
50+ exe := os.join_path(work, 'vsh-runner')
51+ mut compile := [compiler]
52+ // this executable and its hooks target the builder's ABI. supplying it
53+ // keeps V from invoking the host's ldd shell script to guess the libc.
54+ $if linux && glibc ? {
55+ compile << '-glibc'
56+ } $else $if linux && musl ? {
57+ compile << '-musl'
58+ }
59+ compile << ['-skip-running', '-o', exe, recipe]
60+ run(compile)!
61+ description := os.join_path(work, 'recipe.json')
62+ run([exe, 'generate', description])!
63+ desc = json2.decode[NativeRecipe](os.read_file(description)!)!
64+ runner = [exe]
65+ } else {
66+ desc = native_description(recipe_load(recipe)!)!
67+ }
68+ spec := desc.spec
69+ if spec.pkgnames.len == 0 || spec.pkgnames.any(!filename_part(it)) || spec.pkgrel < 1 {
70+ return error('native recipe needs valid package names and a positive pkgrel')
71+ }
72+ host_arch := os.uname().machine
73+ pkg_arch := if host_arch in spec.arch {
74+ host_arch
75+ } else if 'any' in spec.arch {
76+ if os.file_ext(recipe) == '.vsh' && spec.hooks.len > 0 { host_arch } else { 'any' }
77+ } else {
78+ return error('package does not support ${host_arch}')
79+ }
80+ mut deps := spec.depends.clone()
81+ deps << spec.makedepends
82+ deps << spec.checkdepends
83+ if deps.len > 0 {
84+ mut query := [os.executable(), '--makepkg-query', '-T']
85+ query << deps
86+ command_output(query)!
87+ }
88+ for opt in spec.options {
89+ if opt !in ['docs', '!strip', '!debug'] {
90+ return error('unsupported native package option: ${opt}')
91+ }
92+ }
93+ native_sources(spec, start, src)!
94+ original := os.getwd()
95+ os.chdir(src)!
96+ defer { os.chdir(original) or { eprintln('restore working directory: ${err}') } }
97+ os.setenv('VPAC_STARTDIR', start, true)
98+ os.setenv('VPAC_SRCDIR', src, true)
99+ os.setenv('VPAC_PKGNAME', spec.pkgnames[0], true)
100+ os.setenv('VPAC_PKGVER', spec.pkgver, true)
101+ os.unsetenv('VPAC_PKGDIR')
102+ if 'prepare' in desc.phases { run(phase_args(runner, 'prepare'))! }
103+ version := if desc.dynamic {
104+ command_output(phase_args(runner, 'pkgver'))!
105+ } else {
106+ spec.pkgver
107+ }
108+ if !filename_part(version) || version.contains('-') {
109+ return error('invalid pkgver: ${version}')
110+ }
111+ os.setenv('VPAC_PKGVER', version, true)
112+ for phase in ['build', 'check'] {
113+ if phase in desc.phases { run(phase_args(runner, phase))! }
114+ }
115+ hook := if spec.hooks.len == 0 {
116+ ''
117+ } else if os.file_ext(recipe) == '.vsh' {
118+ runner[0]
119+ } else {
120+ write_recipe_hook(recipe, work, desc.hook_files)!
121+ }
122+ pkgs := os.join_path(work, 'pkg')
123+ os.mkdir(pkgs)!
124+ fullver := if spec.epoch > 0 {
125+ '${spec.epoch}:${version}-${spec.pkgrel}'
126+ } else {
127+ '${version}-${spec.pkgrel}'
128+ }
129+ mut archives := []string{}
130+ for name in spec.pkgnames {
131+ pkg := os.join_path(pkgs, name)
132+ os.mkdir(pkg)!
133+ os.setenv('VPAC_PKGDIR', pkg, true)
134+ os.setenv('VPAC_PKGNAME', name, true)
135+ run(phase_args(runner, 'package'))!
136+ archive := os.join_path(work, '${name}-${version}-${spec.pkgrel}-${pkg_arch}.pkg.tar.zst')
137+ native_archive(desc, name, fullver, pkg_arch, pkg, archive, hook, recipe)!
138+ if sign { run(['gpg', '--batch', '--detach-sign', '--output', archive + '.sig', archive])! }
139+ archives << archive
140+ }
141+ complete = true
142+ return archives
143+}
144+
145+fn phase_args(runner []string, phase string) []string {
146+ mut args := runner.clone()
147+ args << phase
148+ return args
149+}
@@ -0,0 +1,63 @@
1+module vmakepkg
2+
3+import json2
4+import vile.scheme
5+import os
6+
7+// the body goes through vpac inside the transaction root. paths in the bundle
8+// are relative to the recipe, including helpers loaded by a later hook.
9+struct RecipeHook {
10+ recipe string
11+ files map[string]string
12+}
13+
14+const hook_header = '#!/usr/bin/env -S vpac --package-hook\n'
15+
16+fn hook_relative_path(name string) bool {
17+ return !name.contains('\x00') && !name.split('/').any(it in ['', '.', '..'])
18+}
19+
20+fn write_recipe_hook(recipe string, work string, helpers []string) !string {
21+ name := os.base(recipe)
22+ base := os.real_path(os.dir(recipe)) + '/'
23+ mut files := {
24+ name: os.read_file(recipe)!
25+ }
26+ for rel in helpers {
27+ path := os.join_path(base, rel)
28+ if !hook_relative_path(rel) || !os.real_path(path).starts_with(base) || !os.is_file(path) {
29+ return error('invalid native hook file: ${rel}')
30+ }
31+ files[rel] = os.read_file(path)!
32+ }
33+ path := os.join_path(work, 'hook')
34+ os.write_file(path, hook_header + json2.encode(RecipeHook{ recipe: name, files: files }))!
35+ return path
36+}
37+
38+pub fn package_hook(args []string) ! {
39+ if args.len < 5 || args[1] != '--nspkg-hook' || args[2] !in recipe_hooks || args.len != 4 + recipe_hook_arity(args[2]) {
40+ return error('invalid native hook arguments')
41+ }
42+ source := os.read_file(args[0])!
43+ if !source.starts_with(hook_header) { return error('unknown recipe hook format') }
44+ bundle := json2.decode[RecipeHook](source[hook_header.len..])!
45+ if bundle.recipe !in ['PKGBUILD.scm', 'PKGBUILD.vile'] || bundle.recipe !in bundle.files {
46+ return error('missing recipe in native hook')
47+ }
48+ dir := private_dir(os.temp_dir())!
49+ defer { os.rmdir_all(dir) or { eprintln('remove staged hook: ${err}') } }
50+ for name, contents in bundle.files {
51+ if !hook_relative_path(name) {
52+ return error('invalid path in native hook')
53+ }
54+ path := os.join_path(dir, name)
55+ os.mkdir_all(os.dir(path))!
56+ os.write_file(path, contents)!
57+ }
58+ path := os.join_path(dir, bundle.recipe)
59+ os.setenv('VPAC_PKGNAME', args[3], true)
60+ mut vm := recipe_new_machine()!
61+ meta := recipe_load_in(mut vm, path)!
62+ if meta.has(args[2]) { vm.call(meta.get(args[2]), args[4..].map(scheme.string_value(it)))! }
63+}
@@ -0,0 +1,50 @@
1+module vmakepkg
2+
3+// the build process owns the VM or compiled V script. only data crosses into
4+// the archive writer; callbacks stay with the recipe that defines them.
5+struct NativeRecipe {
6+pub:
7+ spec Spec
8+ licenses []string
9+ hook_files []string
10+ phases []string
11+ dynamic bool
12+}
13+
14+fn (m PackageMeta) items(key string) ![]string {
15+ if !m.has(key) { return []string{} }
16+ return recipe_items_of(m.get(key), key)
17+}
18+
19+fn native_description(m PackageMeta) !NativeRecipe {
20+ dynamic := !m.has('pkgver') || m.get('pkgver').kind() != .string
21+ return NativeRecipe{
22+ spec: Spec{
23+ pkgnames: m.items('pkgname')!
24+ pkgver: if dynamic { '' } else { m.get('pkgver').as_string()! }
25+ pkgrel: m.get('pkgrel').as_integer()!
26+ epoch: if m.has('epoch') { m.get('epoch').as_integer()! } else { 0 }
27+ pkgdesc: m.get('pkgdesc').as_string()!
28+ arch: m.items('arch')!
29+ url: if m.has('url') { m.get('url').as_string()! } else { '' }
30+
31+ depends: m.items('depends')!
32+ makedepends: m.items('makedepends')!
33+ checkdepends: m.items('checkdepends')!
34+ optdepends: m.items('optdepends')!
35+ provides: m.items('provides')!
36+ conflicts: m.items('conflicts')!
37+ backup: m.items('backup')!
38+ options: (m.items('options')!).map(recipe_option(it))
39+ source: m.items('source')!
40+ validpgpkeys: m.items('validpgpkeys')!
41+ b2sums: m.items('b2sums')!
42+ sha256sums: m.items('sha256sums')!
43+ hooks: recipe_hooks.filter(m.has(it))
44+ }
45+ hook_files: m.items('hook-files')!
46+ licenses: m.items('license')!
47+ phases: recipe_phases.filter(m.has(it))
48+ dynamic: dynamic
49+ }
50+}
@@ -0,0 +1,126 @@
1+module vmakepkg
2+
3+import crypto.blake2b
4+import crypto.sha256
5+import os
6+
7+fn file_digests(path string) !(string, string) {
8+ mut f := os.open(path)!
9+ defer { f.close() }
10+ mut sha := sha256.new()
11+ mut b2 := blake2b.new512()!
12+ mut buf := []u8{len: 65536}
13+ for {
14+ n := f.read(mut buf) or {
15+ if err is os.Eof { break }
16+ return err
17+ }
18+ if n == 0 { break }
19+ sha.write(buf[..n])!
20+ b2.write(buf[..n])!
21+ }
22+ return sha.sum([]).hex(), b2.checksum().hex()
23+}
24+
25+fn verify_source_signature(sig string, keys []string) ! {
26+ data := sig.all_before_last('.')
27+ if !os.is_file(data) { return error('missing signed source for ${sig}') }
28+ // keep machine-readable signature records apart from human diagnostics.
29+ dir := private_dir(os.dir(sig))!
30+ defer { os.rmdir_all(dir) or { eprintln('remove signature status: ${err}') } }
31+ file := os.join_path(dir, 'status')
32+ run(['gpg', '--batch', '--status-file', file, '--verify', '--', sig, data])!
33+ status := os.read_file(file)!
34+ for line in status.split_into_lines() {
35+ if keys.len == 0 {
36+ if line.starts_with('[GNUPG:] TRUST_FULLY ') || line.starts_with('[GNUPG:] TRUST_ULTIMATE ') {
37+ return
38+ }
39+ } else if line.starts_with('[GNUPG:] VALIDSIG ') {
40+ fields := line.fields()
41+ if fields.len >= 3 && (fields[2] in keys || fields.last() in keys) { return }
42+ }
43+ }
44+ return error('source signature has no trusted signing key: ${sig}')
45+}
46+
47+fn native_sources(spec Spec, start string, src string) ! {
48+ if spec.source.len == 0 && spec.b2sums.len == 0 && spec.sha256sums.len == 0 { return }
49+ if spec.sha256sums.len == 0 && spec.b2sums.len == 0 {
50+ return error('sources require sha256sums or b2sums')
51+ }
52+ for sums in [spec.sha256sums, spec.b2sums] {
53+ if sums.len > 0 && sums.len != spec.source.len {
54+ return error('source and checksum counts differ')
55+ }
56+ }
57+ store := os.join_path(os.dir(src), 'sources')
58+ os.mkdir(store)!
59+ mut names := []string{}
60+ mut signed := []string{}
61+ for i, entry in spec.source {
62+ uri := entry.all_after('::')
63+ name := if entry.contains('::') {
64+ entry.all_before('::')
65+ } else {
66+ os.base(uri.all_before('?').all_before('#')).trim_string_right(if uri.starts_with('git+') {
67+ '.git'
68+ } else {
69+ ''
70+ })
71+ }
72+ if name in ['', '.', '..'] || name.contains('/') || name.bytes().any(it < 32) || name in names {
73+ return error('invalid or duplicate source filename: ${name}')
74+ }
75+ names << name
76+ path := os.join_path(store, name)
77+ if uri.starts_with('git+') {
78+ if (spec.sha256sums.len > 0 && spec.sha256sums[i] != 'SKIP')
79+ || (spec.b2sums.len > 0 && spec.b2sums[i] != 'SKIP') {
80+ return error('git sources require SKIP checksums')
81+ }
82+ url := uri[4..].all_before('#')
83+ if !url.starts_with('https://') && !url.starts_with('file://') {
84+ return error('unsupported git transport: ${url}')
85+ }
86+ run(['git', 'clone', '--', url, os.join_path(src, name)])!
87+ if uri.contains('#') {
88+ ref := uri.all_after('#')
89+ if ref.all_before('=') !in ['tag', 'branch', 'commit'] || ref.all_after('=') == '' || ref.all_after('=').starts_with('-') {
90+ return error('invalid git source reference: ${ref}')
91+ }
92+ run(['git', '-C', os.join_path(src, name), 'checkout', '--detach', ref.all_after('='),
93+ '--'])!
94+ }
95+ continue
96+ }
97+ if uri.starts_with('https://') || uri.starts_with('http://') {
98+ run(['curl', '--fail', '--location', '--proto', '=http,https', '--proto-redir',
99+ '=http,https', '--output', path, '--', uri])!
100+ } else {
101+ if uri.contains('://') { return error('unsupported source URL: ${uri}') }
102+ os.cp(os.join_path(start, uri), path)!
103+ }
104+ sha, b2 := file_digests(path)!
105+ if spec.sha256sums.len > 0 && spec.sha256sums[i] != 'SKIP' && spec.sha256sums[i].to_lower() != sha {
106+ return error('sha256 mismatch for ${name}')
107+ }
108+ if spec.b2sums.len > 0 && spec.b2sums[i] != 'SKIP' && spec.b2sums[i].to_lower() != b2 {
109+ return error('b2sum mismatch for ${name}')
110+ }
111+ if name.ends_with('.sig') || name.ends_with('.asc') { signed << path }
112+ }
113+ for sig in signed { verify_source_signature(sig, spec.validpgpkeys)! }
114+ for name in names {
115+ path := os.join_path(store, name)
116+ if !os.exists(path) { continue }
117+ os.cp(path, os.join_path(src, name))!
118+ }
119+ for name in names {
120+ path := os.join_path(store, name)
121+ if !os.exists(path) { continue }
122+ if ['.tar', '.tgz', '.tbz2', '.txz', '.zip'].any(name.ends_with(it)) || name.contains('.tar.') {
123+ run(['bsdtar', '-xf', path, '-C', src])!
124+ }
125+ }
126+}
@@ -0,0 +1,464 @@
1+module vmakepkg
2+
3+import os
4+import vile.reader
5+import vile.scheme
6+
7+// Scheme and Vile recipes share the same metadata and phase bindings.
8+const recipe_list_keys = [
9+ 'pkgname',
10+ 'arch',
11+ 'license',
12+ 'depends',
13+ 'makedepends',
14+ 'checkdepends',
15+ 'optdepends',
16+ 'provides',
17+ 'conflicts',
18+ 'backup',
19+ 'options',
20+ 'source',
21+ 'validpgpkeys',
22+ 'hook-files',
23+ 'b2sums',
24+ 'sha256sums',
25+]
26+
27+const recipe_phases = ['prepare', 'build', 'check', 'package']
28+
29+const recipe_hooks = ['pre-install', 'post-install', 'pre-upgrade', 'post-upgrade', 'pre-remove',
30+ 'post-remove']
31+
32+// upgrade hooks receive the new and old versions, in that order.
33+fn recipe_hook_arity(hook string) int {
34+ if hook in ['pre-upgrade', 'post-upgrade'] {
35+ return 2
36+ }
37+ return 1
38+}
39+
40+// quote one argument for callers that execute a plain PKGBUILD or elevate through su.
41+pub fn shell_quote(s string) string {
42+ return "'" + s.replace("'", "'\\''") + "'"
43+}
44+
45+// recipe_tag_name is for error text: 'a keyword' reads better than a dump of the
46+// tag enum
47+fn recipe_tag_name(t scheme.Kind) string {
48+ return match t {
49+ .nil { 'an empty list' }
50+ .boolean { 'a boolean' }
51+ .integer { 'an integer' }
52+ .real, .rational { 'a number' }
53+ .character { 'a character' }
54+ .string { 'a string' }
55+ .symbol { 'a symbol' }
56+ .keyword { 'a keyword' }
57+ .pair { 'a list' }
58+ .vector { 'a vector' }
59+ .procedure { 'a procedure' }
60+ else { 'a ${t}' }
61+ }
62+}
63+
64+fn recipe_item(v scheme.Value) !string {
65+ return match v.kind() {
66+ .string { v.as_string()! }
67+ .symbol { v.symbol_name()! }
68+ .keyword { v.keyword_name()! }
69+ else { error('items must be strings or keywords, not ${recipe_tag_name(v.kind())}') }
70+ }
71+}
72+
73+// list_items also rejects dotted and cyclic lists, without dropping a tail.
74+fn recipe_items_of(v scheme.Value, what string) ![]string {
75+ match v.kind() {
76+ .string, .symbol, .keyword { return [recipe_item(v)!] }
77+ .nil { return []string{} }
78+ .pair, .vector {
79+ items := if v.kind() == .vector {
80+ v.vector_items()!
81+ } else {
82+ v.list_items() or { return error('pkgbuild #:${what}: a list ends in (): ${err.msg()}') }
83+ }
84+ mut out := []string{}
85+ for item in items {
86+ out << recipe_item(item) or { return error('pkgbuild #:${what}: ${err.msg()}') }
87+ }
88+ return out
89+ }
90+ else { return error('pkgbuild #:${what} must be a string or a quoted list') }
91+ }
92+}
93+
94+// package metadata uses the kernel spelling of x86_64.
95+fn recipe_arch(a string) string {
96+ if a == 'x86-64' {
97+ return 'x86_64'
98+ }
99+ return a
100+}
101+
102+// Scheme keywords spell a disabled option as #:no-strip and package metadata uses !strip.
103+fn recipe_option(keyword string) string {
104+ if keyword.starts_with('no-') {
105+ return '!' + keyword[3..]
106+ }
107+ return keyword
108+}
109+
110+// a source checksum is either its full hexadecimal digest or SKIP.
111+fn recipe_hex(s string, len int, what string) ! {
112+ if s == 'SKIP' {
113+ return
114+ }
115+ if s.len != len {
116+ return error('${what}: ${s} is ${s.len} characters; ${what} entries are ${len} hex characters or SKIP')
117+ }
118+ for c in s {
119+ if !c.is_hex_digit() {
120+ return error('${what}: ${s} has a character that is not hex (${c.ascii_str()})')
121+ }
122+ }
123+}
124+
125+// recipe_key40 checks a PGP fingerprint: the full 40 uppercase hex characters
126+fn recipe_key40(s string, i int) ! {
127+ if s.len != 40 {
128+ return error('validpgpkeys: entry ${i} is ${s.len} characters; fingerprints are 40: the full uppercase one')
129+ }
130+ for c in s {
131+ if !c.is_hex_digit() {
132+ return error('validpgpkeys: entry ${i} has a character that is not hex (${c.ascii_str()})')
133+ }
134+ if c >= `a` && c <= `f` {
135+ return error('validpgpkeys: entry ${i} is lowercase hex (${c.ascii_str()}); uppercase fingerprints only')
136+ }
137+ }
138+}
139+
140+// keep phase closures in the VM that evaluated the recipe.
141+fn prim_defpkgbuild(mut vm scheme.VM, input []scheme.Value) !scheme.Value {
142+ scheme.check_arity('vpac-defpkgbuild', input.len, 2, 2)!
143+ forms := input[0].list_items()!
144+ mut args := input[1].list_items()!
145+ if forms.len != args.len { return error('pkgbuild: source and value counts differ') }
146+ if args.len == 0 {
147+ return error('pkgbuild: (defpkgbuild name ...) needs the name')
148+ }
149+ // the macro quotes the name so package names never resolve as variables.
150+ if args[0].kind() == .pair {
151+ quoted := args[0].list_items()!
152+ if quoted.len == 2 && quoted[0].kind() == .symbol && quoted[0].symbol_name()! == 'quote' {
153+ args[0] = quoted[1]
154+ }
155+ }
156+ if args[0].kind() !in [.string, .symbol] {
157+ return error('pkgbuild: the name is a symbol or a string, not ${recipe_tag_name(args[0].kind())}')
158+ }
159+ pkgbase_name := recipe_item(args[0])!
160+ if (args.len - 1) % 2 != 0 {
161+ return error('pkgbuild: #:key and value come in pairs')
162+ }
163+ mut fields := []string{}
164+ mut vals := map[string]scheme.Value{}
165+ fields << 'name'
166+ vals['name'] = scheme.string_value(pkgbase_name)
167+ mut i := 1
168+ for i < args.len {
169+ kv := args[i]
170+ if kv.kind() != .keyword {
171+ return error('pkgbuild: expected a #:key, got ${scheme.write(kv)!}')
172+ }
173+ key := kv.keyword_name()!
174+ val := args[i + 1]
175+ if key in fields {
176+ return error('pkgbuild #:${key} is set twice')
177+ }
178+ if key in recipe_list_keys {
179+ mut items := recipe_items_of(val, key)!
180+ match key {
181+ 'pkgname' {
182+ if items.len == 0 {
183+ return error('pkgbuild #:pkgname must not be empty')
184+ }
185+ for it in items {
186+ if it.contains(' ') {
187+ return error('pkgbuild #:pkgname: "${it}" has whitespace in it')
188+ }
189+ }
190+ }
191+ 'arch' {
192+ if items.len == 0 {
193+ return error('pkgbuild #:arch must not be empty')
194+ }
195+ for j, it in items {
196+ items[j] = recipe_arch(it)
197+ }
198+ }
199+ 'validpgpkeys' {
200+ for j, it in items {
201+ recipe_key40(it, j)!
202+ }
203+ }
204+ 'b2sums' {
205+ for it in items {
206+ recipe_hex(it, 128, 'b2sums')!
207+ }
208+ }
209+ 'sha256sums' {
210+ for it in items {
211+ recipe_hex(it, 64, 'sha256sums')!
212+ }
213+ }
214+ 'backup' {
215+ for it in items {
216+ if it.starts_with('/') {
217+ return error('pkgbuild #:backup: "${it}" is absolute; backup paths are relative, no leading slash')
218+ }
219+ }
220+ }
221+ else {}
222+ }
223+ mut item_vals := []scheme.Value{}
224+ for it in items {
225+ item_vals << scheme.string_value(it)
226+ }
227+ fields << key
228+ vals[key] = scheme.list(item_vals)
229+ i += 2
230+ continue
231+ }
232+ if key in recipe_phases || key in recipe_hooks {
233+ if val.kind() != .procedure {
234+ return error('pkgbuild #:${key} must be a (lambda ...)')
235+ }
236+ arity := if key in recipe_hooks { recipe_hook_arity(key) } else { 0 }
237+ recipe_check_lambda(forms[i + 1], key, arity)!
238+ fields << key
239+ vals[key] = val
240+ i += 2
241+ continue
242+ }
243+ match key {
244+ 'pkgver' {
245+ // VCS recipes can calculate the version after extracting the sources.
246+ if val.kind() != .string && val.kind() != .procedure {
247+ return error('pkgbuild #:pkgver must be a string or a (lambda ...)')
248+ }
249+ fields << key
250+ vals[key] = val
251+ }
252+ 'pkgrel', 'epoch' {
253+ if val.kind() != .integer {
254+ return error('pkgbuild #:${key} must be an integer')
255+ }
256+ if key == 'epoch' && val.as_integer()! < 0 {
257+ return error('pkgbuild #:epoch is negative; 0 means absent')
258+ }
259+ fields << key
260+ vals[key] = val
261+ }
262+ 'pkgdesc', 'url' {
263+ if val.kind() != .string {
264+ return error('pkgbuild #:${key} must be a string')
265+ }
266+ fields << key
267+ vals[key] = val
268+ }
269+ else {
270+ return error('pkgbuild has no key #:${key}')
271+ }
272+ }
273+ i += 2
274+ }
275+ // data-only packages can go straight to the package phase.
276+ for req in ['pkgname', 'pkgver', 'pkgrel', 'pkgdesc', 'arch', 'package'] {
277+ if req !in fields {
278+ return error('pkgbuild: #:${req} is required')
279+ }
280+ }
281+ return vm.call(vm.lookup('vpac-make-pkgbuild')!, [
282+ scheme.vector(fields.map(scheme.string_value(it))),
283+ scheme.vector(fields.map(vals[it])),
284+ ])
285+}
286+
287+fn prim_exec(mut _vm scheme.VM, args []scheme.Value) !scheme.Value {
288+ mut argv := []string{cap: args.len}
289+ for arg in args {
290+ argv << arg.as_string()!
291+ }
292+ run(argv)!
293+ return scheme.nil_value()
294+}
295+
296+// prim_glob returns a sorted scheme list for for-each, empty when nothing
297+// matches: the loop in the format example iterates it directly
298+fn prim_glob(mut _vm scheme.VM, args []scheme.Value) !scheme.Value {
299+ if args.len != 1 || args[0].kind() != .string {
300+ return error('(glob pattern) takes one string pattern')
301+ }
302+ matches := glob(args[0].as_string()!)!
303+ mut out := []scheme.Value{}
304+ for m in matches {
305+ out << scheme.string_value(m)
306+ }
307+ return scheme.list(out)
308+}
309+
310+fn prim_pkgdir(mut _vm scheme.VM, _ []scheme.Value) !scheme.Value {
311+ return scheme.string_value(pkgdir()!)
312+}
313+
314+fn prim_srcdir(mut _vm scheme.VM, _ []scheme.Value) !scheme.Value {
315+ return scheme.string_value(srcdir()!)
316+}
317+
318+fn prim_startdir(mut _vm scheme.VM, _ []scheme.Value) !scheme.Value {
319+ return scheme.string_value(startdir()!)
320+}
321+
322+fn prim_this_pkg(mut _vm scheme.VM, _ []scheme.Value) !scheme.Value {
323+ return scheme.string_value(this_pkg()!)
324+}
325+
326+// a repository can use a fallback version before it has a matching tag.
327+fn prim_git_desc(mut _vm scheme.VM, args []scheme.Value) !scheme.Value {
328+ if args.len == 0 || args.len > 2 || args[0].kind() != .string {
329+ return error('(git-desc pattern fallback?) takes a string pattern and an optional string fallback')
330+ }
331+ pattern := args[0].as_string()!
332+ mut fallback := ''
333+ if args.len == 2 {
334+ if args[1].kind() != .string {
335+ return error('(git-desc ...): the fallback must be a string')
336+ }
337+ fallback = args[1].as_string()!
338+ }
339+ return scheme.string_value(git_desc(pattern, fallback)!)
340+}
341+
342+// source forms retain literal lambda parameter lists for validation, without
343+// invoking build phases while reading package metadata.
344+fn recipe_check_lambda(form scheme.Value, key string, expected int) ! {
345+ if form.kind() != .pair { return }
346+ parts := form.list_items()!
347+ if parts.len < 2 || parts[0].kind() != .symbol || parts[0].symbol_name()! != 'lambda' { return }
348+ params := parts[1].list_items() or { return error('pkgbuild #:${key} needs a fixed parameter list') }
349+ if params.len != expected {
350+ return error('pkgbuild #:${key} takes ${expected} parameter${if expected == 1 {
351+ ''
352+ } else {
353+ 's'
354+ }}, not ${params.len}')
355+ }
356+}
357+
358+fn recipe_new_machine() !&scheme.VM {
359+ mut m := scheme.new_with_options(max_steps: 100_000_000)!
360+ m.register('vpac-defpkgbuild', prim_defpkgbuild)!
361+ m.register('run', prim_exec)!
362+ m.register('glob', prim_glob)!
363+ m.register('pkgdir', prim_pkgdir)!
364+ m.register('srcdir', prim_srcdir)!
365+ m.register('startdir', prim_startdir)!
366+ m.register('this-pkg', prim_this_pkg)!
367+ m.register('git-desc', prim_git_desc)!
368+ m.eval('(define-record-type vpac-pkgbuild (vpac-make-pkgbuild keys values) vpac-pkgbuild? (keys vpac-pkgbuild-keys) (values vpac-pkgbuild-values))
369+ (define-syntax defpkgbuild
370+ (syntax-rules ()
371+ ((_) (vpac-defpkgbuild (quote ()) (quote ())))
372+ ((_ name arg ...) (vpac-defpkgbuild (quote (name arg ...)) (cons (quote name) (list arg ...))))))')!
373+ return m
374+}
375+
376+// use the evaluator's reader so datum comments, escaped symbols and whitespace
377+// have the same meaning here. quoted data is not a package declaration.
378+fn recipe_count_form(arena &reader.DatumArena, id reader.NodeId, mut seen map[reader.NodeId]bool) !int {
379+ first := arena.canonical_id(id)!
380+ node := arena.node(first)!
381+ if node.kind != .pair || first in seen {
382+ return 0
383+ }
384+ head := arena.node(arena.canonical_id(node.car)!)!
385+ mut count := 0
386+ if head.kind == .symbol {
387+ name := arena.symbol_name(node.car)!
388+ if name in ['quote', 'quasiquote'] {
389+ return 0
390+ }
391+ if name == 'defpkgbuild' {
392+ count++
393+ }
394+ }
395+ mut cursor := first
396+ for cursor !in seen {
397+ seen[cursor] = true
398+ item := arena.node(cursor)!
399+ if item.kind != .pair {
400+ break
401+ }
402+ count += recipe_count_form(arena, item.car, mut seen)!
403+ cursor = arena.canonical_id(item.cdr)!
404+ }
405+ return count
406+}
407+
408+fn recipe_defpkg_count(path string) !int {
409+ source := os.read_file(path)!
410+ doc := if os.file_ext(path) == '.vile' {
411+ reader.read_alt(source)!
412+ } else {
413+ reader.read_all(source)!
414+ }
415+ mut seen := map[reader.NodeId]bool{}
416+ mut count := 0
417+ for form in doc.forms {
418+ count += recipe_count_form(&doc.arena, form, mut seen)!
419+ }
420+ return count
421+}
422+
423+// recipe_load_in checks that the final value is the package metadata record.
424+fn recipe_load_in(mut m scheme.VM, path string) !PackageMeta {
425+ // a recipe that cannot be read fails here, with the read's own reason: the
426+ // one-form check is never skipped on the way to a load that reads it
427+ count := recipe_defpkg_count(path) or { return error('${path}: ${err.msg()}') }
428+ if count > 1 {
429+ return error('${path}: one (defpkgbuild ...) form per file, not ${count}')
430+ }
431+ v := m.eval_file(path)!
432+ if v.kind() != .record || v.record_type()!.record_type_name()! != 'vpac-pkgbuild' {
433+ return error('${path}: the last form must be a (defpkgbuild ...)')
434+ }
435+ return package_meta(v)!
436+}
437+
438+// recipe_load reads the final metadata record in the syntax selected by the filename.
439+pub fn recipe_load(path string) !PackageMeta {
440+ mut m := recipe_new_machine()!
441+ return recipe_load_in(mut m, path)!
442+}
443+
444+// evaluate the phase in the same VM as its metadata and closures.
445+pub fn recipe_run_phase(recipe string, phase string, params []string) ! {
446+ mut m := recipe_new_machine()!
447+ // load on this machine, not recipe_load's: the bootstrap macro has to be
448+ // in the machine that runs the file, with its phases
449+ meta := recipe_load_in(mut m, recipe)!
450+ if !meta.has(phase) {
451+ return error('${recipe}: the pkgbuild has no #:${phase}')
452+ }
453+ cb := meta.get(phase)
454+ if cb.kind() != .procedure {
455+ return error('${recipe}: #:${phase} is not a (lambda ...)')
456+ }
457+ res := m.call(cb, params.map(scheme.string_value(it)))!
458+ if phase == 'pkgver' {
459+ if res.kind() != .string {
460+ return error('pkgver: the lambda ran into ${recipe_tag_name(res.kind())}, not a version string')
461+ }
462+ println(res.as_string()!)
463+ }
464+}
@@ -0,0 +1,413 @@
1+module vmakepkg
2+
3+import os
4+
5+fn test_recipe_phases_load_helpers_and_receive_arguments() ! {
6+ dir := os.join_path(os.vtmp_dir(), 'vpac_recipe_phases_${os.getpid()}')
7+ os.mkdir_all(dir)!
8+ cwd := os.getwd()
9+ old_pkgdir := os.getenv_opt('VPAC_PKGDIR')
10+ old_startdir := os.getenv_opt('VPAC_STARTDIR')
11+ defer {
12+ os.chdir(cwd) or { eprintln('restore test directory: ${err}') }
13+ if value := old_pkgdir {
14+ os.setenv('VPAC_PKGDIR', value, true)
15+ } else {
16+ os.unsetenv('VPAC_PKGDIR')
17+ }
18+ if value := old_startdir {
19+ os.setenv('VPAC_STARTDIR', value, true)
20+ } else {
21+ os.unsetenv('VPAC_STARTDIR')
22+ }
23+ os.rmdir_all(dir) or { eprintln('remove test package: ${err}') }
24+ }
25+ os.setenv('VPAC_PKGDIR', dir, true)
26+ os.setenv('VPAC_STARTDIR', dir, true)
27+ os.chdir(dir)!
28+ os.write_file('helper.scm', '(define (destination name) (string-append (pkgdir) "/" name))')!
29+ os.write_file('one.txt', 'first\n')!
30+ os.write_file('two.txt', 'second\n')!
31+ recipe := os.join_path(dir, 'PKGBUILD.scm')
32+ os.write_file(recipe, '(load "helper.scm")
33+(defpkgbuild phases
34+ #:pkgname "phases" #:pkgver "1.0" #:pkgrel 1
35+ #:pkgdesc "phase execution" #:arch (list "any")
36+ #:package (lambda ()
37+ (for-each (lambda (file) (run "cp" file (destination (string-append file ".copy"))))
38+ (glob "*.txt")))
39+ #:post-install (lambda (version)
40+ (run "touch" (destination version))))')!
41+ recipe_load(recipe)!
42+ assert !os.exists('one.txt.copy')
43+ recipe_run_phase(recipe, 'package', [])!
44+ assert os.read_file('one.txt.copy')! == 'first\n'
45+ assert os.read_file('two.txt.copy')! == 'second\n'
46+ version := '1.0; touch injected'
47+ recipe_run_phase(recipe, 'post-install', [version])!
48+ assert os.is_file(version)
49+ assert !os.exists('injected')
50+ recipe_run_phase(recipe, 'post-install', []) or { return }
51+ assert false, 'a hook ran without its version argument'
52+}
53+
54+fn test_recipe_rejects_malformed_metadata_calls() ! {
55+ dir := os.join_path(os.vtmp_dir(), 'vpac_recipe_metadata_${os.getpid()}')
56+ os.mkdir_all(dir)!
57+ defer { os.rmdir_all(dir) or { eprintln('remove test metadata: ${err}') } }
58+ path := os.join_path(dir, 'PKGBUILD.scm')
59+ for source in ['(vpac-defpkgbuild)', '(vpac-make-pkgbuild #() #())',
60+ '(vpac-make-pkgbuild #("name") #())'] {
61+ os.write_file(path, source)!
62+ recipe_load(path) or { continue }
63+ assert false, 'malformed package metadata loaded: ${source}'
64+ }
65+}
66+
67+// architecture and option spellings in package metadata
68+fn test_recipe_arch() {
69+ assert recipe_arch('x86-64') == 'x86_64'
70+ assert recipe_arch('any') == 'any'
71+ assert recipe_arch('x86') == 'x86'
72+}
73+
74+fn test_recipe_option() {
75+ assert recipe_option('no-strip') == '!strip'
76+ assert recipe_option('docs') == 'docs'
77+ assert recipe_option('zipman') == 'zipman'
78+ assert recipe_option('no-docs') == '!docs'
79+}
80+
81+fn test_recipe_hook_arity() {
82+ assert recipe_hook_arity('pre-install') == 1
83+ assert recipe_hook_arity('post-remove') == 1
84+ assert recipe_hook_arity('pre-upgrade') == 2
85+ assert recipe_hook_arity('post-upgrade') == 2
86+}
87+
88+fn test_shell_quote() {
89+ assert shell_quote("a 'b' c") == "'a '\\''b'\\'' c'"
90+ assert shell_quote('plain') == "'plain'"
91+}
92+
93+fn test_shell_quote_round_trips_through_sh() {
94+ // the property that matters: whatever the value holds, a shell reads it
95+ // back as the one word it was — no expansion, no split, no command
96+ for value in ["it's", '\$HOME', '`id`', '\$(id)', 'a b\tc', 'semi;colon', 'new\nline', 'back\\slash',
97+ '"double"', "'", "''", '*', '-n', '', 'ünï'] {
98+ res := os.exec(['sh', '-c', 'printf %s ' + shell_quote(value)])
99+ assert res.exit_code == 0, value
100+ assert res.output == value, value
101+ }
102+}
103+
104+// recipe_defpkg_count counts real (defpkgbuild ...) forms: comments of either
105+// kind stay out, block comments stay out, a string's mention of the form
106+// stays out, and a longer symbol whose name begins equally is no form
107+fn test_recipe_defpkg_count() {
108+ dir := os.join_path(os.vtmp_dir(), 'vpac_recipe_count_${os.getpid()}')
109+ os.mkdir_all(dir)!
110+ defer {
111+ os.rmdir_all(dir) or {}
112+ }
113+ p := os.join_path(dir, 'count.scm')
114+ os.write_file(p, '(defpkgbuild foo\n)')!
115+ assert recipe_defpkg_count(p)! == 1
116+ os.write_file(p, '(defpkgbuild foo\n)\n(defpkgbuild bar\n)')!
117+ assert recipe_defpkg_count(p)! == 2
118+ os.write_file(p, ';; a comment names (defpkgbuild x)\n(defpkgbuild foo\n)')!
119+ assert recipe_defpkg_count(p)! == 1
120+ os.write_file(p, '(defpkgbuild foo ; inline ends the text (defpkgbuild y)\n)')!
121+ assert recipe_defpkg_count(p)! == 1
122+ os.write_file(p, '#| (defpkgbuild z) reduces the block |#\n(defpkgbuild foo\n)')!
123+ assert recipe_defpkg_count(p)! == 1
124+ // a string's mention of the form stays out: the ('no form counts') text
125+ // spells one whole (defpkgbuild ...) inside a string
126+ os.write_file(p, '(defpkgbuild foo\n #:defpkgdesc "the string names (defpkgbuild x) whole"\n)')!
127+ assert recipe_defpkg_count(p)! == 1
128+ os.write_file(p, '(defpkg-build foo\n)')!
129+ assert recipe_defpkg_count(p)! == 0
130+ os.write_file(p, '(defpkgbuildy foo\n)')!
131+ assert recipe_defpkg_count(p)! == 0
132+ os.write_file(p, '#;(defpkgbuild ignored)\n( defpkgbuild foo)')!
133+ assert recipe_defpkg_count(p)! == 1
134+ os.write_file(p, '(begin ( defpkgbuild foo) (\n defpkgbuild bar))')!
135+ assert recipe_defpkg_count(p)! == 2
136+ os.write_file(p, "'(defpkgbuild quoted)\n#((defpkgbuild literal))\n(|defpkgbuild| foo)")!
137+ assert recipe_defpkg_count(p)! == 1
138+ os.write_file(p, '#\\(\n#0=(begin . #0#)')!
139+ assert recipe_defpkg_count(p)! == 0
140+}
141+
142+fn test_recipe_load_uses_scheme_declarations() ! {
143+ dir := os.join_path(os.vtmp_dir(), 'vpac_recipe_reader_${os.getpid()}')
144+ os.mkdir_all(dir)!
145+ defer { os.rmdir_all(dir) or { eprintln('remove test package: ${err}') } }
146+ path := os.join_path(dir, 'PKGBUILD.scm')
147+ source := valid_recipe.join('\n').replace('(defpkgbuild', '(\n defpkgbuild')
148+ os.write_file(path, '#;(defpkgbuild ignored)\n' + source)!
149+ assert recipe_load(path)!.items('pkgname')! == ['corpus']
150+ os.write_file(path, source + '\n' + source)!
151+ recipe_load(path) or {
152+ assert err.msg().contains('one (defpkgbuild ...) form per file, not 2'), err.msg()
153+ return
154+ }
155+ assert false, 'whitespace hid a second package declaration'
156+}
157+
158+fn test_native_recipe_loads_helpers_and_validates_declarations() ! {
159+ dir := os.join_path(os.vtmp_dir(), 'vpac_vile_recipe_${os.getpid()}')
160+ os.mkdir_all(dir)!
161+ defer { os.rmdir_all(dir) or { eprintln('remove test recipe: ${err}') } }
162+ path := os.join_path(dir, 'PKGBUILD.vile')
163+ os.write_file(os.join_path(dir, 'helper.vile'), 'version := "1.2"')!
164+ source := 'load("helper.vile")
165+defpkgbuild(native, #:pkgname, "native", #:pkgver, version,
166+ #:pkgrel, 1, #:pkgdesc, "native recipe", #:arch, [#:any],
167+ #:package, fn() {})'
168+ os.write_file(path, source)!
169+ assert native_description(recipe_load(path)!)!.spec.pkgver == '1.2'
170+ os.write_file(path, source.replace('fn() {}', 'fn(unexpected) {}'))!
171+ if _ := recipe_load(path) {
172+ assert false, 'a package phase with an argument was accepted'
173+ } else {
174+ assert err.msg().contains('#:package takes 0 parameters'), err.msg()
175+ }
176+ os.write_file(path, source + '\n' + source)!
177+ recipe_load(path) or {
178+ assert err.msg().contains('form per file, not 2'), err.msg()
179+ return
180+ }
181+ assert false, 'a second native package declaration was accepted'
182+}
183+
184+fn test_recipe_load_unreadable() ! {
185+ dir := os.join_path(os.vtmp_dir(), 'vpac_recipe_unreadable_${os.getpid()}')
186+ os.mkdir_all(dir)!
187+ defer {
188+ os.rmdir_all(dir) or {}
189+ }
190+ // no file at all, and a directory where the file should be: each fails
191+ // with the read's reason and the path, not a later, other complaint
192+ for p in [os.join_path(dir, 'missing.scm'), dir] {
193+ recipe_load(p) or {
194+ assert err.msg().starts_with('${p}: '), err.msg()
195+ assert !err.msg().contains('defpkgbuild'), err.msg()
196+ continue
197+ }
198+ assert false, '${p} loaded'
199+ }
200+ // two forms in a readable file are still the one-form error
201+ two := os.join_path(dir, 'two.scm')
202+ os.write_file(two, '(defpkgbuild foo\n)\n(defpkgbuild bar\n)')!
203+ recipe_load(two) or {
204+ assert err.msg().contains('one (defpkgbuild ...) form per file, not 2'), err.msg()
205+ return
206+ }
207+ assert false, 'two forms loaded'
208+}
209+
210+// read_items reads what recipe_items_of makes of a scheme expression's value
211+fn read_items(src string) ![]string {
212+ mut m := recipe_new_machine()!
213+ return recipe_items_of(m.eval(src)!, 'depends')!
214+}
215+
216+fn test_recipe_items_of_every_spelling() ! {
217+ // one item, as a string, a keyword or a symbol
218+ assert read_items('"glibc"')! == ['glibc']
219+ assert read_items('#:any')! == ['any']
220+ assert read_items("'zsh")! == ['zsh']
221+ // a quoted list, a vector, and the empty one
222+ assert read_items('\'("a" "b" #:c)')! == ['a', 'b', 'c']
223+ assert read_items('#("a" "b" #:c)')! == ['a', 'b', 'c']
224+ assert read_items("'()")! == []string{}
225+ assert read_items('#()')! == []string{}
226+ // a list's items are plain: a number among them is said, in both kinds
227+ for src in ['\'("a" 1)', '#("a" 1)'] {
228+ read_items(src) or {
229+ assert err.msg().contains('items must be strings or keywords'), err.msg()
230+ continue
231+ }
232+ assert false, '${src} was read'
233+ }
234+ // a dotted tail is no list: its last item would be dropped silently.
235+ // a cons with a non-list tail exercises the same rejection.
236+ read_items('(cons "a" "b")') or {
237+ assert err.msg().contains('a list ends in ()'), err.msg()
238+ return
239+ }
240+ assert false, 'a dotted list was read'
241+}
242+
243+fn test_recipe_vector_lists_reach_the_pkgbuild() ! {
244+ dir := os.join_path(os.vtmp_dir(), 'vpac_recipe_vector_${os.getpid()}')
245+ os.mkdir_all(dir)!
246+ defer {
247+ os.rmdir_all(dir) or {}
248+ }
249+ // the lists spelled as vectors, where the golden recipe quotes them
250+ recipe := os.join_path(dir, 'vec.scm')
251+ lines := [
252+ '(defpkgbuild vec',
253+ ' #:pkgname "vec"',
254+ ' #:pkgver "1.0"',
255+ ' #:pkgrel 1',
256+ ' #:pkgdesc "vector lists"',
257+ ' #:arch #(#:any)',
258+ ' #:depends #("glibc" "zsh")',
259+ ' #:license #("MIT")',
260+ ' #:build (lambda () (run "true"))',
261+ ' #:package (lambda () (run "true")))',
262+ ]
263+ os.write_file(recipe, lines.join('\n'))!
264+ desc := native_description(recipe_load(recipe)!)!
265+ assert desc.spec.depends == ['glibc', 'zsh']
266+ assert desc.spec.arch == ['any']
267+ assert desc.licenses == ['MIT']
268+}
269+
270+// valid_recipe is a recipe every field of which is right; the corpus below breaks
271+// one thing at a time
272+const valid_recipe = ['(defpkgbuild corpus', ' #:pkgname "corpus"', ' #:pkgver "1.0"', ' #:pkgrel 1',
273+ ' #:pkgdesc "a corpus base"', " #:arch '(#:any)", ' #:build (lambda () (run "true"))',
274+ ' #:package (lambda () (run "true")))']
275+
276+// RecipeCase is a recipe broken one way, and what the validator says about it
277+struct RecipeCase {
278+ what string
279+ text string
280+ says string
281+}
282+
283+// broken replaces the line of valid_recipe that starts with key's spelling, or
284+// appends extra before the closing parenthesis when key is ''
285+fn broken(key string, line string) string {
286+ mut lines := valid_recipe.clone()
287+ if key == '' {
288+ // the last line ends in defpkgbuild's own ')': the new line takes it
289+ last := lines[lines.len - 1]
290+ lines[lines.len - 1] = last[..last.len - 1]
291+ lines << line + ')'
292+ return lines.join('\n')
293+ }
294+ for i, l in lines {
295+ if l.trim_space().starts_with('#:${key} ') {
296+ lines[i] = line
297+ if i == lines.len - 1 {
298+ lines[i] += ')'
299+ }
300+ }
301+ }
302+ return lines.join('\n')
303+}
304+
305+fn test_recipe_validation_corpus() ! {
306+ dir := os.join_path(os.vtmp_dir(), 'vpac_recipe_corpus_${os.getpid()}')
307+ os.mkdir_all(dir)!
308+ defer {
309+ os.rmdir_all(dir) or {}
310+ }
311+ // the base itself is good
312+ base := os.join_path(dir, 'base.scm')
313+ os.write_file(base, valid_recipe.join('\n'))!
314+ recipe_load(base)!
315+
316+ hex64 := 'ab'.repeat(32)
317+ for c in [
318+ RecipeCase{'no name', '(defpkgbuild)', 'needs the name'},
319+ RecipeCase{'a number for a name', valid_recipe.join('\n').replace('(defpkgbuild corpus', '(defpkgbuild 7'), 'the name is a symbol or a string, not'},
320+ RecipeCase{'a key without its value', broken('', ' #:url'), '#:key and value come in pairs'},
321+ RecipeCase{'a value where a key goes', broken('', ' "stray" "pair"'), 'expected a #:key, got "stray"'},
322+ RecipeCase{'a key twice', broken('', ' #:pkgrel 2'), '#:pkgrel is set twice'},
323+ RecipeCase{'an empty name list', broken('pkgname', " #:pkgname '()"), '#:pkgname must not be empty'},
324+ RecipeCase{'a name with a space', broken('pkgname', ' #:pkgname "cor pus"'), 'has whitespace in it'},
325+ RecipeCase{'no arch', broken('arch', " #:arch '()"), '#:arch must not be empty'},
326+ RecipeCase{'a short b2sum', broken('', ' #:b2sums \'("abc")'), 'b2sums: abc is 3 characters; b2sums entries are 128 hex characters or SKIP'},
327+ RecipeCase{'a sha256 that is not hex', broken('', ' #:sha256sums \'("${'zz'.repeat(32)}")'), 'has a character that is not hex (z)'},
328+ RecipeCase{'a short fingerprint', broken('', ' #:validpgpkeys \'("ABCDEF")'), 'validpgpkeys: entry 0 is 6 characters'},
329+ RecipeCase{'a lowercase fingerprint', broken('', ' #:validpgpkeys \'("${'ab'.repeat(20)}")'), 'uppercase fingerprints only'},
330+ RecipeCase{'an absolute backup', broken('', ' #:backup \'("/etc/x.conf")'), 'is absolute; backup paths are relative'},
331+ RecipeCase{'a phase that is no lambda', broken('build', ' #:build "make"'), '#:build must be a (lambda ...)'},
332+ RecipeCase{'a phase with a parameter', broken('build', ' #:build (lambda (x) (run "true"))'), '#:build takes 0 parameters, not 1'},
333+ RecipeCase{'a hook with no version', broken('', ' #:post-install (lambda () (run "true"))'), '#:post-install takes 1 parameter, not 0'},
334+ RecipeCase{'an upgrade hook with one version', broken('', ' #:post-upgrade (lambda (new) (run "true"))'), '#:post-upgrade takes 2 parameters, not 1'},
335+ RecipeCase{'a pkgver that is a number', broken('pkgver', ' #:pkgver 3'), '#:pkgver must be a string or a (lambda ...)'},
336+ RecipeCase{'a pkgrel in quotes', broken('pkgrel', ' #:pkgrel "1"'), '#:pkgrel must be an integer'},
337+ RecipeCase{'a negative epoch', broken('', ' #:epoch -1'), 'epoch is negative'},
338+ RecipeCase{'a pkgdesc that is a number', broken('pkgdesc', ' #:pkgdesc 5'), '#:pkgdesc must be a string'},
339+ RecipeCase{'an unknown key', broken('', ' #:pkgdescription "x"'), 'has no key #:pkgdescription'},
340+ RecipeCase{'a dotted list', broken('', ' #:depends (cons "a" "b")'), 'a list ends in ()'},
341+ RecipeCase{'no pkgdesc', broken('pkgdesc', ''), '#:pkgdesc is required'},
342+ RecipeCase{'no package', broken('package', ' #:url "https://example.org"'), '#:package is required'},
343+ ] {
344+ p := os.join_path(dir, 'case.scm')
345+ os.write_file(p, c.text)!
346+ recipe_load(p) or {
347+ assert err.msg().contains(c.says), '${c.what}: ${err.msg()}'
348+ continue
349+ }
350+ assert false, '${c.what} was taken:\n${c.text}'
351+ }
352+ // the right lengths and SKIP pass
353+ ok := os.join_path(dir, 'sums.scm')
354+ os.write_file(ok, broken('', ' #:sha256sums \'("${hex64}" "SKIP")'))!
355+ recipe_load(ok)!
356+}
357+
358+fn test_split_recipe_metadata() ! {
359+ // the split smoke package: two pkgnames, one shared package lambda that
360+ // asks (this-pkg) which split it runs for
361+ recipe := os.join_path(@VMODROOT, 'pkgs', 'schemesplit', 'PKGBUILD.scm')
362+ desc := native_description(recipe_load(recipe)!)!
363+ assert desc.spec.pkgnames == ['schemesplit', 'schemesplit-doc']
364+ assert desc.phases == ['package']
365+ assert desc.spec.hooks.len == 0
366+}
367+
368+fn test_recipe_without_a_build_phase() ! {
369+ // data-only recipes only declare the package phase
370+ dir := os.join_path(os.vtmp_dir(), 'vpac_recipe_nobuild_${os.getpid()}')
371+ os.mkdir_all(dir)!
372+ defer {
373+ os.rmdir_all(dir) or {}
374+ }
375+ p := os.join_path(dir, 'data.scm')
376+ os.write_file(p, broken('build', ''))!
377+ assert native_description(recipe_load(p)!)!.phases == ['package']
378+}
379+
380+fn test_native_hook_keeps_helpers_and_literal_process_arguments() ! {
381+ dir := private_dir(os.vtmp_dir())!
382+ defer { os.rmdir_all(dir) or { eprintln('remove hook test: ${err}') } }
383+ source := os.join_path(dir, 'recipe')
384+ os.mkdir(source)!
385+ path := os.join_path(source, 'PKGBUILD.scm')
386+ os.write_file(os.join_path(source, 'helper.scm'), '(define (record value) (run "touch" value))')!
387+ os.write_file(path, '(load "helper.scm")
388+(defpkgbuild demo #:pkgname "demo" #:pkgver "1" #:pkgrel 1 #:pkgdesc "test"
389+ #:arch (list "any") #:package (lambda () #t) #:post-install (lambda (v) (record v)))')!
390+ hook := write_recipe_hook(path, dir, ['helper.scm'])!
391+ os.rmdir_all(source)!
392+ message := os.join_path(dir, 'space ; $HOME *')
393+ old := os.getenv_opt('VPAC_PKGNAME')
394+ defer {
395+ if val := old { os.setenv('VPAC_PKGNAME', val, true) } else { os.unsetenv('VPAC_PKGNAME') }
396+ }
397+ package_hook([hook, '--nspkg-hook', 'post-install', 'demo', message])!
398+ assert os.is_file(message)
399+}
400+
401+fn test_native_sources_reject_checksum_before_unpacking() ! {
402+ dir := private_dir(os.vtmp_dir())!
403+ defer { os.rmdir_all(dir) or { eprintln('remove source test: ${err}') } }
404+ src := os.join_path(dir, 'src')
405+ os.mkdir(src)!
406+ os.write_file(os.join_path(dir, 'one'), 'package contents')!
407+ native_sources(Spec{ source: ['one'], sha256sums: ['0'.repeat(64)] }, dir, src) or {
408+ assert err.msg().contains('sha256 mismatch')
409+ assert os.ls(src)!.len == 0
410+ return
411+ }
412+ assert false, 'bad checksum accepted'
413+}
@@ -1,7 +1,8 @@
11module vmakepkg
22
33import os
4-import blip.vlib.blip
4+import json2
5+import vile.scheme
56
67// ------------------------------------------------------------ PKGBUILD.vsh
78//
@@ -29,12 +30,12 @@ import blip.vlib.blip
2930// }
3031//
3132// fn build() ! {
32-// vmakepkg.run('cmake -B build -DCMAKE_INSTALL_PREFIX=/usr')!
33-// vmakepkg.run('cmake --build build')!
33+// vmakepkg.run(['cmake', '-B', 'build', '-DCMAKE_INSTALL_PREFIX=/usr'])!
34+// vmakepkg.run(['cmake', '--build', 'build'])!
3435// }
3536//
3637// fn package() ! {
37-// vmakepkg.run('cmake --install build DESTDIR=' + vmakepkg.pkgdir()!)!
38+// vmakepkg.run(['env', 'DESTDIR=' + vmakepkg.pkgdir()!, 'cmake', '--install', 'build'])!
3839// }
3940//
4041// fn post_install(v []string) ! {
@@ -48,17 +49,10 @@ import blip.vlib.blip
4849// hooks: {'post-install': post_install}
4950// ) or { eprintln(err); exit(1) }
5051//
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.
52+// vpac compiles the script once and invokes the executable for metadata,
53+// phases and packaged install hooks. run takes an argv array.
6054
61-// Spec is a vsh package's head, the same fields the lip format reads
55+// Spec is a vsh package's head, the same fields the recipe format reads
6256pub struct Spec {
6357pub mut:
6458 pkgname string
@@ -102,68 +96,67 @@ fn spec_names(s &Spec) ![]string {
10296 out << it
10397 }
10498 if out.len == 0 {
105- return error('pkgbuild: :pkgname is required')
99+ return error('pkgbuild: #:pkgname is required')
106100 }
107101 for it in out {
108102 if it.contains(' ') {
109- return error('pkgbuild :pkgname: "${it}" has whitespace in it')
103+ return error('pkgbuild #:pkgname: "${it}" has whitespace in it')
110104 }
111105 }
112106 return out
113107}
114108
115-// lip_list wraps string items into a blip list, the shape the head reader
109+// recipe_list wraps string items into a scheme list, the shape the head reader
116110// walks for the array fields
117-fn lip_list(items []string) blip.Value {
118- mut out := []blip.Value{}
111+fn recipe_list(items []string) scheme.Value {
112+ mut out := []scheme.Value{}
119113 for it in items {
120- out << blip.string(it)
114+ out << scheme.string_value(it)
121115 }
122- return blip.list_from(out)
116+ return scheme.list(out)
123117}
124118
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{}
119+// spec_meta hands the spec to the same head the recipe format walks, as one
120+// metadata: the lists normalised, the sums and fingerprints checked, and
121+// the declared phases and hooks must match functions in the compiled entry.
122+fn spec_meta(s &Spec, have map[string]bool) !PackageMeta {
123+ mut vals := map[string]scheme.Value{}
132124 names := spec_names(s)!
133125 // name is the pkgbase, the canonical first of the names: for a
134126 // split-only spec the bare pkgname spelling is empty and this is what
135127 // carries one
136- vals['name'] = blip.string(names[0])
137- vals['pkgname'] = lip_list(names)
128+ vals['name'] = scheme.string_value(names[0])
129+ vals['pkgname'] = recipe_list(names)
138130 if s.pkgver != '' {
139- vals['pkgver'] = blip.string(s.pkgver)
131+ vals['pkgver'] = scheme.string_value(s.pkgver)
140132 }
141- vals['pkgrel'] = blip.integer(s.pkgrel)
142- // as the lip's :epoch: 0 means absent, and a negative one is a mistake
133+ vals['pkgrel'] = scheme.integer(s.pkgrel)
134+ // as the recipe's #:epoch: 0 means absent, and a negative one is a mistake
143135 // to say, not an epoch to leave out
144136 if s.epoch < 0 {
145- return error('pkgbuild :epoch is negative; 0 means absent')
137+ return error('pkgbuild #:epoch is negative; 0 means absent')
146138 }
147139 if s.epoch > 0 {
148- vals['epoch'] = blip.integer(s.epoch)
140+ vals['epoch'] = scheme.integer(s.epoch)
149141 }
150142 if s.pkgdesc == '' {
151- return error('pkgbuild: :pkgdesc is required')
143+ return error('pkgbuild: #:pkgdesc is required')
152144 }
153- vals['pkgdesc'] = blip.string(s.pkgdesc)
145+ vals['pkgdesc'] = scheme.string_value(s.pkgdesc)
154146 if s.arch.len == 0 {
155- return error('pkgbuild: :arch is required')
147+ return error('pkgbuild: #:arch is required')
156148 }
157149 mut arches := []string{}
158150 for a in s.arch {
159- arches << lip_arch(a)
151+ arches << recipe_arch(a)
160152 }
161- vals['arch'] = lip_list(arches)
153+ vals['arch'] = recipe_list(arches)
154+ if s.license != '' { vals['license'] = recipe_list([s.license]) }
162155 if s.url != '' {
163- vals['url'] = blip.string(s.url)
156+ vals['url'] = scheme.string_value(s.url)
164157 }
165158 if s.license != '' {
166- vals['license'] = blip.string(s.license)
159+ vals['license'] = scheme.string_value(s.license)
167160 }
168161 map2 := {
169162 'depends': s.depends
@@ -177,89 +170,66 @@ fn spec_meta(s &Spec, have map[string]bool) !blip.Value {
177170 }
178171 for key, items in map2 {
179172 if items.len > 0 {
180- vals[key] = lip_list(items)
173+ vals[key] = recipe_list(items)
181174 }
182175 }
183176 if s.backup.len > 0 {
184177 for b in s.backup {
185178 if b.starts_with('/') {
186- return error('pkgbuild :backup: "${b}" is absolute; backup paths are relative, no leading slash')
179+ return error('pkgbuild #:backup: "${b}" is absolute; backup paths are relative, no leading slash')
187180 }
188181 }
189- vals['backup'] = lip_list(s.backup)
182+ vals['backup'] = recipe_list(s.backup)
190183 }
191184 if s.validpgpkeys.len > 0 {
192185 for i, k in s.validpgpkeys {
193- lip_key40(k, i)!
186+ recipe_key40(k, i)!
194187 }
195- vals['validpgpkeys'] = lip_list(s.validpgpkeys)
188+ vals['validpgpkeys'] = recipe_list(s.validpgpkeys)
196189 }
197190 if s.b2sums.len > 0 {
198191 for it in s.b2sums {
199- lip_hex(it, 128, 'b2sums')!
192+ recipe_hex(it, 128, 'b2sums')!
200193 }
201- vals['b2sums'] = lip_list(s.b2sums)
194+ vals['b2sums'] = recipe_list(s.b2sums)
202195 }
203196 if s.sha256sums.len > 0 {
204197 for it in s.sha256sums {
205- lip_hex(it, 64, 'sha256sums')!
198+ recipe_hex(it, 64, 'sha256sums')!
206199 }
207- vals['sha256sums'] = lip_list(s.sha256sums)
200+ vals['sha256sums'] = recipe_list(s.sha256sums)
208201 }
209202 for phase in ['prepare', 'build', 'check', 'package', 'pkgver'] {
210203 if have[phase] {
211- vals[phase] = blip.nil_value()
204+ vals[phase] = scheme.nil_value()
212205 }
213206 }
214207 for h in s.hooks {
215- if h !in lip_hooks {
216- return error('pkgbuild hooks: :${h} is not a hook makepkg knows')
208+ if h !in recipe_hooks {
209+ return error('pkgbuild hooks: #:${h} is not a hook makepkg knows')
217210 }
218211 if !have[h] {
219212 return error('pkgbuild hooks: the entry holds no ${h} body')
220213 }
221- vals[h] = blip.nil_value()
214+ vals[h] = scheme.nil_value()
222215 }
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)!
216+ return PackageMeta{ values: vals }
232217}
233218
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}')
219+// run executes a program with literal arguments and the phase's standard streams.
220+pub fn run(argv []string) ! {
221+ if argv.len == 0 || argv[0] == '' || argv.any(it.contains('\x00')) {
222+ return error('run expects a program and literal arguments')
254223 }
224+ code := os.system_args(argv)
225+ if code != 0 { return error('${argv[0]} exited with status ${code}') }
255226}
256227
257-// pkgdir is the directory makepkg is filling during the package phase, the
258-// value of $pkgdir, exported for the phase as VPAC_PKGDIR
228+// pkgdir is the staging directory for the current package.
259229pub fn pkgdir() !string {
260230 p := os.getenv('VPAC_PKGDIR')
261231 if p == '' {
262- return error('pkgdir: the runner only exports it inside a makepkg phase')
232+ return error('pkgdir: unavailable outside a recipe phase')
263233 }
264234 return p
265235}
@@ -268,7 +238,7 @@ pub fn pkgdir() !string {
268238pub fn srcdir() !string {
269239 p := os.getenv('VPAC_SRCDIR')
270240 if p == '' {
271- return error('srcdir: the runner only exports it inside a makepkg phase')
241+ return error('srcdir: unavailable outside a recipe phase')
272242 }
273243 return p
274244}
@@ -277,7 +247,7 @@ pub fn srcdir() !string {
277247pub fn startdir() !string {
278248 p := os.getenv('VPAC_STARTDIR')
279249 if p == '' {
280- return error('startdir: the runner only exports it inside a makepkg phase')
250+ return error('startdir: unavailable outside a recipe phase')
281251 }
282252 return p
283253}
@@ -287,7 +257,7 @@ pub fn startdir() !string {
287257pub fn this_pkg() !string {
288258 p := os.getenv('VPAC_PKGNAME')
289259 if p == '' {
290- return error('this_pkg: the runner only exports it inside a makepkg phase')
260+ return error('this_pkg: unavailable outside a recipe phase')
291261 }
292262 return p
293263}
@@ -298,9 +268,7 @@ pub fn glob(pattern string) ![]string {
298268 return os.glob(pattern)!
299269}
300270
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
271+// a young tree can use the fallback until it has its first matching tag.
304272pub fn git_desc(pattern string, fallback string) !string {
305273 res := os.exec(['git', '--no-pager', 'describe', '--long', '--tags', '--match', pattern])
306274 if res.exit_code != 0 {
@@ -312,10 +280,7 @@ pub fn git_desc(pattern string, fallback string) !string {
312280 return res.output.trim_space()
313281}
314282
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
283+// VshEntry supplies the package spec, phase functions and named install hooks.
319284@[params]
320285pub struct VshEntry {
321286pub mut:
@@ -328,11 +293,7 @@ pub mut:
328293 hooks map[string]fn ([]string) !
329294}
330295
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
296+// vsh_entry dispatches the compiled recipe's metadata, phases and hooks.
336297pub fn vsh_entry(e VshEntry) ! {
337298 // VPAC_VSH_PATH carries the script's own path: `v run` does not say which
338299 // script called in a way the writer can trust
@@ -345,12 +306,16 @@ fn vsh_run(e VshEntry, args []string, script_path string) ! {
345306 phase := if args.len > 0 { args[0] } else { '' }
346307 match phase {
347308 'generate' {
348- if script_path == '' {
349- return error("generate: VPAC_VSH_PATH must hold the script's path")
309+ output := if args.len == 2 && args[1] != '' {
310+ args[1]
311+ } else if args.len == 1 && script_path != '' {
312+ os.join_path(os.dir(script_path), 'recipe.json')
313+ } else {
314+ return error('generate needs an output file or VPAC_VSH_PATH')
350315 }
351316 spec := e.spec or { return error('pkgbuild: a :spec is required') }
352317 s := spec()!
353- // build is optional, as makepkg's build() is; package is not
318+ // a data package can go straight to its package phase.
354319 if e.package == none {
355320 return error('pkgbuild: a :package phase is required')
356321 }
@@ -384,28 +349,18 @@ fn vsh_run(e VshEntry, args []string, script_path string) ! {
384349 if e.check != none {
385350 have['check'] = true
386351 }
387- // package is makepkg's ground truth, so its wrapper always lands
352+ // every recipe has a package phase.
388353 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'
354+ meta := spec_meta(s, have)!
355+ desc := native_description(meta)!
356+ os.write_file(output, json2.encode(desc))!
357+ }
358+ '--nspkg-hook' {
359+ if args.len < 4 || args[1] !in recipe_hooks || args.len != 3 + recipe_hook_arity(args[1]) {
360+ return error('invalid native hook arguments')
407361 }
408- println('wrote ${wrote}')
362+ os.setenv('VPAC_PKGNAME', args[2], true)
363+ if hook := e.hooks[args[1]] { hook(args[3..])! }
409364 }
410365 'pkgver' {
411366 if f := e.pkgver {
@@ -449,7 +404,7 @@ fn vsh_run(e VshEntry, args []string, script_path string) ! {
449404 else {
450405 // no argument: the usage, not a call that lost its phase quietly
451406 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')
407+ return error('vsh: give an argument: generate to describe the recipe, or one of the phases (build, check, package, pkgver) or hooks')
453408 }
454409 if phase in e.hooks {
455410 e.hooks[phase](args[1..])!
@@ -1,6 +1,7 @@
11module vmakepkg
22
33import os
4+import json2
45
56// spec_names is the bare pkgname or the split list: both spellings together
67// name one intent, so nothing is named twice, and the first mention's place
@@ -13,7 +14,7 @@ fn test_spec_names() ! {
1314 assert spec_names(&Spec{ pkgname: 'foo', pkgnames: ['foo', 'bar'] })! == ['foo', 'bar']
1415 // and a split list of repeats is one each, in first-mention order
1516 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+ // white space in a name is a mistake the recipe format refuses too
1718 if _ := spec_names(&Spec{ pkgname: 'foo bar' }) {
1819 assert false, 'a name with whitespace was taken'
1920 } else {
@@ -46,11 +47,11 @@ fn test_spec_meta_name_is_the_pkgbase() ! {
4647 'package': true
4748 }
4849 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')!
50+ st := meta
51+ // the head walks a list for #:pkgname; name stays the base
52+ names := recipe_items_of(st.get('pkgname'), 'pkgname')!
5253 assert names == ['pkg-a', 'pkg-b']
53- assert st.get('name').as_string() == 'pkg-a'
54+ assert st.get('name').as_string()! == 'pkg-a'
5455}
5556
5657// Calls records which of an entry's functions ran, with what
@@ -182,18 +183,16 @@ fn test_vsh_run_generate() ! {
182183 os.setenv('VPAC_V', '/usr/bin/v', true)
183184 mut c := &Calls{}
184185 entry := recording_entry(mut c, '')
185- // generate writes the PKGBUILD, and the .install its hooks need, beside
186- // the script, and runs no phase
186+ // describing a recipe must not run its build phases
187187 capture_stdout(fn [entry, script] () ! {
188188 vsh_run(entry, ['generate'], script)!
189189 })!
190190 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'))
191+ desc := json2.decode[NativeRecipe](os.read_file(os.join_path(dir, 'recipe.json'))!)!
192+ assert desc.spec.pkgnames == ['rec']
193+ assert desc.phases == ['prepare', 'build', 'check', 'package']
194+ assert desc.spec.hooks == ['post-install']
195+ assert !os.exists(os.join_path(dir, 'PKGBUILD'))
197196 // without the script's path there is nowhere to write
198197 vsh_run(entry, ['generate'], '') or {
199198 assert err.msg().contains('VPAC_VSH_PATH')
@@ -294,8 +293,7 @@ fn capture_stdout(f fn () !) !string {
294293}
295294
296295fn test_vsh_run_generate_without_build() ! {
297- // no build phase, as makepkg allows: the PKGBUILD has no build() and
298- // still its package()
296+ // data-only packages can go straight to the package phase
299297 dir := os.join_path(os.vtmp_dir(), 'vpac_vsh_nobuild_${os.getpid()}')
300298 os.mkdir_all(dir)!
301299 defer { os.rmdir_all(dir) or {} }
@@ -318,9 +316,8 @@ fn test_vsh_run_generate_without_build() ! {
318316 capture_stdout(fn [entry, script] () ! {
319317 vsh_run(entry, ['generate'], script)!
320318 })!
321- pkgbuild := os.read_file(os.join_path(dir, 'PKGBUILD'))!
322- assert !pkgbuild.contains('build() {'), pkgbuild
323- assert pkgbuild.contains('package() {'), pkgbuild
319+ desc := json2.decode[NativeRecipe](os.read_file(os.join_path(dir, 'recipe.json'))!)!
320+ assert desc.phases == ['package']
324321}
325322
326323fn test_spec_epoch_edges() ! {
@@ -336,14 +333,14 @@ fn test_spec_epoch_edges() ! {
336333 }
337334 // absent and 0 are the same: no epoch in the head
338335 zero := spec_meta(&base, have)!
339- assert !zero.as_struct().has('epoch')
336+ assert !zero.has('epoch')
340337 // a positive one is carried as it is
341338 three := spec_meta(&Spec{
342339 ...base
343340 epoch: 3
344341 }, 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
342+ assert three.get('epoch').as_integer()! == 3
343+ // a negative one is said, as the recipe's #:epoch says it, not dropped
347344 for bad in [-1, -100] {
348345 if _ := spec_meta(&Spec{
349346 ...base
@@ -352,7 +349,7 @@ fn test_spec_epoch_edges() ! {
352349 {
353350 assert false, 'epoch ${bad} was taken'
354351 } else {
355- assert err.msg() == 'pkgbuild :epoch is negative; 0 means absent', err.msg()
352+ assert err.msg() == 'pkgbuild #:epoch is negative; 0 means absent', err.msg()
356353 }
357354 }
358355}