I am using a node.js project and I need to use various application such as github, sourcetree, etc.. to checkout the git source. Is it possible to custom validate on git commit message and display the error message in all application when commit the changes?
I know there is a git hook 'commit-msg' available in git, but I don't know how to use it.
Here's a sample.
#!/bin/sh
path=$1
echo path is $path
a=$(cat $path)
echo commit message is
echo $a
if [[ "$a" =~ "hello world" ]];then
echo commit format test passed
exit 0
else
echo commit format test failed
exit 1
fi
Save it as a file named commit-msg
and make it executable and put it into .git/hooks/ .
This sample checks if the commit message has a sub string of "hello world". If it does, commit will success. If not, commit will fail.
Here's a python version
#!/usr/bin/python
import sys
path = sys.argv[1]
print "path is " + path
with open(path) as f:
lines = f.read()
print "commit message is"
print lines
if "hello world" in lines:
print "format test passed"
exit(0)
else:
print "format test failed"
exit(1)
You could improve this hook with your logic. You could check if .git/hooks/ has a commit-msg.sample
. If it does, you could read it as a reference. And you could just cp .git/hooks/commit-msg.smaple .git/hooks/commit-msg
and then edit it.
Besides, if you want to deploy this hook into every repo, you could copy this hook into /usr/share/git-core/templates/hooks if you are using Ubuntu. I have no idea what the default template path is in other systems. You may need to have a check. After doing so, when you git clone
, this hook will be copied into .git/hook/ . As to the repos that have existed, you could run git init
to copy the hook.
One more thing, if you don't want the hook to run, you could add the option --no-verify
or just -n
when git commit
, which also bypasses the hook pre-commit
if it exists.
As you mentioned you're on a Nodejs project, I'm assuming you have a package.json
. I suggest you taking a look at ghooks, validate-commit-msg, commitizen and conventional-changelog.
I realize that there's a lot of links here, but here's an example of all of that working together following AngularJS' commit convention:
package.json
:
"devDependencies": {
…
"commitizen": "2.8.1",
"cz-conventional-changelog": "1.1.6",
"ghooks": "1.3.2",
"validate-commit-msg": "2.6.1",
…
}
…
"config": {
"ghooks": {
"commit-msg": "validate-commit-msg"
},
"commitizen": {
"path": "node_modules/cz-conventional-changelog"
}
}
…
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With