Android git commit之前进行checkStyle检查

背景:开发的人员越来越多,水平习惯参差不齐,这就导致了代码的维护越来越复杂,所以希望有一个规范,可以规范大家的提交,所以出现了我所做的这个通过hook实现在代码commit之前进行检查。


实现效果:针对我所提交的代码进行checkStyle检查。


实现:

1.修改pre-commit文件。

在.git下面的hooks文件夹中增加pre-commit 文件,

修改权限chmod a+x pre-commit

#!/bin/sh
#
# An example hook script to verify what is about to be committed.
# Called by "git commit" with no arguments.  The hook should
# exit with non-zero status after issuing an appropriate message if
# it wants to stop the commit.
#
# To enable this hook, rename this file to "pre-commit".

if git rev-parse --verify HEAD >/dev/null 2>&1
then
    against=HEAD
else
    # Initial commit: diff against an empty tree object
    against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi

SCRIPT_DIR=$(dirname "$0")
SCRIPT_ABS_PATH=`cd "$SCRIPT_DIR"; pwd`
cd $SCRIPT_ABS_PATH/../../UCarNew/
cd ..
FILE_LIST=$(git status)
cd UCarNew
RESULT_INFO=$($SCRIPT_ABS_PATH/../../UCarNew/gradlew -Dorg.gradle.project.checkstyle="$FILE_LIST" checkstyle)
if [ $? -eq 0   ]; then
    echo "checkstyle OK"
else
    [[ $ERROR_INFO =~ "checkstyle" ]] && exit 1
fi
cd ..

2.在build.gradle文件中添加checkstyle的task

    task checkstyle(type :Checkstyle) {
        source 'src'
        source 'biz_mine'
        source 'base'
        source 'sdk'
        source 'thirdparty'
        source 'patch'
        source 'plugin'
        if(project.hasProperty('checkstyle')){
            def ft = fc(checkstyle);
            for(int i =0;i<ft.size();i++){
                String spliter = ft.getAt(i);
                String[] fileName = spliter.split("/");
                include '**/'+fileName[fileName.size()-1];
            }
        }
        exclude '**/gen/**'
        exclude '**/R.java'
        exclude '**/BuildConfig.java'
        configFile new File("$rootProject.rootDir/config/checkstyle","checkstyle.xml")
        classpath = files()
    }
def filterCommitter(String androidbootClassFiles){
    ArrayList<String> filterList = new ArrayList<String>();
    String [] files = androidbootClassFiles.split("\\n")
    for(String file : files){
        if(file.contains("UCarNew")){
            String[] b = file.split("modified:   ");
            filterList.add(b[1])
        }
    }
    return filterList;
}

ext {
    fc = this.&filterCommitter
}

这样就实现了我们需要的功能。

接下来还需要需改checkstyle的配置文件

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE module PUBLIC
    "-//Puppy Crawl//DTD Check Configuration 1.2//EN"
    "http://www.puppycrawl.com/dtds/configuration_1_2.dtd"><!-- 对于所有的模块来书,如果有这个模块则说明检测这一项,没有则不检测这一项 --><!-- 所有的模块中,其ROOT必须为Checker -->
