Search code examples
gitpushgit-push

Regarding git force push


I cloned a repository to my local machine.Then, i created a new branch (from the current master )using git checkout -b dev/abc/test1. I am the only person working on this branch. I worked on this branch for a few hours and then made commits and did git pushand created a pull request. Reviewers made some comments on this pull request.

Before starting to work on those comments, i did, git checkout master, then, git pull to update master branch. Later, i wanted to merge those changes(there were a lot many changes in master since i had last updated it) to my branch dev/abc/test1.

Hence, i did git checkout dev/abc/test1. Then i did git reset --hard origin/master and then git merge origin/master. So, all my changes from this branch were lost as expected. I manually copy pasted the changes i made from the pull request. Now i started to work on those reviewer comments and fixed all of them, did a git commit and then git push but only to see the message

hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart.

To avoid this, i went ahead with git push --force.

Will this have any negative impact? I see one of the comments saying here Cannot push to GitHub - keeps saying need merge that 'forcing' is most of the time, if not always, the wrong answer. Will my approach impact the repository in any negative way ? (As a side note, i am the only individual contributor to the branch dev/abc/test1)


Solution

  • When you did git push --force, you forcibly overwrote the remote dev/abc/test1 branch. This means that the previous remote branch was potentially erased for good. There should be no side effects in your case, because you are the only one using the branch. The reason why force pushing is generally bad, is because in general remote branches are shared by several developers at a time. When you rewrite the history of a remote branch, you can cause havoc for anyone else sharing the branch. When that other person goes to git pull, they will see a new history coming in.

    Note that, perhaps ironically, the best thing for you to have done would be to just replace your local copy of dev/abc/test1 with the remote branch. So, instead of doing a hard reset to master, you could have done a hard reset to the dev/abc/test1 tracking branch, via:

    git reset --hard origin/dev/abc/test1
    

    This would have undone whatever you did locally which might have prompted you to reset to master.