man in polo shirt sitting near brown woven basket black and white photography

Github madness what happens if you do not protect main

1

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:

  1. 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!
  2. How does this happen? Well, if someone accidentally pushes into master and you want to get rid of those commits.
  3. 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.
  4. 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:

  1. Do not do a git push -f ever to main!!!
  2. 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.
  3. 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.
  4. 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 with git restore --source=HEAD~3 _the files that changed_ which basically means you can get the old files and put them back.
  5. 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:

  1. 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.
  2. 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.
  3. 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.
  4. 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!

Related Posts

One Reply to “Github madness what happens if you do not protect main”

Comments are closed.