--onto option#Consider the following git history:
gitGraph
commit id: "0-19as8su"
commit id: "1-0a9s8ds"
branch feature-1
checkout feature-1
commit id: "2-a0s9asd"
commit id: "3-ss91820" type: HIGHLIGHT
branch feature-2
checkout feature-2
commit id: "4-as98dam"
commit id: "5-as0d9km"
checkout feature-1
commit id: "6-0as9d8s"
commit id: "7-as90dia"
checkout main
merge feature-1 id: "8-0as9d8s"
We have two branches feature-1 and feature-2 branched off from the feature-1 and work on the feature-2. Then, there are two more commits on the feature-1 and it’s merged to the main branch.
To reduce conflicts when rebasing a branch on top of the main branch, we can use the --onto option of the git rebase command:
git rebase --onto main 3-ss91820The
3-ss91820is the commit hash where thefeature-2branch was branched off from thefeature-1branch.
The new git history will look like this:
gitGraph
commit id: "0-19as8su"
commit id: "1-0a9s8ds"
branch feature-1
checkout feature-1
commit id: "2-a0s9asd"
commit id: "3-ss91820" type: HIGHLIGHT
checkout feature-1
commit id: "6-0as9d8s"
commit id: "7-as90dia"
checkout main
merge feature-1
branch feature-2
checkout feature-2
commit
commit
--update-refs option#We can use the --update-refs option to update all the branches branched off in the chain with one command. Consider the following git history:
%%{init: { 'gitGraph': {'showCommitLabel': false}} }%%
gitGraph
commit
commit
branch feature-1
checkout feature-1
commit
commit
branch feature-2
checkout feature-2
commit
commit
checkout feature-2
branch feature-3
checkout feature-3
commit
commit
commit
checkout feature-1
commit
commit
checkout main
merge feature-1
Technically, after merging the feature-1 branch to the main branch:
feature-2 branch should be rebased on top of the main branchfeature-3 branch should be rebased on top of the feature-2 branchTo achieve this, we can use the --update-refs option:
# Checkout the top branch in the chaingit checkout feature-3
# Rebase the branch on top of the main branch with --update-refs option# This will rebase the branch on top of the main branch and update all the branches in the chaingit rebase main --update-refsThe new git history will look like this:
%%{init: { 'gitGraph': {'showCommitLabel': false}} }%%
gitGraph
commit
commit
branch feature-1
checkout feature-1
commit
commit
checkout feature-1
commit
commit
checkout main
merge feature-1
branch feature-2
checkout feature-2
commit
commit
checkout feature-2
branch feature-3
checkout feature-3
commit
commit
commit
This way, we can reduce the efforts when rebasing a branch on top of another branch with the --update-refs options.