cli-def
A declarative DSL for defining CLI structures with a unified runtime and REPL for argparse/click backends.
project page: https://cli-def.tomesoft.net
source: https://github.com/tomesoft/cli-def
What's new in 0.4.0
- Layered command help and ANSI-colored REPL prompts
- Tab completion for commands, options, aliases, subcommands, and paths
- File suffix filters and application-defined completion providers for
spec_type cli-def --version/cli-def -V
What's new in 0.2.0
- Introduced Resolved model layer
- Added parameter binding (
bind) - Added
validatecommand - Improved inheritance (
inherit_from) - Added support for relative paths (
../) - Improved help and dump output
- Introduced
_earlyparsing phase
✨ Features
- Define CLI structure declaratively (TOML / Python models)
- Generate CLI implementations for:
argparse(standard library, no dependencies)click(optional dependency)
- Separation of:
- CLI definition (DSL)
- Runtime implementation (builders)
- Built-in runtime system:
- Event model (
CliEvent) - Runner
- Dispatcher
- Entrypoint resolution (
module:function) - Result propagation
- Event model (
- Interactive REPL support
- CLI chaining (execute one CLI from another)
📦 Installation
Requires Python 3.12 or later.
Core (argparse only)
pip install cli-def
With click support
pip install cli-def[click]
🚀 Quick Example
[cli]
key = "Your CLI"
help = "Help of your CLI"
prompt = "yourcli> "
[cli.echo]
args = [{key="message", mult="+"}]
cli-def run example.toml -- echo hello world
[run] forwarding args: ['echo', 'hello', 'world'], no_ctx_propagate: False
=== fallback handler ===
PATH: ['Your CLI', 'echo']
PARAMS: {'message': ['hello', 'world']}
Sketching a Command Definition
Use a command-line example to generate a starting TOML snippet:
cli-def sketch -- myapp deploy artifact.tar --env prod --force
[cli]
key = "myapp"
[cli.deploy]
args = [
{key="arg1", mult=1, type="str"},
{key="env", option="--env", mult=1, type="str"},
{key="force", option="--force", is_flag=true, default=false}
]
The sketcher does not execute the example. It treats the first token as the
CLI name and, when present, the second non-option token as the command name.
An option followed by a non-option token takes a value; otherwise it is
treated as a flag. Repeated value options use action = "append". Review the
inferred argument names and types before using the snippet.
Brace notation in a value is translated to choices:
cli-def sketch -- myapp show --level '{high,mid,low}'
{key="level", option="--level", mult=1, type="str", choices=["high", "mid", "low"]}
Quote the brace expression in a shell to prevent shell brace expansion. An all-integer set produces integer choices.
Square brackets mark an argument as optional:
sketch> tool show [--level {1,2,3}]
{key="level", option="--level", mult="?", type="int", choices=[1, 2, 3]}
Uppercase identifiers are placeholders for positional arguments:
sketch> tool copy FILE...
{key="file", mult="+", type="str"}
The supported multiplicity suffixes are FILE?, FILE*, FILE+, and
FILE... (... is equivalent to +). Placeholders also describe option
values, for example --output PATH and --tag TAG*.
Use cli-def sketch --help for sketch command help. To sketch an example that
contains --help, place it after the -- separator.
For repeated sketches, start interactive mode with --interactive or -I:
$ cli-def sketch -I
sketch> myapp deploy artifact.tar --env prod --force
[cli]
key = "myapp"
...
sketch> myapp status --json
...
sketch> exit
Each line is parsed, translated to TOML, and validated before it is printed.
An empty line is ignored; exit, quit, or EOF ends the session.
🚀 Quick Start (Demo)
cli-def demo beginner
beginner profile reads in beginner.toml (see GitHub repository for details)
Type 'help' to list commands, 'exit' to exit
demo[beginner]> echo a b c d
a b c d
-> out[0]
demo[beginner]> greet John --upper
HELLO, JOHN!
-> out[1]
Advanced demo:
cli-def demo advanced
See profiles: https://github.com/tomesoft/cli-def/tree/main/src/cli_def/demo/profiles
Pre-dispatch hook
An application can provide a single hook to inspect the normalized event before the handler runs, with either backend:
from cli_def.runtime import CliRunner, PreDispatchError
def check_event(event):
if event.params.get("where") == "invalid":
raise PreDispatchError("Invalid path")
runner = CliRunner(cli_def, pre_dispatch_hook=check_event)
result = runner.run(["search", "--where", "invalid"])
Treat the event as read-only. The hook also runs before a dry-run handler. A
PreDispatchError is logged and produces a failed CliHandlerResult and exit
code 1 without calling the handler; other exceptions propagate. When omitted or
set to None, the standard hook validates spec_type. A custom hook replaces
the standard hook. CliSession also accepts the hook and mode, retaining them
across reloads:
from cli_def.core.models import get_spec_type_registry, register_builtin_spec_types
from cli_def.runtime import CliRunner, empty_pre_dispatch_hook
register_builtin_spec_types(get_spec_type_registry())
runner = CliRunner(cli_def) # permissive
runner = CliRunner(cli_def, spec_type_mode="strict")
runner = CliRunner(cli_def, pre_dispatch_hook=empty_pre_dispatch_hook)
permissive (the default) warns and skips unknown spec types; strict treats
them as errors. Both modes reject invalid values for known spec types.
Built-in types must be registered explicitly. spec_type_mode applies only
to the standard hook, not to a custom hook.
Register spec types beforehand or define them in TOML:
The built-in TOML definitions can be included alongside local files:
[cli]
key = "MyApp"
include = ["builtin:spec_types.toml"]
[cli.search]
args = [{key = "where", option = "--where", spec_type = "posix_path"}]
The included types are ascii_identifier (ASCII letter followed by letters
or digits), slug (lowercase alphanumeric segments separated by hyphens),
uuid (UUID textual form), hex (hexadecimal characters), and posix_path
(a non-empty path string without NUL). posix_path permits Unicode, whitespace,
newlines, and backslashes; it does not check existence, permissions, lengths,
encoding, or whether a particular filesystem accepts the path.
Custom definitions can be declared as follows:
[spec_types.identifier]
regex_pattern = '[a-zA-Z][a-zA-Z0-9]*'
[cli]
key = "MyApp"
[cli.search]
args = [
{key = "where", option = "--where", spec_type = "identifier"},
{key = "ignore", option = "--ignore", spec_type = "identifier"},
]
Patterns use Python re.fullmatch. An omitted optional value is skipped and
multiple values are checked individually. Invalid patterns and duplicate names
across includes fail during loading/resolution; duplicates with the registry
fail during validation. The hook does not transform values; registered
validators receive the complete value when it is present.
An alias inherits an existing TOML specification while retaining its own name:
[spec_types.my_identifier]
extends = "identifier"
This allows a custom hook to add checks for my_identifier after calling
default_pre_dispatch_hook. Targets may come from includes; missing targets,
cycles, and combining extends with other fields are errors. Registry-only
types cannot be alias targets.
Specification types can instead declare non-empty string choices:
[spec_types.color]
choices = ["red", "green", "blue"]
Arguments inherit these choices and may narrow them using their own choices.
choices and regex_pattern cannot be combined. Both CLI backends enforce
the resulting choices for explicit input even when the pre-dispatch hook is
disabled; the standard hook also checks present default and bound values.
Integer choices are supported with base_type = "num":
[spec_types.one_to_three]
base_type = "num"
choices = [1, 2, 3]
CLI values are compared using Python's int() without changing the value passed
to the handler. Floating-point choices are not yet supported.
An integer range can be specified instead:
[spec_types.port_number]
base_type = "num"
min = 1
max = 65535
Bounds are inclusive; either can be omitted. Ranges cannot be combined with
specification-level choices or regex_pattern. The pre-dispatch hook checks
the range, so disabling the hook also disables range validation. Floating-point
ranges are not yet supported.
An application can declare an existing file or directory type:
[spec_types.existing_file_path]
base_type = "posix_path"
exists = true
kind = "file" # omit for either a file or directory
suffixes = [".toml"] # optional; requires kind = "file"
kind = "directory" requires a directory. The standard pre-dispatch hook
checks existence, follows symbolic links, and resolves relative paths against
the process working directory. It does not open the path or guarantee it
remains available. suffixes restricts files by case-sensitive suffix and is
also used by REPL path completion. Disabling the hook disables these checks.
🖥 Interactive Mode (REPL)
Install the repl extra to use the interactive experience with Tab completion
and colored prompts.
pip install "cli-def[repl]"
cli-def repl --file your_cli.toml
yourcli> help
yourcli> command arg1 --option value
Embedding the REPL in an application
Load the TOML definition and call CliSession.repl() to launch the REPL from
your application. fallback_handler is used when no command-specific handler
is registered.
from cli_def.ops import load_cli_def_path
from cli_def.runtime import CliHandlerResult, CliSession
def dispatch(event):
value = event.params.get("value")
print(value)
return CliHandlerResult.make_result(event, "value", data=value)
cli_def = load_cli_def_path("your_cli.toml")
if cli_def is None:
raise SystemExit("Could not load your_cli.toml")
session = CliSession(
cli_def,
fallback_handler=dispatch,
cli_def_file="your_cli.toml",
)
session.repl(prompt="yourcli> ")
When cli_def_file is provided, the REPL's reload command reloads that file.
Results are kept in session.result_store and can be inspected from the safe
evaluation mode entered with >.
Applications can register completion providers for custom specification types, either while creating the session or afterward:
session.register_spec_type_completer(
"search_kind",
lambda context: [
("source", "Application source"),
("tests", "Test files"),
],
)
Providers can also be passed while constructing the session with
spec_type_completers={"search_kind": complete_search_kind}.
A provider yields strings or (value, description) tuples. Its context
exposes spec_type, argument, executable, prefix, and
completed_tokens. Aliases created with extends are registered by their
resolved specification type name. Specification types based on posix_path
use the built-in file and directory completer.
🔁 Run Another CLI (CLI chaining)
cli-def --version
cli-def run example.toml -- command arg1 arg2
--separates cli-def arguments from the target CLI arguments- Remaining arguments are forwarded to the next CLI
📚 Documentation
Full documentation and design details are available on GitHub:
https://github.com/tomesoft/cli-def
- DSL specification
- Architecture
- Examples
- Development notes
📌 Roadmap
See TODO.md on GitHub: https://github.com/tomesoft/cli-def/blob/main/TODO.md
🤝 Contributing
Contributions are welcome!
📄 License
MIT License
Metadata
Release files for cli-def 0.4.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| cli_def-0.4.0.tar.gz | 78.2 kB | Without provenance | Details for cli_def-0.4.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| cli_def-0.4.0-py3-none-any.whl | Python 3 | none | any | Details for cli_def-0.4.0-py3-none-any.whl |
Total release size: 184.1 kB
Release files / cli_def-0.4.0.tar.gz
| Download URL | cli_def-0.4.0.tar.gz |
|---|---|
| Size | 78.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
c8ac594de3234ef64bb4242618094d1f794f7d979168cca3d44f64503db57790
|
|
BLAKE2b-256 checksum How to use checksums |
192892da838f63c29c0e8379eea74ecf47218118459ab69a876a78e5ca68640d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.14.3
|
Release files / cli_def-0.4.0-py3-none-any.whl
| Download URL | cli_def-0.4.0-py3-none-any.whl |
|---|---|
| Size | 106.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
233a5a15b732c0dc35e8451311e9607fb77860d52d1a7f1f31533077aa4b3551
|
|
BLAKE2b-256 checksum How to use checksums |
8848e7bef4eb1d225cf97c2884d1d0fc1316f1106d97557c6233a9dc87050d8b
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.14.3
|
Security for cli-def 0.4.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.