Skip to content

Instantly share code, notes, and snippets.

@ainformatico
Last active December 14, 2015 02:19
Show Gist options
  • Save ainformatico/5012957 to your computer and use it in GitHub Desktop.
Save ainformatico/5012957 to your computer and use it in GitHub Desktop.
Validator for commit messages when creating a new commit. You should rename the ruby file as `commit-msg` and place it in `repo/.git/hooks` and do not forget `chmod +x commit-msg`

Checkmmit

Validator for commit messages when creating a new commit.

Install

Rename the other attached file as commit-msg and place it in repo/.git/hooks do not forget chmod +x commit-msg if needed.

Add your own validations

Checkmmit.add_validation /foo/, "Does not contain foo text"
Checkmmit.add_validation /bar/, "Needs foo(because it's defined above) and bar"

Author

Alejandro El Informático

#!/usr/bin/env ruby
# @author Alejandro El Informático
#
# @description validator for commit messages when creating a new commit
# you should rename this file as `commit-msg` and place it in `repo/.git/hooks`
# do not forget `chmod +x commit-msg` if needed
#
# @created 20130222
#
class Checkmmit
attr_reader :result
def initialize opts
@config =
{
:file => ''
}.merge(opts)
defaults
@data = get_data
@result = 0
end
# get the validations
def self.validations
@validations
end
# add a new validation
def self.add_validation(regex, message)
@validations ||= []
@validations << {:regex => regex, :message => message}
end
# set default validations
def defaults
Checkmmit.add_validation /^(CHANGE|FIX|ADD|MERGE|Merge)\s/, "Message *must* start with CHANGE, FIX, ADD or MERGE"
end
# check validations
def check!
check_message
@result
end
# print a message
def pretty_print message
puts message
end
private
# check the message and set the return code
def check_message
Checkmmit.validations.each do |validation|
unless @data.match validation[:regex]
pretty_print validation[:message]
@result = 1
break
end
end
end
# get data from file
def get_data
@data = File.read(File.expand_path(@config[:file]))
end
end
# add your own validations here
# example:
# Checkmmit.add_validation /foo/, "Does not contain foo text"
# Checkmmit.add_validation /bar/, "Needs foo(because it's defined above) and bar"
#
####### WARNING: DO NOT CHANGE ANYTHING BELOW THIS LINE
raise ArgumentError unless ARGV.count == 1
#dear maintainer, git is passing the temporal filename that includes the commit message as ARGV[0]
validator = Checkmmit.new({:file => ARGV[0]})
# 0 = success
# 1 = error
exit validator.check!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment