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.
Files changed (51) hide show
  1. simple_module_remote/__init__.py +12 -0
  2. simple_module_remote/commands/__init__.py +1 -0
  3. simple_module_remote/commands/api_cmd.py +157 -0
  4. simple_module_remote/commands/auth_cmd.py +166 -0
  5. simple_module_remote/commands/doctor_cmd.py +157 -0
  6. simple_module_remote/commands/env_cmd.py +198 -0
  7. simple_module_remote/commands/generated.py +50 -0
  8. simple_module_remote/commands/root.py +186 -0
  9. simple_module_remote/commands/runtime.py +263 -0
  10. simple_module_remote/commands/schema_cmd.py +155 -0
  11. simple_module_remote/commands/schema_fetch.py +129 -0
  12. simple_module_remote/commands/schema_source.py +181 -0
  13. simple_module_remote/config/__init__.py +1 -0
  14. simple_module_remote/config/_file_store.py +182 -0
  15. simple_module_remote/config/_private_dir.py +191 -0
  16. simple_module_remote/config/credentials.py +296 -0
  17. simple_module_remote/config/environments.py +186 -0
  18. simple_module_remote/config/paths.py +32 -0
  19. simple_module_remote/config/resolve.py +96 -0
  20. simple_module_remote/curated/__init__.py +1 -0
  21. simple_module_remote/generate/__init__.py +1 -0
  22. simple_module_remote/generate/body.py +198 -0
  23. simple_module_remote/generate/confirm.py +38 -0
  24. simple_module_remote/generate/context.py +38 -0
  25. simple_module_remote/generate/emit.py +278 -0
  26. simple_module_remote/generate/execute.py +220 -0
  27. simple_module_remote/generate/naming.py +69 -0
  28. simple_module_remote/generate/operations.py +181 -0
  29. simple_module_remote/generate/pagination.py +80 -0
  30. simple_module_remote/generate/pairs.py +22 -0
  31. simple_module_remote/generate/params.py +210 -0
  32. simple_module_remote/generate/prepare.py +134 -0
  33. simple_module_remote/generate/tree.py +59 -0
  34. simple_module_remote/generate/trust.py +42 -0
  35. simple_module_remote/generate/validate.py +136 -0
  36. simple_module_remote/http/__init__.py +1 -0
  37. simple_module_remote/http/client.py +292 -0
  38. simple_module_remote/http/errors.py +59 -0
  39. simple_module_remote/http/safety.py +124 -0
  40. simple_module_remote/output/__init__.py +1 -0
  41. simple_module_remote/output/reasons.py +17 -0
  42. simple_module_remote/output/render.py +149 -0
  43. simple_module_remote/output/sanitize.py +32 -0
  44. simple_module_remote/py.typed +0 -0
  45. simple_module_remote/schema/__init__.py +1 -0
  46. simple_module_remote/schema/cache.py +187 -0
  47. simple_module_remote/schema/loader.py +56 -0
  48. simple_module_remote-0.0.50.dist-info/METADATA +73 -0
  49. simple_module_remote-0.0.50.dist-info/RECORD +51 -0
  50. simple_module_remote-0.0.50.dist-info/WHEEL +4 -0
  51. simple_module_remote-0.0.50.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,292 @@
