Git – How to Rebase Your Own Branch and Force Push

gitgitflow

Is it ok when I do rebase and force push in branch which is used only by me? And will I have a problem after merge this branch in master later?

A few situations to illustrate this:

  1. We have master, I need to add some feature, so:
    • git pull origin master
    • git checkout -b new_feature
    • make some changes inside my branch
    • git pull –rebase origin master — because I don't want to have intermediate merge commit
    • if master branch has changes we'll get rebased history of commits in current state
    • git push origin new_feature -f — I'm able to push it only with force because the history is different in current and remote feature branch.

I don't merge it in master in feature, because a merge request is created after that for this branch, so this action is doing by another team member as example.

And I'm absolutely sure that noone commit in my branch and works with my branch, so as I understand force push is acceptable.

  1. The second situation where I want to squash some commits:
    • git pull origin master
    • git checkout -b new_feature
    • git commit -m "tst1"
    • git push origin new_feature
    • git commit -m "tst2"
    • git rebase -i HEAD~2
      After rebase
    • git push origin new_feature -f

And after that merge request in gitlab and merge in master.

Best Answer

A force push is basically saying "forget the old remote branch ever existed and just push what I tell you to". In terms of what ends up on the branch in the remote repo the foloowing are equivilent.

  • Do some stuff
  • Push new branch
  • Do some stuff that changes history
  • Force push branch


  • Do some stuff
  • Do some stuff that changes history
  • Push new branch

So if the branch is truely only used by you in a single client repo and the copy of it on the remote server is basically being used as a backup then force pushing is fine.

If the branch on the remote server is being used from multiple client repos (either by yourself or others) then force pushing can easilly lead to a mess. When one of those other client repos pulls from the server git will try to merge their version of the branch with the servers version. This may result in undesirable things like duplicated history or accidental reintroduction of removed code.

Related Topic