Git Cherry Pick: A Way To Remove Commits Between Two Commits

Git Cherry Pick: A Way To Remove Commits Between Two Commits

One of the best practices when using git is to keep histories on your main branch clean

Sometimes, It's very hard.

Here, I will share one situation which can be fixed using Git Cherry Pick

Git Cherry Pick

Cherry picking in Git means choosing a commit from one branch and applying it to another.

Let's assume you have a feature branch with the following commits:

f457144 add jsdoc support
5b6716b Refactor controllers
30e9b04 Create APIs for student management
95c41ef setup prettier
853ee9c Add CodeSee architecture diagram workflow to the repository
c383769 Fix bugs
f887497 Add dummy files in seeder and migration

Let's say you want to delete commits between c383769 and 5b6716b


Let's dive into get cherry-pick

STEP 1 - Checkout the commit: git checkout c383769

STEP 2 - Create a new branch from there: git checkout -b commit-remove

STEP 3 - Cherry-pick commits you want to keep: git cherry-pick f457144 and git cherry-pick 5b6716b

STEP 4 - Checkout your original branch: git checkout feature

STEP 5 - Reset the original branch to the last usable commit: git reset --hard c383769

STEP 6 - Merge the new branch onto the original branch: git merge commit-remove

STEP 7 - Check that the original branch has the correct commits: git log --oneline

STEP 8 - Push the original branch to the remote repo: git push --hard origin feature

Altogether,

git checkout c383769
git checkout -b commit-remove
git cherry-pick f457144
git cherry-pick 5b6716b
git checkout feature
git reset --hard c383769
git merge commit-remove
git push --hard origin feature

Did you find this article valuable?

Support Sujeet Agrahari by becoming a sponsor. Any amount is appreciated!