Prevent a force pushing to master with ruby

Yeah, everyone knows, it’s the mor law of versioned systems, NEVER do a git push -f on the default branch, never, even when you know what you’re doing, bad things can happen, really bad.

However, sometimes, not very often, when you are tired, not paying too much attention, you may do that and bum!

To prevent the mess and your job, you can use the protected branch feature at Github, Bitbucket and GitLab, however, if you aren’t using one of that services (yeah, there are some cases), you can also have this protection with the built in pre-push Git hook, in ruby.

So, lets cut the talk and show the code.

Easy peasy right? Yeah, now we just need to set it up:

  • Place the file (it’s important that you name it as pre-push, without the extension) to your ~/.git_template/hooks folder

  • Set executable permission to it with:

    $ chmod +x *~/.git_template/hooks*/pre-push
    
  • Config your ~/.git_config to init with the git_template folder
    *~/.git_config*
    
    [init]
     templatedir = ~/.git_template
    
  • Re-init your existing repository to load the hook and check if the file was loaded properly
    $ cd /your_repo_path
    $ git init
    $ ls -l .git/hooks
    

That’s it. Now you have the force push protection on your repos!

With this you can profit and of course, sleep better without that cold fear of messing up the default branch.

We want to work with you. Check out our "What We Do" section!