本文主要讲解关于git如何使用webhooks规范代码提交相关内容,让我们来一起学习下吧!

背景

最近在尝试使用git的webhooks在团队内推广和实施git规范,包括一些对commit message的校验、对分支名称的校验等。

由于使用的是内网开发,无法使用其他现成的规范,所以编写了相关的脚本。本文作为记录,接下来进行一个简要的分享。

本次编写了两个本地脚本,分别是commit-msg和pre-push,分别会在本地commit和push远程分支的时候做相应的校验。

commit-msg

commit-msg代码如下:

msg=`awk '{printf("%s", $0)}' $1` TYPE_LIST=( 'feat:' #新功能feature 'update:' #在feat内修改 'fix:' #修补bug 'docs:' #文档 'style:' #格式化,不影响代码运行的变动 'perf:' #性能优化 'delete:' #删除功能或文件 'modify:' #功能修改 'test:' #增加测试 ) COMMIT_MESSAGE_MIN_LENGTH=10 separator="|" tips_msg="$( printf "${separator}%s" "${TYPE_LIST[@]}" )" tips_msg=${tips_msg:${#separator}} echo 'Start commit-msg check:'$msg if [[ "${TYPE_LIST[@]}" =~ ${msg$:*} ]]; then msg_length=${#msg} if [[ ${msg_length} -lt ${COMMIT_MESSAGE_MIN_LENGTH} ]]; then echo -e "pre-commit Error: Commit message should be bigger than ${COMMIT_MESSAGE_MIN_LENGTH} and current commit message length: ${msg_length}" exit 1 fi echo "commit-msg: Commit comments validate Success!" else echo -e "commit-msg Error: Commit comments message should be started with [${tips_msg}]..." exit 1 fi 

脚本解读:主要是针对commit message的校验,校验message的前缀以及长度(至少10个字符)是否符合规范

pre-push

pre-push代码如下:

remote="$1" url="$2" z40=0000000000000000000000000000000000000000 TYPE_LIST=( 'feature' #新功能分支 'hotfix' #热修复分支 ) separator="|" tips_msg="$( printf "${separator}%s" "${TYPE_LIST[@]}" )" tips_msg=${tips_msg:${#separator}} # 当前分支 branch=$(git rev-parse --abbrev-ref HEAD) echo 'Start pre-push check:' echo "current local branch is ${branch}" while read local_ref local_sha remote_ref remote_sha do for element in "${TYPE_LIST[@]}" do if [[ ${element} == ${branch%%_*} ]]; then echo "pre-push: Push Success!" exit 0 fi done done 

脚本解读:主要是针对本地分支的命名做校验,校验分支名称的前缀是否符合规范

以上就是关于使用git如何使用webhooks规范代码提交相关的全部内容,希望对你有帮助。欢迎持续关注潘子夜个人博客(www.frpkj.com),学习愉快哦!