'how to push rebased branch

I have a feature branch branch-foo. It was branched off from master branch, which is our stable/production branch.

I have the following work process:

  1. I pushed branch-foo to remote repo & created a pull request for team to review.

  2. Then, on my local branch branch-foo, I did code updates based on pull request review comments. But I don't yet push it.

  3. At this point, I noticed the there are new merge to master, so I fetched the latest master branch & did a rebase. That's rebase my branch-foo to the head of latest master.

  4. Now I try to push branch-foo with my code updates. And get rejected git error:

 ! [rejected]    branch-foo -> branch-foo (non-fast-forward)
error: failed to push some refs to 'bitbucket.org:myorg/my-project.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
  1. I see above error suggests me to pull, so I then tried git pull origin branch-foo, but get another error:
From bitbucket.org:myorg/my-app
 * branch            branch-foo -> FETCH_HEAD
fatal: Not possible to fast-forward, aborting.

So, I get stuck that I am not able to push my changes, neither can I pull the remote. Our team enforces to only allow fast-forward, no direct merge allowed.

How can I properly solve this problem so that I can push my rebased branch to my pull request branch now?



Solution 1:[1]

you start with

                 A---B---C foo
                /
           D---E master

you push, and master was updated:

                 A---B---C foo and origin/foo
                /
           D---E---F---G origin/master

you did some modification, you fetch rebase on master:

                 A---B---C origin/foo
                /
           D---E---F---G origin/master
                        \
                          A'---B'---C'  foo

foo is not a fast-forward of origin/foo, but it is a fast forward of master. You need to push with force as you are not doing fast forward on foo:

To avoid bad surprise avoid

git push --force

just use:

git push --force-with-lease

you will have

           D---E---F---G origin/master
                        \
                          A'---B'---C'  foo and origin/foo

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1