When we need to join two or more git commands together, we have two git commands can choose – Merge or Rebase.

The Merge Option

In the past, I always using merge to join my branches:

         A ------> B ------> C      (Feature Branch)

/ \

F -> G ---> H -----> I ----> J (Master Branch)Copy the code

When Commit D merge to Commit J , occasionally occur some conflicts, if it is your own project, you can just fix the conflicts and commit again.

But if it is someone’s repos and you want to create a pull request, than your pull request will be rejected because the conflicts.

In this case, I need to do the following steps:

  1. Merge Commit I into Feature-> Commit X
  2. Fix the conflicts -> Commit Z
  3. Create a pull request again. (Now the conflicts has fixed)
         A ---> B ---> C --> X - > Z         (Feature Branch)

/ / /

F -> G -----> H -------> I ------> J (Master Branch)Copy the code

As you see, the log graph will be more complicated, and if the Master branch is very active, This can crash Feature Branch’s history quite a bit.

Did I really want to merge
Master branch into
Feature ?

No! I just want to avoid the conflicts in my pull request. The merge from Master to Feature is unnecessary. So, here has another option — Rebase.

The Rebase Option

Rebase can change the node that you branch out, you can compare the following graph with previous:

  1. Rebase Master in Feature branch.
  2. If has conflict, fix it then use command rebase --continue.
  3. Create a pull request.
                   A ---> B ---> C         (Feature Branch)

/ \

F -> G -> H -> I --------------> J (Master Branch)

Now we avoid the unnecessary merge and get a more cleaner log graph.

Notice: Because
Rebase command will change the node you branch out, if the information of the branch out node is important, maybe you should not use
Rebase to join your branches.

Reference

www.atlassian.com/git/tutoria…