Contents

Git - Validate commit message - git hooks

enforce commit messages in git repo

To enforce commit messages in git repo to follow specific format or pattern. This can be achieve by using git-hooks, where the commit message is formatted with the help of commit-msg hook. commit-msg hook will be trigger on each commit.

First go to git repo which needs the validator, then create commit-msg hook file in .git/hooks folder

1
2
3
cd <path-to-git-repo-to-install-commit-message-validator>

touch .git/hooks/commit-msg

Modify permission to make the hook executable

1
chmod +x .git/hooks/commit-msg

Open commit-msg file in a editor and add the following lines of script.

1
2
3
4
5
6
7
8
9
#!/usr/bin/env ruby
message_file = ARGV[0]
message = File.read(message_file)
$regex = /((\w):\s(\w))/i 
if !$regex.match(message) 
  puts "[POLICY] Your message is not formatted correctly" 
  puts "[STANDARD] Your message should be in the format: ‘committer_name: commit message’" 
  exit 1
end

Create hook installer

A simple hook installer can be created as follows, here I have used quite a complex pattern.

Customize the $regex found in the script as per need. Existing regex is designed to handle PROJECT-#### [committer_name_1|committer_name_2] commit message pattern, which can be replaced.

To install commit-msg-validator.sh use the following commands

1
2
3
4
5
6
7
cd <path-to-git-repo-to-install-commit-message-validator>

wget https://raw.githubusercontent.com/ImShakthi/hackrator/master/git-hooks/commit-msg-validator.sh

chmod +x commit-msg-validator.sh

sh commit-msg-validator.sh

Hola, commit message validator would be installed successfully.