Skip to content
Latchkey

git apply --3way and --check: Apply Patches in CI

git apply <patch> applies a diff to the working tree; --check verifies it would apply cleanly without doing so, and --3way falls back to a three-way merge using blob info in the patch.

Automation that applies generated patches (dependency bumps, codemods) needs to apply cleanly or fail predictably. --check is the dry run, --3way recovers from minor context drift, and --index stages the result.

What it does

git apply takes a unified diff and applies it to the working tree (and the index with --index). --check reports whether it would apply without changing anything. --3way uses the blob SHAs recorded in a git-formatted patch to do a real three-way merge when straight application fails, leaving conflict markers instead of rejecting outright.

Common usage

Terminal
git apply --check changes.patch        # dry run
git apply changes.patch                # apply to working tree
git apply --index changes.patch        # apply and stage
git apply --3way changes.patch         # merge on context drift
# tolerate trailing-whitespace differences
git apply --whitespace=fix changes.patch

Options

FlagWhat it does
--checkVerify the patch applies without applying it
--3wayFall back to a three-way merge on failure
--indexApply to the index as well as the working tree
-p<n>Strip n leading path components from paths
-R / --reverseApply the patch in reverse
--whitespace=<action>Handle whitespace errors (fix, warn, error)

In CI

Run git apply --check first in a pipeline so a bad patch fails fast with a clear message instead of half-applying. --3way needs the patch to be a git-format diff (with index lines) and the base blobs present locally, so it can fail on a shallow clone that lacks them. For patches that should also become commits, prefer git am over apply.

Common errors in CI

"error: patch failed: <file>:<line>" with "error: <file>: patch does not apply" means the context drifted; try --3way or regenerate the patch. "error: while searching for: ..." shows the mismatching hunk. "fatal: unrecognized input" means the file is not a valid diff (wrong format or truncated). "warning: <n> lines add whitespace errors" comes from --whitespace settings.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →