Skip to content

Instantly share code, notes, and snippets.

@kaushikgopal
Last active April 19, 2023 09:22
Show Gist options
  • Save kaushikgopal/10f7f77a69b142d98f67 to your computer and use it in GitHub Desktop.
Save kaushikgopal/10f7f77a69b142d98f67 to your computer and use it in GitHub Desktop.
pre-commit git hook - no "hacking"
#!/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.
def current_branch()
branches = `git branch --no-color`.split(/\n/)
current = branches.select{ |b| b =~ /\s*\*/ }.first
current.gsub(/[\*\s]/, "")
end
def get_current_hacks
hacks_in_place = ""
files_to_be_commited = `git diff --cached --name-only --diff-filter=ACM`.split(/\n/)
files_to_be_commited.each do |file_name|
hack_present_in_committed_patch = %x[git diff --cached #{file_name} | grep "hacking"]
hack_present = !hack_present_in_committed_patch.nil? && !hack_present_in_committed_patch.empty?
if !hack_present
next
end
hack = %x[grep -iHnw -e "hacking" #{file_name}]
hacks_in_place += "#{hack}\n" if (!hack.nil? && !hack.empty?)
end
hacks_in_place
end
def exit_if_hacks_in_place
hacks = get_current_hacks()
if (!hacks.nil? && !hacks.empty?)
puts
puts " -------------- STOP THE PRESS! ---------------"
puts " WOH WOH WOH! You have Hacks in your code yo!"
puts
puts hacks
puts
puts " Surely you don't want to push that?"
puts
puts
# puts " If you really do, force the commit by adding --no-verify to the command."
# puts
exit 1
end
end
exit_if_hacks_in_place
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment