From: Guo Tingsheng Date: Fri, 12 Sep 2025 13:33:20 GMT Subject: [BUG] git apply misplaces patch when similar code fragments exist in the same file Message-ID: 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 `
`; } function FooterComponent() { return `
`; } 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 `
- +
`; } 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 `
`; } function FooterComponent() { return `
`; } 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