|
| 1 | +"""Read-only clang-format check of changed lines, without historical tree-wide debt. |
| 2 | +
|
| 3 | +PR: merge base to head. Push: before to after. New branch: default branch merge |
| 4 | +base to head. Renames are new files; deletion-only hunks contain no new code. |
| 5 | +Format the full file, but fail only replacements touching added/modified lines. |
| 6 | +""" |
| 7 | +import argparse |
| 8 | +import bisect |
| 9 | +import json |
| 10 | +import os |
| 11 | +from pathlib import Path, PurePosixPath |
| 12 | +import re |
| 13 | +import subprocess |
| 14 | +import sys |
| 15 | +import xml.etree.ElementTree as ET |
| 16 | + |
| 17 | + |
| 18 | +def git(*args, data=None): |
| 19 | + return subprocess.run(["git", *args], input=data, check=True, stdout=subprocess.PIPE).stdout |
| 20 | + |
| 21 | + |
| 22 | +def commit(ref): |
| 23 | + return git("rev-parse", "--verify", "--end-of-options", ref + "^{commit}").decode().strip() |
| 24 | + |
| 25 | + |
| 26 | +def event_base(event, head): |
| 27 | + if "pull_request" in event: |
| 28 | + base = commit(event["pull_request"]["base"]["sha"]) |
| 29 | + return git("merge-base", base, head).decode().strip() |
| 30 | + before = event.get("before", "") |
| 31 | + if before and before != "0" * 40: |
| 32 | + return commit(before) |
| 33 | + default = event.get("repository", {}).get("default_branch") |
| 34 | + if default: |
| 35 | + base = commit("refs/remotes/origin/" + default) |
| 36 | + return git("merge-base", base, head).decode().strip() |
| 37 | + raise ValueError("No comparison base: use --base explicitly outside GitHub Actions") |
| 38 | + |
| 39 | + |
| 40 | +def eligible(name): |
| 41 | + path = PurePosixPath(name) |
| 42 | + return (path.parts[0] == "OptiScaler" and "external" not in path.parts |
| 43 | + and path.parts[:2] != ("OptiScaler", "include") |
| 44 | + and path.suffix.lower() in {".c", ".cc", ".cpp", ".cxx", ".h", ".hh", ".hpp", ".hxx"}) |
| 45 | + |
| 46 | + |
| 47 | +def changed_ranges(diff): |
| 48 | + ranges = [] |
| 49 | + for line in diff.splitlines(): |
| 50 | + match = re.match(rb"@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@", line) |
| 51 | + if match: |
| 52 | + start = int(match[1]) |
| 53 | + count = int(match[2]) if match[2] is not None else 1 |
| 54 | + if count: |
| 55 | + ranges.append((start, start + count - 1)) |
| 56 | + return ranges |
| 57 | + |
| 58 | + |
| 59 | +def violations(source, xml, ranges): |
| 60 | + root = ET.fromstring(xml) |
| 61 | + if root.get("incomplete_format") == "true": |
| 62 | + raise ValueError("clang-format could not completely parse the file") |
| 63 | + starts = [0] + [i + 1 for i, char in enumerate(source) if char == 10] |
| 64 | + result = [] |
| 65 | + for item in root.findall("replacement"): |
| 66 | + offset, length = int(item.attrib["offset"]), int(item.attrib["length"]) |
| 67 | + if offset < 0 or length < 0 or offset + length > len(source): |
| 68 | + raise ValueError("Invalid formatter replacement range") |
| 69 | + first = bisect.bisect_right(starts, offset) |
| 70 | + last = bisect.bisect_right(starts, offset + max(0, length - 1)) |
| 71 | + if any(first <= end and last >= start for start, end in ranges): |
| 72 | + result.append(first) |
| 73 | + return sorted(set(result)) |
| 74 | + |
| 75 | + |
| 76 | +def check(base, head, formatter): |
| 77 | + names = git("diff", "--no-renames", "--name-only", "--diff-filter=AM", "-z", base, head, "--") |
| 78 | + failures = 0 |
| 79 | + checked = 0 |
| 80 | + for raw in names.split(b"\0"): |
| 81 | + if not raw: |
| 82 | + continue |
| 83 | + name = os.fsdecode(raw) |
| 84 | + if not eligible(name): |
| 85 | + continue |
| 86 | + diff = git("diff", "--no-ext-diff", "--no-textconv", "--no-renames", "--unified=0", base, head, "--", name) |
| 87 | + ranges = changed_ranges(diff) |
| 88 | + if not ranges: |
| 89 | + continue |
| 90 | + source = git("show", head + ":" + name) |
| 91 | + output = subprocess.run([formatter, "--style=file", "--fallback-style=none", |
| 92 | + "--assume-filename=" + name, "--output-replacements-xml"], |
| 93 | + input=source, check=True, stdout=subprocess.PIPE).stdout |
| 94 | + checked += 1 |
| 95 | + for line in violations(source, output, ranges): |
| 96 | + # repr prevents filenames with control characters from injecting CI commands. |
| 97 | + print(f"{name!r}:{line}: formatting change required on edited lines") |
| 98 | + failures += 1 |
| 99 | + print(f"Checked {checked} changed C/C++ files; {failures} edited-line violations") |
| 100 | + return 1 if failures else 0 |
| 101 | + |
| 102 | + |
| 103 | +def main(): |
| 104 | + parser = argparse.ArgumentParser(description=__doc__) |
| 105 | + parser.add_argument("--base") |
| 106 | + parser.add_argument("--head", default="HEAD") |
| 107 | + parser.add_argument("--formatter", default="clang-format") |
| 108 | + args = parser.parse_args() |
| 109 | + head = commit(args.head) |
| 110 | + if args.base: |
| 111 | + base = commit(args.base) |
| 112 | + else: |
| 113 | + event_path = os.environ.get("GITHUB_EVENT_PATH") |
| 114 | + event = json.loads(Path(event_path).read_text(encoding="utf-8")) if event_path else {} |
| 115 | + base = event_base(event, head) |
| 116 | + return check(base, head, args.formatter) |
| 117 | + |
| 118 | + |
| 119 | +if __name__ == "__main__": |
| 120 | + try: |
| 121 | + sys.exit(main()) |
| 122 | + except (ValueError, OSError, subprocess.CalledProcessError, ET.ParseError) as error: |
| 123 | + print(f"Formatting check failed: {error}", file=sys.stderr) |
| 124 | + sys.exit(2) |
0 commit comments