args — command-line flags
mzs
include argsWARNING
Not available in bot scripts: a bot script has no command line.
| Function | What it does |
|---|---|
args.parse(spec, opts = {}) | $ARGV → a dict: each flag under its key from spec, plus rest for the positional ones |
args.usage(spec, opts = {}) | the help text, the same one --help prints |
Everything after the script path is the script's arguments: mzs resize.mzs --width 640 photo.png.
Describing flags
The key is the flag (dry_run → --dry-run); the value is a dict or just the default value.
| Key | Meaning |
|---|---|
default | the value without the flag; its type sets the conversion |
help | a line for the help text |
short | one letter: short: "q" → -q |
required | true: the flag is mandatory |
| Default | On the command line | Value |
|---|---|---|
false / true | --force, --no-force | bool |
int | --width 800, --width=800 | int |
float | --quality 0.5 | float |
a string or nil | --out x | a string |
[] | --tag a --tag b | an array of strings |
| Option | What it does |
|---|---|
usage | the line after usage: in the help text |
min, max | how many positional arguments are allowed |
argv | parse this array instead of $ARGV |
exit | false: raise an error instead of exiting |
Parse
mzs
include args
spec = {
width: {default: 800, help: "width in pixels"},
quality: {default: 0.85, short: "q"},
force: {default: false, short: "f"},
tag: [],
}
args.parse(spec) # → {"width":800,"quality":0.85,"force":false,"tag":[],"rest":[]}
args.parse(spec, {argv: ["--width", "640", "-fq", "0.5", "--tag", "web", "--tag", "hero", "photo.png"]}) # → {"width":640,"quality":0.5,"force":true,"tag":["web","hero"],"rest":["photo.png"]}
args.parse({dry_run: true}, {argv: ["--no-dry-run"]}) # → {"dry_run":false,"rest":[]}- Short bools combine:
-fv; the last one may take a value:-fq 0.5. --ends the flags.- A repeated flag keeps the last value; an array keeps all.
Help
-h and --help always exist: they print the help and end the script with code 0.
mzs
include args
print(args.usage({width: {default: 800, help: "width in pixels"}, force: {default: false, short: "f"}}, {usage: "resize [flags] <file>…"}))text
usage: resize [flags] <file>…
flags:
-h, --help show this help
--width <int> width in pixels (default 800)
-f, --forceErrors
An unknown flag, a bad value, too few arguments: a message and the help go to stderr, exit code 2.
sh
$ mzs resize.mzs --widht 640 photo.png
resize: unknown flag --widht (did you mean --width?)With exit: false: an argument error with {flag, reason} in data; that is how tests check the parsing.
mzs
include args
spec = {width: 800, quality: 0.85}
try args.parse(spec, {argv: ["--quality", "fast"], exit: false}) else (e) -> e["data"] # → {"flag":"--quality","reason":"bad_value"}
try args.parse(spec, {argv: ["--widht", "9"], exit: false}) else (e) -> e["data"]["reason"] # → "unknown"
try args.parse(spec, {argv: [], exit: false, min: 1}) else (e) -> e["data"]["reason"] # → "too_few"