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,220 @@
1
+ """Run one generated command: build the request, confirm, send, render."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import json
7
+ import os
8
+ import sys
9
+ from collections.abc import Generator
10
+ from contextlib import ExitStack, contextmanager
11
+ from pathlib import Path
12
+ from typing import Any
13
+ from urllib.parse import urlencode
14
+
15
+ import click
16
+ import httpx
17
+
18
+ from simple_module_remote.generate.confirm import confirm_protected
19
+ from simple_module_remote.generate.context import RunContext
20
+ from simple_module_remote.generate.emit import (
21
+ ERROR_BODY_CHARS,
22
+ emit,
23
+ print_error,
24
+ render_values,
25
+ say,
26
+ say_server,
27
+ )
28
+ from simple_module_remote.generate.operations import Operation
29
+ from simple_module_remote.generate.pagination import iter_items, pagination_style
30
+ from simple_module_remote.generate.params import json_response_schema
31
+ from simple_module_remote.generate.prepare import DEFAULT_CONTENT_TYPE, Prepared, prepare_request
32
+ from simple_module_remote.http.client import ApiClient
33
+ from simple_module_remote.http.errors import (
34
+ EXIT_USAGE,
35
+ ApiError,
36
+ UnsafePathError,
37
+ exit_code_for,
38
+ is_success,
39
+ )
40
+ from simple_module_remote.output.reasons import os_reason
41
+ from simple_module_remote.output.sanitize import is_terminal
42
+
43
+ __all__ = ["run_operation"]
44
+
45
+ SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
46
+
47
+
48
+ def _quiet_stdout() -> None:
49
+ """Point stdout at /dev/null so the interpreter's exit flush cannot fail again."""
50
+ with contextlib.suppress(OSError, ValueError, AttributeError):
51
+ os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
52
+
53
+
54
+ class _HttpFailureError(Exception):
55
+ """A failed response met while paging; the response is already read."""
56
+
57
+ def __init__(self, response: httpx.Response) -> None:
58
+ super().__init__(f"HTTP {response.status_code}")
59
+ self.response = response
60
+
61
+
62
+ def _upload_line(spec: str) -> str:
63
+ field, _, raw = spec.partition("=")
64
+ path = Path(raw.removeprefix("@"))
65
+ try:
66
+ size = f"{path.stat().st_size} bytes"
67
+ except OSError:
68
+ size = "unreadable"
69
+ return f"upload {field}={path} (filename {path.name}, {size})"
70
+
71
+
72
+ def _dry_run(ctx: RunContext, op: Operation, prep: Prepared, values: dict[str, Any]) -> None:
73
+ url = ctx.env.url.rstrip("/") + prep.path
74
+ if prep.params:
75
+ url += "?" + urlencode(prep.params, doseq=True)
76
+ lines = [f"{op.method} {url}"]
77
+ if prep.json is not None:
78
+ lines.append(json.dumps(prep.json, indent=2, ensure_ascii=False))
79
+ if op.body_kind == "multipart":
80
+ lines += [_upload_line(u) for u in values.get("uploads") or ()]
81
+ lines += [f"form {s}" for s in values.get("sets") or ()]
82
+ elif op.body_kind == "raw" and values.get("body_file"):
83
+ kind = values.get("content_type") or DEFAULT_CONTENT_TYPE
84
+ lines.append(f"body-file {values['body_file']} ({kind})")
85
+ for line in lines:
86
+ ctx.stdout.write(line + "\n")
87
+
88
+
89
+ @contextmanager
90
+ def _send(
91
+ client: ApiClient, op: Operation, prep: Prepared, stream: bool
92
+ ) -> Generator[httpx.Response]:
93
+ if stream:
94
+ with client.stream(op.method, prep.path, params=prep.params) as response:
95
+ yield response
96
+ return
97
+ yield client.request(
98
+ op.method,
99
+ prep.path,
100
+ params=prep.params,
101
+ json=prep.json,
102
+ files=prep.files,
103
+ data=prep.data,
104
+ content=prep.content,
105
+ headers=prep.headers,
106
+ )
107
+
108
+
109
+ def _all_pages(
110
+ ctx: RunContext, client: ApiClient, op: Operation, prep: Prepared, values: dict[str, Any]
111
+ ) -> None:
112
+ style = pagination_style(op, json_response_schema(op, ctx.root))
113
+ if style is None:
114
+ raise click.UsageError("--all and --limit are not supported by this command")
115
+
116
+ def fetch(params: dict) -> Any:
117
+ response = client.request(op.method, prep.path, params=params)
118
+ if not is_success(response.status_code):
119
+ raise _HttpFailureError(response)
120
+ try:
121
+ return response.json()
122
+ except ValueError:
123
+ raise ApiError(response.status_code, response.text, "response is not JSON") from None
124
+
125
+ if "page" in prep.params:
126
+ raise click.UsageError("--all and --limit start at page 1: drop --page")
127
+ show = is_terminal(ctx.stderr)
128
+
129
+ def progress(count: int) -> None:
130
+ if show:
131
+ ctx.stderr.write(f"\rfetched {count}")
132
+ ctx.stderr.flush()
133
+
134
+ items = list(iter_items(fetch, style, prep.params, values.get("limit"), progress))
135
+ if show:
136
+ ctx.stderr.write("\n")
137
+ render_values(ctx, items, values)
138
+
139
+
140
+ def _fail(ctx: RunContext, exc: ApiError) -> int:
141
+ say(ctx, f"error: {exc.message}")
142
+ if exc.body_text.strip():
143
+ say_server(ctx, exc.body_text, limit=ERROR_BODY_CHARS)
144
+ return exit_code_for(exc.status)
145
+
146
+
147
+ def _exchange(
148
+ ctx: RunContext,
149
+ client: ApiClient,
150
+ op: Operation,
151
+ prep: Prepared,
152
+ values: dict[str, Any],
153
+ *,
154
+ paged: bool,
155
+ stream: bool,
156
+ ) -> int:
157
+ if paged:
158
+ try:
159
+ _all_pages(ctx, client, op, prep, values)
160
+ except _HttpFailureError as failure:
161
+ print_error(ctx, failure.response)
162
+ return exit_code_for(failure.response.status_code)
163
+ return 0
164
+ with _send(client, op, prep, stream) as response:
165
+ if not is_success(response.status_code):
166
+ print_error(ctx, response)
167
+ return exit_code_for(response.status_code)
168
+ return emit(ctx, response, values)
169
+
170
+
171
+ def run_operation(ctx: RunContext, op: Operation, values: dict[str, Any]) -> int:
172
+ """Execute ``op`` with click ``values``; returns the process exit code."""
173
+ mutation = op.method not in SAFE_METHODS
174
+ ctx.session_only = not op.token_capable
175
+ with ExitStack() as stack:
176
+ if values.get("out") == "":
177
+ raise click.UsageError("--out needs a file name")
178
+ if values.get("out") and (values.get("all_pages") or values.get("limit")):
179
+ raise click.UsageError("--all and --limit print rows to stdout and cannot use --out")
180
+ try:
181
+ prep = prepare_request(op, values, ctx.root, ctx.stdin, stack)
182
+ except UnsafePathError as exc:
183
+ raise click.UsageError(
184
+ f"{exc}; a path value may not contain '/' or '..', because it would change "
185
+ "which endpoint is called"
186
+ ) from None
187
+ if values.get("dry_run"):
188
+ _dry_run(ctx, op, prep, values)
189
+ return 0
190
+ client = stack.enter_context(ctx.client_factory()) # fail on credentials before prompting
191
+ ctx.redact = client.redact
192
+ confirm_protected(
193
+ ctx.env,
194
+ mutation=mutation,
195
+ op_confirm=op.confirm,
196
+ op_safe=op.safe,
197
+ yes=bool(values.get("yes")),
198
+ interactive=ctx.interactive,
199
+ prompt=ctx.prompt,
200
+ method=op.method,
201
+ path=prep.path,
202
+ )
203
+ if mutation:
204
+ say(ctx, f"[{ctx.env.name}/{ctx.tenant}]" if ctx.tenant else f"[{ctx.env.name}]")
205
+ is_get = op.method == "GET"
206
+ paged = is_get and bool(values.get("all_pages") or values.get("limit"))
207
+ # Read nothing up front: emit() streams what is not rendered and caps what is.
208
+ stream = is_get
209
+ try:
210
+ return _exchange(ctx, client, op, prep, values, paged=paged, stream=stream)
211
+ except ApiError as exc:
212
+ return _fail(ctx, exc)
213
+ except httpx.HTTPError as exc:
214
+ return _fail(ctx, ApiError(0, message=f"response failed: {type(exc).__name__}"))
215
+ except BrokenPipeError:
216
+ _quiet_stdout() # the reader (head, grep -q) went away: not an error
217
+ return 0
218
+ except OSError as exc:
219
+ say(ctx, f"error: cannot write output: {os_reason(exc)}")
220
+ return EXIT_USAGE
@@ -0,0 +1,69 @@
1
+ """CLI group and command names derived from OpenAPI tags and operationIds."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+ __all__ = [
8
+ "RESERVED",
9
+ "command_name",
10
+ "group_name",
11
+ "kebab_name",
12
+ "snake_name",
13
+ "valid_command_name",
14
+ ]
15
+
16
+ RESERVED: frozenset[str] = frozenset(
17
+ {"env", "login", "logout", "whoami", "doctor", "schema", "api", "raw"}
18
+ )
19
+
20
+ UNTAGGED_GROUP = "host"
21
+ # What an `x-cli-name` override may be: the same alphabet derived names use.
22
+ _COMMAND_NAME = re.compile(r"[a-z0-9][a-z0-9-]{0,62}")
23
+
24
+
25
+ def valid_command_name(name: str) -> bool:
26
+ return bool(_COMMAND_NAME.fullmatch(name))
27
+
28
+
29
+ def snake_name(name: str) -> str:
30
+ """Snake-case a name, mirroring the server's operationId module prefix.
31
+
32
+ ``FeatureFlags`` -> ``feature_flags``, ``X-Foo`` -> ``x_foo``.
33
+ """
34
+ spaced = re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", name)
35
+ return re.sub(r"[^0-9a-zA-Z]+", "_", spaced).strip("_").lower()
36
+
37
+
38
+ def kebab_name(name: str) -> str:
39
+ return snake_name(name).replace("_", "-")
40
+
41
+
42
+ def group_name(tag: str | None) -> str:
43
+ """``FeatureFlags`` -> ``feature-flags``; no tag -> ``host``."""
44
+ if not tag:
45
+ return UNTAGGED_GROUP
46
+ return kebab_name(tag) or UNTAGGED_GROUP
47
+
48
+
49
+ def command_name(
50
+ operation_id: str,
51
+ tag: str | None,
52
+ override: str | None,
53
+ *,
54
+ method: str = "",
55
+ path: str = "",
56
+ ) -> str:
57
+ """Strip the ``<snake(tag)>_`` prefix and kebab-case the rest; a valid ``override`` wins.
58
+
59
+ Never returns an empty string: an id with no usable characters falls back to the
60
+ kebab of ``<method>-<path>``, then to ``operation``.
61
+ """
62
+ if override and valid_command_name(override):
63
+ return override
64
+ rest = operation_id
65
+ if tag:
66
+ prefix = f"{snake_name(tag)}_"
67
+ if rest.startswith(prefix) and len(rest) > len(prefix):
68
+ rest = rest[len(prefix) :]
69
+ return kebab_name(rest) or kebab_name(f"{method}_{path}") or "operation"
@@ -0,0 +1,181 @@
1
+ """Typed operation model built from an OpenAPI document."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Literal
7
+
8
+ from simple_module_remote.generate.naming import (
9
+ RESERVED,
10
+ command_name,
11
+ group_name,
12
+ valid_command_name,
13
+ )
14
+ from simple_module_remote.schema.loader import resolve_ref, unwrap_nullable
15
+
16
+ __all__ = [
17
+ "Operation",
18
+ "Param",
19
+ "cli_operations",
20
+ "find_collisions",
21
+ "is_json_media",
22
+ "parse_operations",
23
+ ]
24
+
25
+ METHODS = ("get", "put", "post", "delete", "patch")
26
+ JSON_MEDIA = "application/json"
27
+ MULTIPART_MEDIA = "multipart/form-data"
28
+
29
+ BodyKind = Literal["none", "json", "multipart", "raw"]
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class Param:
34
+ name: str
35
+ location: Literal["path", "query"]
36
+ required: bool
37
+ schema: dict
38
+ description: str
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class Operation:
43
+ operation_id: str
44
+ method: str
45
+ path: str
46
+ group: str
47
+ name: str
48
+ params: tuple[Param, ...]
49
+ body_kind: BodyKind
50
+ body_schema: dict | None
51
+ summary: str
52
+ description: str
53
+ safe: bool
54
+ confirm: bool
55
+ token_capable: bool
56
+ body_required: bool = False
57
+
58
+
59
+ def _collect_params(schema: dict, path_item: dict, op: dict) -> tuple[Param, ...]:
60
+ merged: dict[tuple[str, str], dict] = {}
61
+ for raw in [*path_item.get("parameters", []), *op.get("parameters", [])]:
62
+ if not isinstance(raw, dict):
63
+ continue
64
+ param = resolve_ref(schema, raw)
65
+ loc, name = param.get("in"), param.get("name")
66
+ if loc in ("path", "query") and isinstance(name, str):
67
+ merged[(loc, name)] = param
68
+ params: list[Param] = []
69
+ for (loc, name), p in merged.items():
70
+ location: Literal["path", "query"] = "path" if loc == "path" else "query"
71
+ params.append(
72
+ Param(
73
+ name=name,
74
+ location=location,
75
+ required=bool(p.get("required", False)) or location == "path",
76
+ schema=unwrap_nullable(schema, resolve_ref(schema, p.get("schema") or {})),
77
+ description=str(p.get("description") or ""),
78
+ )
79
+ )
80
+ return tuple(params)
81
+
82
+
83
+ def is_json_media(media: str) -> bool:
84
+ base = media.split(";", 1)[0].strip().lower()
85
+ return base == JSON_MEDIA or (base.startswith("application/") and base.endswith("+json"))
86
+
87
+
88
+ def _body_required(schema: dict, op: dict) -> bool:
89
+ return resolve_ref(schema, op.get("requestBody") or {}).get("required") is True
90
+
91
+
92
+ def _body(schema: dict, op: dict) -> tuple[BodyKind, dict | None]:
93
+ request_body = resolve_ref(schema, op.get("requestBody") or {})
94
+ content = request_body.get("content") or {}
95
+ if not isinstance(content, dict) or not content:
96
+ return "none", None
97
+ kind: BodyKind
98
+ json_media = next((m for m in content if isinstance(m, str) and is_json_media(m)), None)
99
+ if json_media is not None:
100
+ kind, media = "json", json_media
101
+ elif MULTIPART_MEDIA in content:
102
+ kind, media = "multipart", MULTIPART_MEDIA
103
+ else:
104
+ kind, media = "raw", next(iter(content))
105
+ body_schema = (content[media] or {}).get("schema")
106
+ return kind, resolve_ref(schema, body_schema) if isinstance(body_schema, dict) else None
107
+
108
+
109
+ def parse_operations(schema: dict) -> list[Operation]:
110
+ """Every operation in the document, with CLI group and command names."""
111
+ ops: list[Operation] = []
112
+ for path, item in (schema.get("paths") or {}).items():
113
+ if not isinstance(item, dict):
114
+ continue
115
+ for method in METHODS:
116
+ op = item.get(method)
117
+ if not isinstance(op, dict):
118
+ continue
119
+ tags = op.get("tags") or []
120
+ tag = tags[0] if tags and isinstance(tags[0], str) else None
121
+ op_id = op.get("operationId") or f"{method}_{path}"
122
+ override = op.get("x-cli-name")
123
+ kind, body_schema = _body(schema, op)
124
+ ops.append(
125
+ Operation(
126
+ operation_id=op_id,
127
+ method=method.upper(),
128
+ path=path,
129
+ group=group_name(tag),
130
+ name=command_name(
131
+ op_id,
132
+ tag,
133
+ override if isinstance(override, str) else None,
134
+ method=method,
135
+ path=path,
136
+ ),
137
+ params=_collect_params(schema, item, op),
138
+ body_kind=kind,
139
+ body_schema=body_schema,
140
+ summary=str(op.get("summary") or ""),
141
+ description=str(op.get("description") or ""),
142
+ safe=op.get("x-cli-safe") is True,
143
+ confirm=op.get("x-cli-confirm") is True,
144
+ token_capable=op.get("x-sm-token") is True,
145
+ body_required=_body_required(schema, op),
146
+ )
147
+ )
148
+ return ops
149
+
150
+
151
+ def invalid_cli_names(schema: dict) -> list[str]:
152
+ """``x-cli-name`` values outside the command-name alphabet (shown sanitised, by repr)."""
153
+ bad: list[str] = []
154
+ for item in (schema.get("paths") or {}).values():
155
+ if not isinstance(item, dict):
156
+ continue
157
+ for method in METHODS:
158
+ op = item.get(method)
159
+ name = op.get("x-cli-name") if isinstance(op, dict) else None
160
+ if name is not None and not (isinstance(name, str) and valid_command_name(name)):
161
+ bad.append(ascii(name)[:80])
162
+ return bad
163
+
164
+
165
+ def cli_operations(ops: list[Operation]) -> list[Operation]:
166
+ """Only the operations a personal access token can call."""
167
+ return [op for op in ops if op.token_capable]
168
+
169
+
170
+ def find_collisions(ops: list[Operation]) -> list[tuple[str, str, list[str]]]:
171
+ """``(group, name, operation_ids)`` for duplicate commands and reserved group names."""
172
+ by_key: dict[tuple[str, str], list[str]] = {}
173
+ for op in ops:
174
+ by_key.setdefault((op.group, op.name), []).append(op.operation_id)
175
+ found = [(g, n, ids) for (g, n), ids in by_key.items() if len(ids) > 1]
176
+ reserved: dict[str, list[str]] = {}
177
+ for op in ops:
178
+ if op.group in RESERVED:
179
+ reserved.setdefault(op.group, []).append(op.operation_id)
180
+ found.extend((g, "", ids) for g, ids in reserved.items())
181
+ return found
@@ -0,0 +1,80 @@
1
+ """Fetch every page of a list endpoint, whatever shape it paginates in."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable, Iterator
6
+ from typing import Any, Literal
7
+
8
+ from simple_module_remote.generate.operations import Operation
9
+
10
+ __all__ = ["PaginationStyle", "iter_items", "pagination_style"]
11
+
12
+ PaginationStyle = Literal["page_envelope", "page_per_page", "file_storage"]
13
+
14
+ PAGE = "page"
15
+ PER_PAGE = "per_page"
16
+ DEFAULT_PER_PAGE = 100
17
+
18
+
19
+ def pagination_style(op: Operation, response_schema: dict | None) -> PaginationStyle | None:
20
+ """Which paging shape ``op`` uses, or ``None`` when it does not page by page/per_page."""
21
+ names = {p.name for p in op.params if p.location == "query"}
22
+ if not {PAGE, PER_PAGE} <= names or not response_schema:
23
+ return None
24
+ if response_schema.get("type") == "array":
25
+ return "page_per_page"
26
+ props = response_schema.get("properties") or {}
27
+ if "items" not in props:
28
+ return None
29
+ return "page_envelope" if "pages" in props else "file_storage"
30
+
31
+
32
+ def _items_of(payload: Any, style: PaginationStyle) -> tuple[list[Any], dict]:
33
+ if style == "page_per_page":
34
+ return (payload if isinstance(payload, list) else []), {}
35
+ if isinstance(payload, dict) and isinstance(payload.get("items"), list):
36
+ return payload["items"], payload
37
+ return [], {}
38
+
39
+
40
+ def _exhausted(
41
+ meta: dict, style: PaginationStyle, page: int, requested: int, count: int
42
+ ) -> bool | None:
43
+ """Whether this was the last page according to the response metadata; ``None`` if unknown."""
44
+ if style == "page_envelope" and isinstance(meta.get("pages"), int):
45
+ return page >= meta["pages"]
46
+ if style == "file_storage" and isinstance(meta.get("total"), int):
47
+ served = meta.get(PER_PAGE) if isinstance(meta.get(PER_PAGE), int) else requested
48
+ return (page - 1) * served + count >= meta["total"]
49
+ return None
50
+
51
+
52
+ def iter_items(
53
+ fetch: Callable[[dict], Any],
54
+ style: PaginationStyle,
55
+ params: dict,
56
+ limit: int | None,
57
+ on_progress: Callable[[int], None],
58
+ ) -> Iterator[Any]:
59
+ """Yield items page by page; stop on a short or empty page, the last page, or ``limit``."""
60
+ query = dict(params)
61
+ query.setdefault(PER_PAGE, DEFAULT_PER_PAGE)
62
+ per_page = int(query[PER_PAGE])
63
+ page = int(query.get(PAGE) or 1)
64
+ seen = 0
65
+ while limit is None or seen < limit:
66
+ query[PAGE] = page
67
+ items, meta = _items_of(fetch(dict(query)), style)
68
+ for item in items:
69
+ if limit is not None and seen >= limit:
70
+ return
71
+ seen += 1
72
+ yield item
73
+ on_progress(seen)
74
+ if not items:
75
+ return
76
+ done = _exhausted(meta, style, page, per_page, len(items))
77
+ # The server may clamp per_page, so a short page only ends the walk without metadata.
78
+ if done or (done is None and len(items) < per_page):
79
+ return
80
+ page += 1
@@ -0,0 +1,22 @@
1
+ """Split ``key=value`` command-line items."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterable
6
+ from typing import Any
7
+
8
+ import click
9
+
10
+ __all__ = ["split_pair", "split_pairs"]
11
+
12
+
13
+ def split_pair(item: str, flag: str, error: type[Exception]) -> tuple[str, str]:
14
+ """``key=value`` -> ``(key, value)``; raises ``error`` naming ``flag`` otherwise."""
15
+ key, sep, value = item.partition("=")
16
+ if not sep or not key:
17
+ raise error(f"{flag}: expected key=value, got {item!r}")
18
+ return key, value
19
+
20
+
21
+ def split_pairs(items: Iterable[Any] | None, flag: str) -> list[tuple[str, str]]:
22
+ return [split_pair(str(item), flag, click.UsageError) for item in items or ()]