Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging or Rebasing?

Tags:

git

merge

rebase

When working with remote repositories, you have the option of merging and rebasing, but after reading about it, I can not figure out why or when I would use rebasing. Seems like merging is the better option overall, even if they both have pros and cons. I can only think about scenarios where merging is the way to go. So I would like to know when is rebasing better.

like image 506
Carlos Garcia Avatar asked Oct 15 '25 07:10

Carlos Garcia


1 Answers

tl;dr Merge feature branches, rebase updates.

If you're merging a feature branch, merge. In fact, force a merge with --no-ff (no-fast-forward). This leaves the history with a "feature bubble" showing which commits were grouped together in a branch. You can see this with git log --graph.

A - B --------- M - H <-- master
     \         /
      E - F - G

If you rebase, you just get a flat history.

A - B - E - F - G - H <-- master

Some people like this flat history, it is simpler, but it does lose information which cannot be recovered. Some reason some prefer squash merges.

A - B - S - H <-- master

Very tidy, but it loses all that useful commit information.


When updating a branch, rebase. This is because the update merges are of little interest to understanding why the code was written. They just obscure the real merges.

# Updating with `git merge master`
# This can look considerably worse if everyone is doing it.

      E - F   G - H  <-- other people's features
     /     \ /     \
A - B ----- M ----- M <-- master
     \       \       \
      C - D - M - I - M - K - L  <-- your feature
# Updating with `git rebase master`
      E - F   G - H  <-- other people's features
     /     \ /     \
A - B ----- M ----- M
                     \
                      C - D - I - K - L  <-- your feature

Instead of your branch being built on a combination of old and new versions of master, every commit is built on the latest version of master. This makes debugging and review simpler, and also the final merged branch is simpler.

# Merge after updating with `git merge master`
# Again, it can be considerably worse.

      E - F   G - H
     /     \ /     \
A - B ----- M ----- M --------- M <-- master
     \       \       \         /
      C - D - M - I - M - K - L
# Merge after updating with `git rebase master`
      E - F   G - H
     /     \ /     \
A - B ----- M ----- M ----------------- M <-- master
                     \                 /
                      C - D - I - K - L

Similarly, a pull is just a fetch plus a merge. Pulls are just updates, so instead do a fetch and a rebase with --rebase or set it to be the default with pull.rebase = merges.

like image 130
Schwern Avatar answered Oct 16 '25 22:10

Schwern