1panel-toolkit 0.3.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 (47) hide show
  1. 1panel_toolkit-0.3.0.dist-info/METADATA +407 -0
  2. 1panel_toolkit-0.3.0.dist-info/RECORD +47 -0
  3. 1panel_toolkit-0.3.0.dist-info/WHEEL +4 -0
  4. 1panel_toolkit-0.3.0.dist-info/entry_points.txt +2 -0
  5. 1panel_toolkit-0.3.0.dist-info/licenses/LICENSE +21 -0
  6. p1toolkit/__init__.py +3 -0
  7. p1toolkit/checks/__init__.py +21 -0
  8. p1toolkit/checks/compose.py +188 -0
  9. p1toolkit/checks/forms.py +129 -0
  10. p1toolkit/checks/hygiene.py +73 -0
  11. p1toolkit/checks/i18n.py +140 -0
  12. p1toolkit/checks/lessons.py +111 -0
  13. p1toolkit/checks/structure.py +140 -0
  14. p1toolkit/checks/substance.py +55 -0
  15. p1toolkit/cli.py +890 -0
  16. p1toolkit/config.py +114 -0
  17. p1toolkit/dependencies.py +218 -0
  18. p1toolkit/deploy.py +302 -0
  19. p1toolkit/depth.py +414 -0
  20. p1toolkit/errors.py +18 -0
  21. p1toolkit/evidence.py +523 -0
  22. p1toolkit/fix.py +394 -0
  23. p1toolkit/gen.py +728 -0
  24. p1toolkit/lifecycle.py +143 -0
  25. p1toolkit/loader.py +110 -0
  26. p1toolkit/logo.py +174 -0
  27. p1toolkit/model.py +71 -0
  28. p1toolkit/net.py +81 -0
  29. p1toolkit/panel.py +154 -0
  30. p1toolkit/patterns/__init__.py +250 -0
  31. p1toolkit/patterns/catalog.py +271 -0
  32. p1toolkit/patterns/data/patterns.json +724 -0
  33. p1toolkit/patterns/extract.py +402 -0
  34. p1toolkit/remote.py +554 -0
  35. p1toolkit/report.py +96 -0
  36. p1toolkit/resolve/__init__.py +554 -0
  37. p1toolkit/resolve/analyze.py +329 -0
  38. p1toolkit/resolve/sources.py +306 -0
  39. p1toolkit/rules/__init__.py +99 -0
  40. p1toolkit/rules/data/decisions.yaml +132 -0
  41. p1toolkit/rules/data/dependencies.yaml +113 -0
  42. p1toolkit/rules/data/envkeys.yaml +19 -0
  43. p1toolkit/rules/data/form-design.yaml +59 -0
  44. p1toolkit/rules/data/i18n.yaml +354 -0
  45. p1toolkit/rules/data/lessons.yaml +84 -0
  46. p1toolkit/rules/data/store.yaml +171 -0
  47. p1toolkit/selftest.py +211 -0
