Skip to main content

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 validate command
  • Improved inheritance (inherit_from)
  • Added support for relative paths (../)
  • Improved help and dump output
  • Introduced _early parsing 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
  • 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.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for cli-def 0.3.1
File Size Uploaded Provenance Actions
cli_def-0.3.1.tar.gz 67.8 kB Without provenance Details for cli_def-0.3.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for cli-def 0.3.1
File Interpreter ABI Platform Actions
cli_def-0.3.1-py3-none-any.whl Python 3 none any Details for cli_def-0.3.1-py3-none-any.whl

Total release size: 164.5 kB

Release files / cli_def-0.3.1.tar.gz

Download URL cli_def-0.3.1.tar.gz
Size 67.8 kB
Tags Source
SHA-256 checksum
How to use checksums
e1722035b517709bd67f95704133fbc2d7cc7e036668ba39b1d00de2c96fe033
BLAKE2b-256 checksum
How to use checksums
67a0ddca770e8260c9aaec0d4e5cf79a1dd91d7c5e6da06d1fc35f7adc027517
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.1-py3-none-any.whl

Download URL cli_def-0.3.1-py3-none-any.whl
Size 96.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
0bedfc2ca25594770113c28cbb0f34aa5278e045ea40eb605065eb451995dd65
BLAKE2b-256 checksum
How to use checksums
07182a96894f55fcf768d084aeb5a662a5f13c6ac9cb3c4d554375043114a16e
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.1

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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page