Subject: Re: [BUG] git apply misplaces patch when similar code fragments exist in the same file

From: Junio C Hamano <[email-masked]>
Date: Fri, 12 Sep 2025 09:48:48 -0700

Guo Tingsheng <[email-masked]> writes:

> 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>
>         `;
>     }

This hunk shown here may be a fabrication (it only has two
pre-context but three post-context lines, which is unusual unless
the shorter one is at the end of the file), but in any case, a patch
hunk above is applied to a location that has exactly these lines:

        return `
            <div class="layout-section">
                <button>Click Me</button>
            </div>
        `;
    }

that is the closest to line #10.

If there are more than one places in the target file that the
preimage (i.e. the context lines that are shown with " " at the
beginning, and the preimage lines that are shown with "-" at the
beginning) would match, the patch is ambiguous.

It is very much expected, depending on what other changes have
happened to the target file since they diverged to make the matching
places move from the original place, it would be applied to a
"wrong" place by chance, as the preimage does not uniquely identify
where the patch hunk should to be applied in such a situation.

You can generate a patch with wider context if you can _anticipate_
the issue (for example, you may _know_ that commit-1 already had
multiple lines that match the preimage in the hunk before running
"git diff" or "git format-patch") to give it a better chance to be
unambiguous, e.g. "git diff -U8".  But in general it is impossible
to guarantee that your preimage in the hunk will be and stay to be
unambiguous.  After all, the receiving end can make independent
changes that happen to match the preimage the patch is looking for,
no matter how wide the context you pick when you generate your
patch.

It might be a good starter project for aspiring Git developers to
teach "git apply" to notice this situation and warn about it.  The
tool cannot by definition to always pick the right place to patch,
but the tool should be able to recognise a situation where a patch
hunk is ambiguous and can apply to multiple places in the target and
let you know about it.