-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbuild_codex_github_review.py
More file actions
191 lines (171 loc) · 5.71 KB
/
Copy pathbuild_codex_github_review.py
File metadata and controls
191 lines (171 loc) · 5.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
#!/usr/bin/env python3
"""Build a GitHub review while preserving findings without valid diff anchors."""
from __future__ import annotations
import argparse
import json
import os
import posixpath
import re
import subprocess
from pathlib import Path
HUNK = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")
def normalize_path(value: str, workspace: str) -> str | None:
candidate = value.replace("\\", "/")
root = workspace.replace("\\", "/").rstrip("/")
if candidate.startswith(root + "/"):
candidate = candidate[len(root) + 1 :]
while candidate.startswith("./"):
candidate = candidate[2:]
candidate = posixpath.normpath(candidate)
if (
not candidate
or candidate == "."
or candidate.startswith("/")
or candidate == ".."
or candidate.startswith("../")
or "/../" in candidate
):
return None
return candidate
def header_path(line: str) -> str | None:
value = line[4:].split("\t", 1)[0]
if value == "/dev/null":
return None
if value.startswith(("a/", "b/")):
value = value[2:]
return value
def changed_lines(diff: str) -> dict[str, set[tuple[str, int]]]:
allowed: dict[str, set[tuple[str, int]]] = {"LEFT": set(), "RIGHT": set()}
old_path: str | None = None
new_path: str | None = None
old_line = 0
new_line = 0
in_hunk = False
for line in diff.splitlines():
if line.startswith("diff --git "):
old_path = new_path = None
in_hunk = False
continue
if not in_hunk and line.startswith("--- "):
old_path = header_path(line)
continue
if not in_hunk and line.startswith("+++ "):
new_path = header_path(line)
continue
match = HUNK.match(line)
if match:
old_line = int(match.group(1))
new_line = int(match.group(3))
in_hunk = True
continue
if not in_hunk or line.startswith("\\"):
continue
if line.startswith("-"):
if old_path is not None:
allowed["LEFT"].add((old_path, old_line))
old_line += 1
elif line.startswith("+"):
if new_path is not None:
allowed["RIGHT"].add((new_path, new_line))
new_line += 1
elif line.startswith(" "):
old_line += 1
new_line += 1
else:
in_hunk = False
return allowed
def finding_body(finding: dict[str, object]) -> str:
return (
f"[P{finding['priority']}] {finding['title']}\n\n"
f"{finding['body']}\n\nConfidence: {finding['confidence_score']}"
)
def build_review(
review: dict[str, object],
*,
commit: str,
workspace: str,
allowed: dict[str, set[tuple[str, int]]],
) -> dict[str, object]:
body = (
"Codex automated review\n\n"
f"Verdict: {review['overall_correctness']}\n"
f"Confidence: {review['overall_confidence_score']}\n\n"
f"{review['overall_explanation']}"
)
comments: list[dict[str, object]] = []
unanchored: list[str] = []
for finding in review["findings"]: # type: ignore[index]
location = finding["code_location"]
path = normalize_path(location["absolute_file_path"], workspace)
side = location["side"]
start = location["line_range"]["start"]
end = location["line_range"]["end"]
valid_anchor = (
path is not None
and side in allowed
and start <= end
and all((path, line) in allowed[side] for line in range(start, end + 1))
)
text = finding_body(finding)
if valid_anchor:
comment: dict[str, object] = {
"path": path,
"line": end,
"side": side,
"body": text,
}
if start != end:
comment["start_line"] = start
comment["start_side"] = side
comments.append(comment)
continue
display_path = path or "unresolved-path"
unanchored.append(f"{text}\n\nLocation: {display_path}:{start}-{end} ({side})")
if unanchored:
body += "\n\nFindings without inline diff anchors\n\n" + "\n\n---\n\n".join(unanchored)
return {"commit_id": commit, "event": "COMMENT", "body": body, "comments": comments}
def pull_request_diff(workspace: str, base: str, head: str) -> str:
merge_base = subprocess.run(
["git", "merge-base", base, head],
cwd=workspace,
check=True,
text=True,
capture_output=True,
).stdout.strip()
return subprocess.run(
[
"git",
"-c",
"core.quotePath=false",
"diff",
"--no-ext-diff",
"--no-renames",
"--unified=0",
merge_base,
head,
],
cwd=workspace,
check=True,
text=True,
capture_output=True,
).stdout
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--input", required=True)
parser.add_argument("--output", required=True)
parser.add_argument("--workspace", required=True)
parser.add_argument("--base", required=True)
parser.add_argument("--head", required=True)
args = parser.parse_args()
diff = pull_request_diff(args.workspace, args.base, args.head)
review = json.loads(Path(args.input).read_text())
payload = build_review(
review,
commit=args.head,
workspace=os.path.abspath(args.workspace),
allowed=changed_lines(diff),
)
Path(args.output).write_text(json.dumps(payload, indent=2) + "\n")
return 0
if __name__ == "__main__":
raise SystemExit(main())