bicker 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- bicker/__init__.py +27 -0
- bicker/_help.py +146 -0
- bicker/_parse.py +268 -0
- bicker/_spec.py +333 -0
- bicker/_style.py +50 -0
- bicker/py.typed +0 -0
- bicker-1.0.0.dist-info/METADATA +137 -0
- bicker-1.0.0.dist-info/RECORD +10 -0
- bicker-1.0.0.dist-info/WHEEL +4 -0
- bicker-1.0.0.dist-info/licenses/LICENSE +21 -0
bicker/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Tiny, fully typed command-line argument parsing: declare your arguments as a class.
|
|
2
|
+
|
|
3
|
+
Example:
|
|
4
|
+
```python
|
|
5
|
+
from typing import Literal
|
|
6
|
+
|
|
7
|
+
from bicker import flag, opt, parse_args, pos
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Args:
|
|
11
|
+
src: str = pos(description="Image to resize")
|
|
12
|
+
width: int = opt(800, "-w", description="Target width in pixels")
|
|
13
|
+
fmt: Literal["png", "jpg"] = opt("png", "-f")
|
|
14
|
+
verbose: bool = flag("-v")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
args = parse_args(Args)
|
|
18
|
+
args.fmt # Type checkers see Literal["png", "jpg"]
|
|
19
|
+
```
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from typing import Final
|
|
23
|
+
|
|
24
|
+
from bicker._parse import parse_args
|
|
25
|
+
from bicker._spec import HelpKey, Nargs, flag, opt, pos
|
|
26
|
+
|
|
27
|
+
__all__: Final = ["HelpKey", "Nargs", "flag", "opt", "parse_args", "pos"]
|
bicker/_help.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from typing import TYPE_CHECKING, Final, LiteralString, TextIO, final
|
|
5
|
+
|
|
6
|
+
from bicker._style import Style, Styles, style, visible_len
|
|
7
|
+
|
|
8
|
+
if TYPE_CHECKING:
|
|
9
|
+
from collections.abc import Collection, Iterable, Sequence
|
|
10
|
+
|
|
11
|
+
from bicker._spec import Field, HelpKey
|
|
12
|
+
|
|
13
|
+
_PAD: Final = " "
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@final
|
|
17
|
+
@dataclass(frozen=True, kw_only=True)
|
|
18
|
+
class HelpConfig:
|
|
19
|
+
"""The `parse_args` settings that shape help and usage output."""
|
|
20
|
+
|
|
21
|
+
prog: str
|
|
22
|
+
help_keys: Collection[HelpKey]
|
|
23
|
+
help_description: str
|
|
24
|
+
description: str | None
|
|
25
|
+
epilog: str | None
|
|
26
|
+
examples: Sequence[str]
|
|
27
|
+
use_shorthand_usage: bool
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@final
|
|
31
|
+
class HelpRenderer:
|
|
32
|
+
"""Build help and usage text, styled for `stream` (stdout for help, stderr for errors)."""
|
|
33
|
+
|
|
34
|
+
def __init__(self, fields: Sequence[Field], cfg: HelpConfig, stream: TextIO) -> None:
|
|
35
|
+
self._cfg = cfg
|
|
36
|
+
self._stream = stream
|
|
37
|
+
|
|
38
|
+
# Required positionals always precede optional ones, so these are in display order
|
|
39
|
+
self._positionals = [field for field in fields if field.is_pos]
|
|
40
|
+
|
|
41
|
+
# Fields are equivalent to options with no values
|
|
42
|
+
self._options = [field for field in fields if not field.is_pos]
|
|
43
|
+
|
|
44
|
+
def help(self) -> str:
|
|
45
|
+
cfg = self._cfg
|
|
46
|
+
|
|
47
|
+
pos_entries = [
|
|
48
|
+
(self._pos_label(field, Styles.OPTIONAL_POS), field.description)
|
|
49
|
+
for field in self._positionals
|
|
50
|
+
]
|
|
51
|
+
opt_entries = [
|
|
52
|
+
(self._option_entry(field.keys, field.style, field.metavar), field.description)
|
|
53
|
+
for field in self._options
|
|
54
|
+
]
|
|
55
|
+
|
|
56
|
+
if cfg.help_keys:
|
|
57
|
+
help_entry = self._option_entry(cfg.help_keys, Styles.FLAG, None)
|
|
58
|
+
opt_entries.append((help_entry, cfg.help_description))
|
|
59
|
+
|
|
60
|
+
# Descriptions start in one column across both sections
|
|
61
|
+
width = max((visible_len(entry) for entry, _ in pos_entries + opt_entries), default=0)
|
|
62
|
+
|
|
63
|
+
sections = [self.usage()]
|
|
64
|
+
if cfg.description:
|
|
65
|
+
sections.append(cfg.description)
|
|
66
|
+
if pos_entries:
|
|
67
|
+
lines = [_described(entry, desc, width) for entry, desc in pos_entries]
|
|
68
|
+
sections.append(self._section("Positionals", lines))
|
|
69
|
+
if opt_entries:
|
|
70
|
+
lines = [_described(entry, desc, width) for entry, desc in opt_entries]
|
|
71
|
+
sections.append(self._section("Options", lines))
|
|
72
|
+
if cfg.examples:
|
|
73
|
+
sections.append(self._section("Examples", map(self._example, cfg.examples)))
|
|
74
|
+
if cfg.epilog:
|
|
75
|
+
sections.append(cfg.epilog)
|
|
76
|
+
|
|
77
|
+
return "\n\n".join(sections)
|
|
78
|
+
|
|
79
|
+
def usage(self) -> str:
|
|
80
|
+
if not self._options:
|
|
81
|
+
options = []
|
|
82
|
+
elif self._cfg.use_shorthand_usage:
|
|
83
|
+
options = [self._st("options", Styles.USAGE_OPT)]
|
|
84
|
+
else:
|
|
85
|
+
# "..." after a list option: it can be repeated
|
|
86
|
+
options = [
|
|
87
|
+
self._st(self._usage_option(field), Styles.USAGE_OPT) + self._ellipsis(field)
|
|
88
|
+
for field in self._options
|
|
89
|
+
]
|
|
90
|
+
|
|
91
|
+
positionals = [
|
|
92
|
+
self._pos_label(field, Styles.USAGE_OPTIONAL_POS) for field in self._positionals
|
|
93
|
+
]
|
|
94
|
+
heading = [self._st("Usage", Styles.HEADING), self._st(self._cfg.prog, Styles.PROG)]
|
|
95
|
+
|
|
96
|
+
return " ".join([*heading, *options, *positionals])
|
|
97
|
+
|
|
98
|
+
def _st(self, text: str, style_: Style) -> str:
|
|
99
|
+
return style(text, style_, self._stream)
|
|
100
|
+
|
|
101
|
+
def _section(self, title: LiteralString, lines: Iterable[str]) -> str:
|
|
102
|
+
styled_title = self._st(title, Styles.HEADING)
|
|
103
|
+
|
|
104
|
+
return "\n".join([styled_title, *(_PAD + line for line in lines)])
|
|
105
|
+
|
|
106
|
+
def _pos_label(self, field: Field, optional_style: Style) -> str:
|
|
107
|
+
"""Style the positional's name, plus `...` if it takes many values."""
|
|
108
|
+
style_ = Styles.POS if field.is_required else optional_style
|
|
109
|
+
return self._st(field.name + self._ellipsis(field), style_)
|
|
110
|
+
|
|
111
|
+
def _usage_option(self, field: Field) -> str:
|
|
112
|
+
"""`-v`, `-c COUNT` or `--color {red,blue}`: the first key, plus a placeholder."""
|
|
113
|
+
return self._st(field.keys[0], field.style) + self._metavar(field.metavar)
|
|
114
|
+
|
|
115
|
+
def _option_entry(self, keys: Collection[str], style_: Style, metavar: str | None) -> str:
|
|
116
|
+
"""`-c, --count COUNT`, ` --color {a,b}` or `-h`, with long keys in one column."""
|
|
117
|
+
ordered = sorted(keys, key=len) # Short first
|
|
118
|
+
# Shorts are always 2 chars ("-c"), so "-c, " or 4 spaces lines up every long key
|
|
119
|
+
indent = " " if ordered[0].startswith("--") else ""
|
|
120
|
+
styled_keys = ", ".join(self._st(key, style_) for key in ordered)
|
|
121
|
+
return indent + styled_keys + self._metavar(metavar)
|
|
122
|
+
|
|
123
|
+
def _example(self, example: str) -> str:
|
|
124
|
+
"""Prefix `prog` and style known keys (e.g. `-w`) as in the options list."""
|
|
125
|
+
styles_by_key = {key: field.style for field in self._options for key in field.keys}
|
|
126
|
+
words = [
|
|
127
|
+
self._st(word, styles_by_key[word]) if word in styles_by_key else word
|
|
128
|
+
for word in example.split()
|
|
129
|
+
]
|
|
130
|
+
prog = self._st(self._cfg.prog, Styles.PROG)
|
|
131
|
+
return " ".join([prog, *words])
|
|
132
|
+
|
|
133
|
+
def _metavar(self, metavar: str | None) -> str:
|
|
134
|
+
"""` COUNT`, with its leading space, or `""` if there's no metavar."""
|
|
135
|
+
return f" {self._st(metavar, Styles.METAVAR)}" if metavar else ""
|
|
136
|
+
|
|
137
|
+
def _ellipsis(self, field: Field) -> str:
|
|
138
|
+
"""`...` if the field takes many values, else `""`."""
|
|
139
|
+
return self._st("...", Styles.ELLIPSIS) if field.is_list else ""
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _described(entry: str, description: str | None, width: int) -> str:
|
|
143
|
+
"""Append `description` after `entry`, padded so descriptions start at `width` + 2."""
|
|
144
|
+
if not description:
|
|
145
|
+
return entry
|
|
146
|
+
return entry + " " * (width - visible_len(entry) + 2) + description
|
bicker/_parse.py
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import sys
|
|
4
|
+
from copy import copy
|
|
5
|
+
from dataclasses import MISSING
|
|
6
|
+
from getopt import GetoptError, gnu_getopt
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import TYPE_CHECKING, final
|
|
9
|
+
|
|
10
|
+
from bicker._help import HelpConfig, HelpRenderer
|
|
11
|
+
from bicker._spec import LITERAL_TYPES, collect_fields
|
|
12
|
+
from bicker._style import Style, Styles, style
|
|
13
|
+
|
|
14
|
+
if TYPE_CHECKING:
|
|
15
|
+
from collections.abc import Collection, Mapping, Sequence
|
|
16
|
+
|
|
17
|
+
from bicker._spec import Field, HelpKey
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def parse_args[T](
|
|
21
|
+
spec: type[T],
|
|
22
|
+
argv: list[str] | tuple[str, ...] | None = None,
|
|
23
|
+
*,
|
|
24
|
+
help_keys: Collection[HelpKey] = ("-h", "--help"),
|
|
25
|
+
help_description: str = "Show this message and exit",
|
|
26
|
+
prog: str | None = None,
|
|
27
|
+
description: str | None = None,
|
|
28
|
+
epilog: str | None = None,
|
|
29
|
+
examples: list[str] | tuple[str, ...] = (),
|
|
30
|
+
usage_on_error: bool = True,
|
|
31
|
+
use_shorthand_usage: bool = False,
|
|
32
|
+
) -> T:
|
|
33
|
+
"""Parse command-line arguments into an instance of `spec`.
|
|
34
|
+
|
|
35
|
+
Each value is converted to its field's type: `str`, `int`, `float`, a `Literal` of strings
|
|
36
|
+
or ints (only its values are allowed), or a `list` of these. Parsing follows GNU
|
|
37
|
+
conventions: options and positionals can be mixed, and everything after `--` is a
|
|
38
|
+
positional. Output is colored in a terminal unless `NO_COLOR` is set.
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
spec: A class whose annotated attributes are declared with `pos()`, `opt()` or
|
|
42
|
+
`flag()`. It must be constructible with no arguments.
|
|
43
|
+
argv: The arguments to parse. Defaults to `sys.argv[1:]`.
|
|
44
|
+
help_keys: The keys that print help and exit. Pass `()` to disable help.
|
|
45
|
+
help_description: The help text for the help option itself.
|
|
46
|
+
prog: The program name shown in help. Defaults to the file name of `sys.argv[0]`.
|
|
47
|
+
description: Text shown below the usage line in help.
|
|
48
|
+
epilog: Text shown at the end of help.
|
|
49
|
+
examples: Example argument lists, each shown in help after the program name.
|
|
50
|
+
usage_on_error: Whether to print the usage line after an error.
|
|
51
|
+
use_shorthand_usage: Whether the usage line shows `[options]` instead of expanding each
|
|
52
|
+
option.
|
|
53
|
+
|
|
54
|
+
Returns:
|
|
55
|
+
An instance of `spec` with each declared attribute set to its parsed or default value.
|
|
56
|
+
|
|
57
|
+
Raises:
|
|
58
|
+
TypeError: If `spec` is declared incorrectly.
|
|
59
|
+
SystemExit: With code 0 after printing help to stdout, or code 1 after printing an
|
|
60
|
+
error (and usage) to stderr.
|
|
61
|
+
|
|
62
|
+
Example:
|
|
63
|
+
```python
|
|
64
|
+
from bicker import flag, opt, parse_args, pos
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class Args:
|
|
68
|
+
src: str = pos(description="File to read")
|
|
69
|
+
count: int = opt(1, "-c", description="How many times")
|
|
70
|
+
verbose: bool = flag("-v")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
args = parse_args(Args) # e.g. `prog in.txt -c 3 -v`
|
|
74
|
+
```
|
|
75
|
+
"""
|
|
76
|
+
fields = collect_fields(spec, help_keys)
|
|
77
|
+
cfg = HelpConfig(
|
|
78
|
+
prog=prog or Path(sys.argv[0]).name,
|
|
79
|
+
help_keys=help_keys,
|
|
80
|
+
help_description=help_description,
|
|
81
|
+
description=description,
|
|
82
|
+
epilog=epilog,
|
|
83
|
+
examples=examples,
|
|
84
|
+
use_shorthand_usage=use_shorthand_usage,
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
pos_fields = [field for field in fields if field.is_pos]
|
|
88
|
+
option_fields = [field for field in fields if not field.is_pos]
|
|
89
|
+
argv = sys.argv[1:] if argv is None else argv
|
|
90
|
+
|
|
91
|
+
# Help wins over any other error; after "--" everything is a positional
|
|
92
|
+
options_part = argv[: argv.index("--")] if "--" in argv else argv
|
|
93
|
+
if any(key in options_part for key in help_keys):
|
|
94
|
+
print(HelpRenderer(fields, cfg, sys.stdout).help())
|
|
95
|
+
sys.exit(0)
|
|
96
|
+
|
|
97
|
+
try:
|
|
98
|
+
option_values, raw_positionals = _parse_options(option_fields, argv)
|
|
99
|
+
pos_values = _parse_positionals(pos_fields, raw_positionals)
|
|
100
|
+
except _ParseError as e:
|
|
101
|
+
print(f"{style('error', Styles.ERROR_PREFIX)} {e}", file=sys.stderr)
|
|
102
|
+
if usage_on_error:
|
|
103
|
+
print("\n" + HelpRenderer(fields, cfg, sys.stderr).usage(), file=sys.stderr)
|
|
104
|
+
sys.exit(1)
|
|
105
|
+
|
|
106
|
+
# Copied so a mutable default (e.g. a list) isn't shared between parses;
|
|
107
|
+
# a list positional without a default (allowed when its min is 0) starts empty
|
|
108
|
+
values: dict[str, object] = {
|
|
109
|
+
field.name: [] if field.is_list and field.default is MISSING else copy(field.default)
|
|
110
|
+
for field in fields
|
|
111
|
+
}
|
|
112
|
+
values |= option_values
|
|
113
|
+
values |= pos_values
|
|
114
|
+
|
|
115
|
+
args = spec()
|
|
116
|
+
for name, value in values.items():
|
|
117
|
+
setattr(args, name, value)
|
|
118
|
+
return args
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _parse_options(
|
|
122
|
+
option_fields: Sequence[Field],
|
|
123
|
+
argv: Sequence[str],
|
|
124
|
+
) -> tuple[dict[str, object], list[str]]:
|
|
125
|
+
|
|
126
|
+
fields_by_key = {key: field for field in option_fields for key in field.keys}
|
|
127
|
+
|
|
128
|
+
# getopt's spec format: short "c:" / long "count=" mean the option takes a value
|
|
129
|
+
shorts = "".join(
|
|
130
|
+
k[1] + ("" if f.is_flag else ":")
|
|
131
|
+
for k, f in fields_by_key.items()
|
|
132
|
+
if not k.startswith("--")
|
|
133
|
+
)
|
|
134
|
+
longs = [
|
|
135
|
+
k[2:] + ("" if f.is_flag else "=") for k, f in fields_by_key.items() if k.startswith("--")
|
|
136
|
+
]
|
|
137
|
+
|
|
138
|
+
try:
|
|
139
|
+
option_pairs, raw_positionals = gnu_getopt(argv, shorts, longs)
|
|
140
|
+
except GetoptError as e:
|
|
141
|
+
raise _ParseError(_getopt_error_message(e, fields_by_key)) from None
|
|
142
|
+
|
|
143
|
+
option_values: dict[str, object] = {}
|
|
144
|
+
repeated: dict[str, list[object]] = {}
|
|
145
|
+
# raw in this context: str version of object (e.g., "3" = raw version of 3)
|
|
146
|
+
for key, raw in option_pairs:
|
|
147
|
+
field = fields_by_key[key]
|
|
148
|
+
value = True if field.is_flag else _convert(key, field, raw)
|
|
149
|
+
if field.is_list:
|
|
150
|
+
repeated.setdefault(field.name, []).append(value)
|
|
151
|
+
else:
|
|
152
|
+
option_values[field.name] = value
|
|
153
|
+
|
|
154
|
+
for field in option_fields:
|
|
155
|
+
if field.is_list:
|
|
156
|
+
_check_count(field.long_key, field, len(repeated.get(field.name, [])))
|
|
157
|
+
|
|
158
|
+
return option_values | repeated, raw_positionals
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _getopt_error_message(e: GetoptError, fields_by_key: Mapping[str, Field]) -> str:
|
|
162
|
+
key = f"--{e.opt}" if f"--{e.opt}" in e.msg else f"-{e.opt}"
|
|
163
|
+
matches = [k for k in fields_by_key if k.startswith(key)]
|
|
164
|
+
|
|
165
|
+
# getopt's own messages for these leak its spec format ("count=, color=")
|
|
166
|
+
if not e.opt: # e.g. "--=x"
|
|
167
|
+
return f"option {style(key, _key_style(key, fields_by_key))} not recognized"
|
|
168
|
+
|
|
169
|
+
if key not in fields_by_key and len(matches) > 1:
|
|
170
|
+
listed = ", ".join(style(k, _key_style(k, fields_by_key)) for k in matches)
|
|
171
|
+
return f"option {style(key, _key_style(key, fields_by_key))} is ambiguous: {listed}"
|
|
172
|
+
|
|
173
|
+
return e.msg.replace(key, style(key, _key_style(key, fields_by_key)))
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _key_style(key: str, fields_by_key: Mapping[str, Field]) -> Style:
|
|
177
|
+
"""Return the key's field style (flag vs option), or the option style for unknown keys."""
|
|
178
|
+
field = fields_by_key.get(key)
|
|
179
|
+
return field.style if field else Styles.OPT
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _convert(label: str, field: Field, raw: str) -> object:
|
|
183
|
+
# A field that takes values is either a scalar or a `Literal` (see `_check_type`)
|
|
184
|
+
typ = field.scalar_typ
|
|
185
|
+
if typ is None:
|
|
186
|
+
return _convert_choice(label, field, raw)
|
|
187
|
+
|
|
188
|
+
try:
|
|
189
|
+
return typ(raw)
|
|
190
|
+
except ValueError:
|
|
191
|
+
msg = (
|
|
192
|
+
f"{style(label, field.style)} expects {style(typ.__name__, Styles.TYPE)}, "
|
|
193
|
+
f"got {style(raw, Styles.STR_VALUE)}"
|
|
194
|
+
)
|
|
195
|
+
raise _ParseError(msg) from None
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _convert_choice(label: str, field: Field, raw: str) -> object:
|
|
199
|
+
choices_by_raw = {str(choice): choice for choice in field.choices}
|
|
200
|
+
if raw not in choices_by_raw:
|
|
201
|
+
listed = ", ".join(
|
|
202
|
+
style(raw_choice, LITERAL_TYPES[type(choice)])
|
|
203
|
+
for raw_choice, choice in choices_by_raw.items()
|
|
204
|
+
)
|
|
205
|
+
msg = f"{style(label, field.style)} must be one of: {listed}"
|
|
206
|
+
raise _ParseError(msg)
|
|
207
|
+
return choices_by_raw[raw]
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _parse_positionals(
|
|
211
|
+
pos_fields: Sequence[Field],
|
|
212
|
+
raw_positionals: Sequence[str],
|
|
213
|
+
) -> dict[str, object]:
|
|
214
|
+
|
|
215
|
+
values: dict[str, object] = {}
|
|
216
|
+
rest = list(raw_positionals)
|
|
217
|
+
|
|
218
|
+
# Each positional takes its values in order: 1 for a single value, N for nargs=N,
|
|
219
|
+
# and (only possible for the last one) up to its max for a variable-count list
|
|
220
|
+
for i, field in enumerate(pos_fields):
|
|
221
|
+
if not rest:
|
|
222
|
+
if missing := [f.name for f in pos_fields[i:] if f.is_required]:
|
|
223
|
+
noun = "positional" if len(missing) == 1 else "positionals"
|
|
224
|
+
msg = f"missing {noun}: {', '.join(style(name, Styles.POS) for name in missing)}"
|
|
225
|
+
raise _ParseError(msg)
|
|
226
|
+
break
|
|
227
|
+
|
|
228
|
+
if not field.is_list:
|
|
229
|
+
values[field.name] = _convert(field.name, field, rest.pop(0))
|
|
230
|
+
continue
|
|
231
|
+
|
|
232
|
+
_, high = field.nargs_range
|
|
233
|
+
taken, rest = (rest, []) if high is None else (rest[:high], rest[high:])
|
|
234
|
+
_check_count(field.name, field, len(taken))
|
|
235
|
+
values[field.name] = [_convert(field.name, field, raw) for raw in taken]
|
|
236
|
+
|
|
237
|
+
if rest:
|
|
238
|
+
noun = "positional" if len(rest) == 1 else "positionals"
|
|
239
|
+
msg = f"unexpected {noun}: {', '.join(style(raw, Styles.STR_VALUE) for raw in rest)}"
|
|
240
|
+
raise _ParseError(msg)
|
|
241
|
+
|
|
242
|
+
return values
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _check_count(label: str, field: Field, count: int) -> None:
|
|
246
|
+
lo, hi = field.nargs_range
|
|
247
|
+
if count < lo or (hi is not None and count > hi):
|
|
248
|
+
msg = f"{style(label, field.style)} expects {_expected_count(lo, hi)}, got {count}"
|
|
249
|
+
raise _ParseError(msg)
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _expected_count(low: int, high: int | None) -> str:
|
|
253
|
+
"""`exactly 2 values`, `at least 1 value`, `at most 3 values` or `1 to 3 values`."""
|
|
254
|
+
if low == high:
|
|
255
|
+
text = f"exactly {low}"
|
|
256
|
+
elif high is None:
|
|
257
|
+
text = f"at least {low}"
|
|
258
|
+
elif low == 0:
|
|
259
|
+
text = f"at most {high}"
|
|
260
|
+
else:
|
|
261
|
+
text = f"{low} to {high}"
|
|
262
|
+
shown = low if high is None else high
|
|
263
|
+
return f"{text} value{'' if shown == 1 else 's'}"
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
@final
|
|
267
|
+
class _ParseError(Exception):
|
|
268
|
+
"""Bad command-line input; `parse_args` turns it into usage + error message + exit."""
|
bicker/_spec.py
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from collections import Counter
|
|
5
|
+
from dataclasses import MISSING, dataclass
|
|
6
|
+
from typing import (
|
|
7
|
+
TYPE_CHECKING,
|
|
8
|
+
Final,
|
|
9
|
+
Literal,
|
|
10
|
+
cast,
|
|
11
|
+
final,
|
|
12
|
+
get_args,
|
|
13
|
+
get_origin,
|
|
14
|
+
get_type_hints,
|
|
15
|
+
overload,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
from bicker._style import Styles
|
|
19
|
+
|
|
20
|
+
if TYPE_CHECKING:
|
|
21
|
+
from collections.abc import Collection, Mapping, Sequence
|
|
22
|
+
|
|
23
|
+
from bicker._style import Style
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
type HelpKey = Literal["-h", "--help"]
|
|
27
|
+
|
|
28
|
+
# How many values a list field takes: exactly `n`, or `(min, max)` with `None` for no max
|
|
29
|
+
type Nargs = int | tuple[int, int | None]
|
|
30
|
+
|
|
31
|
+
_SHORT_KEY: Final = re.compile(r"-[A-Za-z0-9]")
|
|
32
|
+
_LONG_KEY: Final = re.compile(r"--[A-Za-z0-9][A-Za-z0-9-]*")
|
|
33
|
+
|
|
34
|
+
# Supported value types; bool is supported separately, for flags only
|
|
35
|
+
_SCALAR_TYPES: Final = (str, int, float)
|
|
36
|
+
|
|
37
|
+
# Literal can't hold floats (PEP 586); each type maps to how its choices are styled
|
|
38
|
+
LITERAL_TYPES: Final[Mapping[type, Style]] = {str: Styles.STR_VALUE, int: Styles.INT_VALUE}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True, kw_only=True)
|
|
42
|
+
class _Declaration:
|
|
43
|
+
"""What `pos()`, `opt()` and `flag()` return; the type isn't known until `collect_fields`."""
|
|
44
|
+
|
|
45
|
+
default: object
|
|
46
|
+
short: str | None = None
|
|
47
|
+
custom_long: str | None = None
|
|
48
|
+
is_pos: bool = False
|
|
49
|
+
custom_metavar: str | None = None
|
|
50
|
+
description: str | None = None
|
|
51
|
+
nargs: Nargs | None = None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@final
|
|
55
|
+
@dataclass(frozen=True, kw_only=True)
|
|
56
|
+
class Field(_Declaration):
|
|
57
|
+
name: str
|
|
58
|
+
# The annotation as written, e.g. `int`, `list[str]` or `Literal["a", "b"]`
|
|
59
|
+
typ: object
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def long_key(self) -> str:
|
|
63
|
+
"""The custom long key if set, else derived from the name: `dry_run` -> `--dry-run`."""
|
|
64
|
+
return self.custom_long or f"--{self.name.replace('_', '-')}"
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def keys(self) -> tuple[str, ...]:
|
|
68
|
+
"""The option's keys, short first, e.g. `("-c", "--count")`; none for a positional."""
|
|
69
|
+
if self.is_pos:
|
|
70
|
+
return ()
|
|
71
|
+
return (self.short, self.long_key) if self.short else (self.long_key,)
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def style(self) -> Style:
|
|
75
|
+
if self.is_flag:
|
|
76
|
+
return Styles.FLAG
|
|
77
|
+
return Styles.POS if self.is_pos else Styles.OPT
|
|
78
|
+
|
|
79
|
+
@property
|
|
80
|
+
def is_flag(self) -> bool:
|
|
81
|
+
return self.typ is bool
|
|
82
|
+
|
|
83
|
+
@property
|
|
84
|
+
def is_required(self) -> bool:
|
|
85
|
+
if self.is_list:
|
|
86
|
+
return self.nargs_range[0] > 0
|
|
87
|
+
return self.default is MISSING
|
|
88
|
+
|
|
89
|
+
@property
|
|
90
|
+
def nargs_range(self) -> tuple[int, int | None]:
|
|
91
|
+
"""`(min, max)` values for a list; defaults to 1+ for `pos()`, 0+ otherwise."""
|
|
92
|
+
if isinstance(self.nargs, int):
|
|
93
|
+
return (self.nargs, self.nargs)
|
|
94
|
+
if self.nargs is not None:
|
|
95
|
+
return self.nargs
|
|
96
|
+
return (1 if self.is_pos and self.default is MISSING else 0, None)
|
|
97
|
+
|
|
98
|
+
@property
|
|
99
|
+
def is_list(self) -> bool:
|
|
100
|
+
"""Whether this takes many values: the rest of the positionals, or a repeated option."""
|
|
101
|
+
return get_origin(self.typ) is list
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def value_typ(self) -> object:
|
|
105
|
+
"""The type of each value: `T` for `list[T]`, otherwise the field's own type."""
|
|
106
|
+
if not self.is_list:
|
|
107
|
+
return self.typ
|
|
108
|
+
args: tuple[object, ...] = get_args(self.typ)
|
|
109
|
+
return args[0]
|
|
110
|
+
|
|
111
|
+
@property
|
|
112
|
+
def scalar_typ(self) -> type[str | int | float] | None:
|
|
113
|
+
"""The value type if it's `str`, `int` or `float`, else `None` (e.g. for a `Literal`)."""
|
|
114
|
+
typ = self.value_typ
|
|
115
|
+
return typ if isinstance(typ, type) and typ in _SCALAR_TYPES else None
|
|
116
|
+
|
|
117
|
+
@property
|
|
118
|
+
def choices(self) -> tuple[object, ...]:
|
|
119
|
+
"""The values of a `Literal` type, or `()` for any other type."""
|
|
120
|
+
return get_args(self.value_typ) if get_origin(self.value_typ) is Literal else ()
|
|
121
|
+
|
|
122
|
+
@property
|
|
123
|
+
def metavar(self) -> str | None:
|
|
124
|
+
"""The help placeholder: the custom one if set, else `{a,b}` for choices or `NAME`."""
|
|
125
|
+
if self.is_flag:
|
|
126
|
+
return None
|
|
127
|
+
if self.custom_metavar:
|
|
128
|
+
return self.custom_metavar
|
|
129
|
+
if self.choices:
|
|
130
|
+
return "{" + ",".join(map(str, self.choices)) + "}"
|
|
131
|
+
return self.name.upper()
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
# T only in the return type is intentional: it's inferred from the field's annotation
|
|
135
|
+
@overload
|
|
136
|
+
def pos[T](*, description: str | None = None, nargs: Nargs | None = None) -> T: ... # type: ignore[type-var] # pyright: ignore[reportInvalidTypeVarUse]
|
|
137
|
+
@overload
|
|
138
|
+
def pos[T](default: T, *, description: str | None = None, nargs: Nargs | None = None) -> T: ...
|
|
139
|
+
def pos(
|
|
140
|
+
default: object = MISSING,
|
|
141
|
+
*,
|
|
142
|
+
description: str | None = None,
|
|
143
|
+
nargs: Nargs | None = None,
|
|
144
|
+
) -> object:
|
|
145
|
+
"""Declare a positional argument.
|
|
146
|
+
|
|
147
|
+
Positionals are matched in the order they're declared. Positionals with a `default` are
|
|
148
|
+
optional and must come after required ones. Annotate the field as `list[T]` to take several
|
|
149
|
+
values; unless `nargs` fixes the count, it must be the last positional.
|
|
150
|
+
|
|
151
|
+
Args:
|
|
152
|
+
default: The value used when the positional isn't given. Omit it to make the
|
|
153
|
+
positional required.
|
|
154
|
+
description: The help text for this positional.
|
|
155
|
+
nargs: How many values a `list[T]` positional takes: exactly `n`, or `(min, max)` with
|
|
156
|
+
`None` for no max. Defaults to at least 1, or at least 0 when `default` is given.
|
|
157
|
+
|
|
158
|
+
Returns:
|
|
159
|
+
A placeholder that `parse_args` replaces with the parsed value.
|
|
160
|
+
"""
|
|
161
|
+
return _Declaration(default=default, is_pos=True, description=description, nargs=nargs)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def opt[T](
|
|
165
|
+
default: T,
|
|
166
|
+
short: str | None = None,
|
|
167
|
+
*,
|
|
168
|
+
long: str | None = None,
|
|
169
|
+
description: str | None = None,
|
|
170
|
+
metavar: str | None = None,
|
|
171
|
+
nargs: Nargs | None = None,
|
|
172
|
+
) -> T:
|
|
173
|
+
"""Declare an option that takes a value.
|
|
174
|
+
|
|
175
|
+
Annotate the field as `list[T]` to make the option repeatable: each use adds one value.
|
|
176
|
+
|
|
177
|
+
Args:
|
|
178
|
+
default: The value used when the option isn't given. For a `list[T]` option, given
|
|
179
|
+
values replace the default rather than extend it.
|
|
180
|
+
short: A short key like `-c`: a dash plus one letter or digit.
|
|
181
|
+
long: A long key like `--count`. Defaults to the field name, e.g. `--dry-run` for
|
|
182
|
+
`dry_run`.
|
|
183
|
+
description: The help text for this option.
|
|
184
|
+
metavar: The value's placeholder in help. Defaults to `{a,b}` for a `Literal`, and
|
|
185
|
+
the field name in uppercase otherwise.
|
|
186
|
+
nargs: How many times a `list[T]` option can be given: exactly `n`, or `(min, max)`
|
|
187
|
+
with `None` for no max. Defaults to any number.
|
|
188
|
+
|
|
189
|
+
Returns:
|
|
190
|
+
A placeholder that `parse_args` replaces with the parsed value.
|
|
191
|
+
"""
|
|
192
|
+
decl = _Declaration(
|
|
193
|
+
default=default,
|
|
194
|
+
short=short,
|
|
195
|
+
custom_long=long,
|
|
196
|
+
custom_metavar=metavar,
|
|
197
|
+
description=description,
|
|
198
|
+
nargs=nargs,
|
|
199
|
+
)
|
|
200
|
+
return cast("T", decl)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def flag(
|
|
204
|
+
short: str | None = None,
|
|
205
|
+
*,
|
|
206
|
+
long: str | None = None,
|
|
207
|
+
description: str | None = None,
|
|
208
|
+
) -> bool:
|
|
209
|
+
"""Declare a flag: a `bool` option without a value. Defaults to `False` unless flag is given.
|
|
210
|
+
|
|
211
|
+
Args:
|
|
212
|
+
short: A short key like `-v`: a dash plus one letter or digit.
|
|
213
|
+
long: A long key like `--verbose`. Defaults to the field name, e.g. `--dry-run` for
|
|
214
|
+
`dry_run`.
|
|
215
|
+
description: The help text for this flag.
|
|
216
|
+
|
|
217
|
+
Returns:
|
|
218
|
+
A placeholder that `parse_args` replaces with the parsed value.
|
|
219
|
+
"""
|
|
220
|
+
return opt(default=False, short=short, long=long, description=description)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def collect_fields(spec: type[object], help_keys: Collection[HelpKey]) -> list[Field]:
|
|
224
|
+
|
|
225
|
+
fields: list[Field] = []
|
|
226
|
+
hints: dict[str, object] = get_type_hints(spec)
|
|
227
|
+
|
|
228
|
+
for name, typ in hints.items():
|
|
229
|
+
decl = getattr(spec, name, None)
|
|
230
|
+
if not isinstance(decl, _Declaration):
|
|
231
|
+
msg = f"{name!r} must be declared with pos(), opt() or flag()"
|
|
232
|
+
raise TypeError(msg)
|
|
233
|
+
|
|
234
|
+
field = Field(
|
|
235
|
+
name=name,
|
|
236
|
+
typ=typ,
|
|
237
|
+
default=decl.default,
|
|
238
|
+
short=decl.short,
|
|
239
|
+
custom_long=decl.custom_long,
|
|
240
|
+
is_pos=decl.is_pos,
|
|
241
|
+
custom_metavar=decl.custom_metavar,
|
|
242
|
+
description=decl.description,
|
|
243
|
+
nargs=decl.nargs,
|
|
244
|
+
)
|
|
245
|
+
_check_type(field)
|
|
246
|
+
_check_nargs(field)
|
|
247
|
+
fields.append(field)
|
|
248
|
+
|
|
249
|
+
_check_keys(fields)
|
|
250
|
+
if help_keys:
|
|
251
|
+
_check_help_clash(fields, help_keys)
|
|
252
|
+
_check_positional_order(fields)
|
|
253
|
+
|
|
254
|
+
return fields
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _check_type(field: Field) -> None:
|
|
258
|
+
supported = (
|
|
259
|
+
field.scalar_typ is not None
|
|
260
|
+
or (field.is_flag and not field.is_pos)
|
|
261
|
+
or (field.choices and all(type(choice) in LITERAL_TYPES for choice in field.choices))
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
if not supported:
|
|
265
|
+
scalars = ", ".join(t.__name__ for t in _SCALAR_TYPES)
|
|
266
|
+
literals = "/".join(t.__name__ for t in LITERAL_TYPES)
|
|
267
|
+
msg = (
|
|
268
|
+
f"{field.name!r} has unsupported type {field.typ!r} "
|
|
269
|
+
f"(supported: {scalars}, Literal of {literals}, a list of those, "
|
|
270
|
+
"and bool for flags)"
|
|
271
|
+
)
|
|
272
|
+
raise TypeError(msg)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _check_nargs(field: Field) -> None:
|
|
276
|
+
if field.nargs is None:
|
|
277
|
+
return
|
|
278
|
+
if not field.is_list:
|
|
279
|
+
msg = f"{field.name!r} has nargs but isn't a list"
|
|
280
|
+
raise TypeError(msg)
|
|
281
|
+
|
|
282
|
+
low, high = field.nargs_range
|
|
283
|
+
if low < 0 or (high is not None and high < max(low, 1)):
|
|
284
|
+
msg = f"{field.name!r} has invalid nargs {field.nargs!r}"
|
|
285
|
+
raise TypeError(msg)
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _check_keys(fields: Sequence[Field]) -> None:
|
|
289
|
+
for field in fields:
|
|
290
|
+
if field.short is not None and not _SHORT_KEY.fullmatch(field.short):
|
|
291
|
+
msg = (
|
|
292
|
+
f"{field.name!r} has invalid short {field.short!r} "
|
|
293
|
+
"(expected '-' plus one letter or digit)"
|
|
294
|
+
)
|
|
295
|
+
raise TypeError(msg)
|
|
296
|
+
if field.custom_long is not None and not _LONG_KEY.fullmatch(field.custom_long):
|
|
297
|
+
msg = (
|
|
298
|
+
f"{field.name!r} has invalid long {field.custom_long!r} "
|
|
299
|
+
"(expected '--' plus letters, digits or '-')"
|
|
300
|
+
)
|
|
301
|
+
raise TypeError(msg)
|
|
302
|
+
|
|
303
|
+
counts = Counter(key for field in fields for key in field.keys)
|
|
304
|
+
if duplicates := [key for key, count in counts.items() if count > 1]:
|
|
305
|
+
msg = f"option keys used more than once: {', '.join(duplicates)}"
|
|
306
|
+
raise TypeError(msg)
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def _check_help_clash(fields: Sequence[Field], help_keys: Collection[HelpKey]) -> None:
|
|
310
|
+
for field in fields:
|
|
311
|
+
for key in field.keys:
|
|
312
|
+
if key in help_keys:
|
|
313
|
+
msg = (
|
|
314
|
+
f"{field.name!r} uses {key!r}, which is reserved for help "
|
|
315
|
+
"-- free it with parse_args(..., help_keys=...)"
|
|
316
|
+
)
|
|
317
|
+
raise TypeError(msg)
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def _check_positional_order(fields: Sequence[Field]) -> None:
|
|
321
|
+
# False (required) sorts before True (optional)
|
|
322
|
+
is_optional = [not field.is_required for field in fields if field.is_pos]
|
|
323
|
+
|
|
324
|
+
if is_optional != sorted(is_optional):
|
|
325
|
+
msg = "required positionals must precede optional ones"
|
|
326
|
+
raise TypeError(msg)
|
|
327
|
+
|
|
328
|
+
# A variable-count list takes the remaining values, so nothing can follow it;
|
|
329
|
+
# a fixed-count list (nargs=N) can go anywhere
|
|
330
|
+
pos_fields = [field for field in fields if field.is_pos]
|
|
331
|
+
if any(field.is_list and len(set(field.nargs_range)) > 1 for field in pos_fields[:-1]):
|
|
332
|
+
msg = "only the last positional can take a variable number of values (use nargs=N)"
|
|
333
|
+
raise TypeError(msg)
|
bicker/_style.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import re
|
|
3
|
+
import sys
|
|
4
|
+
from typing import Final, NamedTuple, TextIO, final
|
|
5
|
+
|
|
6
|
+
_RESET: Final = "\x1b[0m"
|
|
7
|
+
_ANSI_CODE: Final = re.compile(r"\x1b\[[0-9;]*m")
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@final
|
|
11
|
+
class Style(NamedTuple):
|
|
12
|
+
code: str
|
|
13
|
+
fmt: str = "{}"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@final
|
|
17
|
+
class Styles:
|
|
18
|
+
PROG: Final = Style("1;96")
|
|
19
|
+
POS: Final = Style("96")
|
|
20
|
+
OPTIONAL_POS: Final = Style("96", "[{}]")
|
|
21
|
+
OPT: Final = Style("96")
|
|
22
|
+
FLAG: Final = Style("96")
|
|
23
|
+
TYPE: Final = Style("94")
|
|
24
|
+
STR_VALUE: Final = Style("32", '"{}"')
|
|
25
|
+
INT_VALUE: Final = Style("34")
|
|
26
|
+
METAVAR: Final = Style("2;96")
|
|
27
|
+
ELLIPSIS: Final = Style("96", "{}")
|
|
28
|
+
# --------------------------------------------
|
|
29
|
+
ERROR_PREFIX: Final = Style("91", "{}:")
|
|
30
|
+
HEADING: Final = Style("92;1", "{}:")
|
|
31
|
+
USAGE_OPTIONAL_POS: Final = Style("2;96", "[{}]")
|
|
32
|
+
USAGE_OPT: Final = Style("96;2", "[{}]")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def style(text: str, style_: Style, stream: TextIO | None = None) -> str:
|
|
36
|
+
out = stream or sys.stderr
|
|
37
|
+
use_color = out is not None and out.isatty() and not os.environ.get("NO_COLOR")
|
|
38
|
+
fmted = style_.fmt.format(text)
|
|
39
|
+
|
|
40
|
+
if not use_color:
|
|
41
|
+
return fmted
|
|
42
|
+
|
|
43
|
+
start = f"\x1b[{style_.code}m"
|
|
44
|
+
# Re-apply style after any inner reset, so nested styles don't cancel the outer one
|
|
45
|
+
return start + fmted.replace(_RESET, _RESET + start) + _RESET
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def visible_len(text: str) -> int:
|
|
49
|
+
"""Length as rendered in a terminal, ignoring color codes."""
|
|
50
|
+
return len(_ANSI_CODE.sub("", text))
|
bicker/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: bicker
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Tiny, fully typed CLI argument parser: declare args as a class
|
|
5
|
+
Keywords: cli,command-line,arguments,argument-parser,argparse,typed
|
|
6
|
+
Author: darragh0
|
|
7
|
+
Author-email: darragh0 <156817523+darragh0@users.noreply.github.com>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
11
|
+
Classifier: Environment :: Console
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
19
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: >=3.12
|
|
22
|
+
Project-URL: Homepage, https://github.com/darragh0/bicker
|
|
23
|
+
Project-URL: Repository, https://github.com/darragh0/bicker
|
|
24
|
+
Project-URL: Issues, https://github.com/darragh0/bicker/issues
|
|
25
|
+
Project-URL: Changelog, https://github.com/darragh0/bicker/blob/main/CHANGELOG.md
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
|
|
28
|
+
# bicker
|
|
29
|
+
|
|
30
|
+
[](https://pypi.org/project/bicker/)
|
|
31
|
+
[](https://pypi.org/project/bicker/)
|
|
32
|
+
[](https://github.com/darragh0/bicker/actions/workflows/ci.yml)
|
|
33
|
+
|
|
34
|
+
Tiny, fully typed CLI argument parser: declare your args as a class.
|
|
35
|
+
|
|
36
|
+
```sh
|
|
37
|
+
pip install bicker
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
No dependencies.
|
|
41
|
+
|
|
42
|
+
## Usage
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
from typing import Literal
|
|
46
|
+
|
|
47
|
+
from bicker import flag, opt, parse_args, pos
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class Args:
|
|
51
|
+
src: str = pos(description="Image to resize")
|
|
52
|
+
dst: str = pos("out.png", description="Where to save it")
|
|
53
|
+
width: int = opt(800, "-w", metavar="PX", description="Target width")
|
|
54
|
+
fmt: Literal["png", "jpg"] = opt("png", "-f", description="Output format")
|
|
55
|
+
verbose: bool = flag("-v", description="Print progress")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
args = parse_args(Args)
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
`args` is an `Args` instance, so your type checker knows `args.width` is an `int` and
|
|
62
|
+
`args.fmt` is `Literal["png", "jpg"]`. No casts, no stubs, no plugins.
|
|
63
|
+
|
|
64
|
+
```console
|
|
65
|
+
$ python resize.py -h
|
|
66
|
+
Usage: resize.py [-w PX] [-f {png,jpg}] [-v] src [dst]
|
|
67
|
+
|
|
68
|
+
Positionals:
|
|
69
|
+
src Image to resize
|
|
70
|
+
[dst] Where to save it
|
|
71
|
+
|
|
72
|
+
Options:
|
|
73
|
+
-w, --width PX Target width
|
|
74
|
+
-f, --fmt {png,jpg} Output format
|
|
75
|
+
-v, --verbose Print progress
|
|
76
|
+
-h, --help Show this message and exit
|
|
77
|
+
|
|
78
|
+
$ python resize.py cat.jpg -f gif
|
|
79
|
+
error: -f must be one of: "png", "jpg"
|
|
80
|
+
|
|
81
|
+
Usage: resize.py [-w PX] [-f {png,jpg}] [-v] src [dst]
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Output is colored in a terminal, unless `NO_COLOR` is set.
|
|
85
|
+
|
|
86
|
+
## Declaring arguments
|
|
87
|
+
|
|
88
|
+
| Declaration | Gives |
|
|
89
|
+
| --- | --- |
|
|
90
|
+
| `pos()` | A required positional |
|
|
91
|
+
| `pos(default)` | An optional positional (after the required ones) |
|
|
92
|
+
| `opt(default, "-c")` | An option: `--name VALUE`, plus an optional short key |
|
|
93
|
+
| `flag("-v")` | A `bool` option without a value, `False` unless given |
|
|
94
|
+
|
|
95
|
+
Each takes an optional `description=` for help. Options and flags also take `long=` to
|
|
96
|
+
change their long key (which defaults to the field name, with `_` as `-`), and options
|
|
97
|
+
take `metavar=` to change their placeholder in help.
|
|
98
|
+
|
|
99
|
+
**Types:** `str`, `int`, `float`, or a `Literal` of strings or ints (which only allows its
|
|
100
|
+
values). Annotate a field as `list[...]` of any of these to take several values:
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
class Args:
|
|
104
|
+
point: list[int] = pos(nargs=2) # Exactly 2
|
|
105
|
+
files: list[str] = pos() # One or more: the remaining positionals
|
|
106
|
+
tags: list[str] = opt([], "-t") # Repeatable: -t a -t b
|
|
107
|
+
ids: list[int] = opt([], nargs=(1, 3)) # Given 1 to 3 times
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
A list positional must come last, unless `nargs` fixes its count.
|
|
111
|
+
|
|
112
|
+
Mistakes in the class itself (e.g. an unsupported type or a key used twice) raise
|
|
113
|
+
`TypeError` as soon as `parse_args` runs.
|
|
114
|
+
|
|
115
|
+
## Parsing
|
|
116
|
+
|
|
117
|
+
Command lines follow GNU conventions: options and positionals can be mixed, values can
|
|
118
|
+
be attached (`--width=400`, `-w400`), short flags can be grouped (`-vq`), long keys can be
|
|
119
|
+
shortened to any unambiguous prefix (`--wid`), and everything after `--` is a positional.
|
|
120
|
+
|
|
121
|
+
`parse_args` also takes `description=`, `epilog=` and `examples=` for the help page, and
|
|
122
|
+
a few settings like `prog=` and `help_keys=`. See its docstring for all of them.
|
|
123
|
+
|
|
124
|
+
## Not supported (yet)
|
|
125
|
+
|
|
126
|
+
- Subcommands
|
|
127
|
+
- Other value types (e.g. `Path`, `Enum`)
|
|
128
|
+
- Required options
|
|
129
|
+
- Short-only options
|
|
130
|
+
- `--version`
|
|
131
|
+
- Custom colors
|
|
132
|
+
|
|
133
|
+
Feature requests are welcome: [open an issue](https://github.com/darragh0/bicker/issues).
|
|
134
|
+
|
|
135
|
+
## License
|
|
136
|
+
|
|
137
|
+
MIT
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
bicker/__init__.py,sha256=k1k-d5zoHFhY5q6n2ht4dq6ZbQk2hE15erSjBR-ndL0,721
|
|
2
|
+
bicker/_help.py,sha256=TxS9z5q_WFZ4MFKGmsKDuInlBjmJBu94n3dHbsFaGX4,5814
|
|
3
|
+
bicker/_parse.py,sha256=kp9Df_QbpZ-Xox42_I0jfmgWnR3BxvWYLsqfy28WnDs,10026
|
|
4
|
+
bicker/_spec.py,sha256=_gbHdI_ypb81pl7bpUF8y5Chit9biGGISv8if3yfYME,11520
|
|
5
|
+
bicker/_style.py,sha256=PQgocqCl7YOXHOgOEygudqqXS6CzwWfjxTeg_DZtRH4,1442
|
|
6
|
+
bicker/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
7
|
+
bicker-1.0.0.dist-info/licenses/LICENSE,sha256=ZffTXUPAqqc7FQvtAghC-EcftCnNUa3Gvg9VFWnQpAU,1065
|
|
8
|
+
bicker-1.0.0.dist-info/WHEEL,sha256=G_-rrEibZr7OEM7zdH1dSO6s-VdjfnS5PA4CLAdI9Vw,80
|
|
9
|
+
bicker-1.0.0.dist-info/METADATA,sha256=Uw4f55ySkYDxqBZodjesZ3siC1ufCfqHxND8xAE4-p8,4703
|
|
10
|
+
bicker-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 darragh0
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|