1. commit规范

每个公司的规范都是不同的,这里讲下我常用的规范
type(模块): message

type

用于说明 commit的类别,只允许使用下面7个标识。

  • feat:新功能(feature)
  • fix:修补bug
  • hotfix:紧急修复bug
  • test:增加测试
  • docs:文档(documentation)
  • style: 格式(不影响代码运行的变动)
  • refactor:重构(即不是新增功能,也不是修改bug的代码变动)
  • chore:构建过程或辅助工具的变动

举个例子,我新增了用户登录功能,那么提交信息应该这样写:

git commit -m "feat(user): add the user login"

2. 使用git hooks校验

.git/hooks目录下有很多钩子,我们可以根据需要自定义不同的内容,这里我们只需要修改commit-msg即可。

首先将commit-msg.sample 改为 commit-msg,也就是去掉后缀。
将里面的内容修改为下面内容

#!/bin/bash
MSG=`awk '{printf("%s",$0)}' $1`
if [[ $MSG =~ ^(feat|fix|test|refactor|docs|style|chroe)\(.*\):.*$ ]]
then
	echo -e "\033[32m commit success! \033[0m"
else
    echo -e "\033[31m Error: the commit message is irregular \033[m"
	echo -e "\033[31m Error: type must be one of [feat,fix,docs,style,refactor,test,chore] \033[m"
    echo -e "\033[31m eg: feat(user): add the user login \033[m"
	exit 1
fi

当我们提交不规范的commit信息时就会提醒用户,并终止此提交

2.1 全局hook

mkdir -p ~/.git_template/hooks
cp commit-msg ~/.git_template/hooks
git config --global init.templatedir ~/.git_template

3. gitlab ci 中校验

3.1 .gitlab-ci.yml

stages:
- lint

commit_msg:
  stage: lint
  script:
  - /bin/bash commit-msg.sh
  only:
  - pushes

3.2 commit-msg.sh

#! /bin/bash

# get commit msg
if [[ $CI_COMMIT_MESSAGE ]]; then
    msg=$CI_COMMIT_MESSAGE
else
    read msg < .git/COMMIT_EDITMSG
fi

echo -e "\033[33m The commit msg: \033[0m $msg"

# if the msg is merge then skip it
mergePattern='^Merge '
if [[ $msg =~ $mergeCommitPattern ]]; then
    echo -e "\033[32m skip the merge, commit success! \033[0m"
    exit 0
fi

# check the commit msg
maxLength=50
length=${#msg}
pattern='^(feat|fix|hotfix|test|refactor|docs|style|chroe)\(.*\):.*$'

if [[ $msg =~ $pattern ]]; then
    if [[ $length -gt $maxLength ]]; then
        echo -e "\033[31m Error: the msg over max length \033[m"
        exit 1
    fi
    echo -e "\033[32m commit success! \033[0m"
else
    echo -e "\033[31m Error: the commit message is irregular \033[m"
	echo -e "\033[31m Error: type must be one of [feat,fix,hotfix,docs,style,refactor,test,chore] \033[m"
    echo -e "\033[31m eg: feat(user): add the user login \033[m"
    exit 1
fi
Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