|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Refresh Current Snapshot sections in tutorial README.md files. |
| 3 | +
|
| 4 | +For each tutorial: |
| 5 | +1. Read the README.md |
| 6 | +2. Look up source repo from tutorial-source-verification.json |
| 7 | +3. Fetch latest repo metadata and release from GitHub API |
| 8 | +4. Update or insert the Current Snapshot section |
| 9 | +""" |
| 10 | + |
| 11 | +from __future__ import annotations |
| 12 | + |
| 13 | +import argparse |
| 14 | +import json |
| 15 | +import os |
| 16 | +import re |
| 17 | +import sys |
| 18 | +from concurrent.futures import ThreadPoolExecutor, as_completed |
| 19 | +from datetime import datetime, timezone |
| 20 | +from pathlib import Path |
| 21 | +from typing import Any |
| 22 | +from urllib.error import HTTPError, URLError |
| 23 | +from urllib.request import Request, urlopen |
| 24 | + |
| 25 | +# --------------------------------------------------------------------------- |
| 26 | +# GitHub API helpers |
| 27 | +# --------------------------------------------------------------------------- |
| 28 | + |
| 29 | +def _gh_request(url: str, token: str | None) -> dict[str, Any] | None: |
| 30 | + req = Request(url) |
| 31 | + req.add_header("Accept", "application/vnd.github+json") |
| 32 | + req.add_header("User-Agent", "awesome-code-docs-snapshot-refresh") |
| 33 | + if token: |
| 34 | + req.add_header("Authorization", f"Bearer {token}") |
| 35 | + try: |
| 36 | + with urlopen(req, timeout=30) as resp: |
| 37 | + return json.loads(resp.read().decode("utf-8")) |
| 38 | + except HTTPError as exc: |
| 39 | + if exc.code == 404: |
| 40 | + return None |
| 41 | + if exc.code == 403: |
| 42 | + print(f" RATE LIMITED on {url}", file=sys.stderr) |
| 43 | + return None |
| 44 | + print(f" HTTP {exc.code} on {url}", file=sys.stderr) |
| 45 | + return None |
| 46 | + except URLError as exc: |
| 47 | + print(f" URL error on {url}: {exc.reason}", file=sys.stderr) |
| 48 | + return None |
| 49 | + |
| 50 | + |
| 51 | +def fetch_repo_data(repo: str, token: str | None) -> dict[str, Any]: |
| 52 | + """Fetch repo metadata + latest release for a GitHub repo.""" |
| 53 | + base = _gh_request(f"https://api.github.com/repos/{repo}", token) |
| 54 | + if not base: |
| 55 | + return {"repo": repo, "stars": None, "release_tag": None} |
| 56 | + |
| 57 | + stars = base.get("stargazers_count", 0) |
| 58 | + archived = base.get("archived", False) |
| 59 | + pushed_at = base.get("pushed_at", "") |
| 60 | + |
| 61 | + release = _gh_request( |
| 62 | + f"https://api.github.com/repos/{repo}/releases/latest", token |
| 63 | + ) |
| 64 | + release_tag = None |
| 65 | + release_date = None |
| 66 | + if release and not release.get("prerelease"): |
| 67 | + release_tag = release.get("tag_name") |
| 68 | + pub = release.get("published_at", "") |
| 69 | + if pub: |
| 70 | + try: |
| 71 | + release_date = datetime.fromisoformat( |
| 72 | + pub.replace("Z", "+00:00") |
| 73 | + ).strftime("%Y-%m-%d") |
| 74 | + except ValueError: |
| 75 | + pass |
| 76 | + |
| 77 | + return { |
| 78 | + "repo": repo, |
| 79 | + "stars": stars, |
| 80 | + "archived": archived, |
| 81 | + "pushed_at": pushed_at, |
| 82 | + "release_tag": release_tag, |
| 83 | + "release_date": release_date, |
| 84 | + } |
| 85 | + |
| 86 | + |
| 87 | +# --------------------------------------------------------------------------- |
| 88 | +# Source mapping |
| 89 | +# --------------------------------------------------------------------------- |
| 90 | + |
| 91 | +def load_source_mapping(root: Path) -> dict[str, str]: |
| 92 | + """Build {tutorial_slug: primary_repo} from verification JSON.""" |
| 93 | + verify_path = root / "discoverability" / "tutorial-source-verification.json" |
| 94 | + if not verify_path.is_file(): |
| 95 | + print(f"Missing {verify_path}", file=sys.stderr) |
| 96 | + return {} |
| 97 | + |
| 98 | + data = json.loads(verify_path.read_text(encoding="utf-8")) |
| 99 | + tutorials_root = root / "tutorials" |
| 100 | + |
| 101 | + # Build repo -> tutorial slug mapping from the per-tutorial records |
| 102 | + slug_to_repo: dict[str, str] = {} |
| 103 | + for entry in data.get("top_verified_repos_by_stars", []): |
| 104 | + repo = entry.get("repo", "") |
| 105 | + if not repo: |
| 106 | + continue |
| 107 | + # Find which tutorial(s) reference this repo |
| 108 | + # We need to scan tutorial README.md files for the repo URL |
| 109 | + pass |
| 110 | + |
| 111 | + # Alternative approach: scan each tutorial README.md for the first GitHub repo link |
| 112 | + github_re = re.compile( |
| 113 | + r"https://github\.com/([A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+)" |
| 114 | + ) |
| 115 | + for tdir in sorted(tutorials_root.iterdir()): |
| 116 | + if not tdir.is_dir(): |
| 117 | + continue |
| 118 | + readme = tdir / "README.md" |
| 119 | + if not readme.is_file(): |
| 120 | + continue |
| 121 | + text = readme.read_text(encoding="utf-8") |
| 122 | + # Look for repo in Current Snapshot section first |
| 123 | + snapshot_match = re.search( |
| 124 | + r"repository:\s*\[`([^`]+)`\]", text |
| 125 | + ) |
| 126 | + if snapshot_match: |
| 127 | + slug_to_repo[tdir.name] = snapshot_match.group(1) |
| 128 | + continue |
| 129 | + # Fall back to first GitHub repo badge |
| 130 | + badge_match = re.search( |
| 131 | + r"GitHub-([A-Za-z0-9_.-]+%2F[A-Za-z0-9_.-]+)", text |
| 132 | + ) |
| 133 | + if badge_match: |
| 134 | + slug_to_repo[tdir.name] = badge_match.group(1).replace("%2F", "/") |
| 135 | + continue |
| 136 | + # Fall back to first GitHub link after the title |
| 137 | + links = github_re.findall(text) |
| 138 | + # Filter out common non-repo links |
| 139 | + for link in links: |
| 140 | + parts = link.split("/") |
| 141 | + if len(parts) >= 2 and parts[0] not in ( |
| 142 | + "johnxie", "The-Pocket", "actions", |
| 143 | + ): |
| 144 | + slug_to_repo[tdir.name] = link |
| 145 | + break |
| 146 | + |
| 147 | + return slug_to_repo |
| 148 | + |
| 149 | + |
| 150 | +# --------------------------------------------------------------------------- |
| 151 | +# Snapshot formatting |
| 152 | +# --------------------------------------------------------------------------- |
| 153 | + |
| 154 | +def format_stars(count: int) -> str: |
| 155 | + """Format star count as human-readable string.""" |
| 156 | + if count >= 1000: |
| 157 | + val = count / 1000 |
| 158 | + if val >= 100: |
| 159 | + return f"**{val:,.0f}k**" |
| 160 | + return f"**{val:,.1f}k**".replace(".0k", "k") |
| 161 | + return f"**{count}**" |
| 162 | + |
| 163 | + |
| 164 | +def build_snapshot_lines(data: dict[str, Any]) -> list[str]: |
| 165 | + """Build the Current Snapshot section lines.""" |
| 166 | + repo = data["repo"] |
| 167 | + lines = [ |
| 168 | + "## Current Snapshot (auto-updated)", |
| 169 | + "", |
| 170 | + f"- repository: [`{repo}`](https://github.com/{repo})", |
| 171 | + ] |
| 172 | + if data.get("stars") is not None: |
| 173 | + lines.append(f"- stars: about {format_stars(data['stars'])}") |
| 174 | + if data.get("release_tag"): |
| 175 | + tag = data["release_tag"] |
| 176 | + release_line = f"- latest release: [`{tag}`](https://github.com/{repo}/releases/tag/{tag})" |
| 177 | + if data.get("release_date"): |
| 178 | + release_line += f" (published {data['release_date']})" |
| 179 | + lines.append(release_line) |
| 180 | + if data.get("archived"): |
| 181 | + lines.append("- status: **archived**") |
| 182 | + return lines |
| 183 | + |
| 184 | + |
| 185 | +# --------------------------------------------------------------------------- |
| 186 | +# README.md update logic |
| 187 | +# --------------------------------------------------------------------------- |
| 188 | + |
| 189 | +SNAPSHOT_HEADING = re.compile(r"^## Current Snapshot", re.MULTILINE) |
| 190 | +NEXT_H2 = re.compile(r"^## ", re.MULTILINE) |
| 191 | + |
| 192 | + |
| 193 | +def update_readme_snapshot(readme_path: Path, snapshot_lines: list[str]) -> bool: |
| 194 | + """Update or insert Current Snapshot section in a tutorial README.md. |
| 195 | +
|
| 196 | + Returns True if the file was modified. |
| 197 | + """ |
| 198 | + text = readme_path.read_text(encoding="utf-8") |
| 199 | + new_section = "\n".join(snapshot_lines) |
| 200 | + |
| 201 | + m = SNAPSHOT_HEADING.search(text) |
| 202 | + if m: |
| 203 | + # Find the end of this section (next ## heading or EOF) |
| 204 | + rest = text[m.end():] |
| 205 | + next_h2 = NEXT_H2.search(rest) |
| 206 | + if next_h2: |
| 207 | + end_pos = m.end() + next_h2.start() |
| 208 | + else: |
| 209 | + end_pos = len(text) |
| 210 | + # Replace the section |
| 211 | + updated = text[:m.start()] + new_section + "\n\n" + text[end_pos:] |
| 212 | + else: |
| 213 | + # Insert after ## Why This Track Matters / ## Why This Tutorial Exists |
| 214 | + insert_re = re.compile( |
| 215 | + r"^(## Why This (?:Track Matters|Tutorial Exists).*?)(?=^## )", |
| 216 | + re.MULTILINE | re.DOTALL, |
| 217 | + ) |
| 218 | + im = insert_re.search(text) |
| 219 | + if im: |
| 220 | + insert_pos = im.end() |
| 221 | + updated = text[:insert_pos] + new_section + "\n\n" + text[insert_pos:] |
| 222 | + else: |
| 223 | + # Insert after first ## heading section |
| 224 | + first_h2 = NEXT_H2.search(text) |
| 225 | + if first_h2: |
| 226 | + rest_after = text[first_h2.end():] |
| 227 | + second_h2 = NEXT_H2.search(rest_after) |
| 228 | + if second_h2: |
| 229 | + insert_pos = first_h2.end() + second_h2.start() |
| 230 | + else: |
| 231 | + insert_pos = len(text) |
| 232 | + updated = text[:insert_pos] + new_section + "\n\n" + text[insert_pos:] |
| 233 | + else: |
| 234 | + # Append at end |
| 235 | + updated = text.rstrip() + "\n\n" + new_section + "\n" |
| 236 | + |
| 237 | + if updated == text: |
| 238 | + return False |
| 239 | + |
| 240 | + readme_path.write_text(updated, encoding="utf-8") |
| 241 | + return True |
| 242 | + |
| 243 | + |
| 244 | +# --------------------------------------------------------------------------- |
| 245 | +# Main |
| 246 | +# --------------------------------------------------------------------------- |
| 247 | + |
| 248 | +def main() -> int: |
| 249 | + parser = argparse.ArgumentParser( |
| 250 | + description="Refresh Current Snapshot sections in tutorial README.md files" |
| 251 | + ) |
| 252 | + parser.add_argument("--root", default=".", help="Repository root") |
| 253 | + parser.add_argument("--workers", type=int, default=16, help="API concurrency") |
| 254 | + parser.add_argument("--dry-run", action="store_true", help="Print changes without writing") |
| 255 | + args = parser.parse_args() |
| 256 | + |
| 257 | + root = Path(args.root).resolve() |
| 258 | + token = os.getenv("GITHUB_TOKEN") |
| 259 | + if not token: |
| 260 | + print("Warning: GITHUB_TOKEN not set; API rate limit is 60 req/hr", file=sys.stderr) |
| 261 | + |
| 262 | + # Load tutorial -> repo mapping |
| 263 | + slug_to_repo = load_source_mapping(root) |
| 264 | + print(f"tutorials_mapped={len(slug_to_repo)}") |
| 265 | + |
| 266 | + # Deduplicate repos and fetch data |
| 267 | + unique_repos = sorted(set(slug_to_repo.values())) |
| 268 | + print(f"unique_repos_to_fetch={len(unique_repos)}") |
| 269 | + |
| 270 | + repo_data: dict[str, dict[str, Any]] = {} |
| 271 | + with ThreadPoolExecutor(max_workers=args.workers) as pool: |
| 272 | + futures = { |
| 273 | + pool.submit(fetch_repo_data, repo, token): repo |
| 274 | + for repo in unique_repos |
| 275 | + } |
| 276 | + for i, future in enumerate(as_completed(futures), 1): |
| 277 | + repo = futures[future] |
| 278 | + try: |
| 279 | + result = future.result() |
| 280 | + repo_data[repo] = result |
| 281 | + except Exception as exc: |
| 282 | + print(f" FAILED {repo}: {exc}", file=sys.stderr) |
| 283 | + repo_data[repo] = {"repo": repo, "stars": None, "release_tag": None} |
| 284 | + if i % 50 == 0: |
| 285 | + print(f" fetched {i}/{len(unique_repos)}") |
| 286 | + |
| 287 | + print(f"repos_fetched={len(repo_data)}") |
| 288 | + |
| 289 | + # Update each tutorial |
| 290 | + updated_count = 0 |
| 291 | + skipped_count = 0 |
| 292 | + for slug, repo in sorted(slug_to_repo.items()): |
| 293 | + readme_path = root / "tutorials" / slug / "README.md" |
| 294 | + if not readme_path.is_file(): |
| 295 | + continue |
| 296 | + |
| 297 | + data = repo_data.get(repo) |
| 298 | + if not data or data.get("stars") is None: |
| 299 | + skipped_count += 1 |
| 300 | + continue |
| 301 | + |
| 302 | + snapshot_lines = build_snapshot_lines(data) |
| 303 | + |
| 304 | + if args.dry_run: |
| 305 | + print(f" WOULD UPDATE {slug}: {data.get('stars')} stars, release={data.get('release_tag')}") |
| 306 | + updated_count += 1 |
| 307 | + else: |
| 308 | + if update_readme_snapshot(readme_path, snapshot_lines): |
| 309 | + updated_count += 1 |
| 310 | + |
| 311 | + print(f"tutorials_updated={updated_count}") |
| 312 | + print(f"tutorials_skipped={skipped_count}") |
| 313 | + return 0 |
| 314 | + |
| 315 | + |
| 316 | +if __name__ == "__main__": |
| 317 | + raise SystemExit(main()) |
0 commit comments