cli
Command line programs with several commands, like git commit, and asking the user questions.
import cli
Many tools have several commands: git commit, salam build, salam run. The cli package holds the list of commands, works out from the first argument which one was asked for, and builds the overall help text. It also asks the user questions in the terminal with Prompt, PromptOr and Confirm.
It is deliberately small and does not parse options. Pick the package by the shape of your program:
- One command with options, such as
resize --width 800 photo.png: flag alone is enough. - Several commands, each with its own options:
clipicks the command and a flag set per command reads its options. - Full-screen or coloured terminal output: term.
The things people get wrong:
Dispatchwants the arguments without the program's name. os.Args includes it, so passRemainingArgs(os.Args()).help,-h,--help,version,-vand--versionare taken byDispatch, and inside each command flag treats-hand--helpas a help request. Never registerhas a short flag of your own.- Command names match exactly: no prefixes, aliases or case folding, and
Registerdoes not reject a duplicate (the first one wins). RemainingArgsreturns a new vector; free it withdefer rest.free().
A tool with several commands
The usual shape: Dispatch picks the command from the first argument, RemainingArgs hands everything after it to that command, and each command declares its own flag set, so todo add and todo list can have different options. Each command returns an exit code.
import cli
import flag
import str
func cmd_add(argv: Vector<str>): int:
mut f := flag.New("todo add", "adds a task")
defer flag.Free(f)
flag.AddInt(f, "priority", "p", 3, "1 is the most urgent")
if not flag.Parse(f, argv):
println "todo add:", flag.Error(f)
ret 2
end
if flag.HelpWanted(f):
print flag.Usage(f)
ret 0
end
words := flag.Positional(f)
defer words.Free()
println "added [" + str.Join(words, " ") + "] with priority", flag.GetInt(f, "priority")
ret 0
end
func cmd_list(argv: Vector<str>): int:
mut f := flag.New("todo list", "lists the tasks")
defer flag.Free(f)
flag.AddBool(f, "all", "a", false, "include finished tasks")
if not flag.Parse(f, argv):
println "todo list:", flag.Error(f)
ret 2
end
println "listing", flag.GetBool(f, "all") ? "all tasks" : "open tasks"
ret 0
end
func run(app &: cli.App, line: str): int:
argv := str.Split(line, " ")
defer argv.Free()
command := cli.Dispatch(app, argv)
rest := cli.RemainingArgs(argv)
defer rest.Free()
if command == "add": ret cmd_add(rest) end
if command == "list": ret cmd_list(rest) end
if command == cli.CmdVersion:
println app.name, app.version
ret 0
end
if command == cli.CmdUnknown: println "todo: unknown command:", argv.Get(0) end
print cli.Usage(app)
ret command == cli.CmdHelp ? 0 : 2
end
func main:
mut app := cli.New("todo", "a small task list", "0.3.0")
cli.Register(app, "add", "add a task")
cli.Register(app, "list", "show the tasks")
each line in ["add -p 1 buy milk", "list --all", "add --priority=high call mom", "add --help", "--version", "remove 3"]:
println "$ todo", line
println "exit", run(app, line)
end
endcli.Usage ends with a hint to run todo <command> --help, but answering it is each command's job: check flag.HelpWanted after parsing and print flag.Usage, as add does here. Both help texts are generated in English; only your descriptions appear as you wrote them.
Wiring it to the real arguments
In a real program the arguments come from os.Args. Drop the program's own name with RemainingArgs and pass the rest to Dispatch. With no arguments at all Dispatch returns CmdHelp, so running the tool bare prints its help, which is what users expect.
import cli
import os
func main:
mut app := cli.New("notes", "keeps short notes", "1.2.0")
cli.Register(app, "new", "write a new note")
cli.Register(app, "show", "print every note")
argv := cli.RemainingArgs(os.Args())
defer argv.Free()
command := cli.Dispatch(app, argv)
if command == cli.CmdHelp:
print cli.Usage(app)
ret 0
else command == cli.CmdVersion:
println app.version
ret 0
else command == cli.CmdUnknown:
println "notes: no such command:", argv.Get(0)
ret 2
end
println "running", command, "with", cli.RemainingArgs(argv)
ret 0
endThe output above is what it prints with no arguments. Try salam run notes.salam show --all or salam run notes.salam --version.
Required flags
A flag with no sensible default, such as the server to deploy to, should be required. RequireFlags takes the names that must appear and returns the ones that did not, so you can report all of them at once instead of one per run.
import cli
import flag
import str
func deploy(line: str): int:
argv := str.Split(line, " ")
defer argv.Free()
mut f := flag.New("deploy", "uploads a release")
defer flag.Free(f)
flag.AddStr(f, "host", "H", "", "the server to deploy to")
flag.AddStr(f, "user", "u", "", "the login name")
flag.AddInt(f, "port", "p", 22, "the SSH port")
if not flag.Parse(f, argv):
println "deploy:", flag.Error(f)
ret 2
end
mut required := Vector {} as Vector<str>
defer required.Free()
required.Push("host")
required.Push("user")
missing := cli.RequireFlags(f, required)
defer missing.Free()
if missing.Len() > 0:
println "deploy: missing --" + str.Join(missing, ", --")
ret 2
end
println "deploying to", flag.GetStr(f, "user") + "@" + flag.GetStr(f, "host"), "port", flag.GetInt(f, "port")
ret 0
end
func main:
each line in ["-H example.com -u sara", "--host=example.com -p 2222", "-p 2222"]:
println "$ deploy", line
println "exit", deploy(line)
end
endIt uses flag.WasSet, so it checks that the flag was typed, not that it has a value: --host= counts as given. Check for an empty string too when that matters.
Questions that also work in scripts
PromptOr and Confirm read one line from standard input. When nothing is typed, or the program runs in a script with no terminal, PromptOr returns its default and Confirm returns false, so a forgotten question never does something dangerous. Give every question a flag too, here --name and --yes, so the program can run without anyone at the keyboard.
import cli
import flag
import str
func main:
argv := str.Split("--name demo", " ")
defer argv.Free()
mut f := flag.New("init", "creates a project")
defer flag.Free(f)
flag.AddStr(f, "name", "", "", "the project name")
flag.AddBool(f, "yes", "y", false, "do not ask for confirmation")
flag.Parse(f, argv)
mut name := flag.GetStr(f, "name")
if name.Len() == 0: name = cli.PromptOr("project name", "my-app") end
language := cli.PromptOr("language", "english")
println ""
mut go_on := flag.GetBool(f, "yes")
if not go_on: go_on = cli.Confirm("create " + name + " in " + language + "?") end
println ""
if go_on:
println "created", name
else:
println "nothing created; pass --yes to skip the question"
end
endThis output is what happens with standard input empty, as in a CI job: the language question takes its default and the confirmation is refused. The questions end without a line break because nobody pressed Enter.
Types
App
struct App| Name | Type | Description |
|---|---|---|
name | str = "" | The program's name. |
desc | str = "" | The program's description. |
version | str = "" | The program's version. |
cmd_names | Vector | The names of the commands. |
cmd_descs | Vector | The descriptions of the commands. |
import cli
import str
func run(app &: cli.App, line: str):
args := str.Split(line, " ")
command := cli.Dispatch(app, args)
if command == cli.CmdHelp:
println "help was asked for"
else command == cli.CmdVersion:
println "version:", app.version
else command == cli.CmdUnknown:
println "unknown command"
else:
println "running:", command, cli.RemainingArgs(args)
end
args.Free()
end
func main:
mut app := cli.New("salamctl", "project management", "1.0.0")
cli.Register(app, "build", "build the project")
cli.Register(app, "test", "run the tests")
println cli.HasCommand(app, "build"), cli.CommandDesc(app, "test")
each line in ["build --fast", "--help", "--version", "deploy"]:
run(app, line)
end
print cli.Usage(app)
endConstants and variables
CmdHelp
const CmdHelp: str = "__help__"Dispatch returns when help was asked for, or no argument was given.The example for this item is shown with the ones above: cli-Dispatch.salam
CmdVersion
const CmdVersion: str = "__version__"Dispatch returns when the version was asked for.The example for this item is shown with the ones above: cli-Dispatch.salam
CmdUnknown
const CmdUnknown: str = "__unknown__"Dispatch returns for a command that was never registered.The example for this item is shown with the ones above: cli-Dispatch.salam
Functions
New
func New(name: str, desc: str, version: str): AppThe example for this item is shown with the ones above: cli-Dispatch.salam
Register
func Register(app &: App, name: str, desc: str)Usage in the order they were registered; a duplicate name is not rejected.The example for this item is shown with the ones above: cli-Dispatch.salam
HasCommand
func HasCommand(app &: App, name: str): boolThe example for this item is shown with the ones above: cli-Dispatch.salam
CommandDesc
func CommandDesc(app &: App, name: str): strThe example for this item is shown with the ones above: cli-Dispatch.salam
Dispatch
func Dispatch(app &: App, argv: Vector<str>): strCmdHelp, CmdVersion or CmdUnknown. Pass the arguments without the program's name. help, -h and --help give CmdHelp, as does an empty list; version, -v and --version give CmdVersion.The example for this item is shown with the ones above: cli-Dispatch.salam
RemainingArgs
func RemainingArgs(argv: Vector<str>): Vector<str>os.Args() and again to drop the command name. Free the result.The example for this item is shown with the ones above: cli-Dispatch.salam
Usage
func Usage(app &: App): strprint.The example for this item is shown with the ones above: cli-Dispatch.salam
RequireFlags
func RequireFlags(fs &: flag.FlagSet, names: Vector<str>): Vector<str>--host=, counts as typed.import cli
import flag
func main:
mut f := flag.New("deploy", "")
defer flag.Free(f)
flag.AddStr(f, "host", "H", "", "the server")
flag.AddStr(f, "user", "u", "", "the user")
mut args := Vector {} as Vector<str>
defer args.Free()
args.Push("--host=example.com")
flag.Parse(f, args)
mut required := Vector {} as Vector<str>
defer required.Free()
required.Push("host")
required.Push("user")
println "missing:", cli.RequireFlags(f, required)
endConfirm
func Confirm(question: str): bool[y/N]: and reads one line. y or yes, in any case and with spaces around it, is true; anything else, an empty line or the end of input is false.import cli
func main:
name := cli.Prompt("project name")
language := cli.PromptOr("language", "english")
if cli.Confirm("create it?"):
println "creating", name, "in", language
end
endPrompt
func Prompt(question: str): str: , reads one line and returns it with surrounding spaces trimmed. Do not end the question with a colon yourself. At the end of input it returns an empty string.The example for this item is shown with the ones above: cli-Prompt.salam
PromptOr
func PromptOr(question: str, def: str): strPrompt, but shows the default in brackets, as in language (english): , and returns it when the answer is empty.The example for this item is shown with the ones above: cli-Prompt.salam