@@ -0,0 +1,329 @@
1
+ """Turn upstream files into evidence records.
2
+
3
+ An evidence record always carries where it came from, because the whole point
4
+ of this step is that the next stage is allowed to write values it can point at,
5
+ and must stop on the ones it cannot.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from dataclasses import dataclass, field
12
+ from typing import Any, Iterable
13
+
14
+ import yaml
15
+
16
+ from .sources import SourceFiles
17
+
18
+ SIDECAR_IMAGES = {
19
+ "mysql": "mysql",
20
+ "mariadb": "mariadb",
21
+ "postgres": "postgresql",
22
+ "postgresql": "postgresql",
23
+ "redis": "redis",
24
+ "mongo": "mongodb",
25
+ "mongodb": "mongodb",
26
+ "valkey": "valkey",
27
+ }
28
+
29
+ EXTERNAL_DB_HINTS = ("DATABASE_URL", "DB_HOST", "DB_SERVER", "POSTGRES_HOST", "MYSQL_HOST")
30
+
31
+ # A path-valued environment variable is how many images declare where their
32
+ # state lives when the Dockerfile has no VOLUME (Halo uses HALO_WORK_DIR).
33
+ PATH_ENV_HINTS = (
34
+ "WORK_DIR",
35
+ "DATA_DIR",
36
+ "CONFIG_DIR",
37
+ "STORAGE",
38
+ "_PATH",
39
+ "_HOME",
40
+ "DIRECTORY",
41
+ )
42
+
43
+ IMAGE_REF_RE = re.compile(
44
+ r"(?<![\w./-])([a-z0-9][\w.-]*(?:\.[\w.-]+)*(?::\d+)?/[A-Za-z0-9][\w./-]*(?::[\w.-]+)?)"
45
+ )
46
+ EXTRA_RUNTIME_KEYS = (
47
+ "privileged",
48
+ "cap_add",
49
+ "cap_drop",
50
+ "devices",
51
+ "sysctls",
52
+ "ulimits",
53
+ "shm_size",
54
+ "security_opt",
55
+ "network_mode",
56
+ "pid",
57
+ "ipc",
58
+ "tmpfs",
59
+ "read_only",
60
+ "user",
61
+ "group_add",
62
+ "stop_grace_period",
63
+ )
64
+
65
+
66
+ @dataclass
67
+ class Evidence:
68
+ kind: str
69
+ value: str
70
+ file: str
71
+ line: int | None = None
72
+ snippet: str = ""
73
+
74
+ def render(self) -> str:
75
+ where = f"{self.file}:{self.line}" if self.line else self.file
76
+ return f"{self.value} ({where})"
77
+
78
+
79
+ @dataclass
80
+ class Analysis:
81
+ source: SourceFiles
82
+ evidence: dict[str, list[Evidence]] = field(default_factory=dict)
83
+ compose: dict[str, Any] = field(default_factory=dict)
84
+ notes: list[str] = field(default_factory=list)
85
+
86
+ def add(self, item: Evidence) -> None:
87
+ bucket = self.evidence.setdefault(item.kind, [])
88
+ if not any(e.value == item.value for e in bucket):
89
+ bucket.append(item)
90
+
91
+ def values(self, kind: str) -> list[str]:
92
+ return [e.value for e in self.evidence.get(kind, [])]
93
+
94
+ def first(self, kind: str) -> str | None:
95
+ items = self.evidence.get(kind)
96
+ return items[0].value if items else None
97
+
98
+
99
+ # --------------------------------------------------------------------------
100
+ # Dockerfile
101
+ # --------------------------------------------------------------------------
102
+
103
+
104
+ def _logical_lines(text: str) -> Iterable[tuple[int, str]]:
105
+ buffer = ""
106
+ start = 0
107
+ for number, raw in enumerate(text.splitlines(), start=1):
108
+ line = raw.strip()
109
+ if not line or line.startswith("#"):
110
+ continue
111
+ if not buffer:
112
+ start = number
113
+ if line.endswith("\\"):
114
+ buffer += line[:-1].rstrip() + " "
115
+ continue
116
+ yield start, (buffer + line).strip()
117
+ buffer = ""
118
+ if buffer:
119
+ yield start, buffer.strip()
120
+
121
+
122
+ def parse_dockerfile(analysis: Analysis, path: str, text: str) -> None:
123
+ for number, line in _logical_lines(text):
124
+ head, _, rest = line.partition(" ")
125
+ head = head.upper()
126
+ rest = rest.strip()
127
+ if head == "EXPOSE":
128
+ for token in rest.split():
129
+ port = token.split("/")[0].strip()
130
+ if port.isdigit():
131
+ analysis.add(Evidence("container_port", port, path, number, line))
132
+ elif head == "VOLUME":
133
+ for target in re.findall(r"[^\s\[\]\"]+", rest):
134
+ if target.startswith("/"):
135
+ analysis.add(Evidence("mount_target", target, path, number, line))
136
+ elif head == "USER":
137
+ analysis.add(Evidence("runtime_user", rest, path, number, line))
138
+ elif head == "ENV":
139
+ for key, value in _env_pairs(rest):
140
+ analysis.add(Evidence("env_key", key, path, number, line))
141
+ if value:
142
+ analysis.add(Evidence("env_default", f"{key}={value}", path, number, line))
143
+ if value.startswith("/") and any(
144
+ hint in key.upper() for hint in PATH_ENV_HINTS
145
+ ):
146
+ analysis.add(
147
+ Evidence("mount_target_hint", value, path, number, line)
148
+ )
149
+ elif head in {"ENTRYPOINT", "CMD"}:
150
+ analysis.add(Evidence("entrypoint", rest[:120], path, number, line))
151
+
152
+
153
+ def _env_pairs(rest: str) -> list[tuple[str, str]]:
154
+ if "=" not in rest:
155
+ parts = rest.split(None, 1)
156
+ return [(parts[0], parts[1] if len(parts) > 1 else "")] if parts else []
157
+ pairs = []
158
+ for chunk in re.findall(r'([A-Za-z_][A-Za-z0-9_]*)=("([^"]*)"|\'([^\']*)\'|\S*)', rest):
159
+ pairs.append((chunk[0], chunk[2] or chunk[3] or chunk[1].strip('"\'')))
160
+ return pairs
161
+
162
+
163
+ # --------------------------------------------------------------------------
164
+ # compose
165
+ # --------------------------------------------------------------------------
166
+
167
+
168
+ _VAR = re.compile(r"\$\{[A-Za-z_][A-Za-z0-9_]*(?::?-([^}]*))?\}")
169
+
170
+
171
+ def _expand_defaults(text: str) -> str:
172
+ """``${PORT:-1933}`` -> ``1933``; a variable without a default becomes empty."""
173
+ return _VAR.sub(lambda match: match.group(1) or "", text)
174
+
175
+
176
+ def _container_port(entry: Any) -> str | None:
177
+ if isinstance(entry, dict):
178
+ target = entry.get("target")
179
+ return str(target) if target is not None and str(target).isdigit() else None
180
+ text = _expand_defaults(str(entry)).split("/")[0]
181
+ if ":" in text:
182
+ text = text.rsplit(":", 1)[1]
183
+ text = text.strip()
184
+ return text if text.isdigit() else None
185
+
186
+
187
+ def _volume_split(entry: Any) -> tuple[str, str] | None:
188
+ parts = str(entry).split(":")
189
+ if len(parts) < 2:
190
+ return None
191
+ return parts[0].strip(), parts[1].strip()
192
+
193
+
194
+ def _env_map(service: dict[str, Any]) -> list[tuple[str, str]]:
195
+ env = service.get("environment")
196
+ if isinstance(env, dict):
197
+ return [(str(k), str(v)) for k, v in env.items()]
198
+ out = []
199
+ for item in env or []:
200
+ if not isinstance(item, str):
201
+ continue
202
+ key, _, value = item.partition("=")
203
+ out.append((key.strip(), value.strip()))
204
+ return out
205
+
206
+
207
+ def parse_compose(analysis: Analysis, path: str, text: str) -> None:
208
+ try:
209
+ data = yaml.safe_load(text) or {}
210
+ except yaml.YAMLError as exc:
211
+ analysis.notes.append(f"{path}: compose 解析失败({exc})")
212
+ return
213
+ if not isinstance(data, dict):
214
+ return
215
+ analysis.compose = data
216
+ services = {
217
+ name: svc for name, svc in (data.get("services") or {}).items() if isinstance(svc, dict)
218
+ }
219
+ analysis.add(Evidence("service_count", str(len(services)), path))
220
+ for name, service in services.items():
221
+ image = str(service.get("image") or "").strip()
222
+ if image:
223
+ analysis.add(Evidence("image", image, path, _find_line(text, "image", image)))
224
+ base = image.split(":")[0].split("/")[-1].lower()
225
+ if base in SIDECAR_IMAGES and len(services) > 1:
226
+ analysis.add(Evidence("sidecar_dependency", SIDECAR_IMAGES[base], path))
227
+ for mapping in service.get("ports") or []:
228
+ port = _container_port(mapping)
229
+ if port:
230
+ analysis.add(Evidence("container_port", port, path, _find_line(text, "ports", str(mapping))))
231
+ for volume in service.get("volumes") or []:
232
+ split = _volume_split(volume)
233
+ if split and split[1].startswith("/"):
234
+ analysis.add(
235
+ Evidence("mount_target", split[1], path, _find_line(text, "volumes", str(volume)))
236
+ )
237
+ analysis.add(Evidence("mount_host", split[0], path))
238
+ for key, value in _env_map(service):
239
+ analysis.add(Evidence("env_key", key, path))
240
+ if key in EXTERNAL_DB_HINTS or "DATABASE" in key:
241
+ analysis.add(Evidence("external_dependency", key, path))
242
+ if "REDIS" in key.upper():
243
+ analysis.add(Evidence("external_dependency", "redis", path))
244
+ if value and "${" not in value:
245
+ analysis.add(Evidence("env_default", f"{key}={value}", path))
246
+ for key in EXTRA_RUNTIME_KEYS:
247
+ if key in service:
248
+ analysis.add(Evidence("extra_runtime", f"{name}.{key}", path))
249
+ if service.get("healthcheck"):
250
+ analysis.add(Evidence("healthcheck", name, path))
251
+
252
+
253
+ def _find_line(text: str, anchor: str, needle: str) -> int | None:
254
+ short = needle.strip().strip('"').split(":")[0][:24]
255
+ for number, line in enumerate(text.splitlines(), start=1):
256
+ if short and short in line:
257
+ return number
258
+ return None
259
+
260
+
261
+ # --------------------------------------------------------------------------
262
+ # .env.example / README
263
+ # --------------------------------------------------------------------------
264
+
265
+
266
+ def parse_env_example(analysis: Analysis, path: str, text: str) -> None:
267
+ for number, line in enumerate(text.splitlines(), start=1):
268
+ stripped = line.strip()
269
+ if not stripped or stripped.startswith("#") or "=" not in stripped:
270
+ continue
271
+ key, _, value = stripped.partition("=")
272
+ key = key.strip()
273
+ if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", key):
274
+ continue
275
+ analysis.add(Evidence("env_key", key, path, number, stripped))
276
+ if value.strip():
277
+ analysis.add(Evidence("env_default", f"{key}={value.strip()}", path, number, stripped))
278
+
279
+
280
+ CONFIG_HINTS = (
281
+ "config.yaml",
282
+ "config.yml",
283
+ "config.json",
284
+ "conf.yaml",
285
+ "配置文件",
286
+ ".env.example",
287
+ "cp .env",
288
+ "copy .env",
289
+ )
290
+
291
+
292
+ def parse_readme(analysis: Analysis, path: str, text: str) -> None:
293
+ lines = text.splitlines()
294
+ for number, line in enumerate(lines, start=1):
295
+ if line.startswith("## "):
296
+ analysis.add(Evidence("readme_section", line.strip("# ").strip(), path, number))
297
+ lowered = line.lower()
298
+ for hint in CONFIG_HINTS:
299
+ if hint.lower() in lowered:
300
+ analysis.add(Evidence("config_hint", hint, path, number, line.strip()[:160]))
301
+ break
302
+ for number, line in enumerate(lines, start=1):
303
+ match = re.search(r"docker\s+run\b[^\n]*?-p\s*(\d+):(\d+)", line)
304
+ if match:
305
+ analysis.add(Evidence("container_port", match.group(2), path, number, line.strip()[:160]))
306
+ for url in re.findall(r"https?://[^\s\)\]\"'<>]+", line):
307
+ if "github.com" in url or "shields.io" in url or "badge" in url:
308
+ continue
309
+ analysis.add(Evidence("upstream_link", url.rstrip(".,"), path, number))
310
+ lowered = line.lower()
311
+ if "docker pull" in lowered or "docker run" in lowered or lowered.strip().startswith("image:"):
312
+ for candidate in IMAGE_REF_RE.findall(line):
313
+ if candidate.startswith(("http", "www.")) or "@" in candidate:
314
+ continue
315
+ analysis.add(Evidence("image_hint", candidate.rstrip(".,"), path, number, line.strip()[:160]))
316
+ break
317
+
318
+
319
+ def analyze(source: SourceFiles) -> Analysis:
320
+ analysis = Analysis(source=source)
321
+ if "dockerfile" in source.files:
322
+ parse_dockerfile(analysis, source.paths["dockerfile"], source.files["dockerfile"])
323
+ if "compose" in source.files:
324
+ parse_compose(analysis, source.paths["compose"], source.files["compose"])
325
+ if "env_example" in source.files:
326
+ parse_env_example(analysis, source.paths["env_example"], source.files["env_example"])
327
+ if "readme" in source.files:
328
+ parse_readme(analysis, source.paths["readme"], source.files["readme"])
329
+ return analysis
@@ -0,0 +1,306 @@
1
+ """Where upstream facts come from.
2
+
3
+ Two sources, same interface: a local checkout (works offline, and is how the
4
+ user already works) and a GitHub repository reached through the API plus
5
+ raw.githubusercontent.com. Docker Hub manifests are deliberately not used —
6
+ when the registry is unreachable, architectures stay unknown rather than being
7
+ guessed.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import os
14
+ import re
15
+ import time
16
+ import urllib.error
17
+ import urllib.request
18
+ from dataclasses import dataclass, field
19
+ from pathlib import Path
20
+
21
+ GITHUB_RE = re.compile(
22
+ r"^(?:https?://)?(?:www\.)?github\.com/(?P<owner>[\w.-]+)/(?P<repo>[\w.-]+?)(?:\.git)?(?:/tree/(?P<ref>[^/]+))?/?$"
23
+ )
24
+ SLUG_RE = re.compile(r"^(?P<owner>[\w.-]+)/(?P<repo>[\w.-]+)$")
25
+
26
+ COMPOSE_RE = re.compile(r"(^|/)(docker-)?compose\.ya?ml$", re.IGNORECASE)
27
+ DOCKERFILE_RE = re.compile(r"(^|/)(dockerfile|containerfile)(\.[\w.-]+)?$", re.IGNORECASE)
28
+ ENV_EXAMPLE_RE = re.compile(r"(^|/)(\.env\.(example|sample|template|dist)|env\.example)$", re.IGNORECASE)
29
+ README_RE = re.compile(r"(^|/)readme(\.md|\.rst|\.txt)?$", re.IGNORECASE)
30
+ LOGO_RE = re.compile(r"(^|/)logo\.(png|svg)$", re.IGNORECASE)
31
+ CONFIG_SAMPLE_RE = re.compile(
32
+ r"(^|/)[\w.-]*(config|conf)[\w.-]*\.(ya?ml|json|toml|ini)(\.example|\.sample|\.template)?$",
33
+ re.IGNORECASE,
34
+ )
35
+
36
+ MAX_FILE_BYTES = 400_000
37
+
38
+ # How long the raw-file fetches may take in total before `resolve` gives up and
39
+ # reports the gap instead of silently stalling (`raw.githubusercontent.com` is
40
+ # blocked from some networks, and each candidate then costs a full timeout).
41
+ DEFAULT_FETCH_BUDGET = 60.0
42
+
43
+ # Walking these makes a big checkout crawl and never finds app metadata.
44
+ SKIP_DIRS = {
45
+ ".git",
46
+ "node_modules",
47
+ ".venv",
48
+ "venv",
49
+ "__pycache__",
50
+ ".next",
51
+ "dist",
52
+ "target",
53
+ "vendor",
54
+ }
55
+
56
+ # API responses (repo tree, releases) are much larger than a source file.
57
+ MAX_JSON_BYTES = 12_000_000
58
+ MAX_FILES = 14
59
+
60
+
61
+ @dataclass
62
+ class SourceFiles:
63
+ """Keyed by a stable kind, so the analyzer never looks at paths again."""
64
+
65
+ label: str
66
+ files: dict[str, str] = field(default_factory=dict)
67
+ paths: dict[str, str] = field(default_factory=dict)
68
+ metadata: dict[str, object] = field(default_factory=dict)
69
+ extra_files: list[str] = field(default_factory=list)
70
+ notes: list[str] = field(default_factory=list)
71
+
72
+ def add(self, kind: str, path: str, text: str) -> None:
73
+ self.files[kind] = text
74
+ self.paths[kind] = path
75
+
76
+
77
+ class SourceError(Exception):
78
+ pass
79
+
80
+
81
+ def _pick(paths: list[str], pattern: re.Pattern[str], prefer_root: bool = True) -> list[str]:
82
+ hits = [p for p in paths if pattern.search(p)]
83
+ hits.sort(key=lambda p: (p.count("/"), len(p)))
84
+ return hits
85
+
86
+
87
+ def parse_target(target: str) -> tuple[str, str, str | None]:
88
+ """Return (owner, repo, ref) for a GitHub target, or ('', path, None) locally."""
89
+ candidate = Path(target)
90
+ if candidate.exists():
91
+ return "", str(candidate.resolve()), None
92
+ match = GITHUB_RE.match(target.strip())
93
+ if match:
94
+ return match.group("owner"), match.group("repo"), match.group("ref")
95
+ match = SLUG_RE.match(target.strip())
96
+ if match:
97
+ return match.group("owner"), match.group("repo"), None
98
+ raise SourceError(
99
+ f"cannot interpret {target!r}: pass a local directory, an owner/repo slug, "
100
+ "or a github.com URL"
101
+ )
102
+
103
+
104
+ # --------------------------------------------------------------------------
105
+ # local checkout
106
+ # --------------------------------------------------------------------------
107
+
108
+
109
+ def from_local(path: str) -> SourceFiles:
110
+ root = Path(path)
111
+ source = SourceFiles(label=f"local:{root}")
112
+ all_files = []
113
+ for candidate in root.rglob("*"):
114
+ if not candidate.is_file():
115
+ continue
116
+ parts = candidate.relative_to(root).parts
117
+ if any(part in SKIP_DIRS for part in parts):
118
+ continue
119
+ all_files.append(candidate.relative_to(root).as_posix())
120
+
121
+ def take(kind: str, pattern: re.Pattern[str], limit: int = 1) -> None:
122
+ for candidate in _pick(all_files, pattern):
123
+ if kind in source.files:
124
+ break
125
+ text = _read_limited(root / candidate)
126
+ if text is not None:
127
+ source.add(kind, candidate, text)
128
+ if limit == 1:
129
+ break
130
+
131
+ take("compose", COMPOSE_RE)
132
+ take("dockerfile", DOCKERFILE_RE)
133
+ take("env_example", ENV_EXAMPLE_RE)
134
+ take("readme", README_RE)
135
+ take("logo", LOGO_RE)
136
+ take("config_sample", CONFIG_SAMPLE_RE)
137
+ for candidate in _pick(all_files, CONFIG_SAMPLE_RE)[:5]:
138
+ source.extra_files.append(candidate)
139
+ return source
140
+
141
+
142
+ def _read_limited(path: Path) -> str | None:
143
+ try:
144
+ raw = path.read_bytes()[:MAX_FILE_BYTES]
145
+ except OSError:
146
+ return None
147
+ if b"\x00" in raw[:1024]:
148
+ return None
149
+ return raw.decode("utf-8", errors="replace")
150
+
151
+
152
+ # --------------------------------------------------------------------------
153
+ # github
154
+ # --------------------------------------------------------------------------
155
+
156
+
157
+ class GitHub:
158
+ def __init__(self, token: str | None = None, timeout: float = 20.0) -> None:
159
+ self.token = token or os.environ.get("GITHUB_TOKEN") or ""
160
+ self.timeout = timeout
161
+ # repo metadata is wanted by both `tree()` and the caller; the
162
+ # unauthenticated GitHub API only allows 60 requests an hour.
163
+ self._cache: dict[str, dict] = {}
164
+
165
+ def _get(self, url: str, limit: int = MAX_FILE_BYTES) -> str:
166
+ request = urllib.request.Request(url)
167
+ request.add_header("Accept", "application/vnd.github+json")
168
+ request.add_header("User-Agent", "p1toolkit-resolve")
169
+ if self.token:
170
+ request.add_header("Authorization", f"Bearer {self.token}")
171
+ try:
172
+ with urllib.request.urlopen(request, timeout=self.timeout) as response:
173
+ data = response.read(limit)
174
+ except urllib.error.HTTPError as exc:
175
+ raise SourceError(f"{url} -> HTTP {exc.code}") from exc
176
+ except urllib.error.URLError as exc:
177
+ raise SourceError(f"{url} -> {exc.reason}") from exc
178
+ except (TimeoutError, OSError) as exc:
179
+ # A slow read raises TimeoutError directly, not a URLError.
180
+ raise SourceError(f"{url} -> {type(exc).__name__}: {exc}") from exc
181
+ return data.decode("utf-8", errors="replace")
182
+
183
+ def json(self, url: str) -> dict:
184
+ try:
185
+ return json.loads(self._get(url, limit=MAX_JSON_BYTES))
186
+ except json.JSONDecodeError as exc:
187
+ raise SourceError(f"{url} returned non-JSON") from exc
188
+
189
+ def raw(self, owner: str, repo: str, ref: str, path: str) -> str:
190
+ url = f"https://raw.githubusercontent.com/{owner}/{repo}/{ref}/{path}"
191
+ return self._get(url)
192
+
193
+ def tree(self, owner: str, repo: str, ref: str | None) -> tuple[list[str], str]:
194
+ info = self.repo_metadata(owner, repo)
195
+ default = str(info.get("default_branch") or "main")
196
+ wanted = ref or default
197
+ tree = self.json(
198
+ f"https://api.github.com/repos/{owner}/{repo}/git/trees/{wanted}?recursive=1"
199
+ )
200
+ paths = [
201
+ str(item["path"])
202
+ for item in tree.get("tree") or []
203
+ if item.get("type") == "blob"
204
+ ]
205
+ return paths, wanted
206
+
207
+ def repo_metadata(self, owner: str, repo: str) -> dict:
208
+ if owner in self._cache:
209
+ return self._cache[owner]
210
+ info = self.json(f"https://api.github.com/repos/{owner}/{repo}")
211
+ license_info = info.get("license") or {}
212
+ metadata = {
213
+ "description": info.get("description"),
214
+ "homepage": info.get("homepage"),
215
+ "stars": info.get("stargazers_count"),
216
+ "license": license_info.get("spdx_id"),
217
+ "default_branch": info.get("default_branch"),
218
+ "archived": info.get("archived"),
219
+ "url": info.get("html_url"),
220
+ }
221
+ self._cache[owner] = metadata
222
+ return metadata
223
+
224
+ def latest_release(self, owner: str, repo: str) -> str | None:
225
+ try:
226
+ data = self.json(f"https://api.github.com/repos/{owner}/{repo}/releases/latest")
227
+ except SourceError:
228
+ return None
229
+ tag = str(data.get("tag_name") or "").strip()
230
+ return tag or None
231
+
232
+
233
+ def from_github(
234
+ owner: str,
235
+ repo: str,
236
+ ref: str | None,
237
+ api: GitHub | None = None,
238
+ budget_seconds: float | None = DEFAULT_FETCH_BUDGET,
239
+ ) -> SourceFiles:
240
+ api = api or GitHub()
241
+ paths, resolved_ref = api.tree(owner, repo, ref)
242
+ source = SourceFiles(label=f"github:{owner}/{repo}@{resolved_ref}")
243
+ source.metadata = api.repo_metadata(owner, repo)
244
+ source.metadata["ref"] = resolved_ref
245
+ release = api.latest_release(owner, repo)
246
+ if release:
247
+ source.metadata["latest_release"] = release
248
+ else:
249
+ source.notes.append("no published GitHub release; version must be chosen manually")
250
+
251
+ budget = MAX_FILES
252
+ # `raw.githubusercontent.com` is intermittently unreachable; every candidate
253
+ # file then costs a full request timeout, and `p1 resolve` sits there for
254
+ # minutes without saying why. A total budget turns that into a clear note.
255
+ # 0 means "no raw fetches at all" (metadata only); None disables the budget.
256
+ deadline = (
257
+ time.monotonic() + budget_seconds if budget_seconds is not None else None
258
+ )
259
+ skipped: list[str] = []
260
+
261
+ def take(kind: str, pattern: re.Pattern[str], limit: int = 1) -> None:
262
+ nonlocal budget
263
+ taken = 0
264
+ for candidate in _pick(paths, pattern):
265
+ if budget <= 0 or taken >= limit:
266
+ break
267
+ if deadline is not None and time.monotonic() >= deadline:
268
+ skipped.append(candidate)
269
+ continue
270
+ try:
271
+ text = api.raw(owner, repo, resolved_ref, candidate)
272
+ except SourceError:
273
+ continue
274
+ source.add(kind, candidate, text)
275
+ budget -= 1
276
+ taken += 1
277
+
278
+ take("compose", COMPOSE_RE)
279
+ take("dockerfile", DOCKERFILE_RE)
280
+ take("env_example", ENV_EXAMPLE_RE)
281
+ take("readme", README_RE)
282
+ take("config_sample", CONFIG_SAMPLE_RE, limit=3)
283
+ # The logo is fetched as raw bytes only when we can hand it to the generator.
284
+ logo_candidates = _pick(paths, LOGO_RE)
285
+ if logo_candidates:
286
+ source.paths["logo"] = logo_candidates[0]
287
+ if budget <= 0:
288
+ source.notes.append("file budget exhausted; some upstream files were not fetched")
289
+ if skipped:
290
+ shown = "、".join(skipped[:3]) + (" …" if len(skipped) > 3 else "")
291
+ source.notes.append(
292
+ f"raw 抓取超过 {budget_seconds:.0f}s 预算,跳过 {len(skipped)} 个候选文件({shown});"
293
+ "网络恢复后重试,或用 `p1 resolve --timeout <秒>` 放宽,或改用本地检出"
294
+ )
295
+ return source
296
+
297
+
298
+ def load(
299
+ target: str,
300
+ api: GitHub | None = None,
301
+ budget_seconds: float | None = DEFAULT_FETCH_BUDGET,
302
+ ) -> SourceFiles:
303
+ owner, repo, ref = parse_target(target)
304
+ if owner:
305
+ return from_github(owner, repo, ref, api=api, budget_seconds=budget_seconds)
306
+ return from_local(repo)