Standard library · System and tools

cli

Command line programs with several commands, like <code>git commit</code>, 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: cli picks the command and a flag set per command reads its options.

•

Full-screen or coloured terminal output: term.

The things people get wrong:

•

Dispatch wants the arguments without the program's name. os.Args includes it, so pass RemainingArgs(os.Args()).

•

help, -h, --help, version, -v and --version are taken by Dispatch, and inside each command flag treats -h and --help as a help request. Never register h as a short flag of your own.

•

Command names match exactly: no prefixes, aliases or case folding, and Register does not reject a duplicate (the first one wins).

•

RemainingArgs returns a new vector; free it with defer 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.

cli-guide-subcommands.salam
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
end
Output
$ todo add -p 1 buy milk
added [buy milk] with priority 1
exit 0
$ todo list --all
listing all tasks
exit 0
$ todo add --priority=high call mom
todo add: invalid int value for --priority: high
exit 2
$ todo add --help
Usage: todo add [options] [args]
  adds a task
Options:
  -p, --priority <int>  1 is the most urgent (default: 3)
  -h, --help  show this help
exit 0
$ todo --version
todo 0.3.0
exit 0
$ todo remove 3
todo: unknown command: remove
todo 0.3.0
a small task list

Usage: todo <command> [options]

Commands:
  add           add a task
  list          show the tasks

Run 'todo <command> --help' for help on a specific command.
exit 2

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

cli-guide-main.salam
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
end
Output
notes 1.2.0
keeps short notes

Usage: notes <command> [options]

Commands:
  new           write a new note
  show          print every note

Run 'notes <command> --help' for help on a specific command.

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

cli-guide-required.salam
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
end
Output
$ deploy -H example.com -u sara
deploying to sara@example.com port 22
exit 0
$ deploy --host=example.com -p 2222
deploy: missing --user
exit 2
$ deploy -p 2222
deploy: missing --host, --user
exit 2

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

cli-guide-noninteractive.salam
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
end
Output
language (english): 
create demo in english? [y/N]: 
nothing created; pass --yes to skip the question

This 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

A command line program and its commands.

NameTypeDescription
namestr = ""The program's name.
descstr = ""The program's description.
versionstr = ""The program's version.
cmd_namesVector<str>The names of the commands.
cmd_descsVector<str>The descriptions of the commands.
cli-Dispatch.salam
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)
end
Output
true run the tests
running: build ["--fast"]
help was asked for
version: 1.0.0
unknown command
salamctl 1.0.0
project management

Usage: salamctl <command> [options]

Commands:
  build         build the project
  test          run the tests

Run 'salamctl <command> --help' for help on a specific command.

Constants and variables

CmdHelp

#
const CmdHelp: str = "__help__"

What 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__"

What 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__"

What 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): App

Creates a program with a name, a description and a version.

The example for this item is shown with the ones above: cli-Dispatch.salam

Register

#
func Register(app &: App, name: str, desc: str)

Adds one command with its description. Commands appear in 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): bool

True when the command has been registered.

The example for this item is shown with the ones above: cli-Dispatch.salam

CommandDesc

#
func CommandDesc(app &: App, name: str): str

The description of a command.

The example for this item is shown with the ones above: cli-Dispatch.salam

Dispatch

#
func Dispatch(app &: App, argv: Vector<str>): str

Says from the first argument which command was asked for: its name, or CmdHelp, 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>

A new vector with every argument after the first, for handing to the flag package. Use it once to drop the program name from 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): str

The program's overall help text: name and version, description, a usage line and the commands with their descriptions. It ends with a line break, so print it with print.

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>

Of the names you give, returns the flags that were not typed on the command line, in the same order. A flag given with an empty value, such as --host=, counts as typed.

cli-RequireFlags.salam
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)
end
Output
missing: ["user"]

Confirm

#
func Confirm(question: str): bool

Prints the question with [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.

cli-Prompt.salam
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
end

Prompt

#
func Prompt(question: str): str

Prints the question followed by : , 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): str

Like Prompt, 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