torstai 29. lokakuuta 2015

Advanced git. Cherry-pick, rebase and reset.

Today I encountered the following problem: I had put code in another branch that I would need in my master branch, BUT I could not take all code, just few commits. So I first found command called cherry-pick.

With cherry-pick you can merge one (1) commit from another branch and is quite easy to do, but eventually I found out that it is not a right tool for my job. Anyway, checkout your branch where you want to pick the commit.

git checkout mysecondbranch

then do git log with oneline option to show prettier log.

git log --oneline

Then just select the commit you want and checkout back to the master branch. Do

git cherry-pick 62ecb3

And you will merge that commit to your master.

Now if you need to merge multiple commits but not the whole branch cherry-picking is not the right tool for this job. We can rebase. First create a new temporary branch from the branch you want to do the changes. Then do rebase.

git rebase --onto mythirdbranch 76cada^

This means that from our "mythirdbranch" from commit number to the last one are applied to the temporary branch. 

OK so if you mess up with the rebase thing, you can do 

git rebase --abort

or if you already did the rebase, revert it with the following:

git reflog

git reset --hard HEAD@{5}

and the number inside head is the commit where you started the rebase. 

Finally merge the temporary branch your master branch.


ssh-add id_rsa will add your ssh key to keyring or something. Then you don't need to enter password every single time when you connect to git.