Metadata-Version: 2.4
Name: cli-def
Version: 0.3.1
Summary: A declarative DSL for composable CLI applications with runtime and REPL
Author: Tomesoft
License: MIT License
        
        Copyright (c) 2026 Tomesoft
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to do so, subject to the
        following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
Project-URL: Homepage, https://cli-def.tomesoft.net
Project-URL: Repository, https://github.com/tomesoft/cli-def
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: wcwidth
Provides-Extra: click
Requires-Dist: click>=8.0; extra == "click"
Provides-Extra: repl
Requires-Dist: prompt_toolkit; extra == "repl"
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"
Dynamic: license-file

# cli-def

[日本語](https://github.com/tomesoft/cli-def/blob/main/README.ja.md)

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)

```bash
pip install cli-def
```

With click support

```bash
pip install cli-def[click]
```

## 🚀 Quick Example

```toml
[cli]
key = "Your CLI"
help = "Help of your CLI"
prompt = "yourcli> "

[cli.echo]
args = [{key="message", mult="+"}]
```

```bash
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)

```bash
cli-def demo beginner
```

beginner profile reads in beginner.toml (see GitHub repository for details)

```text
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:

```bash
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:

```python
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:

```python
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:

```toml
[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:

```toml
[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:

```toml
[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:

```toml
[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"`:

```toml
[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:

```toml
[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:

```toml
[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)

```bash
cli-def repl --file your_cli.toml
yourcli> help
yourcli> command arg1 --option value
```

## 🔁 Run Another CLI (CLI chaining)

```bash
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

