interplane.Get Omega
Read in your language

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

branch main Branches Tags History

aien-receipts / audit / tools / loc.py

315 lines · 14493 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Deterministic line-of-code count for one repository at one commit.
3
4Usage:
5 loc.py <git-dir> <sha> [--repo NAME] [--fork-base SHA] [--scc PATH] [--out FILE]
6
7Only the tracked blobs of <sha> are counted, read raw from the object store
8(no checkout, no .gitignore, no line-ending filters), so two machines with the
9same pinned scc get the same bytes out. Omega (.om) is counted here because scc
10has no Omega definition: a line is blank when it holds only whitespace, a
11comment when its first word is `note`, and code otherwise.
12
13Every file is put in exactly one category:
14 first_party - our own source
15 vendored - copied third-party code (vendor/, third_party/, linguist-vendored, ...)
16 generated - machine-written files (generated markers, linguist-generated, lockfiles, *.min.*)
17 evidence - recorded run artifacts under evidence/ or receipts/ trees
18The rules are in RULES below and in classify.json (per-repository additions).
19"""
20import argparse, fnmatch, hashlib, json, os, re, subprocess, sys, tempfile
21
22TOOL_VERSION = "aien-audit-loc/2"
23
24# Languages that are data, markup, prose or styling, not executable code.
25NON_EXECUTABLE = {
26 "JSON", "JSONL", "JSONC", "YAML", "TOML", "INI", "XML", "SVG", "HTML", "XHTML", "CSS", "SCSS", "Sass", "LESS",
27 "Markdown", "Plain Text", "Text", "ReStructuredText", "AsciiDoc", "Org", "TeX", "LaTeX", "BibTeX",
28 "CSV", "TSV", "License", "gitignore", "gitattributes", "Gitignore", "Docker ignore", "Properties File",
29 "Jupyter", "Patch", "Diff", "Unknown", "Protocol Buffers", "Cap'n Proto", "Device Tree", "Rich Text Format",
30 "Wiki", "Systemd", "Hex", "Intel HEX", "Mustache", "Handlebars", "Jinja", "Twig", "Liquid",
31}
32VENDOR_DIRS = {"vendor", "vendored", "third_party", "third-party", "thirdparty", "3rdparty", "node_modules",
33 "external", "extern", "deps", "bower_components", ".cargo-vendor"}
34EVIDENCE_DIRS = {"evidence", "receipts"}
35GENERATED_NAMES = {"Cargo.lock", "package-lock.json", "yarn.lock", "pnpm-lock.yaml", "poetry.lock", "uv.lock",
36 "Pipfile.lock", "go.sum", "composer.lock", "Gemfile.lock", "bun.lockb", "flake.lock"}
37GENERATED_GLOBS = ["*.min.js", "*.min.css", "*.min.mjs", "*.map", "*.pb.go", "*_pb2.py"]
38GENERATED_MARKER = re.compile(rb"(@generated|do not edit|auto-generated|autogenerated|code generated by)", re.I)
39
40SCC_FLAGS = ["--no-ignore", "--no-gitignore", "--no-gitmodule", "--no-scc-ignore", "--no-config",
41 "--no-cocomo", "--no-complexity", "--no-size", "--by-file", "--format", "json",
42 "--exclude-file", "", "--count-as-pattern", "*.osc:OSC (legacy Omega):Rust"]
43
44
45def git(gd, *args, inp=None):
46 return subprocess.run(["git", "-C", gd, *args], input=inp, capture_output=True, check=True).stdout
47
48
49def tree_entries(gd, sha):
50 out = git(gd, "ls-tree", "-r", "-z", "--full-tree", sha)
51 for rec in out.split(b"\0"):
52 if not rec:
53 continue
54 meta, path = rec.split(b"\t", 1)
55 mode, typ, oid = meta.split(b" ")
56 yield mode.decode(), typ.decode(), oid.decode(), path.decode("utf-8", "surrogateescape")
57
58
59def attrs(gd, sha, paths):
60 if not paths:
61 return {}
62 inp = "\0".join(paths).encode("utf-8", "surrogateescape") + b"\0"
63 out = git(gd, "check-attr", "-z", "--source", sha, "--stdin", "linguist-vendored", "linguist-generated",
64 "linguist-documentation", inp=inp)
65 f = out.split(b"\0")
66 res = {}
67 for i in range(0, len(f) - 2, 3):
68 p, a, v = f[i].decode("utf-8", "surrogateescape"), f[i + 1].decode(), f[i + 2].decode()
69 if v in ("set", "true"):
70 res.setdefault(p, set()).add(a)
71 return res
72
73
74def classify(path, head, attr, extra):
75 parts = path.split("/")
76 for rule in extra:
77 if fnmatch.fnmatchcase(path, rule["glob"]):
78 return rule["category"], "classify.json: " + rule["reason"]
79 if "linguist-vendored" in attr:
80 return "vendored", ".gitattributes linguist-vendored"
81 if "linguist-generated" in attr:
82 return "generated", ".gitattributes linguist-generated"
83 for d in parts[:-1]:
84 if d in VENDOR_DIRS:
85 return "vendored", "directory " + d + "/"
86 for d in parts[:-1]:
87 if d in EVIDENCE_DIRS:
88 return "evidence", "directory " + d + "/"
89 name = parts[-1]
90 if name in GENERATED_NAMES:
91 return "generated", "lockfile"
92 for g in GENERATED_GLOBS:
93 if fnmatch.fnmatchcase(name, g):
94 return "generated", "pattern " + g
95 if GENERATED_MARKER.search(head):
96 return "generated", "generated marker in first 5 lines"
97 return "first_party", ""
98
99
100def count_omega(data):
101 blank = comment = code = 0
102 for line in data.split(b"\n") if data else []:
103 s = line.strip()
104 if not s:
105 blank += 1
106 elif s.split(None, 1)[0] == b"note":
107 comment += 1
108 else:
109 code += 1
110 if data.endswith(b"\n"):
111 blank -= 1 # the empty string after the final newline is not a line
112 return blank, comment, code
113
114
115def materialize(gd, entries, root):
116 oids = [e[2] for e in entries]
117 if not oids:
118 return {}
119 heads = {}
120 # a file, not a pipe: writing every request first would deadlock on large trees
121 with tempfile.TemporaryFile() as req:
122 req.write(("\n".join(oids) + "\n").encode())
123 req.seek(0)
124 with subprocess.Popen(["git", "-C", gd, "cat-file", "--batch"], stdin=req, stdout=subprocess.PIPE) as p:
125 for (_, _, oid, path) in entries:
126 hdr = p.stdout.readline().split()
127 if len(hdr) != 3 or hdr[0].decode() != oid:
128 raise ValueError("git cat-file: %s for %s" % (b" ".join(hdr).decode(errors="replace"), path))
129 data = p.stdout.read(int(hdr[2]))
130 p.stdout.read(1)
131 full = os.path.join(root, path)
132 os.makedirs(os.path.dirname(full), exist_ok=True)
133 with open(full, "wb") as fh:
134 fh.write(data)
135 heads[path] = (b"\n".join(data.split(b"\n", 5)[:5]), data if path.endswith(".om") else None)
136 if p.returncode != 0:
137 raise ValueError("git cat-file exit %d" % p.returncode)
138 return heads
139
140
141def run_scc(scc, root):
142 out = subprocess.run([scc, *SCC_FLAGS, root], capture_output=True, check=True).stdout
143 per_file = {}
144 for lang in json.loads(out or b"[]"):
145 for f in lang.get("Files") or []:
146 rel = os.path.relpath(f["Location"], root)
147 per_file[rel] = (lang["Name"], f["Blank"], f["Comment"], f["Code"])
148 return per_file
149
150
151def scc_version(scc):
152 return subprocess.run([scc, "--version"], capture_output=True, text=True).stdout.strip()
153
154
155def fork_added_lines(gd, base, sha, paths):
156 """Non-blank lines added by our commits to each modified upstream file (git diff -U0, no renames)."""
157 if not paths:
158 return {}
159 out = git(gd, "-c", "core.quotePath=false", "diff", "--no-renames", "--no-color", "--no-ext-diff", "-U0",
160 "--src-prefix=a/", "--dst-prefix=b/", base, sha, "--", *[":(literal)" + p for p in paths])
161 counts, cur, in_header = {}, None, False
162 for line in out.split(b"\n"):
163 if line.startswith(b"diff --git "):
164 in_header, cur = True, None
165 elif in_header and line.startswith(b"+++ "):
166 name = line[4:].rstrip(b"\t") # git appends a tab to names that contain a space
167 cur = None if name == b"/dev/null" else name[2:].decode("utf-8", "surrogateescape")
168 if cur is not None:
169 counts.setdefault(cur, 0)
170 elif line.startswith(b"@@"):
171 in_header = False
172 elif not in_header and line.startswith(b"+") and cur is not None and line[1:].strip():
173 counts[cur] += 1
174 return counts
175
176
177def org_totals(docs):
178 """Org-wide totals over per-repository results. `distinct` counts each blob once across repositories,
179 so code copied between repositories is not counted twice."""
180 total = {"repositories": len(docs), "first_party_executable_code": 0, "first_party_code_all": 0,
181 "distinct_first_party_executable_code": 0, "distinct_first_party_code_all": 0, "by_language": {}}
182 seen = set()
183 for d in sorted(docs, key=lambda d: d["repository"]):
184 for f in d["files"]:
185 if f["category"] != "first_party":
186 continue
187 total["first_party_code_all"] += f["code"]
188 if f["executable"]:
189 total["first_party_executable_code"] += f["code"]
190 # a fork-modified file's count is a diff, not the blob's content, so it is never deduplicated
191 key = (f["blob"], f["language"]) if not f.get("fork_modified") else (d["repository"], f["path"])
192 if key in seen:
193 continue
194 seen.add(key)
195 total["distinct_first_party_code_all"] += f["code"]
196 if f["executable"]:
197 total["distinct_first_party_executable_code"] += f["code"]
198 bl = total["by_language"].setdefault(f["language"], 0)
199 total["by_language"][f["language"]] = bl + f["code"]
200 total["by_language"] = dict(sorted(total["by_language"].items(), key=lambda kv: (-kv[1], kv[0])))
201 return total
202
203
204def count(gd, sha, repo, fork_base, scc, extra):
205 sha = git(gd, "rev-parse", sha + "^{commit}").decode().strip()
206 tree = git(gd, "rev-parse", sha + "^{tree}").decode().strip()
207 entries, skipped = [], {"gitlink": 0, "symlink": 0, "binary_or_unknown_language": 0}
208 for mode, typ, oid, path in tree_entries(gd, sha):
209 if typ == "commit":
210 skipped["gitlink"] += 1
211 elif mode == "120000":
212 skipped["symlink"] += 1
213 else:
214 entries.append((mode, typ, oid, path))
215 changed, added_lines = None, {}
216 if fork_base:
217 fork_base = git(gd, "rev-parse", fork_base + "^{commit}").decode().strip()
218 diff = git(gd, "diff", "--no-renames", "-z", "--name-status", fork_base, sha).split(b"\0")
219 changed = {}
220 for i in range(0, len(diff) - 1, 2):
221 st = diff[i].decode()
222 if st and st[0] in "AM":
223 changed[diff[i + 1].decode("utf-8", "surrogateescape")] = st[0]
224 entries = [e for e in entries if e[3] in changed]
225 added_lines = fork_added_lines(gd, fork_base, sha, sorted(p for p, s in changed.items() if s == "M"))
226 oids = {e[3]: e[2] for e in entries}
227 paths = [e[3] for e in entries]
228 at = attrs(gd, sha, paths)
229 with tempfile.TemporaryDirectory(prefix="aien-loc-") as root:
230 heads = materialize(gd, entries, root)
231 per_file = run_scc(scc, root)
232 files = []
233 for p in sorted(paths):
234 head, omdata = heads[p]
235 if p.endswith(".om"):
236 b, c, k = count_omega(omdata)
237 lang = ("Omega", b, c, k)
238 else:
239 lang = per_file.get(p)
240 if lang is None:
241 skipped["binary_or_unknown_language"] += 1
242 continue
243 cat, why = classify(p, head, at.get(p, set()), extra)
244 name, b, c, k = lang
245 rec = {"path": p, "blob": oids[p], "language": name, "category": cat, "reason": why,
246 "code": k, "comment": c, "blank": b, "executable": name not in NON_EXECUTABLE}
247 if fork_base and changed.get(p) == "M":
248 # A diff hunk has no language context, so comments cannot be told from code here:
249 # count every non-blank line our commits added to the upstream file.
250 rec.update({"code": added_lines.get(p, 0), "comment": 0, "blank": 0, "fork_modified": True})
251 files.append(rec)
252 summary = {}
253 for f in files:
254 cat = summary.setdefault(f["category"], {"files": 0, "code_executable": 0, "code_all": 0, "by_language": {}})
255 cat["files"] += 1
256 cat["code_all"] += f["code"]
257 if f["executable"]:
258 cat["code_executable"] += f["code"]
259 bl = cat["by_language"].setdefault(f["language"], {"files": 0, "code": 0, "comment": 0, "blank": 0,
260 "executable": f["executable"]})
261 bl["files"] += 1
262 bl["code"] += f["code"]
263 bl["comment"] += f["comment"]
264 bl["blank"] += f["blank"]
265 result = {
266 "schema": "aien-audit-loc/2",
267 "repository": repo,
268 "commit": sha,
269 "tree": tree,
270 "mode": "fork-diff" if fork_base else "full-tree",
271 "fork_base": fork_base,
272 "tools": {"counter": TOOL_VERSION, "scc": scc_version(scc)},
273 "definition": "code = lines that are neither blank nor comment; executable = language not in NON_EXECUTABLE "
274 "(data, markup, prose, styling); Omega .om counted by this script (comment = first word `note`)."
275 + (" Fork mode: files we added count in full; for upstream files we modified, code = non-blank "
276 "lines added relative to the upstream merge-base (comments included, deletions not subtracted)."
277 if fork_base else ""),
278 "skipped": skipped,
279 "first_party_executable_code": summary.get("first_party", {}).get("code_executable", 0),
280 "categories": summary,
281 "files": files,
282 }
283 return result
284
285
286def canonical(obj):
287 return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode() + b"\n"
288
289
290def main():
291 ap = argparse.ArgumentParser()
292 ap.add_argument("gitdir")
293 ap.add_argument("sha")
294 ap.add_argument("--repo", default="")
295 ap.add_argument("--fork-base", default="")
296 ap.add_argument("--scc", default=os.environ.get("SCC", "scc"))
297 ap.add_argument("--classify", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "classify.json"))
298 ap.add_argument("--out", default="-")
299 a = ap.parse_args()
300 extra = []
301 if os.path.exists(a.classify):
302 extra = json.load(open(a.classify)).get(a.repo, [])
303 res = count(a.gitdir, a.sha, a.repo, a.fork_base, a.scc, extra)
304 data = canonical(res)
305 if a.out == "-":
306 sys.stdout.buffer.write(data)
307 else:
308 with open(a.out, "wb") as fh:
309 fh.write(data)
310 print(json.dumps({"repository": a.repo, "commit": res["commit"], "first_party_executable_code":
311 res["first_party_executable_code"], "sha256": hashlib.sha256(data).hexdigest()}), file=sys.stderr)
312
313
314if __name__ == "__main__":
315 main()