Git and GitHub Series
Why should I cherry-pick?
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.
Step 3: Switch to the my-feature
branch
Add -b
flag if you are creating a new branch. Read more about branches here.
Step 4: If you have
- (i) One commit
- (ii) Multiple commits
- (iii) Consecutive range of commits
Congratulation, you will have those commits in my-feature
branch. π
Step 5: (Optional) Delete commits from master
branch.
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
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.
Credits: Cover Image - Unsplash