Search code examples
gitrebasegit-reset

git reset --hard results in a diverged branch


I'm working on a branch called Feature.

  • I pushed an empty commit 'New' (Commit 1) to indicate the creation of my branch (this is the standard in my company).
  • I then edited an important file and pushed it in a second commit (Commit 2). I realized afterwards that my modification actually resulted in an unknown bug.
  • I ran a reset --hard to go back to the previous, clean commit (Commit 1).
  • I then re-made my modifications in a clean way and made sure it wouldn't cause any bugs. I pushed my modifications in a third commit (Commit 3).

Now when I run git status, it tells me my branch Feature and origin/Feature have diverged and each have one commit. I'm guessing I'm going to have to rebase my branch.

My question is: how am I supposed to go about my commits after a git reset to make sure I don't have a commit 'behind' that eventually results in a branch divergence? How do you keep on committing and pushing after a git reset? Did I miss a step?

My company uses TortoiseGit, so all commands are run through a graphic interface.

enter image description here


Solution

  • Let's call your four bullet points steps 1 thru 4. And let's assume that your description of step 4 is incorrect; you made commit 3, but you did not push it, because you can't — which is the problem.


    So. You pushed as part of step 1 and again as part of step 2. But then in step 3 you left out a push.

    After the reset back to 1, you needed to force push the branch. Otherwise you leave the remote at commit 2, which was the last thing you successfully pushed — resulting in the "diverged branch" situation in your title.

    If feature is now on 3 you can solve the problem by force pushing now.


    But as you've been told, the right thing in step 3 was was never hard reset, which is messy and violent (and dangerous), and can result in the need to force push, which can be bad for everyone else on the team. You should have just reverted 2, resulting in four commits in a straight line:

    1 -- 2 -- undo 2 -- 3
    

    And that way, no divergence would have happened and no force pushing would have been necessary.

    --

    So, to sum up:

    How do you keep on committing and pushing after a git reset?

    Ideally you don't reset after pushing. But if you do, you will have to force push in order to carry on.

    Did I miss a step?

    Yes, you missed the force in force push. But it would be better never to have taken step 3 at all.