forked from ShigureLab/gh-llm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdoctor.py
More file actions
334 lines (278 loc) 路 9.13 KB
/
Copy pathdoctor.py
File metadata and controls
334 lines (278 loc) 路 9.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
from __future__ import annotations
import json
import os
import shlex
import shutil
import subprocess
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, cast
from urllib.parse import SplitResult, urlsplit, urlunsplit
from gh_llm import __version__
from gh_llm.invocation import detect_prog_name, display_command
if TYPE_CHECKING:
from collections.abc import Sequence
from typing import Any
_GRAPHQL_PROBE_QUERY = "query{viewer{login}}"
_DEFAULT_TARGET_HOST = "github.com"
_ENV_KEYS = (
"GH_LLM_DISPLAY_CMD",
"GH_HOST",
"GH_TOKEN",
"GITHUB_TOKEN",
"http_proxy",
"https_proxy",
"HTTP_PROXY",
"HTTPS_PROXY",
"ALL_PROXY",
"NO_PROXY",
)
@dataclass(frozen=True)
class _CommandResult:
ok: bool
output: str
@dataclass(frozen=True)
class _ProbeResult:
name: str
command: str
ok: bool
summary: str
detail: str = ""
critical: bool = True
def register_doctor_parser(subparsers: Any) -> None:
doctor_parser = subparsers.add_parser(
"doctor",
help="show environment, auth, and connectivity diagnostics",
)
doctor_parser.set_defaults(handler=cmd_doctor)
env_parser = subparsers.add_parser(
"env",
help="alias of `doctor`",
)
env_parser.set_defaults(handler=cmd_doctor)
def cmd_doctor(_: Any) -> int:
entrypoint = display_command()
argv0 = detect_prog_name(sys.argv[0])
target_host = _resolve_target_host()
critical_probes = (
_probe_entrypoint_version(entrypoint),
_probe_gh_version(),
_probe_auth_status(target_host),
_probe_rest_user(),
_probe_graphql_viewer(),
)
failed = [probe.name for probe in critical_probes if not probe.ok and probe.critical]
lines: list[str] = [
"## Entrypoint",
f"- entrypoint: {entrypoint}",
f"- argv0: {argv0}",
f"- argv0_path: {_resolve_argv0_path(sys.argv[0], argv0)}",
f"- entrypoint_path: {_resolve_entrypoint_path(entrypoint)}",
f"- gh_path: {_resolve_binary_path('gh')}",
f"- gh_llm_path: {_resolve_binary_path('gh-llm')}",
f"- target_host: {target_host}",
f"- python: {sys.executable}",
f"- cwd: {Path.cwd()}",
"",
"## Versions",
f"- package: {__version__}",
f"- python: {sys.version.split()[0]}",
]
lines.extend(_render_probe_lines(critical_probes[:2]))
lines.extend(
[
"",
"## Environment",
]
)
lines.extend(_render_environment_lines())
lines.extend(
[
"",
"## Auth",
]
)
lines.extend(_render_probe_lines((critical_probes[2],)))
lines.extend(
[
"",
"## Probes",
]
)
lines.extend(_render_probe_lines(critical_probes[3:]))
lines.extend(
[
"",
"## Summary",
f"status: {'ok' if not failed else 'unhealthy'}",
]
)
if failed:
lines.append(f"failed_checks: {', '.join(failed)}")
for line in lines:
print(line)
return 0 if not failed else 1
def _render_probe_lines(probes: Sequence[_ProbeResult]) -> list[str]:
lines: list[str] = []
for probe in probes:
lines.append(f"- {probe.name} (`{probe.command}`): {probe.summary}")
detail = probe.detail.strip()
if detail and detail != probe.summary:
lines.extend(_indent_block(detail))
return lines
def _render_environment_lines() -> list[str]:
lines: list[str] = []
for key in _ENV_KEYS:
lines.append(f"- {key}: {_format_env_value(key, os.environ.get(key))}")
return lines
def _probe_entrypoint_version(entrypoint: str) -> _ProbeResult:
command = _split_command(entrypoint, suffix=("--version",))
rendered = shlex.join(command)
result = _run_command(command)
return _probe_from_command_result(
name="entrypoint version",
command=rendered,
result=result,
success_summary=result.output.strip() or "ok",
)
def _probe_gh_version() -> _ProbeResult:
command = ["gh", "--version"]
result = _run_command(command)
return _probe_from_command_result(
name="gh version",
command=shlex.join(command),
result=result,
success_summary=(result.output.splitlines()[0].strip() if result.output.strip() else "ok"),
)
def _probe_auth_status(target_host: str) -> _ProbeResult:
command = ["gh", "auth", "status", "--active", "--hostname", target_host]
result = _run_command(command)
summary = "ok" if result.ok else "failed"
return _ProbeResult(
name="auth status",
command=shlex.join(command),
ok=result.ok,
summary=summary,
detail=result.output,
)
def _probe_rest_user() -> _ProbeResult:
command = ["gh", "api", "user"]
result = _run_command(command)
if not result.ok:
return _ProbeResult(
name="REST user probe",
command=shlex.join(command),
ok=False,
summary="failed",
detail=result.output,
)
login = _extract_json_login(result.output, path=("login",))
summary = f"ok (@{login})" if login else "ok"
return _ProbeResult(
name="REST user probe",
command=shlex.join(command),
ok=True,
summary=summary,
detail="",
)
def _probe_graphql_viewer() -> _ProbeResult:
command = ["gh", "api", "graphql", "-f", f"query={_GRAPHQL_PROBE_QUERY}"]
result = _run_command(command)
if not result.ok:
return _ProbeResult(
name="GraphQL viewer probe",
command="gh api graphql -f query='query{viewer{login}}'",
ok=False,
summary="failed",
detail=result.output,
)
login = _extract_json_login(result.output, path=("data", "viewer", "login"))
summary = f"ok (@{login})" if login else "ok"
return _ProbeResult(
name="GraphQL viewer probe",
command="gh api graphql -f query='query{viewer{login}}'",
ok=True,
summary=summary,
detail="",
)
def _probe_from_command_result(
*,
name: str,
command: str,
result: _CommandResult,
success_summary: str,
) -> _ProbeResult:
if result.ok:
return _ProbeResult(name=name, command=command, ok=True, summary=success_summary, detail=result.output)
return _ProbeResult(name=name, command=command, ok=False, summary="failed", detail=result.output)
def _run_command(cmd: Sequence[str]) -> _CommandResult:
try:
completed = subprocess.run(list(cmd), check=False, capture_output=True, text=True)
except OSError as error:
return _CommandResult(ok=False, output=str(error))
return _CommandResult(ok=completed.returncode == 0, output=_merge_outputs(completed.stdout, completed.stderr))
def _merge_outputs(stdout: str, stderr: str) -> str:
parts = [part.strip() for part in (stdout, stderr) if part.strip()]
return "\n\n".join(parts)
def _extract_json_login(payload: str, *, path: Sequence[str]) -> str | None:
try:
parsed = json.loads(payload)
except json.JSONDecodeError:
return None
current: object = parsed
for key in path:
if not isinstance(current, dict):
return None
current_dict = cast("dict[str, object]", current)
current = current_dict.get(key)
if isinstance(current, str) and current.strip():
return current.strip()
return None
def _indent_block(text: str) -> list[str]:
return [f" {line}" if line else "" for line in text.splitlines()]
def _split_command(command: str, *, suffix: Sequence[str] = ()) -> list[str]:
base = shlex.split(command)
return [*base, *suffix]
def _resolve_argv0_path(argv0_raw: str, argv0_name: str) -> str:
if argv0_raw:
candidate = Path(argv0_raw)
if candidate.exists():
return str(candidate.resolve())
return _resolve_binary_path(argv0_name)
def _resolve_entrypoint_path(entrypoint: str) -> str:
parts = shlex.split(entrypoint)
if not parts:
return "(unknown)"
return _resolve_binary_path(parts[0])
def _resolve_binary_path(name: str) -> str:
resolved = shutil.which(name)
return resolved or "(not found)"
def _resolve_target_host() -> str:
raw = os.environ.get("GH_HOST", "").strip()
return raw or _DEFAULT_TARGET_HOST
def _format_env_value(key: str, value: str | None) -> str:
if value is None or not value.strip():
return "(unset)"
if key in {"GH_TOKEN", "GITHUB_TOKEN"}:
return "(set)"
return _redact_url_credentials(value.strip())
def _redact_url_credentials(value: str) -> str:
if "://" not in value or "@" not in value:
return value
parsed = urlsplit(value)
if not parsed.hostname:
return value
netloc = parsed.hostname
if parsed.port is not None:
netloc = f"{netloc}:{parsed.port}"
if parsed.username is not None:
netloc = f"***@{netloc}"
redacted = SplitResult(
scheme=parsed.scheme,
netloc=netloc,
path=parsed.path,
query=parsed.query,
fragment=parsed.fragment,
)
return urlunsplit(redacted)