ms-cli 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. ad_cli/__init__.py +6 -0
  2. ad_cli/__main__.py +6 -0
  3. ad_cli/auth.py +351 -0
  4. ad_cli/cli.py +278 -0
  5. ad_cli/discovery.py +243 -0
  6. ad_cli/dynamic.py +816 -0
  7. ad_cli/errors.py +45 -0
  8. ad_cli/http.py +424 -0
  9. ad_cli/invoke.py +652 -0
  10. ad_cli/main.py +703 -0
  11. cann_cli/__init__.py +6 -0
  12. cann_cli/__main__.py +6 -0
  13. cann_cli/auth.py +351 -0
  14. cann_cli/cli.py +278 -0
  15. cann_cli/discovery.py +243 -0
  16. cann_cli/dynamic.py +816 -0
  17. cann_cli/errors.py +45 -0
  18. cann_cli/http.py +424 -0
  19. cann_cli/invoke.py +652 -0
  20. cann_cli/main.py +703 -0
  21. ms_cli/__init__.py +6 -0
  22. ms_cli/__main__.py +6 -0
  23. ms_cli/auth.py +351 -0
  24. ms_cli/cli.py +278 -0
  25. ms_cli/discovery.py +243 -0
  26. ms_cli/dynamic.py +816 -0
  27. ms_cli/errors.py +45 -0
  28. ms_cli/http.py +424 -0
  29. ms_cli/invoke.py +652 -0
  30. ms_cli/main.py +703 -0
  31. ms_cli-0.2.0.dist-info/METADATA +444 -0
  32. ms_cli-0.2.0.dist-info/RECORD +67 -0
  33. ms_cli-0.2.0.dist-info/WHEEL +5 -0
  34. ms_cli-0.2.0.dist-info/entry_points.txt +2 -0
  35. ms_cli-0.2.0.dist-info/licenses/LICENSE +18 -0
  36. ms_cli-0.2.0.dist-info/top_level.txt +5 -0
  37. oed_cli/__init__.py +6 -0
  38. oed_cli/__main__.py +6 -0
  39. oed_cli/auth.py +1629 -0
  40. oed_cli/cli.py +297 -0
  41. oed_cli/defaults.toml +44 -0
  42. oed_cli/discovery.py +243 -0
  43. oed_cli/dynamic.py +816 -0
  44. oed_cli/errors.py +45 -0
  45. oed_cli/http.py +423 -0
  46. oed_cli/invoke.py +651 -0
  47. oed_cli/main.py +782 -0
  48. ogd_cli/__init__.py +6 -0
  49. ogd_cli/__main__.py +6 -0
  50. ogd_cli/auth.py +351 -0
  51. ogd_cli/cli.py +278 -0
  52. ogd_cli/discovery.py +243 -0
  53. ogd_cli/dynamic.py +816 -0
  54. ogd_cli/errors.py +45 -0
  55. ogd_cli/http.py +424 -0
  56. ogd_cli/invoke.py +652 -0
  57. ogd_cli/main.py +703 -0
  58. oud_cli/__init__.py +6 -0
  59. oud_cli/__main__.py +6 -0
  60. oud_cli/auth.py +351 -0
  61. oud_cli/cli.py +278 -0
  62. oud_cli/discovery.py +243 -0
  63. oud_cli/dynamic.py +816 -0
  64. oud_cli/errors.py +45 -0
  65. oud_cli/http.py +424 -0
  66. oud_cli/invoke.py +652 -0
  67. oud_cli/main.py +703 -0
