git hooks

Githooks easily makes our team's code more robust, example below will records some situations of usage.

standard commit msg

filepath to edit: '.git/hooks/commit-msg'

test "" != "$(grep '[A-Z0-9]\+-[0-9]\+ ' "$1")" || {
        echo >&2 "ERROR: Commit message 的格式为: JIRA任务编号 任务名称"
        exit 1

prevent conflicts to be commited

filepath to edit: '.git/hooks/pre-commit'

emsg=$(git diff --check --cached)
if git diff --check --cached | grep -qE 'conflict\smarker';then
    echo -e "请检查有未解决冲突的代码进行提交:\n${emsg}"
    exit 1

using script

as git hook file would not keep track on by git history, you cannot share them between your team members. therefore, I prepared a shell script to do it just by adding this script file into your repository root, and then this file can be shared.

echo "start to create git hooks"

touch $fileCommitMsg
echo "#!/bin/bash" >$fileCommitMsg
echo "test \"\" != \"\$(grep '[A-Z0-9]\\+-[0-9]\\+ ' \"\$1\")\" || {" >>$fileCommitMsg
echo "    echo >&2 \"ERROR: Commit message 的格式为: JIRA任务编号 任务名称\"" >>$fileCommitMsg 
echo "    exit 1" >>$fileCommitMsg
echo "}" >> $fileCommitMsg
chmod +x $fileCommitMsg
echo "finish commit-msg hook"

touch $filePreCommit
echo "#!/bin/bash" >$filePreCommit
echo "emsg=\$(git diff --check --cached)" >>$filePreCommit
echo "if git diff --check --cached | grep -qE 'conflict marker'; then" >>$filePreCommit
echo "   echo -e \"请检查有未解决冲突的代码进行提交:\\n\${emsg}\"" >>$filePreCommit
echo "   exit 1" >>$filePreCommit
echo "fi" >>$filePreCommit
chmod +x $filePreCommit
echo "finish pre-commit hook"

exit 1

to be continue