Created
September 27, 2022 04:57
-
-
Save bikram990/2400312210022c5436fccb68c4d05ce6 to your computer and use it in GitHub Desktop.
git pre-receive hook to reject commits not matching a certain pattern
This file contains hidden or 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 | |
# uncomment following if using update hook script | |
# $refname = ARGV[0] | |
# $oldrev = ARGV[1] | |
# $newrev = ARGV[2] | |
# pre-receive hook script get these values at STDIN | |
$input = STDIN.gets | |
inputs = $input.split(' ') | |
$refname = inputs[2] | |
$oldrev = inputs[0] | |
$newrev = inputs[1] | |
$user = ENV['GL_USERNAME'] | |
$protocol = ENV['GL_PROTOCOL'] | |
if $user == "jenkins" | |
puts "Ignoring update hook for jenkins" | |
exit 0 | |
end | |
if $newrev == "0000000000000000000000000000000000000000" | |
puts "Ignoring policy check for branch deletion" | |
exit 0 | |
end | |
# if $protocol != "ssh" | |
# puts "#############################################################" | |
# puts "# #" | |
# puts "# [POLICY] Only ssh protocol is allowed #" | |
# puts "# #" | |
# puts "#############################################################" | |
# exit 1 | |
# end | |
puts "Enforcing Policies..." | |
puts "(#{$refname}) (#{$oldrev}) (#{$newrev})" | |
# $regex = /\[ref: (\d+)\]/ | |
$regex = /(ProjectA\-|Merge|Revert).*/ | |
# enforced custom commit message format | |
def check_message_format | |
# puts "#{Dir.pwd}" | |
if "0000000000000000000000000000000000000000" == $oldrev | |
# $oldrev = `git rev-list --boundary #{$newrev} --not --all | sed -n 's/^-//p'`.split("\n")[0] | |
# missed_revs = `git rev-list #{$newrev} --not --branches=*`.split("\n") | |
missed_revs = `git rev-list $(git for-each-ref --format='%(refname)' refs/heads/* | sed 's/^/\^/') "#{$newrev}"`.split("\n") | |
else | |
missed_revs = `git rev-list #{$oldrev}..#{$newrev}`.split("\n") | |
end | |
puts "Commits to check: #{missed_revs}" | |
missed_revs.each do |rev| | |
# puts "git cat-file commit #{rev} | sed '1,/^$/d'" | |
message = `git cat-file commit #{rev} | sed '1,/^$/d'` | |
if !$regex.match(message) | |
puts "#############################################################" | |
puts "# #" | |
puts "# [POLICY] Your commit message doesn't have ticket number #" | |
puts "# Wrong message: #{message} #" | |
puts "# #" | |
puts "#############################################################" | |
exit 1 | |
end | |
end | |
end | |
check_message_format |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment