Argmas

Muscle memory for AI. Solve it once in Temper, and every language remembers.

One command line, the same in seven languages.

Declare a program’s options, arguments, and subcommands once, and Argmas parses them, writes the help, explains mistakes, and completes them in the shell, with the same behavior in C++, C#, Java, JavaScript, Lua, Python, and Rust. A tool rewritten in another language keeps its command line, down to the last error message.

The tour’s pack, declared in each language

cli = Command(CommandSpec(name="pack", about="Pack files into archives.", version="1.0.0"))
verbose = cli.flag(FlagSpec(name="verbose", short="v", help="Say what's happening.", inherited=True))

add = cli.subcommand(SubcommandSpec(name="add", about="Add files to an archive."))
level = add.option_or(ints, 6, OptionSpec(name="level", short="l", help="How hard to compress.", env="PACK_LEVEL"))
mode = add.option(choices(["fast", "small"]), OptionSpec(name="mode", help="What to favor."))
archive = add.positional(strings, PositionalSpec(name="ARCHIVE", help="The archive to add to."))
files = add.positionals(strings, PositionalSpec(name="FILE", min=1, help="Files to add."))

list_ = cli.subcommand(SubcommandSpec(name="list", about="List an archive's files.", aliases=["ls"]))
listed = list_.positional(strings, PositionalSpec(name="ARCHIVE", help="The archive to list."))

From demos/tour/py/tour.py

What every one of them prints

pack --help
Pack files into archives.

Usage: pack [OPTIONS] COMMAND

Commands:
  add            Add files to an archive.
  list           List an archive's files. [aliases: ls]
  help           Show help for a command.

Options:
  -v, --verbose  Say what's happening.
  -h, --help     Show this help and exit.
      --version  Show the version and exit.
exit status 0
pack ad out.pack
pack: unknown command 'ad'; did you mean add?
Usage: pack [OPTIONS] COMMAND
Try 'pack --help' for more information.
exit status 2

Same help, same errors, same exit status, whichever language runs it.

Try it

This runs pack, the tour’s JavaScript version, right in this page, with Argmas built to JavaScript. Type a command line, or pick one of the 9 that CI runs in every language. Run parses it; Tab asks for completions, as a shell would. Settings such as PACK_LEVEL=7 before pack are its environment.

pack add --mode quick out.pack a.txt
pack: invalid value 'quick' for --mode: expected one of fast, small
Usage: pack add [OPTIONS] ARCHIVE FILE...
Try 'pack add --help' for more information.
exit status 2

The output above was made when this page was built, by running the same JavaScript in Node; pressing Run makes it again, here.

Argument styles

Unix tools write --verbose, Go’s write -verbose, and Windows tools write /verbose. A command picks its style, and the same declaration parses, writes help, and reports mistakes that way. Here is one frob in all three:

def frob(style):
    cli = Command(CommandSpec(name="frob", about="Frobnicate files.", style=style))
    verbose = cli.flag(FlagSpec(name="verbose", short="v", help="Say more."))
    level = cli.option_or(ints, 3, OptionSpec(name="level", short="l", help="How hard."))
    files = cli.positionals(strings, PositionalSpec(name="FILE", help="Files to frobnicate."))
    return cli, verbose, level, files

gnu = frob(Style.gnu)
go = frob(Style.single_dash)
windows = frob(Style.windows)

From demos/tour/py/examples.py

Style.gnu

-v, -abc, --verbose, --out=f
most Unix tools

The same, each way:

  • frob -v --level=5 a.txt
  • frob -vl5 a.txt
  • frob --verbose -l 5 a.txt

Each runs with, in Python:

verbose = True
level = 5
files = ['a.txt']

Its help, wrapped to 42 columns:

frob --help
Frobnicate files.

Usage: frob [OPTIONS] [FILE]...

Arguments:
  FILE...       Files to frobnicate.

Options:
  -v, --verbose
                Say more.
  -l, --level <LEVEL>
                How hard. [default: 3]
  -h, --help    Show this help and exit.
exit status 0

