[BUG] git apply misplaces patch when similar code fragments exist in the same file
From: Guo Tingsheng <hidden>
Date: 2025-09-12 13:33:22
Hello Git developers,
I would like to report a potential issue in Git's patch application mechanism, where a patch can be incorrectly applied to a similar but unintended code location if line numbers have shifted.
Environment:
- git version: 2.43.0
- OS: Ubuntu 24.04 LTS
Steps to reproduce:
1. Start from Commit_1, containing the following file:
function HeaderComponent() {
return `
<div class="layout-section">
<button>Click Me</button>
</div>
`;
}
function FooterComponent() {
return `
<div class="layout-section">
<button>Click Me</button>
</div>
`;
}
2. In another branch, Commit_2 introduces additional import statements before HeaderComponent, shifting its return statement further down (around line 10).
In Commit_2, the button text in HeaderComponent is modified as follows:
@@ -10,6 +10,6 @@
return `
<div class="layout-section">
- <button>Click Me</button>
+ <button>点击</button>
</div>
`;
}
3. Generate a patch from Commit_2.
4. Apply this patch on top of Commit_1 using:
git apply commit2.patch
Expected result:
- The patch should apply the change to HeaderComponent, modifying its button text.
Actual result:
- The patch is incorrectly applied to FooterComponent instead, producing:
function HeaderComponent() {
return `
<div class="layout-section">
<button>Click Me</button>
</div>
`;
}
function FooterComponent() {
return `
<div class="layout-section">
<button>点击</button>
</div>
`;
}
Additional information:
- This issue occurs when a file contains multiple similar code fragments, and the patch context fails to match due to line number shifts between commits.
- As a result, git apply may incorrectly match against the wrong occurrence of the repeated code, introducing unintended changes.
- This can potentially lead to subtle bugs in real-world projects (e.g., configuration files, HTML/JS components).
Thanks,
Cori