mintchip 0.2.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.
- mintchip/__init__.py +101 -0
- mintchip/__main__.py +7 -0
- mintchip/chips/__init__.py +7 -0
- mintchip/chips/bar.py +233 -0
- mintchip/chips/ci.py +194 -0
- mintchip/chips/delta.py +164 -0
- mintchip/chips/dist.py +384 -0
- mintchip/chips/funnel.py +129 -0
- mintchip/chips/gauge.py +197 -0
- mintchip/chips/num.py +55 -0
- mintchip/chips/rank.py +182 -0
- mintchip/chips/ratio.py +141 -0
- mintchip/chips/share.py +164 -0
- mintchip/chips/spark.py +278 -0
- mintchip/chips/strip.py +173 -0
- mintchip/chips/timeline.py +257 -0
- mintchip/chips/waterfall.py +212 -0
- mintchip/cli.py +691 -0
- mintchip/diff.py +645 -0
- mintchip/directives.py +782 -0
- mintchip/doctor.py +145 -0
- mintchip/fmt.py +135 -0
- mintchip/guide.py +189 -0
- mintchip/ingest.py +725 -0
- mintchip/prose.py +225 -0
- mintchip/render/__init__.py +1 -0
- mintchip/render/html.py +295 -0
- mintchip/render/svg_base.py +337 -0
- mintchip/render/text_base.py +215 -0
- mintchip/scales.py +117 -0
- mintchip/skill.py +332 -0
- mintchip/spec.py +659 -0
- mintchip/tables.py +1043 -0
- mintchip/themes.py +102 -0
- mintchip-0.2.0.dist-info/METADATA +274 -0
- mintchip-0.2.0.dist-info/RECORD +39 -0
- mintchip-0.2.0.dist-info/WHEEL +4 -0
- mintchip-0.2.0.dist-info/entry_points.txt +2 -0
- mintchip-0.2.0.dist-info/licenses/LICENSE +21 -0
mintchip/directives.py
ADDED
|
@@ -0,0 +1,782 @@
|
|
|
1
|
+
"""One token grammar for the command line and for ``{{…}}`` directives in prose.
|
|
2
|
+
|
|
3
|
+
``mintchip spark 1.84 1.32 0.96 --band 0.38:0.48`` and ``{{spark 1.84 1.32 0.96 band=0.38:0.48}}``
|
|
4
|
+
are the same call. Bare tokens fill the kind's positional parameters in order; ``--name value``
|
|
5
|
+
and ``name=value`` set a parameter (either form works in both places); a ``name=value`` whose
|
|
6
|
+
name is not a parameter is an entry of the kind's mapping (``{{share code=62 docs=28}}``).
|
|
7
|
+
Values, by ``Param.type``:
|
|
8
|
+
|
|
9
|
+
- ``number``, ``int``: ``0.82``, ``-1e-3``; ``none`` passes None (e.g. no reference line).
|
|
10
|
+
- ``numbers``: numbers separated by spaces or commas; ``null`` or ``nan`` is a gap.
|
|
11
|
+
- ``range``: ``lo:hi``.
|
|
12
|
+
- ``mapping``: ``name=value`` tokens, ``name=start:end`` for spans; quote names with spaces.
|
|
13
|
+
- ``values``: ``pass warn fail skip``, ``true false null`` or numbers.
|
|
14
|
+
- ``strings``: comma-separated.
|
|
15
|
+
- ``bool``: ``--flag`` / ``--no-flag``, or ``flag=true`` / ``flag=false``.
|
|
16
|
+
|
|
17
|
+
Directives are tokenised with ``shlex``; a directive may also be a JSON object,
|
|
18
|
+
``{{ {"chip": "ci", "estimate": 0.08, "interval": [0.05, 0.11]} }}``. ``\\{{`` is a literal
|
|
19
|
+
``{{``. Everything outside directives passes through unchanged.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import difflib
|
|
25
|
+
import html
|
|
26
|
+
import json
|
|
27
|
+
import re
|
|
28
|
+
import shlex
|
|
29
|
+
from collections.abc import Mapping, Sequence
|
|
30
|
+
from dataclasses import dataclass, field
|
|
31
|
+
from typing import Any
|
|
32
|
+
|
|
33
|
+
from .spec import REGISTRY, Chip, ChipError, Param, from_dict
|
|
34
|
+
|
|
35
|
+
__all__ = [
|
|
36
|
+
"SYNTAX",
|
|
37
|
+
"Directive",
|
|
38
|
+
"DirectiveError",
|
|
39
|
+
"call_text",
|
|
40
|
+
"example_call",
|
|
41
|
+
"find",
|
|
42
|
+
"metavar",
|
|
43
|
+
"parse_tokens",
|
|
44
|
+
"render",
|
|
45
|
+
"shared_domains",
|
|
46
|
+
"spec_tokens",
|
|
47
|
+
]
|
|
48
|
+
|
|
49
|
+
LIST_TYPES = ("numbers", "strings", "values")
|
|
50
|
+
GAP = ("null", "none", "nan", "na")
|
|
51
|
+
TRUE = ("true", "yes")
|
|
52
|
+
FALSE = ("false", "no")
|
|
53
|
+
|
|
54
|
+
# Metavar and one-line description of each type's token syntax (CLI help, guide, errors).
|
|
55
|
+
SYNTAX: dict[str, tuple[str, str]] = {
|
|
56
|
+
"number": ("N", "a number, e.g. 0.82 or -1e-3"),
|
|
57
|
+
"int": ("N", "a whole number"),
|
|
58
|
+
"string": ("TEXT", "text; quote it if it has spaces"),
|
|
59
|
+
"bool": ("", "a flag"),
|
|
60
|
+
"numbers": ("V…", "numbers separated by spaces or commas; null or nan is a gap"),
|
|
61
|
+
"range": ("LO:HI", "two numbers joined by a colon, e.g. 0.05:0.11"),
|
|
62
|
+
"strings": ("A,B,…", "comma-separated text"),
|
|
63
|
+
"values": ("R…", "results: pass warn fail skip, true false null, or numbers"),
|
|
64
|
+
"mapping": ("NAME=V…", "name=value tokens (name=start:end for spans); quote names with spaces"),
|
|
65
|
+
}
|
|
66
|
+
_GENERIC = {
|
|
67
|
+
"number": "0.82",
|
|
68
|
+
"int": "10",
|
|
69
|
+
"string": "text",
|
|
70
|
+
"numbers": "0.9 0.6 0.4",
|
|
71
|
+
"range": "0.05:0.11",
|
|
72
|
+
"strings": "a,b",
|
|
73
|
+
"values": "pass fail",
|
|
74
|
+
"mapping": "a=1",
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
# --- token grammar --------------------------------------------------------------------------
|
|
79
|
+
def parse_tokens(
|
|
80
|
+
kind: str,
|
|
81
|
+
tokens: Sequence[str],
|
|
82
|
+
*,
|
|
83
|
+
extra: Sequence[Param] = (),
|
|
84
|
+
style: str = "cli",
|
|
85
|
+
partial: bool = False,
|
|
86
|
+
) -> dict[str, Any]:
|
|
87
|
+
"""Turn tokens into constructor keyword arguments for ``kind`` (plus any ``extra`` params,
|
|
88
|
+
such as the CLI's output flags). ``style`` ("cli" or "directive") only shapes the corrected
|
|
89
|
+
form shown in errors; ``partial`` skips the check for required parameters. Raises
|
|
90
|
+
``ChipError`` naming ``mintchip.<kind>``."""
|
|
91
|
+
return _Parser(kind, tokens, extra, style).parse(partial=partial)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def spec_tokens(
|
|
95
|
+
kind: str, spec: Mapping[str, Any], *, style: str = "cli", omit: Sequence[str] = ()
|
|
96
|
+
) -> list[str]:
|
|
97
|
+
"""The tokens that ``parse_tokens`` turns back into ``spec`` (the inverse, for examples)."""
|
|
98
|
+
toks: list[str] = []
|
|
99
|
+
bare_ok = True
|
|
100
|
+
for p in REGISTRY[kind].params:
|
|
101
|
+
if p.name in omit or p.name not in spec or spec[p.name] is None:
|
|
102
|
+
bare_ok = bare_ok and not p.positional
|
|
103
|
+
continue
|
|
104
|
+
v = spec[p.name]
|
|
105
|
+
bare = p.positional and (bare_ok or p.type == "mapping")
|
|
106
|
+
if bare or (p.type == "mapping" and style == "directive"):
|
|
107
|
+
toks += _value_tokens(p, v)
|
|
108
|
+
elif p.type == "bool":
|
|
109
|
+
name = p.name.replace("_", "-")
|
|
110
|
+
if style == "cli":
|
|
111
|
+
toks.append(f"--{name}" if v else f"--no-{name}")
|
|
112
|
+
else:
|
|
113
|
+
toks.append(f"{p.name}={'true' if v else 'false'}")
|
|
114
|
+
elif style == "cli":
|
|
115
|
+
toks += [f"--{p.name.replace('_', '-')}", *_value_tokens(p, v)]
|
|
116
|
+
else:
|
|
117
|
+
toks.append(f"{p.name}={','.join(_value_tokens(p, v))}")
|
|
118
|
+
return toks
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def call_text(kind: str, tokens: Sequence[str], style: str = "cli") -> str:
|
|
122
|
+
"""``mintchip kind tok…`` or ``{{kind tok…}}``, quoted so it parses back to ``tokens``."""
|
|
123
|
+
body = " ".join(_quote(t, style) for t in (kind, *tokens))
|
|
124
|
+
return "{{" + body + "}}" if style == "directive" else f"mintchip {body}"
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
_SAFE = re.compile(r"[\w@%+=:,./\-\u2212]*", re.ASCII)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _quote(tok: str, style: str) -> str:
|
|
131
|
+
"""Quote a token so the shell (cli) or shlex (directive) reads it back unchanged; a
|
|
132
|
+
``name=value`` token quotes each side, e.g. ``label="Val loss"``."""
|
|
133
|
+
if tok and _SAFE.fullmatch(tok):
|
|
134
|
+
return tok
|
|
135
|
+
if "=" in tok and not tok.startswith("-"):
|
|
136
|
+
name, _, val = tok.partition("=")
|
|
137
|
+
return f"{_quote1(name, style)}={_quote1(val, style)}"
|
|
138
|
+
return _quote1(tok, style)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _quote1(s: str, style: str) -> str:
|
|
142
|
+
if s and _SAFE.fullmatch(s):
|
|
143
|
+
return s
|
|
144
|
+
if style == "cli":
|
|
145
|
+
return shlex.quote(s)
|
|
146
|
+
return '"' + s.replace("\\", "\\\\").replace('"', '\\"') + '"'
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def example_call(kind: str, style: str = "cli", omit: Sequence[str] = ()) -> str:
|
|
150
|
+
"""The kind's registered example as a ready-to-run command line or directive."""
|
|
151
|
+
return call_text(kind, spec_tokens(kind, REGISTRY[kind].example, style=style, omit=omit), style)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _num(v: Any) -> str:
|
|
155
|
+
if v is None:
|
|
156
|
+
return "null"
|
|
157
|
+
if isinstance(v, bool):
|
|
158
|
+
return "true" if v else "false"
|
|
159
|
+
if isinstance(v, str):
|
|
160
|
+
return v
|
|
161
|
+
f = float(v)
|
|
162
|
+
return str(int(f)) if f.is_integer() and abs(f) < 1e15 else repr(f)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _value_tokens(p: Param, v: Any) -> list[str]:
|
|
166
|
+
t = p.type
|
|
167
|
+
if t in ("numbers", "values"):
|
|
168
|
+
return [_num(x) for x in v]
|
|
169
|
+
if t == "range":
|
|
170
|
+
return [f"{_num(v[0])}:{_num(v[1])}"]
|
|
171
|
+
if t == "strings":
|
|
172
|
+
return [",".join(v)]
|
|
173
|
+
if t == "mapping":
|
|
174
|
+
items = v.items() if isinstance(v, Mapping) else v
|
|
175
|
+
out = []
|
|
176
|
+
for name, x in items:
|
|
177
|
+
is_span = isinstance(x, (list, tuple))
|
|
178
|
+
out.append(f"{name}={_num(x[0])}:{_num(x[1])}" if is_span else f"{name}={_num(x)}")
|
|
179
|
+
return out
|
|
180
|
+
return [_num(v)]
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _float(s: str) -> float | None:
|
|
184
|
+
try:
|
|
185
|
+
return float(s.replace("−", "-"))
|
|
186
|
+
except ValueError:
|
|
187
|
+
return None
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _split(raw: Sequence[str]) -> list[str]:
|
|
191
|
+
out: list[str] = []
|
|
192
|
+
for tok in raw:
|
|
193
|
+
out += [x.strip() for x in tok.strip("[]").split(",") if x.strip()]
|
|
194
|
+
return out
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _norm(name: str) -> str:
|
|
198
|
+
return name.strip().replace("-", "_").lower()
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _is_option(tok: str) -> bool:
|
|
202
|
+
if tok.startswith("--"):
|
|
203
|
+
return len(tok) > 2
|
|
204
|
+
return len(tok) > 1 and tok[0] == "-" and tok[1].isalpha() and _float(tok) is None
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
class _Parser:
|
|
208
|
+
def __init__(self, kind: str, tokens: Sequence[str], extra: Sequence[Param], style: str):
|
|
209
|
+
if kind not in REGISTRY:
|
|
210
|
+
raise _unknown_kind(kind, style)
|
|
211
|
+
self.kind, self.style, self.toks = kind, style, list(tokens)
|
|
212
|
+
params = (*REGISTRY[kind].params, *extra)
|
|
213
|
+
self.params = {p.name: p for p in params}
|
|
214
|
+
self.mapping = next((p for p in params if p.type == "mapping"), None)
|
|
215
|
+
self.example = REGISTRY[kind].example
|
|
216
|
+
self.text_tail: dict[str, tuple[Param, str]] = {} # token after a text value -> option
|
|
217
|
+
|
|
218
|
+
# -- messages ---------------------------------------------------------------------------
|
|
219
|
+
def opt(self, p: Param) -> str:
|
|
220
|
+
if self.style == "cli":
|
|
221
|
+
return "--" + p.name.replace("_", "-")
|
|
222
|
+
return p.name + "="
|
|
223
|
+
|
|
224
|
+
def usage(self) -> str:
|
|
225
|
+
parts = [self.kind]
|
|
226
|
+
for p in REGISTRY[self.kind].params:
|
|
227
|
+
if p.positional:
|
|
228
|
+
meta = metavar(p)
|
|
229
|
+
parts.append(meta if p.required else f"[{meta}]")
|
|
230
|
+
tail = " [options]}}" if self.style == "directive" else " [--option value …]"
|
|
231
|
+
return ("{{" if self.style == "directive" else "mintchip ") + " ".join(parts) + tail
|
|
232
|
+
|
|
233
|
+
def fail(
|
|
234
|
+
self,
|
|
235
|
+
msg: str,
|
|
236
|
+
fix: str | None = None,
|
|
237
|
+
*,
|
|
238
|
+
at: int | None = None,
|
|
239
|
+
repl: Sequence[str] = (),
|
|
240
|
+
span: int = 1,
|
|
241
|
+
) -> ChipError:
|
|
242
|
+
"""An error naming the kind; with ``at``, the fix shows the whole call with tokens
|
|
243
|
+
``at`` to ``at + span`` replaced by ``repl``."""
|
|
244
|
+
hint = fix
|
|
245
|
+
if at is not None:
|
|
246
|
+
fixed = self.toks[:at] + list(repl) + self.toks[at + span :]
|
|
247
|
+
call = call_text(self.kind, fixed, self.style)
|
|
248
|
+
hint = f"{fix}: {call}" if fix else call
|
|
249
|
+
return ChipError(f"mintchip.{self.kind}: {msg}", fix_hint=hint)
|
|
250
|
+
|
|
251
|
+
def example_for(self, p: Param) -> str:
|
|
252
|
+
if p.name in self.example and self.example[p.name] is not None:
|
|
253
|
+
return " ".join(_value_tokens(p, self.example[p.name]))
|
|
254
|
+
return _GENERIC.get(p.type, "")
|
|
255
|
+
|
|
256
|
+
def type_fail(self, p: Param, got: str, at: int | None, why: str = "") -> ChipError:
|
|
257
|
+
meta, desc = SYNTAX[p.type]
|
|
258
|
+
got_s = got if len(got) <= 40 else got[:37] + "..."
|
|
259
|
+
msg = why or f"{p.name} must be {desc}; got {got_s!r}."
|
|
260
|
+
if self.style == "cli":
|
|
261
|
+
fix = f"e.g. {self.opt(p)} {self.example_for(p)}"
|
|
262
|
+
else:
|
|
263
|
+
fix = f"e.g. {p.name}={self.example_for(p).replace(' ', ',')}"
|
|
264
|
+
if p.positional:
|
|
265
|
+
fix = f"e.g. {example_call(self.kind, self.style)}"
|
|
266
|
+
if got in self.text_tail:
|
|
267
|
+
opt, first = self.text_tail[got]
|
|
268
|
+
both = _quote(f"{first} {got}", self.style)
|
|
269
|
+
sep = "" if self.style == "directive" else " "
|
|
270
|
+
return self.fail(msg, f"Quote text that has spaces: {self.opt(opt)}{sep}{both}")
|
|
271
|
+
return self.fail(msg, f"Write {p.name} as {meta or 'a flag'}, {fix}.")
|
|
272
|
+
|
|
273
|
+
# -- parsing ----------------------------------------------------------------------------
|
|
274
|
+
def lookup(self, name: str, at: int) -> tuple[Param, bool]:
|
|
275
|
+
key = _norm(name)
|
|
276
|
+
if key in self.params:
|
|
277
|
+
return self.params[key], False
|
|
278
|
+
if key.startswith("no_") and key[3:] in self.params:
|
|
279
|
+
p = self.params[key[3:]]
|
|
280
|
+
if p.type == "bool":
|
|
281
|
+
return p, True
|
|
282
|
+
raise self.fail(f"--no-{name[3:]} only works for flags; {p.name} takes a value.")
|
|
283
|
+
names = list(self.params)
|
|
284
|
+
close = difflib.get_close_matches(key, names, n=1, cutoff=0.6)
|
|
285
|
+
tok = self.toks[at]
|
|
286
|
+
shown = f"--{name}" if tok.startswith("-") else f"{name}="
|
|
287
|
+
listed = ", ".join(self.opt(self.params[n]).rstrip("=") for n in names)
|
|
288
|
+
if not close:
|
|
289
|
+
raise self.fail(f"unknown option {shown}.", f"Options: {listed}.")
|
|
290
|
+
good = close[0].replace("_", "-") if tok.startswith("-") else close[0]
|
|
291
|
+
raise self.fail(
|
|
292
|
+
f"unknown option {shown}.",
|
|
293
|
+
f"Use {self.opt(self.params[close[0]]).rstrip('=')}",
|
|
294
|
+
at=at,
|
|
295
|
+
repl=[tok.replace(name, good, 1)],
|
|
296
|
+
)
|
|
297
|
+
|
|
298
|
+
def set(self, kw: dict[str, Any], p: Param, value: Any) -> None:
|
|
299
|
+
if p.name in kw:
|
|
300
|
+
raise self.fail(f"{p.name} is given twice.", "Give each option once.")
|
|
301
|
+
kw[p.name] = value
|
|
302
|
+
|
|
303
|
+
def parse(self, *, partial: bool = False) -> dict[str, Any]:
|
|
304
|
+
kw: dict[str, Any] = {}
|
|
305
|
+
bare: list[tuple[int, str]] = []
|
|
306
|
+
entries: list[tuple[int, str]] = []
|
|
307
|
+
toks, i = self.toks, 0
|
|
308
|
+
while i < len(toks):
|
|
309
|
+
t = toks[i]
|
|
310
|
+
if t == "--":
|
|
311
|
+
bare += list(enumerate(toks[i + 1 :], i + 1))
|
|
312
|
+
break
|
|
313
|
+
if _is_option(t):
|
|
314
|
+
name, eq, val = t.lstrip("-").partition("=")
|
|
315
|
+
p, neg = self.lookup(name, i)
|
|
316
|
+
if p.type == "bool":
|
|
317
|
+
if neg:
|
|
318
|
+
v = False
|
|
319
|
+
elif eq:
|
|
320
|
+
v = self.boolean(p, val, i)
|
|
321
|
+
elif i + 1 < len(toks) and toks[i + 1].lower() in TRUE + FALSE:
|
|
322
|
+
i += 1
|
|
323
|
+
v = self.boolean(p, toks[i], i)
|
|
324
|
+
else:
|
|
325
|
+
v = True
|
|
326
|
+
elif eq:
|
|
327
|
+
v = (
|
|
328
|
+
self.mapping_value(p, [val], i)
|
|
329
|
+
if p.type == "mapping"
|
|
330
|
+
else (self.convert(p, [val], i))
|
|
331
|
+
)
|
|
332
|
+
else:
|
|
333
|
+
multi = p.type in LIST_TYPES or p.type == "mapping"
|
|
334
|
+
j = i + 1
|
|
335
|
+
while j < len(toks) and not _is_option(toks[j]) and (multi or j == i + 1):
|
|
336
|
+
if multi and self.keyed(toks[j]):
|
|
337
|
+
break
|
|
338
|
+
j += 1
|
|
339
|
+
if j == i + 1:
|
|
340
|
+
meta, desc = SYNTAX[p.type]
|
|
341
|
+
raise self.fail(
|
|
342
|
+
f"{self.opt(p)} needs a value: {desc}.",
|
|
343
|
+
f"e.g. {self.opt(p)} {self.example_for(p)}.",
|
|
344
|
+
)
|
|
345
|
+
vals = toks[i + 1 : j]
|
|
346
|
+
if p.type == "string" and j < len(toks):
|
|
347
|
+
self.text_tail.setdefault(toks[j], (p, vals[0]))
|
|
348
|
+
v = (
|
|
349
|
+
self.mapping_value(p, vals, i)
|
|
350
|
+
if p.type == "mapping"
|
|
351
|
+
else (self.convert(p, vals, i + 1))
|
|
352
|
+
)
|
|
353
|
+
i = j - 1
|
|
354
|
+
self.set(kw, p, v)
|
|
355
|
+
elif "=" in t and not t.startswith("="):
|
|
356
|
+
name, _, val = t.partition("=")
|
|
357
|
+
if _norm(name) in self.params:
|
|
358
|
+
p = self.params[_norm(name)]
|
|
359
|
+
if p.type == "string" and i + 1 < len(toks):
|
|
360
|
+
self.text_tail.setdefault(toks[i + 1], (p, val))
|
|
361
|
+
if p.type == "bool":
|
|
362
|
+
v = self.boolean(p, val, i)
|
|
363
|
+
elif p.type == "mapping":
|
|
364
|
+
v = self.mapping_value(p, [val], i)
|
|
365
|
+
else:
|
|
366
|
+
v = self.convert(p, [val], i)
|
|
367
|
+
self.set(kw, p, v)
|
|
368
|
+
elif self.mapping is not None:
|
|
369
|
+
entries.append((i, t))
|
|
370
|
+
else:
|
|
371
|
+
self.lookup(name, i) # raises with a suggestion
|
|
372
|
+
else:
|
|
373
|
+
bare.append((i, t))
|
|
374
|
+
i += 1
|
|
375
|
+
if entries:
|
|
376
|
+
p = self.mapping
|
|
377
|
+
assert p is not None
|
|
378
|
+
v = self.mapping_value(p, [t for _, t in entries], entries[0][0])
|
|
379
|
+
if p.name in kw:
|
|
380
|
+
kw[p.name] = {**kw[p.name], **v}
|
|
381
|
+
else:
|
|
382
|
+
kw[p.name] = v
|
|
383
|
+
self.fill_positionals(kw, bare)
|
|
384
|
+
for p in self.params.values():
|
|
385
|
+
if p.required and p.name not in kw and not partial:
|
|
386
|
+
meta = metavar(p)
|
|
387
|
+
raise self.fail(
|
|
388
|
+
f"missing {p.name} ({meta}: {SYNTAX[p.type][1]}).",
|
|
389
|
+
f"Usage: {self.usage()}, e.g. {example_call(self.kind, self.style)}",
|
|
390
|
+
)
|
|
391
|
+
return kw
|
|
392
|
+
|
|
393
|
+
def keyed(self, tok: str) -> bool:
|
|
394
|
+
return "=" in tok and _norm(tok.partition("=")[0]) in self.params
|
|
395
|
+
|
|
396
|
+
def fill_positionals(self, kw: dict[str, Any], bare: list[tuple[int, str]]) -> None:
|
|
397
|
+
open_ = [
|
|
398
|
+
p for p in self.params.values()
|
|
399
|
+
if p.positional and p.name not in kw and p.type != "mapping"
|
|
400
|
+
] # fmt: skip
|
|
401
|
+
k = 0
|
|
402
|
+
for n, p in enumerate(open_):
|
|
403
|
+
if k >= len(bare):
|
|
404
|
+
break
|
|
405
|
+
if p.type in LIST_TYPES:
|
|
406
|
+
take = max(1, len(bare) - k - (len(open_) - n - 1))
|
|
407
|
+
kw[p.name] = self.convert(p, [t for _, t in bare[k : k + take]], bare[k][0])
|
|
408
|
+
k += take
|
|
409
|
+
else:
|
|
410
|
+
kw[p.name] = self.convert(p, [bare[k][1]], bare[k][0])
|
|
411
|
+
k += 1
|
|
412
|
+
if k < len(bare):
|
|
413
|
+
extra = " ".join(t for _, t in bare[k:])
|
|
414
|
+
takes = [metavar(p) for p in self.params.values() if p.positional]
|
|
415
|
+
if not takes:
|
|
416
|
+
msg = f"takes no bare values; got {extra!r}."
|
|
417
|
+
else:
|
|
418
|
+
msg = f"takes positional values {' '.join(takes)}; {extra!r} is left over."
|
|
419
|
+
raise self.fail(msg, f"Usage: {self.usage()}. Put options after the values.")
|
|
420
|
+
|
|
421
|
+
# -- conversion -------------------------------------------------------------------------
|
|
422
|
+
def boolean(self, p: Param, s: str, at: int) -> bool:
|
|
423
|
+
low = s.strip().lower()
|
|
424
|
+
if low in TRUE:
|
|
425
|
+
return True
|
|
426
|
+
if low in FALSE:
|
|
427
|
+
return False
|
|
428
|
+
raise self.fail(
|
|
429
|
+
f"{p.name} is a flag; got {s!r}.",
|
|
430
|
+
f"Write {_flag_forms(p, self.style)}.",
|
|
431
|
+
)
|
|
432
|
+
|
|
433
|
+
def number(self, p: Param, s: str, at: int, *, gaps: bool = False) -> float | None:
|
|
434
|
+
if s.strip().lower() in GAP and (gaps or not p.required):
|
|
435
|
+
return None
|
|
436
|
+
f = _float(s)
|
|
437
|
+
if f is not None:
|
|
438
|
+
return f
|
|
439
|
+
if s.endswith("%") and _float(s[:-1]) is not None:
|
|
440
|
+
frac = _float(s[:-1]) / 100 # type: ignore[operator]
|
|
441
|
+
raise self.fail(
|
|
442
|
+
f"{p.name} must be a plain number; got {s!r}.",
|
|
443
|
+
f"Drop the % sign: write {frac:g} for {s} (or the count, with its total).",
|
|
444
|
+
)
|
|
445
|
+
raise self.type_fail(p, s, at)
|
|
446
|
+
|
|
447
|
+
def convert(self, p: Param, raw: Sequence[str], at: int) -> Any:
|
|
448
|
+
t = p.type
|
|
449
|
+
if t in ("number", "int"):
|
|
450
|
+
if len(raw) != 1:
|
|
451
|
+
raise self.type_fail(p, " ".join(raw), at)
|
|
452
|
+
f = self.number(p, raw[0], at)
|
|
453
|
+
if t == "int" and f is not None:
|
|
454
|
+
if not f.is_integer():
|
|
455
|
+
raise self.type_fail(p, raw[0], at, f"{p.name} must be a whole number; got "
|
|
456
|
+
f"{raw[0]!r}.") # fmt: skip
|
|
457
|
+
return int(f)
|
|
458
|
+
return f
|
|
459
|
+
if t == "string":
|
|
460
|
+
return raw[0] if len(raw) == 1 else " ".join(raw)
|
|
461
|
+
if t == "bool":
|
|
462
|
+
return self.boolean(p, raw[0], at)
|
|
463
|
+
if t == "numbers":
|
|
464
|
+
return [self.number(p, x, at, gaps=True) for x in _split(raw)]
|
|
465
|
+
if t == "range":
|
|
466
|
+
return self.range(p, " ".join(raw), at)
|
|
467
|
+
if t == "strings":
|
|
468
|
+
return _split(raw)
|
|
469
|
+
if t == "values":
|
|
470
|
+
out: list[Any] = []
|
|
471
|
+
for x in _split(raw):
|
|
472
|
+
low = x.lower()
|
|
473
|
+
if low in TRUE + FALSE:
|
|
474
|
+
out.append(low in TRUE)
|
|
475
|
+
elif low in GAP:
|
|
476
|
+
out.append(None)
|
|
477
|
+
elif _float(x) is not None:
|
|
478
|
+
out.append(_float(x))
|
|
479
|
+
else:
|
|
480
|
+
out.append(x)
|
|
481
|
+
return out
|
|
482
|
+
raise TypeError(f"unknown param type {t!r}")
|
|
483
|
+
|
|
484
|
+
def range(self, p: Param, s: str, at: int) -> tuple[float, float] | None:
|
|
485
|
+
if s.strip().lower() in GAP and not p.required:
|
|
486
|
+
return None
|
|
487
|
+
parts = s.split(":") if ":" in s else s.strip("()[]").split(",")
|
|
488
|
+
nums = [_float(x.strip().strip("()[]")) for x in parts]
|
|
489
|
+
if len(nums) == 2 and None not in nums:
|
|
490
|
+
lo, hi = nums
|
|
491
|
+
if lo > hi: # type: ignore[operator]
|
|
492
|
+
good = f"{_num(hi)}:{_num(lo)}"
|
|
493
|
+
raise self.fix(
|
|
494
|
+
f"{p.name} must have lo <= hi; got {s!r}.", "Swap the ends", at, s, good
|
|
495
|
+
)
|
|
496
|
+
return lo, hi # type: ignore[return-value]
|
|
497
|
+
nxt = self.toks[at + 1] if 0 <= at < len(self.toks) - 1 else None
|
|
498
|
+
if len(nums) == 1 and nums[0] is not None and nxt is not None and _float(nxt) is not None:
|
|
499
|
+
good = f"{s}:{nxt}"
|
|
500
|
+
raise self.fail(
|
|
501
|
+
f"{p.name} must be one lo:hi token; got {s!r} then {nxt!r}.",
|
|
502
|
+
"Join the ends with a colon",
|
|
503
|
+
at=at,
|
|
504
|
+
repl=[self.toks[at].replace(s, good, 1)],
|
|
505
|
+
span=2,
|
|
506
|
+
)
|
|
507
|
+
m = re.fullmatch(r"\s*(-?[\d.eE+]+)\s*(?:-|\.\.|to)\s*(-?[\d.eE+]+)\s*", s)
|
|
508
|
+
if m and _float(m[1]) is not None and _float(m[2]) is not None:
|
|
509
|
+
good = f"{m[1]}:{m[2]}"
|
|
510
|
+
raise self.fix(
|
|
511
|
+
f"{p.name} must be lo:hi with a colon; got {s!r}.", "Use a colon", at, s, good
|
|
512
|
+
)
|
|
513
|
+
raise self.type_fail(p, s, at)
|
|
514
|
+
|
|
515
|
+
def fix(self, msg: str, how: str, at: int, old: str, new: str) -> ChipError:
|
|
516
|
+
"""An error whose fix replaces ``old`` with ``new`` in the token at (or after) ``at``."""
|
|
517
|
+
for n in range(max(at, 0), len(self.toks)):
|
|
518
|
+
if old in self.toks[n]:
|
|
519
|
+
return self.fail(msg, how, at=n, repl=[self.toks[n].replace(old, new, 1)])
|
|
520
|
+
return self.fail(msg, f"{how}: {new}.")
|
|
521
|
+
|
|
522
|
+
def mapping_value(self, p: Param, raw: Sequence[str], at: int) -> dict[str, Any]:
|
|
523
|
+
out: dict[str, Any] = {}
|
|
524
|
+
for tok in raw:
|
|
525
|
+
name, eq, val = tok.partition("=")
|
|
526
|
+
if not eq or not name.strip():
|
|
527
|
+
raise self.fail(
|
|
528
|
+
f"{p.name} entries must be name=value; got {tok!r}.",
|
|
529
|
+
f"e.g. {' '.join(_value_tokens(p, self.example[p.name]))}"
|
|
530
|
+
if p.name in self.example
|
|
531
|
+
else None,
|
|
532
|
+
)
|
|
533
|
+
name = name.strip()
|
|
534
|
+
if name in out:
|
|
535
|
+
raise self.fail(f"{p.name} has {name!r} twice.", "Give each name once.")
|
|
536
|
+
if ":" in val:
|
|
537
|
+
out[name] = self.range(p, val, at)
|
|
538
|
+
else:
|
|
539
|
+
f = _float(val)
|
|
540
|
+
if f is None:
|
|
541
|
+
raise self.fail(
|
|
542
|
+
f"{p.name}: {name}={val!r} is not a number.",
|
|
543
|
+
"Write name=value, e.g. fetch=1.2 (or name=start:end for spans).",
|
|
544
|
+
)
|
|
545
|
+
out[name] = f
|
|
546
|
+
return out
|
|
547
|
+
|
|
548
|
+
|
|
549
|
+
def metavar(p: Param) -> str:
|
|
550
|
+
meta = SYNTAX[p.type][0]
|
|
551
|
+
if p.type in ("number", "int", "numbers", "values"):
|
|
552
|
+
meta = p.name.upper() + ("…" if p.type in ("numbers", "values") else "")
|
|
553
|
+
return meta
|
|
554
|
+
|
|
555
|
+
|
|
556
|
+
def _flag_forms(p: Param, style: str) -> str:
|
|
557
|
+
dashed = p.name.replace("_", "-")
|
|
558
|
+
if style == "cli":
|
|
559
|
+
return f"--{dashed} or --no-{dashed}"
|
|
560
|
+
return f"{p.name}=true or {p.name}=false"
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
def _unknown_kind(kind: str, style: str) -> ChipError:
|
|
564
|
+
names = sorted(REGISTRY)
|
|
565
|
+
close = difflib.get_close_matches(kind, names, n=1)
|
|
566
|
+
hint = f"Did you mean {close[0]!r}? " if close else ""
|
|
567
|
+
return ChipError(
|
|
568
|
+
f"mintchip: unknown chip {kind!r}.", fix_hint=f"{hint}Chips: {', '.join(names)}."
|
|
569
|
+
)
|
|
570
|
+
|
|
571
|
+
|
|
572
|
+
# --- directives in prose --------------------------------------------------------------------
|
|
573
|
+
@dataclass
|
|
574
|
+
class Directive:
|
|
575
|
+
"""One ``{{…}}`` in a document: where it is, its source text and the chip it makes."""
|
|
576
|
+
|
|
577
|
+
start: int
|
|
578
|
+
end: int
|
|
579
|
+
line: int
|
|
580
|
+
col: int
|
|
581
|
+
source: str
|
|
582
|
+
chip: Chip | None = None
|
|
583
|
+
domain: tuple[float, float] | None = field(default=None)
|
|
584
|
+
|
|
585
|
+
@property
|
|
586
|
+
def where(self) -> str:
|
|
587
|
+
src = self.source if len(self.source) <= 48 else self.source[:45] + "...}}"
|
|
588
|
+
return f"line {self.line}, column {self.col}: {src}"
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
class DirectiveError(ChipError):
|
|
592
|
+
"""Malformed directives; ``errors`` holds one ``(where, ChipError)`` pair per directive."""
|
|
593
|
+
|
|
594
|
+
def __init__(self, errors: list[tuple[str, ChipError]]) -> None:
|
|
595
|
+
self.errors = errors
|
|
596
|
+
first_where, first = errors[0]
|
|
597
|
+
more = f" (and {len(errors) - 1} more)" if len(errors) > 1 else ""
|
|
598
|
+
super().__init__(f"{first_where}: {first.message}{more}", fix_hint=first.fix_hint)
|
|
599
|
+
|
|
600
|
+
|
|
601
|
+
def _location(text: str, pos: int) -> tuple[int, int]:
|
|
602
|
+
line = text.count("\n", 0, pos) + 1
|
|
603
|
+
return line, pos - (text.rfind("\n", 0, pos) + 1) + 1
|
|
604
|
+
|
|
605
|
+
|
|
606
|
+
def find(text: str) -> tuple[list[str], list[Directive]]:
|
|
607
|
+
"""Split ``text`` into literal pieces and directives (``len(pieces) == len(directives)+1``),
|
|
608
|
+
building each directive's chip. Raises ``DirectiveError`` listing every bad directive."""
|
|
609
|
+
pieces: list[str] = []
|
|
610
|
+
found: list[Directive] = []
|
|
611
|
+
errors: list[tuple[str, ChipError]] = []
|
|
612
|
+
buf, i = [], 0
|
|
613
|
+
while True:
|
|
614
|
+
j = text.find("{{", i)
|
|
615
|
+
if j < 0:
|
|
616
|
+
buf.append(text[i:])
|
|
617
|
+
break
|
|
618
|
+
if j > 0 and text[j - 1] == "\\":
|
|
619
|
+
buf.append(text[i : j - 1] + "{{")
|
|
620
|
+
i = j + 2
|
|
621
|
+
continue
|
|
622
|
+
buf.append(text[i:j])
|
|
623
|
+
line, col = _location(text, j)
|
|
624
|
+
end, body, err = _scan(text, j)
|
|
625
|
+
d = Directive(j, end, line, col, text[j:end])
|
|
626
|
+
if err is not None:
|
|
627
|
+
errors.append((f"line {line}, column {col}: {d.source.splitlines()[0]}", err))
|
|
628
|
+
else:
|
|
629
|
+
try:
|
|
630
|
+
d.chip = _build(body)
|
|
631
|
+
except ChipError as e:
|
|
632
|
+
errors.append((d.where, e))
|
|
633
|
+
pieces.append("".join(buf))
|
|
634
|
+
buf = []
|
|
635
|
+
found.append(d)
|
|
636
|
+
i = end
|
|
637
|
+
pieces.append("".join(buf))
|
|
638
|
+
if errors:
|
|
639
|
+
raise DirectiveError(errors)
|
|
640
|
+
return pieces, found
|
|
641
|
+
|
|
642
|
+
|
|
643
|
+
def _scan(text: str, j: int) -> tuple[int, str, ChipError | None]:
|
|
644
|
+
"""Find the end of the directive opening at ``j``: (end, body, error)."""
|
|
645
|
+
k = j + 2
|
|
646
|
+
while k < len(text) and text[k] in " \t":
|
|
647
|
+
k += 1
|
|
648
|
+
if k < len(text) and text[k] == "{":
|
|
649
|
+
try:
|
|
650
|
+
_, stop = json.JSONDecoder().raw_decode(text, k)
|
|
651
|
+
except json.JSONDecodeError as e:
|
|
652
|
+
line, col = _location(text, e.pos)
|
|
653
|
+
return (
|
|
654
|
+
_line_end(text, j),
|
|
655
|
+
"",
|
|
656
|
+
ChipError(
|
|
657
|
+
f"mintchip: bad JSON in directive at line {line}, column {col}: {e.msg}.",
|
|
658
|
+
fix_hint='Write {{ {"chip": "ci", "estimate": 0.08, "interval": [0.05, 0.11]} }}.',
|
|
659
|
+
),
|
|
660
|
+
)
|
|
661
|
+
m = re.compile(r"\s*\}\}").match(text, stop)
|
|
662
|
+
if not m:
|
|
663
|
+
return (
|
|
664
|
+
_line_end(text, j),
|
|
665
|
+
"",
|
|
666
|
+
ChipError(
|
|
667
|
+
"mintchip: a JSON directive must end with }} right after the object.",
|
|
668
|
+
fix_hint="Close it: {{ {...} }}.",
|
|
669
|
+
),
|
|
670
|
+
)
|
|
671
|
+
return m.end(), text[j + 2 : stop], None
|
|
672
|
+
end = text.find("}}", j + 2)
|
|
673
|
+
nl = text.find("\n", j + 2)
|
|
674
|
+
if end < 0 or 0 <= nl < end:
|
|
675
|
+
stop = _line_end(text, j)
|
|
676
|
+
src = text[j:stop].rstrip()
|
|
677
|
+
m = re.fullmatch(r"(.*?)([.,;:!?)]*)", src)
|
|
678
|
+
src = f"{m[1]}}}}}{m[2]}" if m else src + "}}"
|
|
679
|
+
return (
|
|
680
|
+
stop,
|
|
681
|
+
"",
|
|
682
|
+
ChipError(
|
|
683
|
+
"mintchip: directive is not closed with }} on the same line.",
|
|
684
|
+
fix_hint=f"Close it: {src} (For literal braces write \\{{{{.)",
|
|
685
|
+
),
|
|
686
|
+
)
|
|
687
|
+
return end + 2, text[j + 2 : end], None
|
|
688
|
+
|
|
689
|
+
|
|
690
|
+
def _line_end(text: str, j: int) -> int:
|
|
691
|
+
nl = text.find("\n", j)
|
|
692
|
+
return len(text) if nl < 0 else nl
|
|
693
|
+
|
|
694
|
+
|
|
695
|
+
def _build(body: str) -> Chip:
|
|
696
|
+
s = body.strip()
|
|
697
|
+
if s.startswith("{"):
|
|
698
|
+
return from_dict(json.loads(s))
|
|
699
|
+
try:
|
|
700
|
+
toks = shlex.split(s)
|
|
701
|
+
except ValueError as e:
|
|
702
|
+
raise ChipError(
|
|
703
|
+
f"mintchip: cannot split the directive into tokens ({e}).",
|
|
704
|
+
fix_hint="Close the quote, or drop a stray apostrophe (write it inside double quotes).",
|
|
705
|
+
) from None
|
|
706
|
+
if not toks:
|
|
707
|
+
raise ChipError(
|
|
708
|
+
"mintchip: empty directive.", fix_hint="Write {{kind values…}}, e.g. {{spark 3 1 2}}."
|
|
709
|
+
)
|
|
710
|
+
kind, *rest = toks
|
|
711
|
+
if kind not in REGISTRY:
|
|
712
|
+
err = _unknown_kind(kind, "directive")
|
|
713
|
+
close = difflib.get_close_matches(kind, sorted(REGISTRY), n=1)
|
|
714
|
+
if close:
|
|
715
|
+
err = ChipError(err.message, fix_hint=f"Write {call_text(close[0], rest, 'directive')}")
|
|
716
|
+
raise err
|
|
717
|
+
return REGISTRY[kind].fn(**parse_tokens(kind, rest, style="directive"))
|
|
718
|
+
|
|
719
|
+
|
|
720
|
+
def shared_domains(chips: Sequence[Chip]) -> list[tuple[float, float] | None]:
|
|
721
|
+
"""The domain each chip gets under ``format_prose``'s ``share="auto"`` rule: chips of one
|
|
722
|
+
kind with the same non-empty unit are read on one scale."""
|
|
723
|
+
from .prose import shared_domains as share
|
|
724
|
+
|
|
725
|
+
names = [f"c{n}" for n in range(len(chips))]
|
|
726
|
+
domains = share(dict(zip(names, chips, strict=True)))
|
|
727
|
+
return [domains.get(n) for n in names]
|
|
728
|
+
|
|
729
|
+
|
|
730
|
+
def render(
|
|
731
|
+
text: str,
|
|
732
|
+
*,
|
|
733
|
+
format: str = "text",
|
|
734
|
+
ascii: bool = False,
|
|
735
|
+
compact: bool = False,
|
|
736
|
+
title: str = "mintchip",
|
|
737
|
+
theme: str = "auto",
|
|
738
|
+
fragment: bool = False,
|
|
739
|
+
) -> tuple[str, list[Directive]]:
|
|
740
|
+
"""Replace every directive in ``text`` with its chip. Formats: ``text``, ``ansi``, ``md``
|
|
741
|
+
(code spans), ``html`` (a full page via ``mintchip.document``, or embeddable ``<p>``
|
|
742
|
+
blocks when ``fragment=True``). Returns the output and the directives (each with its
|
|
743
|
+
``chip``), so callers can report warnings by location."""
|
|
744
|
+
if format not in ("text", "ansi", "md", "html"):
|
|
745
|
+
raise ChipError(
|
|
746
|
+
f"mintchip render: unknown format {format!r}.", fix_hint="Use text, ansi, md or html."
|
|
747
|
+
)
|
|
748
|
+
pieces, found = find(text)
|
|
749
|
+
for d, dom in zip(found, shared_domains([d.chip for d in found]), strict=True): # type: ignore[misc]
|
|
750
|
+
d.domain = dom
|
|
751
|
+
if format == "html":
|
|
752
|
+
return _html_page(pieces, found, title=title, theme=theme, fragment=fragment), found
|
|
753
|
+
out = [pieces[0]]
|
|
754
|
+
for d, piece in zip(found, pieces[1:], strict=True):
|
|
755
|
+
c = d.chip
|
|
756
|
+
assert c is not None
|
|
757
|
+
s = c.text(ascii=ascii, compact=compact, color=format == "ansi", domain=d.domain)
|
|
758
|
+
if format == "md":
|
|
759
|
+
s = f"`` {s} ``" if "`" in s else f"`{s}`"
|
|
760
|
+
out += [s, piece]
|
|
761
|
+
return "".join(out), found
|
|
762
|
+
|
|
763
|
+
|
|
764
|
+
def _html_page(
|
|
765
|
+
pieces: list[str],
|
|
766
|
+
found: list[Directive],
|
|
767
|
+
*,
|
|
768
|
+
title: str,
|
|
769
|
+
theme: str,
|
|
770
|
+
fragment: bool = False,
|
|
771
|
+
) -> str:
|
|
772
|
+
import mintchip
|
|
773
|
+
|
|
774
|
+
parts = [html.escape(pieces[0])]
|
|
775
|
+
for d, piece in zip(found, pieces[1:], strict=True):
|
|
776
|
+
assert d.chip is not None
|
|
777
|
+
parts += [d.chip.html(theme=theme, domain=d.domain), html.escape(piece)]
|
|
778
|
+
body = "".join(parts)
|
|
779
|
+
blocks = [f"<p>{b.strip()}</p>" for b in re.split(r"\n[ \t]*\n", body) if b.strip()]
|
|
780
|
+
if fragment:
|
|
781
|
+
return "\n".join(blocks)
|
|
782
|
+
return mintchip.document(title, blocks, theme=theme)
|