How do I set a pattern for git commit messages?
Asked Answered
T

2

13

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

For example: Pair_Name|Story_Number|Commit_Message

Trodden answered 4/1, 2013 at 5:50 Comment(0)
S
13

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 = File.read(message_file)

# $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
end

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(+)
Swale answered 4/1, 2013 at 5:53 Comment(0)
S
1

Note: this kind of restriction is part of gitolite as well (an authorization layer that allows all sort of checks when pushing to a repo)

You can see one example at "git gitolite (v3) pre-receive hook for all commit messages".

The idea with gitolite is that you can easily deploy that hook on specific repos, for specific groups of users.

Stambaugh answered 4/1, 2013 at 7:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.