Repository navigation
Expand file tree
/
Copy pathaudit_github_repos.py
More file actions
316 lines (268 loc) · 9.64 KB
/
Copy pathaudit_github_repos.py
File metadata and controls
316 lines (268 loc) · 9.64 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
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import json
import subprocess
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import asdict, dataclass, field
from datetime import UTC, datetime, timedelta
from pathlib import Path
from typing import Any, Callable
from urllib.parse import urlparse
import yaml
GH_FIELDS = (
"nameWithOwner,url,isArchived,isPrivate,defaultBranchRef,pushedAt,"
"primaryLanguage,description,stargazerCount"
)
Runner = Callable[[list[str]], tuple[int, str, str]]
@dataclass
class AuditResult:
name: str
url: str
reachable: bool
skipped: bool = False
archived: bool | None = None
private: bool | None = None
default_branch: str = ""
pushed_at: str = ""
primary_language: str = ""
description: str = ""
stars: int | None = None
error: str = ""
warnings: list[str] = field(default_factory=list)
def resolve_cli_path(path: Path, root: Path | None = None) -> Path:
"""Resolve a CLI path and require it to remain inside the working tree."""
allowed_root = (root or Path.cwd()).resolve()
candidate = path.expanduser()
resolved = (
candidate.resolve()
if candidate.is_absolute()
else (allowed_root / candidate).resolve()
)
try:
resolved.relative_to(allowed_root)
except ValueError as exc:
raise ValueError(f"path escapes the working tree: {path}") from exc
return resolved
def parse_github_repo(value: str) -> tuple[str, str]:
if value.startswith(("http://", "https://")):
parsed = urlparse(value)
if parsed.netloc.lower() != "github.com":
raise ValueError(f"{value!r} is not a GitHub repo URL")
parts = [part for part in parsed.path.split("/") if part]
else:
parts = [part for part in value.split("/") if part]
if len(parts) < 2:
raise ValueError(f"{value!r} is not a GitHub repo reference")
return parts[0], parts[1]
def run_command(cmd: list[str]) -> tuple[int, str, str]:
completed = subprocess.run(
cmd,
check=False,
capture_output=True,
text=True,
)
return completed.returncode, completed.stdout, completed.stderr
def _parse_github_timestamp(value: str) -> datetime | None:
if not value:
return None
try:
return datetime.fromisoformat(value.replace("Z", "+00:00"))
except ValueError:
return None
def _field_warnings(
entry: dict[str, Any],
metadata: dict[str, Any],
*,
stale_days: int | None = 365,
now: datetime | None = None,
) -> list[str]:
warnings: list[str] = []
expected_language = str(entry.get("primary_language", "")).strip()
actual_language = (metadata.get("primaryLanguage") or {}).get("name") or ""
if expected_language and expected_language.lower() not in {"unknown", "markdown"}:
if actual_language and actual_language.lower() != expected_language.lower():
warnings.append(
f"primary_language is {expected_language!r}, GitHub reports {actual_language!r}"
)
if metadata.get("isArchived"):
warnings.append("repository is archived")
if metadata.get("isPrivate"):
warnings.append("repository is private")
pushed_at = _parse_github_timestamp(metadata.get("pushedAt") or "")
if stale_days and pushed_at:
reference_time = now or datetime.now(UTC)
if pushed_at < reference_time - timedelta(days=stale_days):
warnings.append(f"repository has not been pushed in {stale_days}+ days")
return warnings
def audit_repo(
entry: dict[str, Any],
runner: Runner = run_command,
*,
stale_days: int | None = 365,
now: datetime | None = None,
) -> AuditResult:
name = str(entry["name"])
url = str(entry["url"])
try:
owner, repo = parse_github_repo(url)
except ValueError as exc:
return AuditResult(
name=name,
url=url,
reachable=False,
skipped=True,
error=str(exc),
warnings=["skipped: not a GitHub repository"],
)
repo_ref = f"{owner}/{repo}"
cmd = ["gh", "repo", "view", repo_ref, "--json", GH_FIELDS]
returncode, stdout, stderr = runner(cmd)
if returncode != 0:
return AuditResult(
name=name,
url=url,
reachable=False,
error=(stderr or stdout).strip(),
)
try:
metadata = json.loads(stdout)
except json.JSONDecodeError as exc:
return AuditResult(
name=name,
url=url,
reachable=False,
error=f"invalid gh JSON output: {exc}",
)
default_branch = metadata.get("defaultBranchRef") or {}
primary_language = metadata.get("primaryLanguage") or {}
return AuditResult(
name=name,
url=metadata.get("url") or url,
reachable=True,
archived=metadata.get("isArchived"),
private=metadata.get("isPrivate"),
default_branch=default_branch.get("name") or "",
pushed_at=metadata.get("pushedAt") or "",
primary_language=primary_language.get("name") or "",
description=metadata.get("description") or "",
stars=metadata.get("stargazerCount"),
warnings=_field_warnings(entry, metadata, stale_days=stale_days, now=now),
)
def load_entries(path: Path) -> list[dict[str, Any]]:
with path.open("r", encoding="utf-8") as handle:
data = yaml.safe_load(handle)
if not isinstance(data, list):
raise ValueError(f"{path} must contain a list")
return data
def audit_entries(
entries: list[dict[str, Any]],
workers: int,
*,
stale_days: int | None = 365,
) -> list[AuditResult]:
results: list[AuditResult] = []
with ThreadPoolExecutor(max_workers=workers) as executor:
futures = [
executor.submit(audit_repo, entry, stale_days=stale_days)
for entry in entries
]
for future in as_completed(futures):
results.append(future.result())
return sorted(results, key=lambda result: result.name.lower())
def build_summary(results: list[AuditResult]) -> dict[str, int]:
return {
"total": len(results),
"reachable": sum(1 for result in results if result.reachable),
"unreachable": sum(
1 for result in results if not result.reachable and not result.skipped
),
"skipped": sum(1 for result in results if result.skipped),
"archived": sum(1 for result in results if result.archived),
"with_warnings": sum(1 for result in results if result.warnings),
}
def _markdown_row(result: AuditResult) -> str:
if result.skipped:
reachable = "skipped"
else:
reachable = "yes" if result.reachable else "no"
if result.archived is None:
archived = ""
else:
archived = "yes" if result.archived else "no"
warnings = "; ".join(result.warnings) if result.warnings else result.error
return (
f"| {result.name} | {reachable} | {archived} | "
f"{result.primary_language} | {result.pushed_at} | {warnings} |"
)
def write_report(
results: list[AuditResult],
json_path: Path,
markdown_path: Path,
) -> None:
json_path.parent.mkdir(parents=True, exist_ok=True)
markdown_path.parent.mkdir(parents=True, exist_ok=True)
payload = {
"summary": build_summary(results),
"results": [asdict(result) for result in results],
}
json_path.write_text(json.dumps(payload, indent=2, sort_keys=True), encoding="utf-8")
lines = [
"# GitHub Repo Audit",
"",
"| Repo | Reachable | Archived | Language | Pushed at | Warnings/errors |",
"| --- | --- | --- | --- | --- | --- |",
]
lines.extend(_markdown_row(result) for result in results)
markdown_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
def main() -> int:
parser = argparse.ArgumentParser(description="Audit GitHub repos in data/repos.yaml")
parser.add_argument("--data", type=Path, default=Path("data/repos.yaml"))
parser.add_argument(
"--json-output",
type=Path,
default=Path("reports/github-repo-audit.json"),
)
parser.add_argument(
"--markdown-output",
type=Path,
default=Path("reports/github-repo-audit.md"),
)
parser.add_argument("--workers", type=int, default=8)
parser.add_argument(
"--stale-days",
type=int,
default=365,
help="Warn when GitHub repos have no pushes in this many days; use 0 to disable.",
)
parser.add_argument("--fail-on-unreachable", action="store_true")
args = parser.parse_args()
try:
data_path = resolve_cli_path(args.data)
json_path = resolve_cli_path(args.json_output)
markdown_path = resolve_cli_path(args.markdown_output)
except ValueError as exc:
parser.error(str(exc))
entries = load_entries(data_path)
stale_days = args.stale_days if args.stale_days > 0 else None
results = audit_entries(
entries,
workers=max(1, args.workers),
stale_days=stale_days,
)
write_report(results, json_path=json_path, markdown_path=markdown_path)
summary = build_summary(results)
print(
"GitHub audit complete: "
f"{summary['reachable']}/{summary['total']} reachable, "
f"{summary['skipped']} skipped, "
f"{summary['archived']} archived, "
f"{summary['with_warnings']} with warnings"
)
print(f"JSON report: {json_path}")
print(f"Markdown report: {markdown_path}")
if args.fail_on_unreachable and summary["unreachable"]:
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())