Skip to content
CryoCryo home
Stdlibenv

arguments

import std::env::arguments; · source

Command-line arguments read against a declaration of what a program takes: flags, options with values, and positional arguments. An ArgumentParser declares them, parse reads a command line into ParsedArguments, and help_text describes them.

import std::collections::str::{ Str };
import std::collections::string::{ String };
import std::env;
import std::env::arguments::{ ArgumentParser, ParsedArguments };
import std::fmt;

function main() -> i32 {
    mut parser: ArgumentParser = ArgumentParser::new("grep");
    parser.flag("count", Option::Some('c'), "print only a count")
        .option("context", Option::None, "lines", "lines around a match")
        .positional("pattern", "what to look for")
        .optional_positional("file", "where to look");
    const all: Array<String> = env::args();
    match (parser.parse(all.as_slice().subslice(1, all.length()))) {
        Result::Ok(parsed) => {
            const pattern: Str = parsed.value("pattern").unwrap();
            const counting: boolean = parsed.flag("count");
            fmt::println(f"looking for {pattern}, counting: {counting}");
            return 0;
        }
        Result::Err(error) => {
            fmt::eprintln(f"{error}");
            const help: String = parser.help_text();
            fmt::eprint(f"{help}");
            return 2;
        }
    }
}

An option's value is written --context=3, --context 3, -C3, or -C 3; short flags group, -cv. -- ends the options: every argument after it is positional, even one starting with -. A single - is positional too. A short letter is ASCII.

Types

ArgumentParser

type struct ArgumentParser {
    private program:        String;
    private specifications: Array<ArgumentSpecification>;
}

Each declaring method returns the parser, so declarations chain. A flag is present or not, and counted when repeated. An option takes a value and keeps every value when given more than once. Positional arguments are read in the order they are declared, required ones first: an optional_positional is read after every required one, whatever order they are declared in. parse takes the command line after the program's own name, and the first argument that does not fit the declarations is the error.

Constructors

static new(program: Str) -> ArgumentParser;

A parser that declares nothing yet, for the program named program, the name its help text's usage line shows.

Methods

flag(mut &this, long: Str, short: Option<char>, help: Str) -> mut &ArgumentParser;

A flag, --long or -s: present or not, and counted when repeated.

option(mut &this, long: Str, short: Option<char>, value_name: Str, help: Str) -> mut &ArgumentParser;

An option that takes a value, --long=value, --long value, -svalue or -s value; value_name names the value in the help. Given more than once, it keeps every value, in order.

positional(mut &this, name: Str, help: Str) -> mut &ArgumentParser;

A positional argument that must be given. Positional arguments are read in the order they are declared.

optional_positional(mut &this, name: Str, help: Str) -> mut &ArgumentParser;

A positional argument that may be left out. It is read after every required one, whatever order they are declared in.

repeated_positional(mut &this, name: Str, help: Str) -> mut &ArgumentParser;

Any number of positional arguments, none included: every one left after the required and the optional ones, read with values. Only the first one declared receives any.

parse(&this, arguments: &Slice<String>) -> Result<ParsedArguments, ArgumentError>;

Read arguments - the command line after the program's own name - against the declarations. The first argument that does not fit them is the error.

help_text(&this) -> String;

A description of the arguments: a usage line, then each positional argument and each flag and option with its help, in the order they were declared.

ParsedArguments

type struct ParsedArguments {
    private arguments: Array<ParsedArgument>;
}

Read by the names the arguments were declared under; asking for a name the parser did not declare panics. occurrences counts a repeated flag (-vvv is 3), value is the last value given, and values every one, in order.

Methods

![caller_location]
flag(&this, name: Str) -> boolean;

True when the flag or option name was given.

![caller_location]
occurrences(&this, name: Str) -> i64;

How many times the flag or option name was given: -vvv is 3.

![caller_location]
value(&this, name: Str) -> Option<Str>;

The value of the option or positional argument name: the last one given when the option was given more than once.

![caller_location]
values(&this, name: Str) -> &Slice<String>;

Every value of the option or repeated positional argument name, in the order they were given.

ArgumentError

type struct ArgumentError with [Eq, Clone, Debug] {
    kind:     ArgumentErrorKind;
    argument: String;
}

The argument a command line went wrong at, as written, and how. For a missing positional argument, argument is its name as the help shows it, <file>. It prints as a one-line message, so a program reports it and then the help text.

Properties

PropertyTypeNotes
kindArgumentErrorKind
argumentStringThe argument as written; for a missing positional argument, its name as the help shows it, <file>.

Constructors

static new(kind: ArgumentErrorKind, argument: Str) -> ArgumentError;

An error of kind at argument, which is copied.

ArgumentErrorKind

type enum ArgumentErrorKind with [Eq, Clone, Debug] {
    UnknownOption;
    MissingValue;
    UnexpectedValue;
    MissingPositional;
    UnexpectedPositional;
}
Variants
VariantNotes
UnknownOptionAn option or short letter nothing declares.
MissingValueAn option that takes a value came last, with none after it.
UnexpectedValueA flag written with a value, --verbose=yes.
MissingPositionalA required positional argument was not given.
UnexpectedPositionalMore positional arguments than are declared.

Trait implementations

implement trait Error for struct ArgumentError

implement trait Display for struct ArgumentError