Metadata-Version: 2.4
Name: bicker
Version: 2.5.0
Summary: Tiny, fully typed CLI argument parser: declare args as a class
Keywords: cli,command-line,arguments,argument-parser,argparse,typed
Author: darragh0
Author-email: darragh0 <156817523+darragh0@users.noreply.github.com>
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.12
Project-URL: Homepage, https://github.com/darragh0/bicker
Project-URL: Repository, https://github.com/darragh0/bicker
Project-URL: Issues, https://github.com/darragh0/bicker/issues
Project-URL: Changelog, https://github.com/darragh0/bicker/blob/main/CHANGELOG.md
Description-Content-Type: text/markdown

# bicker

[![PyPI](https://img.shields.io/pypi/v/bicker)](https://pypi.org/project/bicker/)
[![Python](https://img.shields.io/pypi/pyversions/bicker)](https://pypi.org/project/bicker/)
[![CI](https://github.com/darragh0/bicker/actions/workflows/ci.yml/badge.svg)](https://github.com/darragh0/bicker/actions/workflows/ci.yml)

Tiny, fully typed CLI argument parser: declare your args as a class.

```sh
pip install bicker
```

No dependencies.

## Usage

```python
from typing import Literal

from bicker import flag, opt, parse_args, pos


class Args:
    src: str = pos(description="Image to resize")
    dst: str = pos("out.png", description="Where to save it")
    width: int = opt(required=True, short="-w", metavar="PX", description="Target width")
    height: int | None = opt(short="-H", metavar="PX", description="Target height")
    fmt: Literal["png", "jpg"] = opt("png", short="-f", description="Output format")
    verbose: bool = flag(short="-v", description="Print progress")


args = parse_args(Args)
```

`args` is an instance of `Args`, so type checkers know `args.height` is `int | None` and `args.fmt` is
`Literal["png", "jpg"]`.

```console
$ python resize.py -h
Usage: resize.py -w PX [-H PX] [-f {png,jpg}] [-v] src [dst]

Positionals:
  src                  Image to resize
  [dst]                Where to save it [default: "out.png"]

Options:
  -w, --width PX       Target width
  -H, --height PX      Target height
  -f, --fmt {png,jpg}  Output format [default: "png"]
  -v, --verbose        Print progress
  -h, --help           Show this message and exit

$ python resize.py cat.jpg -w 400 -f gif
error: -f must be one of: "png", "jpg"

Usage: resize.py -w PX [-H PX] [-f {png,jpg}] [-v] src [dst]
```

Output is colored in a terminal, unless `NO_COLOR` is set.

## Declaring arguments

| Declaration                | Gives                                                       |
| -------------------------- | ----------------------------------------------------------- |
| `pos()`                    | Required positional                                         |
| `pos(default)`             | Optional positional (after required ones)                   |
| `opt(default, short="-c")` | Option: `--name VALUE`, plus an optional short key          |
| `opt()`                    | Option that's `None` unless given (annotate it `T \| None`) |
| `opt(required=True)`       | Required option                                             |
| `flag(short="-v")`         | `bool` option with no value: `False` unless given           |
| `flag(default=True)`       | `bool` option that's `True` unless `--no-name` is given     |

Each also takes:

- `description=`: its help text
- `long=` (options and flags): its long key -- defaults to the field name with `_` as `-`; `long=False` for a short-only
  one
- `metavar=` (options and positionals): its value's placeholder in help, e.g. `DIR`; a positional's errors use it
  too
- `group=` (options and flags): the help heading it's listed under, `Options` by default
- `exclusive=` (options and flags): a tag shared by options that can't be given together, e.g. `"format"`
- `any_of=`: a tag shared by arguments of which at least one must be given, e.g. `"input"` (positionals must be
  optional); tag the same options `exclusive=` too for exactly one

**Types:**

- `str`, `int`, `float` and `Path`
- An `Enum`, given by member name in kebab-case (`Color.DARK_BLUE` is `dark-blue`)
- A `Literal` of string/int values
- Anything else with a converter: `parse=` for one value, `each=` for a list's items, e.g.
  `when: date | None = opt(parse=date.fromisoformat)`

Annotate a field as `list[...]` of any of these to take several values:

```python
class Args:
    point: list[int] = pos(nargs=2)  # Exactly 2
    files: list[str] = pos()  # One or more: the remaining positionals
    tags: list[str] = opt([], short="-t")  # Repeatable: -t a -t b
    ids: list[int] = opt([], nargs=(1, 3))  # Given 1 to 3 times
```

A list positional must come last, unless `nargs` fixes its count.

**Limits** come from `Annotated` markers, and are checked on each value:

- `gt`, `ge`, `lt`, `le` for numbers; `min_length`, `max_length` for strings
- `path_type` for paths: `"file"`, `"dir"` or `"any"`, which must exist (given paths only, not defaults)
- Any marker with these attributes works: from annotated-types, pydantic, your own, or bicker's aliases:
  - `PositiveInt`, `NonNegativeInt`, `PositiveFloat` and `NonNegativeFloat`
  - `ExistingFile`, `ExistingDir` and `ExistingPath`
- pydantic's `Field()` isn't read; use its types (`PositiveInt`) or annotated-types markers

```python
class Args:
    folder: ExistingDir = pos()  # error: folder: no such directory: "nope"
    runs: PositiveInt = opt(1)  # error: --runs: must be at least 1, got 0
    name: Annotated[str, MaxLen(20)] = opt("run")  # from annotated_types
```

Mistakes in the class itself (e.g. an unsupported type or a key used twice) raise `TypeError` as soon as `parse_args`
runs.

## Commands

Declare each command as a class, and the command field with `cmd()`:

```python
from bicker import cmd, flag, parse_args, pos


class Build:
    """Build the project."""

    release: bool = flag(short="-r")


class Test:
    """Run the tests."""

    pattern: str | None = pos(None)


class Args:
    verbose: bool = flag(short="-v")
    command: Build | Test = cmd()


args = parse_args(Args)
match args.command:
    case Build(release=release):
        print("release build" if release else "debug build")
    case Test(pattern=pattern):
        print(f"testing {pattern or 'everything'}")
```

- A command's name is its class name in kebab-case (`RunTests` is `run-tests`), or set it with
  `@command("ls", aliases=("l",))`
- Its docstring is its help text
- Global options (like `-v`) can go before or after it
- Add `| None` to make the command optional
- Commands can have their own subcommands

## Parsing

CLI parsing follows GNU conventions:

- Options and positionals can be mixed
- Values can be attached: `--width=400`, `-w400`
- Short flags can be grouped: `-vq`
- Long keys can be shortened to any unambiguous prefix: `--wid`
- Everything after `--` is a positional

`parse_args` takes `description=`, `epilog=` and `examples=` for the help page, `version=` to add a `--version` option,
and other settings like `prog=` and `help_keys=`. See docstring for more.

## Not supported (yet)

- Custom colors

Feature requests are welcome: [open an issue](https://github.com/darragh0/bicker/issues).

## License

MIT
