From 6dd26d850a06bb566e621df91bc4af2cfd3685f4 Mon Sep 17 00:00:00 2001 From: developjik <67889389+developjik@users.noreply.github.com> Date: Mon, 30 Nov 2026 13:39:21 +0900 Subject: [PATCH 1/5] =?UTF-8?q?fix(patch):=20review=20pass=20=E2=80=94=20r?= =?UTF-8?q?emoval=20trust,=20hunk=20isolation,=20file=20boundaries?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses the actionable findings from Devin Review on this PR. Each one was reproduced as a test before the fix; the file-on-disk guarantee (any failure leaves the file byte-identical) is unchanged and re-tested. Data loss / corruption: - **A `-` line must be in the file.** The alignment paired a changed line with the nearest one (a mismatch cost less than skipping both) and the renderer then deleted it, so a hunk whose deleted line had been replaced still applied — at a score of 0.625 with one of four lines missing — and removed content the patch never saw. Removals are now verified against their pair (`>= MATCH_FLOOR`); a missing or weakly-matched removal fails as `RemovalMissing`. Context may still drift. This also makes re-applying an applied patch fail instead of deleting its replacement. - **Two hunks can no longer share lines.** When the previous hunk ended past the whole search window, `search_bounds` collapsed the empty range to a single point at the window's edge, so the next hunk could anchor back inside the previous one. An empty range now returns `None` and the hunk fails as `NotAnchored`. A file shorter than the hunk is `None` too. - **A plain `diff -u` multi-file patch is refused.** Only `diff --git` was recognized as a file boundary; a concatenated `---`/`+++` header let the second file's hunks apply to the first file. A `---`/`+++` pair followed by `@@` inside a hunk body is now `MultiFile`. A body line that merely starts with `--` (removing a SQL/Lua comment) is unaffected, and both directions have tests. Wrong-target anchoring: - **Similarity decides before distance.** The distance term was subtracted from the score before ranking, so a nearer 0.96 candidate could outrank the true 1.00 target and the ambiguity check then saw the inversion as a tie (`best - runner < 0`) and skipped itself. Ranking is now similarity-first with distance as the tie-break, and the margin compares the absolute gap. - **Token order counts.** A bag-of-tokens Dice score rated `let elapsed = end - start;` and `let elapsed = start - end;` identical; the similarity now blends the bag score with the same measure over adjacent token pairs (0.6 / 0.4), so a reordered line is similar but not the same line. Rendering: - **Added lines follow their block.** A hunk whose context had moved into a deeper block kept the patch's old indentation, which in Python could move a statement out of its `if` — valid syntax, different program. The indentation shift is taken from the first indented matched line and applied when the patch's prefix matches. - **`\ No newline at end of file` is read per side.** A marker on the removed line means the patch is *adding* the missing newline; it was being treated as "preserve the old shape" and the newline was dropped. An empty file no longer inherits a no-trailing-newline shape it never had (`+hello` now means `hello\n`). Hardening: - The temp file is opened with `create_new` (`O_EXCL`) and named with a random UUID: a predictable name in a shared directory let a planted symlink redirect the write with the patching process's privileges. Documented rather than changed: - `ambiguity_margin: 0.0` disables the rule for *fuzzy* anchors only; two byte-exact blocks at equal distance are still two edits and are still refused. Tests: 67 unit (patch), 27 end-to-end — each finding above has a regression test, plus the existing acceptance-criteria suite. Refs #31 Signed-off-by: 정인권 --- CHANGELOG.md | 44 ++++++--- docs/patch-engine.ko.md | 39 ++++++-- docs/patch-engine.md | 44 +++++++-- src/patch/anchor.rs | 202 ++++++++++++++++++++++++++++++---------- src/patch/atomic.rs | 38 ++++++-- src/patch/mod.rs | 14 +++ src/patch/parse.rs | 104 ++++++++++++++++++--- src/patch/render.rs | 130 ++++++++++++++++++++------ src/patch/score.rs | 81 +++++++++++++--- tests/patch_engine.rs | 109 +++++++++++++++++++++- 10 files changed, 660 insertions(+), 145 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b5d2c4b..d0f0d87 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,13 +18,21 @@ declared line, or a single match within the search window) outranks everything, a pure insertion anchors on its line number, and the rest are scored by token-level similarity — indentation, whitespace runs and - comment tails do not count, two comment-only lines compare at 0.9, but a - changed *code* token does lower the score, and a comment never stands in - for a code line. + comment tails (Python `#` included) do not count, two comment-only lines + compare at 0.9, but a changed *code* token does lower the score, and a + comment never stands in for a code line. Token order counts too: a + bag-of-tokens Dice score blended with adjacent token pairs keeps + `end - start` from passing as `start - end`. +- A hunk's `-` lines are held to a stricter rule than its context: the + context may drift, the line being **removed must be in the file**. A + removal with no trustworthy pair fails as `RemovalMissing` instead of + deleting the nearest line — and a second application of an applied patch + therefore fails instead of removing its replacement. - Two rules turn a score into a decision. An **equal-similarity tie - resolves to the anchor nearest the declared line** (a distance penalty), - so the same patch always lands the same way instead of depending on scan - order. And the best anchor must beat the next non-overlapping one by + resolves to the anchor nearest the declared line** (a distance tie-break + — similarity always decides first, so the tie-break cannot outrank a + better-scoring target), so the same patch always lands the same way + instead of depending on scan order. And the best anchor must beat the next non-overlapping one by `ambiguity_margin`, or the patch fails as `ambiguous` — a patch applied to the wrong place costs far more than one rejected. Exactly the configured margin is still distinguishable, and `margin: 0.0` opts out. @@ -33,8 +41,13 @@ else deleted is not resurrected, and nothing the patch did not address is rewritten. The file's own line endings survive (a CRLF file stays CRLF with an LF-only patch), and a file that ends without a newline keeps - ending that way through a middle edit and through a final-line rewrite - (`\ No newline at end of file` is honored). + ending that way through a middle edit and through a final-line rewrite — + with `\ No newline at end of file` read per side, so a marker on the + removed line means the patch is *adding* the newline back. An empty file + gets the newline a normal patch implies, and an added line follows its + block when the block moved deeper (the indentation shift comes from the + first indented matched line), so a Python statement that moved into an + `if` stays inside it. - **Shadow validation** parses the whole post-patch file and returns `ERROR`/`MISSING` nodes as positioned diagnostics (`line:col: unexpected …`) with the patch rejected, so broken code never reaches the disk and @@ -45,7 +58,9 @@ `SyntaxCheck::Skipped`, never a block. - `apply_patch_file` canonicalizes first (patching through a symlink updates its target, keeping the link) and preserves the target's - permission bits. A no-op patch writes nothing. `render_patch` offers the + permission bits. The temp file name carries a random UUID and is opened + with `O_EXCL` (`create_new`), so a planted symlink in a shared directory + cannot redirect the write. A no-op patch writes nothing. `render_patch` offers the same pipeline in memory with no IO. - `ApplyOptions` carries the knobs: `similarity_threshold` (0.60), `ambiguity_margin` (0.05), `search_window` (±250 lines, `None` = whole @@ -54,11 +69,12 @@ a miscounted hunk header, a fuzzy anchor that moved, or a missing grammar. - Tests: unit coverage for the tokenizer/similarity boundaries (comment - paraphrase vs code change, attributes, strings, Korean text), the parser - (CRLF, bare empty context line, EOF marker, multi-file refusal), the - anchoring rules (exact precedence, moved block, nearest of two, - equidistant ambiguity, margin boundary, out-of-order hunks) and the - atomic write; `tests/patch_engine.rs` covers the issue's acceptance + paraphrase vs code change, token order, attributes, strings, Korean + text), the parser (CRLF, bare empty context line, per-side EOF markers, + `diff --git` and plain `diff -u` multi-file refusal), the anchoring rules + (exact precedence, moved block, nearest of two, equidistant ambiguity, + margin boundary, out-of-order hunks, no hunk reusing another's lines, a + missing removal line) and the atomic write; `tests/patch_engine.rs` covers the issue's acceptance criteria end to end on real files, including `one bad hunk leaves the file byte-identical` and `a syntax error writes nothing`. Docs: `docs/patch-engine.md` (+ `.ko.md`). diff --git a/docs/patch-engine.ko.md b/docs/patch-engine.ko.md index b38004b..94aae78 100644 --- a/docs/patch-engine.ko.md +++ b/docs/patch-engine.ko.md @@ -38,15 +38,26 @@ 퍼지 점수는 줄별 유사도를 정렬해 평균한 값이고, 각 줄은 정규화 후 *토큰*으로 비교한다(`src/patch/score.rs`). 들여쓰기와 연속 공백은 -토큰이 되지 않고, 줄 끝 주석은 코드 토큰에 들어가지 않으며, 주석만 있는 -두 줄은 0.9로 비교된다. 반면 *코드* 토큰이 바뀌면 점수가 실제로 -떨어진다 — 패치가 엉뚱한 함수에 붙지 않게 하는 장치다. 주석 줄이 코드 -줄을 대신할 수는 없다. +토큰이 되지 않고, 줄 끝 주석(파이썬 `#` 주석 포함)은 코드 토큰에 들어가지 +않으며, 주석만 있는 두 줄은 0.9로 비교된다. 반면 *코드* 토큰이 바뀌면 +점수가 실제로 떨어진다 — 패치가 엉뚱한 함수에 붙지 않게 하는 장치다. +주석 줄이 코드 줄을 대신할 수는 없다. 토큰 **순서**도 반영한다. 단어 +가방(bag-of-tokens) Dice 점수와 인접 토큰 쌍에 대한 같은 점수를 섞어, +`end - start`와 `start - end`는 비슷하지만 같지는 않다. + +hunk의 `-` 줄은 컨텍스트와 다르게 다룬다. 컨텍스트는 드리프트를 +견디지만 **삭제 대상 줄은 파일에 있어야 한다**. 믿을 만한 짝이 없는 +삭제 줄은 가장 가까운 줄을 지우는 대신 +`PatchError::RemovalMissing`으로 실패한다. 패치가 보지 못한 내용을 +지우는 조용한 손상은 거부된 패치보다 나쁘다(이미 적용된 패치를 다시 +적용하면 교체 결과를 지우는 대신 실패한다). 점수를 결정으로 바꾸는 규칙 두 가지: - **거리 페널티** — 유사도가 같으면 선언된 줄에 가까운 앵커를 고른다. - 스캔 순서가 아니라 규칙이 결과를 정하므로 재현 가능하다. + 스캔 순서가 아니라 규칙이 결과를 정하므로 재현 가능하다. 점수를 깎는 + 방식이 아니라 동점 처리 규칙이다. 거리 비용을 점수에서 빼면 실제로 + 더 잘 맞는 대상을 앞지를 수 있기 때문에, 유사도가 항상 먼저다. - **모호성 마진** — 최적 앵커는 겹치지 않는 차선 앵커를 `ambiguity_margin`만큼 앞서야 한다. 근소한 차이는 추측하지 않고 `PatchError::Ambiguous`로 실패한다. 잘못 붙은 편집의 복구 비용이 @@ -70,8 +81,14 @@ 있는 그대로 남고, 다른 사람이 지운 주석 줄은 되살아나지 않는다. - CRLF 파일은 패치가 LF로 와도 CRLF를 유지한다. - 파일 끝에 개행이 없으면, 중간 편집 뒤에도, 마지막 줄을 고쳐 쓴 뒤에도 - 개행이 없는 채로 남는다(표준 - `\ No newline at end of file` 마커가 있으면 그대로 따른다). + 개행이 없는 채로 남는다. 표준 `\ No newline at end of file` 마커는 양쪽 + 모두에서 존중한다. 결과 쪽에 붙으면 개행 없음, 삭제 쪽에 붙으면 패치가 + 빠진 개행을 **되살리는** 중이다. +- 블록이 더 깊은 곳으로 옮겨졌으면 추가 줄도 따라간다. 들여쓰기 차이는 + hunk가 맞춘 첫 들여쓰기 줄에서 계산하므로, `if` 안으로 옮겨진 파이썬 + 문장은 `if` 안에 남는다. +- 빈 파일에는 일반 패치가 뜻하는 개행이 들어간다(`+hello`는 `hello\n`). + 애초에 없던 '끝 개행 없음' 모양을 물려받지 않는다. ## 섀도 검증 @@ -99,6 +116,11 @@ best-effort). 같은 파일시스템 안에서 rename은 원자적이라, 읽는 `apply_patch_file`은 먼저 canonicalize하므로 심볼릭 링크를 거친 패치는 링크를 일반 파일로 바꾸지 않고 대상 파일을 고친다. +임시 경로에는 무작위 UUID가 들어가고 `create_new`(`O_EXCL`)로 연다. +다른 로컬 사용자가 쓸 수 있는 디렉터리에서 예측 가능한 이름은 공격 +지점이다. 그 자리에 심볼릭 링크를 심으면 패치 프로세스 권한으로 링크가 +가리키는 곳에 쓰이기 때문이다. + 렌더 결과가 원본과 같으면(무변경 패치) 아무것도 쓰지 않는다. ## API @@ -132,8 +154,9 @@ let rendered = render_patch(Path::new("src/lib.rs"), &original, patch_text, &App | 변형 | 발생 조건 | |---|---| -| `Parse` | 파일 하나의 unified diff가 아님(hunk 없음, 헤더 깨짐, 본문 쓰레기 줄, 두 번째 파일) | +| `Parse` | 파일 하나의 unified diff가 아님(hunk 없음, 헤더 깨짐, 본문 쓰레기 줄, 두 번째 파일 — `diff --git` 또는 `---`/`+++` 쌍 뒤에 `@@`) | | `NotAnchored` | 임계값을 넘는 후보 없음(최고 점수·줄·거리 보고) | +| `RemovalMissing` | `-` 줄이 파일에 없음 — 패치가 본 적 없는 내용을 지우게 됨 | | `Ambiguous` | 최적 두 앵커가 마진 이내 | | `OutOfOrder` | hunk가 파일 순서가 아님 | | `Syntax` | 섀도 파일 파싱 실패(`diagnostics()`로 진단 반환) | diff --git a/docs/patch-engine.md b/docs/patch-engine.md index 723a519..5321616 100644 --- a/docs/patch-engine.md +++ b/docs/patch-engine.md @@ -40,17 +40,29 @@ Three passes, strongest evidence first: The fuzzy score is the aligned average of per-line similarities, each compared on *tokens* after normalization (`src/patch/score.rs`): -indentation and whitespace runs vanish, a line's comment tail is not part -of its code tokens, and two comment-only lines compare at 0.9. A changed -*code* token does move the score — that is what keeps a patch from -anchoring onto the wrong function — and a comment line never stands in -for a code line. +indentation and whitespace runs vanish, a line's comment tail (including +a Python `#` comment) is not part of its code tokens, and two comment-only +lines compare at 0.9. A changed *code* token does move the score — that is +what keeps a patch from anchoring onto the wrong function — and a comment +line never stands in for a code line. Token *order* also counts: the +similarity blends a bag-of-tokens Dice score with the same measure over +adjacent token pairs, so `end - start` and `start - end` are similar but +not identical. + +A hunk's `-` lines are treated differently from its context: the context +may drift, but the line being **removed must be in the file**. A removal +with no trustworthy pair fails as `PatchError::RemovalMissing` instead of +deleting the nearest line — that silent corruption is the one outcome +worse than a rejected patch (and it makes re-applying an applied patch +fail instead of removing its replacement). Two rules turn scores into a decision: - **Distance penalty** — an equal-similarity tie resolves to the anchor nearest the declared line, so the outcome is reproducible instead of - depending on scan order. + depending on scan order. It is a tie-break, not a score adjustment: a + distance cost subtracted from the score could outrank a genuinely + better target, so similarity always decides first. - **Ambiguity margin** — the best anchor must beat the next non-overlapping one by `ambiguity_margin`. A near-tie fails as `PatchError::Ambiguous` rather than guessing: a misplaced edit costs far @@ -76,8 +88,16 @@ Consequences worth knowing: else deleted is not resurrected. - A CRLF file stays CRLF even when the patch arrived LF-only. - A file that ends without a newline keeps ending without one through a - middle edit, and through a rewrite of its final line (the standard - `\ No newline at end of file` marker is honored when present). + middle edit, and through a rewrite of its final line. The standard + `\ No newline at end of file` marker is honored on both sides: on the + result side it means "no newline", on the removed side it means the + patch is *adding* the missing newline back. +- An added line follows its block when the block moved deeper: the + indentation shift is taken from the first indented line the hunk + matched, so a Python statement that moved into an `if` stays inside it. +- An empty file gets the newline a normal patch implies (`+hello` means + `hello\n`), rather than inheriting a "no trailing newline" shape it + never had. ## Shadow validation @@ -105,6 +125,11 @@ filesystem, so a reader sees the old bytes or the new ones, never a mixture. `apply_patch_file` canonicalizes first, so patching through a symlink updates the target instead of replacing the link. +The temp path carries a random UUID and is opened with `create_new` +(`O_EXCL`): a predictable name in a directory another local user can write +to is an attack — plant a symlink there and the write lands wherever it +points, with the patching process's privileges. + If the rendered text equals the original (a no-op patch), nothing is written at all. @@ -139,8 +164,9 @@ All variants of `PatchError` mean the file on disk is unchanged. | variant | when | |---|---| -| `Parse` | not one file's unified diff (no hunk, broken header, garbage body line, second file) | +| `Parse` | not one file's unified diff (no hunk, broken header, garbage body line, second file — `diff --git` or a `---`/`+++` pair followed by `@@`) | | `NotAnchored` | no candidate reached the threshold (reports best score, line, distance) | +| `RemovalMissing` | a `-` line is not in the file — the patch would delete content it never saw | | `Ambiguous` | the best two anchors are within the margin | | `OutOfOrder` | hunks are not in file order | | `Syntax` | the shadow file did not parse (`diagnostics()` returns them) | diff --git a/src/patch/anchor.rs b/src/patch/anchor.rs index a122d5d..abf3181 100644 --- a/src/patch/anchor.rs +++ b/src/patch/anchor.rs @@ -14,9 +14,12 @@ //! 3. **Fuzzy similarity** — a token-level alignment of the hunk's //! pre-patch lines against a window around the declared line. //! -//! Fuzzy ranking applies a small **distance penalty**: equal-scoring -//! anchors resolve to the one nearest the declared line, which makes the -//! outcome reproducible instead of dependent on scan order. And a single +//! Fuzzy ranking puts a small **distance penalty** on equal scores: the +//! anchor nearest the declared line wins a tie, which makes the outcome +//! reproducible instead of dependent on scan order. It is a tie-break, +//! not a score adjustment — a distance cost subtracted from the score +//! could outrank a genuinely better target, so similarity always decides +//! first. And a single //! threshold is not enough to prevent a wrong-but-plausible anchor, so //! the best anchor must also beat the runner-up by `ambiguity_margin`. //! When two anchors are too close to call, the patch fails as @@ -46,12 +49,6 @@ const MISMATCH_PENALTY: f64 = -0.50; /// At or above this line similarity, an aligned pair counts as evidence. const MATCH_FLOOR: f64 = 0.50; -/// How much of the score one line of distance from the declared position -/// can cost, and the cap. The penalty only breaks ties between -/// equal-similarity anchors; it never overrides a real similarity gap. -const DISTANCE_PENALTY_PER_LINE: f64 = 0.0005; -const MAX_DISTANCE_PENALTY: f64 = 0.05; - /// Float slack for "these two scores are the same". const TIE_EPSILON: f64 = 1e-9; @@ -105,7 +102,9 @@ pub(crate) fn anchor_all( }); } previous_start = nominal; - let anchor = anchor_one(index, total, &old, original, &tokens, nominal, floor, opts)?; + let anchor = anchor_one( + index, total, hunk, &old, original, &tokens, nominal, floor, opts, + )?; floor = anchor.end.max(floor); anchors.push(anchor); } @@ -116,6 +115,7 @@ pub(crate) fn anchor_all( fn anchor_one( index: usize, total: usize, + hunk: &Hunk, old: &[&str], original: &[&str], tokens: &[LineTokens], @@ -136,13 +136,26 @@ fn anchor_one( }); } - let (lo, hi) = search_bounds( + let Some((lo, hi)) = search_bounds( nominal, old.len(), original.len(), floor, opts.search_window, - ); + ) else { + // No legal start: every line the declared position allows has + // already been consumed by an earlier hunk, or the file is shorter + // than the block. Never search backward into a previous hunk. + return Err(PatchError::NotAnchored { + hunk: index + 1, + total, + best: 0.0, + line: nominal.min(original.len()) + 1, + distance: 0, + nominal: nominal + 1, + threshold: opts.similarity_threshold, + }); + }; // Pass 1: byte-exact block. let mut exact_matches: Vec = Vec::new(); @@ -158,13 +171,15 @@ fn anchor_one( } if !exact_matches.is_empty() { let chosen = choose_exact(&exact_matches, nominal, index, total, opts)?; - return Ok(Anchor { + let anchor = Anchor { start: chosen, end: chosen + old.len(), pairs: (0..old.len()).map(|i| (i, chosen + i)).collect(), exact: true, similarity: 1.0, - }); + }; + verify_removals(index, total, hunk, old, original, &anchor)?; + return Ok(anchor); } // Pass 2: fuzzy alignment over a window around the declared line. @@ -235,12 +250,11 @@ fn anchor_one( .skip(1) .find(|c| c.end <= best.start || c.start >= best.end) { - let same_score = best.similarity - runner.similarity <= TIE_EPSILON; + let gap = (best.similarity - runner.similarity).abs(); + let same_score = gap <= TIE_EPSILON; let distance_decides = same_score && best.start.abs_diff(nominal) < runner.start.abs_diff(nominal); - if !distance_decides - && within_margin(best.similarity, runner.similarity, opts.ambiguity_margin) - { + if !distance_decides && within_margin(gap, opts.ambiguity_margin) { return Err(PatchError::Ambiguous { hunk: index + 1, total, @@ -253,13 +267,63 @@ fn anchor_one( } } - Ok(Anchor { + let anchor = Anchor { start: best.start, end: best.end, pairs: best.pairs.clone(), exact: false, similarity: best.similarity, - }) + }; + verify_removals(index, total, hunk, old, original, &anchor)?; + Ok(anchor) +} + +/// A hunk's `-` lines are content the patch is *deleting*. The renderer +/// drops them through the alignment, so a removal that only weakly +/// resembles its pair would delete a line the patch never saw — the worst +/// outcome this engine can produce. Context may drift; removal content may +/// not. A removal with no pair, or a pair below [`MATCH_FLOOR`], fails the +/// hunk (and the patch), which also makes a second application of an +/// already-applied patch fail instead of deleting its replacement. +fn verify_removals( + index: usize, + total: usize, + hunk: &Hunk, + old: &[&str], + original: &[&str], + anchor: &Anchor, +) -> Result<(), PatchError> { + let by_old: BTreeMap = anchor.pairs.iter().copied().collect(); + let old_tokens: Vec = old.iter().map(|l| score::tokenize(l)).collect(); + let mut old_index = 0usize; + for line in &hunk.lines { + if line.kind == super::parse::HunkLineKind::Add { + continue; + } + if line.kind == super::parse::HunkLineKind::Remove { + let (line_number, similarity) = match by_old.get(&old_index) { + Some(&file_index) => ( + file_index + 1, + score::similarity( + &old_tokens[old_index], + &score::tokenize(original[file_index]), + ), + ), + None => (anchor.start + 1, 0.0), + }; + if similarity < MATCH_FLOOR { + return Err(PatchError::RemovalMissing { + hunk: index + 1, + total, + expected: line.text.trim().to_string(), + similarity, + line: line_number, + }); + } + } + old_index += 1; + } + Ok(()) } #[derive(Debug, Clone)] @@ -270,54 +334,62 @@ struct Candidate { pairs: Vec<(usize, usize)>, } -/// Order candidates best-first: similarity, then the distance penalty +/// Order candidates best-first: similarity, then the distance tie-break /// (nearer the declared line wins an equal-similarity tie), then file /// order so the result never depends on map iteration order. +/// +/// The distance term is a tie-break, not a score adjustment: subtracting +/// it from the score would let a 0.04-worse candidate 100 lines away +/// outrank the true target, and the ambiguity check would then see its +/// own inverted ranking as a near-tie. fn rank(candidates: &mut [Candidate], nominal: usize) { candidates.sort_by(|a, b| { - let a_rank = a.similarity - distance_penalty(a.start.abs_diff(nominal)); - let b_rank = b.similarity - distance_penalty(b.start.abs_diff(nominal)); - b_rank - .total_cmp(&a_rank) + b.similarity + .total_cmp(&a.similarity) .then(a.start.abs_diff(nominal).cmp(&b.start.abs_diff(nominal))) .then(a.start.cmp(&b.start)) }); } -fn distance_penalty(lines: usize) -> f64 { - (lines as f64 * DISTANCE_PENALTY_PER_LINE).min(MAX_DISTANCE_PENALTY) -} - /// The margin rule: a runner-up within `margin` of the best anchor makes /// the patch ambiguous. Exactly the configured gap is still distinguishable; /// a configured `0.0` switches the rule off, which is how a caller opts -/// into "take the best score even when it is a coin flip". Kept as its own -/// function so the boundary can be pinned by a unit test instead of only -/// showing up as a hand-built file that happens to score a certain way. -fn within_margin(best: f64, runner_up: f64, margin: f64) -> bool { - best - runner_up < margin +/// into "take the best score even when it is a coin flip" — for fuzzy +/// anchors only, since two byte-exact blocks at the same distance are still +/// two edits and are still refused. Kept as its own function so the +/// boundary can be pinned by a unit test instead of only showing up as a +/// hand-built file that happens to score a certain way. +fn within_margin(gap: f64, margin: f64) -> bool { + gap < margin } -/// The inclusive range of candidate start lines to test. +/// The inclusive range of candidate start lines to test. `None` when the +/// window, the file and the previous hunk's end do not intersect: there is +/// no legal start, and searching backward into the previous hunk would let +/// two hunks edit the same lines. fn search_bounds( nominal: usize, len: usize, file_len: usize, floor: usize, window: Option, -) -> (usize, usize) { - let last_start = file_len.saturating_sub(len); +) -> Option<(usize, usize)> { + if file_len < len { + // The block cannot fit: its removal lines are content that must be + // *in* the file, so a file shorter than the hunk has no anchor. + return None; + } + let last_start = file_len - len; let hi = match window { - Some(w) => (nominal + w).min(last_start), + Some(w) => nominal.saturating_add(w).min(last_start), None => last_start, }; let lo = match window { Some(w) => nominal.saturating_sub(w), None => 0, } - .max(floor) - .min(hi); - (lo, hi.max(lo)) + .max(floor); + (lo <= hi).then_some((lo, hi)) } /// Pick between several byte-exact matches: the declared line if it is @@ -512,13 +584,13 @@ mod tests { #[test] fn the_ambiguity_margin_boundary() { // A gap exactly equal to the configured margin is enough. - assert!(!within_margin(0.90, 0.85, 0.05)); - // A hair less is not. - assert!(within_margin(0.90, 0.850_001, 0.05)); + assert!(!within_margin(0.05, 0.05)); + // A hair less is not (0.90 - 0.850_001 = 0.049_999). + assert!(within_margin(0.90 - 0.850_001, 0.05)); // Identical scores are always inside the margin. - assert!(within_margin(0.90, 0.90, 0.05)); + assert!(within_margin(0.0, 0.05)); // Margin 0.0 switches the rule off (callers can opt into best-score-wins). - assert!(!within_margin(0.90, 0.85, 0.0)); + assert!(!within_margin(0.05, 0.0)); } #[test] @@ -556,9 +628,39 @@ mod tests { #[test] fn search_bounds_stay_inside_the_file() { - assert_eq!(search_bounds(0, 3, 10, 0, Some(5)), (0, 5)); - assert_eq!(search_bounds(9, 3, 10, 0, Some(5)), (4, 7)); - assert_eq!(search_bounds(2, 3, 10, 5, Some(5)), (5, 7)); - assert_eq!(search_bounds(2, 3, 10, 0, None), (0, 7)); + assert_eq!(search_bounds(0, 3, 10, 0, Some(5)), Some((0, 5))); + assert_eq!(search_bounds(9, 3, 10, 0, Some(5)), Some((4, 7))); + assert_eq!(search_bounds(2, 3, 10, 5, Some(5)), Some((5, 7))); + assert_eq!(search_bounds(2, 3, 10, 0, None), Some((0, 7))); + } + + #[test] + fn search_bounds_refuse_to_search_backward_into_the_previous_hunk() { + // The previous hunk ended at line 7; this hunk's whole window is + // above that, so there is no legal start at all. + assert_eq!(search_bounds(2, 2, 10, 7, Some(3)), None); + // A file shorter than the block has no start either. + assert_eq!(search_bounds(0, 5, 3, 0, None), None); + } + + #[test] + fn a_second_hunk_never_reuses_the_lines_the_first_one_took() { + // `alpha` exists once; two hunks both want it. + let original = "alpha\nbeta\ngamma\n"; + let patch = "@@ -1,1 +1,1 @@\n-alpha\n+A\n@@ -1,1 +1,1 @@\n-alpha\n+B\n"; + let err = anchor(original, patch).unwrap_err(); + assert!(matches!(err, PatchError::NotAnchored { .. }), "{err}"); + } + + #[test] + fn a_removal_that_is_not_in_the_file_is_refused() { + // Enough surrounding context to pass the threshold; only the line the + // patch deletes was replaced. Dropping the nearest line would delete + // content the patch never saw. + let original = + "keep one\nkeep two\nkeep three\nnew-setting = 2\nkeep five\nkeep six\nkeep seven\n"; + let patch = "@@ -1,7 +1,7 @@\n keep one\n keep two\n keep three\n-obsolete = 1\n+obsolete = 3\n keep five\n keep six\n keep seven\n"; + let err = anchor(original, patch).unwrap_err(); + assert!(matches!(err, PatchError::RemovalMissing { .. }), "{err}"); } } diff --git a/src/patch/atomic.rs b/src/patch/atomic.rs index 701d2ba..04c5165 100644 --- a/src/patch/atomic.rs +++ b/src/patch/atomic.rs @@ -13,6 +13,12 @@ //! the temp file inherits the original's mode, and the rename happens at //! the real path, so patching through a symlink updates its target //! instead of replacing the link with a regular file. +//! +//! The temp file is created with `O_EXCL` (`create_new`). A predictable +//! name in a directory a second local user can write to is otherwise an +//! attack: plant a symlink at the temp path and the write lands wherever +//! it points, with the patching process's privileges. `create_new` refuses +//! to open anything that already exists, symlinks included. use std::io::{self, Write}; use std::path::Path; @@ -29,12 +35,17 @@ pub(crate) fn replace(path: &Path, contents: &[u8]) -> io::Result<()> { .map(|n| n.to_string_lossy().into_owned()) .unwrap_or_else(|| "patch".to_string()); let temp = directory.join(format!(".{name}.damon-patch-{}.tmp", unique_suffix())); - let metadata = std::fs::metadata(path).ok(); + + let mut created = false; let result = (|| -> io::Result<()> { - let mut file = std::fs::File::create(&temp)?; + let mut file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&temp)?; + created = true; if let Some(metadata) = &metadata { - // Keep exec bits and group/other access. File::create would + // Keep exec bits and group/other access. A bare create would // otherwise hand the file the default 0666 & !umask. let _ = file.set_permissions(metadata.permissions()); } @@ -44,9 +55,14 @@ pub(crate) fn replace(path: &Path, contents: &[u8]) -> io::Result<()> { std::fs::rename(&temp, path) })(); - if result.is_err() { - let _ = std::fs::remove_file(&temp); - return result; + if let Err(error) = result { + // Only a file this call created is ours to remove: a name that + // already existed (someone else's file, or a planted symlink) is + // left alone. + if created { + let _ = std::fs::remove_file(&temp); + } + return Err(error); } // Make the rename itself durable on Unix. Best effort: the data is @@ -62,14 +78,16 @@ pub(crate) fn replace(path: &Path, contents: &[u8]) -> io::Result<()> { Ok(()) } -/// Unique enough for concurrent writers in one directory: process id plus -/// a counter that never repeats within the process. +/// Unpredictable and unique: a random UUID plus the process id, so two +/// writers in one directory cannot collide and a local user cannot guess +/// the path ahead of time. fn unique_suffix() -> String { static COUNTER: AtomicU64 = AtomicU64::new(0); format!( - "{}-{}", + "{}-{}-{}", std::process::id(), - COUNTER.fetch_add(1, Ordering::Relaxed) + COUNTER.fetch_add(1, Ordering::Relaxed), + uuid::Uuid::new_v4().simple() ) } diff --git a/src/patch/mod.rs b/src/patch/mod.rs index 0599dfb..cb481ae 100644 --- a/src/patch/mod.rs +++ b/src/patch/mod.rs @@ -169,6 +169,20 @@ pub enum PatchError { runner_line: usize, margin: f64, }, + /// A hunk deletes a line that is not in the file. The context may + /// drift; the line being removed may not — deleting the nearest line + /// instead is exactly the silent corruption this engine exists to + /// prevent. + #[error( + "hunk {hunk}/{total}: `{expected}` is not in the file (best match {similarity:.2} at line {line}); refusing to delete a line the patch never saw" + )] + RemovalMissing { + hunk: usize, + total: usize, + expected: String, + similarity: f64, + line: usize, + }, /// A hunk's declared position is earlier than the hunk before it. #[error( "hunk {hunk}/{total} targets line {line}, before hunk {previous_hunk} at line {previous}; hunks must be in file order" diff --git a/src/patch/parse.rs b/src/patch/parse.rs index 7c06bdb..dd3d853 100644 --- a/src/patch/parse.rs +++ b/src/patch/parse.rs @@ -51,8 +51,14 @@ pub(crate) struct Hunk { /// New-side line count claimed by the header — advisory only. pub declared_new: usize, pub lines: Vec, - /// The hunk ended with `\ No newline at end of file`. - pub eof_no_newline: bool, + /// The hunk's last *new-side* line was marked + /// `\ No newline at end of file` — the result has no trailing newline. + pub new_no_newline: bool, + /// A *pre-patch* line carried that marker: the old file had no trailing + /// newline there. A patch that rewrites that line without the marker is + /// adding the newline back, and the renderer must not preserve the old + /// shape over it. + pub old_no_newline: bool, } impl Hunk { @@ -138,7 +144,8 @@ pub(crate) fn parse(text: &str) -> Result, ParseError> { declared_old: header.old_len, declared_new: header.new_len, lines: Vec::new(), - eof_no_newline: false, + new_no_newline: false, + old_no_newline: false, }); continue; } @@ -153,14 +160,31 @@ pub(crate) fn parse(text: &str) -> Result, ParseError> { if line.starts_with("diff --git ") || line.starts_with("diff --cc ") { return Err(ParseError::MultiFile { line: line_no }); } + // A plain `diff -u` concatenation has no `diff --git` line: the next + // file starts with a `---`/`+++` header pair followed by its first + // `@@`. Inside a hunk body those three lines can only be a file + // boundary — a body line pair (`-­- x` / `+++ y` for a `--` comment) + // is never followed by a hunk header without that header belonging + // to a new file. + if line.starts_with("--- ") + && raw + .get(index + 1) + .is_some_and(|next| next.starts_with("+++ ")) + && raw + .get(index + 2) + .is_some_and(|next| next.starts_with("@@")) + { + return Err(ParseError::MultiFile { line: line_no }); + } if line.is_empty() && index + 1 == raw.len() { // The artifact of the patch text's own final newline, not a // body line. continue; } - // A body line replaces any `\ No newline` marker that preceded it. - hunk.eof_no_newline = false; + // A marker's new-side claim only holds while it closes the hunk; + // the old-side claim is about a line already read, so it stays. + hunk.new_no_newline = false; match line.chars().next() { None => { // A bare empty line: git writes " " for an empty context @@ -184,9 +208,18 @@ pub(crate) fn parse(text: &str) -> Result, ParseError> { }), Some('\\') => { // "\ No newline at end of file" describes the line above. - // It only means something when it closes the hunk; a - // later body line clears it again. - hunk.eof_no_newline = true; + match hunk.lines.last().map(|l| l.kind) { + // A trailing context line is both sides at once. + Some(HunkLineKind::Context) | None => { + hunk.new_no_newline = true; + hunk.old_no_newline = true; + } + Some(HunkLineKind::Add) => hunk.new_no_newline = true, + Some(HunkLineKind::Remove) => { + hunk.old_no_newline = true; + hunk.new_no_newline = false; + } + } } Some(_) => { return Err(ParseError::Garbage { @@ -308,13 +341,33 @@ index 1111111..2222222 100644 #[test] fn eof_no_newline_marker_is_captured() { let hunks = parse("@@ -1,1 +1,1 @@\n-a\n+b\n\\ No newline at end of file\n").unwrap(); - assert!(hunks[0].eof_no_newline); + assert!(hunks[0].new_no_newline); + assert!(!hunks[0].old_no_newline); + } + + #[test] + fn a_marker_on_the_old_side_only_stops_claiming_the_new_side() { + // Both sides lack a newline: the result has none either. + let hunks = parse( + "@@ -1,1 +1,1 @@\n-a\n\\ No newline at end of file\n+b\n\\ No newline at end of file\n", + ) + .unwrap(); + assert!(hunks[0].old_no_newline); + assert!(hunks[0].new_no_newline); + } + + #[test] + fn a_marker_on_a_removed_line_that_is_replaced_says_the_new_side_has_one() { + // git writes this when the patch *adds* the missing final newline. + let hunks = parse("@@ -1,1 +1,1 @@\n-a\n\\ No newline at end of file\n+a\n").unwrap(); + assert!(hunks[0].old_no_newline); + assert!(!hunks[0].new_no_newline); } #[test] fn a_marker_followed_by_another_line_is_not_the_eof_marker() { - let hunks = parse("@@ -1,2 +1,2 @@\n-a\n\\ No newline at end of file\n+b\n c\n").unwrap(); - assert!(!hunks[0].eof_no_newline); + let hunks = parse("@@ -1,2 +1,2 @@\n-a\n+b\n c\n\\ No newline at end of file\n").unwrap(); + assert!(hunks[0].new_no_newline); } #[test] @@ -322,6 +375,35 @@ index 1111111..2222222 100644 assert_eq!(parse("just a sentence\n").unwrap_err(), ParseError::NoHunks); } + #[test] + fn rejects_a_plain_diff_u_second_file() { + // `diff -u a b` output concatenated for two files: no `diff --git`. + let patch = "\ +--- old/one.txt\t2026-11-30 10:00:00 ++++ new/one.txt\t2026-11-30 10:00:00 +@@ -1,1 +1,1 @@ +-a ++A +--- old/two.txt\t2026-11-30 10:00:00 ++++ new/two.txt\t2026-11-30 10:00:00 +@@ -1,1 +1,1 @@ +-b ++B +"; + let err = parse(patch).unwrap_err(); + assert!(matches!(err, ParseError::MultiFile { .. }), "{err}"); + } + + #[test] + fn a_body_that_looks_like_a_file_header_is_still_body() { + // Removing a `--` comment and adding another: the two lines look + // like a `---`/`+++` pair but no hunk header follows them. + let patch = "@@ -1,2 +1,2 @@\n--- old note\n+++ new note\n keep\n"; + let hunks = parse(patch).unwrap(); + assert_eq!(hunks[0].lines[0].text, "-- old note"); + assert_eq!(hunks[0].lines[1].text, "++ new note"); + } + #[test] fn rejects_a_second_file_header() { let err = parse("@@ -1,1 +1,1 @@\n-a\n+b\ndiff --git a/x b/x\n").unwrap_err(); diff --git a/src/patch/render.rs b/src/patch/render.rs index a500c59..bbdd39b 100644 --- a/src/patch/render.rs +++ b/src/patch/render.rs @@ -10,11 +10,24 @@ //! - **added** patch lines, written with the file's own line ending, so a //! CRLF file stays CRLF even when the patch text arrived LF-only. //! -//! The tail is handled separately: a file that ends without a newline -//! keeps ending without one through a middle edit, and a patch that -//! rewrites the final line either carries the standard -//! `\ No newline at end of file` marker or, if the file already ended -//! without one, keeps that ending. +//! Two details make the difference between "the file still means what it +//! did" and "the file compiles but says something else": +//! +//! - **Indentation is rebased onto the matched line.** The score ignores +//! indentation so a block that moved into a deeper block still anchors; +//! the added lines must then follow it there, or a Python statement +//! lands outside the `if` its context lives in. The shift is taken from +//! the first indented line the hunk matched, and applied only when the +//! patch's own prefix is a prefix of the replacement line (a patch that +//! indents differently from its context is left alone). +//! - **The tail keeps its shape.** A file that ends without a newline +//! keeps ending without one through a middle edit; a patch that rewrites +//! the final line either carries `\ No newline at end of file` (no +//! newline) or the marker sat on the removed line (the patch is adding +//! the newline back). + +use std::borrow::Cow; +use std::collections::BTreeMap; use super::anchor::Anchor; use super::parse::{Hunk, HunkLineKind}; @@ -53,20 +66,27 @@ pub(crate) fn render(original: &[FileLine<'_>], hunks: &[Hunk], anchors: &[Ancho } else { "\n" }; - let eof_marker = hunks.last().map(|h| h.eof_no_newline).unwrap_or(false); - let file_ends_with_newline = original.last().map(|(_, e)| !e.is_empty()).unwrap_or(false); + let (new_no_newline, old_no_newline) = hunks + .last() + .map(|h| (h.new_no_newline, h.old_no_newline)) + .unwrap_or((false, false)); + // An empty file has nothing to preserve a shape *from*: a patch that + // adds its first line means `line\n`, not a file with no newline. + let file_ends_with_newline = + original.is_empty() || original.last().map(|(_, e)| !e.is_empty()).unwrap_or(false); - let mut out: Vec<(&str, &str)> = Vec::new(); + let mut out: Vec<(Cow<'_, str>, &str)> = Vec::new(); let mut last_is_added = false; let mut cursor = 0usize; for (hunk, anchor) in hunks.iter().zip(anchors) { + let shift = indent_shift(hunk, anchor, original); while cursor < anchor.start && cursor < original.len() { - out.push(original[cursor]); + out.push((Cow::Borrowed(original[cursor].0), original[cursor].1)); last_is_added = false; cursor += 1; } - let mut mapped = std::collections::BTreeMap::new(); + let mut mapped = BTreeMap::new(); for &(old_index, file_index) in &anchor.pairs { mapped.insert(old_index, file_index); } @@ -76,11 +96,14 @@ pub(crate) fn render(original: &[FileLine<'_>], hunks: &[Hunk], anchors: &[Ancho HunkLineKind::Context => { if let Some(&file_index) = mapped.get(&old_index) { while cursor < file_index { - out.push(original[cursor]); + out.push((Cow::Borrowed(original[cursor].0), original[cursor].1)); cursor += 1; } if cursor == file_index { - out.push(original[file_index]); + out.push(( + Cow::Borrowed(original[file_index].0), + original[file_index].1, + )); last_is_added = false; cursor = file_index + 1; } @@ -94,7 +117,7 @@ pub(crate) fn render(original: &[FileLine<'_>], hunks: &[Hunk], anchors: &[Ancho && file_index >= cursor { while cursor < file_index { - out.push(original[cursor]); + out.push((Cow::Borrowed(original[cursor].0), original[cursor].1)); cursor += 1; } cursor = file_index + 1; @@ -102,38 +125,37 @@ pub(crate) fn render(original: &[FileLine<'_>], hunks: &[Hunk], anchors: &[Ancho old_index += 1; } HunkLineKind::Add => { - out.push((line.text.as_str(), newline)); + out.push((rebase(&line.text, shift.as_ref()), newline)); last_is_added = true; } } } } while cursor < original.len() { - out.push(original[cursor]); + out.push((Cow::Borrowed(original[cursor].0), original[cursor].1)); last_is_added = false; cursor += 1; } // The final line's ending. A kept file line keeps its own ending - // (including none); an added final line takes one unless the patch - // marked it or the file it replaced had no trailing newline. + // (including none). An added final line takes one unless the patch's + // new side is marked, or it replaced a tail that had none and the patch + // did not say it was adding one. let reaches_eof = anchors .last() .map(|a| a.end >= original.len()) .unwrap_or(false); - let drop_final_newline = - eof_marker || (last_is_added && reaches_eof && !file_ends_with_newline); + let keep_old_shape = last_is_added && reaches_eof && !file_ends_with_newline && !old_no_newline; + let drop_final_newline = new_no_newline || keep_old_shape; let mut text = String::new(); for (index, (content, ending)) in out.iter().enumerate() { text.push_str(content); if index + 1 == out.len() { - if last_is_added { - if !drop_final_newline { - text.push_str(newline); - } - } else { + if !last_is_added { text.push_str(ending); + } else if !drop_final_newline { + text.push_str(newline); } } else if ending.is_empty() { text.push_str(newline); @@ -144,18 +166,52 @@ pub(crate) fn render(original: &[FileLine<'_>], hunks: &[Hunk], anchors: &[Ancho text } +/// `(patch prefix, file prefix)` when the hunk's added lines have to move +/// to a different indentation level to stay inside their context. +fn indent_shift( + hunk: &Hunk, + anchor: &Anchor, + original: &[FileLine<'_>], +) -> Option<(String, String)> { + let old: Vec<&str> = hunk.old_lines().collect(); + for &(old_index, file_index) in &anchor.pairs { + let patch_prefix = leading_whitespace(old[old_index]); + if patch_prefix.is_empty() { + continue; + } + let file_prefix = leading_whitespace(original[file_index].0); + if patch_prefix != file_prefix { + return Some((patch_prefix.to_string(), file_prefix.to_string())); + } + // The first indented line decides; a later, deeper line is nested + // *within* the block, not a shift of it. + return None; + } + None +} + +fn leading_whitespace(line: &str) -> &str { + &line[..line.len() - line.trim_start_matches([' ', '\t']).len()] +} + +fn rebase<'a>(line: &'a str, shift: Option<&(String, String)>) -> Cow<'a, str> { + let Some((from, to)) = shift else { + return Cow::Borrowed(line); + }; + match line.strip_prefix(from.as_str()) { + Some(rest) => Cow::Owned(format!("{to}{rest}")), + None => Cow::Borrowed(line), + } +} + #[cfg(test)] mod tests { use super::*; - fn lines(text: &str) -> Vec<(&str, &str)> { - split(text) - } - #[test] fn split_keeps_each_line_ending() { assert_eq!( - lines("a\r\nb\nc"), + split("a\r\nb\nc"), vec![("a", "\r\n"), ("b", "\n"), ("c", "")] ); } @@ -169,4 +225,20 @@ mod tests { fn split_of_a_single_newline_is_one_empty_line() { assert_eq!(split("\n"), vec![("", "\n")]); } + + #[test] + fn leading_whitespace_reads_indentation() { + assert_eq!(leading_whitespace(" x"), " "); + assert_eq!(leading_whitespace("\t\tx"), "\t\t"); + assert_eq!(leading_whitespace("x"), ""); + assert_eq!(leading_whitespace(" "), " "); + } + + #[test] + fn rebase_rewrites_only_a_matching_prefix() { + let shift = Some((" ".to_string(), " ".to_string())); + assert_eq!(rebase(" save();", shift.as_ref()), " save();"); + assert_eq!(rebase("save();", shift.as_ref()), "save();"); + assert_eq!(rebase(" save();", None), " save();"); + } } diff --git a/src/patch/score.rs b/src/patch/score.rs index 6a24494..a5dd0f2 100644 --- a/src/patch/score.rs +++ b/src/patch/score.rs @@ -8,7 +8,8 @@ //! - indentation and runs of whitespace never become tokens, so re-indented //! or re-wrapped lines compare equal; //! - a line's comment tail is not part of its code tokens, so a -//! paraphrased or deleted comment costs nothing on a code line; +//! paraphrased or deleted comment costs nothing on a code line (this +//! includes `#` comments — Python, shell, Ruby, TOML); //! - two comment-only lines compare at [`COMMENT_DRIFT_SIM`] — high enough //! to keep their place in a hunk, low enough that code evidence still //! dominates the hunk score; @@ -18,10 +19,17 @@ //! The cost of that tolerance: a *code* token change does move the score, //! which is what keeps a patch from anchoring onto the wrong function. //! +//! Token *order* still counts: the similarity blends a bag-of-tokens Dice +//! score with the same measure over adjacent token pairs, so +//! `end - start` and `start - end` are similar (same operands, same +//! operator) but not identical. Without the pair term a reordered line +//! scores 1.0, and a patch could land on the line that computes the +//! opposite value. +//! //! Comment detection is deliberately lexical and language-agnostic -//! (`//`, `/* */`, and `#` at the start of the line's code), which also -//! catches C preprocessor lines as "comments". They are treated as -//! prose-like, which is acceptable: preprocessor lines never carry the +//! (`//`, `/* */`, and `#` at the start of the line or after whitespace), +//! which also catches C preprocessor lines as "comments". They are treated +//! as prose-like, which is acceptable: preprocessor lines never carry the //! edit an agent is trying to place. use std::hash::{Hash, Hasher}; @@ -38,6 +46,9 @@ pub(crate) struct LineTokens { /// multiset intersection is a linear merge, and hashed so a token /// comparison is an integer compare. code: Vec, + /// Sorted hashes of each adjacent token pair, so the comparison sees + /// token order and not just the bag of tokens. + pairs: Vec, /// The line carries a comment (and therefore some prose). has_comment: bool, /// The line is empty or whitespace only. @@ -51,6 +62,11 @@ impl LineTokens { } } +/// Between 0 and 1: how much of a line's similarity the pair term carries. +/// High enough that a reordered line cannot pass as identical, low enough +/// that one changed token in a long line still scores as a match. +const PAIR_WEIGHT: f64 = 0.4; + /// Reduce one line to its comparable tokens. pub(crate) fn tokenize(line: &str) -> LineTokens { let mut code: Vec = Vec::new(); @@ -74,11 +90,11 @@ pub(crate) fn tokenize(line: &str) -> LineTokens { None => break, } } - // `#` starts a comment when nothing but indentation precedes it - // and it is not a Rust attribute (`#[…]`) or inner attribute - // (`#![…]`). - '#' if line[..i].trim().is_empty() - && !matches!(bytes.get(i + 1), Some(b'[') | Some(b'!')) => + // `#` starts a comment at the start of the line or after + // whitespace, unless it is a Rust attribute (`#[…]`) or inner + // attribute/ shebang (`#![…]`). `foo#bar` stays a token. + '#' if !matches!(bytes.get(i + 1), Some(b'[') | Some(b'!')) + && bytes[..i].last().is_none_or(|b| *b == b' ' || *b == b'\t') => { has_comment = true; break; @@ -107,14 +123,27 @@ pub(crate) fn tokenize(line: &str) -> LineTokens { } } + let mut pairs: Vec = code + .windows(2) + .map(|pair| pair_hash(pair[0], pair[1])) + .collect(); code.sort_unstable(); + pairs.sort_unstable(); LineTokens { code, + pairs, has_comment, blank: line.trim().is_empty(), } } +fn pair_hash(first: u64, second: u64) -> u64 { + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + first.hash(&mut hasher); + second.hash(&mut hasher); + hasher.finish() +} + /// Token-level Dice coefficient between two lines, 0.0–1.0. pub(crate) fn similarity(a: &LineTokens, b: &LineTokens) -> f64 { if a.blank || b.blank { @@ -138,9 +167,18 @@ pub(crate) fn similarity(a: &LineTokens, b: &LineTokens) -> f64 { 0.0 }; } + let bag = dice(&a.code, &b.code); + if a.pairs.is_empty() || b.pairs.is_empty() { + return bag; + } + (1.0 - PAIR_WEIGHT) * bag + PAIR_WEIGHT * dice(&a.pairs, &b.pairs) +} + +/// Multiset Dice coefficient over two sorted hash lists. +fn dice(a: &[u64], b: &[u64]) -> f64 { let (mut i, mut j, mut common) = (0usize, 0usize, 0usize); - while i < a.code.len() && j < b.code.len() { - match a.code[i].cmp(&b.code[j]) { + while i < a.len() && j < b.len() { + match a[i].cmp(&b[j]) { std::cmp::Ordering::Less => i += 1, std::cmp::Ordering::Greater => j += 1, std::cmp::Ordering::Equal => { @@ -150,7 +188,7 @@ pub(crate) fn similarity(a: &LineTokens, b: &LineTokens) -> f64 { } } } - (2.0 * common as f64) / ((a.code.len() + b.code.len()) as f64) + (2.0 * common as f64) / ((a.len() + b.len()) as f64) } fn hash(token: &str) -> u64 { @@ -237,6 +275,25 @@ mod tests { assert!(s > 0.7 && s < 1.0, "{s}"); } + #[test] + fn token_order_counts() { + let s = sim("let elapsed = end - start;", "let elapsed = start - end;"); + assert!(s > 0.5 && s < 0.9, "{s}"); + } + + #[test] + fn a_python_trailing_comment_is_not_code() { + assert_eq!( + sim( + "return result # read from disk", + "return result # use cache" + ), + 1.0 + ); + // A decorator or a dict is not a comment. + assert!(sim("x = {'a': 1}", "x = {'a': 2}") < 1.0); + } + #[test] fn korean_text_in_a_comment_is_ignored() { assert_eq!(sim("let x = 1; // 값 설정", "let x = 1;"), 1.0); diff --git a/tests/patch_engine.rs b/tests/patch_engine.rs index e7dbb53..2c85f3d 100644 --- a/tests/patch_engine.rs +++ b/tests/patch_engine.rs @@ -131,7 +131,29 @@ fn a_rewritten_code_line_is_not_mistaken_for_comment_drift() { + let count = compute(&users, 2); "; let err = apply(&path, patch).unwrap_err(); - assert!(matches!(err, PatchError::NotAnchored { .. }), "{err}"); + assert!( + matches!( + err, + PatchError::RemovalMissing { .. } | PatchError::NotAnchored { .. } + ), + "{err}" + ); + assert_eq!(contents(&path), body); + assert_no_temp_files(&dir); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn a_removal_of_a_line_the_file_does_not_have_is_refused() { + // The surrounding context still matches; only the deleted line was + // replaced by someone else. Deleting the nearest line instead would + // remove content the patch never saw. + let dir = temp_dir("removal-missing"); + let body = "keep one\nkeep two\nkeep three\nnew-setting = 2\nkeep five\nkeep six\n"; + let path = write(&dir, "notes.txt", body); + let patch = "@@ -1,6 +1,6 @@\n keep one\n keep two\n keep three\n-obsolete = 1\n+obsolete = 3\n keep five\n keep six\n"; + let err = apply(&path, patch).unwrap_err(); + assert!(matches!(err, PatchError::RemovalMissing { .. }), "{err}"); assert_eq!(contents(&path), body); assert_no_temp_files(&dir); std::fs::remove_dir_all(&dir).unwrap(); @@ -313,11 +335,33 @@ fn applying_the_same_patch_twice_does_not_double_apply() { // The pre-patch line is gone, so the retry cannot anchor — it is refused, // and the applied file stays exactly as it is. let err = apply(&path, patch).unwrap_err(); - assert!(matches!(err, PatchError::NotAnchored { .. }), "{err}"); + assert!( + matches!( + err, + PatchError::RemovalMissing { .. } | PatchError::NotAnchored { .. } + ), + "{err}" + ); assert_eq!(contents(&path), "a\nB\nc\n"); std::fs::remove_dir_all(&dir).unwrap(); } +#[test] +fn a_second_hunk_never_edits_the_lines_the_first_one_took() { + // `alpha` exists once; both hunks want it. + let dir = temp_dir("hunk-overlap"); + let body = "alpha\nbeta\ngamma\n"; + let path = write(&dir, "notes.txt", body); + let patch = "@@ -1,1 +1,1 @@\n-alpha\n+A\n@@ -1,1 +1,1 @@\n-alpha\n+B\n"; + let err = apply(&path, patch).unwrap_err(); + assert!( + matches!(err, PatchError::NotAnchored { hunk: 2, .. }), + "{err}" + ); + assert_eq!(contents(&path), body); + std::fs::remove_dir_all(&dir).unwrap(); +} + #[cfg(unix)] #[test] fn patching_through_a_symlink_updates_the_target() { @@ -336,6 +380,67 @@ fn patching_through_a_symlink_updates_the_target() { std::fs::remove_dir_all(&dir).unwrap(); } +#[test] +fn an_empty_file_gains_the_newline_the_patch_asks_for() { + let dir = temp_dir("empty-file"); + let path = write(&dir, "notes.txt", ""); + apply(&path, "@@ -0,0 +1,1 @@\n+hello\n").unwrap(); + assert_eq!(contents(&path), "hello\n"); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn a_patch_can_add_the_final_newline_the_file_was_missing() { + // The marker on the removed line says the old side had no newline; the + // new side does. + let dir = temp_dir("restore-newline"); + let path = write(&dir, "notes.txt", "a\nb"); + let patch = "@@ -2,1 +2,1 @@\n-b\n\\ No newline at end of file\n+b\n"; + apply(&path, patch).unwrap(); + assert_eq!(contents(&path), "a\nb\n"); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn a_python_statement_that_moved_into_a_block_keeps_the_blocks_indent() { + // The file moved `store()` inside the `if` after the patch was written. + // The replacement must follow it there, or it runs unconditionally. + let dir = temp_dir("python-indent"); + let body = "def save(enabled):\n if enabled:\n log()\n store()\n"; + let path = write(&dir, "tool.py", body); + let patch = "@@ -1,2 +1,2 @@\n def save(enabled):\n- store()\n+ persist()\n"; + let report = apply(&path, patch).unwrap(); + assert_eq!(report.syntax, SyntaxCheck::Clean("python")); + assert_eq!( + contents(&path), + "def save(enabled):\n if enabled:\n log()\n persist()\n" + ); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn a_plain_diff_u_multi_file_patch_is_refused() { + let dir = temp_dir("multi-file-u"); + let body = "a\nb\n"; + let path = write(&dir, "notes.txt", body); + let patch = "\ +--- old/one.txt\t2026-11-30 10:00:00 ++++ new/one.txt\t2026-11-30 10:00:00 +@@ -1,1 +1,1 @@ +-a ++A +--- old/two.txt\t2026-11-30 10:00:00 ++++ new/two.txt\t2026-11-30 10:00:00 +@@ -1,1 +1,1 @@ +-b ++B +"; + let err = apply(&path, patch).unwrap_err(); + assert!(matches!(err, PatchError::Parse(_)), "{err}"); + assert_eq!(contents(&path), body); + std::fs::remove_dir_all(&dir).unwrap(); +} + #[test] fn a_multi_file_patch_is_refused() { let dir = temp_dir("multi-file"); From a82d1cafd2cf2a992832f9201d938350c1886c3a Mon Sep 17 00:00:00 2001 From: developjik <67889389+developjik@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:32:59 +0900 Subject: [PATCH 2/5] =?UTF-8?q?fix(patch):=20second=20review=20pass=20?= =?UTF-8?q?=E2=80=94=20code-level=20removal=20check,=20honest=20shifts?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Follow-up findings on #63, each reproduced as a test. - **A removed line's *code* must match, not just its similarity.** The previous 0.5 similarity floor let a stale patch overwrite a line whose argument also changed, because the comment term is normalized away. A removal now requires identical code tokens (comments and indentation may differ); anything else is `RemovalMissing`. - **Indentation is rebased only from code lines, and only when they agree.** A comment that someone moved into an `if` was read as the block having moved, and the replacement call was pushed inside with it. Blank and comment lines no longer decide the shift, and conflicting shifts disable rebasing. - **Multi-line string contents are never rebased.** Reindenting an added line inside an open triple-quoted literal changed data. A small tracker skips lines while a `"""`/`'''` literal is open. - **A `diff -U0` hunk that looks like a file header is body.** The multi-file boundary check now also requires the current hunk to have taken everything its header declared, so a one-file patch whose hunk body is `--- old note` / `+++ new note` parses as one file. - Test corrected: `a_marker_followed_by_another_line_*` now actually has a body line after the marker. Tests: 66 unit (patch), 29 end-to-end. Refs #31 Signed-off-by: 정인권 --- CHANGELOG.md | 15 +++-- docs/patch-engine.ko.md | 11 ++-- docs/patch-engine.md | 21 ++++--- src/patch/anchor.rs | 118 +++++++++++++++++++++++----------------- src/patch/mod.rs | 8 ++- src/patch/parse.rs | 38 +++++++++++-- src/patch/render.rs | 74 ++++++++++++++++++++++--- src/patch/score.rs | 8 +++ tests/patch_engine.rs | 39 +++++++++++++ 9 files changed, 249 insertions(+), 83 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d0f0d87..69c553a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,10 +24,12 @@ bag-of-tokens Dice score blended with adjacent token pairs keeps `end - start` from passing as `start - end`. - A hunk's `-` lines are held to a stricter rule than its context: the - context may drift, the line being **removed must be in the file**. A - removal with no trustworthy pair fails as `RemovalMissing` instead of - deleting the nearest line — and a second application of an applied patch - therefore fails instead of removing its replacement. + context may drift, but the line being **removed must still carry that + code in the file**. Comments and indentation may differ; the tokens may + not. A removal whose pair carries different code (or has no pair) fails + as `RemovalMissing` instead of deleting the nearest line — and a second + application of an applied patch therefore fails instead of removing its + replacement. - Two rules turn a score into a decision. An **equal-similarity tie resolves to the anchor nearest the declared line** (a distance tie-break — similarity always decides first, so the tie-break cannot outrank a @@ -46,8 +48,9 @@ removed line means the patch is *adding* the newline back. An empty file gets the newline a normal patch implies, and an added line follows its block when the block moved deeper (the indentation shift comes from the - first indented matched line), so a Python statement that moved into an - `if` stays inside it. + matched code lines, all of which must agree), so a Python statement that + moved into an `if` stays inside it — while a moved *comment* does not drag + code with it and the inside of a triple-quoted string is left alone. - **Shadow validation** parses the whole post-patch file and returns `ERROR`/`MISSING` nodes as positioned diagnostics (`line:col: unexpected …`) with the patch rejected, so broken code never reaches the disk and diff --git a/docs/patch-engine.ko.md b/docs/patch-engine.ko.md index 94aae78..58596a2 100644 --- a/docs/patch-engine.ko.md +++ b/docs/patch-engine.ko.md @@ -46,8 +46,9 @@ `end - start`와 `start - end`는 비슷하지만 같지는 않다. hunk의 `-` 줄은 컨텍스트와 다르게 다룬다. 컨텍스트는 드리프트를 -견디지만 **삭제 대상 줄은 파일에 있어야 한다**. 믿을 만한 짝이 없는 -삭제 줄은 가장 가까운 줄을 지우는 대신 +견디지만 **삭제 대상 줄은 그 코드가 파일에 그대로 있어야 한다**. 주석과 +들여쓰기는 달라도 되지만 토큰은 달라서는 안 된다. 코드가 다른 짝, 또는 +짝이 아예 없는 삭제 줄은 가장 가까운 줄을 지우는 대신 `PatchError::RemovalMissing`으로 실패한다. 패치가 보지 못한 내용을 지우는 조용한 손상은 거부된 패치보다 나쁘다(이미 적용된 패치를 다시 적용하면 교체 결과를 지우는 대신 실패한다). @@ -85,8 +86,10 @@ hunk의 `-` 줄은 컨텍스트와 다르게 다룬다. 컨텍스트는 드리 모두에서 존중한다. 결과 쪽에 붙으면 개행 없음, 삭제 쪽에 붙으면 패치가 빠진 개행을 **되살리는** 중이다. - 블록이 더 깊은 곳으로 옮겨졌으면 추가 줄도 따라간다. 들여쓰기 차이는 - hunk가 맞춘 첫 들여쓰기 줄에서 계산하므로, `if` 안으로 옮겨진 파이썬 - 문장은 `if` 안에 남는다. + 매칭된 **코드** 줄에서만 계산하고(옮겨진 주석은 블록의 이동을 말해주지 + 않는다), 모든 코드 줄이 같은 차이를 가리켜야 하며, 패치 자체의 접두사가 + 교체 줄의 접두사일 때만 적용한다. 열린 삼중 따옴표 문자열 안의 줄은 + 건드리지 않는다. 그 공백은 들여쓰기가 아니라 데이터다. - 빈 파일에는 일반 패치가 뜻하는 개행이 들어간다(`+hello`는 `hello\n`). 애초에 없던 '끝 개행 없음' 모양을 물려받지 않는다. diff --git a/docs/patch-engine.md b/docs/patch-engine.md index 5321616..7e54adf 100644 --- a/docs/patch-engine.md +++ b/docs/patch-engine.md @@ -50,11 +50,13 @@ adjacent token pairs, so `end - start` and `start - end` are similar but not identical. A hunk's `-` lines are treated differently from its context: the context -may drift, but the line being **removed must be in the file**. A removal -with no trustworthy pair fails as `PatchError::RemovalMissing` instead of -deleting the nearest line — that silent corruption is the one outcome -worse than a rejected patch (and it makes re-applying an applied patch -fail instead of removing its replacement). +may drift, but the line being **removed must still carry that code in the +file**. Comments and indentation may differ; the tokens may not. A +removal whose pair has different code, or no pair at all, fails as +`PatchError::RemovalMissing` instead of deleting the nearest line — that +silent corruption is the one outcome worse than a rejected patch (and it +makes re-applying an applied patch fail instead of removing its +replacement). Two rules turn scores into a decision: @@ -93,8 +95,11 @@ Consequences worth knowing: result side it means "no newline", on the removed side it means the patch is *adding* the missing newline back. - An added line follows its block when the block moved deeper: the - indentation shift is taken from the first indented line the hunk - matched, so a Python statement that moved into an `if` stays inside it. + indentation shift is taken from the matched *code* lines only (a comment + that moved says nothing about the block), must be the same for every one + of them, and is applied only when the patch's own prefix is a prefix of + the replacement line. Lines inside an open triple-quoted string are left + alone — that whitespace is data, not indentation. - An empty file gets the newline a normal patch implies (`+hello` means `hello\n`), rather than inheriting a "no trailing newline" shape it never had. @@ -166,7 +171,7 @@ All variants of `PatchError` mean the file on disk is unchanged. |---|---| | `Parse` | not one file's unified diff (no hunk, broken header, garbage body line, second file — `diff --git` or a `---`/`+++` pair followed by `@@`) | | `NotAnchored` | no candidate reached the threshold (reports best score, line, distance) | -| `RemovalMissing` | a `-` line is not in the file — the patch would delete content it never saw | +| `RemovalMissing` | a `-` line's code is not in the file — the patch would delete content it never saw | | `Ambiguous` | the best two anchors are within the margin | | `OutOfOrder` | hunks are not in file order | | `Syntax` | the shadow file did not parse (`diagnostics()` returns them) | diff --git a/src/patch/anchor.rs b/src/patch/anchor.rs index abf3181..fe8a792 100644 --- a/src/patch/anchor.rs +++ b/src/patch/anchor.rs @@ -279,12 +279,12 @@ fn anchor_one( } /// A hunk's `-` lines are content the patch is *deleting*. The renderer -/// drops them through the alignment, so a removal that only weakly -/// resembles its pair would delete a line the patch never saw — the worst -/// outcome this engine can produce. Context may drift; removal content may -/// not. A removal with no pair, or a pair below [`MATCH_FLOOR`], fails the -/// hunk (and the patch), which also makes a second application of an -/// already-applied patch fail instead of deleting its replacement. +/// drops them through the alignment, so a removal that only *resembles* its +/// pair would delete code the patch never saw — the worst outcome this +/// engine can produce. Context may drift and comments may be rewritten; the +/// code being deleted may not. A removal whose pair carries different code +/// (or no pair at all) fails the hunk, which also makes a second application +/// of an already-applied patch fail instead of deleting its replacement. fn verify_removals( index: usize, total: usize, @@ -301,17 +301,18 @@ fn verify_removals( continue; } if line.kind == super::parse::HunkLineKind::Remove { - let (line_number, similarity) = match by_old.get(&old_index) { - Some(&file_index) => ( - file_index + 1, - score::similarity( - &old_tokens[old_index], - &score::tokenize(original[file_index]), - ), - ), - None => (anchor.start + 1, 0.0), + let (line_number, similarity, same_code) = match by_old.get(&old_index) { + Some(&file_index) => { + let file_tokens = score::tokenize(original[file_index]); + ( + file_index + 1, + score::similarity(&old_tokens[old_index], &file_tokens), + score::code_equal(&old_tokens[old_index], &file_tokens), + ) + } + None => (anchor.start + 1, 0.0, false), }; - if similarity < MATCH_FLOOR { + if !same_code { return Err(PatchError::RemovalMissing { hunk: index + 1, total, @@ -554,50 +555,58 @@ mod tests { #[test] fn equal_similarity_resolves_to_the_nearer_block() { - // The same block twice. The hunk's removal line differs slightly, so - // neither copy is byte-exact and the two alignments score the same; - // the copy beside the declared line must win, every run. - let original = "fn b() {\n one();\n}\n\nfn a() {\n one();\n}\n"; - let patch = "@@ -5,2 +5,2 @@\n fn a() {\n- one(1);\n+ two();\n"; + // Two identical blocks, each with its own comment; the patch's + // comment is a paraphrase, so neither block is byte-exact and both + // score the same. The copy beside the declared line must win. + let original = "\ +// alpha +fn a() { + one(); +} +// beta +fn a() { + one(); +} +"; + let patch = "@@ -6,3 +6,3 @@\n // gamma\n fn a() {\n- one();\n+ two();\n"; let anchors = anchor(original, patch).unwrap(); assert!(!anchors[0].exact); + // The block starts at its comment line, four lines below the first copy. assert_eq!(anchors[0].start, 4); } #[test] fn two_equidistant_blocks_with_equal_scores_are_ambiguous() { - // Blocks at 0-1 and 4-5, declared line exactly between them. - let original = "fn a() {\n one();\n\n\nfn a() {\n one();\n}\n"; - let patch = "@@ -3,2 +3,2 @@\n fn a() {\n- one(1);\n+ two();\n"; + // Blocks at 0-2 and 4-6, declared line exactly between them. + let original = "\ +// alpha +fn a() { + one(); +} +// beta +fn a() { + one(); +} +"; + let patch = "@@ -3,3 +3,3 @@\n // gamma\n fn a() {\n- one();\n+ two();\n"; let err = anchor(original, patch).unwrap_err(); assert!(matches!(err, PatchError::Ambiguous { .. }), "{err}"); } - #[test] - fn out_of_order_hunks_are_rejected() { - let original = "a\nb\nc\nd\n"; - let patch = "@@ -4,1 +4,1 @@\n-d\n+D\n@@ -2,1 +2,1 @@\n-b\n+B\n"; - let err = anchor(original, patch).unwrap_err(); - assert!(matches!(err, PatchError::OutOfOrder { .. }), "{err}"); - } - - #[test] - fn the_ambiguity_margin_boundary() { - // A gap exactly equal to the configured margin is enough. - assert!(!within_margin(0.05, 0.05)); - // A hair less is not (0.90 - 0.850_001 = 0.049_999). - assert!(within_margin(0.90 - 0.850_001, 0.05)); - // Identical scores are always inside the margin. - assert!(within_margin(0.0, 0.05)); - // Margin 0.0 switches the rule off (callers can opt into best-score-wins). - assert!(!within_margin(0.05, 0.0)); - } - #[test] fn a_zero_margin_turns_the_ambiguity_refusal_off() { // Same equidistant pair as above: margin 0 means "always take the best". - let original = "fn a() {\n one();\n\n\nfn a() {\n one();\n}\n"; - let patch = "@@ -3,2 +3,2 @@\n fn a() {\n- one(1);\n+ two();\n"; + let original = "\ +// alpha +fn a() { + one(); +} +// beta +fn a() { + one(); +} +"; + let patch = "@@ -3,3 +3,3 @@\n // gamma\n fn a() {\n- one();\n+ two();\n"; let lines: Vec<&str> = original.split('\n').collect(); let hunks = parse(patch).unwrap(); let opts = ApplyOptions { @@ -609,10 +618,19 @@ mod tests { #[test] fn a_wider_margin_makes_a_close_call_ambiguous() { - // Two near-identical blocks whose scores differ by ~0.10. The default - // margin (0.05) can tell them apart; a wider one refuses to choose. - let original = "fn b() {\n one();\n}\n\nfn a() {\n one();\n}\n"; - let patch = "@@ -5,2 +5,2 @@\n fn a() {\n- one(1);\n+ two();\n"; + // Two similar blocks whose scores differ by ~0.07: the default margin + // (0.05) can tell them apart, a wider one refuses to choose. + let original = "\ +// alpha +fn b() { + one(); +} +// beta +fn a() { + one(); +} +"; + let patch = "@@ -6,3 +6,3 @@\n // gamma\n fn a() {\n- one();\n+ two();\n"; let lines: Vec<&str> = original.split('\n').collect(); let hunks = parse(patch).unwrap(); let anchors = anchor_all(&lines, &hunks, &ApplyOptions::default()).unwrap(); diff --git a/src/patch/mod.rs b/src/patch/mod.rs index cb481ae..4171581 100644 --- a/src/patch/mod.rs +++ b/src/patch/mod.rs @@ -174,7 +174,7 @@ pub enum PatchError { /// instead is exactly the silent corruption this engine exists to /// prevent. #[error( - "hunk {hunk}/{total}: `{expected}` is not in the file (best match {similarity:.2} at line {line}); refusing to delete a line the patch never saw" + "hunk {hunk}/{total}: the line to remove differs from the file (closest {similarity:.2} at line {line}): `{expected}` — only comments and whitespace may differ on a deleted line" )] RemovalMissing { hunk: usize, @@ -433,8 +433,10 @@ mod tests { #[test] fn a_fuzzy_anchor_is_reported_and_warned() { - let original = "// top\nfn main() {\n let a = 1;\n}\n"; - let patch = "@@ -9,2 +9,2 @@\n fn main() {\n- let a = 2;\n+ let a = 3;\n"; + // Declared at line 9, actually at line 3; the deleted line is really + // there, only a comment above it is new. + let original = "fn main() {\n // added later\n let a = 1;\n}\n"; + let patch = "@@ -9,2 +9,2 @@\n fn main() {\n- let a = 1;\n+ let a = 3;\n"; let out = render(original, patch).unwrap(); assert!(!out.report.hunks[0].exact); assert!( diff --git a/src/patch/parse.rs b/src/patch/parse.rs index dd3d853..ac65992 100644 --- a/src/patch/parse.rs +++ b/src/patch/parse.rs @@ -166,7 +166,14 @@ pub(crate) fn parse(text: &str) -> Result, ParseError> { // boundary — a body line pair (`-­- x` / `+++ y` for a `--` comment) // is never followed by a hunk header without that header belonging // to a new file. - if line.starts_with("--- ") + // ...but only once the current hunk has taken everything its header + // declared: `diff -U0` of a one-file change can end a hunk whose + // whole body is `--- old note` / `+++ new note`, with the file's next + // `@@` right after it. + let hunk_complete = + hunk.old_count() == hunk.declared_old && hunk.new_count() == hunk.declared_new; + if hunk_complete + && line.starts_with("--- ") && raw .get(index + 1) .is_some_and(|next| next.starts_with("+++ ")) @@ -365,9 +372,32 @@ index 1111111..2222222 100644 } #[test] - fn a_marker_followed_by_another_line_is_not_the_eof_marker() { - let hunks = parse("@@ -1,2 +1,2 @@\n-a\n+b\n c\n\\ No newline at end of file\n").unwrap(); - assert!(hunks[0].new_no_newline); + fn a_marker_followed_by_another_line_stops_claiming_the_result_side() { + let hunks = parse("@@ -1,2 +1,2 @@\n-a\n+b\n\\ No newline at end of file\n c\n").unwrap(); + // The marker described `+b`; the hunk does not end there, so neither + // side's tail has a claim. + assert!(!hunks[0].new_no_newline); + assert!(!hunks[0].old_no_newline); + } + + #[test] + fn a_diff_u_zero_hunk_that_looks_like_a_header_is_still_body() { + // One file: line 1 is `-- old note` → `++ new note`, line 3 changes. + // The first hunk's whole body is the `---`/`+++`-looking pair. + let patch = "\ +--- notes.txt ++++ notes.txt +@@ -1 +1 @@ +--- old note ++++ new note +@@ -3 +3 @@ +-old value ++new value +"; + let hunks = parse(patch).unwrap(); + assert_eq!(hunks.len(), 2); + assert_eq!(hunks[0].lines[0].text, "-- old note"); + assert_eq!(hunks[0].lines[1].text, "++ new note"); } #[test] diff --git a/src/patch/render.rs b/src/patch/render.rs index bbdd39b..6397b57 100644 --- a/src/patch/render.rs +++ b/src/patch/render.rs @@ -31,6 +31,7 @@ use std::collections::BTreeMap; use super::anchor::Anchor; use super::parse::{Hunk, HunkLineKind}; +use super::score; /// One line of the original file: content without the ending, and the /// ending exactly as it was (`"\n"`, `"\r\n"`, or `""` for a final line @@ -81,6 +82,7 @@ pub(crate) fn render(original: &[FileLine<'_>], hunks: &[Hunk], anchors: &[Ancho for (hunk, anchor) in hunks.iter().zip(anchors) { let shift = indent_shift(hunk, anchor, original); + let mut quote: Option<&'static str> = None; while cursor < anchor.start && cursor < original.len() { out.push((Cow::Borrowed(original[cursor].0), original[cursor].1)); last_is_added = false; @@ -125,7 +127,13 @@ pub(crate) fn render(original: &[FileLine<'_>], hunks: &[Hunk], anchors: &[Ancho old_index += 1; } HunkLineKind::Add => { - out.push((rebase(&line.text, shift.as_ref()), newline)); + let text = if quote.is_some() { + Cow::Borrowed(line.text.as_str()) + } else { + rebase(&line.text, shift.as_ref()) + }; + quote = multiline_quote(quote, &line.text); + out.push((text, newline)); last_is_added = true; } } @@ -168,26 +176,76 @@ pub(crate) fn render(original: &[FileLine<'_>], hunks: &[Hunk], anchors: &[Ancho /// `(patch prefix, file prefix)` when the hunk's added lines have to move /// to a different indentation level to stay inside their context. +/// +/// Only *code* lines may decide the shift. A comment that someone moved +/// into an `if` says nothing about where the code block lives, and blank +/// lines say even less. If two code lines imply different shifts, the +/// answer is "no uniform shift", so nothing is rewritten. fn indent_shift( hunk: &Hunk, anchor: &Anchor, original: &[FileLine<'_>], ) -> Option<(String, String)> { let old: Vec<&str> = hunk.old_lines().collect(); + let mut decided: Option<(String, String)> = None; for &(old_index, file_index) in &anchor.pairs { - let patch_prefix = leading_whitespace(old[old_index]); + let patch_line = old[old_index]; + let tokens = score::tokenize(patch_line); + if tokens.comment_only() || patch_line.trim().is_empty() { + continue; + } + let patch_prefix = leading_whitespace(patch_line); if patch_prefix.is_empty() { + // A top-level line: it neither moved nor proves anything. continue; } let file_prefix = leading_whitespace(original[file_index].0); - if patch_prefix != file_prefix { - return Some((patch_prefix.to_string(), file_prefix.to_string())); + if patch_prefix == file_prefix { + // This code line is exactly where it was, so the block did not + // move and there is nothing to rebase. + return None; + } + let shift = (patch_prefix.to_string(), file_prefix.to_string()); + match &decided { + Some(existing) if existing != &shift => return None, + Some(_) => {} + None => decided = Some(shift), + } + } + decided +} + +/// Track an open triple-quoted Python string while writing added lines: the +/// leading whitespace inside a literal is data, not code indentation, and +/// must not be rebased. Rough by design — it only has to be conservative +/// (skip rebasing) around multi-line strings. +fn multiline_quote(state: Option<&'static str>, line: &str) -> Option<&'static str> { + const DELIMITERS: [&str; 2] = ["\"\"\"", "'''"]; + match state { + Some(delimiter) => { + if line.matches(delimiter).count() % 2 == 1 { + None + } else { + Some(delimiter) + } + } + None => { + let mut first: Option<(usize, &'static str)> = None; + for delimiter in DELIMITERS { + if let Some(at) = line.find(delimiter) + && first.is_none_or(|(earliest, _)| at < earliest) + { + first = Some((at, delimiter)); + } + } + let (_, delimiter) = first?; + if line.matches(delimiter).count() % 2 == 1 { + Some(delimiter) + } else { + None + } } - // The first indented line decides; a later, deeper line is nested - // *within* the block, not a shift of it. - return None; } - None } fn leading_whitespace(line: &str) -> &str { diff --git a/src/patch/score.rs b/src/patch/score.rs index a5dd0f2..40e3d8f 100644 --- a/src/patch/score.rs +++ b/src/patch/score.rs @@ -144,6 +144,14 @@ fn pair_hash(first: u64, second: u64) -> u64 { hasher.finish() } +/// Do two lines carry the same code? Comments and whitespace are already +/// excluded from the token multiset, so this is the bar a *removal* has to +/// clear: the line the patch deletes must still be that line, even if its +/// comment was reworded or its indentation changed. +pub(crate) fn code_equal(a: &LineTokens, b: &LineTokens) -> bool { + a.code == b.code +} + /// Token-level Dice coefficient between two lines, 0.0–1.0. pub(crate) fn similarity(a: &LineTokens, b: &LineTokens) -> f64 { if a.blank || b.blank { diff --git a/tests/patch_engine.rs b/tests/patch_engine.rs index 2c85f3d..24aa3f4 100644 --- a/tests/patch_engine.rs +++ b/tests/patch_engine.rs @@ -418,6 +418,45 @@ fn a_python_statement_that_moved_into_a_block_keeps_the_blocks_indent() { std::fs::remove_dir_all(&dir).unwrap(); } +#[test] +fn a_moved_comment_does_not_rebase_the_code_beside_it() { + // The comment moved into the `if`; the call did not. Rebasing the + // replacement on the comment's indentation would make it conditional. + let dir = temp_dir("python-comment-shift"); + let body = "def save(enabled):\n if enabled:\n # save the result\n store()\n"; + let path = write(&dir, "tool.py", body); + let patch = "@@ -1,2 +1,2 @@\n # save the result\n- store()\n+ persist()\n"; + let report = apply(&path, patch).unwrap(); + assert_eq!(report.syntax, SyntaxCheck::Clean("python")); + assert_eq!( + contents(&path), + "def save(enabled):\n if enabled:\n # save the result\n persist()\n" + ); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn a_multiline_string_value_is_not_reindented() { + // The call moves into the `if`; the string's own line breaks are data. + let dir = temp_dir("python-multiline"); + let body = "def save(enabled):\n if enabled:\n store()\n"; + let path = write(&dir, "tool.py", body); + let patch = "\ +@@ -1,2 +1,2 @@ + def save(enabled): +- store() ++ store(\"\"\"first ++ second\"\"\") +"; + let report = apply(&path, patch).unwrap(); + assert_eq!(report.syntax, SyntaxCheck::Clean("python")); + assert_eq!( + contents(&path), + "def save(enabled):\n if enabled:\n store(\"\"\"first\n second\"\"\")\n" + ); + std::fs::remove_dir_all(&dir).unwrap(); +} + #[test] fn a_plain_diff_u_multi_file_patch_is_refused() { let dir = temp_dir("multi-file-u"); From 24e77d75a2a27d9110da4fcafef24372ebbb0c2a Mon Sep 17 00:00:00 2001 From: developjik <67889389+developjik@users.noreply.github.com> Date: Mon, 30 Nov 2026 15:04:11 +0900 Subject: [PATCH 3/5] =?UTF-8?q?fix(patch):=20third=20review=20pass=20?= =?UTF-8?q?=E2=80=94=20boundary=20after=20body,=20delta=20shifts,=20quote?= =?UTF-8?q?=20state?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - A `---`/`+++`/`@@` triple after the hunk body has started is a file boundary even when the hunk header miscounted its lines. Reading a header pair as body is still allowed while the body is empty (`diff -U0` of a one-file comment swap), but once body lines exist the boundary wins: refusing a strange patch beats mixing two files. Also drops the per-line recount that made parsing quadratic on huge insert hunks. - Indentation rebasing compares the *move* (+4, -4), not the absolute prefix, so a block header and its nested body that moved by the same width still rebase — and tab/space mixing or disagreeing moves disable it. - The triple-quote tracker walks every line the renderer sees (kept, removed, added) and ignores comment-only lines, so a `"""` in a comment does not switch rebasing off and a closing quote on a kept line ends it. Tests: nested-shift and comment-quote cases end to end; miscounted multi-file parse case; 67 unit + 31 end-to-end. Refs #31 Signed-off-by: 정인권 --- src/patch/parse.rs | 36 ++++++++++++---- src/patch/render.rs | 95 ++++++++++++++++++++++++++++++++----------- tests/patch_engine.rs | 45 ++++++++++++++++++++ 3 files changed, 145 insertions(+), 31 deletions(-) diff --git a/src/patch/parse.rs b/src/patch/parse.rs index ac65992..1c9b35d 100644 --- a/src/patch/parse.rs +++ b/src/patch/parse.rs @@ -166,13 +166,15 @@ pub(crate) fn parse(text: &str) -> Result, ParseError> { // boundary — a body line pair (`-­- x` / `+++ y` for a `--` comment) // is never followed by a hunk header without that header belonging // to a new file. - // ...but only once the current hunk has taken everything its header - // declared: `diff -U0` of a one-file change can end a hunk whose - // whole body is `--- old note` / `+++ new note`, with the file's next - // `@@` right after it. - let hunk_complete = - hunk.old_count() == hunk.declared_old && hunk.new_count() == hunk.declared_new; - if hunk_complete + // ...but only once the hunk body has started: `diff -U0` of a + // one-file change can end a hunk whose whole body is + // `--- old note` / `+++ new note`, with the file's next `@@` right + // after it. Reading a header pair as body cannot corrupt a file + // once the hunk has begun, so an early pair is always body; a pair + // after body lines is a boundary even when the hunk header lied + // about its line count — refusing a strange patch is better than + // mixing two files. + if !hunk.lines.is_empty() && line.starts_with("--- ") && raw .get(index + 1) @@ -424,6 +426,26 @@ index 1111111..2222222 100644 assert!(matches!(err, ParseError::MultiFile { .. }), "{err}"); } + #[test] + fn a_second_file_is_detected_even_when_the_first_hunk_miscounted() { + // The first hunk declares five lines and carries one; the second + // file's header must still be a boundary rather than body. + let patch = "\ +--- a/one.txt ++++ b/one.txt +@@ -1,5 +1,5 @@ +-a ++A +--- a/two.txt ++++ b/two.txt +@@ -1,1 +1,1 @@ +-b ++B +"; + let err = parse(patch).unwrap_err(); + assert!(matches!(err, ParseError::MultiFile { .. }), "{err}"); + } + #[test] fn a_body_that_looks_like_a_file_header_is_still_body() { // Removing a `--` comment and adding another: the two lines look diff --git a/src/patch/render.rs b/src/patch/render.rs index 6397b57..8083bfd 100644 --- a/src/patch/render.rs +++ b/src/patch/render.rs @@ -96,6 +96,7 @@ pub(crate) fn render(original: &[FileLine<'_>], hunks: &[Hunk], anchors: &[Ancho for line in &hunk.lines { match line.kind { HunkLineKind::Context => { + quote = track_quote(quote, &line.text); if let Some(&file_index) = mapped.get(&old_index) { while cursor < file_index { out.push((Cow::Borrowed(original[cursor].0), original[cursor].1)); @@ -115,6 +116,7 @@ pub(crate) fn render(original: &[FileLine<'_>], hunks: &[Hunk], anchors: &[Ancho old_index += 1; } HunkLineKind::Remove => { + quote = track_quote(quote, &line.text); if let Some(&file_index) = mapped.get(&old_index) && file_index >= cursor { @@ -132,7 +134,7 @@ pub(crate) fn render(original: &[FileLine<'_>], hunks: &[Hunk], anchors: &[Ancho } else { rebase(&line.text, shift.as_ref()) }; - quote = multiline_quote(quote, &line.text); + quote = track_quote(quote, &line.text); out.push((text, newline)); last_is_added = true; } @@ -174,20 +176,23 @@ pub(crate) fn render(original: &[FileLine<'_>], hunks: &[Hunk], anchors: &[Ancho text } -/// `(patch prefix, file prefix)` when the hunk's added lines have to move -/// to a different indentation level to stay inside their context. +/// How far (in characters of one whitespace character) added lines have to +/// move to stay inside their context. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct Shift { + pad: char, + delta: isize, +} + +/// The indentation move for the hunk's added lines, or `None`. /// /// Only *code* lines may decide the shift. A comment that someone moved /// into an `if` says nothing about where the code block lives, and blank /// lines say even less. If two code lines imply different shifts, the /// answer is "no uniform shift", so nothing is rewritten. -fn indent_shift( - hunk: &Hunk, - anchor: &Anchor, - original: &[FileLine<'_>], -) -> Option<(String, String)> { +fn indent_shift(hunk: &Hunk, anchor: &Anchor, original: &[FileLine<'_>]) -> Option { let old: Vec<&str> = hunk.old_lines().collect(); - let mut decided: Option<(String, String)> = None; + let mut decided: Option = None; for &(old_index, file_index) in &anchor.pairs { let patch_line = old[old_index]; let tokens = score::tokenize(patch_line); @@ -205,9 +210,21 @@ fn indent_shift( // move and there is nothing to rebase. return None; } - let shift = (patch_prefix.to_string(), file_prefix.to_string()); - match &decided { - Some(existing) if existing != &shift => return None, + // Nested lines sit at different depths but move by the same number + // of characters; compare the move, not the absolute prefixes. + let pad = patch_prefix.chars().next()?; + if !patch_prefix.chars().all(|c| c == pad) + || !file_prefix.chars().all(|c| c == pad) + || patch_prefix.len() == file_prefix.len() + { + return None; + } + let shift = Shift { + pad, + delta: file_prefix.len() as isize - patch_prefix.len() as isize, + }; + match decided { + Some(existing) if existing != shift => return None, Some(_) => {} None => decided = Some(shift), } @@ -215,9 +232,9 @@ fn indent_shift( decided } -/// Track an open triple-quoted Python string while writing added lines: the -/// leading whitespace inside a literal is data, not code indentation, and -/// must not be rebased. Rough by design — it only has to be conservative +/// Track an open triple-quoted Python string across the lines the renderer +/// walks (kept context, removed, added): the leading whitespace inside a +/// literal is data, not code indentation, and must not be rebased. Rough by design — it only has to be conservative /// (skip rebasing) around multi-line strings. fn multiline_quote(state: Option<&'static str>, line: &str) -> Option<&'static str> { const DELIMITERS: [&str; 2] = ["\"\"\"", "'''"]; @@ -252,14 +269,30 @@ fn leading_whitespace(line: &str) -> &str { &line[..line.len() - line.trim_start_matches([' ', '\t']).len()] } -fn rebase<'a>(line: &'a str, shift: Option<&(String, String)>) -> Cow<'a, str> { - let Some((from, to)) = shift else { +fn rebase<'a>(line: &'a str, shift: Option<&Shift>) -> Cow<'a, str> { + let Some(shift) = shift else { return Cow::Borrowed(line); }; - match line.strip_prefix(from.as_str()) { - Some(rest) => Cow::Owned(format!("{to}{rest}")), - None => Cow::Borrowed(line), + let indent = leading_whitespace(line); + if indent.is_empty() || !indent.chars().all(|c| c == shift.pad) { + return Cow::Borrowed(line); + } + if shift.delta >= 0 { + let extra: String = std::iter::repeat_n(shift.pad, shift.delta as usize).collect(); + Cow::Owned(format!("{extra}{line}")) + } else { + let strip = ((-shift.delta) as usize).min(indent.len()); + Cow::Owned(line[strip..].to_string()) + } +} + +/// Update the multi-line-string state, ignoring comment-only lines (a `"""` +/// inside a comment is prose, not a delimiter). +fn track_quote(state: Option<&'static str>, line: &str) -> Option<&'static str> { + if score::tokenize(line).comment_only() { + return state; } + multiline_quote(state, line) } #[cfg(test)] @@ -293,10 +326,24 @@ mod tests { } #[test] - fn rebase_rewrites_only_a_matching_prefix() { - let shift = Some((" ".to_string(), " ".to_string())); - assert_eq!(rebase(" save();", shift.as_ref()), " save();"); - assert_eq!(rebase("save();", shift.as_ref()), "save();"); + fn rebase_moves_by_the_delta_not_to_a_fixed_prefix() { + let deeper = Some(Shift { pad: ' ', delta: 4 }); + assert_eq!(rebase(" save();", deeper.as_ref()), " save();"); + // Nested lines move by the same delta, not to the same depth. + assert_eq!( + rebase(" body();", deeper.as_ref()), + " body();" + ); + // A top-level line is not part of the block. + assert_eq!(rebase("save();", deeper.as_ref()), "save();"); + // Tabs are a different indentation style; leave them alone. + assert_eq!(rebase("\tsave();", deeper.as_ref()), "\tsave();"); assert_eq!(rebase(" save();", None), " save();"); + + let shallower = Some(Shift { + pad: ' ', + delta: -4, + }); + assert_eq!(rebase(" save();", shallower.as_ref()), " save();"); } } diff --git a/tests/patch_engine.rs b/tests/patch_engine.rs index 24aa3f4..07e703d 100644 --- a/tests/patch_engine.rs +++ b/tests/patch_engine.rs @@ -435,6 +435,51 @@ fn a_moved_comment_does_not_rebase_the_code_beside_it() { std::fs::remove_dir_all(&dir).unwrap(); } +#[test] +fn a_nested_block_that_moved_as_a_whole_still_rebases() { + // The `if` moved one level deeper and its body moved with it: both + // patch lines shift by the same four columns, at different depths. + let dir = temp_dir("python-nested-shift"); + let body = "def save(enabled):\n if enabled:\n if other:\n store()\n"; + let path = write(&dir, "tool.py", body); + let patch = "\ +@@ -1,3 +1,3 @@ + def save(enabled): + if other: +- store() ++ persist() +"; + let report = apply(&path, patch).unwrap(); + assert_eq!(report.syntax, SyntaxCheck::Clean("python")); + assert_eq!( + contents(&path), + "def save(enabled):\n if enabled:\n if other:\n persist()\n" + ); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn triple_quotes_in_a_comment_do_not_switch_off_rebasing() { + let dir = temp_dir("python-quote-comment"); + let body = + "def save(enabled):\n if enabled:\n # \"\"\"save the result\n store()\n"; + let path = write(&dir, "tool.py", body); + let patch = "\ +@@ -1,3 +1,3 @@ + def save(enabled): + # \"\"\"save the result +- store() ++ persist() +"; + let report = apply(&path, patch).unwrap(); + assert_eq!(report.syntax, SyntaxCheck::Clean("python")); + assert_eq!( + contents(&path), + "def save(enabled):\n if enabled:\n # \"\"\"save the result\n persist()\n" + ); + std::fs::remove_dir_all(&dir).unwrap(); +} + #[test] fn a_multiline_string_value_is_not_reindented() { // The call moves into the `if`; the string's own line breaks are data. From e9501f05206de493fea286f279ec7c108a63dc49 Mon Sep 17 00:00:00 2001 From: developjik <67889389+developjik@users.noreply.github.com> Date: Mon, 30 Nov 2026 15:21:02 +0900 Subject: [PATCH 4/5] =?UTF-8?q?fix(patch):=20fourth=20review=20pass=20?= =?UTF-8?q?=E2=80=94=20shift=20scope,=20prefix=20growth,=20quote=20state?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Only added lines at least as deep as the matched block take the shift: a statement the patch adds above or below a block that moved stays where the patch put it. - The prefix comparison accepts a prefix that merely grew or shrank by a run of one whitespace character, and the pad is applied after the line's own indent, so a tab-indented block that gained four spaces still moves. - The triple-quote state tracks only lines that reach the output (kept context and added lines) and looks for delimiters inside an open literal regardless of `#`; a `#` comment's quotes are prose only outside one. Refs #31 Signed-off-by: 정인권 --- src/patch/render.rs | 92 +++++++++++++++++++++++++++++++-------------- 1 file changed, 64 insertions(+), 28 deletions(-) diff --git a/src/patch/render.rs b/src/patch/render.rs index 8083bfd..ea5759a 100644 --- a/src/patch/render.rs +++ b/src/patch/render.rs @@ -116,7 +116,6 @@ pub(crate) fn render(original: &[FileLine<'_>], hunks: &[Hunk], anchors: &[Ancho old_index += 1; } HunkLineKind::Remove => { - quote = track_quote(quote, &line.text); if let Some(&file_index) = mapped.get(&old_index) && file_index >= cursor { @@ -182,6 +181,9 @@ pub(crate) fn render(original: &[FileLine<'_>], hunks: &[Hunk], anchors: &[Ancho struct Shift { pad: char, delta: isize, + /// Deepest indentation, in the patch, that belongs to the moved block. + /// Added lines shallower than this are outside it and stay put. + min_indent: usize, } /// The indentation move for the hunk's added lines, or `None`. @@ -192,7 +194,8 @@ struct Shift { /// answer is "no uniform shift", so nothing is rewritten. fn indent_shift(hunk: &Hunk, anchor: &Anchor, original: &[FileLine<'_>]) -> Option { let old: Vec<&str> = hunk.old_lines().collect(); - let mut decided: Option = None; + let mut decided: Option<(char, isize)> = None; + let mut min_indent = usize::MAX; for &(old_index, file_index) in &anchor.pairs { let patch_line = old[old_index]; let tokens = score::tokenize(patch_line); @@ -211,25 +214,35 @@ fn indent_shift(hunk: &Hunk, anchor: &Anchor, original: &[FileLine<'_>]) -> Opti return None; } // Nested lines sit at different depths but move by the same number - // of characters; compare the move, not the absolute prefixes. - let pad = patch_prefix.chars().next()?; - if !patch_prefix.chars().all(|c| c == pad) - || !file_prefix.chars().all(|c| c == pad) - || patch_prefix.len() == file_prefix.len() - { + // of characters; compare the move, not the absolute prefixes. The + // prefixes only have to grow or shrink by a run of one whitespace + // character, so a tab-indented block that gained four spaces still + // counts. + let (short, long) = if file_prefix.starts_with(patch_prefix) { + (patch_prefix, file_prefix) + } else if patch_prefix.starts_with(file_prefix) { + (file_prefix, patch_prefix) + } else { return None; - } - let shift = Shift { - pad, - delta: file_prefix.len() as isize - patch_prefix.len() as isize, }; + let added = long.get(short.len()..)?; + let pad = added.chars().next()?; + if !matches!(pad, ' ' | '\t') || !added.chars().all(|c| c == pad) { + return None; + } + let delta = file_prefix.len() as isize - patch_prefix.len() as isize; + min_indent = min_indent.min(patch_prefix.len()); match decided { - Some(existing) if existing != shift => return None, + Some(existing) if existing != (pad, delta) => return None, Some(_) => {} - None => decided = Some(shift), + None => decided = Some((pad, delta)), } } - decided + decided.map(|(pad, delta)| Shift { + pad, + delta, + min_indent, + }) } /// Track an open triple-quoted Python string across the lines the renderer @@ -274,25 +287,40 @@ fn rebase<'a>(line: &'a str, shift: Option<&Shift>) -> Cow<'a, str> { return Cow::Borrowed(line); }; let indent = leading_whitespace(line); - if indent.is_empty() || !indent.chars().all(|c| c == shift.pad) { + if indent.len() < shift.min_indent { + // Outside the block that moved: a statement the patch adds above or + // below it stays where the patch put it. return Cow::Borrowed(line); } if shift.delta >= 0 { + // Extend the line's own prefix, so mixed tab/space styles keep their + // shape ("\t " gains four spaces rather than becoming " \t "). let extra: String = std::iter::repeat_n(shift.pad, shift.delta as usize).collect(); - Cow::Owned(format!("{extra}{line}")) + Cow::Owned(format!("{indent}{extra}{}", &line[indent.len()..])) } else { - let strip = ((-shift.delta) as usize).min(indent.len()); - Cow::Owned(line[strip..].to_string()) + let trailing = indent.len() - indent.trim_end_matches(shift.pad).len(); + let strip = ((-shift.delta) as usize).min(trailing); + let keep = indent.len() - strip; + Cow::Owned(format!("{}{}", &line[..keep], &line[indent.len()..])) } } -/// Update the multi-line-string state, ignoring comment-only lines (a `"""` -/// inside a comment is prose, not a delimiter). +/// Update the multi-line-string state. +/// +/// Inside a literal, `#` is data, so the delimiter is always looked for. +/// Outside one, a delimiter that only appears after the line's `#` is prose +/// in a comment, not a string. fn track_quote(state: Option<&'static str>, line: &str) -> Option<&'static str> { - if score::tokenize(line).comment_only() { - return state; + match state { + Some(_) => multiline_quote(state, line), + None => { + let code = match line.find('#') { + Some(hash) => &line[..hash], + None => line, + }; + multiline_quote(None, code) + } } - multiline_quote(state, line) } #[cfg(test)] @@ -327,22 +355,30 @@ mod tests { #[test] fn rebase_moves_by_the_delta_not_to_a_fixed_prefix() { - let deeper = Some(Shift { pad: ' ', delta: 4 }); + let deeper = Some(Shift { + pad: ' ', + delta: 4, + min_indent: 4, + }); assert_eq!(rebase(" save();", deeper.as_ref()), " save();"); // Nested lines move by the same delta, not to the same depth. assert_eq!( rebase(" body();", deeper.as_ref()), " body();" ); - // A top-level line is not part of the block. + // A line added outside the moved block stays where the patch put it. assert_eq!(rebase("save();", deeper.as_ref()), "save();"); - // Tabs are a different indentation style; leave them alone. - assert_eq!(rebase("\tsave();", deeper.as_ref()), "\tsave();"); + // A mixed tab/space prefix keeps its shape and gains the pad. + assert_eq!( + rebase("\t save();", deeper.as_ref()), + "\t save();" + ); assert_eq!(rebase(" save();", None), " save();"); let shallower = Some(Shift { pad: ' ', delta: -4, + min_indent: 8, }); assert_eq!(rebase(" save();", shallower.as_ref()), " save();"); } From 0550f85aa2d602a3ee202ed7fbc4075d32bf1e54 Mon Sep 17 00:00:00 2001 From: developjik <67889389+developjik@users.noreply.github.com> Date: Mon, 30 Nov 2026 15:34:05 +0900 Subject: [PATCH 5/5] fix(patch): string-aware comment start, backtick literals MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The triple-quote tracker cut the line at its first `#`, which is data inside a string; the comment start now comes from the tokenizer, so a `"""` after a `#` inside a literal is still seen as the literal's close. - Backticks are tracked as multi-line delimiters too: a JavaScript/TypeScript template literal's interior must not be reindented either. Refs #31 Signed-off-by: 정인권 --- src/patch/render.rs | 10 +++++++--- src/patch/score.rs | 16 ++++++++++++++++ 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/src/patch/render.rs b/src/patch/render.rs index ea5759a..a0f591e 100644 --- a/src/patch/render.rs +++ b/src/patch/render.rs @@ -250,7 +250,9 @@ fn indent_shift(hunk: &Hunk, anchor: &Anchor, original: &[FileLine<'_>]) -> Opti /// literal is data, not code indentation, and must not be rebased. Rough by design — it only has to be conservative /// (skip rebasing) around multi-line strings. fn multiline_quote(state: Option<&'static str>, line: &str) -> Option<&'static str> { - const DELIMITERS: [&str; 2] = ["\"\"\"", "'''"]; + // Multi-line delimiters: Python's two triple quotes, and the backtick + // that spans lines in JavaScript/TypeScript templates. + const DELIMITERS: [&str; 3] = ["\"\"\"", "'''", "`"]; match state { Some(delimiter) => { if line.matches(delimiter).count() % 2 == 1 { @@ -314,8 +316,10 @@ fn track_quote(state: Option<&'static str>, line: &str) -> Option<&'static str> match state { Some(_) => multiline_quote(state, line), None => { - let code = match line.find('#') { - Some(hash) => &line[..hash], + // The tokenizer knows where the comment starts without being + // fooled by a `#` inside a string literal. + let code = match score::tokenize(line).comment_at { + Some(at) => &line[..at], None => line, }; multiline_quote(None, code) diff --git a/src/patch/score.rs b/src/patch/score.rs index 40e3d8f..5a34ede 100644 --- a/src/patch/score.rs +++ b/src/patch/score.rs @@ -42,6 +42,9 @@ pub(crate) const COMMENT_DRIFT_SIM: f64 = 0.9; /// A line reduced to comparable tokens. #[derive(Debug, Clone, PartialEq)] pub(crate) struct LineTokens { + /// Byte index where the line's comment starts, when it has one. String + /// aware: a `#` or `//` inside a literal is data. + pub(crate) comment_at: Option, /// Sorted token hashes of everything outside comments. Sorted so a /// multiset intersection is a linear merge, and hashed so a token /// comparison is an integer compare. @@ -71,6 +74,7 @@ const PAIR_WEIGHT: f64 = 0.4; pub(crate) fn tokenize(line: &str) -> LineTokens { let mut code: Vec = Vec::new(); let mut has_comment = false; + let mut comment_at: Option = None; let mut i = 0usize; let bytes = line.as_bytes(); @@ -81,10 +85,12 @@ pub(crate) fn tokenize(line: &str) -> LineTokens { c if c.is_whitespace() => i += c.len_utf8(), '/' if bytes.get(i + 1) == Some(&b'/') => { has_comment = true; + comment_at = Some(i); break; } '/' if bytes.get(i + 1) == Some(&b'*') => { has_comment = true; + comment_at = Some(i); match line[i + 2..].find("*/") { Some(end) => i = i + 2 + end + 2, None => break, @@ -97,6 +103,7 @@ pub(crate) fn tokenize(line: &str) -> LineTokens { && bytes[..i].last().is_none_or(|b| *b == b' ' || *b == b'\t') => { has_comment = true; + comment_at = Some(i); break; } quote @ ('"' | '\'' | '`') => { @@ -130,6 +137,7 @@ pub(crate) fn tokenize(line: &str) -> LineTokens { code.sort_unstable(); pairs.sort_unstable(); LineTokens { + comment_at, code, pairs, has_comment, @@ -302,6 +310,14 @@ mod tests { assert!(sim("x = {'a': 1}", "x = {'a': 2}") < 1.0); } + #[test] + fn a_hash_inside_a_string_is_not_a_comment() { + let line = "value = \"\"\"a#b\"\"\" + tail"; + let tokens = tokenize(line); + assert_eq!(tokens.comment_at, None); + assert!(!tokens.comment_only()); + } + #[test] fn korean_text_in_a_comment_is_ignored() { assert_eq!(sim("let x = 1; // 값 설정", "let x = 1;"), 1.0);