infantDev infantDev - 6 months ago 24
Git Question

How do I set a pattern for git commit messages?

I want to restrict the people whoever commits to have a specific commit message format, how do I do that?

For example:



There is a pre-commit-msg or commit-msg hook, that you could use:

Git repos come with sample hooks, e.g. the sample commit-msg hook under git/hooks/commit-msg.sample catches duplicate Signed-off-by lines.

# This example catches duplicate Signed-off-by lines.

test "" = "$(grep '^Signed-off-by: ' "$1" |
    sort | uniq -c | sed -e '/^[   ]*1[    ]/d')" || {
    echo >&2 Duplicate Signed-off-by lines.
    exit 1

To enable a hook, don't forget to make it executable.


Here's some fictional example, which would only accept commit messages of the london|120|something ... and the like:

#!/usr/bin/env ruby
message_file = ARGV[0]
message =

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

PAIRS = ["london", "paris", "moscow"] # only these names allowed
STORIES = "\d{2,4}"                   # story must be a 2, 3 or 4 digit number
MESSAGE = ".{5,}"                     # message must be at least 5 chars long

$regex = "( (#{PAIRS.join('|')})\|#{STORIES}\|#{MESSAGE} )"

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

In usage:

$ git ci -m "berlin|120"
[POLICY] Your message is not formatted correctly
$ git ci -m "london|120|XX"    
[POLICY] Your message is not formatted correctly
$ git ci -m "london|120|Looks good."    
[master 853e622] london|120|Looks good.
 1 file changed, 1 insertion(+)