This lesson covers two ways of getting commits from one branch to another: merging and rebasing. You’ll learn what is involved in each method as well as how to decide on which one to use in your projects.
Merging and Rebasing
Merging and Rebasing. Once you’re finally finished with your new feature or whatever the purpose of the branch was, it is time to absorb the changes back into the
master branch. And the two most common ways to do this are merging and rebasing.
When you merge, Git creates a new commit and combines the top checksums of the two branches into one. And if all the commits in the feature branch are ahead of the
master branch, Git will do what’s called a fast-forward merge and place the commits on to the adjoining branch. That’s what’s happening in this diagram.
But what if, say, somebody on our team has made commits to the
master since we started our feature branch? Git will account for this with a new commit that is a combination of the changes. If, however, the same section of the code has been modified, Git will stop the merge and tell you there is a merge conflict.
00:52 It will give you instructions on how to start fixing the issues. So, let’s hop into the console and do a fast-forward merge. Back in the console here. Let’s kind of orient ourselves with the parenthetical.
And you can see up at the very top here that
my_new_feature file—that commit’s been added to our
master branch. And if we list the directory,
my_new_feature is now in
master. So that’s a fast-forward merge.
This can potentially muddy up project history and sometimes make it difficult to go back and troubleshoot. Using
rebase instead of
merge can make the project history look more natural, like a branch never occurred.
02:25 Rebasing does this by rewinding to what’s called the common ancestor of both branches and then playing it back. It then takes the diff of each branch’s commits and adds those changes to the project history. You will find yourself asking which one is better, which one you should use.
02:43 The answer is neither is better and you should use the one that fits your team and your project. Now, I don’t have a rebase scenario for you in this series, but if you take a look at the Real Python Git and GitHub for Developers article, there’s some great resources in there for websites that will let you learn and work with advanced merges and rebases.
03:07 Regardless of where you fall on merging versus rebasing, I’ll leave you with this excerpt from the Pro Git book—again, available for free on Git’s website. They say, in general, the way to get the best of both worlds is to […] “rebase local changes you’ve made but haven’t shared yet before you push them in order to clean up your story, but never rebase anything you’ve pushed somewhere else.”
Become a Member to join the conversation.