Standard library · System and tools

flag

Reading command line options such as <code>--port 8080</code> and <code>-v</code> 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 --verbose sets the name to --verbose.

•

Passing negative numbers as positional arguments. -5 looks like a flag and gives "unknown flag"; put -- before it, or use --offset=-5 for a flag value.

•

Expecting a bad boolean to be an error. --verbose=maybe is accepted and reads as false; only true, 1, yes and on are 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.

flag-guide-args.salam
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
end
Output
Hello, Sara!!!
Hello, Sara!!!

Run 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.

flag-guide-errors.salam
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
end
Output
$ resize -w 640 a.jpg
ok: width 640 quality 0.9 files ["a.jpg"]
exit code 0
$ resize --width=wide a.jpg
error: invalid int value for --width: wide
exit code 2
$ resize --quality=0,5 a.jpg
error: invalid float value for --quality: 0,5
exit code 2
$ resize --height 100
error: unknown flag: --height
exit code 2
$ resize a.jpg -o
error: missing value for flag: -o
exit code 2

The 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.

flag-guide-precedence.salam
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")
end
Output
nothing set: 8080
PORT=3000: 3000
PORT=3000 and -p 9000: 9000
PORT=3000 and --port=8080: 8080

The 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.

flag-guide-positional.salam
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
end
Output
true []
recursive: true
dry run: false
depth: 3
arg 0 src
arg 1 docs
arg 2 --not-a-flag
arg 3 -r

Short 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

A program's set of flags and the result of parsing.

NameTypeDescription
progstr = ""The program's name, for the help text.
descstr = ""The program's description, for the help text.
namesVector<str>The long names of the flags.
shortsVector<str>The short names of the flags.
kindsVector<int>The kind of each flag.
valsVector<str>The current value of each flag, as text.
defsVector<str>The default value of each flag.
helpsVector<str>The help line of each flag.
was_setVector<bool>Whether each flag appeared on the command line.
posVector<str>The positional arguments.
errstr = ""The message of the last parse error.
help_wantedbool = falseTrue when --help was given.
flag-Parse.salam
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
end
Output
true []
true backup 4 1
true false
["a.txt", "b.txt"] false
0 1 2 3

Constants and variables

FlagKindBool

#
const FlagKindBool: i32 = 0

The kind of a boolean flag.

The example for this item is shown with the ones above: flag-Parse.salam

FlagKindStr

#
const FlagKindStr: i32 = 1

The kind of a string flag.

The example for this item is shown with the ones above: flag-Parse.salam

FlagKindInt

#
const FlagKindInt: i32 = 2

The kind of a whole number flag.

The example for this item is shown with the ones above: flag-Parse.salam

FlagKindFloat

#
const FlagKindFloat: i32 = 3

The kind of a decimal flag.

The example for this item is shown with the ones above: flag-Parse.salam

Functions

New

#
func New(prog_name: str, description: str): FlagSet

Creates a new flag set with the program's name and description.

The 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)

Declares a boolean flag; it turns true when present, and --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)

Declares a string flag. Its value is the text after = 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)

Declares a whole number flag; a sign and Persian digits are accepted, anything else fails the parse.

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)

Declares a decimal flag; a dot or ٫, 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>): bool

Parses the arguments, not including the program name. On an unknown flag, a missing value or a bad number it returns false and Error 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): str

The value of a string flag, or its default; empty for a name that was never declared.

The example for this item is shown with the ones above: flag-Parse.salam

GetInt

#
func GetInt(fs &: FlagSet, name: str): i64

The value of a whole number flag.

The example for this item is shown with the ones above: flag-Parse.salam

GetFloat

#
func GetFloat(fs &: FlagSet, name: str): f64

The value of a decimal flag.

The example for this item is shown with the ones above: flag-Parse.salam

GetBool

#
func GetBool(fs &: FlagSet, name: str): bool

The value of a boolean flag: true for true, 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): bool

True when the flag appeared on the command line; for telling "the default" apart from "the user asked for exactly this".

The example for this item is shown with the ones above: flag-Parse.salam

Positional

#
func Positional(fs &: FlagSet): Vector<str>

A copy of the positional arguments, in order; free it when done.

The example for this item is shown with the ones above: flag-Parse.salam

HelpWanted

#
func HelpWanted(fs &: FlagSet): bool

True when the user asked for help.

flag-Usage.salam
import 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)
end
Output
Usage: tool [options] [args]
  an example tool
Options:
  -q, --quiet  say nothing
  -p, --port <int>  the port (default: 8080)
  -h, --help  show this help
false invalid int value for --port: abc

Error

#
func Error(fs &: FlagSet): str

The message of the last parse error.

The example for this item is shown with the ones above: flag-Usage.salam

Usage

#
func Usage(fs &: FlagSet): str

The full help text: a usage line, the description, and one line per flag with its short name, kind, help and default, followed by -h, --help.

The example for this item is shown with the ones above: flag-Usage.salam

Free

#
func Free(fs &: FlagSet)

Releases the set's memory.

The example for this item is shown with the ones above: flag-Parse.salam