By default, git apply does not verify that the rest of the file (outside the hunk being applied) has remained unchanged. It only checks if the hunk itself can be applied cleanly to the target file. If the file has changed elsewhere, git apply will still apply the patch as long as the hunk context matches, which can sometimes lead to conflicts or unintended changes.
git apply Verify the Entire FileTo ensure that the file has not changed anywhere except in the hunk you want to apply, you have a few options:
git apply --checkbashgit apply --check your.patch
git apply --reject and Manually Inspectgit diff to Compare the Entire Filebashgit diff --exit-code expected_file current_file
0, the files are identical (except for the hunk you want to apply).bash#!/bin/bash # Compare the file (excluding the hunk) with a known good version if diff <(sed '/hunk pattern/d' current_file) <(sed '/hunk pattern/d' expected_file); then git apply your.patch else echo "File has changed elsewhere. Aborting." exit 1 fi
git apply --3way (if using Git 2.36+)If you want to ensure the file is exactly as expected (except for the hunk), the most reliable approach is to:
Would you like help writing a script for this workflow?