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
# 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.
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 detachedKey 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.