What is Git Rebase?
sobes.tech AI
Answer from AI
Git Rebase is a command that changes the sequence of commits in a branch. It "moves" commits from one branch to another by applying them on top of the latest commits of the target branch. This helps maintain a more linear and clean commit history, avoiding merges.
Main purposes of using Git Rebase:
- Simplify history: Makes the commit history more linear and understandable, which facilitates reading and tracking changes.
- Integrate changes: Allows integrating changes from one branch into another without creating additional merge commits.
- Edit history: Interactive mode (
git rebase -i) allows modifying, combining, reordering, or deleting commits.
Working principle:
When executing git rebase <target_branch> <current_branch>:
- Git determines the common point of divergence between
<current_branch>and<target_branch>. - It temporarily saves commits from
<current_branch>that were created after the common point. - Git moves the pointer of
<current_branch>to the end of<target_branch>. - It sequentially applies the saved commits from
<current_branch>on top of the latest commits of<target_branch>.
Example of basic usage:
Suppose we have branches main and feature.
// Current history
A -- B -- C (main)
\
D -- E (feature)
Execute git checkout feature and then git rebase main:
// After rebase
A -- B -- C -- D' -- E' (feature)
|
(main)
Commits D and E are reapplied on top of C, creating new commits D' and E'.
Interactive mode git rebase -i:
Allows managing the rebase process. An editor opens with a list of commits for rebase and available commands:
pick: use the commit (default).reword: use the commit and change its message.edit: use the commit and stop for making changes.squash: combine the commit with the previous one.fixup: combine the commit with the previous one, ignoring its message.drop: delete the commit.
Important rule: Do not use git rebase for branches that have already been published (shared in the remote repository) and are worked on by other developers. Rebase changes the commit history, which can cause issues when synchronizing with other copies of the repository. For published branches, it is preferable to use git merge.