Even I had this question, in my mind it was another feature that I would never use. But well I was wrong, I use it quite often.
Let's understand it with a real-case scenario.
Ever accidentally commited to a wrong branch, and wanted to revert?
Well, you could have done it the old fashion way of undoing the commit, changing branch and commiting again. But this will be a mess when you are down multiple commits.
But there is a better way to do it.
Step 1: Realise you commited in master
instead of my-feature
branch.
Step 2: Copy the hash of the commits you want in the other branch. Run this where you committed your changes, ie. master
branch here.
Note: If you need multiple commits, either you can copy all the hashes, or if they are consecutive commits, you only need to copy the first mistaken commit hash and the last commit hash.
git log --oneline
Step 3: Switch to the my-feature
branch
git checkout my-feature
Add -b
flag if you are creating a new branch. Read more about branches here.
Step 4: If you have
- (i) One commit
git cherry-pick <hash>
- (ii) Multiple commits
git cherry-pick <hash1> <hash2> <hash3>
- (iii) Consecutive range of commits
git cherry-pick <first-hash>..<last-hash>
Congratulation, you will have those commits in my-feature
branch. 🎉
Step 5: (Optional) Delete commits from master
branch.
git checkout master
git reset --hard HEAD~N
Where N is the number of commits, only do this when the commits are consecutive, and on tip of the branch. This works for our situation.
Or you can also use interactive rebase to drop specific commits
git rebase -i <commit-hash>
Bonus
- You can use
-n
flag to apply changes without commiting in the new branch - Use
-x
file to retain reference of the original commit which was cherry-picked. It shows up like this
That's it. As simple as it is.
It has saved me a lot of time when I accidentally commit changes to the main branch or a wrong feature branch (yeah, I don't delete local branches after they are merged);
Git cherry-picking can also be used for, selecting specific features from a branch, reordering commits, and much more left to your creativity.
Thank you for reading through the blog, its been quite a while (11 months to be exact) since I wrote my last blog. Working on increasing the regularity of blog posts.
Deveesh Shetty
Twitter | GitHub
Credits:
Cover Image - Unsplash
Top comments (1)
motivational comment to keep posting such good content. tho i know cherry picking, since I use it rarely I keep forgetting the commands so this blog can be a reference for me