Skip to content

flag #

Description

The flag module is a command line option parser. Its main features are:

  • simplicity of usage.
  • parses flags like -f or '--flag' or '--stuff=things' or '--things stuff'.
  • handles bool, int, float and string args.
  • can print usage information listing all the declared flags.
  • handles unknown arguments as error.

See also the cli module, for a more complex command line option parser, that supports declaring multiple subcommands each having a separate set of options.

Examples

module main

import os
import flag

fn main() {
mut fp := flag.new_flag_parser(os.args)
fp.application('flag_example_tool')
fp.version('v0.0.1')
fp.limit_free_args(0, 0)! // comment this, if you expect arbitrary texts after the options
fp.description('This tool is only designed to show how the flag lib is working')
fp.skip_executable()
an_int := fp.int('an_int', 0, 0o123, 'some int to define 0o123 is its default value')
a_bool := fp.bool('a_bool', 0, false, 'some boolean flag. --a_bool will set it to true.')
a_float := fp.float('a_float', 0, 1.0, 'some floating point value, by default 1.0 .')
a_string := fp.string('a_string', `a`, 'no text', 'finally, some text with ' +
' `-a` as an abbreviation, so you can pass --a_string abc or just -a abc')
additional_args := fp.finalize() or {
eprintln(err)
println(fp.usage())
return
}
println('an_int: ${an_int} | a_bool: ${a_bool} | a_float: ${a_float} | a_string: "${a_string}" ')
println(additional_args.join_lines())
}

Constants #

const space = '                            '

used for formatting usage message

const underline = '-----------------------------------------------'
const max_args_number = 4048

fn new_flag_parser #

fn new_flag_parser(args []string) &FlagParser

new_flag_parser - create a new flag parser for the given args

fn ([]Flag) str #

fn (af []Flag) str() string

str returns a string representation of the given array of Flags

struct Flag #

struct Flag {
pub:
	name     string // name as it appears on command line
	abbr     u8     // shortcut
	usage    string // help message
	val_desc string // something like '' that appears in usage,
	// and also the default value, when the flag is not given
}

data object storing information about a defined flag

fn (Flag) str #

fn (f Flag) str() string

str returns a string representation of the given Flag

struct FlagParser #

struct FlagParser {
pub:
	original_args      []string // the original arguments to be parsed
	idx_dashdash       int      // the index of a `--`, -1 if there is not any
	all_after_dashdash []string // all options after `--` are ignored, and will be passed to the application unmodified
pub mut:
	usage_examples []string // when set, --help will print:
	// Usage: $appname $usage_examples[0]`
	//    or: $appname $usage_examples[1]`
	// etc
	default_help_label      string = 'display this help and exit'
	default_version_label   string = 'output version information and exit'
	args                    []string // the current list of processed args
	max_free_args           int
	flags                   []Flag // registered flags
	application_name        string
	application_version     string
	application_description string
	min_free_args           int
	args_description        string
	allow_unknown_args      bool     // whether passing undescribed arguments is allowed
	footers                 []string // when set, --help will display all the collected footers at the bottom.
}

FlagParser is the heart of the flag module. That structure is created with mut parser := flag.new_flag_parser(os.args), The returned instance can be further customised by calling various methods, for specifying the accepted options and their values. The user should finally call rest := parser.finalize()! to get the rest of the non optional arguments (if there are any left).

fn (FlagParser) usage_example #

fn (mut fs FlagParser) usage_example(example string)

usage_example - add an usage example All examples will be listed in the help screen. If you do not give any examples, then a default usage will be shown, based on whether the application takes options and expects additional parameters.

fn (FlagParser) footer #

fn (mut fs FlagParser) footer(footer string)

add_footer - add a footnote, that will be shown at the bottom of the help screen.

fn (FlagParser) application #

fn (mut fs FlagParser) application(name string)

change the application name to be used in 'usage' output

fn (FlagParser) version #

fn (mut fs FlagParser) version(vers string)

change the application version to be used in 'usage' output

fn (FlagParser) description #

fn (mut fs FlagParser) description(desc string)

description appends to the application description lines, shown in the help/usage screen

fn (FlagParser) skip_executable #

fn (mut fs FlagParser) skip_executable()

in most cases you do not need the first argv for flag parsing

fn (FlagParser) allow_unknown_args #

fn (mut fs FlagParser) allow_unknown_args()

allow_unknown_args - if your program has sub commands, that have their own arguments, you can call .allow_unknown_args(), so that the subcommand arguments (which generally are not known to your parent program), will not cause the validation in .finalize() to fail.

fn (FlagParser) bool_opt #

fn (mut fs FlagParser) bool_opt(name string, abbr u8, usage string) !bool

