How rebase works and when to use it

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the git category.

Last Updated: 2024-03-02

1. So what does rebase actually do?

# Let's put this in context with some sample code.

# You first checkout the branch that want to rebase
$ git checkout feature
# Then you carry out the rebase using format: git rebase [base]
$ git rebase master

Generally, git rebase moves a branch from one base commit to another. In this case it moves the entire "feature" branch so that it starts at the tip of "master". Or "rebasing feature onto master".

Under the lid, it works by collecting each commit that is an ancestor of the current commit but not of base, putting these changes aside, setting the current head (briefly) to base, then replaying these commits that were set aside.

2. When is rebasing typically used?

3. Why should you never merge any public branch (esp. master) onto a feature branch?

i.e. such a command would be

# Checkout master
git checkout master
# Rebase it into `feature` as a base
git rebase feature