24

Recently I came across the notification that my branch has diverged. That was when I made a feature branch, pushed it to remote, and did a rebase with master a few days later when I started working on it again.

git checkout -b feature-branch
git push origin feature-branch:feature-branch

...and when in master...

git pull origin master
git checkout feature-branch
git rebase master

But when I want to push my branch again, it says:

On branch feature-branch
Your branch and 'origin/feature-branch' have diverged,
and have 67 and 1 different commit each, respectively.

I found this answer in "Git branch diverged after rebase":

Since you'd already pushed the branch, you should have merged in the source branch, rather than rebasing against it.

Question

After reading this I still don't fully understand what I should've done differently in my flow, and why I still want to be using git rebase. Hope someone can explain this, thanks!

Community
  • 1
  • 1
Amber
  • 465
  • 1
  • 5
  • 13
  • 1
    What about the push -f? mentioned in your link (http://stackoverflow.com/a/26349885/6309) If you are alone working on this branch, you can no force push. – VonC Jan 08 '16 at 14:10
  • I work in a team, so I think overwriting the remote branch isn't a good idea... – Amber Jan 08 '16 at 14:16
  • Then no rebase for you. Merge only. – VonC Jan 08 '16 at 14:16
  • Thanks for your reply! So only rebasing when you haven't pushed your branch yet? – Amber Jan 08 '16 at 14:25

1 Answers1

34

The idea is to rebase only if you haven't pushed yet, to replay your local commits.

As soon as you have pushed (and are working in a team), you should not rebase the branch on top of master, as it rewrites its SHA1, forcing you to force push the new state of the branch.

http://rypress.com/tutorials/git/media/5-1.png

Making a git merge master into your branch is preferable here: you resolve the conflicts locally, then you can more commits, and a regular push.

https://i.stack.imgur.com/wBMwq.png

See more at "What is the difference between merging master into branch and merging branch into master?"

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • Sub-Question to this old answer. What about from `feature branch` do `git rebase master` then `git pull`, handle the merge and `git push`? If the remote branch is in line with the local branch (you pushed the most recent version), what would be the problem? Perhaps I am misunderstanding how the internals of Git work. – Eppilo Oct 25 '18 at 11:03
  • @Eppilo Sure, it is just that the rebase of feature on top of master will rewrite its history, resulting in a forced push. – VonC Oct 25 '18 at 11:38