git apply: Usage, Options & Common CI Errors
git apply takes a diff/patch file and applies its changes - without creating commits.
apply is how you replay a diff in CI (e.g. a generated patch). Use --check first and --3way for resilience.
What it does
git apply reads a unified diff and modifies files in the working tree (and, with --index, the index) to match it. Unlike git am it does not create commits.
Common usage
git apply changes.patch
git apply --check changes.patch # dry run, validate only
git apply --3way changes.patch # fall back to 3-way merge
git apply --index changes.patch # also stage the result
git diff > out.patch && git apply out.patchOptions
| Flag | What it does |
|---|---|
| --check | Validate without applying |
| --3way / -3 | Use 3-way merge on conflict |
| --index | Apply to the index as well |
| -p<n> | Strip n leading path components |
| -R / --reverse | Apply the patch in reverse |
Common errors in CI
error: patch failed: <file>:<n> / "error: <file>: patch does not apply" - the target file drifted from what the patch expects. Try git apply --3way, fix the path level with -p, or regenerate the patch against the current base.
Using this in CI
CI checkouts are shallow and detached by default, which changes the answer this command gives you. Commands that read history, branch names, or tags need the checkout configured for it.
- uses: actions/checkout@v4
with:
fetch-depth: 0 # history, tags, and git describe all need this
- run: |
git rev-parse --is-shallow-repository # expect false
git rev-parse --abbrev-ref HEAD # prints HEAD when detached