Search code examples
algorithmgitversion-controldvcs

What are the advantages of a rebase over a merge in git?


In this article, the author explains rebasing with this diagram:

enter image description here

Rebase: If you have not yet published your branch, or have clearly communicated that others should not base their work on it, you have an alternative. You can rebase your branch, where instead of merging, your commit is replaced by another commit with a different parent, and your branch is moved there.

while a normal merge would have looked like this:

enter image description here

So, if you rebase, you are just losing a history state (which would be garbage collected sometime in the future). So, why would someone want to do a rebase at all? What am I missing here?


Solution

  • There are variety of situations in which you might want to rebase.

    • You develop a few parts of a feature on separate branches, then realize they're in reality a linear progression of ideas. Rebase them into that configuration.

    • You fork a topic from the wrong place. Maybe it's too early (you need something from later), maybe it's too late (it actually applies to previous versions as well). Move it to the right place. The "too late" case actually can't be fixed by a merge, so rebase is critical.

    • You want to test the interaction of a branch with another branch, but for some reason don't want to merge. For example, you might want to see what conflicts crop up commit-by-commit, instead of all at once.

    The general theme here is that excessive merging clutters up the history, and rebasing is a way to avoid it if you didn't get your branch/merge plan right at first. Too many merges can make it hard for a human to follow the history, and also can make it harder to use tools like git-bisect.

    There are also all the many cases which prompt an interactive rebase:

    • Multiple commits should've been one commit.

    • A commit (not the current one) should've been multiple commits.

    • A commit (not the current one) had a mistake in it or its message.

    • A commit (not the current one) should be removed.

    • Commits should be reordered (e.g. to flow more logically).

    While it's true that you "lose history" doing these things, the reality is that you want to only publish clean work. If something is still unpublished, it's okay to rebase it in order to transform it to the way you should have committed it. This means that the final version in the public repository will be logical and easy to follow, not preserving any of the hiccups a developer had along the way.