vpac / src / cli.v
753 lines · 718 sloc · 21.36 KB · 3609dfbd82867dc1034a443f8f9ced529ddbbedd
Raw
1@[has_globals]
2module main
3
4import flag
5import os
6import vmakepkg
7
8struct ConfigSearch {
9pub mut:
10 show_help bool @[long: help; short: h]
11 noconfirm bool @[long: noconfirm]
12 local bool @[long: local; short: l]
13 remote bool @[long: remote; short: r]
14 pkgbuild bool @[long: pkgbuild; short: b]
15 quiet bool @[long: quiet; short: q]
16 fuzzy bool @[long: fuzzy; short: f]
17 thold f64 = 0.9 @[long: thold; short: t]
18 sync_dbs bool @[long: sync; short: s]
19 deps bool @[long: deps; short: d]
20 explicit bool @[long: explicit; short: e]
21 foreign bool @[long: foreign; short: m]
22 native bool @[long: native; short: n]
23 unrequired bool @[long: unrequired]
24 // --unrequired given twice is pacman's -tt; the flag parser counts short
25 // flags only, so parse_mode counts the long one itself
26 unrequired_level int @[ignore]
27 upgrades bool @[long: upgrades; short: u]
28 groups bool @[long: groups]
29 groups_level int @[only: g; repeats]
30 installed bool @[long: installed; short: i]
31 fields string @[long: fields; short: F]
32 query []string @[tail]
33}
34
35struct ConfigInstall {
36pub mut:
37 show_help bool @[long: help; short: h]
38 noconfirm bool @[long: noconfirm]
39 no_upgrade_deps bool @[long: no_upgrade_deps]
40 pkgbuild bool @[long: pkgbuild; short: b]
41 no_pkgbuild_confirm bool @[long: nopkgbuildconfirm]
42 download_only bool @[long: download_only; short: w]
43 print_only bool @[long: print; short: p]
44 needed bool @[long: needed]
45 asdeps bool @[long: asdeps]
46 asexplicit bool @[long: asexplicit]
47 dbonly bool @[long: dbonly]
48 nodeps bool @[long: nodeps]
49 nodeps_level int @[only: d; repeats]
50 overwrite []string @[long: overwrite]
51 ignore []string @[long: ignore]
52 ignoregroup []string @[long: ignoregroup]
53 assume_installed []string @[long: assume_installed]
54 disable_timeout bool @[long: disable_timeout]
55 query []string @[tail]
56}
57
58// trans_options are the transaction options a command line carries:
59// install's and upgrade's are the same four flags, read through one body
60fn trans_options[T](c T) TransOptions {
61 return TransOptions{
62 overwrite: c.overwrite
63 ignore: c.ignore
64 ignoregroup: c.ignoregroup
65 assume_installed: c.assume_installed
66 }
67}
68
69struct ConfigInfo {
70pub mut:
71 show_help bool @[long: help; short: h]
72 noconfirm bool @[long: noconfirm]
73 fields string @[long: fields; short: F]
74 changelog bool @[long: changelog; short: c]
75 file bool @[long: file; short: p]
76 query []string @[tail]
77}
78
79struct ConfigWhich {
80pub mut:
81 show_help bool @[long: help; short: h]
82 query []string @[tail]
83}
84
85struct ConfigRank {
86pub mut:
87 show_help bool @[long: help; short: h]
88 stdin bool @[long: stdin]
89 top int = 10 @[long: top; short: n]
90 mirrorlist bool @[long: mirrorlist; short: m]
91 output string @[long: output; short: o]
92 path string @[long: path]
93 write bool @[long: write; short: w]
94 query []string @[tail]
95}
96
97struct ConfigVerify {
98pub mut:
99 show_help bool @[long: help; short: h]
100 checksums bool @[long: checksums]
101 checksums_level int @[only: k; repeats]
102 full bool @[long: full]
103 db bool @[long: db]
104 db_level int @[only: D; repeats]
105 query []string @[tail]
106}
107
108struct ConfigFind {
109pub mut:
110 show_help bool @[long: help; short: h]
111 noconfirm bool @[long: noconfirm]
112 refresh bool @[long: refresh; short: y]
113 list bool @[long: list; short: l]
114 quiet bool @[long: quiet; short: q]
115 regex bool @[long: regex; short: x]
116 machinereadable bool @[long: machinereadable]
117 repos string @[long: repos; short: r]
118 query []string @[tail]
119}
120
121struct ConfigMark {
122pub mut:
123 show_help bool @[long: help; short: h]
124 noconfirm bool @[long: noconfirm]
125 reason string @[long: reason; short: r]
126 query []string @[tail]
127}
128
129struct ConfigRemove {
130pub mut:
131 show_help bool @[long: help; short: h]
132 noconfirm bool @[long: noconfirm]
133 print_only bool @[long: print; short: p]
134 recursive bool @[long: recursive]
135 recursive_level int @[only: s; repeats]
136 unneeded bool @[long: unneeded; short: u]
137 cascade bool @[long: cascade; short: c]
138 nosave bool @[long: nosave; short: n]
139 dbonly bool @[long: dbonly]
140 nodeps bool @[long: nodeps]
141 nodeps_level int @[only: d; repeats]
142 assume_installed []string @[long: assume_installed]
143 query []string @[tail]
144}
145
146struct ConfigUpgrade {
147pub mut:
148 show_help bool @[long: help; short: h]
149 noconfirm bool @[long: noconfirm]
150 print_only bool @[long: print; short: p]
151 sync_dbs bool @[long: sync; short: s]
152 download_only bool @[long: download_only; short: w]
153 dbonly bool @[long: dbonly]
154 nodeps bool @[long: nodeps]
155 nodeps_level int @[only: d; repeats]
156 downgrade bool @[long: downgrade]
157 sysupgrade_level int @[only: u; repeats]
158 overwrite []string @[long: overwrite]
159 ignore []string @[long: ignore]
160 ignoregroup []string @[long: ignoregroup]
161 disable_timeout bool @[long: disable_timeout]
162 assume_installed []string @[long: assume_installed]
163}
164
165struct ConfigFiles {
166pub mut:
167 show_help bool @[long: help; short: h]
168 noconfirm bool @[long: noconfirm]
169 query []string @[tail]
170}
171
172struct ConfigOwner {
173pub mut:
174 show_help bool @[long: help; short: h]
175 quiet bool @[long: quiet; short: q]
176 query []string @[tail]
177}
178
179struct ConfigOrphans {
180pub mut:
181 show_help bool @[long: help; short: h]
182 // pacman's -Qdt and -Qdtt: twice lists the dependencies something still
183 // names as optional too
184 level int @[only: t; repeats]
185}
186
187struct ConfigClean {
188pub mut:
189 show_help bool @[long: help; short: h]
190 noconfirm bool @[long: noconfirm]
191 print_only bool @[long: print; short: p]
192 all bool @[long: all; short: a]
193 keep int @[long: keep; short: k]
194 keep_current bool @[long: keep_current]
195 // pacman's -Sc and -Scc: once is the default clean, twice every archive
196 level int @[only: c; repeats]
197}
198
199struct ConfigTree {
200pub mut:
201 show_help bool @[long: help; short: h]
202 noconfirm bool @[long: noconfirm]
203 reverse bool @[long: reverse; short: r]
204 optional bool @[long: optional; short: o]
205 depth int @[long: depth; short: d]
206 query []string @[tail]
207}
208
209struct ConfigAutoRemove {
210pub mut:
211 show_help bool @[long: help; short: h]
212 noconfirm bool @[long: noconfirm]
213}
214
215@[noreturn]
216fn print_err(e string) {
217 if ipc_on() {
218 // an error before the run started ends it all the same: the channel
219 // opens for it (once: ipc_start is guarded), so every stream starts
220 // with its hello and ends with its exit
221 ipc_start()
222 emit(ErrorEvent{
223 msg: e
224 })
225 } else {
226 eprintln(error_text(e))
227 }
228 end_run(1)
229}
230
231// error_text is an error line the way vpac prints them, 'error: ' in bold red
232fn error_text(e string) string {
233 return erole('error', 'error: ') + e
234}
235
236// failed_targets counts the targets a query reported bad and skipped. like
237// pacman's queries, it goes on with the rest, and main exits 1 at the end
238// when any failed
239__global failed_targets = 0
240
241// target_error reports one bad target of a query that goes on with the next
242fn target_error(e string) {
243 failed_targets++
244 if ipc_on() {
245 emit(ErrorEvent{
246 msg: e
247 target: true
248 })
249 return
250 }
251 os.flush()
252 eprintln(error_text(e))
253}
254
255// need_query stops a command that acts on targets when none were given
256fn need_query(query []string, what string) ! {
257 if query.len == 0 {
258 return error('no ${what} given')
259 }
260}
261
262// scan_globals collects vpac's own flags, wherever they stand in the command
263// line: --config chooses the config file, --eval extends the config with blip
264// code run after it. both repeatable, both also usable as --flag=value. the
265// flags are stripped from the args (the program name stays first, the mode
266// second), so a mode never sees them; escalation still gets the original
267// args, so the root process reads the same config and evals
268fn scan_globals(args []string) !(string, []string, []string) {
269 // the frontend is settled before any other flag can fail: an error is
270 // told over the channel whenever --ui ipc is on the command line, not
271 // only when it happens to come before the flag that is wrong
272 if kind := scan_ui(args) {
273 ui_kind = kind
274 }
275 mut chosen := ''
276 mut evals := []string{}
277 mut rest := [args[0]]
278 mut i := 1
279 for i < args.len {
280 arg := args[i]
281 if arg == '--config' || arg == '--eval' {
282 if i + 1 >= args.len {
283 return error('${arg} needs a value')
284 }
285 value := args[i + 1]
286 if value == '' {
287 return error('${arg} needs a value')
288 }
289 if arg == '--config' {
290 chosen = value
291 } else {
292 evals << value
293 }
294 i += 2
295 } else if arg.starts_with('--config=') {
296 chosen = arg.all_after('=')
297 if chosen == '' {
298 return error('--config needs a file')
299 }
300 i++
301 } else if arg.starts_with('--eval=') {
302 expr := arg.all_after('=')
303 if expr == '' {
304 return error('--eval needs blip code')
305 }
306 evals << expr
307 i++
308 } else if arg == '--color' || arg.starts_with('--color=') {
309 // pacman's --color: auto (the default) styles a terminal only
310 mut value := arg.all_after('=')
311 if arg == '--color' {
312 if i + 1 >= args.len {
313 return error('--color needs a value: auto, always or never')
314 }
315 i++
316 value = args[i]
317 }
318 if value !in ['auto', 'always', 'never'] {
319 return error('--color takes auto, always or never, not "${value}"')
320 }
321 color_flag = value
322 color_given = true
323 i++
324 } else if arg == '--verbose' {
325 // the verbose log: the housekeeping failures a run goes on from
326 verbose_flag = true
327 i++
328 } else if arg == '--ui' || arg.starts_with('--ui=') {
329 // the frontend: tty, a person at a terminal, or ipc, a program
330 // speaking json lines (ipc.v)
331 mut value := arg.all_after('=')
332 if arg == '--ui' {
333 if i + 1 >= args.len {
334 return error('--ui needs a value: tty or ipc')
335 }
336 i++
337 value = args[i]
338 }
339 if value !in ['tty', 'ipc'] {
340 return error('--ui takes tty or ipc, not "${value}"')
341 }
342 ui_kind = value
343 i++
344 } else {
345 rest << arg
346 i++
347 }
348 }
349 return chosen, evals, rest
350}
351
352// global_value_flags are vpac's own flags that take the next argument as
353// their value when spelled without '='
354const global_value_flags = ['--config', '--eval', '--color', '--ui']
355
356// scan_ui finds the --ui the command line settles on — the last valid one,
357// as scan_globals lets the last win — stepping over the values of the other
358// globals the way scan_globals reads them, so an --eval whose code is the
359// text '--ui' is not taken for the flag. none when there is no valid one:
360// a bad value is scan_globals' error to give, on the terminal
361fn scan_ui(args []string) ?string {
362 mut found := ?string(none)
363 mut i := 1
364 for i < args.len {
365 arg := args[i]
366 if arg.starts_with('--ui=') {
367 value := arg.all_after('=')
368 if value in ['tty', 'ipc'] {
369 found = value
370 }
371 } else if arg == '--ui' && i + 1 < args.len && args[i + 1] in ['tty', 'ipc'] {
372 found = args[i + 1]
373 }
374 i += if arg in global_value_flags { 2 } else { 1 }
375 }
376 return found
377}
378
379// ModeConfig is a mode's command line, parsed: which mode, with its flags
380type ModeConfig = ConfigAutoRemove
381 | ConfigBuild
382 | ConfigClean
383 | ConfigDeptest
384 | ConfigFiles
385 | ConfigFind
386 | ConfigInfo
387 | ConfigInstall
388 | ConfigMark
389 | ConfigOrphans
390 | ConfigOwner
391 | ConfigRank
392 | ConfigRemove
393 | ConfigSearch
394 | ConfigTree
395 | ConfigUpgrade
396 | ConfigVerify
397 | ConfigWhich
398
399// mode_flags reads a mode's flags into its struct, then lays the config's
400// options under them: a flag the config turns on (options :noconfirm true)
401// is on for every mode that has it, as if it stood on the command line.
402// the command line can only add to that; --eval turns one off for a run.
403// an option the mode's struct has no field for is an error
404fn mode_flags[T](args []string) !T {
405 mut c, unknown := flag.to_struct[T](args, skip: 2)!
406 // what the parser could not place is an option the mode does not have:
407 // said, as pacman says it, instead of a run that quietly leaves a
408 // mistyped flag out of a transaction
409 bad := unknown.filter(it.len > 1 && it.starts_with('-'))
410 if bad.len > 0 {
411 return error('unknown option: ${bad.map('"${it}"').join(', ')}')
412 }
413 // the rest of it are targets that stand before a flag: the parser's
414 // tail takes only the ones after the last flag, and these lead them
415 early := unknown.filter(!(it.len > 1 && it.starts_with('-')))
416 if early.len > 0 {
417 mut placed := false
418 $for field in T.fields {
419 $if field.name == 'query' {
420 mut query := early.clone()
421 query << c.query
422 c.query = query
423 placed = true
424 }
425 }
426 if !placed {
427 return error('this mode takes no targets: ${early.map('"${it}"').join(', ')}')
428 }
429 }
430 $for field in T.fields {
431 $if field.typ is bool {
432 if opt_flags[field.name] {
433 c.$(field.name) = true
434 }
435 }
436 }
437 return c
438}
439
440// flag_given is whether the command line spells a flag, by its long name or
441// its short letter: what settles that a config default steps back. a letter
442// is looked for in any bundle of short flags, so a doubt reads as given and
443// leaves the mode's own default
444fn flag_given(args []string, long string, short string) bool {
445 for a in args#[2..] {
446 if a == '--${long}' || a.starts_with('--${long}=') {
447 return true
448 }
449 if a.len > 1 && a[0] == `-` && a[1] != `-` && a.contains(short) {
450 return true
451 }
452 }
453 return false
454}
455
456// parse_mode reads the mode and its flags. it runs before any escalation, so
457// a flag that does not parse is an error the user sees before a root prompt
458fn parse_mode(args []string) !ModeConfig {
459 return match args[1] {
460 's', 'S', 'search' {
461 // a long flag given twice is the flag parser's error, so the
462 // repeats of --unrequired are counted and folded into one here
463 level := args.count(it == '--unrequired')
464 mut once := []string{cap: args.len}
465 for i, arg in args {
466 if arg == '--unrequired' && args[..i].contains(arg) {
467 continue
468 }
469 once << arg
470 }
471 mut c := mode_flags[ConfigSearch](once)!
472 if !flag_given(once, 'thold', 't') {
473 c.thold = cfg_search_thold
474 } else if c.thold < 0.0 || c.thold > 1.0 {
475 // the config's (search :thold) is held to the same range
476 return error('--thold must be between 0 and 1, not ${c.thold}')
477 }
478 c.unrequired_level = level
479 c.groups = c.groups || c.groups_level > 0
480 if !c.local && !c.remote && !c.pkgbuild {
481 // the filters only work on the installed packages; the
482 // groups are the sync dbs' unless -l asks for the local ones
483 c.local = c.filtered() && !c.groups
484 c.remote = !c.filtered() || c.groups
485 }
486 ModeConfig(c)
487 }
488 'q', 'Q', 'info' {
489 c := mode_flags[ConfigInfo](args)!
490 ModeConfig(c)
491 }
492 'w', 'W', 'which' {
493 c := mode_flags[ConfigWhich](args)!
494 ModeConfig(c)
495 }
496 'n', 'N', 'deptest' {
497 c := mode_flags[ConfigDeptest](args)!
498 ModeConfig(c)
499 }
500 'm', 'M', 'mark' {
501 c := mode_flags[ConfigMark](args)!
502 ModeConfig(c)
503 }
504 'b', 'B', 'build' {
505 c := mode_flags[ConfigBuild](args)!
506 ModeConfig(c)
507 }
508 'i', 'I', 'install' {
509 c := mode_flags[ConfigInstall](args)!
510 ModeConfig(c)
511 }
512 'r', 'R', 'remove' {
513 c := mode_flags[ConfigRemove](args)!
514 ModeConfig(c)
515 }
516 'u', 'U', 'upgrade' {
517 c := mode_flags[ConfigUpgrade](args)!
518 ModeConfig(c)
519 }
520 'l', 'L', 'files' {
521 c := mode_flags[ConfigFiles](args)!
522 ModeConfig(c)
523 }
524 'o', 'O', 'owner' {
525 c := mode_flags[ConfigOwner](args)!
526 ModeConfig(c)
527 }
528 'd', 'D', 'orphans' {
529 c := mode_flags[ConfigOrphans](args)!
530 ModeConfig(c)
531 }
532 'c', 'C', 'clean' {
533 mut c := mode_flags[ConfigClean](args)!
534 if !flag_given(args, 'keep', 'k') {
535 c.keep = cfg_clean_keep
536 }
537 ModeConfig(c)
538 }
539 't', 'T', 'tree' {
540 mut c := mode_flags[ConfigTree](args)!
541 if !flag_given(args, 'depth', 'd') {
542 c.depth = cfg_tree_depth
543 }
544 ModeConfig(c)
545 }
546 'a', 'A', 'autoremove' {
547 c := mode_flags[ConfigAutoRemove](args)!
548 ModeConfig(c)
549 }
550 'k', 'K', 'rank' {
551 mut c := mode_flags[ConfigRank](args)!
552 if !flag_given(args, 'top', 'n') {
553 c.top = rank_top
554 } else if c.top < 1 {
555 // the config's (rank :top) is held to the same floor
556 return error('--top must be at least 1, not ${c.top}')
557 }
558 ModeConfig(c)
559 }
560 'v', 'V', 'verify' {
561 c := mode_flags[ConfigVerify](args)!
562 ModeConfig(c)
563 }
564 'f', 'F', 'find' {
565 c := mode_flags[ConfigFind](args)!
566 ModeConfig(c)
567 }
568 else {
569 error('unknown subcommand: "${args[1]}"')
570 }
571 }
572}
573
574// needs_root is whether a mode runs as root: the ones that change the
575// system, except a --print preview, which changes nothing and stays the
576// user's as pacman's --print does; find -y, which writes the file dbs; and
577// rank when the file it writes is not the user's to write. rank -w writes
578// the config's mirror file under /etc, so that is known before any ranking
579fn needs_root(c ModeConfig) !bool {
580 return match c {
581 ConfigInstall { !c.print_only }
582 ConfigRemove { !c.print_only }
583 ConfigUpgrade { !c.print_only }
584 ConfigClean { !c.print_only }
585 ConfigBuild, ConfigMark, ConfigAutoRemove { true }
586 ConfigFind { c.refresh }
587 ConfigRank {
588 mut target := c.output
589 if target == '' && c.write {
590 target = rank_write_target(rank_os_name(c.query)!)
591 }
592 target != '' && !can_write(target)
593 }
594 else { false }
595 }
596}
597
598// run_mode runs a parsed mode and returns its exit status: 0, or what the
599// mode's outcome asks for
600fn run_mode(c ModeConfig) !int {
601 match c {
602 ConfigSearch {
603 search(c)!
604 }
605 ConfigInfo {
606 info(c)!
607 }
608 ConfigWhich {
609 which(c)!
610 }
611 ConfigDeptest {
612 // pacman's -T: 127 tells makepkg a dependency is missing
613 if deptest(c)!.len > 0 {
614 return 127
615 }
616 }
617 ConfigMark {
618 mark(c)!
619 }
620 ConfigBuild {
621 build_repo(c)!
622 }
623 ConfigInstall {
624 install(c)!
625 }
626 ConfigRemove {
627 remove(c)!
628 }
629 ConfigUpgrade {
630 upgrade(c)!
631 }
632 ConfigFiles {
633 files(c)!
634 }
635 ConfigOwner {
636 owner(c)!
637 }
638 ConfigOrphans {
639 orphans(c)!
640 }
641 ConfigClean {
642 clean(c)!
643 }
644 ConfigTree {
645 tree(c)!
646 }
647 ConfigAutoRemove {
648 autoremove(c)!
649 }
650 ConfigRank {
651 rank(c)!
652 }
653 ConfigVerify {
654 if verify(c)! > 0 {
655 return 1
656 }
657 }
658 ConfigFind {
659 find(c)!
660 }
661 }
662 return 0
663}
664
665fn main() {
666 // --lip-run <lip> <phase> [args...] is what a PKGBUILD generated from a
667 // PKGBUILD.lip calls back (vpac b): it runs one phase of the lip. it is no
668 // mode, reads no config and never needs root
669 if os.args.len > 3 && os.args[1] == '--lip-run' {
670 vmakepkg.lip_run_phase(os.args[2], os.args[3], os.args[4..]) or {
671 eprintln(error_text('lip: ${err.msg()}'))
672 exit(1)
673 }
674 exit(0)
675 }
676 chosen, evals, args := scan_globals(os.args) or { print_err(err.msg()) }
677 // the config comes first: it is required, and everything downstream reads
678 // it, including the escalation to root
679 load_config(chosen, evals) or { print_err(err.msg()) }
680 // the config's color is the default a --color on the command line beats
681 if !color_given && opt_color != '' {
682 color_flag = opt_color
683 }
684 // a killed run lets go of the db lock it holds (on_interrupt)
685 install_interrupt_handlers()
686 // no mode, or help: the overview. an option where the mode belongs is
687 // one no global scan took, and an error as pacman's unknown options are
688 if args.len < 2 || args[1] in ['h', 'help', '-h', '--help'] {
689 if ipc_on() {
690 ipc_start()
691 }
692 show_help(help_text())
693 end_run(0)
694 }
695 if args[1].starts_with('-') {
696 print_err('unknown option "${args[1]}" before the mode (vpac --help lists the modes)')
697 }
698 // the mode is parsed before anything else happens: a bad flag is an error
699 // here, not a panic in a root process. 'vpac <mode> -h' prints that
700 // mode's options and never runs the command; the flag parser reads the
701 // -h, so one bundled with others (-lh) counts and one that is another
702 // flag's value does not. a help request beside flags that do not parse
703 // is still answered with the help
704 config := parse_mode(args) or {
705 if args[2..].any(it == '-h' || it == '--help') {
706 mode_help(args[1])
707 }
708 print_err(err.msg())
709 }
710 if config.show_help {
711 mode_help(args[1])
712 }
713 // a mode that changes the system runs as root, through the root
714 // provider; the original command line is passed, globals included, so
715 // the root process reads the same config and evals
716 root := needs_root(config) or { print_err(err.msg()) }
717 if root {
718 reexec_as_root(os.args[1..]) or { print_err(err.msg()) }
719 }
720 // this is the process that does the work: a frontend's channel opens here
721 if ipc_on() {
722 ipc_start()
723 }
724 mut status := run_mode(config) or { print_err(err.msg()) }
725 // a query that skipped bad targets still fails, after showing the rest
726 if failed_targets > 0 && status == 0 {
727 status = 1
728 }
729 end_run(status)
730}
731
732// mode_help prints one mode's options and ends the run
733@[noreturn]
734fn mode_help(name string) {
735 if ipc_on() {
736 ipc_start()
737 }
738 mode := find_mode(name) or { print_err('unknown subcommand: "${name}"') }
739 show_help(mode_help_text(mode))
740 end_run(0)
741}
742
743// end_run is the one exit of a run, an error's included: the status, told
744// to a frontend first as the exit event that closes every stream
745@[noreturn]
746fn end_run(status int) {
747 if ipc_on() {
748 emit(ExitEvent{
749 status: status
750 })
751 }
752 exit(status)
753}
754