DEV Community

Discussion on: Gated Commits with Git

Collapse
 
david_ojeda profile image
David Ojeda

For your first question there is a simple solution that can help you. Use the command git commit without specifying anything else. The hook will run and, if tests passes, your default editor will open for you to write your commit message details.

For your bonus question, it is indeed possible. There is a Git hook called commit-msg that allows you to check your commit message format. This is an example from the Git documentation (this would go into a 'commit-msg' file in your .git/hooks folder as well):

#!/usr/bin/env ruby
message_file = ARGV[0]
message = File.read(message_file)

$regex = /\[ref: (\d+)\]/

if !$regex.match(message)
  puts "[POLICY] Your message is not formatted correctly"
  exit 1
end

The commit will fail if the message does not match the defined regex. This hook is written in Ruby, but you can also use a Bash script if you want to.

Here is another tip: it can happen that your tests passes, but then your commit message format is incorrect. So, you need to change the format and then commit again, which means that you also wait for tests to finish, yet again. You can skip the tests with the option --no-verify. Just make sure to use this option once you are sure all tests have passed ๐Ÿ™ƒ