A mistake:

frob --level=high a.txt
frob: invalid value 'high' for --level: expected an integer
Usage: frob [OPTIONS] [FILE]...
Try 'frob --help' for more information.
exit status 2

Style.singleDash

-verbose, -out=f, -out f
Go's flag, Java's tools

The same, each way:

  • frob -v -level=5 a.txt
  • frob -verbose -level 5 a.txt
  • frob --verbose --level=5 a.txt

Each runs with, in Python:

verbose = True
level = 5
files = ['a.txt']

Its help, wrapped to 42 columns:

frob -help
Frobnicate files.

Usage: frob [OPTIONS] [FILE]...

Arguments:
  FILE...       Files to frobnicate.

Options:
  -v, -verbose  Say more.
  -l, -level <LEVEL>
                How hard. [default: 3]
  -h, -help     Show this help and exit.
exit status 0

A mistake:

frob -level=high a.txt
frob: invalid value 'high' for -level: expected an integer
Usage: frob [OPTIONS] [FILE]...
Try 'frob -help' for more information.
exit status 2

Style.windows

/v, /out:f, /out f, /?
Windows command-line tools

The same, each way:

  • frob /v /level:5 a.txt
  • frob /VERBOSE /level 5 a.txt
  • frob -verbose -level=5 a.txt

Each runs with, in Python:

verbose = True
level = 5
files = ['a.txt']

Its help, wrapped to 42 columns:

frob /?
Frobnicate files.

Usage: frob [OPTIONS] [FILE]...

Arguments:
  FILE...       Files to frobnicate.

Options:
  /v, /verbose  Say more.
  /l, /level:<LEVEL>
                How hard. [default: 3]
  /?, /help     Show this help and exit.
exit status 0

A mistake:

frob /level:high a.txt
frob: invalid value 'high' for /level: expected an integer
Usage: frob [OPTIONS] [FILE]...
Try 'frob /?' for more information.
exit status 2

Windows names ignore case, as Windows tools do, and a tool moving from one style to another can accept both with alsoStyle. The design notes have every rule.

Subcommands

Subcommands are commands of their own, with their own arguments, help, and errors, as in git add. An option marked inherited works before or after a subcommand’s name. Other options of the parent go before it, and if one comes after, the error says where it belongs instead of guessing at a near miss.

git = Command(CommandSpec(name="minigit", about="Track files."))
quiet = git.flag(FlagSpec(name="quiet", short="q", help="Say less.", inherited=True))
repo = git.option(directories, OptionSpec(name="dir", help="Where the repository is."))

add = git.subcommand(SubcommandSpec(name="add", about="Add files."))
force = add.flag(FlagSpec(name="force", short="f", help="Add ignored files too."))
added = add.positionals(paths, PositionalSpec(name="PATH", min=1, help="Files to add."))

rm = git.subcommand(SubcommandSpec(name="rm", about="Remove files.", aliases=["remove"]))

From demos/tour/py/examples.py

minigit -q add a.txt
The program runs with, in Python
command = 'minigit add'
quiet = True
dir = None
files = ['a.txt']
exit status 0
minigit add -q a.txt
The program runs with, in Python
command = 'minigit add'
quiet = True
dir = None
files = ['a.txt']
exit status 0
minigit --dir repo add a.txt
The program runs with, in Python
command = 'minigit add'
quiet = False
dir = 'repo'
files = ['a.txt']
exit status 0
minigit add --dir repo a.txt
minigit: unknown option --dir; --dir belongs to minigit, so give it before add
Usage: minigit add [OPTIONS] PATH...
Try 'minigit add --help' for more information.
exit status 2
minigit help add
Add files.

Usage: minigit add [OPTIONS] PATH...

Arguments:
  PATH...      Files to add.

Options:
  -f, --force  Add ignored files too.
  -q, --quiet  Say less.
  -h, --help   Show this help and exit.
exit status 0
minigit ad a.txt
minigit: unknown command 'ad'; did you mean add?
Usage: minigit [OPTIONS] COMMAND
Try 'minigit --help' for more information.
exit status 2

