Question

Note: I know git push -f questions are common, but I really couldn't easily find answers to this specific question anywhere. I want a comprehensive answer, not just something that somewhat solves my problem. At the end of the question I propose a solution myself.

I've pushed some changes to a branch I should not (at work). I have already git revert'ed the changes, but one of the team coordinators wanted me to actually git reset <old commit> && git push -f so that the history wouldn't be cluttered by the revert commits. Few people use that branch, so we thought it was worth the risk.

It worked, but I'm afraid that people who had already pulled my commits may accidentally fast-forward the remote branch again, since the history hasn't diverged yet (I just resetted to an old commit, but didn't make any other commit on top of that one).

I noticed that if I git reset <old HEAD commit> && git status, Git says it's a couple commits ahead of origin/<branch>, so I'm sure if I git push again, Git will just fast-forward it.

git pull says the repo is up-to-date and doesn't backtrack (which I don't think it should, anyway). But then, what should I do to make sure everyone backtracks to the right HEAD on origin/<branch> and work from there? Do I need to ask everybody to git reset origin/<branch> before resuming work on that branch? I really wanted something easier and less error-prone (they might forget to do it).

I know I shouldn't be git resetting a branch on a shared repo, but you know how it is... Sometimes you just feel adventurous, or maybe your superior asked you to do it and you know it's wrong but it could be an educational experience anyway :P

Was it helpful?

Solution

You really do have to communicate with everyone who might push to that branch that the revert has happened and they should sync up their local repositories.

You could try some fancy trick with git hooks to prevent anyone from re-pushing the invalid commit. But if it's a rarely-used branch like you say, then you're probably better off just relying on communication (which should be done in any case when this happens).

For clean checkouts of the shared branch:

git reset origin/<branch>

should do the trick.

If someone has already built a branch on top of the bad commit, it will be necessary to remove the bad commit from the local history to prevent it from being pushed upstream again. This can be accomplished via git rebase with the interactive option:

git rebase -i origin/<branch>

This will present the user with a list of commits made to the local branch since it diverged from upstream. The bad commit will appear in this list and should be deleted.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top