环境

git : git version 2.15.0
java: 1.8+

背景

虽然项目中引入了checkstyle,并且编译时,会进行检查报错。但是每次走到项目编译时,其实已经有点晚了,来不及了。
所以需要在git commit 之前进行检查,这样效果会更好些。

前提条件:你已经在项目中配置了checkstyle

配置步骤

在路径:项目名/.git/hooks/下,放两个文件:

  1. 创建名为:pre-commit的脚本。
  2. checkstyle-8.41.1-all.jar 文件。
    https://search.maven.org/artifact/com.puppycrawl.tools/checkstyle/8.41.1/jar
    右上角有Downloads下载按钮。

pre-commit脚本

存放路径:项目名/.git/hooks/目录下:
下列脚本做了优化, 网上的是循环遍历每个Java文件,优化后是:循环拼接好Java文件后,一次性checkstyle全部的修改文件。目的是为了加快checkstyle速度。因为当文件修改很多的情况下,循环checkstyle超级慢。

#!/bin/bash
#@author:yutao#
#@func:pre-commit#
## cp ./check-style/pre-commit ./.git/hooks/

# 一个打印函数,前后加空行
function print(){
    echo ""
echo "===========$*============"
echo ""
}

print "避免NPE是程序员的基本修养!"
print "开始style checking"

wd=`pwd`
print "当前工作目录:$wd"

check_jar_path="$wd/.git/hooks/checkstyle-8.41.1-all.jar"
check_xml_path="$wd/checkstyle.xml"

# echo $check_jar_path $check_xml_path

# 清空temp文件
rm -rf temp

is_err=0
is_warn=0

path=''
for file in `git status --porcelain | sed s/^...// | grep '\.java$' | grep -v 'test'`;
do
path+="$wd/$file "
done
#print "检查文件:$path"
if [ "x${path}" != "x" ];then
  print "检查文件:$path"
  re=`java -jar $check_jar_path -c $check_xml_path $path >> temp`
  err=`cat temp | grep "ERROR"`
  warn=`cat temp | grep "WARN"`
  info=`cat temp`
  if [[ $err = *"ERROR"* ]];then
    print $err
    is_err=1
  fi
  if [[ $warn = *"WARN"* ]];then
    print $warn
    is_warn=1
  fi
fi
print "检查完成,祝你好运"

rm -rf temp

if [ $is_err -ne 0 ] || [ $is_warn -ne 0 ]
then
print "请先符合style才能提交!"
exit 1
fi

exit 0

checkstyle-8.41.1-all.jar

这个jar包存放的路径项目名/.git/hooks/下。

修改pre-commit 脚本权限

chmod 755 pre-commit

校验

虽然写出不规范的代码;
然后执行git commit -am "fix:测试效果"

在这里插入图片描述

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