From 62f00319db1713ffcfbb049a163836072a573cd4 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Sat, 1 Aug 2026 15:25:49 -0700 Subject: [PATCH] fix(patch-parser): tolerate CRLF patch bodies and Move-then-Update Two V4A parse/validate bugs found in a core-tools audit, reproduced live: 1. CRLF patch body injected stray carriage returns. parse_v4a_patch split on '\n' only, so a CRLF-encoded patch kept '\r' inside every HunkLine and wrote mixed line endings into an LF file; the anchored Begin/End markers could also fail to match because of the trailing '\r'. Strip a trailing '\r' from each line at split time. 2. Move-then-Update of the same file was rejected. _validate_operations read the UPDATE target from disk before the MOVE ran, so 'Move a->b' + 'Update b' failed validation with 'b: file not found'. Added a small pending-move overlay so UPDATE/DELETE/MOVE reads during validation see prior ops' effects (moved-in destinations resolve, moved-away sources read as gone), while a genuine 'destination already exists' conflict is still caught. Both verified with sabotage-checked regression tests. 113 patch/fuzzy/file tests pass. --- tests/tools/test_patch_parser.py | 85 ++++++++++++++++++++++++++++++++ tools/patch_parser.py | 58 +++++++++++++++++----- 2 files changed, 132 insertions(+), 11 deletions(-) diff --git a/tests/tools/test_patch_parser.py b/tests/tools/test_patch_parser.py index 8046fc6d86..78a405ae5b 100644 --- a/tests/tools/test_patch_parser.py +++ b/tests/tools/test_patch_parser.py @@ -666,3 +666,88 @@ class TestV4ALspDiagnosticsPropagation: assert result.lsp_diagnostics is not None assert per_file["a.ts"] in result.lsp_diagnostics assert per_file["b.ts"] in result.lsp_diagnostics + + +class _DictFileOps: + """In-memory file_ops backing store supporting update/move/delete/add.""" + + def __init__(self, files): + self.files = dict(files) + + def read_file_raw(self, path): + if path in self.files: + return SimpleNamespace(content=self.files[path], error=None) + return SimpleNamespace(content="", error="file not found") + + def write_file(self, path, content): + self.files[path] = content + return SimpleNamespace(error=None) + + def move_file(self, src, dst): + self.files[dst] = self.files.pop(src) + return SimpleNamespace(error=None) + + def delete_file(self, path): + self.files.pop(path, None) + return SimpleNamespace(error=None) + + +class TestMoveThenUpdateSameFile: + """A rename-then-edit patch must validate and apply (was rejected). + + Regression: _validate_operations read the UPDATE's target from disk before + the MOVE ran, so `Move a->b` + `Update b` failed with 'b: file not found'. + """ + + def test_move_then_update_destination(self): + patch = ( + "*** Begin Patch\n" + "*** Move File: a.py -> b.py\n" + "*** Update File: b.py\n" + "@@\n" + "-x = 1\n" + "+x = 42\n" + "*** End Patch\n" + ) + ops, err = parse_v4a_patch(patch) + assert err is None + fo = _DictFileOps({"a.py": "x = 1\nkeep = 2\n"}) + result = apply_v4a_operations(ops, fo) + assert result.success is True, getattr(result, "error", None) + assert "a.py" not in fo.files + assert fo.files["b.py"] == "x = 42\nkeep = 2\n" + + def test_move_onto_existing_destination_still_rejected(self): + """The overlay must not mask a genuine 'destination exists' conflict.""" + patch = ( + "*** Begin Patch\n" + "*** Move File: a.py -> b.py\n" + "*** End Patch\n" + ) + ops, err = parse_v4a_patch(patch) + assert err is None + fo = _DictFileOps({"a.py": "1\n", "b.py": "2\n"}) + result = apply_v4a_operations(ops, fo) + assert result.success is False + assert "already exists" in (result.error or "") + + +class TestCrlfPatchBody: + """A CRLF-encoded patch body must not inject stray carriage returns.""" + + def test_crlf_body_applied_to_lf_file(self): + patch = ( + "*** Begin Patch\r\n" + "*** Update File: f.py\r\n" + "@@\r\n" + "- x = 1\r\n" + "+ x = 2\r\n" + "*** End Patch\r\n" + ) + ops, err = parse_v4a_patch(patch) + assert err is None + fo = _DictFileOps({"f.py": "def f():\n x = 1\n return x\n"}) + result = apply_v4a_operations(ops, fo) + assert result.success is True, getattr(result, "error", None) + assert "\r" not in fo.files["f.py"] + assert fo.files["f.py"] == "def f():\n x = 2\n return x\n" diff --git a/tools/patch_parser.py b/tools/patch_parser.py index 5a9cd534e0..b2c7a701f6 100644 --- a/tools/patch_parser.py +++ b/tools/patch_parser.py @@ -78,7 +78,12 @@ def parse_v4a_patch(patch_content: str) -> Tuple[List[PatchOperation], Optional[ - If successful: (list_of_operations, None) - If failed: ([], error_description) """ - lines = patch_content.split('\n') + # Split into lines, tolerating a CRLF patch body: strip the trailing + # ``\r`` from each line. Without this, a CRLF-encoded patch keeps ``\r`` + # inside every HunkLine.content and injects stray carriage returns into an + # LF target file (and the anchored ``...\s*$`` Begin/End markers would fail + # to match because of the trailing ``\r``). + lines = [ln[:-1] if ln.endswith('\r') else ln for ln in patch_content.split('\n')] operations: List[PatchOperation] = [] # Find patch boundaries. Markers must occupy the whole line at column 0: @@ -259,16 +264,34 @@ def _validate_operations( errors: List[str] = [] real_change_count = 0 + # Virtual filesystem overlay so inter-op state (notably a MOVE creating the + # destination a later UPDATE targets) validates correctly. Maps a path to + # its pending content; ``None`` marks a path moved/deleted away. UPDATE and + # MOVE reads consult this overlay before hitting disk. + pending_content: dict = {} # path -> content produced by an earlier op + removed_paths: set = set() # paths a MOVE/DELETE has taken away + + def _read(path: str): + """Read a path honoring the pending-move overlay.""" + if path in removed_paths and path not in pending_content: + return None, "file not found" + if path in pending_content: + return pending_content[path], None + r = file_ops.read_file_raw(path) + if r.error: + return None, r.error + return r.content, None + for op in operations: if op.operation != OperationType.UPDATE: real_change_count += 1 if op.operation == OperationType.UPDATE: - read_result = file_ops.read_file_raw(op.file_path) - if read_result.error: - errors.append(f"{op.file_path}: {read_result.error}") + content, read_err = _read(op.file_path) + if read_err: + errors.append(f"{op.file_path}: {read_err}") continue - simulated = read_result.content + simulated = content for hunk_index, hunk in enumerate(op.hunks, start=1): search_lines = [l.content for l in hunk.lines if l.prefix in {' ', '-'}] removed_lines = [l.content for l in hunk.lines if l.prefix == '-'] @@ -318,24 +341,37 @@ def _validate_operations( # Advance simulation so subsequent hunks validate correctly. # Reuse the result from the call above — no second fuzzy run. simulated = new_simulated + # Record the post-update content so a later op (e.g. a MOVE of this + # file) sees the edited version in the overlay. + pending_content[op.file_path] = simulated elif op.operation == OperationType.DELETE: - read_result = file_ops.read_file_raw(op.file_path) - if read_result.error: + _content, read_err = _read(op.file_path) + if read_err: errors.append(f"{op.file_path}: file not found for deletion") + else: + removed_paths.add(op.file_path) + pending_content.pop(op.file_path, None) elif op.operation == OperationType.MOVE: if not op.new_path: errors.append(f"{op.file_path}: MOVE operation missing destination path") continue - src_result = file_ops.read_file_raw(op.file_path) - if src_result.error: + src_content, src_err = _read(op.file_path) + if src_err: errors.append(f"{op.file_path}: source file not found for move") - dst_result = file_ops.read_file_raw(op.new_path) - if not dst_result.error: + dst_content, dst_err = _read(op.new_path) + if not dst_err: errors.append( f"{op.new_path}: destination already exists — move would overwrite" ) + # Reflect the move in the overlay so a subsequent UPDATE of the + # destination validates against the moved content, and the source + # reads as gone. Only when the move itself validated cleanly. + if not src_err and dst_err: + pending_content[op.new_path] = src_content if src_content is not None else "" + pending_content.pop(op.file_path, None) + removed_paths.add(op.file_path) # ADD: parent directory creation handled by write_file; no pre-check needed.