GIT CHERRY-PICK & PATCH

GIT CHERRY-PICK & PATCH

Divya Srinivasan



What is Cherry-pick?

Cherry-pick lets you copy a single commit from one branch to another. It’s useful when you want just one (or a few) changes, not everything from another branch.

What is a Patch?

A patch is a file with changes from one or more commits. You can share a patch or apply it to another repository, even if it’s unrelated to your own.

How to Cherry-pick a Commit

Copy a single commit to your current branch:
git cherry-pick abc1234
This creates a new commit with the same changes.

Change the Commit Message

git cherry-pick abc1234 --edit

Apply Changes Without Committing

git cherry-pick abc1234 --no-commit
This stages the changes so you can edit them before committing.

Add Commit Origin

git cherry-pick abc1234 -x
Adds a line to the commit message like:
(cherry picked from commit abc1234)

Handling Conflicts

If a conflict happens:
# Fix conflicts manually, then:
git add .
git cherry-pick --continue
To cancel the cherry-pick:
git cherry-pick --abort

How to Create a Patch

Make a patch file for a single commit:
git format-patch -1 abc1234
For the last 3 commits:
git format-patch HEAD~3

How to Apply a Patch

Apply patch without keeping metadata:
git apply 0001-some-change.patch
Apply patch and keep original author & message:
git am 0001-some-change.patch

Reverse a Patch

Undo the changes in a patch:
git apply -R 0001-some-change.patch

Troubleshooting & Best Practices



  • Cherry-pick conflicts: If you encounter conflicts while cherry-picking, resolve them manually, then run
          git cherry-pick --continue
          to finish the process. If you decide to stop, you can cancel the cherry-pick with:
          git cherry-pick --abort
  • Patch doesn’t apply cleanly: Ensure the patch was created from a codebase compatible with yours. If there are issues, you might need to adjust and apply it manually
  • Keep branches updated: Always pull the latest changes before cherry-picking commits or applying patches. This helps prevent unnecessary conflicts and keeps your history clean.







More topic in Git

Tags
Our website uses cookies to enhance your experience. Learn More
Accept !