Last active
August 29, 2015 13:57
-
-
Save tigerclaw-az/9817697 to your computer and use it in GitHub Desktop.
commit-msg hook for Git - Will validate certain criteria within the commit message
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 -w | |
# Called by "git commit" with one argument, the name of the file | |
# that has the commit message. The hook should exit with non-zero | |
# status after issuing an appropriate message if it wants to stop the | |
# commit. The hook is allowed to edit the commit message file. | |
msg_file = ARGV[0] | |
puts "Running hook: commit-msg" | |
FORBIDDEN = [ | |
/fixed/i, | |
/added/i, | |
/changed/i, | |
/updated/i, | |
/modified/i | |
] | |
$errors = [] | |
$first_line = -1 | |
$validTicket = 'ICPIM-\d+' | |
# This will not allow certain words in a commit message. | |
def invalid_words(str) | |
bad = [] | |
FORBIDDEN.each { |re| | |
bad.push("#{$1 || $&}") if str.match(re) | |
} | |
return bad | |
end | |
def line_too_long(str) | |
return true if str.length > 72 | |
return false | |
end | |
def jira_ticket(str) | |
STDIN.reopen('/dev/tty') | |
# This will enforce a JIRA ticket # to be on the first line of commit | |
if (str !~ /#{$validTicket}/mi) | |
print "\t\033[33mWARNING:You did not include a JIRA ticket. Continue?[yN]\033[0m " | |
if (STDIN.gets.chomp() !~ /^y(es)?/i) | |
# print "Enter JIRA ticket: " | |
# ticket = STDIN.gets.chomp() | |
# while ticket !~ /^#{$validTicket}$/ | |
# puts "Invalid format for JIRA ticket!" | |
# print "Enter JIRA ticket: " | |
# ticket = STDIN.gets.chomp() | |
# end | |
$errors.push("Please add a JIRA ticket to your commit message and try again.") | |
end | |
end | |
end | |
File.foreach(msg_file).with_index { |line, line_num| | |
line = line.strip | |
next if line.start_with?('#') || line.start_with?('Merge') | |
bad_words = invalid_words(line) | |
if !bad_words.empty? | |
$errors.push("ERROR #{line_num+1}: [POLICY] Invalid word(s): %s" % bad_words.join(',')) | |
end | |
if line_too_long(line) | |
$errors.push("ERROR #{line_num+1}: [POLICY] Lines cannot be longer than 72 characters.") | |
end | |
if line_num === 0 | |
$first_line = line | |
end | |
} | |
if $first_line != -1 | |
# Enforce a summary on the first line | |
if $first_line.match(/^#{$validTicket}:?$/) || $first_line.empty? | |
$errors.push("ERROR: [POLICY] The first line must have a summary.") | |
else | |
jira_ticket($first_line) | |
end | |
end | |
if !$errors.empty? | |
puts "\t\033[31mFAILED:\n \t%s\033[0m" % $errors.join("\n") | |
exit 1 | |
end | |
puts "\t\033[32mSUCCEEDED\033[0m" | |
exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment