DEV Community

Serhat Teker
Serhat Teker

Posted on • Originally published at tech.serhatteker.com on

Rebase Master

Rebase

While you've been working on something, probably you've been working on a branch on-and-off, or lots has happened in other branches.

The best solution would be to rebase your branch onto master. This keeps the history tidy and makes things a lot easier to follow.

Update your feature branch from master:

  1. Switch the master branch
  $ git checkout master
Enter fullscreen mode Exit fullscreen mode
  1. Get remote updates:
  $ git pull
Enter fullscreen mode Exit fullscreen mode
  1. Switch back to your local branch:
  $ git checkout local_branch
Enter fullscreen mode Exit fullscreen mode
  1. Make the rebase magic:
  $ git rebase master
Enter fullscreen mode Exit fullscreen mode
  1. Push your local branch to remote:
  $ git push
Enter fullscreen mode Exit fullscreen mode

--force flag will be needed if you've already pushed your branch.

  $ git push --force
Enter fullscreen mode Exit fullscreen mode

*Warning* : Think and check twice before doing this.

comparing branches

If you want to compare your local and remote feature branch before "forced push":

$ git diff <master_branch_path> <remote_branch_path>
Enter fullscreen mode Exit fullscreen mode

For example:

$ git diff feature origin/feature
Enter fullscreen mode Exit fullscreen mode

Where feature is your local branch and origin/master is your remote branch.

Git - Your branch and 'origin/xxx' have diverged

If you receive below error:

Your branch and 'origin/xxx' have diverged,
and have 1 and 1 different commit(s) each, respectively.
Enter fullscreen mode Exit fullscreen mode

It is normal. This happens if you rebase the branch which was previously pushed to the origin repository. Rebase rewrites history, so after it you'll have different local and remote state.

We had a history like this:

... o ---- o ---- A ---- B  master, origin/master
                   \
                    C  branch_xxx, origin/branch_xxx
Enter fullscreen mode Exit fullscreen mode

And we "rewrote" the history like this:

... o ---- o ---- A ---------------------- B  master, origin/master
                   \                        \
                    C  origin/branch_xxx     C` branch_xxx
Enter fullscreen mode Exit fullscreen mode

The solution:

$ git push origin branch_xxx --force
Enter fullscreen mode Exit fullscreen mode

So the actual state will be like:

... o ---- o ---- A ---- B  master, origin/master
                          \
                           C` branch_xxx, origin/branch_xxx
Enter fullscreen mode Exit fullscreen mode

As said before:

*Warning* : Think and check twice before doing this.


For more details:

git-scm — Git Branching - Rebasing

Top comments (0)