flag
Reading command line options such as --port 8080 and -v with the right type, and generating the help text.
import flag
The flag package reads command line options. Each flag has a long name (--port), an optional short name (-p), a kind (bool, string, int or float), a default value and a line of help. The value can be given either way: --port=8080 or --port 8080. Any argument that is not a flag is "positional", and after -- everything counts as positional. For a program with subcommands such as tool build and tool test, see cli; for settings from the environment, env.
The steps are always the same: New, one Add... per flag, Parse with the arguments (without the program's own name), then check Parse's result and HelpWanted before reading values with GetStr, GetInt, GetFloat and GetBool. --help and -h are always recognised and reserved, and the Usage text is generated for you.
What people get wrong:
- Forgetting that a value flag takes the next argument whatever it is.
--name --verbosesets the name to--verbose. - Passing negative numbers as positional arguments.
-5looks like a flag and gives "unknown flag"; put--before it, or use--offset=-5for a flag value. - Expecting a bad boolean to be an error.
--verbose=maybeis accepted and reads as false; onlytrue,1,yesandonare true.
Reading the real command line
os.Args returns every argument, with the program's own name first. cli.RemainingArgs drops that first item, which gives exactly what Parse wants. A program then checks three things in order: did parsing fail, was help asked for, and only then does it read the values. Exit with code 2 on a usage error, as most command line tools do.
import cli
import flag
import os
func main:
mut argv := cli.RemainingArgs(os.Args())
defer argv.Free()
if argv.Len() == 0:
each a in ["--name", "Sara", "-n", "2", "--excited"]: argv.Push(a) end
end
mut f := flag.New("greet", "prints a greeting")
defer flag.Free(f)
flag.AddStr(f, "name", "", "world", "who to greet")
flag.AddInt(f, "times", "n", 1, "how many times")
flag.AddBool(f, "excited", "e", false, "end with three exclamation marks")
if not flag.Parse(f, argv):
println "greet:", flag.Error(f)
ret 2
end
if flag.HelpWanted(f):
print flag.Usage(f)
ret 0
end
line := "Hello, " + flag.GetStr(f, "name") + (flag.GetBool(f, "excited") ? "!!!" : ".")
repeat flag.GetInt(f, "times") as int:
println line
end
ret 0
endRun it as salam run greet.salam --name Ali -n 3 to pass your own arguments. When it gets none, as here, it uses a built-in sample so that the output above stays the same.
Reporting bad input
Parse stops at the first problem and returns false, and Error says what went wrong in one line, ready to print. There are four kinds: a value that is not a whole number, a value that is not a decimal, a flag that was never declared, and a flag at the end of the line with no value after it.
import flag
import str
func try_line(line: str): int:
argv := str.Split(line, " ")
defer argv.Free()
mut f := flag.New("resize", "resizes images")
defer flag.Free(f)
flag.AddInt(f, "width", "w", 800, "the new width in pixels")
flag.AddFloat(f, "quality", "q", 0.9, "the JPEG quality")
flag.AddStr(f, "out", "o", "out", "the output directory")
if not flag.Parse(f, argv):
println "error:", flag.Error(f)
ret 2
end
println "ok: width", flag.GetInt(f, "width"), "quality", flag.GetFloat(f, "quality"), "files", flag.Positional(f)
ret 0
end
func main:
each line in ["-w 640 a.jpg", "--width=wide a.jpg", "--quality=0,5 a.jpg", "--height 100", "a.jpg -o"]:
println "$ resize", line
println "exit code", try_line(line)
end
endThe messages are in English. Unknown flags and missing values stop the parse where they occur; numbers are checked after the whole line has been read, in the order the flags were declared. Decimal values need a dot (or the Persian ٫), so 0,5 is rejected. Number flags accept Persian digits as well. When a flag is given twice, the last value wins.
Flag, then environment, then default
Many programs read a setting from a flag, fall back to an environment variable, and use a built-in default last. WasSet makes that possible: it tells "the user typed --port 8080" apart from "8080 is just the default", which GetInt alone cannot.
import env
import flag
import str
func port_from(line: str): i64:
argv := str.Split(line, " ")
defer argv.Free()
mut f := flag.New("server", "")
defer flag.Free(f)
flag.AddInt(f, "port", "p", 8080, "the port to listen on")
flag.Parse(f, argv)
if flag.WasSet(f, "port"): ret flag.GetInt(f, "port") end
ret env.GetInt("PORT", flag.GetInt(f, "port"))
end
func main:
env.Unset("PORT")
println "nothing set:", port_from("app.log")
env.Set("PORT", "3000")
println "PORT=3000:", port_from("app.log")
println "PORT=3000 and -p 9000:", port_from("-p 9000")
println "PORT=3000 and --port=8080:", port_from("--port=8080")
endThe last line matters: --port=8080 is the same number as the default, but the user asked for it explicitly, so it wins over PORT. See env for the environment side.
Short names, booleans and positional arguments
Flags and positional arguments can come in any order. A boolean flag never takes the next argument as its value; to turn off one that defaults to true, write --name=false. After --, even arguments that look like flags are positional, which is how a program accepts a file called -r.
import flag
import str
func main:
argv := str.Split("-r --dry-run=false --depth ۳ src docs -- --not-a-flag -r", " ")
defer argv.Free()
mut f := flag.New("sync", "copies folders")
defer flag.Free(f)
flag.AddBool(f, "recursive", "r", false, "go into subfolders")
flag.AddBool(f, "dry-run", "n", true, "only print what would happen")
flag.AddInt(f, "depth", "d", 1, "how deep to go")
println flag.Parse(f, argv), "[" + flag.Error(f) + "]"
println "recursive:", flag.GetBool(f, "recursive")
println "dry run:", flag.GetBool(f, "dry-run")
println "depth:", flag.GetInt(f, "depth")
pos := flag.Positional(f)
defer pos.Free()
each i, p in pos:
println "arg", i, p
end
endShort names cannot be combined: -rv is read as one flag called rv and gives an "unknown flag" error. Write -r -v instead.
Types
FlagSet
struct FlagSet| Name | Type | Description |
|---|---|---|
prog | str = "" | The program's name, for the help text. |
desc | str = "" | The program's description, for the help text. |
names | Vector | The long names of the flags. |
shorts | Vector | The short names of the flags. |
kinds | Vector | The kind of each flag. |
vals | Vector | The current value of each flag, as text. |
defs | Vector | The default value of each flag. |
helps | Vector | The help line of each flag. |
was_set | Vector | Whether each flag appeared on the command line. |
pos | Vector | The positional arguments. |
err | str = "" | The message of the last parse error. |
help_wanted | bool = false | True when --help was given. |
import flag
func main:
mut f := flag.New("copy", "copies files")
defer flag.Free(f)
flag.AddBool(f, "verbose", "v", false, "report everything")
flag.AddStr(f, "out", "o", "output", "the destination directory")
flag.AddInt(f, "jobs", "j", 1, "how many jobs at once")
flag.AddFloat(f, "ratio", "r", 1.0, "the compression ratio")
mut args := Vector {} as Vector<str>
defer args.Free()
each a in ["-v", "--out=backup", "-j", "4", "a.txt", "b.txt"]:
args.Push(a)
end
println flag.Parse(f, args), "[" + flag.Error(f) + "]"
println flag.GetBool(f, "verbose"), flag.GetStr(f, "out"), flag.GetInt(f, "jobs"), flag.GetFloat(f, "ratio")
println flag.WasSet(f, "jobs"), flag.WasSet(f, "ratio")
println flag.Positional(f), flag.HelpWanted(f)
println flag.FlagKindBool, flag.FlagKindStr, flag.FlagKindInt, flag.FlagKindFloat
endConstants and variables
FlagKindBool
const FlagKindBool: i32 = 0The example for this item is shown with the ones above: flag-Parse.salam
FlagKindStr
const FlagKindStr: i32 = 1The example for this item is shown with the ones above: flag-Parse.salam
FlagKindInt
const FlagKindInt: i32 = 2The example for this item is shown with the ones above: flag-Parse.salam
FlagKindFloat
const FlagKindFloat: i32 = 3The example for this item is shown with the ones above: flag-Parse.salam
Functions
New
func New(prog_name: str, description: str): FlagSetThe example for this item is shown with the ones above: flag-Parse.salam
AddBool
func AddBool(fs &: FlagSet, name: str, short: str, def: bool, help: str)--name=false (or =0, =no) turns it off. It never takes the next argument as its value.The example for this item is shown with the ones above: flag-Parse.salam
AddStr
func AddStr(fs &: FlagSet, name: str, short: str, def: str, help: str)= or the next argument, even one that starts with -.The example for this item is shown with the ones above: flag-Parse.salam
AddInt
func AddInt(fs &: FlagSet, name: str, short: str, def: i64, help: str)The example for this item is shown with the ones above: flag-Parse.salam
AddFloat
func AddFloat(fs &: FlagSet, name: str, short: str, def: f64, help: str)٫, an exponent such as 1e3 and Persian digits are accepted.The example for this item is shown with the ones above: flag-Parse.salam
Parse
func Parse(fs &: FlagSet, arglist: Vector<str>): boolError says why. --help does not make it fail; check HelpWanted.The example for this item is shown with the ones above: flag-Parse.salam
GetStr
func GetStr(fs &: FlagSet, name: str): strThe example for this item is shown with the ones above: flag-Parse.salam
GetInt
func GetInt(fs &: FlagSet, name: str): i64The example for this item is shown with the ones above: flag-Parse.salam
GetFloat
func GetFloat(fs &: FlagSet, name: str): f64The example for this item is shown with the ones above: flag-Parse.salam
GetBool
func GetBool(fs &: FlagSet, name: str): booltrue, 1, yes or on, false for anything else.The example for this item is shown with the ones above: flag-Parse.salam
WasSet
func WasSet(fs &: FlagSet, name: str): boolThe example for this item is shown with the ones above: flag-Parse.salam
Positional
func Positional(fs &: FlagSet): Vector<str>The example for this item is shown with the ones above: flag-Parse.salam
HelpWanted
func HelpWanted(fs &: FlagSet): boolimport flag
func main:
mut f := flag.New("tool", "an example tool")
defer flag.Free(f)
flag.AddBool(f, "quiet", "q", false, "say nothing")
flag.AddInt(f, "port", "p", 8080, "the port")
mut args := Vector {} as Vector<str>
defer args.Free()
args.Push("--help")
flag.Parse(f, args)
if flag.HelpWanted(f):
print flag.Usage(f)
end
mut bad := Vector {} as Vector<str>
defer bad.Free()
bad.Push("--port=abc")
mut f2 := flag.New("tool", "")
defer flag.Free(f2)
flag.AddInt(f2, "port", "p", 8080, "the port")
println flag.Parse(f2, bad), flag.Error(f2)
endError
func Error(fs &: FlagSet): strThe example for this item is shown with the ones above: flag-Usage.salam
Usage
func Usage(fs &: FlagSet): str-h, --help.The example for this item is shown with the ones above: flag-Usage.salam
Free
func Free(fs &: FlagSet)The example for this item is shown with the ones above: flag-Parse.salam