CheckStyle Git hook 简单配置

本次配置 Githook主要有以下几个操作步骤

  1. 下载Checkstyle jar包 官网地址,GitHulb,目前最近版本为checkstyle-8.12-all.jar

  2. 下载对应的规范约束xml文件,目前主要是有两种sun_checks.xml google_checks.xml

  3. 根据官网上的介绍以命令行形式试着执行一次,以下是官网上的命令行demo

java -jar checkstyle-8.12-all.jar -c /sun_checks.xml MyClass.java
java -jar checkstyle-8.12-all.jar -c /google_checks.xml MyClass.java
  • 下面是在我本机电脑上的执行情况
java -jar ~/Desktop/checkstyle-8.12-all.jar -c ~/Desktop/sun_checks.xml config/config-client/src/main/java/learnspring/configclient/health/MyHealthIndicator.java
开始检查……
[ERROR] /Users/chenmingming/workspace/java/my/spring-cloud/config/config-client/src/main/java/learnspring/configclient/health/MyHealthIndicator.java:20:13: 名称 'a_s1l11' 必须匹配表达式: '^[a-z][a-zA-Z0-9]*$' 。 [LocalVariableName]
检查完成。
Checkstyle以 1 个错误结束。

[LocalVariableName] 是错误的项目,具体项目配置可以参考如下 sun_checks.xml

<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
          "-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
          "https://checkstyle.org/dtds/configuration_1_3.dtd">

<!--
  Checkstyle configuration that checks the sun coding conventions from:
    - the Java Language Specification at
      http://java.sun.com/docs/books/jls/second_edition/html/index.html
    - the Sun Code Conventions at http://java.sun.com/docs/codeconv/
    - the Javadoc guidelines at
      http://java.sun.com/j2se/javadoc/writingdoccomments/index.html
    - the JDK Api documentation http://java.sun.com/j2se/docs/api/index.html
    - some best practices
  Checkstyle is very configurable. Be sure to read the documentation at
  http://checkstyle.sf.net (or in your downloaded distribution).
  Most Checks are configurable, be sure to consult the documentation.
  To completely disable a check, just comment it out or delete it from the file.
  Finally, it is worth reading the documentation.
-->

