Modules

Command_Line

moduleSource

Available on macOS, Linux, Windows, Wasm

#import "Command_Line";

Reads the command line into a struct: declare the options as fields and call parse_arguments.

Example↗
Options :: struct { quiet: bool; level := 2; }

ok, options := parse_arguments(Options, args = string.["-level", "5"]);
assert(ok && options.level == 5 && !options.quiet);

Procedures#

($T: Type, flags := Default_Argument_Flags, help_triggers: [] string = .["help", "HELP", "?"], args: [] string = .{ count = -1 }) -> (success: bool, result: T, is_set: Is_Set(T), free_arguments: [..] string)

Reads the program's arguments into a struct. Each field of T is an option: a bool is a switch that is set by its name alone, anything else takes the next argument as its value (-count 3), and a fixed-size array takes one argument per element. Returns whether it worked, the filled struct, an Is_Set of which options appeared, and the arguments that were not options. An unknown option, a missing or bad value or a repeated option makes it fail. Asking for -help prints the options and fails.

Options :: struct {
    verbose: bool;
    count := 1;
    name: string;
}

ok, options, is_set, files := parse_arguments(Options, args = string.["-verbose", "-count", "3", "a.txt"]);
assert(ok && options.verbose && options.count == 3);
assert(!is_set.name && files.count == 1 && files[0] == "a.txt");
↗
($T: Type, flags: Argument_Flags, help_triggers: [] string)

Prints the options of T with their types and defaults, as parse_arguments does when asked for help.

Options :: struct { verbose: bool; count := 1; }
show_help(Options, Default_Argument_Flags, string.["help"]);
↗

This one is only checked to compile, not run.

Types#

:: struct

For a struct T, a struct with a bool for each of its fields that parse_arguments sets to true for every option the user gave. It tells an option left at its default apart from one set to the same value.

:: enum_flags

How parse_arguments treats the command line. Combine them with |.

FREE_ARGUMENTS_ALLOWED
DOUBLE_DASH_REQUIRED
SHOW_HELP_ON_ERROR
SORT_HELP
ALIGN_HELP

Constants#