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
auto cli = Command::make(CommandSpec::make("pack", "Pack files into archives.", "1.0.0"));
// name, short, help, env, negatable, inheritedauto verbose = cli->flag(FlagSpec::make("verbose", "v", "Say what's happening.", nullptr, nullptr, true));
// name, about, aliasesauto add = cli->subcommand(SubcommandSpec::make("add", "Add files to an archive."));
// name, short, help, envauto level = add->optionOr(argmas::ints(), 6, OptionSpec::make("level", "l", "How hard to compress.", "PACK_LEVEL"));
auto mode = add->option(argmas::choices(std::make_shared<Strings>(Strings{"fast", "small"})), OptionSpec::make("mode", nullptr, "What to favor."));
// name, help, minauto archive = add->positional(argmas::strings(), PositionalSpec::make("ARCHIVE", "The archive to add to."));
auto files = add->positionals(argmas::strings(), PositionalSpec::make("FILE", "Files to add.", 1));
auto list = cli->subcommand(SubcommandSpec::make("list", "List an archive's files.", std::make_shared<Strings>(Strings{"ls"})));
auto listed = list->positional(argmas::strings(), PositionalSpec::make("ARCHIVE", "The archive to list."));
var cli = newCommand(newCommandSpec("pack", about: "Pack files into archives.", version: "1.0.0"));
var verbose = cli.Flag(newFlagSpec("verbose", @short: "v", help: "Say what's happening.", inherited: true));
var add = cli.Subcommand(newSubcommandSpec("add", about: "Add files to an archive."));
var level = add.OptionOr(Ints, 6, newOptionSpec("level", @short: "l", help: "How hard to compress.", env: "PACK_LEVEL"));
var mode = add.Option(Choices(new[] { "fast", "small" }), newOptionSpec("mode", help: "What to favor."));
var archive = add.Positional(Strings, newPositionalSpec("ARCHIVE", help: "The archive to add to."));
var files = add.Positionals(Strings, newPositionalSpec("FILE", min: 1, help: "Files to add."));
var list = cli.Subcommand(newSubcommandSpec("list", about: "List an archive's files.", aliases: new[] { "ls" }));
var listed = list.Positional(Strings, newPositionalSpec("ARCHIVE", help: "The archive to list."));
var cli = newCommand(newCommandSpec.Builder().name("pack").about("Pack files into archives.").version("1.0.0").build());
// `short` is a keyword in Java, so its setter is `short_`.var verbose = cli.flag(newFlagSpec.Builder().name("verbose").short_("v").help("Say what's happening.").inherited(true).build());
var add = cli.subcommand(newSubcommandSpec.Builder().name("add").about("Add files to an archive.").build());
var level = add.optionOr(ints, 6, newOptionSpec.Builder().name("level").short_("l").help("How hard to compress.").env("PACK_LEVEL").build());
var mode = add.option(choices(List.of("fast", "small")), newOptionSpec.Builder().name("mode").help("What to favor.").build());
var archive = add.positional(strings, newPositionalSpec.Builder().name("ARCHIVE").help("The archive to add to.").build());
var files = add.positionals(strings, newPositionalSpec.Builder().name("FILE").min(1).help("Files to add.").build());
var list = cli.subcommand(newSubcommandSpec.Builder().name("list").about("List an archive's files.").aliases(List.of("ls")).build());
var listed = list.positional(strings, newPositionalSpec.Builder().name("ARCHIVE").help("The archive to list.").build());
$ 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.packpack: 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.txtpack: 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:
std::shared_ptr<Command> frob(std::shared_ptr<Style> const & style) {
// name, about, version, commandOptional, styleauto cli = Command::make(CommandSpec::make("frob", "Frobnicate files.", nullptr, nullptr, style));
// name, short, help
cli->flag(FlagSpec::make("verbose", "v", "Say more."));
cli->optionOr(argmas::ints(), 3, OptionSpec::make("level", "l", "How hard."));
// name, help
cli->positionals(argmas::strings(), PositionalSpec::make("FILE", "Files to frobnicate."));
return cli;
}
auto gnu = frob(Style::gnu());
auto go = frob(Style::singleDash());
auto windows = frob(Style::windows());
staticCommand frob(Style style) {
var cli = newCommand(newCommandSpec.Builder().name("frob").about("Frobnicate files.").style(style).build());
cli.flag(newFlagSpec.Builder().name("verbose").short_("v").help("Say more.").build());
cli.optionOr(ints, 3, newOptionSpec.Builder().name("level").short_("l").help("How hard.").build());
cli.positionals(strings, newPositionalSpec.Builder().name("FILE").help("Files to frobnicate.").build());
return cli;
}
var gnu = frob(Style.gnu);
var go = frob(Style.singleDash);
var windows = frob(Style.windows);
$ 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.txtfrob: 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.txtfrob: 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.txtfrob: 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.
auto git = Command::make(CommandSpec::make("minigit", "Track files."));
// name, short, help, env, negatable, inheritedauto quiet = git->flag(FlagSpec::make("quiet", "q", "Say less.", nullptr, nullptr, true));
auto repo = git->option(argmas::directories(), OptionSpec::make("dir", nullptr, "Where the repository is."));
// name, about, aliasesauto add = git->subcommand(SubcommandSpec::make("add", "Add files."));
auto force = add->flag(FlagSpec::make("force", "f", "Add ignored files too."));
// name, help, minauto added = add->positionals(argmas::paths(), PositionalSpec::make("PATH", "Files to add.", 1));
auto rm = git->subcommand(SubcommandSpec::make("rm", "Remove files.", std::make_shared<Strings>(Strings{"remove"})));
var git = newCommand(newCommandSpec.Builder().name("minigit").about("Track files.").build());
var quiet = git.flag(newFlagSpec.Builder().name("quiet").short_("q").help("Say less.").inherited(true).build());
var repo = git.option(directories, newOptionSpec.Builder().name("dir").help("Where the repository is.").build());
var add = git.subcommand(newSubcommandSpec.Builder().name("add").about("Add files.").build());
var force = add.flag(newFlagSpec.Builder().name("force").short_("f").help("Add ignored files too.").build());
var added = add.positionals(paths, newPositionalSpec.Builder().name("PATH").min(1).help("Files to add.").build());
var rm = git.subcommand(newSubcommandSpec.Builder().name("rm").about("Remove files.").aliases(List.of("remove")).build());
$ minigit -q add a.txtThe program runs with, in Python
command = 'minigit add'
quiet = True
dir = None
files = ['a.txt']
exit status 0
$ minigit add -q a.txtThe program runs with, in Python
command = 'minigit add'
quiet = True
dir = None
files = ['a.txt']
exit status 0
$ minigit --dir repo add a.txtThe program runs with, in Python
command = 'minigit add'
quiet = False
dir = 'repo'
files = ['a.txt']
exit status 0
$ minigit add --dir repo a.txtminigit: 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.txtminigit: 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.
// name, about, version, commandOptional, style, alsoStyle, completionsauto cli = Command::make(CommandSpec::make("frob", nullptr, nullptr, nullptr, Style::gnu(), nullptr, true));
cli->flag(FlagSpec::make("verbose", "v", "Say more."));
cli->option(argmas::choices(std::make_shared<Strings>(Strings{"fast", "slow"})), OptionSpec::make("mode", nullptr, "How to go about it."));
cli->option(argmas::paths(), OptionSpec::make("out", nullptr, "Where to write."));
var cli = newCommand(newCommandSpec.Builder().name("frob").completions(true).build());
cli.flag(newFlagSpec.Builder().name("verbose").short_("v").help("Say more.").build());
cli.option(choices(List.of("fast", "slow")), newOptionSpec.Builder().name("mode").help("How to go about it.").build());
cli.option(paths, newOptionSpec.Builder().name("out").help("Where to write.").build());
$ 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 Tab
The script runs
Argmas answers
frob --mo
frob __complete 0 "--mo"
--mode→How to go about it.
:none
frob --mode␣
frob __complete 1 "--mode" ""
fast
slow
:none
frob --mode f
frob __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:
Shell
Install
bash 4.4+
frob --completions bash > ~/.local/share/bash-completion/completions/frob (with the bash-completion package), or source <(frob --completions bash) in ~/.bashrc
zsh
frob --completions zsh > ~/.zfunc/_frob, with fpath=(~/.zfunc $fpath) before compinit in ~/.zshrc
fish
frob --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 bash87 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 zsh43 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 fish44 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 powershell50 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.
std::shared_ptr<Command> frobWith(std::map<std::string, std::string> const & messages) {
auto cli = Command::make(CommandSpec::make("frob", "Frobnicate files."));
cli->optionOr(argmas::ints(), 3, OptionSpec::make("level", "l", "How hard."));
// setMessages takes Temper's map type, so a loop is simpler.for (autoconst & message : messages) {
cli->setMessage(message.first, message.second);
}
return cli;
}
auto english = frobWith({});
// A partial translation: what isn't set stays English.auto german = frobWith({
{"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.auto typo = frobWith({{"usge", "Aufruf: {command}"}});
CommandFrobWith(Dictionary<string, string> messages)
{
var cli = newCommand(newCommandSpec("frob", about: "Frobnicate files."));
cli.OptionOr(Ints, 3, newOptionSpec("level", @short: "l", help: "How hard."));
cli.SetMessages(messages);
return cli;
}
var english = FrobWith(new());
// A partial translation: what isn't set stays English.var german = FrobWith(new()
{
["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.var typo = FrobWith(new() { ["usge"] = "Aufruf: {command}" });
staticCommand frobWith(Map<String, String> messages) {
var cli = newCommand(newCommandSpec.Builder().name("frob").about("Frobnicate files.").build());
cli.optionOr(ints, 3, newOptionSpec.Builder().name("level").short_("l").help("How hard.").build());
cli.setMessages(messages);
return cli;
}
var english = frobWith(Map.of());
// A partial translation: what isn't set stays English.var german = frobWith(Map.of(
"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.var typo = frobWith(Map.of("usge", "Aufruf: {command}"));
function frobWith(messages) {
const cli = newCommand(CommandSpec.new({ name: "frob", about: "Frobnicate files." }));
cli.optionOr(ints, 3, OptionSpec.new({ name: "level", short: "l", help: "How hard." }));
cli.setMessages(messages);
return cli;
}
const english = frobWith(newMap());
// A partial translation: what isn't set stays English.const german = frobWith(newMap([
["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.const typo = frobWith(newMap([["usge", "Aufruf: {command}"]]));
localfunction frobWith(messages)
local cli = Command(CommandSpec("frob", "Frobnicate files."))
cli:optionOr(ints, 3, OptionSpec("level", "l", "How hard."))
-- setMessages takes Temper's map type, so a loop over a table is simpler.for key, template in pairs(messages) do
cli:setMessage(key, template)
endreturn cli
endlocal english = frobWith({})
-- A partial translation: what isn't set stays English.local german = frobWith({
["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.local typo = frobWith({ usge = "Aufruf: {command}" })
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}"})
fn frob_with(messages: &[(&str, &str)]) -> Command {
let cli = Command::new(CommandSpecBuilder { name: s("frob") }.options().about(s("Frobnicate files.")).build());
cli.option_or(
ints(),
3,
OptionSpecBuilder { name: s("level") }.options().short(s("l")).help(s("How hard.")).build(),
);
// set_messages takes Temper's map type, so a loop is simpler.for (key, template) in messages {
cli.set_message(*key, *template);
}
cli
}
let english = frob_with(&[]);
// A partial translation: what isn't set stays English.let 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.let typo = frob_with(&[("usge", "Aufruf: {command}")]);
$ 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 5frob: 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 5frob: 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 --helpfrob: 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.var result = cli.Parse(args, newOsEnvironment());
switch (result)
{
caseArgs parsed:
if (parsed.Command.Eq(add))
{
Console.WriteLine($"add to {parsed.GetValue(archive)}: {string.Join(", ", parsed.GetValue(files))}");
var source = parsed.Source(level.Param);
var origin = source.Eq(Source.Absent) ? "default" : source.Name;
Console.WriteLine($"level: {parsed.GetValue(level)} ({origin})");
// GetMaybe gives Temper's Optional, for value types as well as// references; OrNull makes it a nullable reference.Console.WriteLine($"mode: {parsed.GetMaybe(mode).OrNull() ?? "any"}");
}
elseif (parsed.Command.Eq(list))
{
Console.WriteLine($"list {parsed.GetValue(listed)}");
}
Console.WriteLine($"verbose: {(parsed.GetValue(verbose) ? "yes" : "no")}");
break;
caseOutput output:
Console.Write(output.Text());
break;
caseArgError error:
Console.Error.Write(error.Text());
break;
}
return result.ExitStatus;
-- Values to run with, text to print (help and version), or a mistake.local result = cli:parse({ ... }, env)
if temper.instance_of(result, Args) thenlocal args = result
if args.command:eq(add) then
print(("add to %s: %s"):format(args:getValue(archive), table.concat(args:getValue(files), ", ")))
local source = args:source(level.param)
local origin = source:eq(Source.absent) and"default"or source.name
print(("level: %d (%s)"):format(args:getValue(level), origin))
-- A missing value is temper.null, which is truthy, so null_to_nil-- makes it nil.
print("mode: " .. (temper.null_to_nil(args:getMaybe(mode)) or"any"))
elseif args.command:eq(list) then
print("list " .. args:getValue(listed))
end
print("verbose: " .. (args:getValue(verbose) and"yes"or"no"))
elseif temper.instance_of(result, Output) then
io.stdout:write(result:text())
elseif temper.instance_of(result, ArgError) then
io.stderr:write(result:text())
end
os.exit(result.exitStatus)
# Values to run with, text to print (help and version), or a mistake.
result = cli.parse(sys.argv[1:], OsEnvironment())
match result:
caseArgs():
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'}")
caseOutput():
sys.stdout.write(result.text())
caseArgError():
sys.stderr.write(result.text())
sys.exit(result.exit_status)
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: