simple-module-remote 0.0.50__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.
- simple_module_remote/__init__.py +12 -0
- simple_module_remote/commands/__init__.py +1 -0
- simple_module_remote/commands/api_cmd.py +157 -0
- simple_module_remote/commands/auth_cmd.py +166 -0
- simple_module_remote/commands/doctor_cmd.py +157 -0
- simple_module_remote/commands/env_cmd.py +198 -0
- simple_module_remote/commands/generated.py +50 -0
- simple_module_remote/commands/root.py +186 -0
- simple_module_remote/commands/runtime.py +263 -0
- simple_module_remote/commands/schema_cmd.py +155 -0
- simple_module_remote/commands/schema_fetch.py +129 -0
- simple_module_remote/commands/schema_source.py +181 -0
- simple_module_remote/config/__init__.py +1 -0
- simple_module_remote/config/_file_store.py +182 -0
- simple_module_remote/config/_private_dir.py +191 -0
- simple_module_remote/config/credentials.py +296 -0
- simple_module_remote/config/environments.py +186 -0
- simple_module_remote/config/paths.py +32 -0
- simple_module_remote/config/resolve.py +96 -0
- simple_module_remote/curated/__init__.py +1 -0
- simple_module_remote/generate/__init__.py +1 -0
- simple_module_remote/generate/body.py +198 -0
- simple_module_remote/generate/confirm.py +38 -0
- simple_module_remote/generate/context.py +38 -0
- simple_module_remote/generate/emit.py +278 -0
- simple_module_remote/generate/execute.py +220 -0
- simple_module_remote/generate/naming.py +69 -0
- simple_module_remote/generate/operations.py +181 -0
- simple_module_remote/generate/pagination.py +80 -0
- simple_module_remote/generate/pairs.py +22 -0
- simple_module_remote/generate/params.py +210 -0
- simple_module_remote/generate/prepare.py +134 -0
- simple_module_remote/generate/tree.py +59 -0
- simple_module_remote/generate/trust.py +42 -0
- simple_module_remote/generate/validate.py +136 -0
- simple_module_remote/http/__init__.py +1 -0
- simple_module_remote/http/client.py +292 -0
- simple_module_remote/http/errors.py +59 -0
- simple_module_remote/http/safety.py +124 -0
- simple_module_remote/output/__init__.py +1 -0
- simple_module_remote/output/reasons.py +17 -0
- simple_module_remote/output/render.py +149 -0
- simple_module_remote/output/sanitize.py +32 -0
- simple_module_remote/py.typed +0 -0
- simple_module_remote/schema/__init__.py +1 -0
- simple_module_remote/schema/cache.py +187 -0
- simple_module_remote/schema/loader.py +56 -0
- simple_module_remote-0.0.50.dist-info/METADATA +73 -0
- simple_module_remote-0.0.50.dist-info/RECORD +51 -0
- simple_module_remote-0.0.50.dist-info/WHEEL +4 -0
- simple_module_remote-0.0.50.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
"""Click parameters for an :class:`Operation`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
import click
|
|
8
|
+
from click.core import ParameterSource
|
|
9
|
+
|
|
10
|
+
from simple_module_remote.generate.naming import kebab_name, snake_name
|
|
11
|
+
from simple_module_remote.generate.operations import Operation, Param, is_json_media
|
|
12
|
+
from simple_module_remote.output.render import OUTPUT_FORMATS
|
|
13
|
+
from simple_module_remote.output.sanitize import sanitize
|
|
14
|
+
from simple_module_remote.schema.loader import resolve_ref
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"PATH_VAR",
|
|
18
|
+
"RESERVED_OPTIONS",
|
|
19
|
+
"click_params_for",
|
|
20
|
+
"json_response_schema",
|
|
21
|
+
"param_map",
|
|
22
|
+
"returns_list",
|
|
23
|
+
"success_is_json",
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
RESERVED_OPTIONS: frozenset[str] = frozenset(
|
|
27
|
+
{
|
|
28
|
+
"output", "columns", "q", "out", "yes", "dry-run", "all", "limit", "json",
|
|
29
|
+
"file", "set", "set-json", "upload", "body-file", "content-type", "help",
|
|
30
|
+
}
|
|
31
|
+
) # fmt: skip
|
|
32
|
+
|
|
33
|
+
PATH_VAR = re.compile(r"\{([^}]+)\}") # one ``{param}`` placeholder (name captured)
|
|
34
|
+
_SCALARS: dict[str, click.ParamType] = {
|
|
35
|
+
"integer": click.INT,
|
|
36
|
+
"number": click.FLOAT,
|
|
37
|
+
"boolean": click.BOOL,
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _flag_only(ctx: click.Context, param: click.Parameter, value: bool) -> bool:
|
|
42
|
+
"""``--yes`` counts only when typed on the command line, never from the environment."""
|
|
43
|
+
source = ctx.get_parameter_source(param.name or "")
|
|
44
|
+
return bool(value) and source == ParameterSource.COMMANDLINE
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _slug(param: Param) -> str:
|
|
48
|
+
return snake_name(param.name) or "param"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _dest(param: Param) -> str:
|
|
52
|
+
prefix = "p" if param.location == "path" else "q"
|
|
53
|
+
return f"{prefix}_{_slug(param)}"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _ordered(op: Operation) -> list[Param]:
|
|
57
|
+
order = {name: i for i, name in enumerate(PATH_VAR.findall(op.path))}
|
|
58
|
+
paths = sorted(
|
|
59
|
+
(p for p in op.params if p.location == "path"), key=lambda p: order.get(p.name, 99)
|
|
60
|
+
)
|
|
61
|
+
return [*paths, *(p for p in op.params if p.location == "query")]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def param_map(op: Operation) -> dict[str, Param]:
|
|
65
|
+
"""Click dest name -> original OpenAPI parameter, for mapping values back."""
|
|
66
|
+
mapping: dict[str, Param] = {}
|
|
67
|
+
for param in _ordered(op):
|
|
68
|
+
dest = _dest(param)
|
|
69
|
+
while dest in mapping:
|
|
70
|
+
dest += "_2"
|
|
71
|
+
mapping[dest] = param
|
|
72
|
+
return mapping
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _value_type(schema: dict) -> click.ParamType:
|
|
76
|
+
enum = schema.get("enum")
|
|
77
|
+
choices = [str(e) for e in enum] if isinstance(enum, list) else []
|
|
78
|
+
# Choices are printed in help and errors: only single-line printable text is offered.
|
|
79
|
+
if choices and all(c.isprintable() and sanitize(c) == c for c in choices):
|
|
80
|
+
return click.Choice(choices)
|
|
81
|
+
kind = schema.get("type")
|
|
82
|
+
return _SCALARS.get(kind, click.STRING) if isinstance(kind, str) else click.STRING
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _param_option(dest: str, param: Param) -> click.Parameter:
|
|
86
|
+
kebab = kebab_name(param.name) or "param"
|
|
87
|
+
flag = f"--param-{kebab}" if kebab in RESERVED_OPTIONS else f"--{kebab}"
|
|
88
|
+
schema = param.schema
|
|
89
|
+
multiple = schema.get("type") == "array"
|
|
90
|
+
item = schema.get("items") if multiple else schema
|
|
91
|
+
return click.Option(
|
|
92
|
+
[flag, dest],
|
|
93
|
+
type=_value_type(item if isinstance(item, dict) else {}),
|
|
94
|
+
multiple=multiple,
|
|
95
|
+
required=param.required,
|
|
96
|
+
help=param.description or None,
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _body_options(op: Operation) -> list[click.Parameter]:
|
|
101
|
+
if op.body_kind == "json":
|
|
102
|
+
return [
|
|
103
|
+
click.Option(["--json", "json_arg"], help="Request body as a JSON string."),
|
|
104
|
+
click.Option(
|
|
105
|
+
["--file", "file_arg"], help="Read the JSON body from a file ('-' = stdin)."
|
|
106
|
+
),
|
|
107
|
+
click.Option(["--set", "sets"], multiple=True, help="Set a field: key=value (dotted)."),
|
|
108
|
+
click.Option(
|
|
109
|
+
["--set-json", "set_jsons"], multiple=True, help="Set a field: key=<json>."
|
|
110
|
+
),
|
|
111
|
+
]
|
|
112
|
+
if op.body_kind == "multipart":
|
|
113
|
+
return [
|
|
114
|
+
click.Option(
|
|
115
|
+
["--upload", "uploads"],
|
|
116
|
+
multiple=True,
|
|
117
|
+
help="Upload a file: field=path (or field=@path).",
|
|
118
|
+
),
|
|
119
|
+
click.Option(["--set", "sets"], multiple=True, help="Form field: key=value."),
|
|
120
|
+
]
|
|
121
|
+
if op.body_kind == "raw":
|
|
122
|
+
return [
|
|
123
|
+
click.Option(["--body-file", "body_file"], help="File to send as the body."),
|
|
124
|
+
click.Option(["--content-type", "content_type"], help="Content-Type of the body."),
|
|
125
|
+
]
|
|
126
|
+
return []
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _success_response(op: Operation, root: dict) -> dict:
|
|
130
|
+
"""The resolved success response object (200, else first 2xx); ``{}`` when absent."""
|
|
131
|
+
node = ((root.get("paths") or {}).get(op.path) or {}).get(op.method.lower()) or {}
|
|
132
|
+
responses = node.get("responses") or {}
|
|
133
|
+
code = "200" if "200" in responses else next((c for c in responses if str(c)[:1] == "2"), None)
|
|
134
|
+
return resolve_ref(root, responses.get(code) or {}) if code else {}
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def json_response_schema(op: Operation, root: dict) -> dict | None:
|
|
138
|
+
"""The resolved JSON schema of the operation's success response."""
|
|
139
|
+
content = _success_response(op, root).get("content") or {}
|
|
140
|
+
media = next((v for k, v in content.items() if is_json_media(str(k))), None)
|
|
141
|
+
if not isinstance(media, dict) or not isinstance(media.get("schema"), dict):
|
|
142
|
+
return None
|
|
143
|
+
return resolve_ref(root, media["schema"])
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def success_is_json(op: Operation, root: dict) -> bool:
|
|
147
|
+
"""False when the success response declares content but none of it is JSON."""
|
|
148
|
+
content = _success_response(op, root).get("content")
|
|
149
|
+
if not isinstance(content, dict) or not content:
|
|
150
|
+
return True
|
|
151
|
+
return any(is_json_media(str(k)) for k in content)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def returns_list(op: Operation, root: dict) -> bool:
|
|
155
|
+
"""True for a GET whose 200 response is an array or an object with an ``items`` array."""
|
|
156
|
+
if op.method != "GET":
|
|
157
|
+
return False
|
|
158
|
+
schema = json_response_schema(op, root) or {}
|
|
159
|
+
if schema.get("type") == "array":
|
|
160
|
+
return True
|
|
161
|
+
items = resolve_ref(root, (schema.get("properties") or {}).get("items") or {})
|
|
162
|
+
return items.get("type") == "array"
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def click_params_for(op: Operation, *, list_returning: bool = False) -> list[click.Parameter]:
|
|
166
|
+
"""Arguments and options for ``op``; pass ``list_returning=returns_list(op, root)``."""
|
|
167
|
+
params: list[click.Parameter] = []
|
|
168
|
+
mapping = param_map(op)
|
|
169
|
+
for dest, param in mapping.items():
|
|
170
|
+
if param.location == "path":
|
|
171
|
+
kebab = _slug(param).upper()
|
|
172
|
+
params.append(
|
|
173
|
+
click.Argument([dest], type=_value_type(param.schema), metavar=kebab, required=True)
|
|
174
|
+
)
|
|
175
|
+
params.extend(_param_option(d, p) for d, p in mapping.items() if p.location == "query")
|
|
176
|
+
params.extend(_body_options(op))
|
|
177
|
+
params.extend(
|
|
178
|
+
[
|
|
179
|
+
click.Option(
|
|
180
|
+
["--dry-run", "dry_run"], is_flag=True, help="Print the request, send nothing."
|
|
181
|
+
),
|
|
182
|
+
click.Option(
|
|
183
|
+
["-o", "--output", "output"],
|
|
184
|
+
type=click.Choice(OUTPUT_FORMATS),
|
|
185
|
+
help="Output format.",
|
|
186
|
+
),
|
|
187
|
+
click.Option(["--columns", "columns"], help="Comma-separated columns to show."),
|
|
188
|
+
click.Option(["-q", "quiet"], is_flag=True, help="Print only identifiers."),
|
|
189
|
+
click.Option(["--out", "out"], help="Write the response body to a file."),
|
|
190
|
+
click.Option(
|
|
191
|
+
["--yes", "yes"],
|
|
192
|
+
is_flag=True,
|
|
193
|
+
allow_from_autoenv=False,
|
|
194
|
+
callback=_flag_only,
|
|
195
|
+
help="Skip the confirmation prompt.",
|
|
196
|
+
),
|
|
197
|
+
]
|
|
198
|
+
)
|
|
199
|
+
if list_returning:
|
|
200
|
+
params.extend(
|
|
201
|
+
[
|
|
202
|
+
click.Option(["--all", "all_pages"], is_flag=True, help="Fetch every page."),
|
|
203
|
+
click.Option(
|
|
204
|
+
["--limit", "limit"],
|
|
205
|
+
type=click.IntRange(min=1),
|
|
206
|
+
help="Maximum rows (implies --all).",
|
|
207
|
+
),
|
|
208
|
+
]
|
|
209
|
+
)
|
|
210
|
+
return params
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""Turn click values into the pieces of one HTTP request."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from contextlib import ExitStack
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any, TextIO
|
|
9
|
+
from urllib.parse import quote
|
|
10
|
+
|
|
11
|
+
import click
|
|
12
|
+
|
|
13
|
+
from simple_module_remote.generate.body import BodyError, build_json_body, missing_required
|
|
14
|
+
from simple_module_remote.generate.operations import Operation
|
|
15
|
+
from simple_module_remote.generate.pairs import split_pairs
|
|
16
|
+
from simple_module_remote.generate.params import param_map
|
|
17
|
+
from simple_module_remote.http.safety import validate_api_path
|
|
18
|
+
from simple_module_remote.output.reasons import os_reason
|
|
19
|
+
from simple_module_remote.output.sanitize import sanitize
|
|
20
|
+
from simple_module_remote.schema.loader import resolve_ref
|
|
21
|
+
|
|
22
|
+
__all__ = ["Prepared", "field_list", "prepare_request"]
|
|
23
|
+
|
|
24
|
+
DEFAULT_CONTENT_TYPE = "application/octet-stream"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class Prepared:
|
|
29
|
+
path: str
|
|
30
|
+
params: dict[str, Any]
|
|
31
|
+
json: Any = None
|
|
32
|
+
files: list[tuple[str, tuple[str, Any]]] | None = None
|
|
33
|
+
data: dict[str, str] | None = None
|
|
34
|
+
content: bytes | None = None
|
|
35
|
+
headers: dict[str, str] = field(default_factory=dict)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def field_list(names: list[str]) -> str:
|
|
39
|
+
"""Server-supplied field names for an error line: plain when printable, else escaped."""
|
|
40
|
+
return ", ".join(n if n.isprintable() and sanitize(n) == n else ascii(n) for n in names)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _query_value(value: Any) -> Any:
|
|
44
|
+
if isinstance(value, bool):
|
|
45
|
+
return "true" if value else "false"
|
|
46
|
+
if isinstance(value, tuple | list):
|
|
47
|
+
return [_query_value(v) for v in value]
|
|
48
|
+
return value
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _empty_body(op: Operation, root: dict) -> dict:
|
|
52
|
+
"""``{}`` for a required body whose fields are all optional; an error for any other shape."""
|
|
53
|
+
schema = resolve_ref(root, op.body_schema) if op.body_schema else {}
|
|
54
|
+
kind = schema.get("type")
|
|
55
|
+
if kind == "object" or not schema or (kind is None and "properties" in schema):
|
|
56
|
+
return {}
|
|
57
|
+
raise click.UsageError("this command needs a request body: use --json, --file or --set")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _json_body(op: Operation, values: dict[str, Any], root: dict, stdin: TextIO) -> Any:
|
|
61
|
+
try:
|
|
62
|
+
body = build_json_body(
|
|
63
|
+
json_arg=values.get("json_arg"),
|
|
64
|
+
file_arg=values.get("file_arg"),
|
|
65
|
+
sets=values.get("sets") or (),
|
|
66
|
+
set_jsons=values.get("set_jsons") or (),
|
|
67
|
+
body_schema=op.body_schema,
|
|
68
|
+
root=root,
|
|
69
|
+
stdin=stdin,
|
|
70
|
+
)
|
|
71
|
+
except BodyError as exc:
|
|
72
|
+
raise click.UsageError(str(exc)) from None
|
|
73
|
+
missing = missing_required(body if isinstance(body, dict) else {}, op.body_schema, root)
|
|
74
|
+
if missing and (body is None or isinstance(body, dict)):
|
|
75
|
+
raise click.UsageError(f"missing required body fields: {field_list(missing)}")
|
|
76
|
+
if body is None and op.body_required:
|
|
77
|
+
return _empty_body(op, root)
|
|
78
|
+
return body
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _multipart(
|
|
82
|
+
op: Operation, values: dict[str, Any], root: dict, stack: ExitStack, prep: Prepared
|
|
83
|
+
) -> None:
|
|
84
|
+
files = []
|
|
85
|
+
for field_name, raw in split_pairs(values.get("uploads"), "--upload"):
|
|
86
|
+
path = raw[1:] if raw.startswith("@") else raw
|
|
87
|
+
try:
|
|
88
|
+
handle = stack.enter_context(Path(path).open("rb")) # noqa: SIM115
|
|
89
|
+
except OSError as exc:
|
|
90
|
+
raise click.UsageError(
|
|
91
|
+
f"--upload {field_name}: cannot read {path}: {os_reason(exc)}"
|
|
92
|
+
) from None
|
|
93
|
+
files.append((field_name, (Path(path).name, handle)))
|
|
94
|
+
prep.files = files or None
|
|
95
|
+
prep.data = dict(split_pairs(values.get("sets"), "--set")) or None
|
|
96
|
+
given = {name for name, _ in files} | set(prep.data or {})
|
|
97
|
+
missing = missing_required(dict.fromkeys(given), op.body_schema, root)
|
|
98
|
+
if missing:
|
|
99
|
+
raise click.UsageError(
|
|
100
|
+
f"missing required form fields: {field_list(missing)} (use --upload field=path "
|
|
101
|
+
"or --set field=value)"
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def prepare_request(
|
|
106
|
+
op: Operation, values: dict[str, Any], root: dict, stdin: TextIO, stack: ExitStack
|
|
107
|
+
) -> Prepared:
|
|
108
|
+
"""Build the request; files opened for upload are registered on ``stack``."""
|
|
109
|
+
path, query = op.path, {}
|
|
110
|
+
for dest, param in param_map(op).items():
|
|
111
|
+
value = values.get(dest)
|
|
112
|
+
if param.location == "path":
|
|
113
|
+
if not str(value).strip():
|
|
114
|
+
raise click.UsageError(f"path parameter {param.name!r} must not be empty")
|
|
115
|
+
path = path.replace("{" + param.name + "}", quote(str(value), safe=""))
|
|
116
|
+
elif value is not None and value != ():
|
|
117
|
+
query[param.name] = _query_value(value)
|
|
118
|
+
prep = Prepared(path=path, params=query)
|
|
119
|
+
if op.body_kind == "json":
|
|
120
|
+
prep.json = _json_body(op, values, root, stdin)
|
|
121
|
+
elif op.body_kind == "multipart":
|
|
122
|
+
_multipart(op, values, root, stack, prep)
|
|
123
|
+
elif op.body_kind == "raw" and values.get("body_file"):
|
|
124
|
+
try:
|
|
125
|
+
prep.content = Path(values["body_file"]).read_bytes()
|
|
126
|
+
except OSError as exc:
|
|
127
|
+
raise click.UsageError(
|
|
128
|
+
f"--body-file: cannot read {values['body_file']}: {os_reason(exc)}"
|
|
129
|
+
) from None
|
|
130
|
+
prep.headers["Content-Type"] = values.get("content_type") or DEFAULT_CONTENT_TYPE
|
|
131
|
+
elif op.body_kind == "raw" and op.body_required:
|
|
132
|
+
raise click.UsageError("this command needs a request body: pass --body-file FILE")
|
|
133
|
+
validate_api_path(prep.path)
|
|
134
|
+
return prep
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""Build the click command tree from the OpenAPI operations."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
|
|
7
|
+
import click
|
|
8
|
+
|
|
9
|
+
from simple_module_remote.generate.naming import group_name
|
|
10
|
+
from simple_module_remote.generate.operations import (
|
|
11
|
+
Operation,
|
|
12
|
+
cli_operations,
|
|
13
|
+
find_collisions,
|
|
14
|
+
parse_operations,
|
|
15
|
+
)
|
|
16
|
+
from simple_module_remote.output.sanitize import sanitize
|
|
17
|
+
|
|
18
|
+
__all__ = ["TreeError", "build_groups", "session_only_operations"]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class TreeError(Exception):
|
|
22
|
+
"""The schema yields commands that cannot be told apart."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def session_only_operations(schema: dict) -> list[Operation]:
|
|
26
|
+
"""Operations a personal access token cannot call."""
|
|
27
|
+
return sorted(
|
|
28
|
+
(op for op in parse_operations(schema) if not op.token_capable),
|
|
29
|
+
key=lambda op: (op.path, op.method),
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def build_groups(
|
|
34
|
+
schema: dict, factory: Callable[[Operation, dict], click.Command]
|
|
35
|
+
) -> list[click.Group]:
|
|
36
|
+
"""One group per tag; raises :class:`TreeError` when names collide."""
|
|
37
|
+
ops = cli_operations(parse_operations(schema))
|
|
38
|
+
collisions = find_collisions(ops)
|
|
39
|
+
if collisions:
|
|
40
|
+
detail = "; ".join(
|
|
41
|
+
f"{group} {name}".strip() + f" ({', '.join(ids)})" for group, name, ids in collisions
|
|
42
|
+
)
|
|
43
|
+
raise TreeError(sanitize(f"command name collisions in the schema: {detail}"))
|
|
44
|
+
described = {
|
|
45
|
+
group_name(t["name"]): str(t["description"])
|
|
46
|
+
for t in schema.get("tags") or []
|
|
47
|
+
if isinstance(t, dict) and isinstance(t.get("name"), str) and t.get("description")
|
|
48
|
+
}
|
|
49
|
+
groups: dict[str, click.Group] = {}
|
|
50
|
+
for op in ops:
|
|
51
|
+
group = groups.setdefault(
|
|
52
|
+
op.group,
|
|
53
|
+
click.Group(
|
|
54
|
+
op.group,
|
|
55
|
+
help=sanitize(described.get(op.group, f"Commands for the {op.group} API.")),
|
|
56
|
+
),
|
|
57
|
+
)
|
|
58
|
+
group.add_command(factory(op, schema))
|
|
59
|
+
return [groups[name] for name in sorted(groups)]
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Which schema may relax a safety hint.
|
|
2
|
+
|
|
3
|
+
A live schema comes from the server, so it may only make the CLI more careful: its
|
|
4
|
+
``x-cli-confirm`` adds a confirmation, but only the bundled schema's ``x-cli-safe`` for
|
|
5
|
+
the same method and path template can waive the confirmation of a mutation on a
|
|
6
|
+
protected environment. Templates are compared with placeholder names erased
|
|
7
|
+
(``/a/{x}`` is ``/a/{id}``), so a renamed placeholder neither gains nor loses a hint.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import re
|
|
13
|
+
from dataclasses import replace
|
|
14
|
+
|
|
15
|
+
from simple_module_remote.generate.operations import Operation, parse_operations
|
|
16
|
+
|
|
17
|
+
__all__ = ["HintIndex", "hint_index", "route_key", "trusted_hints"]
|
|
18
|
+
|
|
19
|
+
_PLACEHOLDER = re.compile(r"\{[^}]*\}")
|
|
20
|
+
HintIndex = dict[tuple[str, str], list[Operation]]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def route_key(method: str, path: str) -> tuple[str, str]:
|
|
24
|
+
"""A route's identity: method plus the template with placeholder names erased."""
|
|
25
|
+
return method.upper(), _PLACEHOLDER.sub("{}", path)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def hint_index(bundled: dict) -> HintIndex:
|
|
29
|
+
index: HintIndex = {}
|
|
30
|
+
for op in parse_operations(bundled):
|
|
31
|
+
index.setdefault(route_key(op.method, op.path), []).append(op)
|
|
32
|
+
return index
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def trusted_hints(op: Operation, index: HintIndex) -> Operation:
|
|
36
|
+
"""``op`` with ``safe`` from its bundled twin(s) and ``confirm`` from either side."""
|
|
37
|
+
twins = index.get(route_key(op.method, op.path), [])
|
|
38
|
+
return replace(
|
|
39
|
+
op,
|
|
40
|
+
safe=bool(twins) and all(t.safe for t in twins),
|
|
41
|
+
confirm=op.confirm or any(t.confirm for t in twins),
|
|
42
|
+
)
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""Shape checks for the parts of a schema that commands consume when they run.
|
|
2
|
+
|
|
3
|
+
Building the command tree reads only part of the document; bodies, parameters and
|
|
4
|
+
responses are read again at invocation (``body.py``, ``params.py``, ``prepare.py``).
|
|
5
|
+
A live schema is server-supplied, so these structures are checked up front: a
|
|
6
|
+
document with a non-object ``properties``, a non-list ``required``/``enum``, a
|
|
7
|
+
non-object parameter schema and the like is refused rather than crashing later.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from simple_module_remote.generate.operations import METHODS
|
|
13
|
+
from simple_module_remote.schema.loader import resolve_ref
|
|
14
|
+
|
|
15
|
+
__all__ = ["schema_problems"]
|
|
16
|
+
|
|
17
|
+
MAX_PROBLEMS = 5
|
|
18
|
+
_SCHEMA_LISTS = ("anyOf", "oneOf", "allOf")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _check_schema_node(node: dict, where: str, problems: list[str], stack: list) -> None:
|
|
22
|
+
props = node.get("properties")
|
|
23
|
+
if props is not None:
|
|
24
|
+
if not isinstance(props, dict) or not all(isinstance(v, dict) for v in props.values()):
|
|
25
|
+
problems.append(f"{where}: 'properties' is not an object of schemas")
|
|
26
|
+
else:
|
|
27
|
+
stack.extend((v, f"{where}.properties") for v in props.values())
|
|
28
|
+
required = node.get("required")
|
|
29
|
+
if required is not None and not (
|
|
30
|
+
isinstance(required, list) and all(isinstance(r, str) for r in required)
|
|
31
|
+
):
|
|
32
|
+
problems.append(f"{where}: 'required' is not a list of names")
|
|
33
|
+
if "enum" in node and not isinstance(node["enum"], list):
|
|
34
|
+
problems.append(f"{where}: 'enum' is not a list")
|
|
35
|
+
kind = node.get("type")
|
|
36
|
+
if kind is not None and not (
|
|
37
|
+
isinstance(kind, str) or (isinstance(kind, list) and all(isinstance(k, str) for k in kind))
|
|
38
|
+
):
|
|
39
|
+
problems.append(f"{where}: 'type' is not a name or list of names")
|
|
40
|
+
for key in ("items", "additionalProperties"):
|
|
41
|
+
child = node.get(key)
|
|
42
|
+
if key == "items" and child is not None and not isinstance(child, dict):
|
|
43
|
+
problems.append(f"{where}: 'items' is not a schema")
|
|
44
|
+
elif isinstance(child, dict):
|
|
45
|
+
stack.append((child, f"{where}.{key}"))
|
|
46
|
+
for key in _SCHEMA_LISTS:
|
|
47
|
+
branches = node.get(key)
|
|
48
|
+
if branches is None:
|
|
49
|
+
continue
|
|
50
|
+
if not isinstance(branches, list) or not all(isinstance(b, dict) for b in branches):
|
|
51
|
+
problems.append(f"{where}: '{key}' is not a list of schemas")
|
|
52
|
+
else:
|
|
53
|
+
stack.extend((b, f"{where}.{key}") for b in branches)
|
|
54
|
+
ref = node.get("$ref")
|
|
55
|
+
if ref is not None and not isinstance(ref, str):
|
|
56
|
+
problems.append(f"{where}: '$ref' is not text")
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _walk_schemas(root: dict, start: list[tuple[object, str]], problems: list[str]) -> None:
|
|
60
|
+
stack = list(start)
|
|
61
|
+
seen: set[int] = set()
|
|
62
|
+
while stack and len(problems) < MAX_PROBLEMS:
|
|
63
|
+
node, where = stack.pop()
|
|
64
|
+
if not isinstance(node, dict):
|
|
65
|
+
problems.append(f"{where}: schema is not an object")
|
|
66
|
+
continue
|
|
67
|
+
if id(node) in seen:
|
|
68
|
+
continue
|
|
69
|
+
seen.add(id(node))
|
|
70
|
+
_check_schema_node(node, where, problems, stack)
|
|
71
|
+
if isinstance(node.get("$ref"), str):
|
|
72
|
+
stack.append((resolve_ref(root, node), where))
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _content_schemas(container: object, where: str, problems: list[str], out: list) -> None:
|
|
76
|
+
if container is None:
|
|
77
|
+
return
|
|
78
|
+
if not isinstance(container, dict):
|
|
79
|
+
problems.append(f"{where}: not an object")
|
|
80
|
+
return
|
|
81
|
+
content = container.get("content")
|
|
82
|
+
if content is None:
|
|
83
|
+
return
|
|
84
|
+
if not isinstance(content, dict):
|
|
85
|
+
problems.append(f"{where}: 'content' is not an object")
|
|
86
|
+
return
|
|
87
|
+
for media in content.values():
|
|
88
|
+
if not isinstance(media, dict):
|
|
89
|
+
problems.append(f"{where}: a media type is not an object")
|
|
90
|
+
elif "schema" in media:
|
|
91
|
+
out.append((media["schema"], f"{where} body"))
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _params(root: dict, raw: object, where: str, problems: list[str], out: list) -> None:
|
|
95
|
+
if raw is None:
|
|
96
|
+
return
|
|
97
|
+
if not isinstance(raw, list):
|
|
98
|
+
problems.append(f"{where}: 'parameters' is not a list")
|
|
99
|
+
return
|
|
100
|
+
for item in raw:
|
|
101
|
+
param = resolve_ref(root, item) if isinstance(item, dict) else None
|
|
102
|
+
if not param or not isinstance(param.get("name"), str):
|
|
103
|
+
problems.append(f"{where}: a parameter is not an object with a name")
|
|
104
|
+
elif "schema" in param:
|
|
105
|
+
out.append((param["schema"], f"{where} parameter"))
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def schema_problems(root: dict) -> list[str]:
|
|
109
|
+
"""Up to :data:`MAX_PROBLEMS` descriptions of unusable structures (empty when fine)."""
|
|
110
|
+
problems: list[str] = []
|
|
111
|
+
schemas: list[tuple[object, str]] = []
|
|
112
|
+
for path, item in (root.get("paths") or {}).items():
|
|
113
|
+
if not isinstance(item, dict):
|
|
114
|
+
continue
|
|
115
|
+
_params(root, item.get("parameters"), str(path), problems, schemas)
|
|
116
|
+
for method in METHODS:
|
|
117
|
+
op = item.get(method)
|
|
118
|
+
if not isinstance(op, dict):
|
|
119
|
+
continue
|
|
120
|
+
where = f"{method.upper()} {path}"
|
|
121
|
+
_params(root, op.get("parameters"), where, problems, schemas)
|
|
122
|
+
body = op.get("requestBody")
|
|
123
|
+
_content_schemas(
|
|
124
|
+
resolve_ref(root, body) if isinstance(body, dict) else body,
|
|
125
|
+
where,
|
|
126
|
+
problems,
|
|
127
|
+
schemas,
|
|
128
|
+
)
|
|
129
|
+
responses = op.get("responses")
|
|
130
|
+
if responses is not None and not isinstance(responses, dict):
|
|
131
|
+
problems.append(f"{where}: 'responses' is not an object")
|
|
132
|
+
for response in (responses or {}).values() if isinstance(responses, dict) else ():
|
|
133
|
+
resolved = resolve_ref(root, response) if isinstance(response, dict) else response
|
|
134
|
+
_content_schemas(resolved, f"{where} response", problems, schemas)
|
|
135
|
+
_walk_schemas(root, schemas, problems)
|
|
136
|
+
return problems[:MAX_PROBLEMS]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""http area of the remote CLI engine."""
|