git apply Command: Apply Patches in CI
git apply takes a unified diff and applies it to files, without creating a commit.
When CI patches a file (for example to inject a generated change or apply a vendor fix), git apply applies a diff cleanly and can verify it first. Unlike am, it does not make commits.
Common flags
--check- verify the patch applies cleanly without changing anything--index- apply to both the working tree and the index (so it is staged)--3way- fall back to a three-way merge when context does not match-p<n>- strip n leading path components from filenames in the patch--reverse/-R- undo a previously applied patch--reject- apply what it can and write .rej files for the rest
Example
shell
# Verify, then apply and stage a patch in CI
git apply --check fix.patch
git apply --index fix.patchIn CI
Run git apply --check first so the job fails fast with a clear message if a patch is stale, rather than half-applying. Use --3way for resilience when the base has drifted, and --index when the change should be staged for an automated commit.
Key takeaways
- git apply --check validates a patch before touching any files, enabling fail-fast.
- --3way makes patches more robust to a drifted base via merge fallback.
- Use --index to stage the change for a follow-up automated commit.
Related guides
git diff Command: Detect Changes in CIgit diff shows changes between commits or the working tree. Reference for --name-only, --stat, and --exit-cod…
git cherry-pick Command in CIgit cherry-pick applies the changes of specific commits onto the current branch. Reference for -x, --no-commi…
git reset Command: Move HEAD in CIgit reset moves HEAD and optionally the index and working tree. Reference for --hard and --soft to roll back…
git show Command: Inspect Objects in CIgit show displays commits, tags, and file contents at a revision. Reference for printing a commit message or…