Shell completions

Pressing Tab in bash, zsh, fish, or PowerShell runs a short script that asks the program itself what could come next. Argmas answers from the same declaration it parses with, so completions always match what the program accepts, values included, and never need regenerating.

cli = Command(CommandSpec(name="frob", completions=True))
cli.flag(FlagSpec(name="verbose", short="v", help="Say more."))
cli.option(choices(["fast", "slow"]), OptionSpec(name="mode", help="How to go about it."))
cli.option(paths, OptionSpec(name="out", help="Where to write."))

From demos/tour/py/examples.py

Pressing Tab, in a shell that shows descriptions

frob --moTab frob --mode
frob --mode␣Tab fast slow
frob --mode fTab frob --mode fast
frob --Tab --verbose -- Say more. --mode -- How to go about it. --out -- Where to write. --help -- Show this help and exit. --completions -- Print a completion script for a shell and exit.
frob --out=Tab (the shell lists files)

What the shells get

Each Tab runs frob __complete with the position of the word being completed and the words so far. Argmas answers with one candidate a line, each with a tab and its description, if it has one, and last what else the shell should do, such as list files.

Typed, then TabThe script runsArgmas answers
frob --mofrob __complete 0 "--mo"
--mode→How to go about it.
:none
frob --mode␣frob __complete 1 "--mode" ""
fast
slow
:none
frob --mode ffrob __complete 1 "--mode" "f"
fast
:none
frob --frob __complete 0 "--"
--verbose→Say more.
--mode→How to go about it.
--out→Where to write.
--help→Show this help and exit.
--completions→Print a completion script for a shell and exit.
:none
frob --out=frob __complete 0 "--out="
:files --out=

Installing

With completions: true, frob --completions SHELL prints the script. Argmas only prints it; users save it where their shell looks:

ShellInstall
bash 4.4+frob --completions bash > ~/.local/share/bash-completion/completions/frob (with the bash-completion package), or source <(frob --completions bash) in ~/.bashrc
zshfrob --completions zsh > ~/.zfunc/_frob, with fpath=(~/.zfunc $fpath) before compinit in ~/.zshrc
fishfrob --completions fish > ~/.config/fish/completions/frob.fish
PowerShell 5.1+frob --completions powershell | Out-String | Invoke-Expression in your profile ($PROFILE)

zsh, fish, and PowerShell show descriptions, and bash shows only the candidates. Each script, as frob prints it:

frob --completions bash 87 lines
# bash completion for frob, generated by Argmas.
#
# Save this as ~/.local/share/bash-completion/completions/frob for the
# bash-completion package to load when needed, or source it from
# ~/.bashrc. Needs bash 4.4 or later.

_frob_argmas() {
    local line=${COMP_LINE:0:COMP_POINT} words=() word= quote= open=0 started= keep=0 c j
    # bash completes only the part of a word after its last = or :.
    local breaks=${COMP_WORDBREAKS//[^=:]/}
    # The words as the program gets them, without their quotes and
    # backslashes, noting where in the last bash replaces what's typed:
    # after an open quote, or else after its last = or : outside quotes.
    for (( j = 0; j < ${#line}; j++ )); do
        c=${line:j:1}
        if [[ $quote == "'" ]]; then
            if [[ $c == "'" ]]; then quote=; else word+=$c; fi
        elif [[ $quote == '"' ]]; then
            if [[ $c == '"' ]]; then
                quote=
            elif [[ $c == '\' && ${line:j+1:1} == [\"\\\$\`] ]]; then
                word+=${line:j+1:1}
                (( j++ ))
            else
                word+=$c
            fi
        elif [[ $c == [[:space:]] ]]; then
            [[ -n $started ]] && words+=("$word")
            word= started= keep=0
        else
            started=1
            if [[ $c == [\"\'] ]]; then
                quote=$c open=${#word}
            elif [[ $c == '\' ]]; then
                word+=${line:j+1:1}
                (( j++ ))
            else
                word+=$c
                [[ -n $breaks && $c == ["$breaks"] ]] && keep=${#word}
            fi
        fi
    done
    words+=("$word")
    [[ -n $quote ]] && keep=$open
    local cur=$word program=${words[0]} kept=${word:0:keep}
    [[ $program == "~/"* ]] && program=$HOME/${program:2}
    local out lines=() files=() found=() i quoted
    out=$("$program" __complete $(( ${#words[@]} - 2 )) "${words[@]:1}" 2>/dev/null) || return 0
    mapfile -t lines <<< "$out"
    local directive=${lines[${#lines[@]}-1]}
    unset 'lines[${#lines[@]}-1]'
    for i in "${lines[@]}"; do
        i=${i%%$'\t'*}
        [[ -n $i && $i == "$kept"* ]] && found+=("${i:keep}")
    done
    case $directive in
    :files*|:directories*)
        local prefix= option=-f
        [[ $directive == *" "* ]] && prefix=${directive#* }
        [[ $directive == :directories* ]] && option=-d
        if [[ -z $prefix && ${#found[@]} -eq 0 ]]; then
            if [[ $option == -f ]]; then compopt -o default; else compopt -o dirnames; fi
            return 0
        fi
        compopt -o filenames
        mapfile -t files < <(compgen "$option" -- "${cur#"$prefix"}")
        for i in "${files[@]}"; do
            i=$prefix$i
            [[ $i == "$kept"* ]] && found+=("${i:keep}")
        done
        ;;
    esac
    # bash quotes what it inserts, closing an open quote, when told the
    # candidates are file names, as files are; others need that only in
    # a quote or when the shell would read some character in them.
    for i in "${found[@]}"; do
        printf -v quoted %q "$i"
        if [[ -n $quote || $quoted != "$i" ]]; then
            compopt -o filenames
            break
        fi
    done
    COMPREPLY=("${found[@]}")
    return 0
}

complete -F _frob_argmas 'frob'
frob --completions zsh 43 lines
#compdef frob
# zsh completion for frob, generated by Argmas.
#
# Save this as _frob in a directory on $fpath, such as ~/.zfunc with
# fpath=(~/.zfunc $fpath) before compinit in ~/.zshrc, or source it
# after compinit.

_frob_argmas() {
    local -a lines described
    local line directive prefix program=${(Q)words[1]}
    program=${program/#\~/$HOME}
    lines=("${(@f)$("$program" __complete $(( CURRENT - 2 )) "${(@Q)words[2,CURRENT-1]}" "${(Q)PREFIX}" 2>/dev/null)}")
    (( ${#lines} )) || return 1
    directive=${lines[-1]}
    lines[-1]=()
    for line in $lines; do
        [[ -n $line ]] || continue
        if [[ $line == *$'\t'* ]]; then
            described+=("${${line%%$'\t'*}//:/\\:}:${line#*$'\t'}")
        else
            described+=("${line//:/\\:}")
        fi
    done
    local ret=1
    (( ${#described} )) && _describe -t values 'frob' described && ret=0
    case $directive in
    :files*|:directories*)
        [[ $directive == *' '* ]] && compset -P "${(b)directive#* }"
        if [[ $directive == :files* ]]; then
            _files && ret=0
        else
            _files -/ && ret=0
        fi
        ;;
    esac
    return ret
}

if [[ $zsh_eval_context[-1] == loadautofunc ]]; then
    _frob_argmas "$@"
else
    compdef _frob_argmas 'frob'
fi
frob --completions fish 44 lines
# fish completion for frob, generated by Argmas.
#
# Save this as ~/.config/fish/completions/frob.fish.

function __frob_argmas
    set -l words (commandline -opc)
    set -l current (commandline -ct)
    # The word being completed as the program gets it, without its
    # quotes and backslashes, as the other words already are; an open
    # quote is closed first.
    set -l unquoted
    for closing in '' '"' "'"
        if set unquoted (string unescape -- "$current$closing" 2>/dev/null)
            set current "$unquoted"
            break
        end
    end
    set -l arguments $words
    set -e arguments[1]
    set -l lines ($words[1] __complete (count $arguments) $arguments $current 2>/dev/null)
    or return
    set -q lines[1]
    or return
    set -l directive $lines[-1]
    set -e lines[-1]
    for line in $lines
        test -n "$line"
        and echo $line
    end
    set -l prefix (string replace -r '^:\S+ ?' '' -- $directive)
    set -l path (string sub -s (math (string length -- "$prefix") + 1) -- "$current")
    switch $directive
        case ':files*'
            for p in (__fish_complete_path "$path")
                echo $prefix$p
            end
        case ':directories*'
            for p in (__fish_complete_directories "$path")
                echo $prefix$p
            end
    end
end

complete -c 'frob' -f -a '(__frob_argmas)'
frob --completions powershell 50 lines
# PowerShell completion for frob, generated by Argmas.
#
# Add this to your profile (the file $PROFILE names), or save it and
# dot-source it from there, but not as frob.ps1 in a directory on
# PATH, where PowerShell would run it in place of frob. Needs
# PowerShell 5.1 or later.

Register-ArgumentCompleter -Native -CommandName @('frob', 'frob.exe') -ScriptBlock {
    param($wordToComplete, $commandAst, $cursorPosition)
    $words = @()
    foreach ($element in $commandAst.CommandElements) {
        $extent = $element.Extent
        if ($extent.StartOffset -ge $cursorPosition) { break }
        $text = $extent.Text
        if ($extent.EndOffset -gt $cursorPosition) {
            $text = $text.Substring(0, $cursorPosition - $extent.StartOffset)
        } elseif ($element -is [System.Management.Automation.Language.StringConstantExpressionAst]) {
            $text = $element.Value
        }
        $words += $text
    }
    $arguments = @($words | Select-Object -Skip 1)
    $index = $arguments.Count
    if ($wordToComplete -ne '') { $index -= 1 }
    $lines = @(& $words[0] __complete $index @arguments 2>$null)
    if ($lines.Count -eq 0) { return }
    $directive = $lines[-1]
    $results = @()
    foreach ($line in ($lines | Select-Object -SkipLast 1)) {
        if ($line -eq '') { continue }
        $value, $description = $line -split "`t", 2
        if (-not $description) { $description = $value }
        $text = $value
        if ($value -match '[\s''"`$;,(){}|&<>@#]') { $text = "'" + ($value -replace "'", "''") + "'" }
        $results += [System.Management.Automation.CompletionResult]::new($text, $value, 'ParameterValue', $description)
    }
    if ($directive -match '^:(files|directories)(?: (.*))?$') {
        $kind = $Matches[1]
        $prefix = "$($Matches[2])"
        # With nothing else to offer, PowerShell completes files itself,
        # but directories only here.
        if ($kind -eq 'files' -and $prefix -eq '' -and $results.Count -eq 0) { return }
        $part = $wordToComplete.Substring([Math]::Min($prefix.Length, $wordToComplete.Length))
        foreach ($path in [System.Management.Automation.CompletionCompleters]::CompleteFilename($part)) {
            if ($kind -eq 'directories' -and $path.ResultType -ne 'ProviderContainer') { continue }
            $results += [System.Management.Automation.CompletionResult]::new($prefix + $path.CompletionText, $path.ListItemText, $path.ResultType, $path.ToolTip)
        }
    }
    $results
}

Messages and translations

Everything Argmas writes itself, from Usage: to each error and suggestion, comes from one table of messages, English unless the program sets its own. Each message has a stable key and named placeholders, so a translation can put them in its own order, and a key left out stays English. The program’s own text, such as its options’ help, is the program’s to translate.

def frob_with(messages):
    cli = Command(CommandSpec(name="frob", about="Frobnicate files."))
    cli.option_or(ints, 3, OptionSpec(name="level", short="l", help="How hard."))
    cli.set_messages(messages)
    return cli

english = frob_with({})
# A partial translation: what isn't set stays English.
german = frob_with(
    {
        "usage": "Aufruf: {command}",
        "usage.options": "[OPTIONEN]",
        "help.options": "Optionen:",
        "help.default": "[Vorgabe: {value}]",
        "error.unknownOption.suggest": "unbekannte Option {option}; meinten Sie {suggestion}?",
        "error.tryHelp": "Mehr dazu mit '{command} {help}'.",
    }
)
# A typo in a key is a mistake in the spec, found on the first run.
typo = frob_with({"usge": "Aufruf: {command}"})

From demos/tour/py/examples.py

English, built in

frob --help
Frobnicate files.

Usage: frob [OPTIONS]

Options:
  -l, --level <LEVEL>  How hard. [default: 3]
  -h, --help           Show this help and exit.
exit status 0
frob --levle 5
frob: unknown option --levle; did you mean --level?
Usage: frob [OPTIONS]
Try 'frob --help' for more information.
exit status 2

Partly German

frob --help
Frobnicate files.

Aufruf: frob [OPTIONEN]

Optionen:
  -l, --level <LEVEL>  How hard. [Vorgabe: 3]
  -h, --help           Show this help and exit.
exit status 0
frob --levle 5
frob: unbekannte Option --levle; meinten Sie --level?
Aufruf: frob [OPTIONEN]
Mehr dazu mit 'frob --help'.
exit status 2

A typo in a key is caught on the first run:

frob --help
frob: invalid command spec: unknown message key 'usge'
Usage: frob [OPTIONS]
Try 'frob --help' for more information.
exit status 2

The design notes list every key with its English text. Argmas never guesses the user’s language; the program picks a table, as the README shows.

Errors are values

Parsing never prints, exits, or throws. It returns one of three values: Args, to run with; Output, help or a version to print before exiting with status 0; or ArgError, a mistake to print to standard error before exiting with status 2. Nothing outside is touched: the program passes the arguments and, for environment variables, an Environment. That makes a command line easy to test, and easy to embed in a program that isn’t a command-line tool.

# Values to run with, text to print (help and version), or a mistake.
result = cli.parse(sys.argv[1:], OsEnvironment())
match result:
    case Args():
        args = result
        if args.command == add:
            print(f"add to {args.get_value(archive)}: {', '.join(args.get_value(files))}")
            source = args.source(level.param)
            origin = "default" if source == Source.absent else source.name
            print(f"level: {args.get_value(level)} ({origin})")
            print(f"mode: {args.get_maybe(mode) or 'any'}")
        elif args.command == list_:
            print(f"list {args.get_value(listed)}")
        print(f"verbose: {'yes' if args.get_value(verbose) else 'no'}")
    case Output():
        sys.stdout.write(result.text())
    case ArgError():
        sys.stderr.write(result.text())
sys.exit(result.exit_status)

From demos/tour/py/tour.py

  • One behavior to learn. A team with tools in several languages gets one set of rules for --, bundled flags, negative numbers, and option values, instead of each library’s own.
  • One set of docs. Help and errors read the same in every language, so documentation, tutorials, and scripts written for one version of a tool fit the others.
  • Tested once, in every language. Argmas’s tests run on all seven, and CI checks that the tour prints exactly the same in each, that completions work in real shells on Linux, macOS, and Windows, and that command lines parse as with getopt_long, argparse, and clap, except where the design says why not.
  • Port without surprises. Rewriting a tool in another language keeps its command line, so nobody’s scripts break.

Get started

Argmas isn’t released yet. There are no packages to install, and it’s built with Temper’s new compiler, which isn’t released either. For now, build the compiler from source at the commit Argmas’s CI pins (see test.yml), then build Argmas for your language and depend on it by path, as each tour does:

  1. Build the Python library, from a clone of Argmas:
    temper build -b py
    It lands in temper.out/py/.
  2. Depend on it by path, as demos/tour/py/pyproject.toml does.
  3. Or run the tour, in demos/tour/py:
    uv run tour.py add -v out.pack a.txt

docs/languages.md shows what the API looks like in each language, and what still reads awkwardly there.