<module name="Checker">
    <!-- 检验每个包是否存在package.html文件-->
    <!-- See http://checkstyle.sf.net/config_javadoc.html#PackageHtml -->
    <!--
    <module name="PackageHtml"/>
    -->
    <!-- 检验每个文件末尾是否有一个空行-->
    <!-- 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" />
    <module name="TreeWalker">
        <!-- Checks for Javadoc comments. -->
        <!-- See http://checkstyle.sf.net/config_javadoc.html -->
        <!-- Checks Javadoc comments for method definitions.-->
        <module name="JavadocMethod">
            <property name="scope" value="public" />
            <!-- 是否允许错误的参数声明,true为允许,缺省为不允许 -->
            <property name="allowMissingParamTags" value="true" />
            <!-- 是否允许错误的错误声明,true为允许,缺省为不允许 -->
            <property name="allowMissingThrowsTags" value="true" />
            <!-- 是否允许错误的返回类型声明,true为允许,缺省为不允许 -->
            <property name="allowMissingReturnTag" value="true" />
        </module>
        <!--Checks Javadoc comments for class and interface definitions.-->
        <module name="JavadocType" />
        <!-- Checks that variables have Javadoc comments.-->
        <module name="JavadocVariable">
            <property name="scope" value="protected" />
        </module>
        <!-- 检查Javadoc的格式 -->
        <module name="JavadocStyle">
            <property name="scope" value="public" />
            <!-- Comment的第一句的末尾是否要有一个句号,true必须有,default为true -->
            <property name="checkFirstSentence" value="false" />
            <!-- 检查错误的HTML脚本,比如不匹配,true检查,default为true -->
            <property name="checkHtml" value="true" />
        </module>
        <!-- Checks for Naming Conventions. -->
        <!-- See http://checkstyle.sf.net/config_naming.html -->
        <!-- 确省必须以Abstract开始或者以Factory结束 -->
        <!--
        <module name="AbstractClassName"/>
        -->
        <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" />
        <!-- Checks for Headers -->
        <!-- See http://checkstyle.sf.net/config_header.html -->
        <!-- 检查文件是否以指定文件开始,这里最好是放一些版权信息和工程描述 -->
        <!-- headerFile:指定的文件 -->
        <!-- ignoreLines:忽略哪些行,以","分隔 -->
        <!--
        <module name="Header">
        <property name="headerFile" value="java.header"/>
        <property name="ignoreLines" value="2, 3, 4, 5"/>
        </module>
        -->
        <!-- Following interprets the header file as regular expressions. -->
        <!--
        <module name="RegexpHeader"/>
        -->
        <!-- Checks for imports -->
        <!-- See http://checkstyle.sf.net/config_import.html -->
        <!-- 检查使用*号的导入,默认为全部类 -->
        <module name="AvoidStarImport" />
        <!-- 检查是否有非法的包,确省检查sun.*;对于某些包是不建议直接调用的 -->
        <module name="IllegalImport">
            <property name="illegalPkgs" value="sun.*" />
        </module>
        <!-- 检查多于的导入,如一个类导入了多次 -->
        <module name="RedundantImport" />
        <!-- 检查没有使用的导入 -->
        <module name="UnusedImports" />
        <!-- 导入排序 -->
        <!-- groups:分组,哪些是一组的 -->
        <!-- ordered:同一个组内是否排序,true排序,确省为true -->
        <!-- separated:各个组之间是否需要用空行分隔,确省为false -->
        <!-- caseSensitive:是否是大小写敏感的,确省是 -->
        <!--
        <module name="ImportOrder">
        <property name="groups" value="java,javax"/>
        <property name="ordered" value="true"/>
        <property name="separated" value="true"/>
        <property name="caseSensitive" value="true"/>
        </module>
        -->
        <!-- Checks for Size Violations. -->
        <!-- See http://checkstyle.sf.net/config_sizes.html -->
        <!-- 检查方法内可执行语句的个数,确省为30行 -->
        <!--
        <module name="ExecutableStatementCount">
        <property name="max" value="30"/>
        </module>
        -->
        <!-- 文件的最大行数,缺省为1500 -->
        <!--<module name="FileLength">-->
            <!--<property name="max" value="2000" />-->
        <!--</module>-->
        <!-- 每行的最大字符数,缺省为80 -->
        <module name="LineLength">
            <!-- 忽略指定格式的行,如*号开始的,等 -->
            <!--
            <property name="ignorePattern" value="^ *\* *[^ ]+$"/>
            -->
            <property name="max" value="120" />
        </module>
        <!-- 方法的最大行数,缺省为150 -->
        <module name="MethodLength">
            <property name="max" value="200" />
            <!-- 统计时是否包括空行和以//开始的注释,缺省为统计(true)-->
            <property name="countEmpty" value="false" />
        </module>
        <!-- 匿名类的最大行数,缺省为20 -->
        <module name="AnonInnerLength">
            <property name="max" value="60" />
        </module>
        <!-- 检查方法和构造子参数的最大个数,缺省为7 -->
        <module name="ParameterNumber" />
        <!-- Checks for whitespace -->
        <!-- See http://checkstyle.sf.net/config_whitespace.html -->
        <module name="EmptyForInitializerPad" />
        <module name="EmptyForIteratorPad" />
        <module name="MethodParamPad">
            <property name="allowLineBreaks" value="true" />
        </module>
        <module name="NoWhitespaceAfter" />
        <module name="NoWhitespaceBefore" />
        <module name="OperatorWrap" />
        <module name="ParenPad" />
        <module name="TypecastParenPad" />
        <!--<module name="TabCharacter" />-->
        <module name="WhitespaceAfter" />
        <module name="WhitespaceAround" />
        <!-- Modifier Checks -->
        <!-- See http://checkstyle.sf.net/config_modifiers.html -->
        <!-- 要求JLS suggestions -->
        <!--
        <module name="ModifierOrder"/>
        -->
        <module name="RedundantModifier" />
        <!-- Checks for blocks. You know, those {}'s -->
        <!-- See http://checkstyle.sf.net/config_blocks.html -->
        <!-- 检查空块 -->
        <!--
        <module name="EmptyBlock"/>
        -->
        <module name="LeftCurly" />
        <!-- 检查只有必须有{},确省为必须,主要在if,else时有这样的情况 -->
        <module name="NeedBraces" />
        <!-- 检查"}",确省在同一行 -->
        <module name="RightCurly">
            <property name="option" value="alone" />
        </module>
        <!-- 检查多余嵌套的{},请看文档,不易说明 -->
        <module name="AvoidNestedBlocks" />
        <!-- Checks for common coding problems -->
        <!-- See http://checkstyle.sf.net/config_coding.html -->
        <module name="AvoidInlineConditionals" />
        <module name="CovariantEquals" />
        <module name="DeclarationOrder" />
        <module name="DefaultComesLast" />
        <!--<module name="DoubleCheckedLocking" />-->
        <!--
        <module name="EmptyStatement"/>
        -->
        <module name="EqualsHashCode" />
        <!-- 变量必须初始化为自己的类型,如果给一个Object类型的变量初始化为null会提示 -->
        <!--
        <module name="ExplicitInitialization"/>
        -->
        <module name="FallThrough" />
        <!--
        <module name="FinalLocalVariable"/>
        -->
        <module name="HiddenField">
            <property name="ignoreConstructorParameter" value="true" />
            <property name="ignoreSetter" value="true" />
        </module>
        <!-- Exception, Throwable, RuntimeException是不允许catch的 -->
        <!--
        <module name="IllegalCatch"/>
        -->
        <module name="IllegalInstantiation" />
        <!--
        <module name="IllegalToken"/>
        -->
        <module name="IllegalTokenText" />
        <module name="IllegalType" />
        <module name="InnerAssignment" />
        <!--检查直接数
        <module name="MagicNumber"/>
        检查是否有构造子
        <module name="MissingCtor"/>
        -->
        <module name="MissingSwitchDefault" />
        <module name="MultipleVariableDeclarations" />
        <!--
        <module name="JUnitTestCase"/>
        <module name="NestedIfDepth"">
        <property name="max" value="5"/>
        </module>
        <module name="NestedTryDepth"">
        <property name="max" value="5"/>
        </module>
        <module name="PackageDeclaration"/>
        <module name="ReturnCount"/>
        -->
        <!-- 不能为参数付值 -->
        <!--
        <module name="ParameterAssignment"/>
        -->
        <module name="RedundantThrows" />
        <!-- 不能理解的,好像是bug
        <module name="RequireThis"/>
        -->
        <module name="SimplifyBooleanExpression" />
        <module name="SimplifyBooleanReturn" />
        <module name="StringLiteralEquality" />
        <module name="SuperClone" />
        <module name="SuperFinalize" />
        <module name="UnnecessaryParentheses" />
        <!-- Checks for class design -->
        <!-- See http://checkstyle.sf.net/config_design.html -->
        <!-- 要求一个方法必须声明为Extension的,否则必声明为abstract, final or empty -->
        <!--
        <module name="DesignForExtension"/>
        -->
        <!-- 检查private构造子是否声明为final,这里有个问题,在Java中构造子是不能声明为final的 -->
        <!--
        <module name="FinalClass"/>
        -->
        <!-- 要求一定要有一个构造子 -->
        <!--
        <module name="HideUtilityClassConstructor"/>
        -->
        <module name="InterfaceIsType" />
        <!-- 检查变量的可见性,确省只允许static final 为public,否则只能为private -->
        <module name="VisibilityModifier">
            <property name="packageAllowed" value="true" />
            <property name="protectedAllowed" value="true" />
        </module>
        <!--
        <module name="MutableException"/>
        -->
        <!-- 限制抛出声明的指定数量,确省为1 -->
        <!--
        <module name="ThrowsCount"/>
        -->
        <!-- Miscellaneous other checks. -->
        <!-- See http://checkstyle.sf.net/config_misc.html -->
        <!-- 数组的声明是否允许Java的类型,确省为允许,Java类型为String[] xx,C++的类型为String xx[]; -->
        <module name="ArrayTypeStyle" />
        <!--
        <module name="FinalParameters"/>
        -->
        <!-- 一般性的代码问题,不好的习惯等,可以多 -->
        <!-- 文件中使用了System.out.print等-->
        <!--<module name="GenericIllegalRegexp">-->
            <!--<property name="format" value="System\.out\.print" />-->
            <!--<property name="message" value="bad practice of use System.out.print" />-->
        <!--</module>-->
        <!--<module name="GenericIllegalRegexp">-->
            <!--<property name="format" value="System\.exit" />-->
            <!--<property name="message" value="bad practice of use System.exit" />-->
        <!--</module>-->
        <!--<module name="GenericIllegalRegexp">-->
            <!--<property name="format" value="printStackTrace" />-->
            <!--<property name="message" value="bad practice of use printStackTrace" />-->
        <!--</module>-->
        <!-- 关于Task,你可以声明自己的Task标识 -->
        <module name="TodoComment">
            <property name="format" value="TODO" />
        </module>
        <!-- 强迫//注释必须如何,入下要求只能有一行,具体看文档 -->
        <!--
        <module name="TrailingComment">
        <property name="format" value="^\\s*$"/>
        </module>
        -->
        <!-- main方法经常会在debug时使用,但发行版本的时候可能并不需要这个方法,提示 -->
        <!--
        <module name="UncommentedMain"/>
        -->
        <!-- 当定义一个常量时,希望使用大写的L来代替小写的l,原因是小写的l和数字1很象 -->
        <module name="UpperEll" />
        <!-- 检查正确的缩进,这个更象是个人习惯 -->
        <!--
        <module name="Indentation">
        <property name="braceAdjustment" value="0"/>
        </module>
        -->
        <!-- Checks For Metrics -->
        <!-- See http://checkstyle.sf.net/config_metrics.html -->
        <!-- 检查嵌套复杂度 -->
        <module name="CyclomaticComplexity">
            <property name="max" value="12" />
        </module>
    </module>
</module>


到这里就完成了整个配置了,可以根据自己的需求来配置不同的选项了

最后再说一下如何使用

每次git commit 或者通过android studio commit代码的时候,都会先对修改的java文件进行检查,如果有问题,

则会在build/reports/checkstyle/checkstyle.xml中将错误列举出来。

<error line="39" column="9" severity="error" message="Variable access definition in wrong order." source="com.puppycrawl.tools.checkstyle.checks.coding.DeclarationOrderCheck"/>
以这一条举例说明:

39行第9列 错误,声明变量顺序错误,进行的是com.puppycrawl.tools.checkstyle.checks.coding.DeclarationOrderCheck检查。

具体错误原因可以参考下面表格

错误提示

错误说明

missing a javadoc comment

缺少类注释

Line longer than X characters

行长度超过X个字符(包括空格)

Return count is X(max allowed 3)

一个方法内的返回数量是X(最大值只能为3)

Nested if-else depth is X(max allowed is 3)

最大的if-else嵌套层数为X(最大只能为3)

Array brackets at illegal position

数组的方括号“[]”的位置不正确(检查数组类型的定义是String[] args,而不是String args[])

Line matchs the illegal pattern 'System\.out\.println'

本行包含System.out.println语句

ctor def modifier at indentation level 8 not at corrent indentation 4

