Add commit message validator using Ruby and Lefthook
Ensuring that commit messages follow a consistent pattern is important for any software development workflow. It streamlines the process of identifying and understanding the changes made during the project's lifecycle. In this article, we'll explore how to add a commit message validator using Ruby and git hooks manager - Lefthook. Let's start with creating a new file in your_project_folder/.hooks/lint_commit_msg.rb
# .hooks/lint_commit_msg.rb
# Import required library
require 'fileutils'
def validate_commit_msg
# Get the current directory
root_dir = FileUtils.pwd
# Get the commit file
commit_file = File.join(root_dir, '.git/COMMIT_EDITMSG')
commit_message = File.read(commit_file) if File.exist?(commit_file)
valid_tags = %w[ci docs feat fix perf refactor style test]
# Define a regex pattern
reg_exp = Regexp.new("(#{valid_tags.join('|')}):\\s*.+")
if commit_message
valid = commit_message.match?(reg_exp)
if valid
puts '👍 Nice commit message!'
else
puts '👎 Bad commit message!'
puts "Your commit message: '#{commit_message.strip}'"
puts "The commit message does not follow the required format: 'type: description'"
puts "Type can be one of the following: #{valid_tags.join(', ')}"
puts 'Description should be a brief summary of the changes made.'
exit(1)
end
else
puts 'Commit message file does not exist'
exit(1)
end
end
validate_commit_msg
This script checks commit messages to see if they match a certain format: type: description
. Where type
can be any of the predefined list: ci, docs, feat, fix, perf, refactor, style, test
. This follows the popular structure in the Git community. For example, this commit will be valid feat: Add query param to users API
. You can change the validator to your needs based on that code from above with ease.
Integrating with Lefthook
To run this Ruby script on every commit, we will use a Git hook tool called Lefthook. Make sure you installed that tool already. Then let's edit or create a lefthook.yml
file in your project root directory with the following content:
# lefthook.yml
commit-msg:
commands:
lint-commit-msg:
run: ruby .hooks/lint_commit_msg.rb
Lefthook triggers the appropriate git hook each time you execute an appropriate Git command. In our case, whenever a commit is made, the lefthook will trigger our validate_commit_msg
function and check if the commit message follows the expected format.
Summary
This article provided a brief tutorial on using Ruby and Lefthook to validate commit messages in a software development project. Commit message validation is an important aspect of maintaining a clean and understandable commit history, and with tools like Ruby and Lefthook, implementing such validation becomes a straightforward task without additional external tools or libraries. From this step, it is easy to implement any automated release process, or simply make your commit history much cleaner.
Happy coding!