1
+ """The guarded HTTP client: every CLI request goes through ApiClient."""
2
+
3
+ import ipaddress
4
+ import re
5
+ import time
6
+ from collections.abc import Callable, Generator, Mapping
7
+ from contextlib import contextmanager
8
+ from datetime import UTC, datetime
9
+ from email.utils import parsedate_to_datetime
10
+ from types import TracebackType
11
+ from typing import Any
12
+ from urllib.parse import unquote, urljoin, urlsplit
13
+
14
+ import httpx
15
+
16
+ from simple_module_remote.config.environments import Environment
17
+ from simple_module_remote.http.errors import ApiError, UnsafePathError
18
+ from simple_module_remote.http.safety import (
19
+ LOOPBACK_HOSTS,
20
+ validate_api_path,
21
+ validate_base_url,
22
+ validate_request_url,
23
+ )
24
+
25
+ REDIRECT_STATUSES = frozenset({301, 302, 303, 307, 308})
26
+ MAX_HOPS = 5
27
+ MAX_RETRIES = 3
28
+ MAX_WAIT_SECONDS = 30.0
29
+ DEFAULT_RETRY_AFTER = 1.0
30
+ TOO_MANY_REQUESTS = 429
31
+ TIMEOUT_SECONDS = 30.0
32
+ # %2e (dot), %2f (slash), %5c (backslash) and %25 (a double-encoded escape) in a redirect path
33
+ # are never followed with the token: a server may decode them once and traverse out of /api/.
34
+ _PATH_CHARS = re.compile(r"(?:[A-Za-z0-9\-._~!$&'()*+,;=:@/]|%[0-9A-Fa-f]{2})*")
35
+ _ENCODED_ESCAPE = re.compile(r"%(2e|2f|5c|25)", re.IGNORECASE)
36
+ METADATA_HOSTS = frozenset({"metadata.google.internal", "metadata"})
37
+ REDIRECTED_EXTENSION = "smr_redirected"
38
+ INVALID_REDIRECT = "the server sent an invalid redirect URL"
39
+ _STRIPPED_HEADERS = frozenset({"authorization", "cookie", "host", "user-agent"})
40
+
41
+
42
+ def _retry_delay(value: str | None, now: datetime | None = None) -> float:
43
+ if value is None:
44
+ return DEFAULT_RETRY_AFTER
45
+ text = value.strip()
46
+ if text.isascii() and text.isdigit():
47
+ return min(float(text), MAX_WAIT_SECONDS)
48
+ try:
49
+ when = parsedate_to_datetime(text)
50
+ except (TypeError, ValueError, IndexError):
51
+ return DEFAULT_RETRY_AFTER
52
+ if when.tzinfo is None:
53
+ when = when.replace(tzinfo=UTC)
54
+ return min(max(0.0, (when - (now or datetime.now(UTC))).total_seconds()), MAX_WAIT_SECONDS)
55
+
56
+
57
+ class ApiClient:
58
+ def __init__(
59
+ self,
60
+ env: Environment,
61
+ token: str | None,
62
+ *,
63
+ user_agent: str,
64
+ transport: httpx.BaseTransport | None = None,
65
+ sleep: Callable[[float], None] = time.sleep,
66
+ on_wait: Callable[[float], None] | None = None,
67
+ ) -> None:
68
+ self._on_wait = on_wait
69
+ self._base = validate_base_url(env.url).rstrip("/")
70
+ self._sleep = sleep
71
+ self._token = token
72
+ headers = {"User-Agent": user_agent}
73
+ if token:
74
+ headers["Authorization"] = f"Bearer {token}"
75
+ self._client = httpx.Client(
76
+ headers=headers,
77
+ follow_redirects=False,
78
+ transport=transport,
79
+ timeout=TIMEOUT_SECONDS,
80
+ )
81
+ # No token, no cookie carry-over: used only to follow redirects.
82
+ self._follower = httpx.Client(
83
+ headers={"User-Agent": user_agent},
84
+ follow_redirects=False,
85
+ transport=transport,
86
+ timeout=TIMEOUT_SECONDS,
87
+ )
88
+
89
+ def redact(self, text: str) -> str:
90
+ """``text`` with this client's token replaced, for anything shown to the user."""
91
+ return text.replace(self._token, "[redacted]") if self._token else text
92
+
93
+ def __enter__(self) -> "ApiClient":
94
+ return self
95
+
96
+ def __exit__(
97
+ self,
98
+ exc_type: type[BaseException] | None,
99
+ exc: BaseException | None,
100
+ tb: TracebackType | None,
101
+ ) -> None:
102
+ self.close()
103
+
104
+ def close(self) -> None:
105
+ self._client.close()
106
+ self._follower.close()
107
+
108
+ def request(
109
+ self,
110
+ method: str,
111
+ path: str,
112
+ *,
113
+ params: Mapping[str, Any] | None = None,
114
+ json: Any = None,
115
+ files: Any = None,
116
+ data: Any = None,
117
+ content: Any = None,
118
+ headers: Mapping[str, str] | None = None,
119
+ follow: bool = True,
120
+ ) -> httpx.Response:
121
+ return self._execute(
122
+ method, path, params, json, files, data, content, headers,
123
+ stream=False, follow=follow,
124
+ ) # fmt: skip
125
+
126
+ @contextmanager
127
+ def stream(
128
+ self,
129
+ method: str,
130
+ path: str,
131
+ *,
132
+ params: Mapping[str, Any] | None = None,
133
+ headers: Mapping[str, str] | None = None,
134
+ follow: bool = True,
135
+ ) -> Generator[httpx.Response]:
136
+ """Like ``request`` but the body is not read; iterate it, then the response closes."""
137
+ response = self._execute(
138
+ method, path, params, None, None, None, None, headers, stream=True, follow=follow
139
+ )
140
+ try:
141
+ yield response
142
+ finally:
143
+ response.close()
144
+
145
+ def _execute(
146
+ self,
147
+ method: str,
148
+ path: str,
149
+ params: Mapping[str, Any] | None,
150
+ json: Any,
151
+ files: Any,
152
+ data: Any,
153
+ content: Any,
154
+ headers: Mapping[str, str] | None,
155
+ *,
156
+ stream: bool,
157
+ follow: bool = True,
158
+ ) -> httpx.Response:
159
+ url = validate_request_url(self._base, self._base + validate_api_path(path))
160
+ extra = {k: v for k, v in (headers or {}).items() if k.lower() not in _STRIPPED_HEADERS}
161
+ verb = method.upper()
162
+ attempts = 0
163
+ while True:
164
+ try:
165
+ request = self._client.build_request(
166
+ verb, url, params=params, json=json, files=files, data=data,
167
+ content=content, headers=extra,
168
+ ) # fmt: skip
169
+ except httpx.InvalidURL:
170
+ raise UnsafePathError("the request URL is not valid") from None
171
+ validate_request_url(self._base, str(request.url), allow_query=True)
172
+ response = self._send(self._client, request, stream)
173
+ if response.status_code != TOO_MANY_REQUESTS or attempts >= MAX_RETRIES:
174
+ break
175
+ attempts += 1
176
+ delay = _retry_delay(response.headers.get("Retry-After"))
177
+ if self._on_wait is not None:
178
+ self._on_wait(delay)
179
+ self._sleep(delay)
180
+ response.close()
181
+ if follow and verb == "GET" and response.status_code in REDIRECT_STATUSES:
182
+ return self._follow(response, stream)
183
+ return response
184
+
185
+ @staticmethod
186
+ def was_redirected(response: httpx.Response) -> bool:
187
+ """True when ``response`` came from a redirect hop (sent without the token)."""
188
+ return bool(response.extensions.get(REDIRECTED_EXTENSION))
189
+
190
+ @staticmethod
191
+ def _send(client: httpx.Client, request: httpx.Request, stream: bool) -> httpx.Response:
192
+ try:
193
+ return client.send(request, stream=stream)
194
+ except httpx.HTTPError as exc:
195
+ raise ApiError(0, message=f"request failed: {type(exc).__name__}") from None
196
+ except httpx.InvalidURL:
197
+ # httpx parses a redirect's Location while sending, even with redirects off.
198
+ raise ApiError(0, message=INVALID_REDIRECT) from None
199
+
200
+ def _unsafe_redirect(self, target: str) -> bool:
201
+ """True for a target with userinfo (or unparsable) or one that carries the token."""
202
+ try:
203
+ if "@" in urlsplit(target).netloc:
204
+ return True
205
+ except ValueError:
206
+ return True
207
+ decoded = (target, unquote(target), unquote(unquote(target)))
208
+ return bool(self._token) and any(self._token in text for text in decoded)
209
+
210
+ def _is_local(self, host: str) -> bool:
211
+ """Whether the environment itself is on loopback or a private address."""
212
+ if host in LOOPBACK_HOSTS:
213
+ return True
214
+ try:
215
+ ip = ipaddress.ip_address(host)
216
+ except ValueError:
217
+ return False
218
+ return ip.is_private or ip.is_loopback
219
+
220
+ def _blocked_hop(self, target: str) -> str | None:
221
+ """Why the tokenless follower must not fetch ``target``, or ``None`` when it may."""
222
+ parts = urlsplit(target)
223
+ host = (parts.hostname or "").lower()
224
+ if parts.scheme == "http" and host not in LOOPBACK_HOSTS:
225
+ return "plain http to a non-loopback host"
226
+ if host in METADATA_HOSTS:
227
+ return "a metadata service address"
228
+ env_local = self._is_local((urlsplit(self._base).hostname or "").lower())
229
+ try:
230
+ ip = ipaddress.ip_address(host)
231
+ except ValueError:
232
+ return None if host not in LOOPBACK_HOSTS or env_local else "a loopback address"
233
+ if ip.is_link_local:
234
+ return "a link-local address"
235
+ if (ip.is_private or ip.is_loopback or ip.is_unspecified or ip.is_reserved) and (
236
+ not env_local
237
+ ):
238
+ return "a private or loopback address"
239
+ return None
240
+
241
+ def _stays_in_api(self, target: str) -> bool:
242
+ """True for a redirect target on the environment's origin under its /api/ prefix."""
243
+ # Judge the URL httpx will actually send, not our own parse of the string: when the two
244
+ # parsers could disagree, follow without the token.
245
+ try:
246
+ if "\\" in target or any(ord(ch) < 0x21 or ord(ch) > 0x7E for ch in target):
247
+ return False
248
+ request = self._client.build_request("GET", target)
249
+ raw_path = request.url.raw_path.split(b"?", 1)[0].decode("ascii")
250
+ if not _PATH_CHARS.fullmatch(raw_path) or _ENCODED_ESCAPE.search(raw_path):
251
+ return False # not a plain path, or an encoded dot/slash/backslash/percent
252
+ validate_request_url(self._base, str(request.url), allow_query=True)
253
+ except (UnsafePathError, ValueError, httpx.InvalidURL, UnicodeError):
254
+ return False
255
+ return True
256
+
257
+ def _follow(self, response: httpx.Response, stream: bool) -> httpx.Response:
258
+ current = response
259
+ for _ in range(MAX_HOPS):
260
+ location = current.headers.get("Location")
261
+ if current.status_code not in REDIRECT_STATUSES or not location:
262
+ return current
263
+ try:
264
+ target = urljoin(str(current.url), location)
265
+ except ValueError:
266
+ current.close()
267
+ raise ApiError(0, message=INVALID_REDIRECT) from None
268
+ if not target.lower().startswith(("http://", "https://")):
269
+ current.close()
270
+ raise ApiError(0, message="redirect to an unsupported URL scheme")
271
+ if self._unsafe_redirect(target):
272
+ current.close()
273
+ raise ApiError(0, message="redirect to a URL carrying credentials or invalid")
274
+ current.close()
275
+ # Same origin and still under the env's /api/: the token travels with it.
276
+ # Anything else goes out bare, through the client that holds no credentials.
277
+ keep_token = self._stays_in_api(target)
278
+ if not keep_token and (why := self._blocked_hop(target)):
279
+ raise ApiError(0, message=f"redirect refused: it points at {why}")
280
+ client = self._client if keep_token else self._follower
281
+ client.cookies.clear()
282
+ try:
283
+ hop = client.build_request("GET", target)
284
+ except httpx.InvalidURL:
285
+ raise ApiError(0, message=INVALID_REDIRECT) from None
286
+ current = self._send(client, hop, stream)
287
+ if not keep_token:
288
+ current.extensions[REDIRECTED_EXTENSION] = True
289
+ if current.status_code in REDIRECT_STATUSES:
290
+ current.close()
291
+ raise ApiError(0, message=f"too many redirects (more than {MAX_HOPS})")
292
+ return current
@@ -0,0 +1,59 @@
1
+ """HTTP errors and the status-to-exit-code mapping."""
2
+
3
+ EXIT_USAGE = 1
4
+ EXIT_CLIENT_ERROR = 2
5
+ EXIT_SERVER_ERROR = 3
6
+ EXIT_AUTH = 4
7
+ EXIT_NOT_FOUND = 5
8
+ EXIT_CONFLICT = 6
9
+
10
+ AUTH_STATUSES = frozenset({401, 403})
11
+ # A route or a body shape the server does not know: the CLI's schema may be stale.
12
+ SCHEMA_STALE_STATUSES = frozenset({404, 422})
13
+ _CONFLICT_STATUSES = frozenset({409, 412})
14
+ _NOT_FOUND = 404
15
+ _SERVER_MIN = 500
16
+ ERROR_MIN = 400
17
+ OK_MIN = 200
18
+ REDIRECT_MIN = 300
19
+
20
+
21
+ class UnsafePathError(ValueError):
22
+ """Raised when a request path or base URL could leave the environment's API."""
23
+
24
+
25
+ class ApiError(Exception):
26
+ """A failed request. Carries the status and body only; never headers or tokens."""
27
+
28
+ def __init__(self, status: int, body_text: str = "", message: str | None = None) -> None:
29
+ self.status = status
30
+ self.body_text = body_text
31
+ self.message = message or f"HTTP {status}"
32
+ super().__init__(self.message)
33
+
34
+ def __str__(self) -> str:
35
+ return self.message
36
+
37
+ def __repr__(self) -> str:
38
+ return f"ApiError(status={self.status})"
39
+
40
+
41
+ def is_success(status: int) -> bool:
42
+ return OK_MIN <= status < REDIRECT_MIN
43
+
44
+
45
+ def exit_code_for(status: int) -> int:
46
+ if status in AUTH_STATUSES:
47
+ return EXIT_AUTH
48
+ if status == _NOT_FOUND:
49
+ return EXIT_NOT_FOUND
50
+ if status in _CONFLICT_STATUSES:
51
+ return EXIT_CONFLICT
52
+ if status == 0 or status >= _SERVER_MIN:
53
+ return EXIT_SERVER_ERROR
54
+ if status < OK_MIN or REDIRECT_MIN <= status < ERROR_MIN:
55
+ # A 1xx or a leftover 3xx: the request itself has to change, the server did not fail.
56
+ return EXIT_CLIENT_ERROR
57
+ if status < REDIRECT_MIN:
58
+ return EXIT_SERVER_ERROR # a 2xx that could not be used (malformed success body)
59
+ return EXIT_CLIENT_ERROR
@@ -0,0 +1,124 @@
1
+ """Guards that keep requests inside the environment's own /api/ surface."""
2
+
3
+ from urllib.parse import SplitResult, unquote, urlsplit, urlunsplit
4
+
5
+ import httpx
6
+
7
+ from simple_module_remote.http.errors import UnsafePathError
8
+
9
+ API_PREFIX = "/api/"
10
+ LOOPBACK_HOSTS = frozenset({"localhost", "127.0.0.1", "::1"})
11
+ _FORBIDDEN_SUBSTRINGS = ("://", "@", "//", "\\", "?", "#")
12
+ _DOT_SEGMENTS = frozenset({"..", "."})
13
+
14
+
15
+ def validate_api_path(path: str) -> str:
16
+ if not path.startswith(API_PREFIX):
17
+ raise UnsafePathError(f"path must start with {API_PREFIX}: {path!r}")
18
+ if any(token in path for token in _FORBIDDEN_SUBSTRINGS):
19
+ raise UnsafePathError(f"unsafe characters in path: {path!r}")
20
+ if any(ord(ch) < 0x20 or ord(ch) == 0x7F for ch in path):
21
+ raise UnsafePathError("control characters in path")
22
+ for segment in path.split("/"):
23
+ decoded = unquote(segment)
24
+ if decoded in _DOT_SEGMENTS or "/" in decoded or "\\" in decoded:
25
+ raise UnsafePathError(f"unsafe path segment in {path!r}")
26
+ return path
27
+
28
+
29
+ def _redacted(parts: SplitResult) -> str:
30
+ """The URL without userinfo, query or fragment, safe to show in an error."""
31
+ return urlunsplit(parts._replace(netloc=parts.netloc.rpartition("@")[2], query="", fragment=""))
32
+
33
+
34
+ def validate_base_url(url: str) -> str:
35
+ if not url.isprintable() or any(ch.isspace() for ch in url) or "\\" in url:
36
+ raise UnsafePathError(
37
+ "environment url must not contain whitespace, control characters or backslashes"
38
+ )
39
+ try:
40
+ parts = urlsplit(url)
41
+ except ValueError:
42
+ raise UnsafePathError("environment url is not a valid URL") from None
43
+ if (
44
+ "@" in parts.netloc
45
+ or parts.username
46
+ or parts.password
47
+ or parts.query
48
+ or parts.fragment
49
+ or "?" in url
50
+ or "#" in url
51
+ ):
52
+ raise UnsafePathError("environment url must not carry credentials, query or fragment")
53
+ if any(unquote(seg) in _DOT_SEGMENTS for seg in parts.path.split("/")):
54
+ raise UnsafePathError("environment url path must not contain dot segments")
55
+ try:
56
+ port = parts.port # raises ValueError for a malformed or out-of-range port
57
+ except ValueError:
58
+ port = 0
59
+ if port == 0:
60
+ raise UnsafePathError("environment url has an invalid port")
61
+ host = parts.hostname
62
+ if not host or parts.scheme not in ("http", "https"):
63
+ shown = "" if "@" in url else f": {_redacted(parts)!r}"
64
+ raise UnsafePathError(f"environment url must be http(s) with a host{shown}")
65
+ if parts.scheme == "http" and host not in LOOPBACK_HOSTS:
66
+ raise UnsafePathError(f"refusing plain http to non-loopback host {host!r}: use https")
67
+ return url
68
+
69
+
70
+ _DEFAULT_PORTS = {"http": 80, "https": 443}
71
+
72
+
73
+ def normalize_origin(url: str) -> str:
74
+ """``scheme://host[:port]`` with a lowercase scheme and host and no default port.
75
+
76
+ A string that does not parse comes back unchanged (validation reports it elsewhere).
77
+ """
78
+ try:
79
+ parts = urlsplit(url)
80
+ host, number = parts.hostname, parts.port
81
+ except ValueError:
82
+ return url
83
+ if not host or not parts.scheme:
84
+ return url
85
+ shown = f"[{host}]" if ":" in host else host
86
+ port = f":{number}" if number and number != _DEFAULT_PORTS.get(parts.scheme.lower()) else ""
87
+ return f"{parts.scheme.lower()}://{shown}{port}"
88
+
89
+
90
+ def normalize_url(url: str) -> str:
91
+ """The canonical form stored for an environment: normalised origin, path without ``/``."""
92
+ try:
93
+ path = urlsplit(url).path.rstrip("/")
94
+ except ValueError:
95
+ return url
96
+ origin = normalize_origin(url)
97
+ return url if origin == url else origin + path
98
+
99
+
100
+ def _origin(parts: SplitResult) -> tuple[str, str | None, int | None]:
101
+ return (parts.scheme, parts.hostname, parts.port or _DEFAULT_PORTS.get(parts.scheme))
102
+
103
+
104
+ def validate_request_url(base: str, url: str, *, allow_query: bool = False) -> str:
105
+ """Refuse a request URL that is not under ``base`` + ``/api/`` on the same origin.
106
+
107
+ Run it on the composed string and again on the URL httpx built, which has had its
108
+ dot segments resolved (``allow_query`` then admits the encoded query parameters).
109
+ """
110
+ try:
111
+ # The same parser as the client, so IDNA hosts compare in their ASCII form.
112
+ wanted, got = urlsplit(str(httpx.URL(base))), urlsplit(str(httpx.URL(url)))
113
+ same_origin = _origin(got) == _origin(wanted)
114
+ except (ValueError, httpx.InvalidURL):
115
+ raise UnsafePathError("request URL is not valid") from None
116
+ prefix = wanted.path.rstrip("/") + API_PREFIX
117
+ if (
118
+ not same_origin
119
+ or (got.query and not allow_query)
120
+ or got.fragment
121
+ or not got.path.startswith(prefix)
122
+ ):
123
+ raise UnsafePathError("request URL would leave the environment's /api/ surface")
124
+ return url
@@ -0,0 +1 @@
1
+ """output area of the remote CLI engine."""
@@ -0,0 +1,17 @@
1
+ """A readable reason for an OS error, never a bare exception class name."""
2
+
3
+ from __future__ import annotations
4
+
5
+ __all__ = ["os_reason"]
6
+
7
+ _REASONS: dict[type[OSError], str] = {
8
+ FileNotFoundError: "no such file or directory",
9
+ IsADirectoryError: "it is a directory",
10
+ NotADirectoryError: "a parent is not a directory",
11
+ PermissionError: "permission denied",
12
+ }
13
+
14
+
15
+ def os_reason(exc: BaseException) -> str:
16
+ """``no such file or directory`` and friends; the exception name for anything else."""
17
+ return _REASONS.get(type(exc), type(exc).__name__)
@@ -0,0 +1,149 @@
1
+ """Render API results as a table, JSON, YAML or bare identifiers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any, Literal, TextIO
7
+
8
+ import yaml
9
+ from rich.console import Console
10
+ from rich.table import Table
11
+ from rich.text import Text
12
+
13
+ from simple_module_remote.output.sanitize import sanitize, sanitize_for
14
+
15
+ __all__ = ["OUTPUT_FORMATS", "NoIdentifierError", "UnknownColumnError", "render"]
16
+
17
+ Format = Literal["table", "json", "yaml", "id"]
18
+ OUTPUT_FORMATS: tuple[str, ...] = ("table", "json", "yaml", "id")
19
+ MAX_AUTO_COLUMNS = 8
20
+ MAX_CELL_CHARS = 200
21
+ ID_KEYS = ("id", "name", "key", "slug", "email")
22
+ NO_IDENTIFIER = "no identifier field in the response; use -o json"
23
+ UNSAFE_IDENTIFIER = (
24
+ "identifier contains control characters or is not a string or number; use -o json"
25
+ )
26
+
27
+
28
+ class UnknownColumnError(ValueError):
29
+ """``--columns`` named a field the rows do not have."""
30
+
31
+
32
+ class NoIdentifierError(ValueError):
33
+ """``-o id`` was asked for data that has none of the :data:`ID_KEYS`."""
34
+
35
+
36
+ def _rows(data: Any) -> list[Any] | None:
37
+ if isinstance(data, list):
38
+ return data
39
+ if isinstance(data, dict) and isinstance(data.get("items"), list):
40
+ return data["items"]
41
+ return None
42
+
43
+
44
+ def _text(value: Any) -> Text:
45
+ return Text(sanitize(_cell(value)))
46
+
47
+
48
+ def _cell(value: Any) -> str:
49
+ if value is None:
50
+ return ""
51
+ text = json.dumps(value, default=str) if isinstance(value, dict | list) else str(value)
52
+ if len(text) > MAX_CELL_CHARS:
53
+ return text[: MAX_CELL_CHARS - 1] + "…"
54
+ return text
55
+
56
+
57
+ def _auto_columns(rows: list[Any]) -> list[str]:
58
+ first = next((r for r in rows if isinstance(r, dict)), {})
59
+ scalars = [k for k, v in first.items() if not isinstance(v, dict | list)]
60
+ return scalars[:MAX_AUTO_COLUMNS]
61
+
62
+
63
+ def _check_columns(columns: list[str], rows: list[Any]) -> None:
64
+ known = {key for row in rows if isinstance(row, dict) for key in row}
65
+ unknown = [c for c in columns if c not in known]
66
+ if unknown:
67
+ raise UnknownColumnError(
68
+ f"unknown column {', '.join(unknown)}; available: {', '.join(sorted(known))}"
69
+ )
70
+
71
+
72
+ def _table(data: Any, columns: list[str] | None, out: TextIO) -> None:
73
+ console = Console(file=out, highlight=False, color_system=None, soft_wrap=False)
74
+ rows = _rows(data)
75
+ table = Table(show_header=True, header_style="bold")
76
+ if rows is not None and not rows:
77
+ out.write("no results\n")
78
+ return
79
+ if rows is None:
80
+ table.add_column(Text("key"))
81
+ table.add_column(Text("value"))
82
+ pairs = data.items() if isinstance(data, dict) else [("value", data)]
83
+ if columns and isinstance(data, dict):
84
+ _check_columns(columns, [data])
85
+ pairs = [(k, v) for k, v in pairs if k in columns]
86
+ for key, value in pairs:
87
+ table.add_row(_text(key), _text(value))
88
+ elif rows and all(isinstance(r, dict) for r in rows):
89
+ cols = columns or _auto_columns(rows)
90
+ if columns:
91
+ _check_columns(columns, rows)
92
+ for col in cols:
93
+ table.add_column(Text(sanitize(col)))
94
+ for row in rows:
95
+ table.add_row(*(_text(row.get(col)) for col in cols))
96
+ else:
97
+ table.add_column(Text("value"))
98
+ for row in rows:
99
+ table.add_row(_text(row))
100
+ console.print(table)
101
+
102
+
103
+ def _identifier(item: Any) -> Any:
104
+ if not isinstance(item, dict):
105
+ return item
106
+ return next((item[k] for k in ID_KEYS if item.get(k) is not None), None)
107
+
108
+
109
+ def _plain_identifier(value: Any) -> bool:
110
+ """A string or integer with no control characters (a newline would forge a second id)."""
111
+ if isinstance(value, bool) or not isinstance(value, str | int):
112
+ return False
113
+ return not any(ord(ch) < 0x20 or 0x7F <= ord(ch) <= 0x9F for ch in str(value))
114
+
115
+
116
+ def _ids(data: Any, out: TextIO) -> None:
117
+ rows = _rows(data)
118
+ values = [_identifier(item) for item in (rows if rows is not None else [data])]
119
+ if any(value is None for value in values):
120
+ raise NoIdentifierError(NO_IDENTIFIER)
121
+ if not all(_plain_identifier(value) for value in values):
122
+ raise NoIdentifierError(UNSAFE_IDENTIFIER)
123
+ for value in values:
124
+ out.write(sanitize_for(out, f"{value}") + "\n")
125
+
126
+
127
+ def render(
128
+ data: Any,
129
+ *,
130
+ fmt: Format | None,
131
+ columns: list[str] | None,
132
+ quiet: bool,
133
+ is_tty: bool,
134
+ out: TextIO,
135
+ ) -> None:
136
+ """Write ``data`` to ``out``; a table by default for lists on a terminal, else JSON."""
137
+ chosen: str | None = "id" if quiet else fmt
138
+ if chosen is None:
139
+ chosen = "table" if is_tty and _rows(data) is not None else "json"
140
+ if chosen == "id":
141
+ _ids(data, out)
142
+ elif chosen == "yaml":
143
+ out.write(sanitize_for(out, yaml.safe_dump(data, sort_keys=False, allow_unicode=True)))
144
+ elif chosen == "table":
145
+ _table(data, columns, out)
146
+ else:
147
+ out.write(
148
+ sanitize_for(out, json.dumps(data, indent=2, default=str, ensure_ascii=False)) + "\n"
149
+ )
@@ -0,0 +1,32 @@
1
+ """Strip terminal control sequences from server-controlled text before it reaches a terminal."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import TextIO
7
+
8
+ __all__ = ["is_terminal", "sanitize", "sanitize_for"]
9
+
10
+ _ESCAPES = re.compile(
11
+ r"\x1b\][^\x07\x1b\x9c]*(?:\x07|\x1b\\|\x9c)?" # OSC (titles, hyperlinks)
12
+ r"|\x1b[PX^_][^\x1b\x9c]*(?:\x1b\\|\x9c)?" # DCS, SOS, PM, APC strings
13
+ r"|\x1b\[[0-?]*[ -/]*[@-~]" # CSI
14
+ r"|\x1b[ -/]*[0-~]?" # other escapes, incl. a lone ESC
15
+ )
16
+ # C0/C1 controls (not newline/tab), bidi overrides/isolates, line and paragraph separators.
17
+ _CONTROLS = re.compile("[\x00-\x08\x0b-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069\u2028\u2029]")
18
+
19
+
20
+ def sanitize(text: str) -> str:
21
+ """Remove ESC sequences and C0/C1 controls, keeping newline and tab."""
22
+ return _CONTROLS.sub("", _ESCAPES.sub("", text))
23
+
24
+
25
+ def is_terminal(stream: TextIO) -> bool:
26
+ check = getattr(stream, "isatty", None)
27
+ return bool(check()) if callable(check) else False
28
+
29
+
30
+ def sanitize_for(stream: TextIO, text: str) -> str:
31
+ """``text`` made safe for ``stream``: sanitized on a terminal, byte-exact otherwise."""
32
+ return sanitize(text) if is_terminal(stream) else text
File without changes
@@ -0,0 +1 @@
1
+ """schema area of the remote CLI engine."""