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}!")
}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
| Function | Gives |
|---|---|
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() -> Bool | Whether standard output is a terminal: false for a file, a pipe or a test. Needs Console |
io.colors() -> Bool | Whether 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 ! CliError | The arguments, parsed into record type T, or into union type T of commands. Needs Env |
cli.on_stop(grace: 10.seconds) -> StopHold | A 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() -> Bool | Whether 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.