grape-cli 0.3.4__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.
- grape_cli/__init__.py +2 -0
- grape_cli/__main__.py +7 -0
- grape_cli/cli.py +354 -0
- grape_cli/client.py +397 -0
- grape_cli/commands/__init__.py +0 -0
- grape_cli/commands/doctor.py +324 -0
- grape_cli/commands/git.py +137 -0
- grape_cli/config.py +221 -0
- grape_cli/contracts.py +281 -0
- grape_cli/data/examples.json +85 -0
- grape_cli/data/openapi.json +1 -0
- grape_cli/data/token-scope.json +17 -0
- grape_cli/registry.py +1193 -0
- grape_cli/update_check.py +290 -0
- grape_cli-0.3.4.dist-info/METADATA +274 -0
- grape_cli-0.3.4.dist-info/RECORD +20 -0
- grape_cli-0.3.4.dist-info/WHEEL +5 -0
- grape_cli-0.3.4.dist-info/entry_points.txt +2 -0
- grape_cli-0.3.4.dist-info/licenses/LICENSE +21 -0
- grape_cli-0.3.4.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
"""grape doctor:一站式环境自检(Issue #2662)。
|
|
2
|
+
|
|
3
|
+
五类独立检查,每项返回 ``{name, status: OK|WARN|FAIL, detail, hint}``:
|
|
4
|
+
|
|
5
|
+
- ``token-channels`` 三通道(GRAPE_SESSION_TOKEN tk_ / GRAPE_API_TOKEN grape_ / GRAPE_AUTH_FILE):
|
|
6
|
+
全未配置 → WARN(附配置指引,可选通道缺一不等于环境坏);已配置但失效(401)→ FAIL。
|
|
7
|
+
GRAPE_AUTH_FILE 配置但不可读:无任何回退通道 → FAIL(配置已失效);回退通道验证可用 →
|
|
8
|
+
WARN(口径见 check_token_channels:功能正常的环境不应被死配置打成 exit 1)。
|
|
9
|
+
通道归集复用 config.effective_token_channel(与 config.resolve 同一优先级链,含
|
|
10
|
+
DSH_GRAPE_SESSION_TOKEN / GRAPE_CLI_MODE / config.json token,防止分叉误报「无通道」)。
|
|
11
|
+
- ``base-url`` 报告实际生效值(--base-url > GRAPE_BASE_URL > GRAPE_SERVER_URL > config.json > 默认)
|
|
12
|
+
并探活(/api/health → 404 回退 /openapi.json);超时/不可达 → WARN——断网不误报 FAIL、不阻断自检。
|
|
13
|
+
来源与生效值复用 config.resolve_with_source(单一事实源,不再私有穿透重推导优先级链)。
|
|
14
|
+
- ``proxy-env`` 复用 #2252 sanitize 口径做「检查不改写」:未知 scheme / socks 缺 socksio →
|
|
15
|
+
WARN 并点名变量(请求期会被自动忽略,不崩溃)。
|
|
16
|
+
- ``contract-cache`` 复用 #2438 校验口径(contracts.validate_cache 公开接口):文件名版本 ≠ 内容版本
|
|
17
|
+
(伪高版污染)→ FAIL + ``grape refresh`` 指引(refresh 自愈清理);无缓存 → WARN;健康 → OK(附版本)。
|
|
18
|
+
- ``cli-version`` 本机 __version__ vs GitCode tags 最新(与 #2661 共用数据源);更新可用/离线 → WARN。
|
|
19
|
+
|
|
20
|
+
退出码:全 OK/WARN → 0;任一 FAIL → 1(worker 部署后可作为标准验证动作)。
|
|
21
|
+
doctor 只诊断 + 指引,不自动修复、不改写用户配置。
|
|
22
|
+
"""
|
|
23
|
+
import json
|
|
24
|
+
import os
|
|
25
|
+
|
|
26
|
+
import click
|
|
27
|
+
import httpx
|
|
28
|
+
|
|
29
|
+
from grape_cli import __version__, config
|
|
30
|
+
from grape_cli.client import ApiClient, CliError, _proxy_scheme, _socks_supported
|
|
31
|
+
from grape_cli.contracts import validate_cache, version_key
|
|
32
|
+
|
|
33
|
+
# 版本对比数据源(与 #2661 启动检查共用):GitCode 公开 tags API——
|
|
34
|
+
# releases/latest 停在 v0.3.2-pre(发 release 不及时),tags 始终随发布推进,取其最新。
|
|
35
|
+
_TAGS_URL = "https://api.gitcode.com/api/v5/repos/grape-dev/grape-cli/tags"
|
|
36
|
+
|
|
37
|
+
# 探活/校验超时:doctor 是自检入口,网络面(探活 + token 校验 + 版本)各自独立短超时,
|
|
38
|
+
# 任一超时降级 WARN,不让单点网络抖动拖垮整轮自检。
|
|
39
|
+
_PROBE_TIMEOUT = 10
|
|
40
|
+
|
|
41
|
+
_HEALTH_PATHS = ("/api/health", "/openapi.json")
|
|
42
|
+
|
|
43
|
+
# token 校验端点:session 域轻量端点;grape_ 用户钥在此 403 = 有效但作用域受限,不算失效。
|
|
44
|
+
_TOKEN_PROBE_PATH = "/api/tasks/current"
|
|
45
|
+
|
|
46
|
+
_PROXY_VAR_NAMES = ("http_proxy", "https_proxy", "all_proxy")
|
|
47
|
+
_SUPPORTED_PROXY_SCHEMES = ("http", "https", "socks", "socks5", "socks5h")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _result(name: str, status: str, detail: str, hint: str = "") -> dict:
|
|
51
|
+
return {"name": name, "status": status, "detail": detail, "hint": hint}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def check_token_channels(env=None) -> dict:
|
|
55
|
+
"""token 通道检查:未配置 WARN / 配置失效 FAIL / 作用域受限 OK。
|
|
56
|
+
|
|
57
|
+
归集复用 ``config.effective_token_channel``(与 ``config.resolve`` 同一优先级链,
|
|
58
|
+
覆盖 DSH_GRAPE_SESSION_TOKEN / GRAPE_CLI_MODE / config.json,防止分叉误报「无通道」)。
|
|
59
|
+
|
|
60
|
+
GRAPE_AUTH_FILE 配置但不可读的口径(QA Spec (c) 确认):
|
|
61
|
+
- 无任何回退通道 → FAIL(配置已失效,通道形同虚设);
|
|
62
|
+
- 回退通道验证可用 → WARN(功能正常的环境不应被死配置打成 exit 1,降级警示并点名);
|
|
63
|
+
- 回退通道也 401 → FAIL(两条通道都不可用,环境确实坏)。
|
|
64
|
+
"""
|
|
65
|
+
env = os.environ if env is None else env
|
|
66
|
+
configured = {name: (env.get(name) or "").strip()
|
|
67
|
+
for name in ("GRAPE_SESSION_TOKEN", "GRAPE_API_TOKEN", "GRAPE_AUTH_FILE")}
|
|
68
|
+
configured = {k: v for k, v in configured.items() if v}
|
|
69
|
+
token, channel = config.effective_token_channel(env=env, cfg=config.load_file_config())
|
|
70
|
+
if not token and not configured:
|
|
71
|
+
return _result(
|
|
72
|
+
"token-channels", "WARN",
|
|
73
|
+
"no token channel configured (GRAPE_SESSION_TOKEN / GRAPE_API_TOKEN / GRAPE_AUTH_FILE)",
|
|
74
|
+
"export GRAPE_SESSION_TOKEN=<tk_...> (task token), GRAPE_API_TOKEN=<grape_...> "
|
|
75
|
+
"(user key), or point GRAPE_AUTH_FILE at a token file; see `grape --help`",
|
|
76
|
+
)
|
|
77
|
+
# auth 文件在报告范围内配置了,但实际生效通道不是它 → 文件不可读/为空
|
|
78
|
+
auth_bad = "GRAPE_AUTH_FILE" in configured and channel != "GRAPE_AUTH_FILE"
|
|
79
|
+
if not token:
|
|
80
|
+
# auth 文件不可读且无任何回退通道 → 配置已失效
|
|
81
|
+
return _result(
|
|
82
|
+
"token-channels", "FAIL",
|
|
83
|
+
f"GRAPE_AUTH_FILE={configured['GRAPE_AUTH_FILE']!r} is set but unreadable or empty; "
|
|
84
|
+
"no other token channel available",
|
|
85
|
+
"re-export a valid token file path (re-run the session) or unset GRAPE_AUTH_FILE "
|
|
86
|
+
"and export GRAPE_SESSION_TOKEN / GRAPE_API_TOKEN",
|
|
87
|
+
)
|
|
88
|
+
base_url, _ = config.resolve()
|
|
89
|
+
kind = "session (tk_)" if token.startswith("tk_") else (
|
|
90
|
+
"user key (grape_)" if token.startswith("grape_") else "unrecognized prefix")
|
|
91
|
+
|
|
92
|
+
def _auth_bad_note() -> str:
|
|
93
|
+
return (f"; but GRAPE_AUTH_FILE={configured['GRAPE_AUTH_FILE']!r} is set but "
|
|
94
|
+
"unreadable or empty (fell back to the channel above)")
|
|
95
|
+
|
|
96
|
+
try:
|
|
97
|
+
api = ApiClient(base_url=base_url, token=token, timeout=_PROBE_TIMEOUT)
|
|
98
|
+
status, _data = api.request("GET", _TOKEN_PROBE_PATH)
|
|
99
|
+
if status == 401:
|
|
100
|
+
return _result(
|
|
101
|
+
"token-channels", "FAIL",
|
|
102
|
+
f"channel {channel} ({kind}) rejected: 401 invalid or expired",
|
|
103
|
+
"re-inject the token: re-export GRAPE_SESSION_TOKEN / GRAPE_API_TOKEN "
|
|
104
|
+
"(or refresh the auth file)",
|
|
105
|
+
)
|
|
106
|
+
scope_note = "" if status == 200 else (
|
|
107
|
+
f" (probe endpoint returned {status}: token recognized, scope-limited)")
|
|
108
|
+
if auth_bad:
|
|
109
|
+
# Spec (c):回退通道验证可用 → WARN,不因死 auth-file 配置误报 FAIL 阻断 exit 1
|
|
110
|
+
return _result(
|
|
111
|
+
"token-channels", "WARN",
|
|
112
|
+
f"effective channel: {channel} ({kind}); validated against {_TOKEN_PROBE_PATH}"
|
|
113
|
+
f"{scope_note}{_auth_bad_note()}",
|
|
114
|
+
"fix or unset the stale GRAPE_AUTH_FILE so the auth-file channel works again",
|
|
115
|
+
)
|
|
116
|
+
return _result(
|
|
117
|
+
"token-channels", "OK",
|
|
118
|
+
f"effective channel: {channel} ({kind}); validated against {_TOKEN_PROBE_PATH}{scope_note}",
|
|
119
|
+
)
|
|
120
|
+
except CliError as e:
|
|
121
|
+
if e.code == 401:
|
|
122
|
+
return _result(
|
|
123
|
+
"token-channels", "FAIL",
|
|
124
|
+
f"channel {channel} ({kind}) rejected: token invalid or expired",
|
|
125
|
+
"re-inject the token: re-export GRAPE_SESSION_TOKEN / GRAPE_API_TOKEN "
|
|
126
|
+
"(or refresh the auth file)",
|
|
127
|
+
)
|
|
128
|
+
if e.code in (403, 404, 405):
|
|
129
|
+
# 403=作用域受限、404/405=探针端点不在该服务端版本——token 本身未被鉴权层拒绝
|
|
130
|
+
if auth_bad:
|
|
131
|
+
return _result(
|
|
132
|
+
"token-channels", "WARN",
|
|
133
|
+
f"effective channel: {channel} ({kind}); probe {_TOKEN_PROBE_PATH} returned "
|
|
134
|
+
f"{e.code} (token not rejected; scope/endpoint limited){_auth_bad_note()}",
|
|
135
|
+
"fix or unset the stale GRAPE_AUTH_FILE so the auth-file channel works again",
|
|
136
|
+
)
|
|
137
|
+
return _result(
|
|
138
|
+
"token-channels", "OK",
|
|
139
|
+
f"effective channel: {channel} ({kind}); probe {_TOKEN_PROBE_PATH} returned "
|
|
140
|
+
f"{e.code} (token not rejected; scope/endpoint limited)",
|
|
141
|
+
)
|
|
142
|
+
return _result(
|
|
143
|
+
"token-channels", "WARN",
|
|
144
|
+
f"channel {channel} ({kind}) configured but could not validate (offline?): {e}"
|
|
145
|
+
+ (_auth_bad_note() if auth_bad else ""),
|
|
146
|
+
"check connectivity with `grape doctor` again once the network is back",
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def check_base_url() -> dict:
|
|
151
|
+
"""base_url 检查:报告实际生效值(含来源)+ 探活(网络失败 WARN 不误报 FAIL)。
|
|
152
|
+
|
|
153
|
+
实际生效值与来源复用 ``config.resolve_with_source``(单一事实源;
|
|
154
|
+
QA Standards 2:不再私有穿透 config._CLI_PARAMS / load_file_config 重推导优先级链)。
|
|
155
|
+
"""
|
|
156
|
+
base_url, source, _token = config.resolve_with_source()
|
|
157
|
+
last_err = ""
|
|
158
|
+
for path in _HEALTH_PATHS:
|
|
159
|
+
try:
|
|
160
|
+
api = ApiClient(base_url=base_url, token="", timeout=_PROBE_TIMEOUT,
|
|
161
|
+
require_token=False)
|
|
162
|
+
status, _data = api.request("GET", path)
|
|
163
|
+
if status == 200:
|
|
164
|
+
return _result(
|
|
165
|
+
"base-url", "OK",
|
|
166
|
+
f"{base_url} (source: {source}); probe {path}: ok",
|
|
167
|
+
)
|
|
168
|
+
last_err = f"probe {path} returned HTTP {status}"
|
|
169
|
+
except CliError as e:
|
|
170
|
+
if e.code == 404:
|
|
171
|
+
last_err = f"probe {path} returned 404"
|
|
172
|
+
continue
|
|
173
|
+
return _result(
|
|
174
|
+
"base-url", "WARN",
|
|
175
|
+
f"{base_url} (source: {source}); unreachable: {e}",
|
|
176
|
+
"check the URL/network, or override with --base-url / GRAPE_BASE_URL; "
|
|
177
|
+
"offline environments can ignore this if only version data is unreachable",
|
|
178
|
+
)
|
|
179
|
+
return _result(
|
|
180
|
+
"base-url", "WARN",
|
|
181
|
+
f"{base_url} (source: {source}); {last_err}",
|
|
182
|
+
"no health endpoint answered; is this a grape server? (expected /api/health)",
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def check_proxy_env(env=None) -> dict:
|
|
187
|
+
"""代理环境变量形态检查(#2252 口径):只检查不改写,未知 scheme 点名变量 → WARN。"""
|
|
188
|
+
env = os.environ if env is None else env
|
|
189
|
+
if not config.trust_env():
|
|
190
|
+
return _result(
|
|
191
|
+
"proxy-env", "OK",
|
|
192
|
+
"proxies bypassed (--no-proxy / GRAPE_TRUST_ENV=0): connecting directly",
|
|
193
|
+
)
|
|
194
|
+
issues = []
|
|
195
|
+
seen = []
|
|
196
|
+
for name in _PROXY_VAR_NAMES + tuple(n.upper() for n in _PROXY_VAR_NAMES):
|
|
197
|
+
value = (env.get(name) or "").strip()
|
|
198
|
+
if not value:
|
|
199
|
+
continue
|
|
200
|
+
seen.append(f"{name}={value}")
|
|
201
|
+
scheme = _proxy_scheme(value)
|
|
202
|
+
if scheme and scheme not in _SUPPORTED_PROXY_SCHEMES:
|
|
203
|
+
issues.append(
|
|
204
|
+
f"{name}: unsupported scheme {scheme!r} (ignored at request time; "
|
|
205
|
+
"supported: http, https, socks5)")
|
|
206
|
+
elif scheme in ("socks", "socks5", "socks5h") and not _socks_supported():
|
|
207
|
+
issues.append(
|
|
208
|
+
f"{name}: socks proxy needs the 'socksio' package "
|
|
209
|
+
"(pip install 'httpx[socks]'); ignored at request time")
|
|
210
|
+
if issues:
|
|
211
|
+
return _result(
|
|
212
|
+
"proxy-env", "WARN", "; ".join(issues),
|
|
213
|
+
"fix or unset the offending *_proxy variable(s), or bypass with --no-proxy",
|
|
214
|
+
)
|
|
215
|
+
if not seen:
|
|
216
|
+
return _result("proxy-env", "OK", "no proxy variables configured")
|
|
217
|
+
return _result(
|
|
218
|
+
"proxy-env", "OK",
|
|
219
|
+
f"{len(seen)} proxy variable(s), all forms supported at request time",
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def check_contract_cache() -> dict:
|
|
224
|
+
"""契约缓存健康(#2438 口径):校验复用 contracts.validate_cache 公开接口,
|
|
225
|
+
污染/不可读 → FAIL + grape refresh 指引;无缓存 → WARN。"""
|
|
226
|
+
report = validate_cache()
|
|
227
|
+
if not report["files"]:
|
|
228
|
+
return _result(
|
|
229
|
+
"contract-cache", "WARN",
|
|
230
|
+
f"no contract cache in {config.CONFIG_DIR} (first run or offline)",
|
|
231
|
+
"run `grape refresh` to fetch and cache the latest contract",
|
|
232
|
+
)
|
|
233
|
+
if report["polluted"] or report["unreadable"]:
|
|
234
|
+
parts = report["polluted"] + [f"{n}: unreadable JSON" for n in report["unreadable"]]
|
|
235
|
+
return _result(
|
|
236
|
+
"contract-cache", "FAIL", "; ".join(parts),
|
|
237
|
+
"run `grape refresh` — it validates content version and cleans polluted caches",
|
|
238
|
+
)
|
|
239
|
+
return _result(
|
|
240
|
+
"contract-cache", "OK",
|
|
241
|
+
f"{len(report['files'])} cache file(s), latest v{_fmt(report['latest_key'])}",
|
|
242
|
+
)
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _fmt(key: tuple) -> str:
|
|
246
|
+
return ".".join(str(p) for p in key) if key != (0,) else "unknown"
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _fetch_latest_tag() -> str:
|
|
250
|
+
"""拉取 GitCode 公开 tags 的最新版本 tag(如 'v0.3.3');失败抛异常由调用方降级 WARN。"""
|
|
251
|
+
r = httpx.get(_TAGS_URL, timeout=_PROBE_TIMEOUT)
|
|
252
|
+
r.raise_for_status()
|
|
253
|
+
names = [str(t.get("name") or "").lstrip("v") for t in r.json() if t.get("name")]
|
|
254
|
+
if not names:
|
|
255
|
+
raise CliError("no tags returned by " + _TAGS_URL)
|
|
256
|
+
return "v" + max(names, key=version_key)
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def check_cli_version() -> dict:
|
|
260
|
+
"""版本对比(与 #2661 共用数据源):更新可用 / 离线 → WARN,不误报 FAIL。"""
|
|
261
|
+
try:
|
|
262
|
+
latest = _fetch_latest_tag().lstrip("v")
|
|
263
|
+
except Exception as e:
|
|
264
|
+
return _result(
|
|
265
|
+
"cli-version", "WARN",
|
|
266
|
+
f"local {__version__}; could not check latest (offline?): {e}",
|
|
267
|
+
"check for updates manually: https://gitcode.com/grape-dev/grape-cli/tags",
|
|
268
|
+
)
|
|
269
|
+
if version_key(__version__) >= version_key(latest):
|
|
270
|
+
note = "up to date" if version_key(__version__) == version_key(latest) else \
|
|
271
|
+
"local is newer than the latest published tag (dev build?)"
|
|
272
|
+
return _result("cli-version", "OK", f"local {__version__} / latest v{latest}: {note}")
|
|
273
|
+
return _result(
|
|
274
|
+
"cli-version", "WARN",
|
|
275
|
+
f"local {__version__} is older than latest v{latest}",
|
|
276
|
+
"upgrade: git pull && pip install -e . (or pip install --upgrade grape-cli "
|
|
277
|
+
"once published), see README install section",
|
|
278
|
+
)
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def run_checks() -> list[dict]:
|
|
282
|
+
"""跑全部五项检查(顺序即输出顺序)。"""
|
|
283
|
+
return [
|
|
284
|
+
check_token_channels(),
|
|
285
|
+
check_base_url(),
|
|
286
|
+
check_proxy_env(),
|
|
287
|
+
check_contract_cache(),
|
|
288
|
+
check_cli_version(),
|
|
289
|
+
]
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _print_human(results: list[dict]) -> None:
|
|
293
|
+
width = max(len(r["name"]) for r in results)
|
|
294
|
+
for r in results:
|
|
295
|
+
click.echo(f"{r['name']:<{width}} {r['status']:<4} {r['detail']}")
|
|
296
|
+
if r["hint"]:
|
|
297
|
+
click.echo(f"{'':<{width}} hint: {r['hint']}")
|
|
298
|
+
failed = [r for r in results if r["status"] == "FAIL"]
|
|
299
|
+
warned = [r for r in results if r["status"] == "WARN"]
|
|
300
|
+
if failed:
|
|
301
|
+
click.echo(f"doctor: {len(failed)} failed, {len(warned)} warning(s)")
|
|
302
|
+
else:
|
|
303
|
+
click.echo(f"doctor: all checks passed ({len(warned)} warning(s))")
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def doctor_command() -> click.Command:
|
|
307
|
+
"""grape doctor:一站式环境自检(只诊断 + 指引,不自动修复)。"""
|
|
308
|
+
|
|
309
|
+
@click.command(name="doctor",
|
|
310
|
+
help="One-shot environment self-check: token channels, base_url probe, "
|
|
311
|
+
"proxy env, contract cache, CLI version (OK/WARN/FAIL + hints; "
|
|
312
|
+
"exit 1 on any FAIL)")
|
|
313
|
+
@click.option("--json-out", is_flag=True, help="machine-readable JSON output")
|
|
314
|
+
def _doctor(json_out: bool):
|
|
315
|
+
results = run_checks()
|
|
316
|
+
if json_out:
|
|
317
|
+
click.echo(json.dumps(results, ensure_ascii=False))
|
|
318
|
+
else:
|
|
319
|
+
_print_human(results)
|
|
320
|
+
if any(r["status"] == "FAIL" for r in results):
|
|
321
|
+
# click.exceptions.Exit 在 standalone/非 standalone 两模式下都正确落到退出码
|
|
322
|
+
raise click.exceptions.Exit(1)
|
|
323
|
+
|
|
324
|
+
return _doctor
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""grape git 本地执行(方案③):git 原生命令透传 + 进程内凭据注入(token 零暴露)。
|
|
2
|
+
|
|
3
|
+
- 裸用自动识别仓库(docs/grape-git-auto-detect-design.md):
|
|
4
|
+
- clone:从 URL 参数解析 owner/repo(此时 cwd 尚无 .git);
|
|
5
|
+
- 其他:从当前目录 `remote.origin.url` 解析。
|
|
6
|
+
- 识别到 gitcode / github 仓库 → `GET /api/repos/{o}/{r}/git-credential` 换券,仅以 GIT_CONFIG env
|
|
7
|
+
注入 git 子进程(不进命令行、不落磁盘、宿主非白名单一律不注入)。
|
|
8
|
+
- 换券失败**降级**:仅 stderr 警告,不阻塞本地命令;远端操作按 git 原生结果。
|
|
9
|
+
- `--help`/`-h`/`help`:直接透传 git(与 `git --help` 一致,docs/grape-git-help-design.md)。
|
|
10
|
+
"""
|
|
11
|
+
import os
|
|
12
|
+
import shutil
|
|
13
|
+
import subprocess
|
|
14
|
+
import sys
|
|
15
|
+
from urllib.parse import urlsplit
|
|
16
|
+
|
|
17
|
+
import click
|
|
18
|
+
|
|
19
|
+
from grape_cli.client import ApiClient, CliError, basic_auth
|
|
20
|
+
|
|
21
|
+
_GITCODE_HOSTS = frozenset({"gitcode.com", "www.gitcode.com"})
|
|
22
|
+
_GITHUB_HOSTS = frozenset({"github.com", "www.github.com"})
|
|
23
|
+
# 平台支持白名单:gitcode + github(含 www 变体);换券按 host 命中后才注入,
|
|
24
|
+
# 防止 http.extraheader 把平台 token 发给第三方 host(见 Issue #433)。
|
|
25
|
+
_SUPPORTED_HOSTS = _GITCODE_HOSTS | _GITHUB_HOSTS
|
|
26
|
+
|
|
27
|
+
_EXTRA_HEADER = "http.extraheader"
|
|
28
|
+
|
|
29
|
+
# 无需凭据的顶层参数(帮助/版本类),跳过注入
|
|
30
|
+
_NO_CRED_CMD = frozenset({"help", "--help", "-h"})
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _repo_from_url(url: str) -> str:
|
|
34
|
+
"""从 git URL 解析 owner/repo(gitcode / github 形态),不匹配返回空串。
|
|
35
|
+
|
|
36
|
+
支持:https://gitcode.com/o/r.git / git@gitcode.com:o/r.git / ssh://git@gitcode.com/o/r.git
|
|
37
|
+
以及 https://github.com/o/r.git / git@github.com:o/r.git / ssh://git@github.com/o/r.git
|
|
38
|
+
"""
|
|
39
|
+
url = (url or "").strip()
|
|
40
|
+
if not url:
|
|
41
|
+
return ""
|
|
42
|
+
if "://" not in url and ":" in url and "/" not in url.split(":", 1)[0]:
|
|
43
|
+
# scp-like:git@host:o/r.git
|
|
44
|
+
host = url.split(":", 1)[0].split("@")[-1]
|
|
45
|
+
path = url.split(":", 1)[1]
|
|
46
|
+
else:
|
|
47
|
+
u = urlsplit(url)
|
|
48
|
+
host = u.hostname or ""
|
|
49
|
+
path = u.path
|
|
50
|
+
if host.lower() not in _SUPPORTED_HOSTS:
|
|
51
|
+
return ""
|
|
52
|
+
path = path.strip("/")
|
|
53
|
+
if path.endswith(".git"):
|
|
54
|
+
path = path[: -len(".git")]
|
|
55
|
+
parts = [p for p in path.split("/") if p]
|
|
56
|
+
if len(parts) >= 2:
|
|
57
|
+
return f"{parts[0]}/{parts[1]}"
|
|
58
|
+
return ""
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _repo_from_cwd(cwd: str | None = None) -> str:
|
|
62
|
+
"""读当前仓库 remote.origin.url 解析 owner/repo(子目录内也能取到)。"""
|
|
63
|
+
try:
|
|
64
|
+
out = subprocess.check_output(
|
|
65
|
+
["git", "config", "--get", "remote.origin.url"],
|
|
66
|
+
cwd=cwd, stderr=subprocess.DEVNULL, text=True, timeout=10,
|
|
67
|
+
)
|
|
68
|
+
except Exception:
|
|
69
|
+
return ""
|
|
70
|
+
return _repo_from_url(out.strip())
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _repo_from_args(args: list[str], cwd: str | None = None) -> str:
|
|
74
|
+
"""决定换券目标:clone 由 URL 解析,其他由 cwd origin 解析。"""
|
|
75
|
+
if args and args[0] == "clone":
|
|
76
|
+
for a in args[1:]:
|
|
77
|
+
r = _repo_from_url(a)
|
|
78
|
+
if r:
|
|
79
|
+
return r
|
|
80
|
+
return ""
|
|
81
|
+
return _repo_from_cwd(cwd)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _inject_git_credentials(owner_repo: str, env: dict) -> None:
|
|
85
|
+
"""换券并注入 http.extraheader 到子进程 env;凭据缺字段抛 CliError。"""
|
|
86
|
+
api = ApiClient()
|
|
87
|
+
_s, cred = api.request("GET", f"/api/repos/{owner_repo}/git-credential")
|
|
88
|
+
username = cred.get("username")
|
|
89
|
+
password = cred.get("password")
|
|
90
|
+
if not username or not password:
|
|
91
|
+
raise CliError(
|
|
92
|
+
f"server git-credential response missing username/password (repo {owner_repo})"
|
|
93
|
+
)
|
|
94
|
+
idx = int(env.get("GIT_CONFIG_COUNT") or 0)
|
|
95
|
+
env["GIT_CONFIG_COUNT"] = str(idx + 1)
|
|
96
|
+
env[f"GIT_CONFIG_KEY_{idx}"] = _EXTRA_HEADER
|
|
97
|
+
env[f"GIT_CONFIG_VALUE_{idx}"] = f"Authorization: {basic_auth(username, password)}"
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def git_command() -> click.Command:
|
|
101
|
+
@click.command(
|
|
102
|
+
name="git",
|
|
103
|
+
help="Run git locally: passthrough any native git command (credentials auto-injected in-process)",
|
|
104
|
+
context_settings=dict(ignore_unknown_options=True, allow_extra_args=True),
|
|
105
|
+
add_help_option=False,
|
|
106
|
+
)
|
|
107
|
+
@click.pass_context
|
|
108
|
+
def git_cmd(ctx):
|
|
109
|
+
if not shutil.which("git"):
|
|
110
|
+
raise click.ClickException("git executable not found")
|
|
111
|
+
|
|
112
|
+
env = dict(os.environ)
|
|
113
|
+
args = list(ctx.args)
|
|
114
|
+
# 帮助/版本类:纯透传,不做换券注入
|
|
115
|
+
if not (args and args[0] in _NO_CRED_CMD):
|
|
116
|
+
owner_repo = _repo_from_args(args)
|
|
117
|
+
if owner_repo:
|
|
118
|
+
try:
|
|
119
|
+
_inject_git_credentials(owner_repo, env)
|
|
120
|
+
except CliError as e:
|
|
121
|
+
click.echo(
|
|
122
|
+
f"warning: grape git credential injection failed ({e}); "
|
|
123
|
+
"falling back to native git behavior",
|
|
124
|
+
err=True,
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
cmd = ["git"] + args
|
|
128
|
+
try:
|
|
129
|
+
r = subprocess.run(cmd, env=env)
|
|
130
|
+
except KeyboardInterrupt:
|
|
131
|
+
# Ctrl+C 时 git 与 CLI 同控制组已收到中断;拉起主入口统一 130 收口
|
|
132
|
+
raise
|
|
133
|
+
except OSError as e:
|
|
134
|
+
raise click.ClickException(f"git execution failed: {e}")
|
|
135
|
+
sys.exit(r.returncode)
|
|
136
|
+
|
|
137
|
+
return git_cmd
|
grape_cli/config.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
"""配置解析:CLI 参数 > 环境变量 > ~/.grape/config.json。
|
|
2
|
+
|
|
3
|
+
token 优先级:--token 参数 > `GRAPE_SESSION_TOKEN`(任务级临时 token,worker 优先)> `GRAPE_API_TOKEN`(用户级)> config.json。
|
|
4
|
+
|
|
5
|
+
`GRAPE_AUTH_FILE`(由 DshRuntime.get_env 写入,指向一个 0600 临时文件)在所有模式下
|
|
6
|
+
优先于环境变量:dsh 的 subprocess 服务会 scrub 掉名字匹配 /KEY|PASSWORD|SECRET|TOKEN/i
|
|
7
|
+
的父进程变量,GRAPE_SESSION_TOKEN 命中 TOKEN → 被洗掉 → bash 里拿不到。
|
|
8
|
+
DshRuntime 把 token 值写到临时文件,路径通过 GRAPE_AUTH_FILE(不命中 scrub)传递;
|
|
9
|
+
grape CLI 从文件读 token 值,完全绕过 env scrub。
|
|
10
|
+
其他引擎不做此 scrub,GRAPE_AUTH_FILE 不存在 → fallback 到 GRAPE_SESSION_TOKEN,零影响。
|
|
11
|
+
|
|
12
|
+
`DSH_GRAPE_SESSION_TOKEN`(由 dsh-grape 插件的 shellEnv contributor 注入)同样优先于
|
|
13
|
+
`GRAPE_SESSION_TOKEN`,作为插件层的备选穿透路径(目前 headless 不加载插件,此路径不生效)。
|
|
14
|
+
"""
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
CONFIG_DIR = Path.home() / ".grape"
|
|
20
|
+
CONFIG_FILE = CONFIG_DIR / "config.json"
|
|
21
|
+
|
|
22
|
+
DEFAULT_TIMEOUT = 30 # 秒
|
|
23
|
+
|
|
24
|
+
# 本次进程的 CLI 一次性参数(--base-url / --token / --timeout / --no-proxy),优先级最高,不落盘
|
|
25
|
+
_CLI_PARAMS = {"base_url": "", "token": "", "timeout": 0, "no_proxy": False}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def set_cli_params(base_url: str = "", token: str = "", timeout: int = 0,
|
|
29
|
+
no_proxy: bool = False):
|
|
30
|
+
"""记录本次调用 `grape --base-url/--token/--timeout/--no-proxy ...` 的一次性参数(进程内,随命令结束即失)。"""
|
|
31
|
+
_CLI_PARAMS["base_url"] = (base_url or "").strip()
|
|
32
|
+
_CLI_PARAMS["token"] = (token or "").strip()
|
|
33
|
+
_CLI_PARAMS["no_proxy"] = bool(no_proxy)
|
|
34
|
+
try:
|
|
35
|
+
_CLI_PARAMS["timeout"] = max(0, int(timeout or 0))
|
|
36
|
+
except (TypeError, ValueError):
|
|
37
|
+
_CLI_PARAMS["timeout"] = 0
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def cli_timeout() -> int:
|
|
41
|
+
"""本次调用请求超时(秒);未指定用默认 30。"""
|
|
42
|
+
return _CLI_PARAMS["timeout"] or DEFAULT_TIMEOUT
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def trust_env() -> bool:
|
|
46
|
+
"""HTTP 环境信任开关(httpx trust_env 语义,grape#2252)。
|
|
47
|
+
|
|
48
|
+
`--no-proxy` 或 `GRAPE_TRUST_ENV`∈{0,false,no,off}(不区分大小写)→ False:
|
|
49
|
+
忽略 `*_proxy`/`NO_PROXY` 等环境代理,强制直连。未设置/空/真值 → True(默认行为)。
|
|
50
|
+
"""
|
|
51
|
+
if _CLI_PARAMS.get("no_proxy"):
|
|
52
|
+
return False
|
|
53
|
+
raw = (os.environ.get("GRAPE_TRUST_ENV") or "").strip().lower()
|
|
54
|
+
return raw not in ("0", "false", "no", "off")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def load_file_config() -> dict:
|
|
58
|
+
try:
|
|
59
|
+
if CONFIG_FILE.exists():
|
|
60
|
+
return json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
|
|
61
|
+
except Exception:
|
|
62
|
+
pass
|
|
63
|
+
return {}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def a2a_fallback_base_url() -> str:
|
|
67
|
+
"""A2A fallback base:`GRAPE_A2A_FALLBACK_BASE_URL` > config.json 的 `a2a_fallback_base_url`。
|
|
68
|
+
|
|
69
|
+
仅在 a2a 路径命中 405 时启用,避免主服务误路由业务命令。
|
|
70
|
+
"""
|
|
71
|
+
env = os.environ
|
|
72
|
+
return (env.get("GRAPE_A2A_FALLBACK_BASE_URL") or "").strip() or \
|
|
73
|
+
str(load_file_config().get("a2a_fallback_base_url") or "").strip()
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
_config_warned = False
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _read_auth_file(env) -> str:
|
|
80
|
+
"""从 GRAPE_AUTH_FILE 指向的文件读 token 值。
|
|
81
|
+
|
|
82
|
+
DshRuntime.get_env 把 session token 写到一个 0600 临时文件,
|
|
83
|
+
路径通过 GRAPE_AUTH_FILE 传递(该变量名不命中 dsh 的 /KEY|PASSWORD|SECRET|TOKEN/i scrub)。
|
|
84
|
+
文件不存在或为空 → 返回空字符串(fallback 到环境变量)。
|
|
85
|
+
"""
|
|
86
|
+
path = (env.get("GRAPE_AUTH_FILE") or "").strip()
|
|
87
|
+
if not path:
|
|
88
|
+
return ""
|
|
89
|
+
try:
|
|
90
|
+
p = Path(path)
|
|
91
|
+
if not p.exists():
|
|
92
|
+
return ""
|
|
93
|
+
val = p.read_text(encoding="utf-8").strip()
|
|
94
|
+
return val
|
|
95
|
+
except Exception:
|
|
96
|
+
return ""
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _resolve_base_url(base_url: str, env, cfg: dict) -> tuple[str, str]:
|
|
100
|
+
"""base_url 优先级链:--base-url > GRAPE_BASE_URL > GRAPE_SERVER_URL > config.json > 默认。
|
|
101
|
+
|
|
102
|
+
返回 (base_url, 来源标签);来源标签供 doctor 报告「实际生效值 + 来源」
|
|
103
|
+
(QA 复审 Standards 2:resolve()/resolve_with_source() 同一实现,不再两处推导)。
|
|
104
|
+
"""
|
|
105
|
+
for val, label in ((base_url, "--base-url"), (_CLI_PARAMS["base_url"], "--base-url")):
|
|
106
|
+
val = (val or "").strip()
|
|
107
|
+
if val:
|
|
108
|
+
return val, label
|
|
109
|
+
for var in ("GRAPE_BASE_URL", "GRAPE_SERVER_URL"):
|
|
110
|
+
val = (env.get(var) or "").strip()
|
|
111
|
+
if val:
|
|
112
|
+
return val, var
|
|
113
|
+
val = str(cfg.get("base_url") or "").strip()
|
|
114
|
+
if val:
|
|
115
|
+
return val, "config.json"
|
|
116
|
+
return "http://localhost:8000", "default (http://localhost:8000)"
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def effective_token_channel(token: str = "", env=None, cfg: dict | None = None) -> tuple[str, str]:
|
|
120
|
+
"""token 归集公开接口(与 resolve() 完全同一优先级链):返回 (token 值, 通道名)。
|
|
121
|
+
|
|
122
|
+
通道名 ∈ {"--token", "GRAPE_AUTH_FILE", "DSH_GRAPE_SESSION_TOKEN",
|
|
123
|
+
"GRAPE_SESSION_TOKEN", "GRAPE_API_TOKEN", "config.json"};全缺 → ("", "")。
|
|
124
|
+
|
|
125
|
+
优先级:--token(CLI 一次性参数/函数参数)> GRAPE_AUTH_FILE 文件 >
|
|
126
|
+
env 三通道(GRAPE_CLI_MODE=USER 时 GRAPE_API_TOKEN 优先,否则 DSH_GRAPE_SESSION_TOKEN >
|
|
127
|
+
GRAPE_SESSION_TOKEN > GRAPE_API_TOKEN)> config.json token。
|
|
128
|
+
doctor 复用本接口做三通道归集(QA 复审 Standards 4:防止与 resolve() 分叉
|
|
129
|
+
漏 DSH_GRAPE_SESSION_TOKEN / GRAPE_CLI_MODE 而误报「无通道」)。
|
|
130
|
+
"""
|
|
131
|
+
env = os.environ if env is None else env
|
|
132
|
+
one_shot = (token or "").strip() or _CLI_PARAMS["token"]
|
|
133
|
+
if one_shot:
|
|
134
|
+
return one_shot, "--token"
|
|
135
|
+
file_tok = _read_auth_file(env)
|
|
136
|
+
if file_tok:
|
|
137
|
+
return file_tok, "GRAPE_AUTH_FILE"
|
|
138
|
+
mode = (env.get("GRAPE_CLI_MODE") or "ALL").strip().upper()
|
|
139
|
+
names = (("GRAPE_API_TOKEN", "DSH_GRAPE_SESSION_TOKEN", "GRAPE_SESSION_TOKEN")
|
|
140
|
+
if mode == "USER" else
|
|
141
|
+
("DSH_GRAPE_SESSION_TOKEN", "GRAPE_SESSION_TOKEN", "GRAPE_API_TOKEN"))
|
|
142
|
+
for name in names:
|
|
143
|
+
val = (env.get(name) or "").strip()
|
|
144
|
+
if val:
|
|
145
|
+
return val, name
|
|
146
|
+
if cfg is None:
|
|
147
|
+
cfg = load_file_config()
|
|
148
|
+
val = str(cfg.get("token") or "").strip()
|
|
149
|
+
return (val, "config.json") if val else ("", "")
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def resolve_with_source(base_url: str = "", token: str = "", refresh: bool = False) -> tuple[str, str, str]:
|
|
153
|
+
"""返回 (base_url, base_url 来源标签, token)——resolve() 的公开伴生。
|
|
154
|
+
|
|
155
|
+
base_url 优先级链与 token 归集和 resolve() 共用同一实现(本函数是单一事实源),
|
|
156
|
+
供 doctor 等报告「实际生效值 + 来源」,不再私有穿透 _CLI_PARAMS/load_file_config 重推导。
|
|
157
|
+
"""
|
|
158
|
+
cfg = load_file_config() if not refresh else {}
|
|
159
|
+
env = os.environ
|
|
160
|
+
_base, source = _resolve_base_url(base_url, env, cfg)
|
|
161
|
+
_token, _channel = effective_token_channel(token, env=env, cfg=cfg)
|
|
162
|
+
return _base.rstrip("/"), source, _token
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def resolve(base_url: str = "", token: str = "", refresh: bool = False) -> tuple[str, str]:
|
|
166
|
+
"""返回 (base_url, token)。缺任一 → 抛 if config incomplete.
|
|
167
|
+
|
|
168
|
+
优先级:函数参数 == CLI 一次性参数(--base-url/--token)> 环境变量 > config.json。
|
|
169
|
+
token 双变量在 GRAPE_CLI_MODE=USER 时优先 GRAPE_API_TOKEN,否则 session 优先。
|
|
170
|
+
实现:base_url 链与 token 归集均委托 resolve_with_source()(同一事实源)。
|
|
171
|
+
"""
|
|
172
|
+
global _config_warned
|
|
173
|
+
env = os.environ
|
|
174
|
+
# USER 模式缺 GRAPE_API_TOKEN 的迁移提示(只提示,不影响归集结果)
|
|
175
|
+
if (env.get("GRAPE_CLI_MODE") or "ALL").strip().upper() == "USER" \
|
|
176
|
+
and not (env.get("GRAPE_API_TOKEN") or "").strip() \
|
|
177
|
+
and not (token or "").strip() and not _CLI_PARAMS["token"] \
|
|
178
|
+
and not _read_auth_file(env) and not _config_warned:
|
|
179
|
+
_config_warned = True
|
|
180
|
+
import sys
|
|
181
|
+
sys.stderr.write(
|
|
182
|
+
"warning: GRAPE_CLI_MODE=USER but GRAPE_API_TOKEN is missing; "
|
|
183
|
+
"falling back to session token\n"
|
|
184
|
+
)
|
|
185
|
+
_base, _source, _token = resolve_with_source(base_url, token, refresh)
|
|
186
|
+
return _base, _token
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def save_config(base_url: str, token: str = ""):
|
|
190
|
+
cfg = load_file_config()
|
|
191
|
+
if base_url:
|
|
192
|
+
cfg["base_url"] = base_url
|
|
193
|
+
if token:
|
|
194
|
+
cfg["token"] = token
|
|
195
|
+
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
|
196
|
+
CONFIG_FILE.write_text(json.dumps(cfg, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
197
|
+
|
|
198
|
+
def _truthy(value) -> bool:
|
|
199
|
+
return str(value or "").strip().lower() in {"1", "true", "yes", "on"}
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def version_check_disabled(*, no_version_check: bool = False, env=None,
|
|
203
|
+
config_path=None) -> bool:
|
|
204
|
+
"""新版本检查三通道开关(优先级:命令行 > 环境变量 > 配置文件)。
|
|
205
|
+
|
|
206
|
+
任一命中即返回 True(完全跳过:零线程、零网络)。
|
|
207
|
+
``--no-version-check`` / ``GRAPE_NO_VERSION_CHECK=1`` / config ``version_check=false``。
|
|
208
|
+
"""
|
|
209
|
+
if no_version_check:
|
|
210
|
+
return True
|
|
211
|
+
env_map = os.environ if env is None else env
|
|
212
|
+
if _truthy(env_map.get("GRAPE_NO_VERSION_CHECK")):
|
|
213
|
+
return True
|
|
214
|
+
if config_path is not None:
|
|
215
|
+
try:
|
|
216
|
+
cfg = json.loads(Path(config_path).read_text(encoding="utf-8"))
|
|
217
|
+
except Exception:
|
|
218
|
+
cfg = {}
|
|
219
|
+
else:
|
|
220
|
+
cfg = load_file_config()
|
|
221
|
+
return isinstance(cfg, dict) and cfg.get("version_check") is False
|