Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@patmood
Last active February 22, 2017 18:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save patmood/9609325 to your computer and use it in GitHub Desktop.
Save patmood/9609325 to your computer and use it in GitHub Desktop.
Git pre-commit to prevent bad commits (forbidden branches and code)

What it does

If you try to commit directly to a "forbidden" branch like master or staging, you'll get a warning like this:

 HOLD UP!
 You are trying to commit directly to *master* branch.
 (>_<)

 You can force the commit by adding --no-verify to the command.

Trying to commit debuggers, logs, and merge conflict markers will also trigger the warning and tell you where the issue is.

How to setup

cd into the root of the respository you want to add the pre-commit hook to and run:

curl https://gist.githubusercontent.com/patmood/9609325/raw/9f4bd39dba7d5a58b431277b6989e3232296c6ae/pre-commit > .git/hooks/pre-commit && chmod u+x .git/hooks/pre-commit
#!/usr/bin/env ruby
# This pre-commit hook will prevent any commits to forbidden branches
# It will also help prevent you leaving debuggers and merge conflig flags
# Put this file in your local repo, in the .git/hooks folder
# and make sure it is executable by running: chmod u+x pre-commit
# The name of the file *must* be "pre-commit" for Git to pick it up.
error_found = false
FORBIDDEN_BRANCHES = ["master", "staging", "production"]
FORBIDDEN_CODE = [
/TMP_DEBUG/, # My TextExpander macros for embedding debug code always include this for easy scanning.
/>>>>>>/, # Git conflict markers
/<<<<<</, # ''
/======/, # ''
/console\.debug/, # JavaScript debug code that would break IE.
/console\.log/, # ''
/binding\.pry/, # pry debugging code
/binding\.remote_pry/, # ''
/save_and_open_page/, # Launchy debugging code
/debugger/, # Ruby debugging code
/focus:\s*true/
]
branch = `git rev-parse --abbrev-ref=strict HEAD`.chomp
if FORBIDDEN_BRANCHES.include?(branch)
puts
puts " HOLD UP!"
puts " You are trying to commit directly to *#{branch}* branch."
puts " (>_<)"
error_found = true
end
full_diff = `git diff --cached --`
full_diff.scan(%r{^\+\+\+ b/(.+)\n@@.*\n([\s\S]*?)(?:^diff|\z)}).each do |file, diff|
added = diff.split("\n").select { |x| x.start_with?("+") }.join("\n")
# Scan for "forbidden" calls
FORBIDDEN_CODE.each do |re|
if added.match(re)
puts %{Error: git pre-commit hook forbids committing lines with "#{$1 || $&}" to #{file}\n--------------}
error_found = true
end
end
end
if error_found
puts
puts " You can force the commit by adding --no-verify to the command."
puts
exit 1
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment