强制执行Lint规范代码

Lint

开发中使用静态代码检测工具对代码进行检查,达到规范代码减少bug的目的。常用的检测工具有FindBugs、PMD、Coverity,Checkstyle。
Android工程使用Lint是最方便。Lint作为官方配套工具,功能完善,自定义扩展性强,常规需求基本可以做到无需修改。
自定义Lint网上相关文章也很多,不在本篇讨论范围之中。

现实

虽然Lint很好,能够在代码中实时提示,但只要不影响到编译流程,改不改,全看开发者自觉。所以我们需要增加一些强制性,不修改就不能继续。

  1. 将Lint任务部署到CI中,Pull Request进行Lint任务,不通过则不允许提交
  2. hook到git commit,在git commit时执行Lint任务
  3. 本地编译时执行Lint任务,不通过中断编译

根据实际情况选择即可,下面对方案3讲解一下

插入到编译过程中

众所周知,apk生成或者aar生成会执行assemble任务,子module时在不输出aar并不会执行这个任务,经过
观察会执行bundleLibRuntimeToDirxxxx任务,所以可以把Lint任务插入到这两个任务之前执行。

common.gradle, 基于AGP7.0+

/**当设置为true时每次运行都会进行lint,设置为false时只会在发布版本时检查*/
def lintAlways = true

def isAppModule = plugins.hasPlugin('com.android.application')
def isLibraryModule = plugins.hasPlugin('com.android.library')

//lint检测
if (isAppModule) {
    android.applicationVariants.all { variant ->
        def lintTask = tasks["lint${variant.name.capitalize()}"]
        variant.assembleProvider.get().dependsOn lintTask
    }
} else if (isLibraryModule) {
    android.libraryVariants.all { variant ->
        def lintTask = tasks["lint${variant.name.capitalize()}"]
        if (lintAlways) {
            def runTask = tasks["bundleLibRuntimeToDir${variant.name.capitalize()}"]
            if (runTask != null) {
                //直接运行时也进行lint
                runTask.dependsOn lintTask
            }
        }
        //打包成aar
        variant.assembleProvider.get().dependsOn lintTask
    }
}

最后在每个模块引入这个gradle即可。

Lint配置

只有error或者fatal级别的issue,才会中断编译。如果我们想修改issue等级或者我们想忽略某些文件错误。可以在工程根目录添加lint.xml文件,

<?xml version="1.0" encoding="UTF-8"?>
<lint>
    <!-- Disable the given check in this project -->
    <issue id="IconMissingDensityFolder" severity="ignore" />

    <!-- Ignore the ObsoleteLayoutParam issue in the specified files -->
    <issue id="ObsoleteLayoutParam">
        <ignore path="res/layout/activation.xml" />
        <ignore path="res/layout-xlarge/activation.xml" />
    </issue>

    <!-- Ignore the UselessLeaf issue in the specified file -->
    <issue id="UselessLeaf">
        <ignore path="res/layout/main.xml" />
    </issue>

    <!-- Change the severity of hardcoded strings to "error" -->
    <issue id="HardcodedText" severity="error" />
</lint>

配置好后,当有error级别的issue未解决时就不编译不通过,督促开发人员进行修改。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容