<module name="Checker">
    <!--
        If you set the basedir property below, then all reported file
        names will be relative to the specified directory. See
        http://checkstyle.sourceforge.net/5.x/config.html#Checker

        <property name="basedir" value="${basedir}"/>
    -->

    <property name="fileExtensions" value="java, properties, xml"/>

    <!-- Checks that a package-info.java file exists for each package.     -->
    <!-- See http://checkstyle.sf.net/config_javadoc.html#JavadocPackage -->
    <!-- <module name="JavadocPackage"/>-->


    <!-- Checks whether files end with a new line.                        -->
    <!-- See http://checkstyle.sf.net/config_misc.html#NewlineAtEndOfFile -->
    <!-- 检查空行结束 -->
    <!-- <module name="NewlineAtEndOfFile"/> -->

    <!-- Checks that property files contain the same keys.         -->
    <!-- See http://checkstyle.sf.net/config_misc.html#Translation -->
    <module name="Translation"/>

    <!-- Checks for Size Violations.                    -->
    <!-- See http://checkstyle.sf.net/config_sizes.html -->
    <!-- 文件长度不超过1500行 -->
    <module name="FileLength">
        <property name="max" value="2500"/>
    </module>
    

    <!-- Checks for whitespace                               -->
    <!-- See http://checkstyle.sf.net/config_whitespace.html -->
    <!-- 检查文件中是否含有'\t' -->
    <!-- <module name="FileTabCharacter"/> -->

    <!-- Miscellaneous other checks.                   -->
    <!-- See http://checkstyle.sf.net/config_misc.html -->
    <!-- 正则表表达式 -->
    <module name="RegexpSingleline">
       <property name="format" value="\s+$"/>
       <property name="minimum" value="0"/>
       <property name="maximum" value="0"/>
       <property name="message" value="Line has trailing spaces."/>
    </module>

    
    <!-- Checks for Headers                                -->
    <!-- See http://checkstyle.sf.net/config_header.html   -->
    <!-- <module name="Header"> -->
    <!--   <property name="headerFile" value="${checkstyle.header.file}"/> -->
    <!--   <property name="fileExtensions" value="java"/> -->
    <!-- </module> -->
    <!-- 每个java文件一个语法树 -->
    <module name="TreeWalker">

        <!-- 主要检查 Javadoc -->
        <!-- Checks for Javadoc comments.                     -->
        <!-- See http://checkstyle.sf.net/config_javadoc.html -->
        <!-- 检查方法和构造函数的javadoc -->
        <!-- <module name="JavadocMethod"/> -->
        
        <!-- 检查类和接口的javadoc。默认不检查author和version tags -->
        <!-- <module name="JavadocType"/> -->
        
        <!-- 检查变量的javadoc -->
        <!-- <module name="JavadocVariable"/> -->
        
        <!-- 检查javadoc的格式 -->
        <!-- <module name="JavadocStyle"/> -->


        <!--  主要检查 Java 代码 -->
        <!-- Checks for Naming Conventions.                  -->
        <!-- See http://checkstyle.sf.net/config_naming.html -->
        <!-- 常量名的检查(只允许大写),默认^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$ -->
        <module name="ConstantName"/>
        
        <!-- 本地常量 -->
        <module name="LocalFinalVariableName"/>
        
        <!-- 局部的非final型的变量,包括catch中的参数的检查 -->
        <module name="LocalVariableName"/>
        
        <!-- 非static型变量的检查 -->
        <module name="MemberName" />
        
        <!-- 方法名的检查 -->
        <module name="MethodName"/>
        
        <!-- 包名的检查(只允许小写字母),默认^[a-z]+(\.[a-zA-Z_][a-zA-Z_0-9_]*)*$ -->
        
        <module name="PackageName"/>
        <!-- 方法的参数名 -->
        
        <module name="ParameterName"/>
        
        <!-- 仅仅是static型的变量(不包括static final型)的检查 -->
        <module name="StaticVariableName"/>

        <!-- Class或Interface名检查,默认^[A-Z][a-zA-Z0-9]*$-->
        <module name="TypeName"/>


        <!-- import检查-->
        <!-- Checks for imports                              -->
        <!-- See http://checkstyle.sf.net/config_import.html -->
        <!-- 避免使用* -->
        <module name="AvoidStarImport"/>
        
        <!-- 检查是否从非法的包中导入了类 -->
        <module name="IllegalImport"/> <!-- defaults to sun.* packages -->
        
        <!-- 检查是否导入了多余的包 -->
        <module name="RedundantImport"/>

        <!-- 没用的import检查,比如:1.没有被用到2.重复的3.import java.lang的4.import 与该类在同一个package的 -->
        <module name="UnusedImports">
            <property name="processJavadoc" value="false"/>
        </module>

        
        <!-- 代码长度检查 -->
        <!-- Checks for Size Violations.                    -->
        <!-- See http://checkstyle.sf.net/config_sizes.html -->
        <!-- 每行不超过150个字符 -->
        <module name="LineLength">
            <property name="max" value="150" />
        </module>
        
        <!-- 方法不超过150行 -->
        <module name="MethodLength">
            <property name="tokens" value="METHOD_DEF" />
            <property name="max" value="150" />
        </module>
        <!-- 方法的参数个数不超过5个。 并且不对构造方法进行检查-->
        <module name="ParameterNumber">
            <property name="max" value="10" />
            <property name="ignoreOverriddenMethods" value="true"/>
            <property name="tokens" value="METHOD_DEF" />
        </module>
        

        <!-- Checks for whitespace                               -->
        <!-- See http://checkstyle.sf.net/config_whitespace.html -->
        
        <module name="EmptyForIteratorPad"/>
        <!-- 检查尖括号 -->
        <module name="GenericWhitespace"/>
        
        <!-- 方法名后跟左圆括号"(" -->
        <module name="MethodParamPad"/>

        <!-- 检查在某个特定关键字之后应保留空格 -->
        <module name="NoWhitespaceAfter"/>

        <!-- 检查在某个特定关键字之前应保留空格 -->
        <module name="NoWhitespaceBefore"/>
        
        <!-- 操作符换行策略检查 -->
        <module name="OperatorWrap"/>
        
        <!-- 圆括号空白 -->
        <!-- <module name="ParenPad"/> -->
        <!-- <module name="TypecastParenPad"/> -->
        <!-- <module name="WhitespaceAfter"/> -->
        <!-- <module name="WhitespaceAround"/> -->

        <!-- Modifier Checks                                    -->
        <!-- See http://checkstyle.sf.net/config_modifiers.html -->
        <!-- 修饰符检查 -->
        <!-- 检查修饰符的顺序是否遵照java语言规范,默认public、protected、private、abstract、static、final、trans-->

        <!-- Checks for blocks. You know, those {}'s         -->
        <!-- See http://checkstyle.sf.net/config_blocks.html -->
        <!-- <module name="AvoidNestedBlocks"/> -->
        <!-- <module name="EmptyBlock"/> -->
        <!-- <module name="LeftCurly"/> -->
        <!-- <module name="NeedBraces"/> -->
        <!-- <module name="RightCurly"/> -->

        <!-- 代码问题检查 -->
        <!-- Checks for common coding problems               -->
        <!-- See http://checkstyle.sf.net/config_coding.html -->
        <!-- 避免内联条件 -->
        <module name="AvoidInlineConditionals"/>
        <!-- 检查空的代码段 -->
        <module name="EmptyStatement"/>

        <!-- 检查在重写了equals方法后是否重写了hashCode方法 -->
        <module name="EqualsHashCode"/>
        
        <!-- 检查局部变量或参数是否隐藏了类中的变量 -->
        <!-- <module name="HiddenField"/> -->
        
        <!-- 检查是否使用工厂方法实例化 -->
        <module name="IllegalInstantiation"/>

        <!-- 检查子表达式中是否有赋值操作 -->
        <module name="InnerAssignment"/>

        <!-- 魔法值 -->
        <module name="MagicNumber"/>

        <!-- 检查switch语句是否有default -->
        <module name="MissingSwitchDefault"/>

        <!-- 检查是否有过度复杂的布尔表达式 -->
        <module name="SimplifyBooleanExpression"/>

        <!-- 检查是否有过于复杂的布尔返回代码段 -->
        <module name="SimplifyBooleanReturn"/>

        <!-- 类设计检查 -->
        <!-- Checks for class design                         -->
        <!-- See http://checkstyle.sf.net/config_design.html -->
        <!-- 检查类是否为扩展设计l -->
        <!-- <module name="DesignForExtension"/> -->
        <!-- 检查只有private构造函数的类是否声明为final -->
        <module name="FinalClass"/>
        <!-- 检查工具类是否有public的构造器 -->
        <module name="HideUtilityClassConstructor"/>
        <!-- 检查接口是否仅定义类型 -->
        <module name="InterfaceIsType"/>
        <!-- 检查类成员的可见度 -->
        <module name="VisibilityModifier"/>

        <!-- Miscellaneous other checks.                   -->
        <!-- See http://checkstyle.sf.net/config_misc.html -->
        <!-- 检查数组类型定义的样式 -->
        <module name="ArrayTypeStyle"/>
        <!-- 检查方法名、构造函数、catch块的参数是否是final的 -->
        <!-- <module name="FinalParameters"/> -->
        <!-- //TODO -->
        <module name="TodoComment"/>
        <!-- 检查long型定义是否有大写的“L” -->
        <module name="UpperEll"/>

    </module>

