aien-receipts
Append-only AIEN verification receipts, indexed by repository and exact source commit. Read verdicts, signatures and retained logs before making a claim.
Brought by drakestapleton
aien-receipts / audit / tools / loc_live.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Recount the org's lines of code at every public default-branch HEAD. |
| 3 | |
| 4 | Usage: |
| 5 | loc_live.py --config audit/loc/repos.json --tools DIR --latest audit/loc/latest.json |
| 6 | --history audit/loc/history.jsonl [--date YYYY-MM-DD] [--work DIR] [--no-discover] |
| 7 | |
| 8 | repos.json names the public repositories and, for each fork, the upstream repository |
| 9 | and the upstream merge-base we diverged from. Every public repository the GitHub API |
| 10 | lists for the org is counted; one missing from repos.json is counted as first-party |
| 11 | full-tree if it is not a fork, and is NOT_COUNTED (with the reason) if it is a fork |
| 12 | without a pinned base, so new repositories never vanish from the total silently. |
| 13 | |
| 14 | Each repository is fetched at its HEAD and counted with loc.py (forks in fork-diff |
| 15 | mode against the pinned base, which must still be an ancestor of HEAD; otherwise |
| 16 | the fork is NOT_COUNTED until the base is re-pinned). Totals come from |
| 17 | loc.org_totals: `distinct_*` counts each identical blob once across repositories. |
| 18 | |
| 19 | latest.json carries no clock time, so an unchanged org rewrites identical bytes. |
| 20 | history.jsonl gains one line, stamped with --date, only when a HEAD or a total moved. |
| 21 | Private repositories are not counted here; nobody outside can re-run them. |
| 22 | Exit 0 when every listed repository was counted, 3 when any is NOT_COUNTED. |
| 23 | """ |
| 24 | import argparse, datetime, hashlib, json, os, subprocess, sys, tempfile, urllib.request |
| 25 | |
| 26 | HERE = os.path.dirname(os.path.abspath(__file__)) |
| 27 | sys.path.insert(0, HERE) |
| 28 | import loc # noqa: E402 |
| 29 | |
| 30 | |
| 31 | def git(*args, cwd=None): |
| 32 | return subprocess.run(["git", *args], cwd=cwd, capture_output=True, check=True, |
| 33 | env=dict(os.environ, GIT_TERMINAL_PROMPT="0")).stdout |
| 34 | |
| 35 | |
| 36 | def org_public_repos(org): |
| 37 | """[(name, fork, archived)] for every public repository, from the REST API.""" |
| 38 | out, page = [], 1 |
| 39 | tok = os.environ.get("GITHUB_TOKEN", "") |
| 40 | while True: |
| 41 | req = urllib.request.Request("https://api.github.com/orgs/%s/repos?type=public&per_page=100&page=%d" % (org, page), |
| 42 | headers={"Accept": "application/vnd.github+json", |
| 43 | **({"Authorization": "Bearer " + tok} if tok else {})}) |
| 44 | with urllib.request.urlopen(req, timeout=60) as r: |
| 45 | batch = json.load(r) |
| 46 | out += [(b["name"], b["fork"], b["archived"]) for b in batch if not b["private"]] |
| 47 | if len(batch) < 100: |
| 48 | return out |
| 49 | page += 1 |
| 50 | |
| 51 | |
| 52 | def fetch(org, name, work, fork_base): |
| 53 | gd = os.path.join(work, name + ".git") |
| 54 | if not os.path.isdir(gd): |
| 55 | git("init", "-q", "--bare", gd) |
| 56 | url = "https://github.com/%s/%s" % (org, name) |
| 57 | head = git("ls-remote", url, "HEAD").decode().split("\t", 1)[0].strip() |
| 58 | if fork_base: |
| 59 | # blobless: the fork diff reads only the blobs our commits touched; the rest are never fetched. |
| 60 | # The pinned upstream base arrives with HEAD's history when it is still an ancestor. |
| 61 | if not _has_remote(gd): |
| 62 | git("-C", gd, "remote", "add", "origin", url) |
| 63 | git("-C", gd, "config", "remote.origin.promisor", "true") |
| 64 | git("-C", gd, "config", "remote.origin.partialclonefilter", "blob:none") |
| 65 | git("-C", gd, "config", "extensions.partialClone", "origin") |
| 66 | git("-C", gd, "fetch", "-q", "--filter=blob:none", "origin", head) |
| 67 | else: |
| 68 | git("-C", gd, "fetch", "-q", "--depth", "1", url, head) |
| 69 | return gd, head |
| 70 | |
| 71 | |
| 72 | def _has_remote(gd): |
| 73 | return subprocess.run(["git", "-C", gd, "remote", "get-url", "origin"], capture_output=True).returncode == 0 |
| 74 | |
| 75 | |
| 76 | def main(): |
| 77 | ap = argparse.ArgumentParser() |
| 78 | ap.add_argument("--config", required=True) |
| 79 | ap.add_argument("--tools", required=True) |
| 80 | ap.add_argument("--latest", required=True) |
| 81 | ap.add_argument("--history", required=True) |
| 82 | ap.add_argument("--date", default=datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d")) |
| 83 | ap.add_argument("--work", default="") |
| 84 | ap.add_argument("--no-discover", action="store_true", help="count only repos.json (tests)") |
| 85 | a = ap.parse_args() |
| 86 | with open(a.config) as fh: |
| 87 | cfg = json.load(fh) |
| 88 | org = cfg["org"] |
| 89 | listed = {r["name"]: r for r in cfg["repositories"]} |
| 90 | if not a.no_discover: |
| 91 | for name, fork, archived in org_public_repos(org): |
| 92 | if name not in listed: |
| 93 | listed[name] = {"name": name, "kind": "UPSTREAM-FORK" if fork else ("ARCHIVED" if archived else "FIRST-PARTY"), |
| 94 | "unlisted": True} |
| 95 | scc = os.path.join(a.tools, "scc") |
| 96 | classify = os.path.join(HERE, "classify.json") |
| 97 | extra_all = json.load(open(classify)) if os.path.exists(classify) else {} |
| 98 | docs, rows = [], [] |
| 99 | with tempfile.TemporaryDirectory(prefix="aien-loc-live-") as tmp: |
| 100 | work = a.work or tmp |
| 101 | for name in sorted(listed): |
| 102 | r = listed[name] |
| 103 | row = {"repository": name, "kind": r["kind"]} |
| 104 | base = (r.get("upstream") or {}).get("base_sha", "") |
| 105 | if r["kind"] == "UPSTREAM-FORK" and not base: |
| 106 | rows.append(dict(row, state="NOT_COUNTED", reason="fork without a pinned upstream base in repos.json")) |
| 107 | continue |
| 108 | try: |
| 109 | gd, head = fetch(org, name, work, base) |
| 110 | if base and subprocess.run(["git", "-C", gd, "merge-base", "--is-ancestor", base, head], |
| 111 | capture_output=True).returncode != 0: |
| 112 | rows.append(dict(row, state="NOT_COUNTED", commit=head, |
| 113 | reason="pinned upstream base is not an ancestor of HEAD; re-pin it")) |
| 114 | continue |
| 115 | doc = loc.count(gd, head, name, base, scc, extra_all.get(name, [])) |
| 116 | except (subprocess.CalledProcessError, OSError, ValueError) as e: |
| 117 | rows.append(dict(row, state="NOT_COUNTED", reason="%s: %s" % (type(e).__name__, str(e)[:200]))) |
| 118 | continue |
| 119 | docs.append(doc) |
| 120 | rows.append(dict(row, state="COUNTED", commit=doc["commit"], mode=doc["mode"], |
| 121 | fork_base=doc.get("fork_base"), unlisted=bool(r.get("unlisted")), |
| 122 | first_party_executable_code=doc["first_party_executable_code"], |
| 123 | sha256=hashlib.sha256(loc.canonical(doc)).hexdigest())) |
| 124 | latest = {"schema": "aien-audit-loc-live/1", "org": org, "loc_tool": loc.TOOL_VERSION, |
| 125 | "scc_version": cfg.get("scc_version"), "repositories": rows, "totals": loc.org_totals(docs), |
| 126 | "not_counted": sum(r["state"] == "NOT_COUNTED" for r in rows), |
| 127 | "scope": "public repositories only; private repositories are not counted here"} |
| 128 | old = None |
| 129 | if os.path.exists(a.latest): |
| 130 | with open(a.latest) as fh: |
| 131 | old = json.load(fh) |
| 132 | with open(a.latest, "w") as fh: |
| 133 | fh.write(json.dumps(latest, indent=1, sort_keys=True) + "\n") |
| 134 | if old != latest: |
| 135 | line = {"date": a.date, "totals": latest["totals"], "not_counted": latest["not_counted"], |
| 136 | "heads": {r["repository"]: r.get("commit") for r in rows}} |
| 137 | with open(a.history, "a") as fh: |
| 138 | fh.write(json.dumps(line, sort_keys=True, separators=(",", ":")) + "\n") |
| 139 | t = latest["totals"] |
| 140 | print("repos=%d counted=%d not_counted=%d first_party_executable=%d distinct=%d" % ( |
| 141 | len(rows), len(docs), latest["not_counted"], t["first_party_executable_code"], t["distinct_first_party_executable_code"])) |
| 142 | sys.exit(3 if latest["not_counted"] else 0) |
| 143 | |
| 144 | |
| 145 | if __name__ == "__main__": |
| 146 | main() |