9. git rebase
This article is to prepare our mind for a git fast-forward
Every git branch comes from an older commit hash. This commit hash is the base of the branch. This commit hash can be a branch, tag, or simple commit hash.
It happens so often that, the base of our branch will continue to grow. At some time, we bring the new changes from grown up base to our branch. This is typically done with git merge. But there is a better way, it is 'rebase'.
When we branch from a main branch, main branch continues to grow
while, we continue to work on our branch. We can bring the main
branch changes using git rebase
command.
git rebase
is used to change the base of the current branch to some
other commit. Typically, this some other commit will be the very
branch which we based earlier, but need not be always!
git rebase -i <AFTER_THIS_commit_OR_branch_OR_tag>
Example
# assume, current branch: `my-mkdocs` ; -i: --interactive
git rebase -i main
# if there are any conflicts shown on screen, resolve them + commit.
git commit -am 'resovled conflict'
# Finally we need to `force` push local rebased branch to remote!
git push origin --force my-mkdocs
Once you execute above command, git will internally
- create a temp_branch from main and switches to it.
- apply each commit from current branch and apply to that temp_branch.
- assume, there are no conflicts. the temp_branch will be renamed to
my-mkdocs
(old my-mkdocs is deleted) - if we visualize in graphical tool like Git-Graph, mk-docs is shown
with new base. - each commit hash in mkdocs are changed! But the diff and important
meta data did not change. So, it should not bother us.
9.1 Interactive mode
When we pass -i
to the git rebase
, git will open editor asking what
changes to pick/edit/drop etc. Generally we want all, and, if that is the
case, simply exit the editor. If applying the the commits fails due to
merge conflicts, git will print which file has the conflicts with conflicts
marker. We can make necessary changes and commit.
git commit -am 'conflicts fixed'
git rebase --continue # start applying next commits.
Or, if we want to stop and go back to the state that was before we started rebase
git rebase --abort
The rebase happened in the local repo, we have to update this to remote.
This needs force
push because, we are re-writing the history of the remote branch.
Yes, our diff are same, yet commit hash are changed for each after rebase.
git push origin --force <remote_branch>