gitgit-mergegit-rebasebitbucket-cloud

Which is recommended git rebase or git merge to include the changes


I am working on branch A which was created from branch B which was created from master.
Now master has moved ahead and I want to include the master branch changes into A.
How can I do that?

I have done this in the past by merging master into branch A. But I am not sure if that is a good approach.
I have heard a lot about doing a rebase from the master but not sure what's the difference as ultimately I just want the new code to be there in the branch A


Solution

  • Well, I'm pretty sure there are tons of similar questions - and answers - covering this topic, but nevertheless.

    Your history is master -> B -> A.

    And it looks like you want to go to new-master -> new-A (no B anymore).

    Or in other words, you want to get to a situation where your work branch A contains your changes on top of whatever is currently in master.

    Rebase

    In this case, you pretty much always want to rebase your local changes on top of that new master.

    What rebase does is that it takes each commit that you made on top of the "old master" and "re-applies" them on top of the "new master".

    Assuming there are no conflicts - as those could possible make a rebase a bit more challenging at first sight (but there is a remedy to it) - and let's say you made 5 commits to your work branch.

    After the rebase, your new work branch will still contain 5 commits - but with different commit SHA's as those will be rewritten - on top of the latest "master".

    Merge

    Same setup, no conflicts and you made 5 commits in your branch.

    After the merge, all of these commits will still exist with their existing SHA's - and there will be a 6th commit, a so-called "merge commit" that will take all of master's changes and merge them onto your branch.

    When to choose which

    Since rebase will re-apply your local changes on top of the new master, their commit SHA's will change.

    However, you will end up in a situation where it will be much easier for you to eventually upstream your changes because your history will look like new-master -> your 5 commits -> HEAD.

    Whereas a merge will not touch those old commits - but yield a history such as master -> your 5 commits -> all changes between old and new master in a single merge commit -> HEAD.

    This can often be much harder to eventually merge upstream.

    Rebasing a large number of commits

    In case your work branch has a larger number of local changes, but you still want to rebase, one thing you could do to help with potential merge conflicts is to first squash your changes prior to the rebase.