Files
.github/tools/migration-inventory.py
poli0981andClaude Opus 5.5 966549d128 feat(tools): detect Flutter and Go in migration-inventory
MarkLens is a Flutter app (pubspec.yaml); go.mod is detected for the
same reason. The stack line now names them instead of reporting none.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MnPQKxkPgL2sb8BqwHKv5k
2026-11-23 19:46:35 +07:00

282 lines
13 KiB
Python

"""Read-only Gitea-migration inventory of local repos (runbook §3.1).
Usage, from anywhere:
python3 tools/migration-inventory.py [--json OUT.json] [REPO_DIR ...] (default: .)
Nothing is written inside the repos. For each repo it reports the git state, every workflow
(where it lives, triggers, crons and whether they fit 13:00-16:00 UTC, runners, actions that do
not work on Gitea, unpinned actions, unsupported permissions, secrets, calls to the ops repo),
migration markers (renovate.json, dependabot, SECURITY.md, GitLab templates, ...) and the
GitHub references left in tracked files. Needs Python 3.10+; PyYAML is optional (without it,
triggers, runners and permissions are not parsed).
"""
import json
import pathlib
import re
import subprocess
import sys
try:
import yaml # PyYAML
except ImportError: # pragma: no cover
yaml = None
SKIP_DIRS = {".git", "node_modules", "bin", "obj", "target", "dist", "build", ".svelte-kit", ".next",
".astro", ".wrangler", "vendor", ".venv", "venv", "__pycache__", ".idea", ".vs", ".claude",
"coverage", ".output", ".turbo", "packages", "out", ".pnpm-store", "TestResults"}
TEXT_EXT = {".md", ".json", ".jsonc", ".toml", ".yml", ".yaml", ".cs", ".csproj", ".props", ".targets",
".resx", ".xaml", ".ts", ".tsx", ".js", ".mjs", ".cjs", ".svelte", ".astro", ".py", ".rs",
".html", ".txt", ".cfg", ".ini", ".xml", ".sh", ".ps1", ".iss", ".nuspec", ".gitmodules"}
GH_PATTERNS = {
"github.com/poli0981": re.compile(r"github\.com/poli0981(?:org)?\b", re.I),
"githubusercontent": re.compile(r"githubusercontent\.com", re.I),
"api.github.com": re.compile(r"api\.github\.com", re.I),
"github.io": re.compile(r"\.github\.io", re.I),
"GithubSource": re.compile(r"GithubSource"),
}
UNSUPPORTED_PERMS = {"id-token", "statuses", "checks", "deployments", "security-events", "pages", "attestations"}
BAD_ACTIONS = {
"github/codeql-action": "CodeQL (not on Gitea)",
"actions/upload-artifact": "upstream artifact v4 (use christopherhx/gitea-upload-artifact)",
"actions/download-artifact": "upstream artifact v4 (use christopherhx/gitea-download-artifact)",
"softprops/action-gh-release": "GitHub release action",
"ncipollo/release-action": "GitHub release action",
"tauri-apps/tauri-action": "tauri-action (build with Tauri CLI + R2)",
"cloudflare/wrangler-action": "wrangler-action (use npx wrangler deploy)",
"JetBrains/qodana-action": "qodana-action (use Qodana CLI)",
"aquasecurity/trivy-action": "trivy-action (removed, supply-chain incident)",
"aquasecurity/setup-trivy": "setup-trivy (removed)",
"actions/github-script": "github-script (GitHub API)",
"actions/configure-pages": "GitHub Pages",
"actions/upload-pages-artifact": "GitHub Pages",
"actions/deploy-pages": "GitHub Pages",
"actions/dependency-review-action": "dependency review (GitHub only)",
"actions/attest-build-provenance": "attestations (GitHub only)",
"actions/stale": "stale bot",
"SonarSource/sonarqube-scan-action": "SonarCloud (dropped)",
"SonarSource/sonarcloud-github-action": "SonarCloud (dropped)",
}
SHA_RE = re.compile(r"@[0-9a-f]{40}\b")
def git(repo, *args):
r = subprocess.run(["git", "-C", str(repo), "-c", "core.autocrlf=true", *args],
capture_output=True, text=True)
return r.stdout.strip()
def walk_text_files(root):
"""Tracked files only (git ls-files): build output and reports are not the repo."""
listed = git(root, "ls-files", "-z")
if listed:
for rel in listed.split("\0"):
p = root / rel
if rel and (p.suffix.lower() in TEXT_EXT or p.name in {"Dockerfile", ".gitmodules", "CODEOWNERS"}):
try:
if p.is_file() and p.stat().st_size <= 2_000_000:
yield p
except OSError:
pass
return
stack = [root]
while stack:
d = stack.pop()
try:
entries = list(d.iterdir())
except OSError:
continue
for p in entries:
if p.is_dir():
if p.name not in SKIP_DIRS and not p.is_symlink():
stack.append(p)
elif p.suffix.lower() in TEXT_EXT or p.name in {"Dockerfile", ".gitmodules", "CODEOWNERS"}:
try:
if p.stat().st_size <= 2_000_000:
yield p
except OSError:
pass
def triggers_of(doc):
on = doc.get("on", doc.get(True)) # PyYAML parses bare `on` as True
if isinstance(on, str):
return [on], []
if isinstance(on, list):
return on, []
if isinstance(on, dict):
crons = [c.get("cron") for c in (on.get("schedule") or []) if isinstance(c, dict)]
return list(on.keys()), crons
return [], []
def analyse_workflow(path):
text = path.read_text(encoding="utf-8", errors="replace")
info = {"file": path.name, "triggers": [], "crons": [], "runs_on": [], "uses": [], "unpinned": [],
"bad_actions": [], "unsupported_perms": [], "secrets": sorted(set(re.findall(r"secrets\.([A-Za-z0-9_]+)", text))),
"vars": sorted(set(re.findall(r"vars\.([A-Za-z0-9_]+)", text))), "ops_calls": [], "name": None,
"macos": bool(re.search(r"macos-", text)), "parse_error": None}
for line in text.splitlines():
m = re.match(r"\s*-?\s*uses:\s*([^\s#]+)", line)
if not m:
continue
ref = m.group(1).strip("'\"")
info["uses"].append(ref)
base = ref.split("@")[0]
if "poli0981/.github/" in ref:
info["ops_calls"].append(ref)
elif not ref.startswith("./") and not ref.startswith("$/") and not ref.startswith("docker://") \
and not SHA_RE.search(ref):
info["unpinned"].append(ref)
for bad, why in BAD_ACTIONS.items():
if base.lower().startswith(bad.lower()):
info["bad_actions"].append(f"{base}: {why}")
if yaml:
try:
doc = yaml.safe_load(text) or {}
info["name"] = doc.get("name")
info["triggers"], info["crons"] = triggers_of(doc)
perms = []
if isinstance(doc.get("permissions"), dict):
perms += list(doc["permissions"].keys())
for job in (doc.get("jobs") or {}).values():
if not isinstance(job, dict):
continue
ro = job.get("runs-on")
if ro is not None:
info["runs_on"].append(ro if isinstance(ro, str) else json.dumps(ro))
if isinstance(job.get("permissions"), dict):
perms += list(job["permissions"].keys())
info["unsupported_perms"] = sorted(set(perms) & UNSUPPORTED_PERMS)
info["triggers"] = [str(t) for t in info["triggers"]]
except Exception as e: # noqa: BLE001
info["parse_error"] = str(e)[:200]
info["runs_on"] = sorted(set(info["runs_on"]))
return info
def detect_stack(root):
s = []
names = {p.name for p in root.iterdir()}
tracked = git(root, "ls-files").splitlines()
if any(t.endswith((".sln", ".slnx", ".csproj")) for t in tracked):
s.append("dotnet")
if any(t.endswith("tauri.conf.json") for t in tracked):
s.append("tauri")
if "package.json" in names:
pkg = (root / "package.json").read_text(encoding="utf-8", errors="replace")
for fw in ("wxt", "@sveltejs/kit", "astro", "react", "vite", "svelte"):
if f'"{fw}"' in pkg:
s.append(f"node:{fw}")
break
else:
s.append("node")
if "Cargo.toml" in names or (root / "src-tauri" / "Cargo.toml").exists():
s.append("rust")
if "pyproject.toml" in names or "requirements.txt" in names:
s.append("python")
if "pubspec.yaml" in names:
s.append("flutter")
if "go.mod" in names:
s.append("go")
if names & {"wrangler.jsonc", "wrangler.json", "wrangler.toml"}:
s.append("workers")
return s
def inventory(root):
root = pathlib.Path(root).resolve()
r = {"repo": root.name, "branch": git(root, "branch", "--show-current"),
"dirty": [l for l in git(root, "status", "--short").splitlines() if l and not l.startswith("?? .claude")],
"has_migration_branch": bool(git(root, "branch", "--list", "chore/gitea-migration")),
"remote_origin": git(root, "remote", "get-url", "origin"),
"stack": detect_stack(root), "workflows": {}, "files": {}, "github_refs": {}, "github_ref_files": {}}
for d in (".github/workflows", ".gitea/workflows"):
p = root / d
if p.is_dir():
r["workflows"][d] = [analyse_workflow(f) for f in sorted(p.iterdir())
if f.suffix in (".yml", ".yaml")]
checks = {
"dependabot": ".github/dependabot.yml", "renovate.json": "renovate.json",
"SECURITY.md": "SECURITY.md", "CONTRIBUTING.md": "CONTRIBUTING.md", "CLAUDE.md": "CLAUDE.md",
"qodana.yaml": "qodana.yaml", "deny.toml": "deny.toml", "gitlab_issue_templates": ".gitlab/issue_templates",
"gitlab_mr_templates": ".gitlab/merge_request_templates", "gh_issue_templates": ".github/ISSUE_TEMPLATE",
"gh_pr_template": ".github/pull_request_template.md", "CODEOWNERS": ".github/CODEOWNERS",
"FUNDING": ".github/FUNDING.yml", "gitea_issue_templates": ".gitea/ISSUE_TEMPLATE",
}
for k, rel in checks.items():
r["files"][k] = (root / rel).exists()
sec = root / "SECURITY.md"
if sec.exists():
t = sec.read_text(encoding="utf-8", errors="replace")
r["files"]["SECURITY_mentions_github_advisory"] = bool(re.search(r"security/advisories|private vulnerability|Report a vulnerability", t, re.I))
r["files"]["SECURITY_mentions_security_at"] = "security@poli0981.dev" in t
emails = set()
for f in walk_text_files(root):
try:
t = f.read_text(encoding="utf-8", errors="replace")
except OSError:
continue
rel = str(f.relative_to(root)).replace("\\", "/")
for key, rx in GH_PATTERNS.items():
n = len(rx.findall(t))
if n:
r["github_refs"][key] = r["github_refs"].get(key, 0) + n
r["github_ref_files"].setdefault(key, []).append(f"{rel}:{n}")
emails.update(re.findall(r"[A-Za-z0-9._%+-]+@poli0981\.dev", t))
r["emails"] = sorted(emails)
for k in r["github_ref_files"]:
r["github_ref_files"][k] = sorted(r["github_ref_files"][k], key=lambda s: -int(s.rsplit(":", 1)[1]))[:25]
return r
def cron_in_window(expr):
"""True when every hour of a 5-field cron is inside 13-15 (13:00-16:00 UTC) and the minute is fixed."""
parts = (expr or "").split()
if len(parts) != 5 or not parts[0].isdigit():
return False
hours = parts[1].split(",")
return all(h.isdigit() and 13 <= int(h) <= 15 for h in hours)
def main():
args = sys.argv[1:]
out = None
if args[:1] == ["--json"]:
out, args = pathlib.Path(args[1]), args[2:]
data = [inventory(p) for p in (args or ["."])]
for r in data:
for items in r["workflows"].values():
for w in items:
w["crons_outside_window"] = [c for c in w["crons"] if not cron_in_window(c)]
if out:
out.write_text(json.dumps(data, indent=1, default=str), encoding="utf-8")
for r in data:
wf = r["workflows"]
print(f"\n## {r['repo']} [{', '.join(r['stack'])}] branch={r['branch']} migration-branch={r['has_migration_branch']} dirty={len(r['dirty'])}")
for d, items in wf.items():
print(f" {d}: {len(items)} workflows")
for w in items:
flags = []
if w["crons"]:
flags.append("cron=" + ",".join(w["crons"]))
if w["crons_outside_window"]:
flags.append("CRON-OUTSIDE-13-16-UTC")
if w["bad_actions"]:
flags.append("BAD=" + "; ".join(sorted(set(w["bad_actions"]))))
if w["unpinned"]:
flags.append(f"unpinned={len(w['unpinned'])}")
if w["unsupported_perms"]:
flags.append("perms=" + ",".join(w["unsupported_perms"]))
if w["macos"]:
flags.append("macOS")
if w["ops_calls"]:
flags.append("ops=" + ",".join(sorted({c.split('/')[-1] for c in w['ops_calls']})))
print(f" - {w['file']}: on={','.join(w['triggers'])} runs-on={','.join(w['runs_on'])} secrets={','.join(w['secrets'])} {' '.join(flags)}")
print(" files: " + ", ".join(k for k, v in r["files"].items() if v))
print(" github refs: " + json.dumps(r["github_refs"]))
print(" emails: " + ", ".join(r["emails"]))
if __name__ == "__main__":
main()