</module>
  1. 编写Git hook脚本 这里我基本是网上抄袭的一段 Python脚本
#! /usr/bin/env python
# -*- encoding: utf-8 -*-

import sys,os,re

print '\n.......................Code Style Checking....................\n'

#the count of level, like ERROR,WARN
def get_level(content, level):
    return len(re.compile(r"\[%s\]" % level).findall(content))

#get the commit file name (whole path)
def get_file_name(content, postfix=None):
    content = content.replace("\t", " ")
    line_divided = content.split("\n")
    space_divided = [[j for j in i.split(" ") if j.strip()]for i in line_divided]
    filenames = [i[5] for i in space_divided if i]
    if not postfix:
        return filenames
    return [i for i in filenames if ".%s" % postfix in i]

jarpath = os.popen('git config --get checkstyle.jar').read()
checkfilepath = os.popen('git config --get checkstyle.checkfile').read()

#check code command
command = 'java -jar ' + jarpath[:-1] + ' -c ' + checkfilepath[:-1]

#the file to check
files = os.popen('git diff-index --cached HEAD').read()

#the result of command
content = get_file_name(files, 'java')

resultsum = 0

for i in content:
    result = os.popen(command + ' ' + i).read()
    print result
    resultsum += get_level(result,'ERROR')
    resultsum += get_level(result,'WARN')

if resultsum > 0:
    print '\n.......................You must fix the errors and warnings first, then excute commit command again...........\n'
    sys.exit(-1)
else:
    print '\n.................................Code is very good...................\n'
    sys.exit(0)

将这段脚本改名为对应的Git 操作时间如 pre-commit pre-push,放在项目的 .git/hooksd的文件下, 然后将、对应之前的xxx.sample文件移除或改名,再将此脚本文件 chmod 777 升级为可执行即可

  1. 最将IDE 安装上 checkstyle 插件,plugin 安装搜索安装即可
  2. 下面就是我安装了一个 pre-commit的脚本执行结果如下,在我commit之前进行代码格式化校验,检查不符合规范则commit失败
➜  spring-cloud git:(master) ✗ git commit -am "cs2"

.......................Code Style Checking....................

开始检查……
[ERROR] /Users/chenmingming/workspace/java/my/spring-cloud/config/config-client/src/main/java/learnspring/configclient/health/MyHealthIndicator.java:20:13: 名称 'a_s1l11' 必须匹配表达式: '^[a-z][a-zA-Z0-9]*$' 。 [LocalVariableName]
检查完成。
Checkstyle以 1 个错误结束。


.......................You must fix the errors and warnings first, then excute commit command again...........
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值