Changing base branch in git

If your git flow is heavily based on feature branches being merged into master branch, you may need to replace base branch for changes on your feature branch.

Following command might be helpful:

git rebase --onto <new base> <old base> <your branch>

Use case

Let's take following use case:

--------------> master
   -- A -- B -- C --> feature branch
            -- D -- E --> your branch

What's going on here?

  • Your colleague works on a feature branch
  • You contributed to this branch by creating new branch in order to make pull request
    • Your branch is ahead two commits D and E
    • Your branch is also behind feature branch by commit C

What happens next?

Your colleague decided to squash all his changes and put them under one commit. History was overwritten basically.

Now it looks like that:

--------------> master
   -- F --> feature branch
   -- A -- B
            -- D -- E --> your branch

What to do now? git rebase --onto comes with help. This command is going to pick all your changes and put them under "new" base commit.

If you run:

git rebase --onto feature_branch <rev of commit B> <your branch>

You tell git to move all your commits (3rd argument) from base revision that points to commit B to new base branch which is current state of branch feature_branch.

No conflicts.

If you used regular rebase operation you would end up having bunch of conflicts that don't exist.