oud_cli/main.py ADDED
@@ -0,0 +1,703 @@
1
+ """Entry point for the ``oud`` console script.
2
+
3
+ This module implements the top-level dispatch:
4
+
5
+ * Reserved sub-commands (``info``, ``services``, ``schema``, ``cache``,
6
+ ``completion``, ``--version``, ``--help`` …) go to the click tree in
7
+ :mod:`oud_cli.cli`.
8
+ * Anything else is treated as ``oud <service> [<method>] [flags]`` and
9
+ resolved dynamically via :mod:`oud_cli.dynamic`.
10
+
11
+ Dynamic dispatch is what makes ``oud`` interesting — a new service shows
12
+ up in the discovery feed, and ``oud <new-service> -- ...`` works on the
13
+ next TTL refresh without any code change.
14
+
15
+ Per-parameter flag surface
16
+ --------------------------
17
+
18
+ For each declared ``query`` / ``path`` parameter on an operation,
19
+ ``oud`` exposes a dedicated ``--<kebab-case>`` flag — derived from the
20
+ spec name (``cveId`` → ``--cve-id``, ``page_num`` → ``--page-num``).
21
+ ``oud <service> <operation> --help`` enumerates them all.
22
+
23
+ The legacy ``--params '{...}'`` JSON form is preserved as an escape
24
+ hatch: useful for rarely-used parameters and for piping bulk data.
25
+ Per-parameter flags and ``--params`` can be mixed; per-parameter flags
26
+ override matching keys from ``--params``.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import json
32
+ import os
33
+ import sys
34
+ from collections.abc import Sequence
35
+ from typing import Any
36
+
37
+ import click
38
+
39
+ from .auth import clear_token, read_token, store_token, token_backend, token_info, token_path
40
+ from .cli import cli as click_cli
41
+ from .dynamic import (
42
+ coerce_flag_value,
43
+ coerce_param_types,
44
+ collect_operations,
45
+ fetch_service_spec,
46
+ operations_table,
47
+ param_flag_index,
48
+ parse_json_arg,
49
+ resolve_operation,
50
+ resolve_runtime_gateway,
51
+ resolve_service_by_name,
52
+ )
53
+ from .errors import NotFoundError, OgdError
54
+ from .invoke import (
55
+ GATEWAY_MANAGED_PARAMS,
56
+ call_operation,
57
+ describe_operation_help,
58
+ describe_service,
59
+ )
60
+
61
+
62
+ def _resolve_auth() -> tuple[str | None, str | None]:
63
+ """Resolve the runtime token + cookie from the ``OUD_TOKEN`` / ``OUD_COOKIE``
64
+ env vars.
65
+
66
+ Mirrors :func:`oud_cli.http._resolve_user_agent` precedence. Returns
67
+ ``(None, None)`` when no credential is available — oud has no login flow,
68
+ so env vars are the only ad-hoc credential source.
69
+ """
70
+
71
+ return os.environ.get("OUD_TOKEN") or None, os.environ.get("OUD_COOKIE") or None
72
+
73
+ # Tokens that always go through the click sub-tree, regardless of whether
74
+ # they happen to match a discovered service. Recognised single tokens:
75
+ RESERVED_FIRST_TOKENS: frozenset[str] = frozenset(
76
+ {
77
+ "info",
78
+ "services",
79
+ "schema",
80
+ "cache",
81
+ "completion",
82
+ "help",
83
+ # the user typed only the binary with no args
84
+ "",
85
+ # passthrough flags
86
+ }
87
+ )
88
+ # Click passes these verbatim when they're the first argv item
89
+ LEADING_FLAGS: frozenset[str] = frozenset({"-h", "--help", "-V", "--version"})
90
+
91
+ # Built-in control flags handled by the dispatcher itself. Everything
92
+ # else is treated as a candidate per-parameter flag, validated later
93
+ # against the resolved operation's declared parameters.
94
+ _VALUE_FLAGS: frozenset[str] = frozenset({"params", "json", "path", "user-agent"})
95
+ _BOOL_FLAGS: frozenset[str] = frozenset({"dry-run"})
96
+
97
+
98
+ def _looks_like_reserved(argv: Sequence[str]) -> bool:
99
+ if not argv:
100
+ return True
101
+ head = argv[0]
102
+ if head in LEADING_FLAGS:
103
+ return True
104
+ if head.startswith("-"):
105
+ return True
106
+ return head in RESERVED_FIRST_TOKENS
107
+
108
+
109
+ def _split_dispatch_argv(rest: list[str]) -> tuple[dict[str, str], set[str], bool, list[str]]:
110
+ """First-pass split of argv (after ``service_name``) into:
111
+
112
+ - ``raw_flags``: ``--key value`` (or ``--key=value``) pairs
113
+ - ``bool_flags``: ``--key`` with no value (e.g. ``--dry-run``)
114
+ - ``help_requested``: ``--help`` / ``-h`` was seen
115
+ - ``positional``: non-flag arguments
116
+
117
+ Unknown ``--<key>`` flags are kept in ``raw_flags`` so they can be
118
+ matched against the resolved operation's declared parameters before
119
+ being rejected.
120
+ """
121
+
122
+ raw_flags: dict[str, str] = {}
123
+ bool_flags: set[str] = set()
124
+ help_requested = False
125
+ positional: list[str] = []
126
+
127
+ while rest:
128
+ tok = rest.pop(0)
129
+ if tok == "--":
130
+ positional.extend(rest)
131
+ break
132
+ if tok in ("-h", "--help"):
133
+ help_requested = True
134
+ continue
135
+ if tok.startswith("--"):
136
+ body = tok[2:]
137
+ if "=" in body:
138
+ k, v = body.split("=", 1)
139
+ if k in _BOOL_FLAGS:
140
+ bool_flags.add(k)
141
+ else:
142
+ raw_flags[k] = v
143
+ continue
144
+ if body in _VALUE_FLAGS:
145
+ if not rest:
146
+ raise OgdError(f"--{body} requires a value", kind="missing_flag_value")
147
+ raw_flags[body] = rest.pop(0)
148
+ continue
149
+ if body in _BOOL_FLAGS:
150
+ bool_flags.add(body)
151
+ continue
152
+ # Candidate per-parameter flag: consume the next token as its
153
+ # value unless that token is itself a flag.
154
+ if rest and not rest[0].startswith("-"):
155
+ raw_flags[body] = rest.pop(0)
156
+ else:
157
+ bool_flags.add(body)
158
+ continue
159
+ if tok.startswith("-"):
160
+ raise OgdError(f"unknown short flag: {tok}", kind="unknown_flag")
161
+ positional.append(tok)
162
+
163
+ return raw_flags, bool_flags, help_requested, positional
164
+
165
+
166
+ def _merge_params(
167
+ op,
168
+ raw_flags: dict[str, str],
169
+ ) -> tuple[dict, dict | None, int]:
170
+ """Build the final params + body from ``--params`` JSON and per-param flags.
171
+
172
+ Returns ``(params, body, exit_code)`` — exit_code is non-zero when a
173
+ JSON parse error short-circuits the call.
174
+ """
175
+
176
+ params: dict = {}
177
+ if "params" in raw_flags:
178
+ try:
179
+ parsed = parse_json_arg(raw_flags["params"], flag="params") or {}
180
+ except OgdError as exc:
181
+ return {}, None, exc.code
182
+ if not isinstance(parsed, dict):
183
+ return {}, None, 1
184
+ params.update(parsed)
185
+
186
+ body = None
187
+ if "json" in raw_flags:
188
+ try:
189
+ body = parse_json_arg(raw_flags["json"], flag="json")
190
+ except OgdError as exc:
191
+ return params, None, exc.code
192
+
193
+ # Per-parameter flags override matching keys from --params.
194
+ declared: dict[str, dict] = param_flag_index(op)
195
+ declared_names = {
196
+ p["name"] for p in op.parameters if p.get("in") in {"query", "path"}
197
+ }
198
+ for flag_key, value in raw_flags.items():
199
+ if flag_key in _VALUE_FLAGS or flag_key in _BOOL_FLAGS:
200
+ continue
201
+ if flag_key not in declared:
202
+ if flag_key.lower() in {p.lower() for p in GATEWAY_MANAGED_PARAMS}:
203
+ raise OgdError(
204
+ f"--{flag_key} is injected by the gateway for forum calls",
205
+ kind="gateway_managed_param",
206
+ hint=(
207
+ "Do not pass Api-Key / Api-Username — oud auto-fills "
208
+ "the placeholder headers on every forum call and the "
209
+ "gateway converts them."
210
+ ),
211
+ )
212
+ raise OgdError(
213
+ f"unknown flag: --{flag_key}",
214
+ kind="unknown_flag",
215
+ hint=(
216
+ f"Declared parameters for {op.operation_id}: "
217
+ f"{sorted(declared_names) or '(none)'}. "
218
+ "Use `--params '{...}'` for arbitrary JSON."
219
+ ),
220
+ )
221
+ param_def = declared[flag_key]
222
+ params[param_def["name"]] = coerce_flag_value(param_def, value)
223
+
224
+ # Final pass for any --params-derived values that need string→int coercion.
225
+ params = coerce_param_types(op, params)
226
+ return params, body, 0
227
+
228
+
229
+ _AG_LOGIN_INSTRUCTIONS = (
230
+ "AtomGit login\n"
231
+ "=============\n"
232
+ "1. Open https://atomgit.com and sign in.\n"
233
+ "2. Create a personal access token under Settings "
234
+ "(https://atomgit.com/setting/token-classic/create)\n"
235
+ "3. Paste the token below. It is stored encrypted for this Windows/Linux user "
236
+ "and is never echoed back.\n"
237
+ )
238
+
239
+
240
+ def _ag_login_help() -> int:
241
+ click.echo(
242
+ json.dumps(
243
+ {
244
+ "ok": True,
245
+ "help_for": "ag login",
246
+ "usage": "oud ag login [--token <pat>] [--no-verify] [--status]",
247
+ "flags": {
248
+ "--token": "provide the AtomGit personal access token non-interactively",
249
+ "--no-verify": "skip validating the token against AtomGit before storing",
250
+ "--status": "report whether a token is configured, without prompting",
251
+ },
252
+ "examples": [
253
+ "oud ag login",
254
+ "oud ag login --token <pat> --no-verify",
255
+ "oud ag login --status",
256
+ "oud ag logout",
257
+ ],
258
+ },
259
+ ensure_ascii=False,
260
+ indent=2,
261
+ )
262
+ )
263
+ return 0
264
+
265
+
266
+ def _ag_login(raw_flags: dict[str, str], bool_flags: set[str], help_requested: bool) -> int:
267
+ """Configure the AtomGit access token used by ``oud ag`` requests."""
268
+
269
+ if help_requested:
270
+ return _ag_login_help()
271
+
272
+ if "status" in bool_flags:
273
+ return _ag_status()
274
+
275
+ token = raw_flags.pop("token", None)
276
+ if token == "":
277
+ click.echo(
278
+ json.dumps(
279
+ {
280
+ "ok": False,
281
+ "code": 1,
282
+ "error": "missing_flag_value",
283
+ "message": "--token requires a non-empty value",
284
+ },
285
+ ensure_ascii=False,
286
+ ),
287
+ err=True,
288
+ )
289
+ return 1
290
+
291
+ if token is None:
292
+ click.echo(_AG_LOGIN_INSTRUCTIONS, err=True)
293
+ try:
294
+ token = click.prompt("AtomGit personal access token", hide_input=True, err=True)
295
+ except click.Abort:
296
+ click.echo(
297
+ json.dumps(
298
+ {"ok": False, "code": 1, "error": "aborted", "message": "login cancelled"},
299
+ ensure_ascii=False,
300
+ ),
301
+ err=True,
302
+ )
303
+ return 1
304
+
305
+ token = token.strip()
306
+ if not token:
307
+ click.echo(
308
+ json.dumps(
309
+ {
310
+ "ok": False,
311
+ "code": 1,
312
+ "error": "missing_token",
313
+ "message": "no token provided",
314
+ },
315
+ ensure_ascii=False,
316
+ ),
317
+ err=True,
318
+ )
319
+ return 1
320
+
321
+ if "no-verify" not in bool_flags:
322
+ verify_code = _verify_ag_token(token)
323
+ if verify_code != 0:
324
+ return verify_code
325
+
326
+ path = store_token(token)
327
+ backend = token_backend("ag")
328
+ if backend == "keyring":
329
+ # The token landed in the OS credential manager (Keychain / DPAPI /
330
+ # SecretService); the plaintext fallback file was deleted on the
331
+ # successful keyring write. Pointing the user at that (now absent)
332
+ # file path would be misleading — say where it actually is.
333
+ click.echo(
334
+ json.dumps(
335
+ {
336
+ "ok": True,
337
+ "service": "ag",
338
+ "configured": True,
339
+ "backend": "keyring",
340
+ "note": "token saved to the OS credential manager; "
341
+ "no local file is written, and the token is never echoed back",
342
+ },
343
+ ensure_ascii=False,
344
+ indent=2,
345
+ )
346
+ )
347
+ else:
348
+ # Plaintext fallback (headless / CI / Docker without an OS keystore):
349
+ # the 0600 file at `path` is the real store, so its path is accurate.
350
+ click.echo(
351
+ json.dumps(
352
+ {
353
+ "ok": True,
354
+ "service": "ag",
355
+ "configured": True,
356
+ "backend": "plaintext",
357
+ "token_path": str(path),
358
+ "note": "token stored locally (0600 file); it is never echoed back",
359
+ },
360
+ ensure_ascii=False,
361
+ indent=2,
362
+ )
363
+ )
364
+ return 0
365
+
366
+
367
+ def _verify_ag_token(token: str) -> int:
368
+ """Best-effort validation: hit an authenticated ``ag`` endpoint with ``token``.
369
+
370
+ Returns ``0`` when the token looks valid (or validation is unavailable for
371
+ the current spec); a nonzero exit code when the token was rejected or the
372
+ check itself failed.
373
+ """
374
+
375
+ try:
376
+ service = resolve_service_by_name("ag")
377
+ spec = fetch_service_spec(service)
378
+ base_url = resolve_runtime_gateway(service)
379
+ table = operations_table(spec, service.service_name, base_url=base_url)
380
+ op = resolve_operation(table, "listAuthenticatedUserIssues")
381
+ except NotFoundError:
382
+ return 0
383
+ except OgdError as exc:
384
+ click.echo(json.dumps(exc.to_dict(), ensure_ascii=False), err=True)
385
+ return exc.code
386
+
387
+ try:
388
+ result = call_operation(op, params={"access_token": token}, include_request=False)
389
+ except OgdError as exc:
390
+ click.echo(json.dumps(exc.to_dict(), ensure_ascii=False), err=True)
391
+ return exc.code
392
+
393
+ if not result.get("ok"):
394
+ click.echo(
395
+ json.dumps(
396
+ {
397
+ "ok": False,
398
+ "code": 1,
399
+ "error": "invalid_token",
400
+ "message": "AtomGit rejected the token",
401
+ "hint": (
402
+ "Check the token is active, or create a new one at "
403
+ "AtomGit > Settings > Access Tokens, then run `oud ag login` again."
404
+ ),
405
+ },
406
+ ensure_ascii=False,
407
+ ),
408
+ err=True,
409
+ )
410
+ return 1
411
+ return 0
412
+
413
+
414
+ def _ag_status() -> int:
415
+ """Report whether a token is configured, without prompting or network access."""
416
+
417
+ configured = read_token("ag") is not None
418
+ meta = token_info("ag") or {}
419
+ encryption = meta.get("encryption")
420
+ status: dict[str, Any] = {
421
+ "ok": True,
422
+ "service": "ag",
423
+ "configured": configured,
424
+ "encryption": encryption,
425
+ "created_at": meta.get("created_at"),
426
+ "token": None,
427
+ }
428
+ # Show the on-disk path only when plaintext is the real backend; in keyring
429
+ # mode that file does not exist (it is deleted on a successful keyring write),
430
+ # so reporting it would mislead the user about where the token lives.
431
+ if encryption != "keyring":
432
+ status["token_path"] = str(token_path("ag"))
433
+ click.echo(
434
+ json.dumps(status, ensure_ascii=False, indent=2)
435
+ )
436
+ return 0
437
+
438
+
439
+ def _ag_logout(help_requested: bool) -> int:
440
+ """Delete the stored ``ag`` token."""
441
+
442
+ if help_requested:
443
+ click.echo(
444
+ json.dumps(
445
+ {
446
+ "ok": True,
447
+ "help_for": "ag logout",
448
+ "usage": "oud ag logout",
449
+ "examples": ["oud ag logout"],
450
+ },
451
+ ensure_ascii=False,
452
+ indent=2,
453
+ )
454
+ )
455
+ return 0
456
+ was_set = clear_token("ag")
457
+ click.echo(
458
+ json.dumps(
459
+ {"ok": True, "service": "ag", "configured": False, "was_set": was_set},
460
+ ensure_ascii=False,
461
+ indent=2,
462
+ )
463
+ )
464
+ return 0
465
+
466
+
467
+ def _dispatch_dynamic(argv: Sequence[str]) -> int:
468
+ """Parse ``oud <service> [<method>] [flags]`` and run the resolved call."""
469
+
470
+ if not argv:
471
+ click.echo(_usage_dynamic(), err=True)
472
+ return 1
473
+
474
+ service_name = argv[0]
475
+ rest = list(argv[1:])
476
+
477
+ try:
478
+ raw_flags, bool_flags, help_requested, positional = _split_dispatch_argv(rest)
479
+ except OgdError as exc:
480
+ click.echo(json.dumps(exc.to_dict(), ensure_ascii=False), err=True)
481
+ return exc.code
482
+
483
+ user_agent = raw_flags.pop("user-agent", None)
484
+ method = positional[0] if positional else None
485
+
486
+ # `ag login`/`ag logout` are credential-management commands that must not
487
+ # reach the dispatch backend.
488
+ if service_name == "ag" and method in ("login", "logout"):
489
+ if len(positional) > 1:
490
+ click.echo(
491
+ json.dumps(
492
+ {
493
+ "ok": False,
494
+ "code": 1,
495
+ "error": "too_many_positional",
496
+ "message": "`oud ag login` takes flags, not extra positionals",
497
+ "extra_args": positional[1:],
498
+ },
499
+ ensure_ascii=False,
500
+ ),
501
+ err=True,
502
+ )
503
+ return 1
504
+ if method == "login":
505
+ return _ag_login(raw_flags, bool_flags, help_requested)
506
+ return _ag_logout(help_requested)
507
+
508
+ try:
509
+ service = resolve_service_by_name(service_name)
510
+ except OgdError as exc:
511
+ click.echo(json.dumps(exc.to_dict(), ensure_ascii=False), err=True)
512
+ return exc.code
513
+
514
+ try:
515
+ spec = fetch_service_spec(service)
516
+ except OgdError as exc:
517
+ click.echo(json.dumps(exc.to_dict(), ensure_ascii=False), err=True)
518
+ return exc.code
519
+
520
+ base_url = resolve_runtime_gateway(service)
521
+ ops = collect_operations(spec, service.service_name, base_url=base_url)
522
+
523
+ if not method:
524
+ # ``oud <service>`` alone → list every available operation.
525
+ if help_requested:
526
+ click.echo(
527
+ json.dumps(_service_help_payload(service, ops), ensure_ascii=False, indent=2)
528
+ )
529
+ return 0
530
+ click.echo(json.dumps(describe_service(service, ops), ensure_ascii=False, indent=2))
531
+ return 0
532
+
533
+ table = operations_table(spec, service.service_name, base_url=base_url)
534
+ if method not in table:
535
+ for key in table:
536
+ if key.lower() == method.lower():
537
+ method = key
538
+ break
539
+
540
+ try:
541
+ op = resolve_operation(table, method)
542
+ except OgdError as exc:
543
+ click.echo(json.dumps(exc.to_dict(), ensure_ascii=False), err=True)
544
+ return exc.code
545
+
546
+ if help_requested:
547
+ click.echo(
548
+ json.dumps(describe_operation_help(op, service), ensure_ascii=False, indent=2)
549
+ )
550
+ return 0
551
+
552
+ try:
553
+ params, body, exit_code = _merge_params(op, raw_flags)
554
+ except OgdError as exc:
555
+ click.echo(json.dumps(exc.to_dict(), ensure_ascii=False), err=True)
556
+ return exc.code
557
+ if exit_code:
558
+ # Re-parse the params we tried to load so the user sees the error.
559
+ if "params" in raw_flags:
560
+ try:
561
+ parse_json_arg(raw_flags["params"], flag="params")
562
+ except OgdError as exc:
563
+ click.echo(json.dumps(exc.to_dict(), ensure_ascii=False), err=True)
564
+ return exc.code
565
+ if "json" in raw_flags:
566
+ try:
567
+ parse_json_arg(raw_flags["json"], flag="json")
568
+ except OgdError as exc:
569
+ click.echo(json.dumps(exc.to_dict(), ensure_ascii=False), err=True)
570
+ return exc.code
571
+ return exit_code
572
+
573
+ dry_run = "dry-run" in bool_flags
574
+
575
+ try:
576
+ token, cookie = _resolve_auth()
577
+ result = call_operation(
578
+ op,
579
+ params=params,
580
+ body=body,
581
+ dry_run=dry_run,
582
+ include_request=True,
583
+ user_agent=user_agent,
584
+ token=token,
585
+ cookie=cookie,
586
+ )
587
+ except OgdError as exc:
588
+ click.echo(json.dumps(exc.to_dict(), ensure_ascii=False), err=True)
589
+ return exc.code
590
+
591
+ click.echo(json.dumps(result, ensure_ascii=False, indent=2))
592
+ return 0 if result.get("ok") else 3
593
+
594
+
595
+ def _usage_dynamic() -> str:
596
+ return json.dumps(
597
+ {
598
+ "ok": False,
599
+ "code": 1,
600
+ "error": "missing_service",
601
+ "message": "dynamic dispatch: pass <service> as the first argument",
602
+ "examples": [
603
+ "oud <service> # list operations",
604
+ "oud <service> <operation> # operation-level help",
605
+ "oud <service> <operation> --<flag> <value> # call with one flag",
606
+ "oud <service> <operation> --params '{...}' # bulk JSON params",
607
+ "oud <service> <operation> --dry-run # preview only",
608
+ ],
609
+ },
610
+ ensure_ascii=False,
611
+ indent=2,
612
+ )
613
+
614
+
615
+ def _service_help_payload(service, ops: list) -> dict:
616
+ """Payload for ``oud <service> --help``: enumerate operations + flag cheatsheet."""
617
+
618
+ return {
619
+ "ok": True,
620
+ "help_for": service.name,
621
+ "title": service.title,
622
+ "operations": [op.display_name for op in ops],
623
+ "operation_aliases": {
624
+ op.display_name: op.operation_id
625
+ for op in ops
626
+ if op.display_name != op.operation_id
627
+ } or None,
628
+ "usage": (
629
+ "oud <service> <operation> --<flag> <value>\n"
630
+ "Each declared query / path parameter is exposed as its own "
631
+ "--<kebab-case> flag. Use `oud <service> <operation> --help` "
632
+ "to list them, or pass `--params '{...}'` for bulk JSON."
633
+ ),
634
+ "examples": [
635
+ f"oud {service.service_name} {ops[0].display_name} --help",
636
+ f"oud {service.service_name} {ops[0].display_name} --dry-run",
637
+ ],
638
+ }
639
+
640
+
641
+ def _dispatch_dynamic_help(service_name: str, positional: list[str]) -> int:
642
+ """Legacy ``oud <service> --help`` entry point — kept for tests.
643
+
644
+ New code path goes through :func:`_service_help_payload` directly
645
+ inside :func:`_dispatch_dynamic`; this thin wrapper preserves the
646
+ public function name so existing tests stay in sync.
647
+ """
648
+
649
+ if positional:
650
+ click.echo(
651
+ json.dumps(
652
+ {
653
+ "ok": False,
654
+ "code": 1,
655
+ "error": "too_many_positional",
656
+ "message": "`oud <service> --help` lists operations; drop the extra argument",
657
+ "extra_args": positional,
658
+ },
659
+ ensure_ascii=False,
660
+ ),
661
+ err=True,
662
+ )
663
+ return 1
664
+
665
+ try:
666
+ service = resolve_service_by_name(service_name)
667
+ except OgdError as exc:
668
+ click.echo(json.dumps(exc.to_dict(), ensure_ascii=False), err=True)
669
+ return exc.code
670
+ try:
671
+ spec = fetch_service_spec(service)
672
+ except OgdError as exc:
673
+ click.echo(json.dumps(exc.to_dict(), ensure_ascii=False), err=True)
674
+ return exc.code
675
+
676
+ base_url = resolve_runtime_gateway(service)
677
+ ops = collect_operations(spec, service.service_name, base_url=base_url)
678
+ click.echo(json.dumps(_service_help_payload(service, ops), ensure_ascii=False, indent=2))
679
+ return 0
680
+
681
+
682
+ def main(argv: Sequence[str] | None = None) -> int:
683
+ """Top-level entry point. Returns a Unix-style exit code."""
684
+
685
+ raw = list(argv if argv is not None else sys.argv[1:])
686
+ try:
687
+ if _looks_like_reserved(raw):
688
+ try:
689
+ click_cli.main(args=raw, standalone_mode=False)
690
+ except click.exceptions.ClickException as exc:
691
+ exc.show()
692
+ return exc.exit_code
693
+ except SystemExit as exc:
694
+ return int(exc.code or 0)
695
+ return 0
696
+ return _dispatch_dynamic(raw)
697
+ except OgdError as exc:
698
+ click.echo(json.dumps(exc.to_dict(), ensure_ascii=False), err=True)
699
+ return exc.code
700
+
701
+
702
+ if __name__ == "__main__":
703
+ sys.exit(main())