Metadata-Version: 2.4
Name: cli-def
Version: 0.4.0
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.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 `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']}
```

## Sketching a Command Definition

Use a command-line example to generate a starting TOML snippet:

```bash
cli-def sketch -- myapp deploy artifact.tar --env prod --force
```

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

```bash
cli-def sketch -- myapp show --level '{high,mid,low}'
```

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

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

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

```text
$ 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)

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

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

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

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

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

