Fixing the branch source with git rebase
git rebase can be used to make various history adjustments, from rewriting the commit tree (and by doing that rewriting the history) to even pushing commits forward as if the branch were created in the future.
In this pro tip I will show you how to use git rebase to fix the source of a given branch.
Creating a branch from an incorrect branch
Suppose you have two tasks to do in the next few weeks and you want to work on each task in a different branch.
So to work on task #1 you create a branch with that name from
Let’s say that during your implementation you got tired of messing with that problem and decided that it would be a good idea to change the context for a bit and start working on task 2.
For that you need to create a new branch also from
main, however, without realizing it you ended up creating your branch from branch
And then, you started working and only realized the mistake later. After you commit to
task-2 your history looks something like this:
If you look at your history graph you’ll see that it shows that the most recent commit (
1078aa) on the branch
task-2 depends on the commit made on the branch
So we need to fix this.
Fixing the branch source
With this mistake in hand and since the implementations of each task are independent of each other you want to make this correction.
For this you must use
git rebase followed by the flag
--onto and the name of the three branches, the full command looks like this:
git rebase --onto main task-1 task-2
The result should look similar to the image below:
Now, having run the above command, your history becomes what it should have been from the beginning:
And if you check the history graph again, you’ll see that we only see the commits from task 2 in the corresponding branch:
Three important things to notice:
- First, it is always necessary to give the names of the three branches involved to avoid missing commits;
- Second, now branch
task-2has its source in the branch
- And third, the hash of the commit on the branch
task-2is no longer
b25a97since the commit has changed.
With that now you know how to change or fix the source of a branch, if you want more details about the command
git rebase, I recommend reading the command’s documentation.
Below you can see a card that can help you remember the command
git rebase --onto: