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






<module name="Checker">
    

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

    
    
    


    
    
    
    

    
    
    <module name="Translation"/>

    
    
    
    <module name="FileLength">
        <property name="max" value="2500"/>
    module>
    

    
    
    
    

    
    
    
    <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>

    
    
    
    
    
    
    
    
    <module name="TreeWalker">

        
        
        
        
        
        
        
        
        
        
        
        
        
        


        
        
        
        
        <module name="ConstantName"/>
        
        
        <module name="LocalFinalVariableName"/>
        
        
        <module name="LocalVariableName"/>
        
        
        <module name="MemberName" />
        
        
        <module name="MethodName"/>
        
        
        
        <module name="PackageName"/>
        
        
        <module name="ParameterName"/>
        
        
        <module name="StaticVariableName"/>

        
        <module name="TypeName"/>


        
        
        
        
        <module name="AvoidStarImport"/>
        
        
        <module name="IllegalImport"/> 
        
        
        <module name="RedundantImport"/>

        
        <module name="UnusedImports">
            <property name="processJavadoc" value="false"/>
        module>

        
        
        
        
        
        <module name="LineLength">
            <property name="max" value="150" />
        module>
        
        
        <module name="MethodLength">
            <property name="tokens" value="METHOD_DEF" />
            <property name="max" value="150" />
        module>
        
        <module name="ParameterNumber">
            <property name="max" value="10" />
            <property name="ignoreOverriddenMethods" value="true"/>
            <property name="tokens" value="METHOD_DEF" />
        module>
        

        
        
        
        <module name="EmptyForIteratorPad"/>
        
        <module name="GenericWhitespace"/>
        
        
        <module name="MethodParamPad"/>

        
        <module name="NoWhitespaceAfter"/>

        
        <module name="NoWhitespaceBefore"/>
        
        
        <module name="OperatorWrap"/>
        
        
        
        
        
        

        
        
        
        

        
        
        
        
        
        
        

        
        
        
        
        <module name="AvoidInlineConditionals"/>
        
        <module name="EmptyStatement"/>

        
        <module name="EqualsHashCode"/>
        
        
        
        
        
        <module name="IllegalInstantiation"/>

        
        <module name="InnerAssignment"/>

        
        <module name="MagicNumber"/>

        
        <module name="MissingSwitchDefault"/>

        
        <module name="SimplifyBooleanExpression"/>

        
        <module name="SimplifyBooleanReturn"/>

        
        
        
        
        
        
        <module name="FinalClass"/>
        
        <module name="HideUtilityClassConstructor"/>
        
        <module name="InterfaceIsType"/>
        
        <module name="VisibilityModifier"/>

        
        
        
        <module name="ArrayTypeStyle"/>
        
        
        
        <module name="TodoComment"/>
        
        <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...........

你可能感兴趣的:(CheckStyle Git hook 简单配置)