Sigh, here is what happens when an idiot like me doesn’t pay enough attention and you don’t protect your main branch and how to get out of it.
The problem:
- The free version of git does not allow protection of the main branch. That means any one can do a
git switch main && git push -f
to complete the change the history which is what I did! - How does this happen? Well, if someone accidentally pushes into master and you want to get rid of those commits.
- The problem is that I did not do a
git switch main && git fetch -p --all && git rebase origin/main
so I was working with a local main which was two days old. - So when I tried to clip of the three bad commits with
git reset HEAD~3 && git push -f
I actually cut out days of work!
The the lessons:
- Do not do a git push -f ever to main!!!
- Protect main so people can’t do that. This does mean that you need to add more administrative overhead and make sure only the reviewers can push to main.
- And if this every happens, the right steps are to just reverse the commits rather than a forced push. Forcing rewrites the entire history which is dangerous for sure.
- It is more work, but you have to do a
git diff HEAD HEAD~3
to see what’s changed and then do more commits to reverse those changes withgit restore --source=HEAD~3 _the files that changed_
which basically means you can get the old files and put them back. - yes your git history is a little messed up with a revert right in the middle, but it means you don’t every have to force push into main.
And yes if you get tired of typing HEAD, you can now just use an @
instead so you can do a git difftool @..@^3
which manes look at the current head and compare it with three commits ago.
So how do you get out of this:
- Well the first step is figure out what commits you’ve now deleted, so basically you have to reapply those commits and get back to the correct main.
- When you do this, you will have to rebase all your pull requests since the history has changed. That is penance for the person who did all this.
- The most important thing to do though is to look carefully at your PRs to make sure you are committing the files that you want. You can also look at the commit section to make sure that you don’t have strange commits from the incorrect past polluting your PRs.
- The most painful part of a fast moving project is the need to constantly rebase up to the main branch so it is a good idea not to have too many PRs pile up.
Now I’m exhausted after a morning of fixing what I broke!
One response to “Github madness what happens if you do not protect main”
[…] madness and pull request splitting […]