Skip to content

Instantly share code, notes, and snippets.

@wacko
Last active September 16, 2020 22:57
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save wacko/62560b45c1d191859d6b to your computer and use it in GitHub Desktop.
Save wacko/62560b45c1d191859d6b to your computer and use it in GitHub Desktop.
Git hook to avoid commit debug lines (binding.pry console.log debugger...)
#!/usr/bin/env ruby
# Validates that you don't commit forbidden keywords to the repo
# You can skip this checking with 'git commit --no-verify'
exit 0 if ARGV.include?('--no-verify')
# Update this list with your own forbidden keywords
KEYWORDS = %w(binding.pry console.log debugger)
def red(text) "\033[31m#{text}\033[0m"; end
def yellow(text) "\033[33m#{text}\033[0m"; end
# list all the files staged for commit
files_changed = %x(git diff --cached --name-only --).split
# search files for keywords
%x(git grep -q -E "#{KEYWORDS.join('|')}" #{files_changed.join(' ')})
if $?.exitstatus.zero?
puts "# Check following lines:"
files_changed.each do |file|
KEYWORDS.each do |keyword|
%x(git grep -q #{keyword} #{file})
if $?.exitstatus.zero?
line = %x(git grep -n #{keyword} #{file} | awk -F ":" '{print $2}').split.join(', ')
puts "#\t#{red(file)}:#{line} contains #{yellow keyword}."
end
end
end
puts "Use 'git commit --no-verify' to skip this validation"
exit 1
end
@wacko
Copy link
Author

wacko commented May 19, 2015

Hooks should be located on $GIT_DIR/hooks/ folder.
i.e.: ~/my-project/.git/hooks/pre-commit

Bonus:
Save this hook under $HOME/.git-templates/hooks
And then add to $HOME/.gitconfig:

[init]
  templatedir = $HOME/.git-templates

So it will be automatically copied into your project any time you run git init 😉
(you can replace .git-templates with any other path)

More info: Git Init

@sathiyaseelan
Copy link

sathiyaseelan commented Feb 19, 2017

While adding manually to the existing project, don't forget to change mode (chmod +X pre-commit) . I've missed and the hook is not executed

@yasalmasri
Copy link

👍
thank you so much

@tamphh
Copy link

tamphh commented Aug 30, 2018

Thank you.

@bluemihai
Copy link

I have found this very useful — thank you!

I just ran into an issue with a merge conflict though... since I believe git merge automatically calls git commit, I found myself in a bit of a Catch-22.

If I git merge --continue, I get the error

  (use "git commit" to conclude merge)

If I git commit, I get the error message from the hook.

I had to just temporarily turn off the hook.
Any thoughts on how to handle this?

@nelsontkq
Copy link

nelsontkq commented Sep 16, 2020

@bluemihai

Any thoughts on how to handle this?

You could check if merge head exists by adding exit 0 if File.file?('./.git/MERGE_HEAD') to the top of the script

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