diff options
| author | Andrew Dolgov <fox@fakecake.org> | 2026-06-22 18:23:53 +0300 |
|---|---|---|
| committer | Andrew Dolgov <fox@fakecake.org> | 2026-06-22 18:23:53 +0300 |
| commit | f83b210bc4cec556b82b0a6bfa1900830455132b (patch) | |
| tree | 45ee420686e32583a255925f93505e1e31838bea | |
| parent | 7e515ef3a86cb63ef467bdfcbe3c52393d3a67e6 (diff) | |
| download | the-epube-f83b210bc4cec556b82b0a6bfa1900830455132b.tar.gz the-epube-f83b210bc4cec556b82b0a6bfa1900830455132b.tar.xz | |
more diff stuff
| -rw-r--r-- | review_mr.py | 125 |
1 files changed, 104 insertions, 21 deletions
diff --git a/review_mr.py b/review_mr.py index 901d6b8..acf57d6 100644 --- a/review_mr.py +++ b/review_mr.py @@ -61,21 +61,70 @@ def _api_post(url: str, headers: dict, payload: dict) -> dict: # Diff fetching # --------------------------------------------------------------------------- +def _format_diff_with_line_numbers(diff_text: str) -> str: + """Format a unified diff string with absolute line numbers. + + Parses @@ hunk headers to compute line numbers, then prepends them. + Only lines that exist in the new file (additions and context) get + line numbers; removal lines are left without a number. + + Example output: + === src/App.php === + @@ -10,7 +10,7 @@ + - return $user->name; + 10 + return $user->name ?? ""; + """ + import re as _re + + lines = diff_text.split("\n") + hunk_re = _re.compile(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@") + + output = [] + new_line = None # current line number in the new file + + for line in lines: + m = hunk_re.match(line) + if m: + new_line = int(m.group(1)) + output.append(line) # keep hunk header as-is + continue + + if new_line is None: + output.append(line) + continue + + if line.startswith("+"): + output.append(f"{new_line:>5} {line}") + new_line += 1 + elif line.startswith(" "): + output.append(f"{new_line:>5}{line}") + new_line += 1 + elif line.startswith("-"): + # Removal — no line number in the new file + output.append(f"{'':>5} {line}") + else: + # Other lines (e.g., index, new file, etc.) + output.append(line) + + return "\n".join(output) + + def fetch_diff(project_id: str, mr_iid: str, token: str, server_url: str): """Fetch the MR diff and return (formatted_text, raw_diffs). raw_diffs is a list of dicts with keys: old_path, new_path, diff, position. + The formatted text includes file headers and line numbers for each diff hunk. """ url = f"{server_url}/api/v4/projects/{project_id}/merge_requests/{mr_iid}/diffs" diffs = _api_get(url, {"PRIVATE-TOKEN": token}) - # Build readable text with file headers for the LLM + # Build readable text with file headers and line numbers for the LLM parts = [] for d in diffs: path = d.get("new_path") or d.get("old_path", "<unknown>") parts.append(f"=== {path} ===") if d.get("diff"): - parts.append(d["diff"]) + parts.append(_format_diff_with_line_numbers(d["diff"])) diff_text = "\n".join(parts)[:10000] return diff_text, diffs @@ -89,6 +138,9 @@ SYSTEM_PROMPT = ( "You are a code review assistant. Review the diff below and return " "a JSON object with an \"annotations\" key containing an array of " "line annotations.\n\n" + "The diff is formatted with absolute line numbers in the new file " + "padded to 5 characters on the left. Only lines with a line number " + "are valid annotation targets.\n\n" "JSON Schema:\n" "```json\n" "{\n" @@ -112,7 +164,8 @@ SYSTEM_PROMPT = ( '}\n' "```\n\n" "Rules:\n" - "- Only annotate lines that actually exist in the diff.\n" + "- Use the line numbers shown in the diff output (the 5-char number on the left).\n" + "- Only annotate lines that have a line number prefix.\n" "- Be specific — reference the code you're commenting on.\n" "- Skip unchanged lines.\n" "- Return ONLY the JSON object, no markdown wrapping, no explanation." @@ -228,17 +281,59 @@ def post_comment( print("Plain review comment posted.") +def _build_positions_from_diff(diffs: list[dict], base_sha: str, head_sha: str) -> dict[tuple, dict]: + """Build position lookup from diff entries by parsing hunk headers. + + Returns a mapping of (old_path, new_path, old_line, new_line) -> position dict. + """ + import re as _re + + hunk_re = _re.compile(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@") + lookup: dict[tuple, dict] = {} + + for d in diffs: + old_path = d.get("old_path", "") + new_path = d.get("new_path", old_path) + diff_text = d.get("diff", "") + if not diff_text: + continue + + new_line = None + for line in diff_text.split("\n"): + m = hunk_re.match(line) + if m: + new_line = int(m.group(1)) + continue + if new_line is None: + continue + if line.startswith("+"): + key = (old_path, new_path, None, new_line) + lookup[key] = { + "base_sha": base_sha, + "head_sha": head_sha, + "position_type": "text", + } + new_line += 1 + elif line.startswith(" "): + key = (old_path, new_path, new_line, new_line) + lookup[key] = { + "base_sha": base_sha, + "head_sha": head_sha, + "position_type": "text", + } + new_line += 1 + # removal lines (-) have no new_line, skip + + return lookup + + def _fetch_position_metadata( project_id: str, mr_iid: str, token: str, server_url: str ) -> dict[tuple, dict]: """Fetch diff position metadata (base_sha, head_sha) for annotation positions. Returns a mapping of (old_path, new_path, old_line, new_line) -> position dict. - Falls back to MR-level SHA if the positions endpoint is unavailable. """ - url = ( - f"{server_url}/api/v4/projects/{project_id}/merge_requests/{mr_iid}/notes" - ) lookup: dict[tuple, dict] = {} # Try the /positions endpoint first @@ -264,29 +359,17 @@ def _fetch_position_metadata( except requests.HTTPError: pass # Fall through to MR-level fallback - # Fallback: get MR info and use its SHA for both base and head + # Fallback: get MR info and parse diff text for line numbers mr_url = f"{server_url}/api/v4/projects/{project_id}/merge_requests/{mr_iid}" mr = _api_get(mr_url, {"PRIVATE-TOKEN": token}) sha = mr.get("sha", "") print(" (Using MR-level SHA as fallback for position metadata)", file=sys.stderr) - # We still need old_path/new_path/line info from the diff - # Build minimal position entries from the diff itself diffs_url = ( f"{server_url}/api/v4/projects/{project_id}/merge_requests/{mr_iid}/diffs" ) diffs = _api_get(diffs_url, {"PRIVATE-TOKEN": token}) - for d in diffs: - path = d.get("new_path") or d.get("old_path", "") - old_line = d.get("old_line") - new_line = d.get("new_line") - if path and new_line is not None: - key = (d.get("old_path"), path, old_line, new_line) - lookup[key] = { - "base_sha": sha, - "head_sha": sha, - "position_type": "text", - } + lookup = _build_positions_from_diff(diffs, sha, sha) return lookup |
