#!/usr/bin/env python3 # comment_diff.py [base-ref]: every .luau / .lua file changed since base-ref (default HEAD) must have the same token # stream as at base-ref once comments are removed, so a comment cleanup can't change code. Exit 1 on any difference. import os, re, subprocess, sys ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) LONG_OPEN = re.compile(r"\[(=*)\[") def tokens(src): out, i, n = [], 0, len(src) while i < n: c = src[i] if c in " \t\r\n": i += 1 elif src.startswith("--", i): m = LONG_OPEN.match(src, i + 2) if m: close = "]" + m.group(1) + "]" j = src.find(close, m.end()) i = n if j < 0 else j + len(close) else: j = src.find("\n", i) i = n if j < 0 else j elif c == "[" and LONG_OPEN.match(src, i): m = LONG_OPEN.match(src, i) close = "]" + m.group(1) + "]" j = src.find(close, m.end()) j = n if j < 0 else j + len(close) out.append(src[i:j]) i = j elif c in "'\"`": j = i + 1 while j < n and src[j] != c: j += 2 if src[j] == "\\" else 1 out.append(src[i:j + 1]) i = j + 1 else: m = re.compile(r"[A-Za-z_][A-Za-z0-9_]*|0[xXbB][0-9A-Fa-f_]+|[0-9][0-9_]*\.?[0-9_]*(?:[eE][+-]?[0-9]+)?|\.\.\.|\.\.=?|[=~<>]=|//=?|::|->|[-+*/%^#&|]=?|.").match(src, i) out.append(m.group(0)) i = m.end() return out def git(*args): return subprocess.run(["git", "-C", ROOT, *args], capture_output=True, text=True) def main(): base = sys.argv[1] if len(sys.argv) > 1 else "HEAD" names = git("diff", "--name-only", base, "--", "*.luau", "*.lua").stdout.split() bad = 0 for name in names: path = os.path.join(ROOT, name) old = git("show", "%s:%s" % (base, name)) if old.returncode != 0 or not os.path.exists(path): continue # added or deleted file: not a comment edit a, b = tokens(old.stdout), tokens(open(path, encoding="utf-8", errors="replace").read()) if a != b: k = next((i for i in range(min(len(a), len(b))) if a[i] != b[i]), min(len(a), len(b))) print("comment_diff: code changed in %s near token %d: %r -> %r" % (name, k, a[k:k + 4], b[k:k + 4])) bad += 1 print("comment_diff: %d files compared against %s, %d with code changes" % (len(names), base, bad)) sys.exit(1 if bad else 0) if __name__ == "__main__": main()