How do I set a pattern for git commit messages?

2020-07-06 07:44发布

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

标签: git
2条回答
时光不老,我们不散
2楼-- · 2020-07-06 08:14

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.

查看更多
太酷不给撩
3楼-- · 2020-07-06 08:28

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(+)
查看更多
登录 后发表回答