Common
Imal Perera  

Git Cherry-Pick

Spread the love

I have been using git more than 8 years now and there is a single mistake that I keep on doing, It is kind of a trademark of me 🙂 and because of this I have to spend extra some time to get the work done, I hope many of you do this mistake and looking for ways how to get it fixed. 

The mistake is ‘committing to wrong branches ‘

I’m sure you have come across this situation at least several times if you are busy with multiple projects, so let’s see how to fix this issue very easily.

Let’s say your team practices feature branch workflow and the team are using ‘dev‘ branch as the development branch so according to the practice you have to create a branch from the dev branch 

whenever there is a feature or a bug fix but however you have somehow committed directly to the dev  and other developers have also merged  their branches back to the dev branch so the tree looks like this 

Note: blue commits are from other developers 

but you want both commits in yellow to be like this and then merge back to dev whenever you think is the right time

Here are the steps 

Hard reset the branch to the commit f3dxr3c which is the oldest commit before the commits you want to move

 

git reset --hard f3dxr3c

Now let’s create the feature branch we forgot to create

 

git branch adding_client_feature 
git checkout adding_client_feature 

Now we have to add the commits that we want to have on this branch ( obviously 1c73c12 and b12d3c1 )

 
git cherry-pick 1c73c12 
git cherry-pick b12d3c1 

That is easy now we have a new branch called ‘adding_client_feature’ branch with only the commits that we want 

Now we have to fix the dev branch because it has qw23r18 and few other commits that have made by other devs

save the changes to the new branch and checkout to dev


git checkout dev 

Follow step 2 again to add the commits that are required to be in the branch 

Finally, push the fixed branch back to the origin 

git push --force origin dev

If you are interested reading more articles likes this visited the common category

Leave A Comment