Last active
December 19, 2015 16:08
-
-
Save bigfive/5981306 to your computer and use it in GitHub Desktop.
Creates a git template dir that will allow all folders that you run 'git init' in will now use a pre-commit hook that forbids commits directly on master and staging
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
def add_new_git_template | |
# Paths | |
home_dir = File.expand_path('~') | |
template_dir = File.join(home_dir, ".git_template") | |
hooks_dir = File.join(template_dir, "/hooks") | |
pre_commit_file = File.join(hooks_dir, "pre-commit") | |
# Create dirs | |
Dir.mkdir(template_dir) unless File.exists?(template_dir) | |
Dir.mkdir(hooks_dir) unless File.exists?(hooks_dir) | |
# Early out | |
if File.exists?(pre_commit_file) | |
puts "You all ready have a pre-commit in your template directory" | |
puts "Please ensure you are using the DD git commit standards" | |
return false | |
end | |
# Write the file | |
File.open(pre_commit_file, 'w') do |f| | |
f.write( | |
%q{#!/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", "master"] | |
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} | |
) | |
end | |
# Add to git | |
`chmod a+x ~/.git_template/hooks/pre-commit` | |
`git config --global init.templatedir ~/.git_template` | |
puts "Setup complete" | |
puts "All folders that you run 'git init' in will now use a pre-commit hook that forbids commits directly on master and staging" | |
end | |
add_new_git_template() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment