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.3.0
- Reusable argument specification types defined in TOML or registered in Python
- Regex, choices, integer ranges, path existence checks, and aliases
- Pre-dispatch validation with strict or permissive handling of unknown types
- Custom pre-dispatch hooks and built-in specification types
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']}
🚀 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
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. Disabling the hook disables this check.
🖥 Interactive Mode (REPL)
cli-def repl --file your_cli.toml
yourcli> help
yourcli> command arg1 --option value
🔁 Run Another CLI (CLI chaining)
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.3.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.3.0.tar.gz | 67.5 kB | Without provenance | Details for cli_def-0.3.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| cli_def-0.3.0-py3-none-any.whl | Python 3 | none | any | Details for cli_def-0.3.0-py3-none-any.whl |
Total release size: 163.6 kB
Release files / cli_def-0.3.0.tar.gz
| Download URL | cli_def-0.3.0.tar.gz |
|---|---|
| Size | 67.5 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
5579b7d131272f9d12591fae397f6042aa519ead0a7c9d5a7b78ca507c01c83a
|
|
BLAKE2b-256 checksum How to use checksums |
c3050e00356c1dd14e43ff9707e1cba8ffa164b4cda4a696b45941ab6fd84968
|
| 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.3.0-py3-none-any.whl
| Download URL | cli_def-0.3.0-py3-none-any.whl |
|---|---|
| Size | 96.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
eca03cd186a97cc44efb68f5691ff71fa566b18b7ebfdf392cec8a27fb0aa913
|
|
BLAKE2b-256 checksum How to use checksums |
2673f4f2babe35a42de91bebe209c6f8e130b0b75303a2debf0a514deebc7a28
|
| 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.3.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.