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,198 @@
|
|
|
1
|
+
"""Build a JSON request body from ``--json/--file/--set/--set-json`` input."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
from collections.abc import Sequence
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import TextIO
|
|
10
|
+
|
|
11
|
+
from simple_module_remote.generate.pairs import split_pair
|
|
12
|
+
from simple_module_remote.output.reasons import os_reason
|
|
13
|
+
from simple_module_remote.schema.loader import resolve_ref, unwrap_nullable
|
|
14
|
+
|
|
15
|
+
__all__ = ["BodyError", "build_json_body", "missing_required"]
|
|
16
|
+
|
|
17
|
+
STDIN = "-"
|
|
18
|
+
_TRUE = frozenset({"true", "1", "yes"})
|
|
19
|
+
_FALSE = frozenset({"false", "0", "no"})
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class BodyError(Exception):
|
|
23
|
+
"""Invalid request-body input; the message names the offending flag or key."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _read_text(source: str, stdin: TextIO, flag: str) -> str:
|
|
27
|
+
if source == STDIN:
|
|
28
|
+
return stdin.read().removeprefix("\ufeff")
|
|
29
|
+
try:
|
|
30
|
+
return Path(source).read_text(encoding="utf-8-sig")
|
|
31
|
+
except (OSError, UnicodeDecodeError) as exc:
|
|
32
|
+
raise BodyError(f"{flag}: cannot read {source}: {os_reason(exc)}") from None
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _reject_constant(name: str) -> object:
|
|
36
|
+
raise ValueError(name)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _finite_float(text: str) -> float:
|
|
40
|
+
number = float(text)
|
|
41
|
+
if not math.isfinite(number): # 1e999 overflows to infinity
|
|
42
|
+
raise ValueError(text)
|
|
43
|
+
return number
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _parse_json(text: str, flag: str) -> object:
|
|
47
|
+
try:
|
|
48
|
+
return json.loads(text, parse_constant=_reject_constant, parse_float=_finite_float)
|
|
49
|
+
except json.JSONDecodeError as exc:
|
|
50
|
+
raise BodyError(f"{flag}: invalid JSON ({exc.msg} at position {exc.pos})") from None
|
|
51
|
+
except ValueError as exc: # NaN, Infinity and -Infinity are not JSON
|
|
52
|
+
raise BodyError(f"{flag}: invalid JSON ({exc} is not allowed)") from None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _property_schema(root: dict, schema: dict | None, parts: Sequence[str]) -> dict | None:
|
|
56
|
+
current = schema
|
|
57
|
+
for part in parts:
|
|
58
|
+
if current is None:
|
|
59
|
+
return None
|
|
60
|
+
props = resolve_ref(root, current).get("properties")
|
|
61
|
+
nxt = props.get(part) if isinstance(props, dict) else None
|
|
62
|
+
current = nxt if isinstance(nxt, dict) else None
|
|
63
|
+
return resolve_ref(root, current) if current is not None else None
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _type_of(schema: dict | None, root: dict) -> str | None:
|
|
67
|
+
if not schema:
|
|
68
|
+
return None
|
|
69
|
+
schema = unwrap_nullable(root, schema)
|
|
70
|
+
declared = schema.get("type")
|
|
71
|
+
if isinstance(declared, list):
|
|
72
|
+
declared = next((t for t in declared if t != "null"), None)
|
|
73
|
+
return declared if isinstance(declared, str) else None
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _coerce(raw: str, key: str, schema: dict | None, root: dict) -> object:
|
|
77
|
+
kind = _type_of(schema, root)
|
|
78
|
+
try:
|
|
79
|
+
if kind == "integer":
|
|
80
|
+
return int(raw)
|
|
81
|
+
if kind == "number":
|
|
82
|
+
number = float(raw)
|
|
83
|
+
if not math.isfinite(number):
|
|
84
|
+
raise ValueError(raw)
|
|
85
|
+
return number
|
|
86
|
+
except ValueError:
|
|
87
|
+
raise BodyError(f"--set {key}: expected {kind}, got {raw!r}") from None
|
|
88
|
+
if kind == "array":
|
|
89
|
+
# One element, coerced by the items schema; repeat --set to add more (or --set-json).
|
|
90
|
+
items = unwrap_nullable(root, schema).get("items") if schema else None
|
|
91
|
+
element = resolve_ref(root, items) if isinstance(items, dict) else None
|
|
92
|
+
return [_coerce(raw, key, element, root)]
|
|
93
|
+
if kind == "boolean":
|
|
94
|
+
lowered = raw.strip().lower()
|
|
95
|
+
if lowered in _TRUE:
|
|
96
|
+
return True
|
|
97
|
+
if lowered in _FALSE:
|
|
98
|
+
return False
|
|
99
|
+
raise BodyError(f"--set {key}: expected boolean (true/false), got {raw!r}")
|
|
100
|
+
return raw
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _existing(body: dict, key: str) -> list | None:
|
|
104
|
+
"""The list currently at ``key`` (dotted), or ``None`` when it is not a list."""
|
|
105
|
+
node: object = body
|
|
106
|
+
for part in key.split("."):
|
|
107
|
+
node = node.get(part) if isinstance(node, dict) else None
|
|
108
|
+
return node if isinstance(node, list) else None
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _related(a: str, b: str) -> bool:
|
|
112
|
+
return a == b or a.startswith(b + ".") or b.startswith(a + ".")
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _assign(target: dict, key: str, value: object, flag: str) -> None:
|
|
116
|
+
parts = key.split(".")
|
|
117
|
+
if not all(parts):
|
|
118
|
+
raise BodyError(f"{flag} {key}: empty path segment")
|
|
119
|
+
node = target
|
|
120
|
+
for part in parts[:-1]:
|
|
121
|
+
child = node.setdefault(part, {})
|
|
122
|
+
if not isinstance(child, dict):
|
|
123
|
+
raise BodyError(f"{flag} {key}: {part!r} is not an object")
|
|
124
|
+
node = child
|
|
125
|
+
node[parts[-1]] = value
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _set_value(raw: str, key: str, stdin: TextIO, schema: dict | None, root: dict) -> object:
|
|
129
|
+
if raw.startswith("@"):
|
|
130
|
+
text = _read_text(raw[1:], stdin, f"--set {key}")
|
|
131
|
+
return text.removesuffix("\n").removesuffix("\r")
|
|
132
|
+
if raw == "null":
|
|
133
|
+
return None
|
|
134
|
+
return _coerce(raw, key, schema, root)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def build_json_body(
|
|
138
|
+
*,
|
|
139
|
+
json_arg: str | None,
|
|
140
|
+
file_arg: str | None,
|
|
141
|
+
sets: Sequence[str],
|
|
142
|
+
set_jsons: Sequence[str],
|
|
143
|
+
body_schema: dict | None,
|
|
144
|
+
root: dict,
|
|
145
|
+
stdin: TextIO,
|
|
146
|
+
) -> dict | list | None:
|
|
147
|
+
"""Merge json -> file -> set-json -> set; ``None`` when no input was given."""
|
|
148
|
+
stdin_users = (file_arg == STDIN) + sum(1 for s in sets if s.partition("=")[2] == f"@{STDIN}")
|
|
149
|
+
if stdin_users > 1:
|
|
150
|
+
raise BodyError("--file - and --set key=@- cannot both read stdin in one command")
|
|
151
|
+
if json_arg is None and file_arg is None and not sets and not set_jsons:
|
|
152
|
+
return None
|
|
153
|
+
|
|
154
|
+
body: object = {}
|
|
155
|
+
if json_arg is not None:
|
|
156
|
+
body = _parse_json(json_arg, "--json")
|
|
157
|
+
if file_arg is not None:
|
|
158
|
+
loaded = _parse_json(_read_text(file_arg, stdin, "--file"), "--file")
|
|
159
|
+
if isinstance(body, dict) and isinstance(loaded, dict) and json_arg is not None:
|
|
160
|
+
body = {**body, **loaded}
|
|
161
|
+
else:
|
|
162
|
+
body = loaded
|
|
163
|
+
if not isinstance(body, dict | list):
|
|
164
|
+
raise BodyError("request body must be a JSON object or array")
|
|
165
|
+
expected = _type_of(body_schema, root)
|
|
166
|
+
if expected == "object" and isinstance(body, list):
|
|
167
|
+
raise BodyError("this command takes a JSON object, but --json/--file gave an array")
|
|
168
|
+
if (sets or set_jsons) and not isinstance(body, dict):
|
|
169
|
+
raise BodyError("--set/--set-json need an object body, but --json/--file gave an array")
|
|
170
|
+
if isinstance(body, dict):
|
|
171
|
+
for item in set_jsons:
|
|
172
|
+
key, raw = split_pair(item, "--set-json", BodyError)
|
|
173
|
+
_assign(body, key, _parse_json(raw, f"--set-json {key}"), "--set-json")
|
|
174
|
+
arrays: set[str] = set()
|
|
175
|
+
for item in sets:
|
|
176
|
+
key, raw = split_pair(item, "--set", BodyError)
|
|
177
|
+
schema = _property_schema(root, body_schema, key.split("."))
|
|
178
|
+
value = _set_value(raw, key, stdin, schema, root)
|
|
179
|
+
current = _existing(body, key) if key in arrays else None
|
|
180
|
+
if current is not None and isinstance(value, list):
|
|
181
|
+
current.extend(value) # a repeated --set on an array field adds an element
|
|
182
|
+
continue
|
|
183
|
+
# Replacing a field (or an ancestor) ends any array being accumulated under it.
|
|
184
|
+
arrays = {a for a in arrays if not _related(a, key)}
|
|
185
|
+
_assign(body, key, value, "--set")
|
|
186
|
+
if _type_of(schema, root) == "array" and isinstance(value, list):
|
|
187
|
+
arrays.add(key)
|
|
188
|
+
return body
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def missing_required(body: dict, body_schema: dict | None, root: dict) -> list[str]:
|
|
192
|
+
"""Top-level required property names absent from ``body``."""
|
|
193
|
+
if not body_schema:
|
|
194
|
+
return []
|
|
195
|
+
required = resolve_ref(root, body_schema).get("required")
|
|
196
|
+
if not isinstance(required, list):
|
|
197
|
+
return []
|
|
198
|
+
return [name for name in required if isinstance(name, str) and name not in body]
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""The protected-environment confirmation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
|
|
7
|
+
import click
|
|
8
|
+
|
|
9
|
+
from simple_module_remote.config.environments import Environment
|
|
10
|
+
|
|
11
|
+
__all__ = ["confirm_protected"]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def confirm_protected(
|
|
15
|
+
env: Environment,
|
|
16
|
+
*,
|
|
17
|
+
mutation: bool,
|
|
18
|
+
op_confirm: bool,
|
|
19
|
+
op_safe: bool,
|
|
20
|
+
yes: bool,
|
|
21
|
+
interactive: bool,
|
|
22
|
+
prompt: Callable[[str], str],
|
|
23
|
+
method: str,
|
|
24
|
+
path: str,
|
|
25
|
+
) -> None:
|
|
26
|
+
"""Require typing the environment name before a risky call on a protected environment."""
|
|
27
|
+
if not env.protected or not ((mutation and not op_safe) or op_confirm):
|
|
28
|
+
return
|
|
29
|
+
if yes:
|
|
30
|
+
return
|
|
31
|
+
if not interactive:
|
|
32
|
+
raise click.UsageError(
|
|
33
|
+
f"environment {env.name!r} is protected: pass --yes to run {method} {path} "
|
|
34
|
+
"non-interactively"
|
|
35
|
+
)
|
|
36
|
+
answer = prompt(f'Type "{env.name}" to run {method} {path} on {env.name} ({env.url})')
|
|
37
|
+
if answer.rstrip("\r\n") != env.name: # exact: no other whitespace is forgiven
|
|
38
|
+
raise click.UsageError(f"confirmation did not match {env.name!r}; nothing was sent")
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""The runtime context handed to :func:`run_operation`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import TextIO
|
|
8
|
+
|
|
9
|
+
from simple_module_remote.config.environments import Environment
|
|
10
|
+
from simple_module_remote.http.client import ApiClient
|
|
11
|
+
|
|
12
|
+
__all__ = ["RunContext"]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _keep(text: str) -> str:
|
|
16
|
+
return text
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class RunContext:
|
|
21
|
+
env: Environment
|
|
22
|
+
client_factory: Callable[[], ApiClient]
|
|
23
|
+
is_tty: bool
|
|
24
|
+
stdout: TextIO
|
|
25
|
+
stderr: TextIO
|
|
26
|
+
stdin: TextIO
|
|
27
|
+
prompt: Callable[[str], str]
|
|
28
|
+
root: dict
|
|
29
|
+
# stdin and stderr are both terminals: a confirmation prompt can be answered.
|
|
30
|
+
interactive: bool = False
|
|
31
|
+
login_hint: str = ""
|
|
32
|
+
# Said after a 404/422: the command may come from a schema older than the server's.
|
|
33
|
+
schema_hint: str = ""
|
|
34
|
+
tenant: str | None = None
|
|
35
|
+
# The operation is known to refuse tokens (a session-only route reached through `api`).
|
|
36
|
+
session_only: bool = False
|
|
37
|
+
# Strips the active token from server-derived text before it is shown (set per request).
|
|
38
|
+
redact: Callable[[str], str] = _keep
|
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
"""Write a response to the terminal, a pipe or a file."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import contextlib
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import tempfile
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
from urllib.parse import unquote
|
|
13
|
+
|
|
14
|
+
import click
|
|
15
|
+
import httpx
|
|
16
|
+
|
|
17
|
+
from simple_module_remote.generate.context import RunContext
|
|
18
|
+
from simple_module_remote.http.client import ApiClient
|
|
19
|
+
from simple_module_remote.http.errors import AUTH_STATUSES, ERROR_MIN, SCHEMA_STALE_STATUSES
|
|
20
|
+
from simple_module_remote.output.render import (
|
|
21
|
+
OUTPUT_FORMATS,
|
|
22
|
+
NoIdentifierError,
|
|
23
|
+
UnknownColumnError,
|
|
24
|
+
render,
|
|
25
|
+
)
|
|
26
|
+
from simple_module_remote.output.sanitize import sanitize_for
|
|
27
|
+
|
|
28
|
+
__all__ = ["emit", "print_error", "render_values", "say", "say_server"]
|
|
29
|
+
|
|
30
|
+
ERROR_BODY_CHARS = 500
|
|
31
|
+
CHUNK = 64 * 1024
|
|
32
|
+
MAX_RENDER_BYTES = 64 * 1024 * 1024
|
|
33
|
+
FILE_MODE = 0o666
|
|
34
|
+
# The server's wording for a route only a browser session may call (checked before scopes).
|
|
35
|
+
_SESSION_ONLY = re.compile(
|
|
36
|
+
r"browser session|session[- ]only|session required|tokens cannot be used|signed-in session"
|
|
37
|
+
)
|
|
38
|
+
REDIRECT_HINT = (
|
|
39
|
+
"hint: this response followed a redirect; the token is not forwarded on redirects, "
|
|
40
|
+
"so the redirect target rejected the request."
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def say(ctx: RunContext, text: str) -> None:
|
|
45
|
+
"""Write a line to stderr, safe for a terminal."""
|
|
46
|
+
ctx.stderr.write(sanitize_for(ctx.stderr, text) + "\n")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _clean(ctx: RunContext, text: str) -> str:
|
|
50
|
+
"""Server text made safe for stderr: sanitised, then redacted in both forms."""
|
|
51
|
+
return ctx.redact(sanitize_for(ctx.stderr, ctx.redact(text)))
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def say_server(ctx: RunContext, text: str, *, limit: int | None = None) -> None:
|
|
55
|
+
"""Like :func:`say` for text the server sent: the token is stripped, then ``limit`` applied."""
|
|
56
|
+
# Sanitise first, then redact both forms: control characters interleaved into the token
|
|
57
|
+
# would otherwise be stripped afterwards and reassemble it on a terminal.
|
|
58
|
+
clean = _clean(ctx, text)
|
|
59
|
+
say(ctx, clean if limit is None else clean[:limit])
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _media_type(response: httpx.Response) -> str:
|
|
63
|
+
return response.headers.get("Content-Type", "").split(";", 1)[0].strip().lower()
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def is_binary(response: httpx.Response) -> bool:
|
|
67
|
+
kind = _media_type(response)
|
|
68
|
+
if not kind:
|
|
69
|
+
return False
|
|
70
|
+
return not (_json_type(kind) or kind.startswith("text/"))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def has_type(response: httpx.Response) -> bool:
|
|
74
|
+
return bool(_media_type(response))
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _json_type(kind: str) -> bool:
|
|
78
|
+
# Responses are read broadly: application/json and any */*+json. (Request media for the
|
|
79
|
+
# schema side, operations.is_json_media, is stricter: application/*+json only.)
|
|
80
|
+
return kind == "application/json" or kind.endswith("+json")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def is_json(response: httpx.Response) -> bool:
|
|
84
|
+
return _json_type(_media_type(response))
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _read_capped(response: httpx.Response) -> bytes:
|
|
88
|
+
"""The body, read in chunks; refuses one larger than :data:`MAX_RENDER_BYTES`."""
|
|
89
|
+
declared = response.headers.get("Content-Length", "")
|
|
90
|
+
if declared.isascii() and declared.isdigit() and int(declared) > MAX_RENDER_BYTES:
|
|
91
|
+
raise _TooLargeError
|
|
92
|
+
chunks, size = [], 0
|
|
93
|
+
for chunk in response.iter_bytes(CHUNK):
|
|
94
|
+
size += len(chunk)
|
|
95
|
+
if size > MAX_RENDER_BYTES:
|
|
96
|
+
raise _TooLargeError
|
|
97
|
+
chunks.append(chunk)
|
|
98
|
+
return b"".join(chunks)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class _TooLargeError(Exception):
|
|
102
|
+
pass
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _safe_location(ctx: RunContext, location: str) -> str:
|
|
106
|
+
"""The Location value, or a placeholder when it holds the token raw or percent-decoded."""
|
|
107
|
+
for variant in (location, unquote(location), unquote(unquote(location))):
|
|
108
|
+
if ctx.redact(variant) != variant:
|
|
109
|
+
return "[redacted]"
|
|
110
|
+
return location
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _detail(text: str) -> str:
|
|
114
|
+
try:
|
|
115
|
+
detail = json.loads(text).get("detail")
|
|
116
|
+
except (ValueError, AttributeError):
|
|
117
|
+
return ""
|
|
118
|
+
return detail if isinstance(detail, str) else ""
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _auth_hint(ctx: RunContext, text: str) -> None:
|
|
122
|
+
"""Point at re-login only when the token itself is the problem."""
|
|
123
|
+
detail = _detail(text)
|
|
124
|
+
lowered = detail.lower()
|
|
125
|
+
shown = _clean(ctx, detail)[:ERROR_BODY_CHARS] # sanitise, redact, then cut
|
|
126
|
+
msg: str | None = None
|
|
127
|
+
if "tenant" in lowered or "organisation" in lowered or "organization" in lowered:
|
|
128
|
+
msg = (
|
|
129
|
+
f"hint: the server needs a tenant: {shown}; pass --tenant or use a token pinned to one"
|
|
130
|
+
)
|
|
131
|
+
elif ctx.session_only or _SESSION_ONLY.search(lowered):
|
|
132
|
+
cli = ctx.login_hint.split()[0] if ctx.login_hint else "the CLI"
|
|
133
|
+
msg = f"hint: tokens cannot call this route; `{cli} api --session-only` lists such routes"
|
|
134
|
+
elif "permission" in lowered or "scope" in lowered:
|
|
135
|
+
msg = "hint: the token lacks the permission named above; create one with the needed scopes"
|
|
136
|
+
elif ctx.login_hint:
|
|
137
|
+
msg = (
|
|
138
|
+
f"hint: the token may be missing or expired; run `{ctx.login_hint}` "
|
|
139
|
+
"(or pipe it to --token-stdin)"
|
|
140
|
+
)
|
|
141
|
+
if msg is not None:
|
|
142
|
+
say(ctx, msg)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def print_error(ctx: RunContext, response: httpx.Response) -> None:
|
|
146
|
+
response.read()
|
|
147
|
+
text = response.text
|
|
148
|
+
say(ctx, f"error: HTTP {response.status_code}")
|
|
149
|
+
if text.strip():
|
|
150
|
+
try:
|
|
151
|
+
# Redact the final text: JSON escapes decode back to the token when pretty-printed.
|
|
152
|
+
say_server(
|
|
153
|
+
ctx,
|
|
154
|
+
json.dumps(json.loads(text), indent=2, ensure_ascii=False),
|
|
155
|
+
limit=ERROR_BODY_CHARS,
|
|
156
|
+
)
|
|
157
|
+
except ValueError:
|
|
158
|
+
say_server(ctx, text, limit=ERROR_BODY_CHARS)
|
|
159
|
+
location = response.headers.get("Location")
|
|
160
|
+
if location and response.status_code < ERROR_MIN:
|
|
161
|
+
say(ctx, f"Location: {_safe_location(ctx, location)}")
|
|
162
|
+
redirected = ApiClient.was_redirected(response)
|
|
163
|
+
if response.status_code == 401 and redirected:
|
|
164
|
+
say(ctx, REDIRECT_HINT)
|
|
165
|
+
elif response.status_code in AUTH_STATUSES:
|
|
166
|
+
_auth_hint(ctx, text)
|
|
167
|
+
elif response.status_code in SCHEMA_STALE_STATUSES and ctx.schema_hint:
|
|
168
|
+
say(ctx, ctx.schema_hint)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _write_file(response: httpx.Response, target: str) -> None:
|
|
172
|
+
"""Stream to a temp file beside ``target`` and rename on success."""
|
|
173
|
+
destination = Path(target)
|
|
174
|
+
handle = tempfile.NamedTemporaryFile( # noqa: SIM115
|
|
175
|
+
"wb", dir=destination.parent, prefix=".smr-", delete=False
|
|
176
|
+
)
|
|
177
|
+
tmp = Path(handle.name)
|
|
178
|
+
try:
|
|
179
|
+
with handle:
|
|
180
|
+
for chunk in response.iter_bytes(CHUNK):
|
|
181
|
+
handle.write(chunk)
|
|
182
|
+
mask = os.umask(0)
|
|
183
|
+
os.umask(mask)
|
|
184
|
+
tmp.chmod(FILE_MODE & ~mask)
|
|
185
|
+
tmp.replace(destination)
|
|
186
|
+
except BaseException:
|
|
187
|
+
with contextlib.suppress(OSError):
|
|
188
|
+
tmp.unlink()
|
|
189
|
+
raise
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _write_stdout_bytes(ctx: RunContext, response: httpx.Response) -> bool:
|
|
193
|
+
sink = getattr(ctx.stdout, "buffer", None)
|
|
194
|
+
if sink is None:
|
|
195
|
+
return False
|
|
196
|
+
for chunk in response.iter_bytes(CHUNK):
|
|
197
|
+
sink.write(chunk)
|
|
198
|
+
sink.flush()
|
|
199
|
+
return True
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def render_values(ctx: RunContext, data: Any, values: dict[str, Any]) -> None:
|
|
203
|
+
fmt = values.get("output")
|
|
204
|
+
if fmt is not None and fmt not in OUTPUT_FORMATS:
|
|
205
|
+
raise click.UsageError(f"--output must be one of: {', '.join(OUTPUT_FORMATS)}")
|
|
206
|
+
columns = [c.strip() for c in (values.get("columns") or "").split(",") if c.strip()]
|
|
207
|
+
try:
|
|
208
|
+
render(
|
|
209
|
+
data,
|
|
210
|
+
fmt=fmt,
|
|
211
|
+
columns=columns or None,
|
|
212
|
+
quiet=bool(values.get("quiet")),
|
|
213
|
+
is_tty=ctx.is_tty,
|
|
214
|
+
out=ctx.stdout,
|
|
215
|
+
)
|
|
216
|
+
except (NoIdentifierError, UnknownColumnError) as exc:
|
|
217
|
+
# Column names come from the response: sanitise and redact them like any server text.
|
|
218
|
+
raise click.ClickException(_clean(ctx, str(exc))[:ERROR_BODY_CHARS]) from None
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _id_mode(values: dict[str, Any]) -> bool:
|
|
222
|
+
return values.get("output") == "id" or bool(values.get("quiet"))
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _refuse_render_flags(values: dict[str, Any]) -> None:
|
|
226
|
+
"""-o/-q/--columns format JSON; refuse them for a body that is not (a CSV export)."""
|
|
227
|
+
given = [
|
|
228
|
+
f
|
|
229
|
+
for f, key in (("-o", "output"), ("-q", "quiet"), ("--columns", "columns"))
|
|
230
|
+
if values.get(key)
|
|
231
|
+
]
|
|
232
|
+
if given:
|
|
233
|
+
raise click.ClickException(
|
|
234
|
+
f"{'/'.join(given)} cannot be used here: the response is not JSON "
|
|
235
|
+
"(redirect stdout or use --out FILE)"
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def emit(ctx: RunContext, response: httpx.Response, values: dict[str, Any]) -> int:
|
|
240
|
+
out = values.get("out")
|
|
241
|
+
if response.status_code == 204:
|
|
242
|
+
say(ctx, "done (204 No Content)")
|
|
243
|
+
return 0
|
|
244
|
+
non_json = has_type(response) and not is_json(response)
|
|
245
|
+
if non_json and not out:
|
|
246
|
+
_refuse_render_flags(values)
|
|
247
|
+
if is_binary(response) and not out:
|
|
248
|
+
if ctx.is_tty or not _write_stdout_bytes(ctx, response):
|
|
249
|
+
kind = response.headers.get("Content-Type", "binary")
|
|
250
|
+
say_server(ctx, f"error: binary response ({kind}); use --out FILE to save it")
|
|
251
|
+
return 1
|
|
252
|
+
return 0
|
|
253
|
+
if out:
|
|
254
|
+
_write_file(response, out)
|
|
255
|
+
say(ctx, f"wrote {out}")
|
|
256
|
+
return 0
|
|
257
|
+
streamable = not ctx.is_tty and non_json
|
|
258
|
+
# A pipe gets a non-JSON body chunk by chunk; a terminal needs it sanitized instead.
|
|
259
|
+
if streamable and _write_stdout_bytes(ctx, response):
|
|
260
|
+
return 0
|
|
261
|
+
try:
|
|
262
|
+
body = _read_capped(response)
|
|
263
|
+
except _TooLargeError:
|
|
264
|
+
say(ctx, "error: response is too large to render; use --out FILE to save it")
|
|
265
|
+
return 1
|
|
266
|
+
if not body:
|
|
267
|
+
if _id_mode(values): # no body, no identifiers: not a silent success
|
|
268
|
+
raise click.ClickException("-o id/-q cannot be used here: the response is empty")
|
|
269
|
+
return 0
|
|
270
|
+
try:
|
|
271
|
+
data: Any = json.loads(body)
|
|
272
|
+
except ValueError:
|
|
273
|
+
_refuse_render_flags(values) # identifiers/columns cannot come from a body that is not JSON
|
|
274
|
+
text = body.decode(response.charset_encoding or "utf-8", errors="replace")
|
|
275
|
+
ctx.stdout.write(sanitize_for(ctx.stdout, text))
|
|
276
|
+
return 0
|
|
277
|
+
render_values(ctx, data, values)
|
|
278
|
+
return 0
|