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.
- ad_cli/__init__.py +6 -0
- ad_cli/__main__.py +6 -0
- ad_cli/auth.py +351 -0
- ad_cli/cli.py +278 -0
- ad_cli/discovery.py +243 -0
- ad_cli/dynamic.py +816 -0
- ad_cli/errors.py +45 -0
- ad_cli/http.py +424 -0
- ad_cli/invoke.py +652 -0
- ad_cli/main.py +703 -0
- cann_cli/__init__.py +6 -0
- cann_cli/__main__.py +6 -0
- cann_cli/auth.py +351 -0
- cann_cli/cli.py +278 -0
- cann_cli/discovery.py +243 -0
- cann_cli/dynamic.py +816 -0
- cann_cli/errors.py +45 -0
- cann_cli/http.py +424 -0
- cann_cli/invoke.py +652 -0
- cann_cli/main.py +703 -0
- ms_cli/__init__.py +6 -0
- ms_cli/__main__.py +6 -0
- ms_cli/auth.py +351 -0
- ms_cli/cli.py +278 -0
- ms_cli/discovery.py +243 -0
- ms_cli/dynamic.py +816 -0
- ms_cli/errors.py +45 -0
- ms_cli/http.py +424 -0
- ms_cli/invoke.py +652 -0
- ms_cli/main.py +703 -0
- ms_cli-0.2.0.dist-info/METADATA +444 -0
- ms_cli-0.2.0.dist-info/RECORD +67 -0
- ms_cli-0.2.0.dist-info/WHEEL +5 -0
- ms_cli-0.2.0.dist-info/entry_points.txt +2 -0
- ms_cli-0.2.0.dist-info/licenses/LICENSE +18 -0
- ms_cli-0.2.0.dist-info/top_level.txt +5 -0
- oed_cli/__init__.py +6 -0
- oed_cli/__main__.py +6 -0
- oed_cli/auth.py +1629 -0
- oed_cli/cli.py +297 -0
- oed_cli/defaults.toml +44 -0
- oed_cli/discovery.py +243 -0
- oed_cli/dynamic.py +816 -0
- oed_cli/errors.py +45 -0
- oed_cli/http.py +423 -0
- oed_cli/invoke.py +651 -0
- oed_cli/main.py +782 -0
- ogd_cli/__init__.py +6 -0
- ogd_cli/__main__.py +6 -0
- ogd_cli/auth.py +351 -0
- ogd_cli/cli.py +278 -0
- ogd_cli/discovery.py +243 -0
- ogd_cli/dynamic.py +816 -0
- ogd_cli/errors.py +45 -0
- ogd_cli/http.py +424 -0
- ogd_cli/invoke.py +652 -0
- ogd_cli/main.py +703 -0
- oud_cli/__init__.py +6 -0
- oud_cli/__main__.py +6 -0
- oud_cli/auth.py +351 -0
- oud_cli/cli.py +278 -0
- oud_cli/discovery.py +243 -0
- oud_cli/dynamic.py +816 -0
- oud_cli/errors.py +45 -0
- oud_cli/http.py +424 -0
- oud_cli/invoke.py +652 -0
- oud_cli/main.py +703 -0
ad_cli/__init__.py
ADDED
ad_cli/__main__.py
ADDED
ad_cli/auth.py
ADDED
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
"""Credential storage for ``ad`` — AtomGit personal-access-token store.
|
|
2
|
+
|
|
3
|
+
ad-cli does not implement a user-login flow: the Ascend community
|
|
4
|
+
services (mailman, etherpad, ...) are called anonymously. The only credential
|
|
5
|
+
the CLI manages is the AtomGit PAT used by ``ad ag login``.
|
|
6
|
+
|
|
7
|
+
Storage goes through :class:`_SecureStore`: the OS-native credential store
|
|
8
|
+
(keyring: macOS Keychain / Windows DPAPI / Linux SecretService) when
|
|
9
|
+
reachable, with a transparent fallback to a 0600 plaintext file otherwise.
|
|
10
|
+
|
|
11
|
+
Public surface:
|
|
12
|
+
- :func:`store_token` / :func:`read_token` / :func:`token_info` /
|
|
13
|
+
:func:`clear_token` / :func:`token_path` — per-service PAT storage
|
|
14
|
+
(consumed by :mod:`ad_cli.main` and :mod:`ad_cli.invoke`)
|
|
15
|
+
- :func:`get_token` / :func:`get_cookie` — ``AD_TOKEN`` / ``AD_COOKIE``
|
|
16
|
+
env overrides for ad-hoc authenticated calls
|
|
17
|
+
- :class:`_SecureStore` — the keyring-primary / plaintext-fallback store
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import contextlib
|
|
23
|
+
import json
|
|
24
|
+
import os
|
|
25
|
+
import time
|
|
26
|
+
from collections.abc import Callable
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
from typing import Any
|
|
29
|
+
|
|
30
|
+
from .discovery import ag_token_path
|
|
31
|
+
|
|
32
|
+
# Credential store identifiers for the OS-native backend (keyring).
|
|
33
|
+
_KEYRING_SERVICE = "ad-cli"
|
|
34
|
+
_KEYRING_USERNAME = "default"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def get_token() -> str | None:
|
|
38
|
+
"""Return the ``AD_TOKEN`` env override, or ``None``."""
|
|
39
|
+
|
|
40
|
+
return os.environ.get("AD_TOKEN") or None
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def get_cookie() -> str | None:
|
|
44
|
+
"""Return the ``AD_COOKIE`` env override, or ``None``."""
|
|
45
|
+
|
|
46
|
+
return os.environ.get("AD_COOKIE") or None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
# ---------------------------------------------------------------------------
|
|
50
|
+
# Token storage (keyring primary + plaintext fallback)
|
|
51
|
+
# ---------------------------------------------------------------------------
|
|
52
|
+
#
|
|
53
|
+
# Tokens are persisted into the OS-native credential store via the ``keyring``
|
|
54
|
+
# library when an accessible backend is detected (macOS Keychain, Windows
|
|
55
|
+
# DPAPI / Credential Manager, Linux SecretService). On environments where
|
|
56
|
+
# keyring is unreachable (headless Linux / CI / Docker without libsecret) or
|
|
57
|
+
# when keyring raises on read/write, the implementation falls back to a
|
|
58
|
+
# 0600-mode plaintext file. The plaintext file is deleted after a successful
|
|
59
|
+
# keyring write so the OS keystore is the single source of truth.
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _read_existing(path: Path) -> dict[str, Any]:
|
|
63
|
+
"""Read the plaintext store; return empty dict if missing or corrupt."""
|
|
64
|
+
|
|
65
|
+
if not path.is_file():
|
|
66
|
+
return {}
|
|
67
|
+
try:
|
|
68
|
+
return json.loads(path.read_text(encoding="utf-8"))
|
|
69
|
+
except (OSError, json.JSONDecodeError, UnicodeDecodeError):
|
|
70
|
+
# Corrupt file — wrong encoding / truncated / half-written. Drop it
|
|
71
|
+
# rather than crash the caller. A fresh save() overwrites the bad file.
|
|
72
|
+
with contextlib.suppress(OSError):
|
|
73
|
+
path.unlink()
|
|
74
|
+
return {}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _atomic_write_json_plaintext(path: Path, data: dict[str, Any]) -> None:
|
|
78
|
+
"""Write ``data`` as JSON to ``path`` atomically with 0600 perms.
|
|
79
|
+
|
|
80
|
+
Plaintext fallback path used by :class:`_SecureStore` when ``keyring``
|
|
81
|
+
is unreachable.
|
|
82
|
+
"""
|
|
83
|
+
|
|
84
|
+
tmp = path.with_suffix(path.suffix + ".tmp")
|
|
85
|
+
tmp.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
86
|
+
with contextlib.suppress(OSError):
|
|
87
|
+
os.chmod(tmp, 0o600)
|
|
88
|
+
tmp.replace(path)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class _SecureStore:
|
|
92
|
+
"""Thin facade over :mod:`keyring` with a transparent plaintext fallback.
|
|
93
|
+
|
|
94
|
+
Resolution is lazy: each call probes the current best backend and caches
|
|
95
|
+
the verdict. Any ``keyring`` failure (``NoKeyringError``, locked
|
|
96
|
+
credential DB, ``OSError`` from libsecret, sandbox restrictions) causes
|
|
97
|
+
a silent fallback to the 0600 plaintext file and a one-line stderr
|
|
98
|
+
note — never a hard error, so ``ad ag login`` keeps working headless.
|
|
99
|
+
"""
|
|
100
|
+
|
|
101
|
+
def __init__(self, *, username: str = _KEYRING_USERNAME,
|
|
102
|
+
fallback_path: Callable[[], Path] = lambda: ag_token_path("ag")) -> None:
|
|
103
|
+
# ``username`` namespaces the keyring entry so additional credentials
|
|
104
|
+
# can share the ``_KEYRING_SERVICE`` without colliding.
|
|
105
|
+
# ``fallback_path`` picks the plaintext 0600 file used when keyring
|
|
106
|
+
# is unreachable — the ag PAT lives under ``tokens/ag.json``.
|
|
107
|
+
self._username = username
|
|
108
|
+
self._fallback_path = fallback_path
|
|
109
|
+
self._keyring: Any | None = None
|
|
110
|
+
# ``None`` = not probed yet, ``True``/``False`` = resolved verdict
|
|
111
|
+
self._available: bool | None = None
|
|
112
|
+
self._last_backend: str = "unprobed"
|
|
113
|
+
|
|
114
|
+
# -- internal ----------------------------------------------------------
|
|
115
|
+
|
|
116
|
+
def _resolve(self) -> bool:
|
|
117
|
+
if self._available is not None:
|
|
118
|
+
return self._available
|
|
119
|
+
try:
|
|
120
|
+
import keyring # type: ignore[import-untyped]
|
|
121
|
+
import keyring.errors # type: ignore[import-untyped]
|
|
122
|
+
|
|
123
|
+
self._keyring = keyring
|
|
124
|
+
# Cheapest probe: a single get. Side-effect free — we don't want
|
|
125
|
+
# to write a probe entry into the user's real keychain.
|
|
126
|
+
# NoKeyringError is the canonical "no backend" signal; other
|
|
127
|
+
# exceptions mean the backend exists but is broken/locked, in
|
|
128
|
+
# which case we silently fall through to plaintext 0600.
|
|
129
|
+
try:
|
|
130
|
+
keyring.get_password(_KEYRING_SERVICE, self._username)
|
|
131
|
+
except keyring.errors.NoKeyringError:
|
|
132
|
+
self._available = False
|
|
133
|
+
return False
|
|
134
|
+
except Exception: # noqa: BLE001 — best-effort probe
|
|
135
|
+
# Locked credential DB, libsecret not running, sandbox block,
|
|
136
|
+
# GNOME Keyring not unlocked — module loaded but unusable.
|
|
137
|
+
# Surface the backend via `ad ag login --status`, not stderr noise.
|
|
138
|
+
self._available = False
|
|
139
|
+
return False
|
|
140
|
+
self._available = True
|
|
141
|
+
return True
|
|
142
|
+
except ImportError:
|
|
143
|
+
self._available = False
|
|
144
|
+
return False
|
|
145
|
+
|
|
146
|
+
# -- public API ---------------------------------------------------------
|
|
147
|
+
|
|
148
|
+
def save(self, payload: dict[str, Any]) -> str:
|
|
149
|
+
"""Persist ``payload`` via the best available backend.
|
|
150
|
+
|
|
151
|
+
Returns the backend label (``"keyring"`` or ``"plaintext"``) so the
|
|
152
|
+
caller can surface it (``ad ag login --status``).
|
|
153
|
+
"""
|
|
154
|
+
|
|
155
|
+
path = self._fallback_path()
|
|
156
|
+
if self._resolve():
|
|
157
|
+
try:
|
|
158
|
+
blob = json.dumps(payload, ensure_ascii=False)
|
|
159
|
+
self._keyring.set_password(_KEYRING_SERVICE, self._username, blob) # type: ignore[union-attr]
|
|
160
|
+
# keyring is the source of truth now — drop the plaintext copy
|
|
161
|
+
# so a later read cannot see stale data from a previous
|
|
162
|
+
# plaintext-only session.
|
|
163
|
+
with contextlib.suppress(OSError):
|
|
164
|
+
path.unlink()
|
|
165
|
+
self._last_backend = "keyring"
|
|
166
|
+
return "keyring"
|
|
167
|
+
except Exception: # noqa: BLE001 — best-effort fallback
|
|
168
|
+
# Backend reported as available by the probe but the real
|
|
169
|
+
# write raised (locked keyring, etc.). Mark broken for this
|
|
170
|
+
# process so subsequent operations go straight to plaintext
|
|
171
|
+
# instead of re-probing keyring on every call.
|
|
172
|
+
self._available = False
|
|
173
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
174
|
+
_atomic_write_json_plaintext(path, payload)
|
|
175
|
+
self._last_backend = "plaintext"
|
|
176
|
+
return "plaintext"
|
|
177
|
+
|
|
178
|
+
def load(self) -> dict[str, Any] | None:
|
|
179
|
+
"""Read ``payload`` from the best available backend.
|
|
180
|
+
|
|
181
|
+
Prefers keyring when reachable; falls back to the plaintext file
|
|
182
|
+
(used for headless environments without an OS keystore).
|
|
183
|
+
"""
|
|
184
|
+
|
|
185
|
+
if self._resolve():
|
|
186
|
+
try:
|
|
187
|
+
raw = self._keyring.get_password(_KEYRING_SERVICE, self._username) # type: ignore[union-attr]
|
|
188
|
+
except Exception: # noqa: BLE001 — best-effort fallback
|
|
189
|
+
# Same as save(): mark broken so we don't keep retrying
|
|
190
|
+
# keyring (and burning time on a locked backend) every read.
|
|
191
|
+
self._available = False
|
|
192
|
+
raw = None
|
|
193
|
+
if raw:
|
|
194
|
+
try:
|
|
195
|
+
self._last_backend = "keyring"
|
|
196
|
+
return json.loads(raw)
|
|
197
|
+
except json.JSONDecodeError:
|
|
198
|
+
# corrupt entry — drop it and let the caller treat as
|
|
199
|
+
# unconfigured rather than crash
|
|
200
|
+
with contextlib.suppress(Exception):
|
|
201
|
+
self._keyring.delete_password(_KEYRING_SERVICE, self._username) # type: ignore[union-attr]
|
|
202
|
+
# Fallback: plaintext file.
|
|
203
|
+
existing = _read_existing(self._fallback_path())
|
|
204
|
+
self._last_backend = "plaintext" if existing else "unprobed"
|
|
205
|
+
return existing or None
|
|
206
|
+
|
|
207
|
+
def clear(self) -> None:
|
|
208
|
+
"""Remove the payload from both backends (idempotent)."""
|
|
209
|
+
|
|
210
|
+
if self._resolve():
|
|
211
|
+
with contextlib.suppress(Exception):
|
|
212
|
+
self._keyring.delete_password(_KEYRING_SERVICE, self._username) # type: ignore[union-attr]
|
|
213
|
+
with contextlib.suppress(OSError):
|
|
214
|
+
self._fallback_path().unlink()
|
|
215
|
+
self._last_backend = "unprobed"
|
|
216
|
+
|
|
217
|
+
def backend_label(self) -> str:
|
|
218
|
+
"""Last backend actually used (``"keyring"`` / ``"plaintext"`` / ``"unprobed"``)."""
|
|
219
|
+
|
|
220
|
+
return self._last_backend
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
# ---------------------------------------------------------------------------
|
|
224
|
+
# AtomGit (``ag``) personal-access-token storage
|
|
225
|
+
# ---------------------------------------------------------------------------
|
|
226
|
+
#
|
|
227
|
+
# The AtomGit PAT is persisted through a :class:`_SecureStore` instance
|
|
228
|
+
# namespaced by ``username="ag:{service}"``, falling back to separate
|
|
229
|
+
# plaintext files (``tokens/{service}.json``). Storage semantics: keyring
|
|
230
|
+
# (macOS Keychain / Windows DPAPI / Linux SecretService) preferred, 0600
|
|
231
|
+
# plaintext fallback otherwise. The public API (``store_token`` /
|
|
232
|
+
# ``read_token`` / ``token_info`` / ``clear_token`` / ``token_path``) stays
|
|
233
|
+
# stable so :mod:`ad_cli.main` and :mod:`ad_cli.invoke` need no changes.
|
|
234
|
+
|
|
235
|
+
# Per-service AtomGit stores, keyed by ``service`` so a future general token
|
|
236
|
+
# store can share this code. ``"ag"`` is the only wired service today.
|
|
237
|
+
_ag_stores: dict[str, _SecureStore] = {}
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _ag_store(service: str = "ag") -> _SecureStore:
|
|
241
|
+
"""Return the namespaced :class:`_SecureStore` for ``service``."""
|
|
242
|
+
|
|
243
|
+
store = _ag_stores.get(service)
|
|
244
|
+
if store is None:
|
|
245
|
+
store = _SecureStore(
|
|
246
|
+
username=f"ag:{service}",
|
|
247
|
+
fallback_path=lambda s=service: ag_token_path(s),
|
|
248
|
+
)
|
|
249
|
+
_ag_stores[service] = store
|
|
250
|
+
return store
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def token_path(service: str = "ag") -> Path:
|
|
254
|
+
"""Return the plaintext-fallback path for ``service``'s AtomGit token.
|
|
255
|
+
|
|
256
|
+
The real secret prefers the OS keystore (see :class:`_SecureStore`); this
|
|
257
|
+
path is only the 0600 fallback when keyring is unreachable. Exposed for
|
|
258
|
+
diagnostics (``ad ag login --status``) and for ``ad cache`` isolation.
|
|
259
|
+
"""
|
|
260
|
+
|
|
261
|
+
return ag_token_path(service)
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def store_token(token: str, *, service: str = "ag") -> Path:
|
|
265
|
+
"""Persist ``token`` for ``service`` via :class:`_SecureStore`.
|
|
266
|
+
|
|
267
|
+
Writes through the keyring when reachable (OS-encrypted), otherwise a
|
|
268
|
+
0600 plaintext file. Returns the fallback path. Never raises on a
|
|
269
|
+
keystore failure — it degrades to plaintext so ``ad ag login`` keeps
|
|
270
|
+
working in headless / CI / Docker.
|
|
271
|
+
"""
|
|
272
|
+
|
|
273
|
+
if not token:
|
|
274
|
+
from .errors import UserError
|
|
275
|
+
|
|
276
|
+
raise UserError("token must be a non-empty string", kind="missing_token")
|
|
277
|
+
payload: dict[str, Any] = {
|
|
278
|
+
"service": service,
|
|
279
|
+
"access_token": token,
|
|
280
|
+
"created_at": time.time(),
|
|
281
|
+
}
|
|
282
|
+
store = _ag_store(service)
|
|
283
|
+
store.save(payload)
|
|
284
|
+
return token_path(service)
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def read_token(service: str = "ag") -> str | None:
|
|
288
|
+
"""Return the stored AtomGit token for ``service``, or ``None``.
|
|
289
|
+
|
|
290
|
+
Any read failure (no token stored, corrupt entry, undecryptable blob)
|
|
291
|
+
degrades silently to ``None`` so callers fall through to the
|
|
292
|
+
missing-token path rather than crashing.
|
|
293
|
+
"""
|
|
294
|
+
|
|
295
|
+
stored = _ag_store(service).load()
|
|
296
|
+
if not isinstance(stored, dict):
|
|
297
|
+
return None
|
|
298
|
+
token = stored.get("access_token")
|
|
299
|
+
return token if isinstance(token, str) else None
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def token_backend(service: str = "ag") -> str:
|
|
303
|
+
"""The storage backend actually used for ``service``'s last write/read.
|
|
304
|
+
|
|
305
|
+
Reflects the cached verdict from the most recent :meth:`_SecureStore.save`
|
|
306
|
+
/ :meth:`_SecureStore.load` (``"keyring"`` / ``"plaintext"`` / ``"unprobed"``)
|
|
307
|
+
without re-probing. Use it right after :func:`store_token` to tell the user
|
|
308
|
+
*where* their token landed — the OS credential manager (no on-disk file) or
|
|
309
|
+
the 0600 plaintext fallback (the file at :func:`token_path`).
|
|
310
|
+
"""
|
|
311
|
+
|
|
312
|
+
return _ag_store(service).backend_label()
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def token_info(service: str = "ag") -> dict[str, Any] | None:
|
|
316
|
+
"""Return ``{encryption, created_at}`` metadata for ``service``'s token.
|
|
317
|
+
|
|
318
|
+
``encryption`` reports the backend actually used (``"keyring"`` or
|
|
319
|
+
``"plaintext"``), not a hand-rolled cipher marker. Returns ``None`` when
|
|
320
|
+
no token is stored.
|
|
321
|
+
"""
|
|
322
|
+
|
|
323
|
+
store = _ag_store(service)
|
|
324
|
+
stored = store.load()
|
|
325
|
+
if not isinstance(stored, dict):
|
|
326
|
+
return None
|
|
327
|
+
return {
|
|
328
|
+
"encryption": store.backend_label(),
|
|
329
|
+
"created_at": stored.get("created_at"),
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def clear_token(service: str = "ag") -> bool:
|
|
334
|
+
"""Delete ``service``'s stored token from both backends; return if set."""
|
|
335
|
+
|
|
336
|
+
store = _ag_store(service)
|
|
337
|
+
had_data = store.load() is not None
|
|
338
|
+
store.clear()
|
|
339
|
+
return had_data
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
__all__ = [
|
|
343
|
+
"clear_token",
|
|
344
|
+
"get_cookie",
|
|
345
|
+
"get_token",
|
|
346
|
+
"read_token",
|
|
347
|
+
"store_token",
|
|
348
|
+
"token_backend",
|
|
349
|
+
"token_info",
|
|
350
|
+
"token_path",
|
|
351
|
+
]
|
ad_cli/cli.py
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
"""Click command surface for ``ad``.
|
|
2
|
+
|
|
3
|
+
Reserved (built-in) commands:
|
|
4
|
+
ad --version
|
|
5
|
+
ad info
|
|
6
|
+
ad services
|
|
7
|
+
ad schema <service>[.<method>]
|
|
8
|
+
ad cache {show,clear,refresh}
|
|
9
|
+
|
|
10
|
+
Dynamic dispatch (``ad <service> <method> ...``) lives in :mod:`ad_cli.main`
|
|
11
|
+
and is documented in ``docs/cli-design.md`` (v0.2).
|
|
12
|
+
|
|
13
|
+
``ad --help`` additionally lists every auto-discovered service so newcomers
|
|
14
|
+
can see what the CLI exposes without reading docs first.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import datetime as dt
|
|
20
|
+
import json
|
|
21
|
+
import sys
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
import click
|
|
25
|
+
|
|
26
|
+
from . import __version__
|
|
27
|
+
from .discovery import (
|
|
28
|
+
CACHE_TTL_SECONDS,
|
|
29
|
+
DiscoveryFeed,
|
|
30
|
+
ServiceMeta,
|
|
31
|
+
current_community,
|
|
32
|
+
fetch_discovery,
|
|
33
|
+
fetch_spec,
|
|
34
|
+
)
|
|
35
|
+
from .errors import OgdError
|
|
36
|
+
from .http import resolve_gateway
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _print_json(data: Any, *, error: bool = False) -> None:
|
|
40
|
+
click.echo(json.dumps(data, ensure_ascii=False, indent=2), err=error, color=False)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _resolve_feed(*, force_refresh: bool) -> DiscoveryFeed:
|
|
44
|
+
try:
|
|
45
|
+
return fetch_discovery(community=None, force_refresh=force_refresh)
|
|
46
|
+
except OgdError as exc:
|
|
47
|
+
_print_json(exc.to_dict(), error=True)
|
|
48
|
+
sys.exit(exc.code)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class OgdCli(click.Group):
|
|
52
|
+
"""Click group that decorates ``--help`` with the live discovery feed.
|
|
53
|
+
|
|
54
|
+
Falls back gracefully if the gateway is unreachable / the cache is empty:
|
|
55
|
+
no extra section in that case, the standard help still renders.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
def get_help(self, ctx: click.Context) -> str:
|
|
59
|
+
original = super().get_help(ctx)
|
|
60
|
+
extra = self._services_help_section()
|
|
61
|
+
return f"{original}\n\n{extra}" if extra else original
|
|
62
|
+
|
|
63
|
+
@staticmethod
|
|
64
|
+
def _services_help_section() -> str | None:
|
|
65
|
+
try:
|
|
66
|
+
feed = fetch_discovery()
|
|
67
|
+
except Exception:
|
|
68
|
+
return None
|
|
69
|
+
community = current_community()
|
|
70
|
+
services = feed.for_community(community)
|
|
71
|
+
if not services:
|
|
72
|
+
return None
|
|
73
|
+
|
|
74
|
+
widths = {"name": max(len(s.service_name) for s in services)}
|
|
75
|
+
rows: list[str] = []
|
|
76
|
+
for s in services:
|
|
77
|
+
desc = (s.description or s.title or "").strip().split("\n", 1)[0]
|
|
78
|
+
if len(desc) > 78:
|
|
79
|
+
desc = desc[:75] + "..."
|
|
80
|
+
rows.append(f" {s.service_name.ljust(widths['name'])} {desc}")
|
|
81
|
+
|
|
82
|
+
first = services[0].service_name
|
|
83
|
+
title = (
|
|
84
|
+
f"Auto-discovered services (community='{community}', "
|
|
85
|
+
f"{len(services)} service{'' if len(services) == 1 else 's'} "
|
|
86
|
+
f"resolved live from the gateway):"
|
|
87
|
+
)
|
|
88
|
+
return (
|
|
89
|
+
f"{title}\n\n"
|
|
90
|
+
+ "\n".join(rows)
|
|
91
|
+
+ "\n\n"
|
|
92
|
+
"Every declared query / path parameter on an operation is exposed\n"
|
|
93
|
+
"as its own --<kebab-case> flag. Use `ad <service> --help` to list\n"
|
|
94
|
+
"operations, then `ad <service> <operation> --help` to see the\n"
|
|
95
|
+
"flags for that operation. For the full spec: `ad schema <service>`.\n"
|
|
96
|
+
"\n"
|
|
97
|
+
"Quickstart:\n"
|
|
98
|
+
f" ad {first} # list operations\n"
|
|
99
|
+
f" ad mailman listMailinglists # anonymous real call\n"
|
|
100
|
+
f" ad mailman retrieveMailinglist --help # flags for one operation\n"
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _format_service(service: ServiceMeta, *, age_s: float | None) -> dict[str, Any]:
|
|
105
|
+
out: dict[str, Any] = {
|
|
106
|
+
"name": service.name,
|
|
107
|
+
"service_name": service.service_name,
|
|
108
|
+
"community": service.community,
|
|
109
|
+
"title": service.title,
|
|
110
|
+
"version": service.version,
|
|
111
|
+
}
|
|
112
|
+
if service.description:
|
|
113
|
+
out["description"] = service.description
|
|
114
|
+
if service.base_url:
|
|
115
|
+
out["base_url"] = service.base_url
|
|
116
|
+
if age_s is not None:
|
|
117
|
+
out["fetched_seconds_ago"] = round(age_s, 1)
|
|
118
|
+
return out
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
@click.group(
|
|
122
|
+
cls=OgdCli,
|
|
123
|
+
context_settings={"help_option_names": ["-h", "--help"]},
|
|
124
|
+
invoke_without_command=True,
|
|
125
|
+
)
|
|
126
|
+
@click.version_option(version=__version__, prog_name="ad")
|
|
127
|
+
@click.option(
|
|
128
|
+
"--no-color",
|
|
129
|
+
is_flag=True,
|
|
130
|
+
default=True,
|
|
131
|
+
help="Disable ANSI colors in output (default: true, AI-friendly).",
|
|
132
|
+
)
|
|
133
|
+
@click.pass_context
|
|
134
|
+
def cli(ctx: click.Context, no_color: bool) -> None:
|
|
135
|
+
"""ad — Ascend Infra command line. Auto-discovered, AI-friendly."""
|
|
136
|
+
ctx.ensure_object(dict)
|
|
137
|
+
ctx.obj["no_color"] = no_color
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
@cli.command("info")
|
|
141
|
+
def info() -> None:
|
|
142
|
+
"""Show gateway reachability and the discovery snapshot summary."""
|
|
143
|
+
import time
|
|
144
|
+
|
|
145
|
+
feed = _resolve_feed(force_refresh=False)
|
|
146
|
+
age = time.time() - feed.fetched_at
|
|
147
|
+
|
|
148
|
+
services = feed.services
|
|
149
|
+
payload = {
|
|
150
|
+
"ok": True,
|
|
151
|
+
"ad_version": __version__,
|
|
152
|
+
"gateway": resolve_gateway(),
|
|
153
|
+
"community": current_community(),
|
|
154
|
+
"services_total": len(services),
|
|
155
|
+
"communities_seen": sorted({s.community for s in services}),
|
|
156
|
+
"cache": {
|
|
157
|
+
"ttl_seconds": CACHE_TTL_SECONDS,
|
|
158
|
+
"stale": age >= CACHE_TTL_SECONDS,
|
|
159
|
+
"fetched_seconds_ago": round(age, 1),
|
|
160
|
+
"fetched_at_iso": dt.datetime.fromtimestamp(
|
|
161
|
+
feed.fetched_at, tz=dt.timezone.utc
|
|
162
|
+
).isoformat(),
|
|
163
|
+
},
|
|
164
|
+
}
|
|
165
|
+
_print_json(payload)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
@cli.command("services")
|
|
169
|
+
@click.option("--community", default=None, help="Limit to one community (default: current).")
|
|
170
|
+
@click.option("--refresh", is_flag=True, help="Force re-fetch the discovery feed first.")
|
|
171
|
+
def services_cmd(community: str | None, refresh: bool) -> None:
|
|
172
|
+
"""List services in the discovery feed."""
|
|
173
|
+
import time
|
|
174
|
+
|
|
175
|
+
feed = _resolve_feed(force_refresh=refresh)
|
|
176
|
+
target = community or current_community()
|
|
177
|
+
items = [s for s in feed.services if s.community == target]
|
|
178
|
+
age = time.time() - feed.fetched_at
|
|
179
|
+
_print_json([_format_service(s, age_s=age) for s in items])
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
@cli.command("schema")
|
|
183
|
+
@click.argument("target")
|
|
184
|
+
@click.option("--refresh", is_flag=True, help="Force re-fetch the discovery feed first.")
|
|
185
|
+
def schema_cmd(target: str, refresh: bool) -> None:
|
|
186
|
+
"""Print OpenAPI 3.x spec for SERVICE[.METHOD] from the current community."""
|
|
187
|
+
if "." in target:
|
|
188
|
+
service_name, method = target.split(".", 1)
|
|
189
|
+
else:
|
|
190
|
+
service_name, method = target, None
|
|
191
|
+
|
|
192
|
+
feed = _resolve_feed(force_refresh=refresh)
|
|
193
|
+
community = current_community()
|
|
194
|
+
try:
|
|
195
|
+
service = feed.find_service(community, service_name)
|
|
196
|
+
except OgdError as exc:
|
|
197
|
+
_print_json(exc.to_dict(), error=True)
|
|
198
|
+
sys.exit(exc.code)
|
|
199
|
+
|
|
200
|
+
try:
|
|
201
|
+
spec = fetch_spec(service)
|
|
202
|
+
except OgdError as exc:
|
|
203
|
+
_print_json(exc.to_dict(), error=True)
|
|
204
|
+
sys.exit(exc.code)
|
|
205
|
+
|
|
206
|
+
if method is None:
|
|
207
|
+
_print_json(spec)
|
|
208
|
+
return
|
|
209
|
+
|
|
210
|
+
paths: dict[str, Any] = spec.get("paths", {})
|
|
211
|
+
matches: list[dict[str, Any]] = []
|
|
212
|
+
for path, item in paths.items():
|
|
213
|
+
for verb, op in item.items():
|
|
214
|
+
if verb.lower() not in {"get", "post", "put", "patch", "delete", "head", "options"}:
|
|
215
|
+
continue
|
|
216
|
+
if op.get("operationId") == method or method in (path, f"{verb.upper()} {path}"):
|
|
217
|
+
matches.append({"path": path, "method": verb.upper(), "operation": op})
|
|
218
|
+
if not matches:
|
|
219
|
+
_print_json(
|
|
220
|
+
{
|
|
221
|
+
"ok": False,
|
|
222
|
+
"code": 4,
|
|
223
|
+
"error": "method_not_found",
|
|
224
|
+
"message": f"no path matches method '{method}' on service '{service_name}'",
|
|
225
|
+
"available_paths": sorted(paths.keys()),
|
|
226
|
+
},
|
|
227
|
+
error=True,
|
|
228
|
+
)
|
|
229
|
+
sys.exit(4)
|
|
230
|
+
|
|
231
|
+
_print_json({"service": service.name, "matches": matches})
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
@cli.group()
|
|
235
|
+
def cache() -> None:
|
|
236
|
+
"""Manage the local discovery cache."""
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
@cache.command("show")
|
|
240
|
+
def cache_show() -> None:
|
|
241
|
+
from .discovery import _cache_path
|
|
242
|
+
|
|
243
|
+
p = _cache_path()
|
|
244
|
+
if not p.is_file():
|
|
245
|
+
_print_json({"cached": False, "path": str(p)})
|
|
246
|
+
return
|
|
247
|
+
stat = p.stat()
|
|
248
|
+
_print_json(
|
|
249
|
+
{
|
|
250
|
+
"cached": True,
|
|
251
|
+
"path": str(p),
|
|
252
|
+
"size_bytes": stat.st_size,
|
|
253
|
+
"modified_iso": dt.datetime.fromtimestamp(
|
|
254
|
+
stat.st_mtime, tz=dt.timezone.utc
|
|
255
|
+
).isoformat(),
|
|
256
|
+
"ttl_seconds": CACHE_TTL_SECONDS,
|
|
257
|
+
}
|
|
258
|
+
)
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
@cache.command("clear")
|
|
262
|
+
def cache_clear() -> None:
|
|
263
|
+
from .discovery import _cache_path
|
|
264
|
+
|
|
265
|
+
p = _cache_path()
|
|
266
|
+
if p.is_file():
|
|
267
|
+
p.unlink()
|
|
268
|
+
_print_json({"ok": True, "cleared": str(p)})
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
@cache.command("refresh")
|
|
272
|
+
def cache_refresh() -> None:
|
|
273
|
+
feed = fetch_discovery(community=None, force_refresh=True)
|
|
274
|
+
_print_json({"ok": True, "services_total": len(feed.services)})
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
if __name__ == "__main__":
|
|
278
|
+
cli()
|