Git Rebase Magic - RichikaRangta/otb-academy-2018 GitHub Wiki

While reading 'Think Like (a) Git' site/document I came across with an interesting thing as how we can use 'git rebase' as a shortcut which lets us to pick up the entire sections of a repository and move them somewhere else. I have been using rebase earlier as well but didn't know about this feature of it .

Problems I faced before ==> Few months ago when something went wrong with the branch which the pushed to the remote, I wanted to cherry-pick some of the commits from that branch and create a new one with the base as master. It was quite tedious to look for all the references(id's) of the commits (which i wanted to have in my new branch) and then cherry pick them one by one so that nothing goes wrong .

So when I read about USING 'GIT CHERRY-PICK' TO SIMULATE 'GIT REBASE' it took my interest. git rebasebeing a faster way to cherry-pick all of the commits in a given branch at once, rather than having to type out their IDs separately.

Example ==> Lets say we have few commits(A,B,C,D,E,F,G,H,I,J and K) and few branches (foo, bar, baz)

A<-B<-F<-G<-H<--foo

A<-B<-C<-D<-E<--bar

A<-B<-C<-I<-J<-K<--baz

Apply the following commands:

git checkout foo

git checkout -b newbar

git cherry-pick C D E

These commands make sure that we are at H (because 'foo' points to it),create and check out a temporary branch called "newbar", also pointing at H,apply the changes from C, D, and E, creating new commits C', D', and E', and update the "newbar" branch so it points at E', we write the following commands:

Which would give me a repository like:

A<-B<-F<-G<-H<-C<-D<-E<--new bar

A<-B<-C<-D<-E<--bar

A<-B<-C<-I<-J<-K<--baz

where foo is pointing to H

Then I can Apply the following commands:

**git checkout bar **

**git reset --hard newbar **

git branch -d newbar

This would do the following : Switch to the branch called "bar", Forcibly move the "bar" branch pointer so that it pointed to the same place as the "newbar" branch, and Delete the temporary "newbar" branch.

Now the repository looks like this:

A<-B<-F<-G<-H<-C<-D<-E<--bar

A<-B<-C

A<-B<-C<-I<-J<-K<--baz

As by now I have struggled a lot to make my repository to look like this , I would have achieved all this by simply applying the following command:

git rebase foo bar

Thus, 'git rebase' is a shortcut that lets us to pick up entire sections of a repository and move them somewhere else.

Hopefully this will make my life easier whenever something will go wrong with my branch and i need few commits out of it !