bool_opt returns an option with the bool value of the given command line flag, named name. It returns an error, when the flag is not given by the user. This version supports abbreviations.

fn (FlagParser) bool #

fn (mut fs FlagParser) bool(name string, abbr u8, bdefault bool, usage string) bool

bool defines and parses a string flag/option named name. If that flag is given by the user, then it returns its parsed bool value. When it is not, it returns the default value in bdefault. This version supports abbreviations.

fn (FlagParser) int_multi #

fn (mut fs FlagParser) int_multi(name string, abbr u8, usage string) []int

int_multi returns all values associated with the provided flag in name. When that flag has no values, it returns an empty array. This version supports abbreviations.

fn (FlagParser) int_opt #

fn (mut fs FlagParser) int_opt(name string, abbr u8, usage string) !int

int_opt returns an option with the integer value, associated with the flag in name. When the flag is not given by the user, it returns an error. This version supports abbreviations.

fn (FlagParser) int #

fn (mut fs FlagParser) int(name string, abbr u8, idefault int, usage string) int

int defines and parses an integer flag, named name. When the flag is given by the user, it returns its parsed integer value. When it is not, it returns the integer value in idefault. This version supports abbreviations.

fn (FlagParser) float_multi #

fn (mut fs FlagParser) float_multi(name string, abbr u8, usage string) []f64

float_multi returns all floating point values, associated with the flag named name. When no values for that flag are found, it returns an empty array. This version supports abbreviations.

fn (FlagParser) float_opt #

fn (mut fs FlagParser) float_opt(name string, abbr u8, usage string) !f64

float_opt returns an option with the floating point value, associated with the flag in name. When the flag is not given by the user, it returns an error. This version supports abbreviations.

fn (FlagParser) float #

fn (mut fs FlagParser) float(name string, abbr u8, fdefault f64, usage string) f64

float defines and parses a floating point flag, named name. When the flag is given by the user, it returns its parsed floating point value. When it is not, it returns the value in fdefault. This version supports abbreviations.

fn (FlagParser) string_multi #

fn (mut fs FlagParser) string_multi(name string, abbr u8, usage string) []string

string_multi returns all string values, associated with the flag named name. When no values for that flag are found, it returns an empty array. This version supports abbreviations.

fn (FlagParser) string_opt #

fn (mut fs FlagParser) string_opt(name string, abbr u8, usage string) !string

string_opt returns an option with the string value, associated with the flag in name. When the flag is not given by the user, it returns an error. This version supports abbreviations.

fn (FlagParser) string #

fn (mut fs FlagParser) string(name string, abbr u8, sdefault string, usage string) string

string defines and parses a string flag/option, named name. If that flag is given as an option, then its parsed value is returned as a string. When it is not, it returns the default string value in sdefault. This version supports abbreviations.

fn (FlagParser) limit_free_args_to_at_least #

fn (mut fs FlagParser) limit_free_args_to_at_least(n int) !

limit_free_args_to_at_least restricts the list of free arguments (non options) to be at least n in length. If the user gives less free arguments to the program, the parser will return an error.

fn (FlagParser) limit_free_args_to_exactly #

fn (mut fs FlagParser) limit_free_args_to_exactly(n int) !

limit_free_args_to_exactly restricts the list of free arguments (non options) to be at exactly n in length. If the user gives more or less free arguments to the program, the parser will return an error.

fn (FlagParser) limit_free_args #

fn (mut fs FlagParser) limit_free_args(min int, max int) !

limit_free_args restricts the list of free arguments (non options) to be between min and max in length. If the user gives more or less free arguments to the program, the parser will return an error.

fn (FlagParser) arguments_description #

fn (mut fs FlagParser) arguments_description(description string)

arguments_description sets the description field of the parser. This field is usually shown when the --help option is given to the program.

fn (FlagParser) usage #

fn (fs FlagParser) usage() string

usage returns a nicely formatted usage screen, containing all the possible options, as well as the description for the program. That screen is usually shown when the --help option is given to the program.

fn (FlagParser) finalize #

fn (mut fs FlagParser) finalize() ![]string

finalize - return all remaining arguments (non options). Call .finalize() after all arguments are defined. The remaining arguments are returned in the same order they are defined on the command line. If additional flags are found, i.e. (things starting with '--' or '-'), it returns an error.

fn (FlagParser) remaining_parameters #

fn (mut fs FlagParser) remaining_parameters() []string

remaining_parameters will return all remaining parameters. Call .remaining_parameters() AFTER you have defined all options that your program needs. remaining_parameters will also print any parsing errors and stop the program. Use .finalize() instead, if you want more control over the error handling.