vpac / src / config.v
1027 lines · 983 sloc · 31.62 KB · 3609dfbd82867dc1034a443f8f9ced529ddbbedd
Raw
1@[has_globals]
2module main
3
4import os
5import blip.vlib.blip
6import blip.vlib.blip.machine
7import alpm
8
9// config_path is the file read at startup, written in blip: a lisp dialect
10// embedded from V. the file is required, since the config carries parts of
11// vpac (the repos, for one); a setting no form of it names keeps the
12// default its __global is declared with below, which reset_config puts
13// back before every load
14pub const config_path = '/etc/vpac.d/config.lip'
15
16// the settings below were consts until the config existed. root_path and
17// db_path are joined onto file names directly, so they keep a trailing slash
18__global root_path = '/'
19__global db_path = '/var/lib/pacman/'
20__global arch = 'x86_64'
21__global parallel_downloads = 3
22// the rank form: how many mirrors to probe at once (0 = unset, so the rank
23// parallelism falls back to the network's parallel) and how long one probe
24// may take
25__global rank_parallel = 0
26__global rank_timeout = 10
27// the pkgbuild form: the command that builds and how deep the clone is.
28// where it builds is path :dir. the build command is the system's makepkg,
29// which ships in the pacman package with the libalpm vpac runs on; :makepkg
30// names another
31// the build command is trusted text: it is spelled whole into a shell that
32// runs it in the cloned dir, first as the building user and through the
33// reviews of the pkgbuild for its content. vpac does not vet it — the config
34// is code the machine's user writes (like pacman.conf no more and no less),
35// and whoever controls a user's config already controls their shell
36__global pkgbuild_makepkg = 'makepkg -f'
37__global pkgbuild_depth = 1
38// the unprivileged user libalpm downloads as, like DownloadUser in pacman.conf
39__global download_user = 'alpm'
40// the configured directories and lists. the defaults are the values the
41// hardcoded vpac used
42__global cfg_cachedirs = ['/var/cache/pacman/pkg/']
43// pacman's default HookDir, beside the system one libalpm adds by itself
44__global cfg_hookdirs = ['/etc/pacman.d/hooks/']
45// where pkgbuild packages are cloned and built (path :build): a relative
46// dir is taken under the invoking user's home, because makepkg runs as that user
47__global pkgbuild_dir = '.cache/vpac/pkgbuild'
48__global cfg_logfile = ''
49// the keyring signatures are checked against: pacman's GPGDir default, not
50// moved under a fake root (pacman keeps it as configuration). libalpm has
51// no default of its own, and without one gpgme falls back on root's own
52// ~/.gnupg, where no packager's key is
53__global cfg_gpgdir = '/etc/pacman.d/gnupg/'
54__global cfg_protocols = ['https']
55// the signature level every sync db is registered with and packages are
56// checked against. libalpm's freshly calloc'd handle verifies nothing, so
57// vpac defaults to pacman's shipped SigLevel: a package and a database
58// signature are both verified when they are present, and a mismatching one
59// fails. override with (network :siglevel [...])
60__global cfg_siglevel = alpm.SigLevel.package | .package_optional | .database | .database_optional
61__global cfg_hold = []string{}
62__global cfg_ignore = []string{}
63// the rest of pacman.conf's [options]: groups ignored as cfg_ignore's packages
64// are, files an upgrade or an install leaves alone, and the download timeout
65__global cfg_ignore_groups = []string{}
66__global cfg_noupgrade = []string{}
67__global cfg_noextract = []string{}
68__global cfg_disable_timeout = false
69// pacman.conf's DisableSandboxFilesystem and DisableSandboxSyscalls: libalpm
70// sandboxes its downloads and extracts, and this turns both parts off
71__global cfg_disable_sandbox = false
72// pacman.conf's UseSyslog: libalpm logs to syslog too, (path :syslog true)
73__global cfg_syslog = false
74// cfg_repos holds the repos the config defines
75__global cfg_repos = []CfgRepo{}
76
77// CfgRepo is one registered repo: a name, a kind ('sync', or 'pkgbuild' for
78// a site to build from), and the urls to fetch it from, where a url keeps
79// the $repo and $arch placeholders
80struct CfgRepo {
81 name string
82 kind string
83 servers []string
84 // what the db is used for, as pacman.conf's Usage; every use by default
85 usage alpm.DBUsage = alpm.db_usage_all
86}
87
88// QuietConfigHost reads the config file from the real filesystem and throws
89// away anything it prints: a config is read for its definitions, and its
90// output has no place in vpac's own. it never reads stdin
91struct QuietConfigHost {}
92
93fn (h &QuietConfigHost) host_print(_ string) {}
94
95fn (h &QuietConfigHost) host_write(_ string) {}
96
97fn (h &QuietConfigHost) host_read_line() ?string {
98 return none
99}
100
101fn (h &QuietConfigHost) host_load(path string) !string {
102 return os.read_file(path)
103}
104
105// str_of reads one quoted string out of a config value
106// usage_of reads a repo's :usage, pacman.conf's Usage: one or more of sync,
107// search, install, upgrade and all
108fn usage_of(v blip.Value, what string) !alpm.DBUsage {
109 names := match v.tag {
110 .string { [v.as_string()] }
111 else { strs_of(v, what)! }
112 }
113 if names.len == 0 {
114 return error('config: ${what} needs at least one of sync, search, install, upgrade, all')
115 }
116 mut usage := unsafe { alpm.DBUsage(0) }
117 for name in names {
118 usage |= match name.to_lower() {
119 'sync' { alpm.DBUsage.sync }
120 'search' { alpm.DBUsage.search }
121 'install' { alpm.DBUsage.install }
122 'upgrade' { alpm.DBUsage.upgrade }
123 'all' { alpm.db_usage_all }
124 else {
125 return error('config: ${what} takes sync, search, install, upgrade and all, not "${name}"')
126 }
127 }
128 }
129 return usage
130}
131
132fn 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
139fn 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
147fn 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
167fn 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
175fn 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
184fn 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
193fn count_of(v blip.Value, what string, min int) !int {
194 n := int_of(v, what)!
195 if n < min {
196 return error('config: ${what} must be at least ${min}')
197 }
198 return n
199}
200
201// siglevel_names are the names (network :siglevel) accepts, mapped onto
202// libalpm's SigLevel bits, plus what each one means
203const siglevel_names = {
204 'package': alpm.SigLevel.package
205 'package_optional': alpm.SigLevel.package_optional
206 'package_marginal_ok': alpm.SigLevel.package_marginal_ok
207 'package_unknown_ok': alpm.SigLevel.package_unknown_ok
208 'database': alpm.SigLevel.database
209 'database_optional': alpm.SigLevel.database_optional
210 'database_marginal_ok': alpm.SigLevel.database_marginal_ok
211 'database_unknown_ok': alpm.SigLevel.database_unknown_ok
212}
213
214// siglevel_of reads a SigLevel out of a config value: one name or an array
215// of names, e.g. (network :siglevel ['package' 'database_optional'])
216fn siglevel_of(v blip.Value, what string) !alpm.SigLevel {
217 names := match v.tag {
218 .string { [v.as_string()] }
219 else { strs_of(v, what)! }
220 }
221 // an empty one verifies nothing: libalpm would take the silent answer
222 // as handing everything over unsigned, which nobody ever means
223 if names.len == 0 {
224 return error('config: ${what} needs at least one of: ${siglevel_names.keys().join(', ')}')
225 }
226 mut level := unsafe { alpm.SigLevel(0) }
227 for name in names {
228 key := name.to_lower()
229 bit := siglevel_names[key] or {
230 return error('config: ${what} must be one or more of: ${siglevel_names.keys().join(', ')}')
231 }
232 level |= bit
233 }
234 return level
235}
236
237// dir_path checks a configured directory: names are joined onto it directly,
238// so it must not be empty and it has to end with a slash
239fn 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
247fn 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
255fn keyword_args(form string, args []blip.Value) !([]string, []blip.Value) {
256 if args.len % 2 != 0 {
257 return error('config: ${form} keys and values come in pairs')
258 }
259 mut keys := []string{}
260 mut values := []blip.Value{}
261 mut i := 0
262 for i < args.len {
263 keys << keyword_of(args[i], form)!
264 values << args[i + 1]
265 i += 2
266 }
267 return keys, values
268}
269
270// prim_path is the config's (path ...) form: root, db, log, gpg, cache, hook,
271// and :syslog true for pacman.conf's UseSyslog
272fn prim_path(args []blip.Value) !blip.Value {
273 keys, values := keyword_args('path', args)!
274 mut i := 0
275 for i < keys.len {
276 match keys[i] {
277 'root' {
278 root_path = dir_path('path :root', str_of(values[i], 'path :root')!)!
279 }
280 'db' {
281 db_path = dir_path('path :db', str_of(values[i], 'path :db')!)!
282 }
283 'log' {
284 cfg_logfile = str_of(values[i], 'path :log')!
285 }
286 'syslog' {
287 cfg_syslog = bool_of(values[i], 'path :syslog')!
288 }
289 'gpg' {
290 cfg_gpgdir = dir_path('path :gpg', str_of(values[i], 'path :gpg')!)!
291 }
292 'cache' {
293 dirs := strs_of(values[i], 'path :cache')!
294 cfg_cachedirs = []string{}
295 for dir in dirs {
296 cfg_cachedirs << dir_path('path :cache', dir)!
297 }
298 }
299 'hook' {
300 dirs := strs_of(values[i], 'path :hook')!
301 cfg_hookdirs = []string{}
302 for dir in dirs {
303 cfg_hookdirs << dir_path('path :hook', dir)!
304 }
305 }
306 'build' {
307 d := str_of(values[i], 'path :build')!
308 if d == '' {
309 return error('config: path :build must not be empty')
310 }
311 pkgbuild_dir = d
312 }
313 else {
314 return error('config: path has no key :${keys[i]}')
315 }
316 }
317 i++
318 }
319 return blip.nil_value()
320}
321
322// prim_pkg is the config's (pkg ...) form: arch, hold, ignore, and pacman.conf's
323// IgnoreGroup, NoUpgrade and NoExtract as :ignoregroup, :noupgrade and
324// :noextract, each a list, e.g. (pkg :noextract ["usr/share/doc/*"])
325fn prim_pkg(args []blip.Value) !blip.Value {
326 keys, values := keyword_args('pkg', args)!
327 mut i := 0
328 for i < keys.len {
329 match keys[i] {
330 'arch' {
331 a := str_of(values[i], 'pkg :arch')!
332 // it fills the $arch of every server url and is the one
333 // architecture libalpm installs for: one plain word
334 if a == '' || a.contains('/') || a.fields().len != 1 || a.fields()[0] != a {
335 return error('config: pkg :arch must be one plain word, such as x86_64')
336 }
337 arch = a
338 }
339 'hold' {
340 cfg_hold = strs_of(values[i], 'pkg :hold')!
341 }
342 'ignore' {
343 cfg_ignore = strs_of(values[i], 'pkg :ignore')!
344 }
345 'ignoregroup' {
346 cfg_ignore_groups = strs_of(values[i], 'pkg :ignoregroup')!
347 }
348 'noupgrade' {
349 cfg_noupgrade = strs_of(values[i], 'pkg :noupgrade')!
350 }
351 'noextract' {
352 cfg_noextract = strs_of(values[i], 'pkg :noextract')!
353 }
354 else {
355 return error('config: pkg has no key :${keys[i]}')
356 }
357 }
358 i++
359 }
360 return blip.nil_value()
361}
362
363// prim_network is the config's (network ...) form: parallel, protocols, user,
364// siglevel, :disable-timeout true for pacman.conf's DisableDownloadTimeout, and
365// :disable-sandbox true for its DisableSandbox
366fn prim_network(args []blip.Value) !blip.Value {
367 keys, values := keyword_args('network', args)!
368 mut i := 0
369 for i < keys.len {
370 match keys[i] {
371 'parallel' {
372 n := int_of(values[i], 'network :parallel')!
373 if n < 1 {
374 return error('config: network :parallel must be at least 1')
375 }
376 parallel_downloads = n
377 }
378 'protocols' {
379 protos := strs_of(values[i], 'network :protocols')!
380 if protos.len == 0 {
381 return error('config: network :protocols needs at least one, https or http')
382 }
383 // a scheme no mirror is listed under would filter every
384 // mirror out without a word
385 for proto in protos {
386 if proto !in ['https', 'http'] {
387 return error('config: network :protocols takes https and http, not "${proto}"')
388 }
389 }
390 cfg_protocols = protos.clone()
391 }
392 'user' {
393 download_user = str_of(values[i], 'network :user')!
394 }
395 'siglevel' {
396 cfg_siglevel = siglevel_of(values[i], 'network :siglevel')!
397 }
398 'disable-timeout' {
399 cfg_disable_timeout = bool_of(values[i], 'network :disable-timeout')!
400 }
401 'disable-sandbox' {
402 cfg_disable_sandbox = bool_of(values[i], 'network :disable-sandbox')!
403 }
404 else {
405 return error('config: network has no key :${keys[i]}')
406 }
407 }
408 i++
409 }
410 return blip.nil_value()
411}
412
413// prim_rank is the config's (rank ...) form: parallel and timeout for the
414// mirror ranking. the parallelism falls back to the network's parallel when
415// the rank form does not set its own. :top is how many mirrors are answered,
416// :completion (0 to 1) and :max-delay (seconds) what a mirror must report to
417// be probed, :candidates how many get the speed test, :retest how many of
418// the fastest are timed twice, :dir where rank -w writes
419fn prim_rank(args []blip.Value) !blip.Value {
420 keys, values := keyword_args('rank', args)!
421 mut i := 0
422 for i < keys.len {
423 match keys[i] {
424 'parallel' {
425 n := int_of(values[i], 'rank :parallel')!
426 if n < 1 {
427 return error('config: rank :parallel must be at least 1')
428 }
429 rank_parallel = n
430 }
431 'timeout' {
432 n := int_of(values[i], 'rank :timeout')!
433 if n < 1 {
434 return error('config: rank :timeout must be at least 1')
435 }
436 rank_timeout = n
437 }
438 'top' {
439 rank_top = count_of(values[i], 'rank :top', 1)!
440 }
441 'dir' {
442 d := str_of(values[i], 'rank :dir')!
443 if !d.starts_with('/') {
444 return error('config: rank :dir must be an absolute path')
445 }
446 rank_dir = d.trim_right('/')
447 }
448 'candidates' {
449 rank_speed_candidates = count_of(values[i], 'rank :candidates', 1)!
450 }
451 'retest' {
452 rank_retest = count_of(values[i], 'rank :retest', 0)!
453 }
454 'completion' {
455 rank_min_completion = ratio_of(values[i], 'rank :completion')!
456 }
457 'max-delay' {
458 rank_max_delay = i64(count_of(values[i], 'rank :max-delay', 0)!)
459 }
460 else {
461 return error('config: rank has no key :${keys[i]}')
462 }
463 }
464 i++
465 }
466 return blip.nil_value()
467}
468
469// prim_repo is the config's (repo ...) form: a repo's name, its type ('sync',
470// or 'pkgbuild', a site to build from) and the mirrors it is fetched
471// from, with $repo and $arch left as placeholders
472// :usage is pacman.conf's Usage: a list of sync, search, install, upgrade
473// and all; every use when it is left out
474fn prim_repo(args []blip.Value) !blip.Value {
475 keys, values := keyword_args('repo', args)!
476 mut repo := CfgRepo{
477 kind: 'sync'
478 }
479 mut i := 0
480 for i < keys.len {
481 match keys[i] {
482 'name' {
483 rname := str_of(values[i], 'repo :name')!
484 repo = CfgRepo{
485 ...repo
486 name: rname
487 }
488 }
489 'type' {
490 rkind := str_of(values[i], 'repo :type')!
491 if rkind !in ['sync', 'pkgbuild'] {
492 return error("config: repo :type is 'sync' or 'pkgbuild', not '${rkind}'")
493 }
494 repo = CfgRepo{
495 ...repo
496 kind: rkind
497 }
498 }
499 'src' {
500 rservers := strs_of(values[i], 'repo :src')!
501 if rservers.len == 0 {
502 return error('config: repo :src needs at least one url')
503 }
504 for server in rservers {
505 if server == '' {
506 return error('config: repo :src has an empty url in it')
507 }
508 }
509 repo = CfgRepo{
510 ...repo
511 servers: rservers
512 }
513 }
514 'usage' {
515 rusage := usage_of(values[i], 'repo :usage')!
516 repo = CfgRepo{
517 ...repo
518 usage: rusage
519 }
520 }
521 else {
522 return error('config: repo has no key :${keys[i]}')
523 }
524 }
525 i++
526 }
527 if repo.name == '' {
528 return error('config: repo needs a :name')
529 }
530 // libalpm refuses a second db of a name, and 'local' is its own db's:
531 // said here, by name, instead of late and from inside a mode
532 if repo.name == 'local' {
533 return error('config: a repo cannot be named local, the installed packages are')
534 }
535 if cfg_repos.any(it.name == repo.name) {
536 return error('config: repo ${repo.name} is defined twice')
537 }
538 if repo.kind == 'sync' && repo.servers.len == 0 {
539 return error('config: a sync repo takes at least one :src')
540 }
541 if repo.kind == 'pkgbuild' && repo.servers.len != 1 {
542 return error('config: a pkgbuild repo takes one :src, the site to build from')
543 }
544 cfg_repos << repo
545 return blip.nil_value()
546}
547
548// pkgbuild_repos are the configured pkgbuild repos, in config order. the
549// --pkgbuild flags search and build from all of them, each under its own name
550fn pkgbuild_repos() []CfgRepo {
551 return cfg_repos.filter(it.kind == 'pkgbuild')
552}
553
554// prim_pkgbuild is the config's (pkgbuild ...) form: makepkg, depth, and
555// timeout, the seconds one lookup of a pkgbuild repo may take. where the
556// build happens is path :build
557fn prim_pkgbuild(args []blip.Value) !blip.Value {
558 keys, values := keyword_args('pkgbuild', args)!
559 mut i := 0
560 for i < keys.len {
561 match keys[i] {
562 'makepkg' {
563 m := str_of(values[i], 'pkgbuild :makepkg')!
564 if m == '' {
565 return error('config: pkgbuild :makepkg must not be empty')
566 }
567 pkgbuild_makepkg = m
568 }
569 'depth' {
570 n := int_of(values[i], 'pkgbuild :depth')!
571 if n < 1 {
572 return error('config: pkgbuild :depth must be at least 1')
573 }
574 pkgbuild_depth = n
575 }
576 'timeout' {
577 pkgbuild_rpc_timeout = count_of(values[i], 'pkgbuild :timeout', 1)!
578 }
579 else {
580 return error('config: pkgbuild has no key :${keys[i]}')
581 }
582 }
583 i++
584 }
585 return blip.nil_value()
586}
587
588// option_flags are the mode flags (options ...) can turn on for every run,
589// by the config's key: each names the field the modes' flag structs keep it
590// in, so a mode that has no such flag is simply not touched
591const option_flags = {
592 'noconfirm': 'noconfirm'
593 'nopkgbuildconfirm': 'no_pkgbuild_confirm'
594 'needed': 'needed'
595 'no-upgrade-deps': 'no_upgrade_deps'
596 'quiet': 'quiet'
597 'keep-current': 'keep_current'
598 'fuzzy': 'fuzzy'
599 'disable-timeout': 'disable_timeout'
600}
601
602// opt_flags holds the fields of option_flags the config turned on;
603// opt_color is options :color, empty when the config names none
604__global opt_flags = map[string]bool{}
605__global opt_color = ''
606
607// prim_options is the config's (options ...) form: root, the command vpac
608// gets root with (privilege.v); color, the --color a run starts from;
609// verbose, the verbose log of a run's housekeeping failures (--verbose);
610// sync-age, the hours after which the sync dbs are called stale (0: never);
611// suggest, how close (0 to 1) a name must be to be offered for a typo; and
612// the mode flags of option_flags, true or false
613fn prim_options(args []blip.Value) !blip.Value {
614 keys, values := keyword_args('options', args)!
615 mut i := 0
616 for i < keys.len {
617 match keys[i] {
618 'root' {
619 r := str_of(values[i], 'options :root')!
620 if r.trim_space() == '' {
621 return error('config: options :root must not be empty')
622 }
623 root_provider = r
624 }
625 'color' {
626 c := str_of(values[i], 'options :color')!
627 if c !in ['auto', 'always', 'never'] {
628 return error('config: options :color takes auto, always or never, not "${c}"')
629 }
630 opt_color = c
631 }
632 'sync-age' {
633 // hours; 0 never warns
634 sync_max_age = i64(count_of(values[i], 'options :sync-age', 0)!) * 3600
635 }
636 'suggest' {
637 suggest_thold = ratio_of(values[i], 'options :suggest')!
638 }
639 'verbose' {
640 // the verbose log for every run, as --verbose for one
641 cfg_verbose = bool_of(values[i], 'options :verbose')!
642 }
643 else {
644 field := option_flags[keys[i]] or {
645 return error('config: options has no key :${keys[i]}')
646 }
647 // only what is on is held: a false takes back an earlier
648 // true (an --eval over the file) and leaves no entry behind
649 if bool_of(values[i], 'options :${keys[i]}')! {
650 opt_flags[field] = true
651 } else {
652 opt_flags.delete(field)
653 }
654 }
655 }
656 i++
657 }
658 return blip.nil_value()
659}
660
661// prim_search is the config's (search ...) form: fields, the columns of a
662// listing when --fields names none, and thold, the fuzzy threshold
663fn prim_search(args []blip.Value) !blip.Value {
664 keys, values := keyword_args('search', args)!
665 mut i := 0
666 for i < keys.len {
667 match keys[i] {
668 'fields' {
669 names := strs_of(values[i], 'search :fields')!
670 if names.len == 0 {
671 return error('config: search :fields needs at least one field')
672 }
673 cfg_search_fields = parse_fields(names.join(','), []string{}) or {
674 return error('config: search :fields: ${err.msg()}')
675 }
676 }
677 'thold' {
678 cfg_search_thold = ratio_of(values[i], 'search :thold')!
679 }
680 else {
681 return error('config: search has no key :${keys[i]}')
682 }
683 }
684 i++
685 }
686 return blip.nil_value()
687}
688
689// prim_clean is the config's (clean ...) form: keep, the versions of every
690// package the cache keeps when -k names none
691fn prim_clean(args []blip.Value) !blip.Value {
692 keys, values := keyword_args('clean', args)!
693 mut i := 0
694 for i < keys.len {
695 match keys[i] {
696 'keep' {
697 cfg_clean_keep = count_of(values[i], 'clean :keep', 0)!
698 }
699 else {
700 return error('config: clean has no key :${keys[i]}')
701 }
702 }
703 i++
704 }
705 return blip.nil_value()
706}
707
708// prim_tree is the config's (tree ...) form: depth, how deep a tree is
709// drawn when -d names none
710fn prim_tree(args []blip.Value) !blip.Value {
711 keys, values := keyword_args('tree', args)!
712 mut i := 0
713 for i < keys.len {
714 match keys[i] {
715 'depth' {
716 cfg_tree_depth = count_of(values[i], 'tree :depth', 0)!
717 }
718 else {
719 return error('config: tree has no key :${keys[i]}')
720 }
721 }
722 i++
723 }
724 return blip.nil_value()
725}
726
727// prim_color is the config's (color ...) form, the theme: each key is a role
728// of default_theme, each value one style or a list of them out of
729// style_names, e.g. (color :version "cyan" :warning ["bold" "magenta"])
730fn prim_color(args []blip.Value) !blip.Value {
731 keys, values := keyword_args('color', args)!
732 mut i := 0
733 for i < keys.len {
734 if keys[i] !in theme {
735 return error('config: color has no role :${keys[i]}, the roles are: ${default_theme().keys().join(', ')}')
736 }
737 styles := strs_of(values[i], 'color :${keys[i]}')!
738 for style in styles {
739 if style !in style_names {
740 return error('config: color :${keys[i]} takes ${style_names.join(', ')}, not "${style}"')
741 }
742 }
743 theme[keys[i]] = styles.clone()
744 i++
745 }
746 return blip.nil_value()
747}
748
749// prim_mirrorlist is the config's (mirrorlist ...) form: an os for the
750// ranker, new or one of its own redefined. :name is what rank is asked for
751// (and what /etc/os-release is matched against), :repo the repo whose db the
752// speed test pulls, and the mirrors come from one of :status, a mirror
753// status json api as arch publishes, or :list, a Server = mirrorlist at a
754// url or an absolute path
755fn prim_mirrorlist(args []blip.Value) !blip.Value {
756 keys, values := keyword_args('mirrorlist', args)!
757 mut name := ''
758 mut status := ''
759 mut list := ''
760 mut repo := ''
761 mut i := 0
762 for i < keys.len {
763 match keys[i] {
764 'name' { name = str_of(values[i], 'mirrorlist :name')! }
765 'status' { status = str_of(values[i], 'mirrorlist :status')! }
766 'list' { list = str_of(values[i], 'mirrorlist :list')! }
767 'repo' { repo = str_of(values[i], 'mirrorlist :repo')! }
768 else { return error('config: mirrorlist has no key :${keys[i]}') }
769 }
770 i++
771 }
772 if name == '' || name.contains('/') || name.starts_with('.') || name.starts_with('-')
773 || name.fields().len != 1 || name.fields()[0] != name {
774 return error('config: mirrorlist needs a :name, one plain word')
775 }
776 if repo == '' {
777 return error('config: mirrorlist ${name} needs a :repo, the repo whose db is timed')
778 }
779 if (status == '') == (list == '') {
780 return error('config: mirrorlist ${name} takes one of :status and :list')
781 }
782 if status != '' && !status.starts_with('https://') && !status.starts_with('http://') {
783 return error('config: mirrorlist ${name} :status must be an http or https url')
784 }
785 if list != '' && !list.starts_with('https://') && !list.starts_with('http://')
786 && !list.starts_with('/') {
787 return error('config: mirrorlist ${name} :list must be a url or an absolute path')
788 }
789 rank_oses[name] = RankOs{
790 status_json: status
791 mirrorlist: list
792 repo: repo
793 }
794 return blip.nil_value()
795}
796
797// cell_of reads one piece of a bar graphic: text of exactly one rune, or of
798// at most one when it may be left out
799fn cell_of(v blip.Value, what string, may_be_empty bool) !string {
800 text := str_of(v, what)!
801 n := text.runes().len
802 if n > 1 || (n == 0 && !may_be_empty) {
803 return error('config: ${what} must be one character')
804 }
805 return text
806}
807
808// prim_progress is the config's (progress ...) form, the bars: style
809// ('classic' or 'block'); the graphic's pieces start, end, fill, head and
810// empty; length in cells (0 fills the terminal); percent, eta, elapsed and
811// rate, true or false; delay, the milliseconds between redraws
812fn prim_progress(args []blip.Value) !blip.Value {
813 keys, values := keyword_args('progress', args)!
814 mut i := 0
815 for i < keys.len {
816 what := 'progress :${keys[i]}'
817 match keys[i] {
818 'style' {
819 s := str_of(values[i], what)!
820 if s !in ['classic', 'block'] {
821 return error('config: ${what} is classic or block, not "${s}"')
822 }
823 cfg_progress.style = s
824 }
825 'start', 'end' {
826 cfg_progress.parts[keys[i]] = str_of(values[i], what)!
827 }
828 'fill', 'empty' {
829 cfg_progress.parts[keys[i]] = cell_of(values[i], what, false)!
830 }
831 'head' {
832 cfg_progress.parts[keys[i]] = cell_of(values[i], what, true)!
833 }
834 'length' {
835 cfg_progress.length = count_of(values[i], what, 0)!
836 }
837 'percent' {
838 cfg_progress.percent = bool_of(values[i], what)!
839 }
840 'eta' {
841 cfg_progress.eta = bool_of(values[i], what)!
842 }
843 'elapsed' {
844 cfg_progress.elapsed = bool_of(values[i], what)!
845 }
846 'rate' {
847 cfg_progress.rate = bool_of(values[i], what)!
848 }
849 'delay' {
850 cfg_progress.delay = count_of(values[i], what, 1)!
851 }
852 else {
853 return error('config: progress has no key :${keys[i]}')
854 }
855 }
856 i++
857 }
858 return blip.nil_value()
859}
860
861// prim_spinner is the config's (spinner ...) form: frames, a set by name
862// (spinner_sets) or a list of frames of one's own; interval, the
863// milliseconds a frame stays; done, what a finished step shows in place of
864// the animation; elapsed, whether the time taken is shown
865fn prim_spinner(args []blip.Value) !blip.Value {
866 keys, values := keyword_args('spinner', args)!
867 mut i := 0
868 for i < keys.len {
869 what := 'spinner :${keys[i]}'
870 match keys[i] {
871 'frames' {
872 if values[i].tag == .string {
873 name := values[i].as_string()
874 cfg_progress.frames = spinner_frames_named(name) or {
875 return error('config: ${what} knows ${spinner_sets.join(', ')}, not "${name}"; a list gives frames of your own')
876 }
877 } else {
878 frames := strs_of(values[i], what)!
879 if frames.len == 0 {
880 return error('config: ${what} needs at least one frame')
881 }
882 cfg_progress.frames = frames.clone()
883 }
884 }
885 'interval' {
886 cfg_progress.interval = count_of(values[i], what, 1)!
887 }
888 'done' {
889 cfg_progress.done = str_of(values[i], what)!
890 }
891 'elapsed' {
892 cfg_progress.timed = bool_of(values[i], what)!
893 }
894 else {
895 return error('config: spinner has no key :${keys[i]}')
896 }
897 }
898 i++
899 }
900 return blip.nil_value()
901}
902
903// prim_array_append is (array-append! dst src): every element of src pushed
904// onto dst. it is std.lip's, provided by the host so the config's mirror lists
905// are fillable without vpac loading std.lip
906fn prim_array_append(args []blip.Value) !blip.Value {
907 if args.len != 2 {
908 return error('config: array-append! needs an array and an array of values')
909 }
910 if args[0].tag !in [.vector, .array] {
911 return error('config: array-append! the first argument must be an array')
912 }
913 match args[1].tag {
914 .vector, .array {
915 for item in args[1].as_vector().data {
916 args[0].as_vector().push(item)
917 }
918 }
919 .emptylist {}
920 else {
921 return error('config: array-append! the second argument must be an array')
922 }
923 }
924 return args[0]
925}
926
927// reset_config puts every config global back at its declared default, the
928// values the hardcoded vpac used. load_config runs it first, so a second
929// load in one process neither duplicates the repos nor keeps settings the
930// new file does not name; a failed load can leave values behind, and the
931// next load starts clean again
932fn reset_config() {
933 root_path = '/'
934 root_provider = 'sudo'
935 opt_flags = map[string]bool{}
936 opt_color = ''
937 cfg_verbose = false
938 sync_max_age = i64(24 * 60 * 60)
939 suggest_thold = 0.85
940 pkgbuild_rpc_timeout = 10
941 rank_min_completion = 1.0
942 rank_max_delay = i64(86400)
943 rank_speed_candidates = 40
944 rank_retest = 5
945 rank_top = 10
946 cfg_search_fields = search_default_fields.clone()
947 cfg_search_thold = 0.9
948 cfg_clean_keep = 0
949 cfg_tree_depth = 0
950 theme = default_theme()
951 rank_oses = default_rank_oses()
952 rank_dir = '/etc/vpac.d/mirrors'
953 cfg_progress = ProgressCfg{}
954 db_path = '/var/lib/pacman/'
955 arch = 'x86_64'
956 parallel_downloads = 3
957 rank_parallel = 0
958 rank_timeout = 10
959 pkgbuild_makepkg = 'makepkg -f'
960 pkgbuild_depth = 1
961 download_user = 'alpm'
962 pkgbuild_dir = '.cache/vpac/pkgbuild'
963 cfg_cachedirs = ['/var/cache/pacman/pkg/']
964 cfg_hookdirs = ['/etc/pacman.d/hooks/']
965 cfg_logfile = ''
966 cfg_gpgdir = '/etc/pacman.d/gnupg/'
967 cfg_protocols = ['https']
968 cfg_siglevel = alpm.SigLevel.package | .package_optional | .database | .database_optional
969 cfg_hold = []string{}
970 cfg_ignore = []string{}
971 cfg_ignore_groups = []string{}
972 cfg_noupgrade = []string{}
973 cfg_noextract = []string{}
974 cfg_disable_timeout = false
975 cfg_disable_sandbox = false
976 cfg_syslog = false
977 cfg_repos = []CfgRepo{}
978}
979
980// load_config reads the config file -- the one --config names, else
981// config_path -- and evaluates it in a machine that provides the config
982// forms. the file is required: vpac has no defaults to fall back to once its
983// repos, paths and mirror lists live in the config. the --eval snippets run
984// after it, in the same machine, so they can extend or override the file for
985// this run. a file that does not parse, or a form with the wrong keys, stops
986// vpac, because running on silently could act on the wrong database
987fn load_config(chosen string, evals []string) ! {
988 reset_config()
989 path := if chosen != '' { chosen } else { config_path }
990 if !os.exists(path) {
991 return error('${path} is required: write it, starting with (require ...) for each part')
992 }
993 mut m := machine.new_standalone(&QuietConfigHost{})
994 m.prims['path'] = prim_path
995 m.prims['pkg'] = prim_pkg
996 m.prims['network'] = prim_network
997 m.prims['rank'] = prim_rank
998 m.prims['pkgbuild'] = prim_pkgbuild
999 m.prims['options'] = prim_options
1000 m.prims['search'] = prim_search
1001 m.prims['clean'] = prim_clean
1002 m.prims['tree'] = prim_tree
1003 m.prims['color'] = prim_color
1004 m.prims['mirrorlist'] = prim_mirrorlist
1005 m.prims['progress'] = prim_progress
1006 m.prims['spinner'] = prim_spinner
1007 m.prims['repo'] = prim_repo
1008 m.prims['array-append!'] = prim_array_append
1009 m.load(path) or {
1010 return error('config: ${err.msg()}')
1011 }
1012 for code in evals {
1013 m.run_str(code) or {
1014 return error('config --eval: ${err.msg()}')
1015 }
1016 }
1017}
1018
1019// check_hold refuses to remove a package the config holds, as pacman does for
1020// HoldPkg. libalpm has no option for it, so it is a frontend check
1021fn check_hold(names []string) ! {
1022 for name in names {
1023 if name in cfg_hold {
1024 return error('${name} is held by the config: remove it from pkg :hold first')
1025 }
1026 }
1027}
1028