libstd/argparse
A command-line parser in the style of Python's argparse: options with values, boolean flags, positionals, subcommands with their own options, automatic --help. Create an ArgParser, register everything, call parse(), then read the values. Every parser is independent and you can create as many as you like.
#include <libstd/argparse>
Includes libstd/string, libstd/type, libstd/list, libstd/os.
Example
#include <libstd/stdio>
#include <libstd/argparse>
p = ArgParser("mygit", "a toy git, to demonstrate argparse")
p.add_flag("--verbose", "-v", "print extra information")
add_id = p.add_subcommand("add", "add a file to the staging area")
p.add_sub_positional(add_id, "file", "path of the file to add")
commit_id = p.add_subcommand("commit", "record a commit")
p.add_sub(commit_id, "--message", "-m", "commit message", 1, "")
p.parse() // exits with a message on errors and on --help
cmd = p.subcommand()
if p.get_bool("--verbose"):
print("[verbose] command: ", cmd, "\n")
if cmd == "add":
print("adding ", p.get_positional("file"), "\n")
if cmd == "commit":
print("commit: ", p.get("--message"), "\n")
The command line, as in Python
- After
--every argument is a positional, even if it starts with-(--helpincluded). - An option takes its value from
--name=valueor from the next argument, which must not start with-unless it is a negative number:--count -5works,--name -xis a missing value.--name=-xis fine. - A flag does not take a value:
--verbose=1is an error. - Every parse starts again from the defaults.
Several parsers on one command line
parse_known() is Python's parse_known_args. It reads the options of its own parser and puts the others aside instead of failing, so each parser picks its own options from the same command line. Here prog -t 2 --name Mario works:
log = ArgParser("prog", "")
log.add("--times", "-t", "how many times", 0, "1")
log.parse_known() // --name Mario are put aside
app = ArgParser("prog", "")
app.add("--name", "-n", "who to greet", 0, "world")
app.parse_known() // -t 2 are put aside
i = 0
while i < app.unknown_count:
print("not mine: ", app.unknown_at(i), "\n")
i++
Arguments are analysed once
The arguments of a process never change, and what each one means depends only on the command line. The first parser that reads them therefore analyses them once for the whole process: it copies each argument into a TryC string, so its length costs O(1), and records its kind (option, positional, --, help, negative number) and the two halves of --name=value. Every ArgParser, also one created later, reads from there.
The argparse_* functions do the same things on a single parser of the program, for code that does not need instances: argparse_init(prog, description), argparse_add(...), argparse_parse(), argparse_get(...).
Constants
| Name | Value | Meaning |
|---|---|---|
ARGPARSE_NO_OWNER | -1 | subcommand id of options and positionals valid for every subcommand |
ARGPARSE_KIND_VALUE | 0 | an option that takes a value |
ARGPARSE_KIND_FLAG | 1 | a boolean flag |
ARGPARSE_ARG_POSITIONAL | 0 | anche ogni argomento dopo "--" e i numeri negativi |
ARGPARSE_ARG_OPTION | 1 | inizia con '-' |
ARGPARSE_ARG_SEPARATOR | 2 | il primo "--" |
ARGPARSE_ARG_HELP | 3 | --help o -h |
Classes
One argument of the process in the cache: the copied text, its kind (ARGPARSE_ARG_*), and for an option the name before = and the value after.
text str
kind int
name str
value str
has_value intA registered option: long and short form, help, default, value after the parse, kind, whether it is required, whether it was given, the subcommand it belongs to.
long_flag str
short_flag str
help str
default_value str
value str
kind int
required int
provided int
owner intA registered positional: name, help, value, subcommand.
name str
help str
value str
owner intA registered subcommand: name and help.
name str
help strA parser. Create it with ArgParser(prog, description); the methods are called on the instance: add, add_flag, add_positional, add_subcommand, add_sub, add_sub_flag, add_sub_positional, parse, parse_known, unknown_at, print_help, get, get_int, get_bool, was_provided, get_positional, subcommand. unknown_count is how many arguments parse_known put aside.
prog str
description str
options List
positionals List
commands List
unknown List
option_count int
positional_count int
command_count int
unknown_count int
matched_sub int
add &argparser_add
add_flag &argparser_add_flag
add_positional &argparser_add_positional
add_subcommand &argparser_add_subcommand
add_sub &argparser_add_sub
add_sub_flag &argparser_add_sub_flag
add_sub_positional &argparser_add_sub_positional
parse &argparser_parse
parse_known &argparser_parse_known
unknown_at &argparser_unknown_at
print_help &argparser_print_help
get &argparser_get
get_int &argparser_get_int
get_bool &argparser_get_bool
was_provided &argparser_was_provided
get_positional &argparser_get_positional
subcommand &argparser_subcommandFunctions
Creates an empty parser, like ArgumentParser in Python. prog is the name in help and error messages; with "" it is argv[0] without its directory.
p.add_sub(sub_id, ...): like add, valid only when that subcommand is invoked.p.add(long_flag, short_flag, help, required, default): registers an option that takes a value (--name Mario or --name=Mario). Pass "" for no short form. Returns its index.p.add_sub_flag(sub_id, ...): like add_flag, valid only for that subcommand.p.add_flag(long_flag, short_flag, help): registers a boolean flag (present or absent).p.add_sub_positional(sub_id, name, help): a positional valid only for that subcommand.p.add_positional(name, help): registers a positional, recognised by position in registration order; it is required.p.add_subcommand(name, help): registers a subcommand (the first positional on the command line) and returns its id.p.print_help(): prints usage, description, subcommands and options, plus the options of the recognised subcommand.p.parse(): parses the command line. On an unknown option, a missing value, a missing required option or positional, an extra positional or an unknown command it prints the error and the help and exits with 1; on --help/-h before -- it prints the help and exits with 0.p.parse_known(): like parse, but unknown options and extra positionals are put aside (unknown_count, unknown_at) instead of being errors. An unknown command, a missing value and missing required arguments are still errors.p.unknown_at(i): the text of the i-th argument put aside by parse_known.p.get(long_flag): the value of an option after the parse; the default if it was not given, "" if it was never registered.p.get_int(long_flag): get converted to an integer (0 if not a number or absent).p.was_provided(long_flag): 1 if the option was given explicitly rather than defaulted.p.get_bool(long_flag): 1 if a flag was on the command line.p.get_positional(name): the value of a positional by its registered name, "" if absent.p.subcommand(): the subcommand recognised by the last parse, "" if none.Resets the program's parser with the program name and description. Call it before any argparse_add*.
add on the program's parser.add_flag on the program's parser.add_positional on the program's parser.add_subcommand on the program's parser.add_sub on the program's parser.add_sub_flag on the program's parser.add_sub_positional on the program's parser.parse on the program's parser.print_help on the program's parser.get on the program's parser.get_int on the program's parser.get_bool on the program's parser.was_provided on the program's parser.get_positional on the program's parser.subcommand on the program's parser.Internal helpers
Used by the functions above; not meant to be called directly.
- def argparser_is_negative_number(text: str) -> int
- def argparser_parse_arg(text: str, after_separator: int) -> ArgParserArg
- def argparser_args() -> int
- def argparser_arg_at(index: int) -> ArgParserArg
- inline def argparser_reset(self: ArgParser, prog: str, description: str) -> None
- def argparser_option_at(self: ArgParser, idx: int) -> ArgParserOption
- def argparser_positional_at(self: ArgParser, idx: int) -> ArgParserPositional
- def argparser_command_at(self: ArgParser, idx: int) -> ArgParserCommand
- def argparser_applies(self: ArgParser, owner: int) -> int
- def argparser_prog(self: ArgParser) -> str
- def argparser_find_option(self: ArgParser, long_flag: str) -> int
- def argparser_find_subcommand(self: ArgParser, name: str) -> int
- def argparser_next_positional(self: ArgParser, from_idx: int) -> int
- def argparser_fail(self: ArgParser, message: str) -> None
- def argparser_print_one_help(opt: ArgParserOption) -> int
- def argparser_match_and_consume(self: ArgParser, arg: ArgParserArg, i: int) -> int
- def argparser_clear_values(self: ArgParser) -> None
- inline def argparser_put_aside(self: ArgParser, text: str) -> None
- def argparser_parse_args(self: ArgParser, known_only: int) -> int