0

I want to do configuration in GIT that will enforce all commit messages to follow certain pattern. How can I do that?

EDIT: I want it for Github.

pooja jain
  • 11
  • 3
  • 1
    Shor answer: Overwrite (or create) one of the scripts in .git/hooks and make it executable. Check this out for more info: https://githooks.com/ – cavalcantelucas Jul 15 '21 at 06:58
  • @lucascavalcante This will enforce only me for all my branches to have proper commit messages. I want to set up something globally that restricts everyone. – pooja jain Jul 16 '21 at 10:45

1 Answers1

0

The best way to do this is to set up a CI job that checks the commit messages and verifies they're in the format you want. In some environments, it's also possible to use a pre-receive hook, although that's not possible on github.com (but it is on GitHub Enterprise Server).

That command will look something like this:

#!/bin/sh

git rev-list $1 | \
  xargs -L1 sh -c 'git log --format=%B -1 $0 | grep -qs Signed-off-by'

In my case, I'm passing the command a range of commits on the branch (that is, in the form BASE..HEAD) and my check is verifying that each commit contains the text Signed-off-by. You can replace the grep command with whatever you like, provided it exits 0 if the commit message is acceptable and nonzero if it is not. Then, the script itself will exit 0 on success, and nonzero if the commits are unacceptable, and you can then reject the commits.

You may wish to help developers by offering them a commit-msg hook as well using a similar technique. However, as outlined in the Git FAQ, mandatory client-side hooks are both ineffective, since they can trivially be bypassed with the developer without anyone noticing, and also annoying to some advanced developers, so you should make them opt-in for those who want them.

bk2204
  • 64,793
  • 6
  • 84
  • 100