缩进不正确,一般是因为没有在Eclipse中使用4个空格代替tab键引起。

'static' modifier out of order with the JLS suggestions

static修饰符没有按照JLS的建议来排序(eg.写成public final static...应该改成public static final)

Name 'X' must match pattern '^[A-Z][A-Z0-9][_A-Z0-9+]$'(正则表达式)

名称不符合正则表达式'^[A-Z][A-Z0-9][_A-Z0-9+]$'(即为大写字母,数字、下划线等)。

一般在静态变量没有大写时提示,包名不是全部消息时提示,类名不是大写开头时提示,方法名不是小写开头时提示

Variable access definition in wrong order

变量定义顺序不正确(例如在类成员变量定义时,将private类型的变量定义在public类型的变量之前)

Static variable definition in wrong order

静态变量定义顺序不正确(例如在构造函数之后定义静态变量)

Instance variable definition in wrong order

成员变量定义顺序不正确(例如在构造函数之后定义成员变量)

X is a magic number

X是一个魔术数字(非0、1、2的数字)

if construct must use '{}'

if结构必须使用'{}'

Got an exception - Unexpected character 0xfffd in identifier

因为没有设置checkstyle配置文件的charset为UTF-8,而类文件使用UTF-8编码,并且含有中文

“{” should be on the previous line

“{” 应该位于前一行

Methods is missing a javadoc comment

方法前面缺少javadoc注释

Expected @throws tag for “Exception”

在注释中希望有@throws的说明

“.” Is preceeded with whitespace

“.” 前面不能有空格

“.” Is followed by whitespace

“.” 后面不能有空格

“=” is not preceeded with whitespace“=”

前面缺少空格

“=” is not followed with whitespace

“=” 后面缺少空格

“}” should be on the same line

“}” 应该与下条语句位于同一行

Unused @param tag for “unused”

没有参数“unused”,不需注释

Variable “X” missing javadoc

变量“CA”缺少javadoc注释

Line contains a tab character

行含有”tab” 字符

Redundant “Public” modifier

冗余的“public” modifier

final modifier out of order with the JSL suggestion

final修饰符的顺序错误

Avoid using the “.*” form of import

Import格式避免使用“.*”

Redundant import from the same package

从同一个包中Import内容

Unused import-X Import

import的X类没有被使用

Duplicate import to line X

重复Import同一个内容

Import from illegal package

从非法包中 Import内容

“while” construct must use “{}”

“while” 语句缺少“{}”

Variable “X” must be private and have accessor method

变量“X”应该是private的,并且有调用它的方法

Variable “X” must match pattern “^[a-z][a-zA-Z0-9]*$”

变量“X”不符合命名规则“^[a-z][a-zA-Z0-9]*$”

“(” is followed by whitespace

“(” 后面不能有空格

“)” is proceeded by whitespace

“)” 前面不能有空格





评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值