Skip to content

Instantly share code, notes, and snippets.

@Simbul
Created February 9, 2012 18:06
Show Gist options
  • Star 52 You must be signed in to star a gist
  • Fork 16 You must be signed in to fork a gist
  • Save Simbul/1781656 to your computer and use it in GitHub Desktop.
Save Simbul/1781656 to your computer and use it in GitHub Desktop.
Git hook to prevent commits on a staging/production branch
#!/usr/bin/env ruby
# This pre-commit hook will prevent any commit to forbidden branches
# (by default, "staging" and "production").
# Put this file in your local repo, in the .git/hooks folder
# and make sure it is executable.
# The name of the file *must* be "pre-commit" for Git to pick it up.
FORBIDDEN_BRANCHES = ["staging", "production"]
def current_branch()
branches = `git branch --no-color`.split(/\n/)
current = branches.select{ |b| b =~ /\s*\*/ }.first
current.gsub(/[\*\s]/, "")
end
branch = current_branch
if (FORBIDDEN_BRANCHES.include?(branch))
puts
puts " STOP THE PRESS!"
puts " You are trying to commit on the *#{branch}* branch."
puts " Surely you don't mean that?"
puts
puts " If you really do, force the commit by adding --no-verify to the command."
puts
exit 1
end
@chrishough
Copy link

Thank you for posting this fixed our issue!

@pvdb
Copy link

pvdb commented Aug 19, 2013

Instead of using the git branch porcelain command, and as a result having to parse its output, it might make more sense to use the following interrogator (ancillary git command) to get the name of the current branch:

def current_branch()
  git rev-parse --abbrev-ref=strict HEAD
end

@RafaelCosman
Copy link

Thanks for posting this! Would you be so kind as to point me to the documentation for how to create a pre-commit hook?

Best,

Rafael

@yonatanp
Copy link

@RafaelCosman Place a file named pre-commit with the above content under the folder .git/hooks/ in your local git clone.

@marlonbernardes
Copy link

Another option is to use git symbolic-ref --short HEAD to obtain the name of the current branch. Tested on git 1.8.1 and it works just fine.

@mcavallo
Copy link

How about?

def current_branch
  branch = `git rev-parse --abbrev-ref=strict HEAD 2>&1`
  $?.success? ? branch.chomp : nil
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment