From 3e04f8b7d333fa1bc1eb684d6eb273985b800e6d Mon Sep 17 00:00:00 2001 From: Azusa111 <133939721+Azusa111@users.noreply.github.com> Date: Wed, 2 Dec 2026 16:08:10 +0800 Subject: [PATCH] pr_runtime: parse spaced and quoted Git paths Git quotes paths containing spaces or non-ASCII characters in diff headers. The old header matcher merged their blocks into adjacent source patches, allowing hidden test edits into the source patch and leaving the test patch empty. Parse file boundaries and Git path metadata consistently for patch splitting and file extraction. Refs #291 --- src/repo2rlenv/pipelines/pr_runtime.py | 77 +++++++++++++++++---- tests/test_pipeline_pr_runtime.py | 95 ++++++++++++++++++++++++++ 2 files changed, 157 insertions(+), 15 deletions(-) diff --git a/src/repo2rlenv/pipelines/pr_runtime.py b/src/repo2rlenv/pipelines/pr_runtime.py index a6f43053..e9018812 100644 --- a/src/repo2rlenv/pipelines/pr_runtime.py +++ b/src/repo2rlenv/pipelines/pr_runtime.py @@ -38,6 +38,7 @@ from __future__ import annotations +import ast import json import logging import posixpath @@ -200,8 +201,59 @@ def _reflow_pr_body(body: str) -> str: _path_is_test = is_test_path -# Match `diff --git a/ b/` block boundaries to split a unified diff -_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$", re.MULTILINE) +# File boundaries must not depend on whether Git quotes or spaces a path. +_DIFF_HEADER_RE = re.compile(r'^diff --git (?:a/|"a/).+$', re.MULTILINE) +_QUOTED_GIT_PATH = r'"(?:\\.|[^"\\])*"' +_DIFF_PATH_RE = re.compile( + rf"^diff --git (?P{_QUOTED_GIT_PATH}|a/.*) (?P{_QUOTED_GIT_PATH}|b/.*)$" +) + + +def _git_path(raw: str) -> str: + """Decode a Git path, including UTF-8 bytes in C-quoted octal escapes.""" + if raw.startswith('"') and raw.endswith('"'): + try: + raw = ast.literal_eval(raw) + try: + raw = raw.encode("latin-1").decode("utf-8") + except (UnicodeEncodeError, UnicodeDecodeError): + pass + except (SyntaxError, ValueError): + return "" + return raw[2:] if raw.startswith(("a/", "b/")) else raw + + +def _paths_in_diff_block(block: str) -> tuple[str, str]: + """Use file markers to disambiguate paths containing header separators.""" + match = _DIFF_PATH_RE.match(block.split("\n", 1)[0]) + source = _git_path(match.group("source")) if match else "" + target = _git_path(match.group("target")) if match else "" + for line in block.splitlines()[1:]: + if line.startswith(("--- ", "+++ ")): + path = _git_path(line[4:].split("\t", 1)[0]) + if path == "/dev/null": + continue + if line.startswith("--- "): + source = path + else: + target = path + elif line.startswith(("rename from ", "copy from ")): + source = _git_path(line.split(" ", 2)[2]) + elif line.startswith(("rename to ", "copy to ")): + target = _git_path(line.split(" ", 2)[2]) + elif line.startswith("@@ "): + break + return source, target + + +def _diff_blocks(unified_diff: str) -> list[str]: + matches = list(_DIFF_HEADER_RE.finditer(unified_diff)) + return [ + unified_diff[ + match.start() : matches[i + 1].start() if i + 1 < len(matches) else len(unified_diff) + ] + for i, match in enumerate(matches) + ] def split_patch_and_test_patch(unified_diff: str) -> tuple[str, str]: @@ -216,20 +268,15 @@ def split_patch_and_test_patch(unified_diff: str) -> tuple[str, str]: if not unified_diff.strip(): return "", "" - # Find each "diff --git a/X b/Y" header and the byte offset where its block starts - matches = list(_DIFF_HEADER_RE.finditer(unified_diff)) - if not matches: + blocks = _diff_blocks(unified_diff) + if not blocks: # Empty / malformed — return whole thing as patch return unified_diff, "" patch_parts: list[str] = [] test_parts: list[str] = [] - for i, m in enumerate(matches): - start = m.start() - end = matches[i + 1].start() if i + 1 < len(matches) else len(unified_diff) - block = unified_diff[start:end] - path_a = m.group(1) - path_b = m.group(2) + for block in blocks: + path_a, path_b = _paths_in_diff_block(block) # If EITHER path looks like a test file (covers renames, new files), it's a test if _path_is_test(path_a) or _path_is_test(path_b): test_parts.append(block) @@ -993,10 +1040,10 @@ def _files_in_patch(unified_diff: str) -> list[str]: if not unified_diff.strip(): return [] seen: list[str] = [] - for m in _DIFF_HEADER_RE.finditer(unified_diff): - b = m.group(2) - if b not in seen: - seen.append(b) + for block in _diff_blocks(unified_diff): + _, target = _paths_in_diff_block(block) + if target and target not in seen: + seen.append(target) return seen diff --git a/tests/test_pipeline_pr_runtime.py b/tests/test_pipeline_pr_runtime.py index 44c9f5d6..5a13ded4 100644 --- a/tests/test_pipeline_pr_runtime.py +++ b/tests/test_pipeline_pr_runtime.py @@ -11,6 +11,9 @@ from __future__ import annotations +import subprocess +from pathlib import Path + import pytest from repo2rlenv.bootstrap.spec import BootstrapResult, LanguageHint @@ -99,6 +102,98 @@ def test_split_patch_renames_to_test_dir_count_as_test(): assert patch == "" +@pytest.mark.parametrize( + ("source_name", "test_name"), + [ + ("src.py", "tests/test space.py"), + ("src.py", "tests/test 中文.py"), + ("src.py", "tests/test\tname.py"), + ("src.py", 'tests/test"name.py'), + ("src/源 file.py", "tests/test_ordinary.py"), + ("src/a b/utility.py", "tests/test space.py"), + ], +) +def test_split_real_git_diff_with_spaced_or_quoted_paths( + tmp_path: Path, source_name: str, test_name: str +) -> None: + for name in (source_name, test_name): + file = tmp_path / name + file.parent.mkdir(parents=True, exist_ok=True) + file.write_text("old\n", encoding="utf-8") + subprocess.run(["git", "init", "-q", str(tmp_path)], check=True) + subprocess.run(["git", "-C", str(tmp_path), "add", "."], check=True) + subprocess.run( + [ + "git", + "-C", + str(tmp_path), + "-c", + "user.name=Example", + "-c", + "user.email=example@example.com", + "commit", + "-qm", + "base", + ], + check=True, + ) + for name in (source_name, test_name): + (tmp_path / name).write_text("new\n", encoding="utf-8") + diff = subprocess.run( + ["git", "-C", str(tmp_path), "-c", "core.quotePath=true", "diff"], + check=True, + capture_output=True, + text=True, + ).stdout + + patch, test_patch = split_patch_and_test_patch(diff) + + assert patch.count("diff --git ") == 1 + assert test_patch.count("diff --git ") == 1 + assert _files_in_patch(patch) == [source_name] + assert _files_in_patch(test_patch) == [test_name] + + +def test_split_rename_without_hunks_to_spaced_test_path(tmp_path: Path) -> None: + source = tmp_path / "src/old name.py" + target = tmp_path / "tests/test new name.py" + source.parent.mkdir(parents=True) + target.parent.mkdir(parents=True) + source.write_text("x = 1\n", encoding="utf-8") + subprocess.run(["git", "init", "-q", str(tmp_path)], check=True) + subprocess.run(["git", "-C", str(tmp_path), "add", "."], check=True) + subprocess.run( + [ + "git", + "-C", + str(tmp_path), + "-c", + "user.name=Example", + "-c", + "user.email=example@example.com", + "commit", + "-qm", + "base", + ], + check=True, + ) + subprocess.run( + ["git", "-C", str(tmp_path), "mv", "src/old name.py", "tests/test new name.py"], check=True + ) + diff = subprocess.run( + ["git", "-C", str(tmp_path), "diff", "--cached", "--find-renames"], + check=True, + capture_output=True, + text=True, + ).stdout + + patch, test_patch = split_patch_and_test_patch(diff) + + assert patch == "" + assert test_patch == diff + assert _files_in_patch(test_patch) == ["tests/test new name.py"] + + def test_path_is_test_heuristic(): # True positives: files inside test directories assert _path_is_test("tests/test_foo.py")