Skip to content
Kavachकवच

Command-line Programs

● Intermediate4 minBefore this: FilesSpec 14.6

A command-line program reads the words typed after its name. cli.args gives them as a list; cli.parse turns them into a record.

use std.cli

fn main() {
    const args = cli.args()
    print("{args.len()} arguments: {args}")
    const name = args.first() ?? "friend"
    print("Namaste, {name}!")
}
src/main.kav: Kavach code
terminal
kavach run src/main.kav Asha Pune
2 arguments: ["Asha", "Pune"]
Namaste, Asha!
kavach run src/main.kav
0 arguments: []
Namaste, friend!
kavach run --native src/main.kav -- Asha Pune
2 arguments: ["Asha", "Pune"]
Namaste, Asha!

cli.args() gives the arguments without the program's own name. Reading them needs the Env capability, which main has. Arguments after -- go to the program too, without the --, in every way of running it: the last run above is native code.

Every function

FunctionGives
io.read_line() -> String?The next line typed (without its line ending), or none at the end of input. Needs Console
io.read_hidden() -> String?A line typed without being shown on the screen, for a password, when standard input is a terminal; otherwise an ordinary line, so a pipe can answer it. none at the end of input. Needs Console (decision 0036)
io.write(text)Prints text without a line end, shown at once (for a prompt, or a line drawn again with \r). Needs Console
io.is_terminal() -> BoolWhether standard output is a terminal: false for a file, a pipe or a test. Needs Console
io.colors() -> BoolWhether standard output shows colors: it is a terminal, and the environment variable NO_COLOR is not set (no-color.org). Needs Console
cli.args() -> [String]The program's arguments, without its own name. Needs Env
cli.exit(code)Ends the program at once with code. Needs Env
cli.parse<T>() -> T ! CliErrorThe arguments, parsed into record type T, or into union type T of commands. Needs Env
cli.on_stop(grace: 10.seconds) -> StopHoldA hold on the program's stop (5.8): while it is held, the first Ctrl+C, SIGTERM or closed terminal lets the program finish its work, for at most grace, instead of ending it at once
hold.asked() -> BoolWhether a stop has been asked for
hold.done()Lets go of the hold: once no hold is left after a stop was asked, the program ends

kavach build makes the program an executable of its own, run as ./greet Asha Pune, with the same arguments.

One page for each form