cli-contracts-runtime 0.36.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.
- cli_contracts_runtime/__init__.py +54 -0
- cli_contracts_runtime/client.py +86 -0
- cli_contracts_runtime/extract.py +87 -0
- cli_contracts_runtime/jsonvalue.py +102 -0
- cli_contracts_runtime/policy.py +237 -0
- cli_contracts_runtime/program.py +550 -0
- cli_contracts_runtime/py.typed +0 -0
- cli_contracts_runtime/typing_compat.py +18 -0
- cli_contracts_runtime-0.36.0.dist-info/METADATA +68 -0
- cli_contracts_runtime-0.36.0.dist-info/RECORD +12 -0
- cli_contracts_runtime-0.36.0.dist-info/WHEEL +5 -0
- cli_contracts_runtime-0.36.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""The runtime of the Python programs and command wrappers cli-contracts
|
|
2
|
+
generates from a CLI contract. A generated program holds its command tree
|
|
3
|
+
and dispatches to its handlers; this package parses an invocation over the
|
|
4
|
+
tree by commander's rules, so the program behaves as the TypeScript program
|
|
5
|
+
generated from the same contract."""
|
|
6
|
+
|
|
7
|
+
from .client import ExecResult, arg_string, exec_cli, format_number
|
|
8
|
+
from .extract import ExtractSet, ExtractSpec
|
|
9
|
+
from .jsonvalue import Number, quote, stringify
|
|
10
|
+
from .policy import introspect
|
|
11
|
+
from .typing_compat import NotRequired
|
|
12
|
+
from .program import (
|
|
13
|
+
FLAG,
|
|
14
|
+
NEGATE,
|
|
15
|
+
TAKES_VALUE,
|
|
16
|
+
Action,
|
|
17
|
+
Argument,
|
|
18
|
+
Command,
|
|
19
|
+
Invocation,
|
|
20
|
+
Option,
|
|
21
|
+
Outcome,
|
|
22
|
+
Program,
|
|
23
|
+
UsageError,
|
|
24
|
+
outcome,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
__version__ = "0.36.0"
|
|
28
|
+
|
|
29
|
+
__all__ = [
|
|
30
|
+
"FLAG",
|
|
31
|
+
"NEGATE",
|
|
32
|
+
"TAKES_VALUE",
|
|
33
|
+
"Action",
|
|
34
|
+
"Argument",
|
|
35
|
+
"Command",
|
|
36
|
+
"ExecResult",
|
|
37
|
+
"ExtractSet",
|
|
38
|
+
"ExtractSpec",
|
|
39
|
+
"Invocation",
|
|
40
|
+
"NotRequired",
|
|
41
|
+
"Number",
|
|
42
|
+
"Option",
|
|
43
|
+
"Outcome",
|
|
44
|
+
"Program",
|
|
45
|
+
"UsageError",
|
|
46
|
+
"arg_string",
|
|
47
|
+
"exec_cli",
|
|
48
|
+
"format_number",
|
|
49
|
+
"introspect",
|
|
50
|
+
"outcome",
|
|
51
|
+
"quote",
|
|
52
|
+
"stringify",
|
|
53
|
+
"__version__",
|
|
54
|
+
]
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""The command wrappers' side: running a CLI with the arguments a wrapper
|
|
2
|
+
built, and writing a number as an argument the way the TypeScript wrapper's
|
|
3
|
+
``String(value)`` does."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import math
|
|
8
|
+
import subprocess
|
|
9
|
+
from decimal import Decimal
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from typing import List
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class ExecResult:
|
|
16
|
+
exit_code: int
|
|
17
|
+
stdout: str
|
|
18
|
+
stderr: str
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def exec_cli(executable: str, args: List[str]) -> ExecResult:
|
|
22
|
+
"""Runs an executable with arguments. A CLI that cannot be started, or is
|
|
23
|
+
ended by a signal, has exit code 1."""
|
|
24
|
+
try:
|
|
25
|
+
done = subprocess.run([executable, *args], capture_output=True, check=False)
|
|
26
|
+
except OSError:
|
|
27
|
+
return ExecResult(exit_code=1, stdout="", stderr="")
|
|
28
|
+
code = done.returncode if done.returncode >= 0 else 1
|
|
29
|
+
return ExecResult(
|
|
30
|
+
exit_code=code,
|
|
31
|
+
stdout=done.stdout.decode("utf-8", "replace"),
|
|
32
|
+
stderr=done.stderr.decode("utf-8", "replace"),
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def format_number(f: float) -> str:
|
|
37
|
+
"""Writes a number as JavaScript's ``String(n)`` does (Number::toString:
|
|
38
|
+
the shortest digits that read back as the number, in fixed notation from
|
|
39
|
+
1e-7 up to 1e21 and exponential notation outside)."""
|
|
40
|
+
f = float(f)
|
|
41
|
+
if math.isnan(f):
|
|
42
|
+
return "NaN"
|
|
43
|
+
if math.isinf(f):
|
|
44
|
+
return "Infinity" if f > 0 else "-Infinity"
|
|
45
|
+
if f == 0:
|
|
46
|
+
return "0"
|
|
47
|
+
sign = "-" if f < 0 else ""
|
|
48
|
+
# repr writes the shortest digits that read back as the number.
|
|
49
|
+
_, digit_tuple, exponent = Decimal(repr(abs(f))).as_tuple()
|
|
50
|
+
digits = "".join(map(str, digit_tuple))
|
|
51
|
+
stripped = digits.rstrip("0")
|
|
52
|
+
exponent += len(digits) - len(stripped)
|
|
53
|
+
digits = stripped.lstrip("0")
|
|
54
|
+
k = len(digits)
|
|
55
|
+
n = k + int(exponent)
|
|
56
|
+
if k <= n <= 21:
|
|
57
|
+
out = digits + "0" * (n - k)
|
|
58
|
+
elif 0 < n <= 21:
|
|
59
|
+
out = digits[:n] + "." + digits[n:]
|
|
60
|
+
elif -6 < n <= 0:
|
|
61
|
+
out = "0." + "0" * (-n) + digits
|
|
62
|
+
else:
|
|
63
|
+
m = digits[0] + ("." + digits[1:] if k > 1 else "")
|
|
64
|
+
out = f"{m}e{'-' if n - 1 < 0 else '+'}{abs(n - 1)}"
|
|
65
|
+
return sign + out
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def arg_string(value: object) -> str:
|
|
69
|
+
"""Writes a value as an argument the way JavaScript's ``String(value)``
|
|
70
|
+
does: a number in JavaScript's notation, a list as its items joined by
|
|
71
|
+
commas (None as nothing), an object as ``[object Object]``."""
|
|
72
|
+
if value is None:
|
|
73
|
+
return "null"
|
|
74
|
+
if value is True:
|
|
75
|
+
return "true"
|
|
76
|
+
if value is False:
|
|
77
|
+
return "false"
|
|
78
|
+
if isinstance(value, int):
|
|
79
|
+
return str(value)
|
|
80
|
+
if isinstance(value, float):
|
|
81
|
+
return format_number(value)
|
|
82
|
+
if isinstance(value, str):
|
|
83
|
+
return value
|
|
84
|
+
if isinstance(value, (list, tuple)):
|
|
85
|
+
return ",".join("" if item is None else arg_string(item) for item in value)
|
|
86
|
+
return "[object Object]"
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""The built-in extract command.
|
|
2
|
+
|
|
3
|
+
Its output is computed when the program is generated (cli-contracts
|
|
4
|
+
``src/generators/runtime-spec.ts``, ExtractSpec); what depends on the
|
|
5
|
+
invocation is filled in here: the time, and which commands the given IDs
|
|
6
|
+
select.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from datetime import datetime, timezone
|
|
13
|
+
from typing import Any, Dict, List, Tuple
|
|
14
|
+
|
|
15
|
+
EXTRACTED_AT = "\x00cli-contracts:extractedAt\x00"
|
|
16
|
+
"""Stands where the time of the invocation goes in the output."""
|
|
17
|
+
_EXTRACTED_AT_JSON = "\\u0000cli-contracts:extractedAt\\u0000"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class ExtractSet:
|
|
22
|
+
"""A command set of the embedded contract; ``commands`` holds each command's ID and its JSON at its depth."""
|
|
23
|
+
|
|
24
|
+
id: str
|
|
25
|
+
key: str
|
|
26
|
+
before: List[str] = field(default_factory=list)
|
|
27
|
+
after: List[str] = field(default_factory=list)
|
|
28
|
+
commands: List[Tuple[str, str]] = field(default_factory=list)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class ExtractSpec:
|
|
33
|
+
yaml_with_meta: str
|
|
34
|
+
yaml_without_meta: str
|
|
35
|
+
json_with_meta: str
|
|
36
|
+
json_without_meta: str
|
|
37
|
+
filter_head: str
|
|
38
|
+
filter_tail: str
|
|
39
|
+
sets: List[ExtractSet] = field(default_factory=list)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _iso_now() -> str:
|
|
43
|
+
"""The time as JavaScript's ``Date.prototype.toISOString`` writes it."""
|
|
44
|
+
now = datetime.now(timezone.utc)
|
|
45
|
+
return now.strftime("%Y-%m-%dT%H:%M:%S.") + f"{now.microsecond // 1000:03d}Z"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _truthy(values: Dict[str, Any], key: str) -> bool:
|
|
49
|
+
v = values.get(key)
|
|
50
|
+
if v is None or v is False:
|
|
51
|
+
return False
|
|
52
|
+
if isinstance(v, str):
|
|
53
|
+
return v != ""
|
|
54
|
+
return True
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def run_extract(spec: ExtractSpec, args: List[Any], opts: Dict[str, Any]) -> Tuple[int, str, str]:
|
|
58
|
+
"""Runs the built-in extract command: the exit code, stdout and stderr."""
|
|
59
|
+
commands = list(args[0]) if args and isinstance(args[0], list) else []
|
|
60
|
+
all_ = _truthy(opts, "all")
|
|
61
|
+
if not commands and not all_:
|
|
62
|
+
return 2, "", '{"code":"INVALID_ARGS","message":"Specify command IDs or use --all"}\n'
|
|
63
|
+
fmt = opts.get("format") if _truthy(opts, "format") else "yaml"
|
|
64
|
+
ids = [] if all_ else commands
|
|
65
|
+
include_meta = _truthy(opts, "includeMeta")
|
|
66
|
+
now = _iso_now()
|
|
67
|
+
if not ids:
|
|
68
|
+
if fmt == "json":
|
|
69
|
+
text = spec.json_with_meta if include_meta else spec.json_without_meta
|
|
70
|
+
return 0, text.replace(_EXTRACTED_AT_JSON, now), ""
|
|
71
|
+
text = spec.yaml_with_meta if include_meta else spec.yaml_without_meta
|
|
72
|
+
return 0, text.replace(EXTRACTED_AT, now), ""
|
|
73
|
+
|
|
74
|
+
def selected(set_id: str, cmd_id: str) -> bool:
|
|
75
|
+
return any(i == cmd_id or i == f"{set_id}.{cmd_id}" or cmd_id.startswith(i + ".") for i in ids)
|
|
76
|
+
|
|
77
|
+
sets: List[str] = []
|
|
78
|
+
for s in spec.sets:
|
|
79
|
+
matched = [text for cmd_id, text in s.commands if selected(s.id, cmd_id)]
|
|
80
|
+
if not matched:
|
|
81
|
+
continue
|
|
82
|
+
entries = list(s.before)
|
|
83
|
+
entries.append(' "commands": {\n' + ",\n".join(matched) + "\n }")
|
|
84
|
+
entries.extend(s.after)
|
|
85
|
+
sets.append(s.key + "{\n" + ",\n".join(entries) + "\n }")
|
|
86
|
+
command_sets = "{\n" + ",\n".join(sets) + "\n }" if sets else "{}"
|
|
87
|
+
return 0, spec.filter_head + command_sets + spec.filter_tail, ""
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""JSON values and a writer that writes them as ``JSON.stringify`` does.
|
|
2
|
+
|
|
3
|
+
A JSON object is a ``dict`` (it keeps its keys in insertion order, as a
|
|
4
|
+
JavaScript object does); a number is a :class:`Number`, which holds the text
|
|
5
|
+
JavaScript writes for it.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class Number:
|
|
14
|
+
"""A JSON number, held as the text JavaScript writes for it."""
|
|
15
|
+
|
|
16
|
+
__slots__ = ("text",)
|
|
17
|
+
|
|
18
|
+
def __init__(self, text: str) -> None:
|
|
19
|
+
self.text = text
|
|
20
|
+
|
|
21
|
+
def __eq__(self, other: object) -> bool:
|
|
22
|
+
return isinstance(other, Number) and other.text == self.text
|
|
23
|
+
|
|
24
|
+
def __hash__(self) -> int:
|
|
25
|
+
return hash(self.text)
|
|
26
|
+
|
|
27
|
+
def __repr__(self) -> str:
|
|
28
|
+
return f"Number({self.text!r})"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
_ESCAPES = {'"': '\\"', "\\": "\\\\", "\b": "\\b", "\f": "\\f", "\n": "\\n", "\r": "\\r", "\t": "\\t"}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def quote(s: str) -> str:
|
|
35
|
+
"""A string as ``JSON.stringify`` writes it."""
|
|
36
|
+
out = ['"']
|
|
37
|
+
for c in s:
|
|
38
|
+
escaped = _ESCAPES.get(c)
|
|
39
|
+
if escaped is not None:
|
|
40
|
+
out.append(escaped)
|
|
41
|
+
elif ord(c) < 0x20:
|
|
42
|
+
out.append("\\u%04x" % ord(c))
|
|
43
|
+
else:
|
|
44
|
+
out.append(c)
|
|
45
|
+
out.append('"')
|
|
46
|
+
return "".join(out)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def stringify(value: Any, indent: int = 0) -> str:
|
|
50
|
+
"""Writes a value as ``JSON.stringify(value, null, indent)`` does; an
|
|
51
|
+
indent of 0 writes it on one line."""
|
|
52
|
+
out: list[str] = []
|
|
53
|
+
_write(out, value, indent, 0)
|
|
54
|
+
return "".join(out)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _newline(out: list[str], indent: int, depth: int) -> None:
|
|
58
|
+
if indent > 0:
|
|
59
|
+
out.append("\n" + " " * (indent * depth))
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _write(out: list[str], value: Any, indent: int, depth: int) -> None:
|
|
63
|
+
if value is None:
|
|
64
|
+
out.append("null")
|
|
65
|
+
elif value is True:
|
|
66
|
+
out.append("true")
|
|
67
|
+
elif value is False:
|
|
68
|
+
out.append("false")
|
|
69
|
+
elif isinstance(value, Number):
|
|
70
|
+
out.append(value.text)
|
|
71
|
+
elif isinstance(value, int):
|
|
72
|
+
out.append(str(value))
|
|
73
|
+
elif isinstance(value, str):
|
|
74
|
+
out.append(quote(value))
|
|
75
|
+
elif isinstance(value, (list, tuple)):
|
|
76
|
+
if not value:
|
|
77
|
+
out.append("[]")
|
|
78
|
+
return
|
|
79
|
+
out.append("[")
|
|
80
|
+
for i, item in enumerate(value):
|
|
81
|
+
if i > 0:
|
|
82
|
+
out.append(",")
|
|
83
|
+
_newline(out, indent, depth + 1)
|
|
84
|
+
_write(out, item, indent, depth + 1)
|
|
85
|
+
_newline(out, indent, depth)
|
|
86
|
+
out.append("]")
|
|
87
|
+
elif isinstance(value, dict):
|
|
88
|
+
if not value:
|
|
89
|
+
out.append("{}")
|
|
90
|
+
return
|
|
91
|
+
out.append("{")
|
|
92
|
+
for i, (k, v) in enumerate(value.items()):
|
|
93
|
+
if i > 0:
|
|
94
|
+
out.append(",")
|
|
95
|
+
_newline(out, indent, depth + 1)
|
|
96
|
+
out.append(quote(k))
|
|
97
|
+
out.append(": " if indent > 0 else ":")
|
|
98
|
+
_write(out, v, indent, depth + 1)
|
|
99
|
+
_newline(out, indent, depth)
|
|
100
|
+
out.append("}")
|
|
101
|
+
else:
|
|
102
|
+
raise TypeError(f"not a JSON value: {value!r}")
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
"""The policy derivation of ``--introspect``.
|
|
2
|
+
|
|
3
|
+
The derivation is defined by cli-contracts ``src/policy-runtime.ts``
|
|
4
|
+
(introspectCommand, derivePolicy, isOptionActive); this is its port, and
|
|
5
|
+
test/conformance compares the two. A definition is the command's
|
|
6
|
+
CommandPolicyDefinition as JSON.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import Any, Dict, List, Optional
|
|
12
|
+
|
|
13
|
+
from .jsonvalue import Number
|
|
14
|
+
|
|
15
|
+
_RISK_ORDER = {"low": 0, "medium": 1, "high": 2, "critical": 3}
|
|
16
|
+
_ABSENT = object()
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _truthy(v: Any) -> bool:
|
|
20
|
+
"""JavaScript's truthiness of a JSON value; absent is falsy."""
|
|
21
|
+
if v is _ABSENT or v is None or v is False:
|
|
22
|
+
return False
|
|
23
|
+
if isinstance(v, str):
|
|
24
|
+
return v != ""
|
|
25
|
+
if isinstance(v, Number):
|
|
26
|
+
return v.text not in ("0", "-0", "NaN")
|
|
27
|
+
return True
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _get(v: Any, key: str) -> Any:
|
|
31
|
+
if isinstance(v, dict) and key in v:
|
|
32
|
+
return v[key]
|
|
33
|
+
return _ABSENT
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _risk_level(effects: Any) -> Any:
|
|
37
|
+
level = _get(effects, "risk_level")
|
|
38
|
+
return "low" if level is _ABSENT or level is None else level
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _risk(level: Any) -> Optional[int]:
|
|
42
|
+
return _RISK_ORDER.get(level) if isinstance(level, str) else None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _source_requires_confirmation(effects: Any) -> bool:
|
|
46
|
+
"""The source's explicit requires_confirmation, or else its own risk level at high or above."""
|
|
47
|
+
explicit = _get(effects, "requires_confirmation")
|
|
48
|
+
if explicit is not _ABSENT and explicit is not None:
|
|
49
|
+
return _truthy(explicit)
|
|
50
|
+
n = _risk(_risk_level(effects))
|
|
51
|
+
return n is not None and n >= _RISK_ORDER["high"]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def camel_case(name: str) -> str:
|
|
55
|
+
"""Joins the ``-``-separated words of a name in camelCase, as commander keys an option's value."""
|
|
56
|
+
words = name.split("-")
|
|
57
|
+
return words[0] + "".join(w[:1].upper() + w[1:] for w in words[1:])
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _is_option_active(definition: Any, value: Any, specified: bool) -> bool:
|
|
61
|
+
if _get(_get(definition, "schema"), "type") == "boolean":
|
|
62
|
+
return value is True
|
|
63
|
+
if _truthy(_get(definition, "repeatable")):
|
|
64
|
+
return specified and isinstance(value, list) and len(value) > 0
|
|
65
|
+
return specified and value is not None and value is not _ABSENT
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _copy(out: Dict[str, Any], key: str, src: Any) -> None:
|
|
69
|
+
v = _get(src, key)
|
|
70
|
+
if v is not _ABSENT:
|
|
71
|
+
out[key] = v
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _copy_if_truthy(out: Dict[str, Any], key: str, src: Any) -> None:
|
|
75
|
+
v = _get(src, key)
|
|
76
|
+
if _truthy(v):
|
|
77
|
+
out[key] = v
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _semantic_read(r: Any, source: str) -> Dict[str, Any]:
|
|
81
|
+
read = {"target": r} if isinstance(r, str) else r
|
|
82
|
+
out: Dict[str, Any] = {"kind": "semantic"}
|
|
83
|
+
_copy(out, "target", read)
|
|
84
|
+
_copy(out, "description", read)
|
|
85
|
+
out["source"] = source
|
|
86
|
+
return out
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _semantic_write(w: Any, source: str) -> Dict[str, Any]:
|
|
90
|
+
write = {"target": w} if isinstance(w, str) else w
|
|
91
|
+
out: Dict[str, Any] = {"kind": "semantic"}
|
|
92
|
+
for key in ("target", "description", "overwrite", "destructive", "idempotent"):
|
|
93
|
+
_copy(out, key, write)
|
|
94
|
+
_copy_if_truthy(out, "idempotency_key", write)
|
|
95
|
+
_copy_if_truthy(out, "idempotent_note", write)
|
|
96
|
+
out["source"] = source
|
|
97
|
+
return out
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _network_effect(network: Any, source: str) -> Dict[str, Any]:
|
|
101
|
+
out: Dict[str, Any] = {}
|
|
102
|
+
_copy_if_truthy(out, "description", network)
|
|
103
|
+
_copy_if_truthy(out, "domains", network)
|
|
104
|
+
_copy(out, "idempotent", network)
|
|
105
|
+
_copy_if_truthy(out, "idempotency_key", network)
|
|
106
|
+
_copy_if_truthy(out, "idempotent_note", network)
|
|
107
|
+
out["source"] = source
|
|
108
|
+
return out
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class _Derivation:
|
|
112
|
+
def __init__(self) -> None:
|
|
113
|
+
self.side_effects: List[str] = []
|
|
114
|
+
self.reads: List[Any] = []
|
|
115
|
+
self.writes: List[Any] = []
|
|
116
|
+
self.network: List[Any] = []
|
|
117
|
+
self.risk_levels: List[Any] = []
|
|
118
|
+
self.execution_mode: Any = None
|
|
119
|
+
self.confirmation = False
|
|
120
|
+
|
|
121
|
+
def add_side_effect(self, effect: str) -> None:
|
|
122
|
+
if effect not in self.side_effects:
|
|
123
|
+
self.side_effects.append(effect)
|
|
124
|
+
|
|
125
|
+
def add_write(self, write: Dict[str, Any]) -> None:
|
|
126
|
+
# Every derived write, and only a write, puts file_write among the side effects.
|
|
127
|
+
self.add_side_effect("file_write")
|
|
128
|
+
self.writes.append(write)
|
|
129
|
+
|
|
130
|
+
def add_effects(self, effects: Any, source: str, is_command: bool) -> None:
|
|
131
|
+
self.risk_levels.append(_risk_level(effects))
|
|
132
|
+
if _source_requires_confirmation(effects):
|
|
133
|
+
self.confirmation = True
|
|
134
|
+
writes = _get(effects, "writes")
|
|
135
|
+
if _truthy(writes) and isinstance(writes, list):
|
|
136
|
+
for w in writes:
|
|
137
|
+
self.add_write(_semantic_write(w, source))
|
|
138
|
+
reads = _get(effects, "reads")
|
|
139
|
+
if _truthy(reads) and isinstance(reads, list):
|
|
140
|
+
for r in reads:
|
|
141
|
+
self.reads.append(_semantic_read(r, source))
|
|
142
|
+
network = _get(effects, "network")
|
|
143
|
+
if _truthy(network):
|
|
144
|
+
self.add_side_effect("network")
|
|
145
|
+
if isinstance(network, dict):
|
|
146
|
+
self.network.append(_network_effect(network, source))
|
|
147
|
+
mode = _get(effects, "execution_mode")
|
|
148
|
+
if _truthy(mode) and (is_command or self.execution_mode is None):
|
|
149
|
+
self.execution_mode = mode
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _derive_policy(command_id: str, definition: Any, options: Dict[str, Dict[str, Any]]) -> Dict[str, Any]:
|
|
153
|
+
d = _Derivation()
|
|
154
|
+
effects = _get(definition, "effects")
|
|
155
|
+
if _truthy(effects):
|
|
156
|
+
d.add_effects(effects, f"command:{command_id}", True)
|
|
157
|
+
|
|
158
|
+
for name, inp in options.items():
|
|
159
|
+
if not _is_option_active(inp["definition"], inp["value"], inp["specified"]):
|
|
160
|
+
continue
|
|
161
|
+
source = f"option:{name}"
|
|
162
|
+
file = _get(inp["definition"], "file")
|
|
163
|
+
if _truthy(file):
|
|
164
|
+
value = inp["value"]
|
|
165
|
+
mode = _get(file, "mode")
|
|
166
|
+
if mode in ("read", "readWrite"):
|
|
167
|
+
read: Dict[str, Any] = {"kind": "option-file", "option": name}
|
|
168
|
+
if isinstance(value, str):
|
|
169
|
+
read["path"] = value
|
|
170
|
+
read["source"] = source
|
|
171
|
+
d.reads.append(read)
|
|
172
|
+
if mode in ("write", "append", "readWrite"):
|
|
173
|
+
write: Dict[str, Any] = {"kind": "option-file", "option": name}
|
|
174
|
+
if isinstance(value, str):
|
|
175
|
+
write["path"] = value
|
|
176
|
+
write["mode"] = mode
|
|
177
|
+
write["source"] = source
|
|
178
|
+
d.add_write(write)
|
|
179
|
+
option_effects = _get(inp["definition"], "effects")
|
|
180
|
+
if _truthy(option_effects):
|
|
181
|
+
d.add_effects(option_effects, source, False)
|
|
182
|
+
|
|
183
|
+
final_risk: Any = "low"
|
|
184
|
+
max_order = 0
|
|
185
|
+
for level in d.risk_levels:
|
|
186
|
+
n = _risk(level)
|
|
187
|
+
if n is not None and n > max_order:
|
|
188
|
+
max_order = n
|
|
189
|
+
final_risk = level
|
|
190
|
+
|
|
191
|
+
secrets: List[str] = []
|
|
192
|
+
env = _get(definition, "env")
|
|
193
|
+
if isinstance(env, dict):
|
|
194
|
+
for env_name, var in env.items():
|
|
195
|
+
if _truthy(_get(var, "sensitive")):
|
|
196
|
+
secrets.append(env_name)
|
|
197
|
+
|
|
198
|
+
idempotent = all(w.get("idempotent") is True for w in d.writes if w.get("kind") == "semantic") and all(
|
|
199
|
+
n.get("idempotent") is True for n in d.network
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
policy: Dict[str, Any] = {
|
|
203
|
+
"risk_level": final_risk,
|
|
204
|
+
"requires_confirmation": d.confirmation,
|
|
205
|
+
"idempotent": idempotent,
|
|
206
|
+
"side_effects": list(d.side_effects),
|
|
207
|
+
"reads": d.reads,
|
|
208
|
+
"writes": d.writes,
|
|
209
|
+
}
|
|
210
|
+
if d.network:
|
|
211
|
+
policy["network"] = d.network
|
|
212
|
+
if d.execution_mode is not None:
|
|
213
|
+
policy["execution_mode"] = d.execution_mode
|
|
214
|
+
if secrets:
|
|
215
|
+
policy["requires_secrets"] = secrets
|
|
216
|
+
return policy
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def introspect(command_id: str, definition: Any, option_values: Dict[str, Any]) -> Dict[str, Any]:
|
|
220
|
+
"""Derives a command's policy from the option values the program parsed for it (introspectCommand)."""
|
|
221
|
+
options: Dict[str, Dict[str, Any]] = {}
|
|
222
|
+
active: List[str] = []
|
|
223
|
+
defs = _get(definition, "options")
|
|
224
|
+
for opt in defs if isinstance(defs, list) else []:
|
|
225
|
+
name = _get(opt, "name")
|
|
226
|
+
name = name if isinstance(name, str) else ""
|
|
227
|
+
key = camel_case(name)
|
|
228
|
+
value = option_values.get(key)
|
|
229
|
+
specified = key in option_values and value is not None
|
|
230
|
+
options[name] = {"definition": opt, "value": value, "specified": specified}
|
|
231
|
+
if _is_option_active(opt, value, specified):
|
|
232
|
+
active.append(name)
|
|
233
|
+
return {
|
|
234
|
+
"command": command_id,
|
|
235
|
+
"active_options": active,
|
|
236
|
+
"policy": _derive_policy(command_id, definition, options),
|
|
237
|
+
}
|
|
@@ -0,0 +1,550 @@
|
|
|
1
|
+
"""The command tree of a generated program and the parsing of an invocation.
|
|
2
|
+
|
|
3
|
+
The tree is the one commander builds for the contract (cli-contracts
|
|
4
|
+
``src/generators/commander-tree.ts``); the generator writes it as a literal.
|
|
5
|
+
An invocation is parsed by the rules of commander 14 (lib/command.js:
|
|
6
|
+
parseOptions, _parseCommand, _dispatchSubcommand, _dispatchHelpCommand,
|
|
7
|
+
_processArguments, addOption's value handling, optsWithGlobals, version,
|
|
8
|
+
_outputHelpIfRequested and the error messages; lib/suggestSimilar.js), over
|
|
9
|
+
the parts of commander a generated program uses. The TypeScript program
|
|
10
|
+
generated from the same contract is commander itself; test/conformance
|
|
11
|
+
compares the two.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import re
|
|
17
|
+
import sys
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
from typing import IO, Any, Callable, Dict, List, Optional, Tuple
|
|
20
|
+
|
|
21
|
+
from .jsonvalue import stringify
|
|
22
|
+
from .policy import introspect
|
|
23
|
+
|
|
24
|
+
FLAG = "flag"
|
|
25
|
+
NEGATE = "negate"
|
|
26
|
+
TAKES_VALUE = "value"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class Option:
|
|
31
|
+
"""An option as commander registers it."""
|
|
32
|
+
|
|
33
|
+
flags: str
|
|
34
|
+
name: str
|
|
35
|
+
key: str
|
|
36
|
+
kind: str = FLAG
|
|
37
|
+
short: Optional[str] = None
|
|
38
|
+
long: Optional[str] = None
|
|
39
|
+
variadic: bool = False
|
|
40
|
+
version: bool = False
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass
|
|
44
|
+
class Argument:
|
|
45
|
+
name: str
|
|
46
|
+
required: bool = False
|
|
47
|
+
variadic: bool = False
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass
|
|
51
|
+
class Action:
|
|
52
|
+
"""What a command runs: a contract command's handler, or the built-in extract command."""
|
|
53
|
+
|
|
54
|
+
command_id: Optional[str] = None
|
|
55
|
+
llm: bool = False
|
|
56
|
+
introspect: bool = False
|
|
57
|
+
extract: bool = False
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass
|
|
61
|
+
class Command:
|
|
62
|
+
name: str
|
|
63
|
+
help: str
|
|
64
|
+
options: List[Option] = field(default_factory=list)
|
|
65
|
+
initial_values: List[Tuple[str, Any]] = field(default_factory=list)
|
|
66
|
+
arguments: List[Argument] = field(default_factory=list)
|
|
67
|
+
commands: List["Command"] = field(default_factory=list)
|
|
68
|
+
hidden: bool = False
|
|
69
|
+
default_command: Optional[str] = None
|
|
70
|
+
help_command: Optional[str] = None
|
|
71
|
+
help_short: Optional[str] = None
|
|
72
|
+
help_long: Optional[str] = None
|
|
73
|
+
action: Optional[Action] = None
|
|
74
|
+
option_suggestions: List[str] = field(default_factory=list)
|
|
75
|
+
command_suggestions: List[str] = field(default_factory=list)
|
|
76
|
+
digit_short_option: bool = False
|
|
77
|
+
parent: Optional["Command"] = field(default=None, repr=False, compare=False)
|
|
78
|
+
|
|
79
|
+
def _link(self) -> None:
|
|
80
|
+
for sub in self.commands:
|
|
81
|
+
sub.parent = self
|
|
82
|
+
sub._link()
|
|
83
|
+
|
|
84
|
+
def _find_command(self, name: Optional[str]) -> Optional["Command"]:
|
|
85
|
+
if not name:
|
|
86
|
+
return None
|
|
87
|
+
for sub in self.commands:
|
|
88
|
+
if sub.name == name:
|
|
89
|
+
return sub
|
|
90
|
+
return None
|
|
91
|
+
|
|
92
|
+
def _find_option(self, arg: str) -> Optional[Option]:
|
|
93
|
+
for opt in self.options:
|
|
94
|
+
if (opt.short is not None and opt.short == arg) or (opt.long is not None and opt.long == arg):
|
|
95
|
+
return opt
|
|
96
|
+
return None
|
|
97
|
+
|
|
98
|
+
def _is_help_flag(self, arg: str) -> bool:
|
|
99
|
+
return (self.help_short is not None and arg == self.help_short) or (
|
|
100
|
+
self.help_long is not None and arg == self.help_long
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
@dataclass
|
|
105
|
+
class UsageError:
|
|
106
|
+
"""An invocation the program rejects. ``code`` is commander's code for the error."""
|
|
107
|
+
|
|
108
|
+
code: str
|
|
109
|
+
message: str
|
|
110
|
+
exit_code: int = 1
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@dataclass
|
|
114
|
+
class Invocation:
|
|
115
|
+
"""What a command's handler receives: the argument values (a string, None
|
|
116
|
+
for an optional argument not given, a list for a variadic one), the
|
|
117
|
+
command's own option values (commander's ``opts()``) and those of the
|
|
118
|
+
command and its ancestors, an ancestor's value replacing the command's
|
|
119
|
+
(``optsWithGlobals()``)."""
|
|
120
|
+
|
|
121
|
+
args: List[Any]
|
|
122
|
+
opts: Dict[str, Any]
|
|
123
|
+
globals: Dict[str, Any]
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
@dataclass
|
|
127
|
+
class Outcome:
|
|
128
|
+
exit_code: int = 0
|
|
129
|
+
prompt: Optional[str] = None
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
Dispatch = Callable[[str, Invocation], Outcome]
|
|
133
|
+
UsageErrorHandler = Callable[[UsageError, Command], int]
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
class _Exit(Exception):
|
|
137
|
+
def __init__(self, code: int) -> None:
|
|
138
|
+
super().__init__(code)
|
|
139
|
+
self.code = code
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
_NEGATIVE_NUMBER = re.compile(r"-(\d+|\d*\.\d+)(e[+-]?\d+)?\Z", re.ASCII)
|
|
143
|
+
_LONG_WITH_VALUE = re.compile(r"^--[^=]+=")
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _maybe_option(arg: str) -> bool:
|
|
147
|
+
return len(arg) > 1 and arg[0] == "-"
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _js_len(s: str) -> int:
|
|
151
|
+
"""The length of a string in UTF-16 code units, as JavaScript counts it."""
|
|
152
|
+
return sum(2 if ord(c) >= 0x10000 else 1 for c in s)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _truthy(values: Dict[str, Any], key: str) -> bool:
|
|
156
|
+
"""JavaScript's truthiness of an option value."""
|
|
157
|
+
if key not in values:
|
|
158
|
+
return False
|
|
159
|
+
v = values[key]
|
|
160
|
+
if v is None or v is False:
|
|
161
|
+
return False
|
|
162
|
+
if isinstance(v, str):
|
|
163
|
+
return v != ""
|
|
164
|
+
return True
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
class Program:
|
|
168
|
+
"""A generated program: the tree, the version ``--version`` writes, and
|
|
169
|
+
what ``--introspect`` and the built-in extract command write."""
|
|
170
|
+
|
|
171
|
+
def __init__(
|
|
172
|
+
self,
|
|
173
|
+
root: Command,
|
|
174
|
+
version: str,
|
|
175
|
+
dispatch: Dispatch,
|
|
176
|
+
on_usage_error: Optional[UsageErrorHandler] = None,
|
|
177
|
+
policy: Optional[Dict[str, Any]] = None,
|
|
178
|
+
extract: Any = None,
|
|
179
|
+
) -> None:
|
|
180
|
+
root._link()
|
|
181
|
+
self.root = root
|
|
182
|
+
self.version = version
|
|
183
|
+
self.dispatch = dispatch
|
|
184
|
+
self.on_usage_error = on_usage_error
|
|
185
|
+
self.policy = policy or {}
|
|
186
|
+
self.extract = extract
|
|
187
|
+
|
|
188
|
+
def run(self, argv: List[str], stdout: Optional[IO[str]] = None, stderr: Optional[IO[str]] = None) -> int:
|
|
189
|
+
"""Parses an invocation, runs what it names and returns the exit code."""
|
|
190
|
+
run = _Run(self, stdout or sys.stdout, stderr or sys.stderr)
|
|
191
|
+
try:
|
|
192
|
+
return run.parse_command(self.root, [], list(argv))
|
|
193
|
+
except _Exit as e:
|
|
194
|
+
return e.code
|
|
195
|
+
|
|
196
|
+
def main(self) -> None:
|
|
197
|
+
"""Runs the program with the process's arguments and exits with its exit code."""
|
|
198
|
+
sys.exit(self.run(sys.argv[1:]))
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
class _Run:
|
|
202
|
+
def __init__(self, program: Program, stdout: IO[str], stderr: IO[str]) -> None:
|
|
203
|
+
self.p = program
|
|
204
|
+
self.stdout = stdout
|
|
205
|
+
self.stderr = stderr
|
|
206
|
+
self.values: Dict[int, Dict[str, Any]] = {}
|
|
207
|
+
# The keys of each command the invocation set.
|
|
208
|
+
self.given: set = set()
|
|
209
|
+
self._prepare(program.root)
|
|
210
|
+
|
|
211
|
+
def _prepare(self, cmd: Command) -> None:
|
|
212
|
+
self.values[id(cmd)] = {k: (list(v) if isinstance(v, list) else v) for k, v in cmd.initial_values}
|
|
213
|
+
for sub in cmd.commands:
|
|
214
|
+
self._prepare(sub)
|
|
215
|
+
|
|
216
|
+
def help(self, cmd: Command, is_error: bool) -> None:
|
|
217
|
+
if is_error:
|
|
218
|
+
self.stderr.write(cmd.help)
|
|
219
|
+
raise _Exit(1)
|
|
220
|
+
self.stdout.write(cmd.help)
|
|
221
|
+
raise _Exit(0)
|
|
222
|
+
|
|
223
|
+
def error(self, cmd: Command, message: str, code: str) -> None:
|
|
224
|
+
err = UsageError(code=code, message=message, exit_code=1)
|
|
225
|
+
if self.p.on_usage_error is not None:
|
|
226
|
+
raise _Exit(self.p.on_usage_error(err, cmd))
|
|
227
|
+
self.stderr.write(message + "\n")
|
|
228
|
+
raise _Exit(1)
|
|
229
|
+
|
|
230
|
+
def negative_number_arg(self, cmd: Command, arg: str) -> bool:
|
|
231
|
+
return _NEGATIVE_NUMBER.match(arg) is not None and not cmd.digit_short_option
|
|
232
|
+
|
|
233
|
+
def emit_option(self, cmd: Command, opt: Option, value: Optional[str]) -> None:
|
|
234
|
+
if opt.version:
|
|
235
|
+
self.stdout.write(self.p.version + "\n")
|
|
236
|
+
raise _Exit(0)
|
|
237
|
+
values = self.values[id(cmd)]
|
|
238
|
+
given_before = (id(cmd), opt.key) in self.given
|
|
239
|
+
self.given.add((id(cmd), opt.key))
|
|
240
|
+
if value is None:
|
|
241
|
+
values[opt.key] = opt.kind != NEGATE
|
|
242
|
+
elif opt.variadic:
|
|
243
|
+
# A value given replaces the default and is added to the values given before it.
|
|
244
|
+
previous = values.get(opt.key)
|
|
245
|
+
if given_before and isinstance(previous, list):
|
|
246
|
+
values[opt.key] = [*previous, value]
|
|
247
|
+
else:
|
|
248
|
+
values[opt.key] = [value]
|
|
249
|
+
else:
|
|
250
|
+
values[opt.key] = value
|
|
251
|
+
|
|
252
|
+
def parse_options(self, cmd: Command, args: List[str]) -> Tuple[List[str], List[str]]:
|
|
253
|
+
operands: List[str] = []
|
|
254
|
+
unknown: List[str] = []
|
|
255
|
+
to_unknown = False
|
|
256
|
+
active_variadic: Optional[Option] = None
|
|
257
|
+
active_group: Optional[str] = None
|
|
258
|
+
i = 0
|
|
259
|
+
while i < len(args) or active_group is not None:
|
|
260
|
+
if active_group is not None:
|
|
261
|
+
arg = active_group
|
|
262
|
+
active_group = None
|
|
263
|
+
else:
|
|
264
|
+
arg = args[i]
|
|
265
|
+
i += 1
|
|
266
|
+
|
|
267
|
+
if arg == "--":
|
|
268
|
+
dest = unknown if to_unknown else operands
|
|
269
|
+
if to_unknown:
|
|
270
|
+
dest.append(arg)
|
|
271
|
+
dest.extend(args[i:])
|
|
272
|
+
break
|
|
273
|
+
|
|
274
|
+
if active_variadic is not None and (not _maybe_option(arg) or self.negative_number_arg(cmd, arg)):
|
|
275
|
+
self.emit_option(cmd, active_variadic, arg)
|
|
276
|
+
continue
|
|
277
|
+
active_variadic = None
|
|
278
|
+
|
|
279
|
+
if _maybe_option(arg):
|
|
280
|
+
opt = cmd._find_option(arg)
|
|
281
|
+
if opt is not None:
|
|
282
|
+
if opt.kind == TAKES_VALUE:
|
|
283
|
+
if i >= len(args):
|
|
284
|
+
self.error(cmd, f"error: option '{opt.flags}' argument missing", "commander.optionMissingArgument")
|
|
285
|
+
value = args[i]
|
|
286
|
+
i += 1
|
|
287
|
+
self.emit_option(cmd, opt, value)
|
|
288
|
+
else:
|
|
289
|
+
self.emit_option(cmd, opt, None)
|
|
290
|
+
if opt.variadic:
|
|
291
|
+
active_variadic = opt
|
|
292
|
+
continue
|
|
293
|
+
|
|
294
|
+
# Combined short options, like -abc: the first one if known. A
|
|
295
|
+
# character outside the BMP is two code units in JavaScript, of
|
|
296
|
+
# which arg[1] holds only the first; no flag matches it.
|
|
297
|
+
if _js_len(arg) > 2 and arg[0] == "-" and arg[1] != "-" and ord(arg[1]) < 0x10000:
|
|
298
|
+
opt = cmd._find_option("-" + arg[1])
|
|
299
|
+
if opt is not None:
|
|
300
|
+
if opt.kind == TAKES_VALUE:
|
|
301
|
+
self.emit_option(cmd, opt, arg[2:])
|
|
302
|
+
else:
|
|
303
|
+
self.emit_option(cmd, opt, None)
|
|
304
|
+
active_group = "-" + arg[2:]
|
|
305
|
+
continue
|
|
306
|
+
|
|
307
|
+
# A known long option with its value, like --foo=bar.
|
|
308
|
+
if _LONG_WITH_VALUE.match(arg):
|
|
309
|
+
index = arg.index("=")
|
|
310
|
+
opt = cmd._find_option(arg[:index])
|
|
311
|
+
if opt is not None and opt.kind == TAKES_VALUE:
|
|
312
|
+
self.emit_option(cmd, opt, arg[index + 1 :])
|
|
313
|
+
continue
|
|
314
|
+
|
|
315
|
+
# An unknown option makes the arguments after it unknown too, so a
|
|
316
|
+
# subcommand parses them again. A negative number in a leaf command
|
|
317
|
+
# is not an option.
|
|
318
|
+
if (
|
|
319
|
+
not to_unknown
|
|
320
|
+
and _maybe_option(arg)
|
|
321
|
+
and not (len(cmd.commands) == 0 and self.negative_number_arg(cmd, arg))
|
|
322
|
+
):
|
|
323
|
+
to_unknown = True
|
|
324
|
+
(unknown if to_unknown else operands).append(arg)
|
|
325
|
+
return operands, unknown
|
|
326
|
+
|
|
327
|
+
def parse_command(self, cmd: Command, operands: List[str], unknown: List[str]) -> int:
|
|
328
|
+
parsed_operands, parsed_unknown = self.parse_options(cmd, unknown)
|
|
329
|
+
operands = operands + parsed_operands
|
|
330
|
+
unknown = parsed_unknown
|
|
331
|
+
args = operands + unknown
|
|
332
|
+
|
|
333
|
+
if operands and cmd._find_command(operands[0]) is not None:
|
|
334
|
+
return self.dispatch_subcommand(cmd, operands[0], operands[1:], unknown)
|
|
335
|
+
if cmd.help_command is not None and operands and operands[0] == cmd.help_command:
|
|
336
|
+
return self.dispatch_help_command(cmd, operands[1] if len(operands) > 1 else "")
|
|
337
|
+
if cmd.default_command is not None:
|
|
338
|
+
self.output_help_if_requested(cmd, unknown)
|
|
339
|
+
return self.dispatch_subcommand(cmd, cmd.default_command, operands, unknown)
|
|
340
|
+
if cmd.commands and not args and cmd.action is None:
|
|
341
|
+
self.help(cmd, True)
|
|
342
|
+
|
|
343
|
+
self.output_help_if_requested(cmd, unknown)
|
|
344
|
+
|
|
345
|
+
if cmd.action is not None:
|
|
346
|
+
self.check_for_unknown_options(cmd, unknown)
|
|
347
|
+
processed = self.process_arguments(cmd, args)
|
|
348
|
+
return self.run_action(cmd, processed)
|
|
349
|
+
if operands:
|
|
350
|
+
if cmd.commands:
|
|
351
|
+
self.unknown_command(cmd, args[0])
|
|
352
|
+
self.check_for_unknown_options(cmd, unknown)
|
|
353
|
+
self.process_arguments(cmd, args)
|
|
354
|
+
return 0
|
|
355
|
+
self.check_for_unknown_options(cmd, unknown)
|
|
356
|
+
if cmd.commands:
|
|
357
|
+
self.help(cmd, True)
|
|
358
|
+
self.process_arguments(cmd, args)
|
|
359
|
+
return 0
|
|
360
|
+
|
|
361
|
+
def dispatch_subcommand(self, cmd: Command, name: str, operands: List[str], unknown: List[str]) -> int:
|
|
362
|
+
sub = cmd._find_command(name)
|
|
363
|
+
if sub is None:
|
|
364
|
+
self.help(cmd, True)
|
|
365
|
+
assert sub is not None
|
|
366
|
+
return self.parse_command(sub, operands, unknown)
|
|
367
|
+
|
|
368
|
+
def dispatch_help_command(self, cmd: Command, name: str) -> int:
|
|
369
|
+
if not name:
|
|
370
|
+
self.help(cmd, False)
|
|
371
|
+
sub = cmd._find_command(name)
|
|
372
|
+
if sub is not None:
|
|
373
|
+
self.help(sub, False)
|
|
374
|
+
flag = cmd.help_long or cmd.help_short or "--help"
|
|
375
|
+
return self.dispatch_subcommand(cmd, name, [], [flag])
|
|
376
|
+
|
|
377
|
+
def output_help_if_requested(self, cmd: Command, args: List[str]) -> None:
|
|
378
|
+
if any(cmd._is_help_flag(a) for a in args):
|
|
379
|
+
self.stdout.write(cmd.help)
|
|
380
|
+
raise _Exit(0)
|
|
381
|
+
|
|
382
|
+
def check_for_unknown_options(self, cmd: Command, unknown: List[str]) -> None:
|
|
383
|
+
if unknown:
|
|
384
|
+
self.unknown_option(cmd, unknown[0])
|
|
385
|
+
|
|
386
|
+
def process_arguments(self, cmd: Command, args: List[str]) -> List[Any]:
|
|
387
|
+
for i, arg in enumerate(cmd.arguments):
|
|
388
|
+
if arg.required and i >= len(args):
|
|
389
|
+
self.error(cmd, f"error: missing required argument '{arg.name}'", "commander.missingArgument")
|
|
390
|
+
n = len(cmd.arguments)
|
|
391
|
+
if not (n > 0 and cmd.arguments[-1].variadic) and len(args) > n:
|
|
392
|
+
for_subcommand = f" for '{cmd.name}'" if cmd.parent is not None else ""
|
|
393
|
+
s = "" if n == 1 else "s"
|
|
394
|
+
self.error(
|
|
395
|
+
cmd,
|
|
396
|
+
f"error: too many arguments{for_subcommand}. Expected {n} argument{s} but got {len(args)}.",
|
|
397
|
+
"commander.excessArguments",
|
|
398
|
+
)
|
|
399
|
+
processed: List[Any] = []
|
|
400
|
+
for i, arg in enumerate(cmd.arguments):
|
|
401
|
+
if arg.variadic:
|
|
402
|
+
processed.append(list(args[i:]))
|
|
403
|
+
else:
|
|
404
|
+
processed.append(args[i] if i < len(args) else None)
|
|
405
|
+
return processed
|
|
406
|
+
|
|
407
|
+
def unknown_option(self, cmd: Command, flag: str) -> None:
|
|
408
|
+
suggestion = suggest_similar(flag, cmd.option_suggestions) if flag.startswith("--") else ""
|
|
409
|
+
self.error(cmd, f"error: unknown option '{flag}'{suggestion}", "commander.unknownOption")
|
|
410
|
+
|
|
411
|
+
def unknown_command(self, cmd: Command, name: str) -> None:
|
|
412
|
+
suggestion = suggest_similar(name, cmd.command_suggestions)
|
|
413
|
+
self.error(cmd, f"error: unknown command '{name}'{suggestion}", "commander.unknownCommand")
|
|
414
|
+
|
|
415
|
+
def opts_with_globals(self, cmd: Command) -> Dict[str, Any]:
|
|
416
|
+
combined: Dict[str, Any] = {}
|
|
417
|
+
at: Optional[Command] = cmd
|
|
418
|
+
while at is not None:
|
|
419
|
+
combined.update(self.values[id(at)])
|
|
420
|
+
at = at.parent
|
|
421
|
+
return combined
|
|
422
|
+
|
|
423
|
+
def run_action(self, cmd: Command, args: List[Any]) -> int:
|
|
424
|
+
from .extract import run_extract
|
|
425
|
+
|
|
426
|
+
action = cmd.action
|
|
427
|
+
assert action is not None
|
|
428
|
+
opts = self.values[id(cmd)]
|
|
429
|
+
if action.extract:
|
|
430
|
+
code, out, err = run_extract(self.p.extract, args, opts)
|
|
431
|
+
self.stdout.write(out)
|
|
432
|
+
self.stderr.write(err)
|
|
433
|
+
return code
|
|
434
|
+
assert action.command_id is not None
|
|
435
|
+
globals_ = self.opts_with_globals(cmd)
|
|
436
|
+
if action.introspect and _truthy(globals_, "introspect"):
|
|
437
|
+
result = introspect(action.command_id, self.p.policy.get(action.command_id), globals_)
|
|
438
|
+
self.stdout.write(stringify(result, 2) + "\n")
|
|
439
|
+
return 0
|
|
440
|
+
show_prompt = action.llm and _truthy(opts, "showPrompt")
|
|
441
|
+
outcome = self.p.dispatch(action.command_id, Invocation(args=args, opts=dict(opts), globals=globals_))
|
|
442
|
+
if show_prompt and outcome.prompt is not None:
|
|
443
|
+
self.stdout.write(outcome.prompt + "\n")
|
|
444
|
+
return outcome.exit_code
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
# ─── suggestions (lib/suggestSimilar.js) ─────────────────────────────
|
|
448
|
+
|
|
449
|
+
_MAX_DISTANCE = 3
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def _units(s: str) -> List[int]:
|
|
453
|
+
"""A string as JavaScript's UTF-16 code units."""
|
|
454
|
+
data = s.encode("utf-16-le", "surrogatepass")
|
|
455
|
+
return [data[i] | (data[i + 1] << 8) for i in range(0, len(data), 2)]
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
def _edit_distance(a: List[int], b: List[int]) -> int:
|
|
459
|
+
if abs(len(a) - len(b)) > _MAX_DISTANCE:
|
|
460
|
+
return max(len(a), len(b))
|
|
461
|
+
d = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
|
|
462
|
+
for i in range(len(a) + 1):
|
|
463
|
+
d[i][0] = i
|
|
464
|
+
for j in range(len(b) + 1):
|
|
465
|
+
d[0][j] = j
|
|
466
|
+
for j in range(1, len(b) + 1):
|
|
467
|
+
for i in range(1, len(a) + 1):
|
|
468
|
+
cost = 0 if a[i - 1] == b[j - 1] else 1
|
|
469
|
+
d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost)
|
|
470
|
+
if i > 1 and j > 1 and a[i - 1] == b[j - 2] and a[i - 2] == b[j - 1]:
|
|
471
|
+
d[i][j] = min(d[i][j], d[i - 2][j - 2] + 1)
|
|
472
|
+
return d[len(a)][len(b)]
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
def _collation_key(c: str) -> Tuple[int, bool]:
|
|
476
|
+
"""The order of a character in the root collation ``String.prototype.localeCompare``
|
|
477
|
+
uses, for the characters of option and command names: punctuation (``_``
|
|
478
|
+
before ``-``), then digits, then letters alphabetically without regard to
|
|
479
|
+
case; any other character by its code point after them."""
|
|
480
|
+
o = ord(c)
|
|
481
|
+
if c == "_":
|
|
482
|
+
return 1, False
|
|
483
|
+
if c == "-":
|
|
484
|
+
return 2, False
|
|
485
|
+
if "0" <= c <= "9":
|
|
486
|
+
return 200 + o - ord("0"), False
|
|
487
|
+
if "a" <= c <= "z":
|
|
488
|
+
return 300 + o - ord("a"), False
|
|
489
|
+
if "A" <= c <= "Z":
|
|
490
|
+
return 300 + o - ord("A"), True
|
|
491
|
+
if o < 0x80:
|
|
492
|
+
return 3 + o, False
|
|
493
|
+
return 1000 + o, False
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
def _locale_key(s: str) -> Tuple[List[int], List[bool]]:
|
|
497
|
+
keys = [_collation_key(c) for c in s]
|
|
498
|
+
return [k[0] for k in keys], [k[1] for k in keys]
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
def suggest_similar(word: str, candidates: List[str]) -> str:
|
|
502
|
+
if not candidates:
|
|
503
|
+
return ""
|
|
504
|
+
unique = list(dict.fromkeys(candidates))
|
|
505
|
+
searching_options = word.startswith("--")
|
|
506
|
+
if searching_options:
|
|
507
|
+
word = word[2:]
|
|
508
|
+
unique = [c[2:] for c in unique]
|
|
509
|
+
w = _units(word)
|
|
510
|
+
similar: List[str] = []
|
|
511
|
+
best_distance = _MAX_DISTANCE
|
|
512
|
+
min_similarity = 0.4
|
|
513
|
+
for candidate in unique:
|
|
514
|
+
c = _units(candidate)
|
|
515
|
+
if len(c) <= 1:
|
|
516
|
+
continue
|
|
517
|
+
distance = _edit_distance(w, c)
|
|
518
|
+
length = max(len(w), len(c))
|
|
519
|
+
similarity = (length - distance) / length
|
|
520
|
+
if similarity > min_similarity:
|
|
521
|
+
if distance < best_distance:
|
|
522
|
+
best_distance = distance
|
|
523
|
+
similar = [candidate]
|
|
524
|
+
elif distance == best_distance:
|
|
525
|
+
similar.append(candidate)
|
|
526
|
+
similar.sort(key=_locale_key)
|
|
527
|
+
if searching_options:
|
|
528
|
+
similar = ["--" + c for c in similar]
|
|
529
|
+
if len(similar) > 1:
|
|
530
|
+
return "\n(Did you mean one of " + ", ".join(similar) + "?)"
|
|
531
|
+
if len(similar) == 1:
|
|
532
|
+
return "\n(Did you mean " + similar[0] + "?)"
|
|
533
|
+
return ""
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
def outcome(result: Any) -> Outcome:
|
|
537
|
+
"""The outcome of what a handler returned: None (exit 0), an exit code, a
|
|
538
|
+
prompt (exit 0; written with ``--show-prompt``), or an exit code and a
|
|
539
|
+
prompt."""
|
|
540
|
+
if result is None:
|
|
541
|
+
return Outcome()
|
|
542
|
+
if isinstance(result, bool):
|
|
543
|
+
raise TypeError("a handler returns an exit code, not a bool")
|
|
544
|
+
if isinstance(result, int):
|
|
545
|
+
return Outcome(exit_code=result)
|
|
546
|
+
if isinstance(result, str):
|
|
547
|
+
return Outcome(prompt=result)
|
|
548
|
+
if isinstance(result, tuple) and len(result) == 2:
|
|
549
|
+
return Outcome(exit_code=result[0], prompt=result[1])
|
|
550
|
+
raise TypeError(f"a handler returns None, an exit code or a prompt, not {result!r}")
|
|
File without changes
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""``NotRequired`` for the TypedDicts of generated types. Python 3.11 has it
|
|
2
|
+
in ``typing``; before it, a key it marks is typed as required."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
try:
|
|
9
|
+
from typing import NotRequired # type: ignore[attr-defined]
|
|
10
|
+
except ImportError: # Python < 3.11
|
|
11
|
+
|
|
12
|
+
class _NotRequired:
|
|
13
|
+
def __getitem__(self, item: Any) -> Any:
|
|
14
|
+
return item
|
|
15
|
+
|
|
16
|
+
NotRequired = _NotRequired() # type: ignore[assignment]
|
|
17
|
+
|
|
18
|
+
__all__ = ["NotRequired"]
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cli-contracts-runtime
|
|
3
|
+
Version: 0.36.0
|
|
4
|
+
Summary: Python runtime for the programs and command wrappers cli-contracts generates from a CLI contract: commander-compatible argument parsing, help, policy derivation and the built-in extract command.
|
|
5
|
+
License: MIT
|
|
6
|
+
Project-URL: Homepage, https://github.com/foo-log-inc/cli-contracts
|
|
7
|
+
Project-URL: Repository, https://github.com/foo-log-inc/cli-contracts
|
|
8
|
+
Keywords: cli,contract,codegen,argument-parsing
|
|
9
|
+
Requires-Python: >=3.10
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
|
|
12
|
+
# cli-contracts-runtime
|
|
13
|
+
|
|
14
|
+
The runtime for the Python programs and command wrappers that [cli-contracts](https://github.com/foo-log-inc/cli-contracts) generates from a CLI contract (`templates: builtin:python`). A generated program holds its command tree and handler protocol; this package parses an invocation over the tree by the same rules as the TypeScript program generated from the same contract (which uses commander), and writes the same help, errors, `--introspect` policy and `extract` output.
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
pip install cli-contracts-runtime
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Python 3.10 or later. The package uses the standard library only.
|
|
21
|
+
|
|
22
|
+
## Usage
|
|
23
|
+
|
|
24
|
+
Generate the package (`cli-contracts.config.yaml`):
|
|
25
|
+
|
|
26
|
+
```yaml
|
|
27
|
+
generators:
|
|
28
|
+
python:
|
|
29
|
+
enabled: true
|
|
30
|
+
output: ./tool/cli
|
|
31
|
+
templates: builtin:python
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Implement the handlers and run the program:
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
import sys
|
|
38
|
+
|
|
39
|
+
import cli_contracts_runtime
|
|
40
|
+
|
|
41
|
+
from tool import cli
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class Handlers:
|
|
45
|
+
# One method per command of the contract; it returns the exit code (None for 0).
|
|
46
|
+
def users_import(self, file, options, parent_opts):
|
|
47
|
+
if options.get("dryRun"):
|
|
48
|
+
print("dry run:", file)
|
|
49
|
+
return 0
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def on_usage_error(err, command):
|
|
53
|
+
# Optional: for an invocation the program rejects, writes what the contract declares for invalid arguments and returns the exit code.
|
|
54
|
+
sys.stderr.write('{"code":"INVALID_ARGS","message":%s}\n' % cli_contracts_runtime.quote(err.message))
|
|
55
|
+
return 2
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
if __name__ == "__main__":
|
|
59
|
+
cli.create_program(Handlers(), "1.0.0", on_usage_error).main()
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
The options a handler receives are a dict of the options given or defaulted, keyed as the program keys them (`dry-run` → `dryRun`); `parent_opts` holds those of the command and its ancestors. A command that takes `--adapter` may return the prompt it built, or `(exit_code, prompt)`; the program writes the prompt with `--show-prompt`.
|
|
63
|
+
|
|
64
|
+
`create_program` returns a `cli_contracts_runtime.Program`; its `run(argv, stdout, stderr)` runs an invocation (`argv` without the program name) without exiting and returns its exit code.
|
|
65
|
+
|
|
66
|
+
## License
|
|
67
|
+
|
|
68
|
+
MIT
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
cli_contracts_runtime/__init__.py,sha256=uymqlcGkC21apyKAKuPde6f2Iau4uALfPY_adGmRLBg,1187
|
|
2
|
+
cli_contracts_runtime/client.py,sha256=wpDVB2ed6kMRwb7Ix2Wrua9XfvVQVEEDN62KX4kI770,2841
|
|
3
|
+
cli_contracts_runtime/extract.py,sha256=D2rqApg09jo6PSzx1-NU_WX1R3EDP_BC9rt4OOw50AI,3195
|
|
4
|
+
cli_contracts_runtime/jsonvalue.py,sha256=RXOW5LTY-LSH59AIhlmMLIKzBAlxY-_IXB0EO0_MKnU,2946
|
|
5
|
+
cli_contracts_runtime/policy.py,sha256=Om3yLGX_Q3nRFvmECuHdSMxKeC_s35Lbvxy4IXf3vz0,8514
|
|
6
|
+
cli_contracts_runtime/program.py,sha256=e7DlZlQnY1amVNSo5C284kAlma8sx2DEAwHTPXI6yyQ,20260
|
|
7
|
+
cli_contracts_runtime/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
+
cli_contracts_runtime/typing_compat.py,sha256=RWmIq_4xOhZhV7mhoi-PEoKKMBJt6PHTJT4bYPAo4rs,498
|
|
9
|
+
cli_contracts_runtime-0.36.0.dist-info/METADATA,sha256=cXt7vmfUMAcbZX1VZEpjM8-I4yweSRXiNE8UpLdIvNc,2621
|
|
10
|
+
cli_contracts_runtime-0.36.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
11
|
+
cli_contracts_runtime-0.36.0.dist-info/top_level.txt,sha256=hh0SsxYiaGNwhx8iCem7slHn71PGaD1jATMzvsoeedc,22
|
|
12
|
+
cli_contracts_runtime-0.36.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
cli_contracts_runtime
|