@[has_globals] module main import flag import os import vmakepkg struct ConfigSearch { pub mut: show_help bool @[long: help; short: h] noconfirm bool @[long: noconfirm] local bool @[long: local; short: l] remote bool @[long: remote; short: r] pkgbuild bool @[long: pkgbuild; short: b] quiet bool @[long: quiet; short: q] fuzzy bool @[long: fuzzy; short: f] thold f64 = 0.9 @[long: thold; short: t] sync_dbs bool @[long: sync; short: s] deps bool @[long: deps; short: d] explicit bool @[long: explicit; short: e] foreign bool @[long: foreign; short: m] native bool @[long: native; short: n] unrequired bool @[long: unrequired] // --unrequired given twice is pacman's -tt; the flag parser counts short // flags only, so parse_mode counts the long one itself unrequired_level int @[ignore] upgrades bool @[long: upgrades; short: u] groups bool @[long: groups] groups_level int @[only: g; repeats] installed bool @[long: installed; short: i] fields string @[long: fields; short: F] query []string @[tail] } struct ConfigInstall { pub mut: show_help bool @[long: help; short: h] noconfirm bool @[long: noconfirm] no_upgrade_deps bool @[long: no_upgrade_deps] pkgbuild bool @[long: pkgbuild; short: b] no_pkgbuild_confirm bool @[long: nopkgbuildconfirm] download_only bool @[long: download_only; short: w] print_only bool @[long: print; short: p] needed bool @[long: needed] asdeps bool @[long: asdeps] asexplicit bool @[long: asexplicit] dbonly bool @[long: dbonly] nodeps bool @[long: nodeps] nodeps_level int @[only: d; repeats] overwrite []string @[long: overwrite] ignore []string @[long: ignore] ignoregroup []string @[long: ignoregroup] assume_installed []string @[long: assume_installed] disable_timeout bool @[long: disable_timeout] query []string @[tail] } // trans_options are the transaction options a command line carries: // install's and upgrade's are the same four flags, read through one body fn trans_options[T](c T) TransOptions { return TransOptions{ overwrite: c.overwrite ignore: c.ignore ignoregroup: c.ignoregroup assume_installed: c.assume_installed } } struct ConfigInfo { pub mut: show_help bool @[long: help; short: h] noconfirm bool @[long: noconfirm] fields string @[long: fields; short: F] changelog bool @[long: changelog; short: c] file bool @[long: file; short: p] query []string @[tail] } struct ConfigWhich { pub mut: show_help bool @[long: help; short: h] query []string @[tail] } struct ConfigRank { pub mut: show_help bool @[long: help; short: h] stdin bool @[long: stdin] top int = 10 @[long: top; short: n] mirrorlist bool @[long: mirrorlist; short: m] output string @[long: output; short: o] path string @[long: path] write bool @[long: write; short: w] query []string @[tail] } struct ConfigVerify { pub mut: show_help bool @[long: help; short: h] checksums bool @[long: checksums] checksums_level int @[only: k; repeats] full bool @[long: full] db bool @[long: db] db_level int @[only: D; repeats] query []string @[tail] } struct ConfigFind { pub mut: show_help bool @[long: help; short: h] noconfirm bool @[long: noconfirm] refresh bool @[long: refresh; short: y] list bool @[long: list; short: l] quiet bool @[long: quiet; short: q] regex bool @[long: regex; short: x] machinereadable bool @[long: machinereadable] repos string @[long: repos; short: r] query []string @[tail] } struct ConfigMark { pub mut: show_help bool @[long: help; short: h] noconfirm bool @[long: noconfirm] reason string @[long: reason; short: r] query []string @[tail] } struct ConfigRemove { pub mut: show_help bool @[long: help; short: h] noconfirm bool @[long: noconfirm] print_only bool @[long: print; short: p] recursive bool @[long: recursive] recursive_level int @[only: s; repeats] unneeded bool @[long: unneeded; short: u] cascade bool @[long: cascade; short: c] nosave bool @[long: nosave; short: n] dbonly bool @[long: dbonly] nodeps bool @[long: nodeps] nodeps_level int @[only: d; repeats] assume_installed []string @[long: assume_installed] query []string @[tail] } struct ConfigUpgrade { pub mut: show_help bool @[long: help; short: h] noconfirm bool @[long: noconfirm] print_only bool @[long: print; short: p] sync_dbs bool @[long: sync; short: s] download_only bool @[long: download_only; short: w] dbonly bool @[long: dbonly] nodeps bool @[long: nodeps] nodeps_level int @[only: d; repeats] downgrade bool @[long: downgrade] sysupgrade_level int @[only: u; repeats] overwrite []string @[long: overwrite] ignore []string @[long: ignore] ignoregroup []string @[long: ignoregroup] disable_timeout bool @[long: disable_timeout] assume_installed []string @[long: assume_installed] } struct ConfigFiles { pub mut: show_help bool @[long: help; short: h] noconfirm bool @[long: noconfirm] query []string @[tail] } struct ConfigOwner { pub mut: show_help bool @[long: help; short: h] quiet bool @[long: quiet; short: q] query []string @[tail] } struct ConfigOrphans { pub mut: show_help bool @[long: help; short: h] // pacman's -Qdt and -Qdtt: twice lists the dependencies something still // names as optional too level int @[only: t; repeats] } struct ConfigClean { pub mut: show_help bool @[long: help; short: h] noconfirm bool @[long: noconfirm] print_only bool @[long: print; short: p] all bool @[long: all; short: a] keep int @[long: keep; short: k] keep_current bool @[long: keep_current] // pacman's -Sc and -Scc: once is the default clean, twice every archive level int @[only: c; repeats] } struct ConfigTree { pub mut: show_help bool @[long: help; short: h] noconfirm bool @[long: noconfirm] reverse bool @[long: reverse; short: r] optional bool @[long: optional; short: o] depth int @[long: depth; short: d] query []string @[tail] } struct ConfigAutoRemove { pub mut: show_help bool @[long: help; short: h] noconfirm bool @[long: noconfirm] } @[noreturn] fn print_err(e string) { if ipc_on() { // an error before the run started ends it all the same: the channel // opens for it (once: ipc_start is guarded), so every stream starts // with its hello and ends with its exit ipc_start() emit(ErrorEvent{ msg: e }) } else { eprintln(error_text(e)) } end_run(1) } // error_text is an error line the way vpac prints them, 'error: ' in bold red fn error_text(e string) string { return erole('error', 'error: ') + e } // failed_targets counts the targets a query reported bad and skipped. like // pacman's queries, it goes on with the rest, and main exits 1 at the end // when any failed __global failed_targets = 0 // target_error reports one bad target of a query that goes on with the next fn target_error(e string) { failed_targets++ if ipc_on() { emit(ErrorEvent{ msg: e target: true }) return } os.flush() eprintln(error_text(e)) } // need_query stops a command that acts on targets when none were given fn need_query(query []string, what string) ! { if query.len == 0 { return error('no ${what} given') } } // scan_globals collects vpac's own flags, wherever they stand in the command // line: --config chooses the config file, --eval extends the config with blip // code run after it. both repeatable, both also usable as --flag=value. the // flags are stripped from the args (the program name stays first, the mode // second), so a mode never sees them; escalation still gets the original // args, so the root process reads the same config and evals fn scan_globals(args []string) !(string, []string, []string) { // the frontend is settled before any other flag can fail: an error is // told over the channel whenever --ui ipc is on the command line, not // only when it happens to come before the flag that is wrong if kind := scan_ui(args) { ui_kind = kind } mut chosen := '' mut evals := []string{} mut rest := [args[0]] mut i := 1 for i < args.len { arg := args[i] if arg == '--config' || arg == '--eval' { if i + 1 >= args.len { return error('${arg} needs a value') } value := args[i + 1] if value == '' { return error('${arg} needs a value') } if arg == '--config' { chosen = value } else { evals << value } i += 2 } else if arg.starts_with('--config=') { chosen = arg.all_after('=') if chosen == '' { return error('--config needs a file') } i++ } else if arg.starts_with('--eval=') { expr := arg.all_after('=') if expr == '' { return error('--eval needs blip code') } evals << expr i++ } else if arg == '--color' || arg.starts_with('--color=') { // pacman's --color: auto (the default) styles a terminal only mut value := arg.all_after('=') if arg == '--color' { if i + 1 >= args.len { return error('--color needs a value: auto, always or never') } i++ value = args[i] } if value !in ['auto', 'always', 'never'] { return error('--color takes auto, always or never, not "${value}"') } color_flag = value color_given = true i++ } else if arg == '--verbose' { // the verbose log: the housekeeping failures a run goes on from verbose_flag = true i++ } else if arg == '--ui' || arg.starts_with('--ui=') { // the frontend: tty, a person at a terminal, or ipc, a program // speaking json lines (ipc.v) mut value := arg.all_after('=') if arg == '--ui' { if i + 1 >= args.len { return error('--ui needs a value: tty or ipc') } i++ value = args[i] } if value !in ['tty', 'ipc'] { return error('--ui takes tty or ipc, not "${value}"') } ui_kind = value i++ } else { rest << arg i++ } } return chosen, evals, rest } // global_value_flags are vpac's own flags that take the next argument as // their value when spelled without '=' const global_value_flags = ['--config', '--eval', '--color', '--ui'] // scan_ui finds the --ui the command line settles on — the last valid one, // as scan_globals lets the last win — stepping over the values of the other // globals the way scan_globals reads them, so an --eval whose code is the // text '--ui' is not taken for the flag. none when there is no valid one: // a bad value is scan_globals' error to give, on the terminal fn scan_ui(args []string) ?string { mut found := ?string(none) mut i := 1 for i < args.len { arg := args[i] if arg.starts_with('--ui=') { value := arg.all_after('=') if value in ['tty', 'ipc'] { found = value } } else if arg == '--ui' && i + 1 < args.len && args[i + 1] in ['tty', 'ipc'] { found = args[i + 1] } i += if arg in global_value_flags { 2 } else { 1 } } return found } // ModeConfig is a mode's command line, parsed: which mode, with its flags type ModeConfig = ConfigAutoRemove | ConfigBuild | ConfigClean | ConfigDeptest | ConfigFiles | ConfigFind | ConfigInfo | ConfigInstall | ConfigMark | ConfigOrphans | ConfigOwner | ConfigRank | ConfigRemove | ConfigSearch | ConfigTree | ConfigUpgrade | ConfigVerify | ConfigWhich // mode_flags reads a mode's flags into its struct, then lays the config's // options under them: a flag the config turns on (options :noconfirm true) // is on for every mode that has it, as if it stood on the command line. // the command line can only add to that; --eval turns one off for a run. // an option the mode's struct has no field for is an error fn mode_flags[T](args []string) !T { mut c, unknown := flag.to_struct[T](args, skip: 2)! // what the parser could not place is an option the mode does not have: // said, as pacman says it, instead of a run that quietly leaves a // mistyped flag out of a transaction bad := unknown.filter(it.len > 1 && it.starts_with('-')) if bad.len > 0 { return error('unknown option: ${bad.map('"${it}"').join(', ')}') } // the rest of it are targets that stand before a flag: the parser's // tail takes only the ones after the last flag, and these lead them early := unknown.filter(!(it.len > 1 && it.starts_with('-'))) if early.len > 0 { mut placed := false $for field in T.fields { $if field.name == 'query' { mut query := early.clone() query << c.query c.query = query placed = true } } if !placed { return error('this mode takes no targets: ${early.map('"${it}"').join(', ')}') } } $for field in T.fields { $if field.typ is bool { if opt_flags[field.name] { c.$(field.name) = true } } } return c } // flag_given is whether the command line spells a flag, by its long name or // its short letter: what settles that a config default steps back. a letter // is looked for in any bundle of short flags, so a doubt reads as given and // leaves the mode's own default fn flag_given(args []string, long string, short string) bool { for a in args#[2..] { if a == '--${long}' || a.starts_with('--${long}=') { return true } if a.len > 1 && a[0] == `-` && a[1] != `-` && a.contains(short) { return true } } return false } // parse_mode reads the mode and its flags. it runs before any escalation, so // a flag that does not parse is an error the user sees before a root prompt fn parse_mode(args []string) !ModeConfig { return match args[1] { 's', 'S', 'search' { // a long flag given twice is the flag parser's error, so the // repeats of --unrequired are counted and folded into one here level := args.count(it == '--unrequired') mut once := []string{cap: args.len} for i, arg in args { if arg == '--unrequired' && args[..i].contains(arg) { continue } once << arg } mut c := mode_flags[ConfigSearch](once)! if !flag_given(once, 'thold', 't') { c.thold = cfg_search_thold } else if c.thold < 0.0 || c.thold > 1.0 { // the config's (search :thold) is held to the same range return error('--thold must be between 0 and 1, not ${c.thold}') } c.unrequired_level = level c.groups = c.groups || c.groups_level > 0 if !c.local && !c.remote && !c.pkgbuild { // the filters only work on the installed packages; the // groups are the sync dbs' unless -l asks for the local ones c.local = c.filtered() && !c.groups c.remote = !c.filtered() || c.groups } ModeConfig(c) } 'q', 'Q', 'info' { c := mode_flags[ConfigInfo](args)! ModeConfig(c) } 'w', 'W', 'which' { c := mode_flags[ConfigWhich](args)! ModeConfig(c) } 'n', 'N', 'deptest' { c := mode_flags[ConfigDeptest](args)! ModeConfig(c) } 'm', 'M', 'mark' { c := mode_flags[ConfigMark](args)! ModeConfig(c) } 'b', 'B', 'build' { c := mode_flags[ConfigBuild](args)! ModeConfig(c) } 'i', 'I', 'install' { c := mode_flags[ConfigInstall](args)! ModeConfig(c) } 'r', 'R', 'remove' { c := mode_flags[ConfigRemove](args)! ModeConfig(c) } 'u', 'U', 'upgrade' { c := mode_flags[ConfigUpgrade](args)! ModeConfig(c) } 'l', 'L', 'files' { c := mode_flags[ConfigFiles](args)! ModeConfig(c) } 'o', 'O', 'owner' { c := mode_flags[ConfigOwner](args)! ModeConfig(c) } 'd', 'D', 'orphans' { c := mode_flags[ConfigOrphans](args)! ModeConfig(c) } 'c', 'C', 'clean' { mut c := mode_flags[ConfigClean](args)! if !flag_given(args, 'keep', 'k') { c.keep = cfg_clean_keep } ModeConfig(c) } 't', 'T', 'tree' { mut c := mode_flags[ConfigTree](args)! if !flag_given(args, 'depth', 'd') { c.depth = cfg_tree_depth } ModeConfig(c) } 'a', 'A', 'autoremove' { c := mode_flags[ConfigAutoRemove](args)! ModeConfig(c) } 'k', 'K', 'rank' { mut c := mode_flags[ConfigRank](args)! if !flag_given(args, 'top', 'n') { c.top = rank_top } else if c.top < 1 { // the config's (rank :top) is held to the same floor return error('--top must be at least 1, not ${c.top}') } ModeConfig(c) } 'v', 'V', 'verify' { c := mode_flags[ConfigVerify](args)! ModeConfig(c) } 'f', 'F', 'find' { c := mode_flags[ConfigFind](args)! ModeConfig(c) } else { error('unknown subcommand: "${args[1]}"') } } } // needs_root is whether a mode runs as root: the ones that change the // system, except a --print preview, which changes nothing and stays the // user's as pacman's --print does; find -y, which writes the file dbs; and // rank when the file it writes is not the user's to write. rank -w writes // the config's mirror file under /etc, so that is known before any ranking fn needs_root(c ModeConfig) !bool { return match c { ConfigInstall { !c.print_only } ConfigRemove { !c.print_only } ConfigUpgrade { !c.print_only } ConfigClean { !c.print_only } ConfigBuild, ConfigMark, ConfigAutoRemove { true } ConfigFind { c.refresh } ConfigRank { mut target := c.output if target == '' && c.write { target = rank_write_target(rank_os_name(c.query)!) } target != '' && !can_write(target) } else { false } } } // run_mode runs a parsed mode and returns its exit status: 0, or what the // mode's outcome asks for fn run_mode(c ModeConfig) !int { match c { ConfigSearch { search(c)! } ConfigInfo { info(c)! } ConfigWhich { which(c)! } ConfigDeptest { // pacman's -T: 127 tells makepkg a dependency is missing if deptest(c)!.len > 0 { return 127 } } ConfigMark { mark(c)! } ConfigBuild { build_repo(c)! } ConfigInstall { install(c)! } ConfigRemove { remove(c)! } ConfigUpgrade { upgrade(c)! } ConfigFiles { files(c)! } ConfigOwner { owner(c)! } ConfigOrphans { orphans(c)! } ConfigClean { clean(c)! } ConfigTree { tree(c)! } ConfigAutoRemove { autoremove(c)! } ConfigRank { rank(c)! } ConfigVerify { if verify(c)! > 0 { return 1 } } ConfigFind { find(c)! } } return 0 } fn main() { // --lip-run [args...] is what a PKGBUILD generated from a // PKGBUILD.lip calls back (vpac b): it runs one phase of the lip. it is no // mode, reads no config and never needs root if os.args.len > 3 && os.args[1] == '--lip-run' { vmakepkg.lip_run_phase(os.args[2], os.args[3], os.args[4..]) or { eprintln(error_text('lip: ${err.msg()}')) exit(1) } exit(0) } chosen, evals, args := scan_globals(os.args) or { print_err(err.msg()) } // the config comes first: it is required, and everything downstream reads // it, including the escalation to root load_config(chosen, evals) or { print_err(err.msg()) } // the config's color is the default a --color on the command line beats if !color_given && opt_color != '' { color_flag = opt_color } // a killed run lets go of the db lock it holds (on_interrupt) install_interrupt_handlers() // no mode, or help: the overview. an option where the mode belongs is // one no global scan took, and an error as pacman's unknown options are if args.len < 2 || args[1] in ['h', 'help', '-h', '--help'] { if ipc_on() { ipc_start() } show_help(help_text()) end_run(0) } if args[1].starts_with('-') { print_err('unknown option "${args[1]}" before the mode (vpac --help lists the modes)') } // the mode is parsed before anything else happens: a bad flag is an error // here, not a panic in a root process. 'vpac -h' prints that // mode's options and never runs the command; the flag parser reads the // -h, so one bundled with others (-lh) counts and one that is another // flag's value does not. a help request beside flags that do not parse // is still answered with the help config := parse_mode(args) or { if args[2..].any(it == '-h' || it == '--help') { mode_help(args[1]) } print_err(err.msg()) } if config.show_help { mode_help(args[1]) } // a mode that changes the system runs as root, through the root // provider; the original command line is passed, globals included, so // the root process reads the same config and evals root := needs_root(config) or { print_err(err.msg()) } if root { reexec_as_root(os.args[1..]) or { print_err(err.msg()) } } // this is the process that does the work: a frontend's channel opens here if ipc_on() { ipc_start() } mut status := run_mode(config) or { print_err(err.msg()) } // a query that skipped bad targets still fails, after showing the rest if failed_targets > 0 && status == 0 { status = 1 } end_run(status) } // mode_help prints one mode's options and ends the run @[noreturn] fn mode_help(name string) { if ipc_on() { ipc_start() } mode := find_mode(name) or { print_err('unknown subcommand: "${name}"') } show_help(mode_help_text(mode)) end_run(0) } // end_run is the one exit of a run, an error's included: the status, told // to a frontend first as the exit event that closes every stream @[noreturn] fn end_run(status int) { if ipc_on() { emit(ExitEvent{ status: status }) } exit(status) }