Android代码静态检查(lint、Checkstyle、ktlint、Detekt)

Android代码静态检查(lint、Checkstyle、ktlint、Detekt)

icon12-ed.jpg

Android项目开发过程中,开发团队往往要花费大量的时间和精力发现并修改代码缺陷。

静态代码分析工具能够在代码构建过程中帮助开发人员快速、有效的定位代码缺陷并及时纠正这些问题,从而极大地提高软件可靠性

节省软件开发和测试成本。

Android目前主要使用的语言为kotlinjava,所以我们需要尽可能支持这两种语言。

Lint

Android Studio 提供的代码扫描工具。通过进行 lint 检查来改进代码

能检测什么?是否包含潜在错误,以及在正确性、安全性、性能、易用性、便利性和国际化方面是否需要优化改进,帮助我们发现代码结/质量问题,同时提供一些解决方案。每个问题都有信息描述和等级。

支持【300+】检测规则,支持Manifest文件XMLJavaKotlinJava字节码Gradle文件Proguard文件Propetty文件和图片资源;

基于抽象语法树分析,经历了LOMBOK-AST、PSI、UAST三种语法分析器;

主要包括以下几个方面

  • Correctness:不够完美的编码,比如硬编码、使用过时 API 等;
  • Performance:对性能有影响的编码,比如:静态引用,循环引用等;
  • Internationalization:国际化,直接使用汉字,没有使用资源引用等;
  • Security:不安全的编码,比如在 WebView 中允许使用 JavaScriptInterface

在module下的build.gradle中添加以下代码:

android {
  lintOptions {
        // true--关闭lint报告的分析进度
        quiet true
        // true--错误发生后停止gradle构建
        abortOnError false
        // true--只报告error
        ignoreWarnings true
        // true--忽略有错误的文件的全/绝对路径(默认是true)
        //absolutePaths true
        // true--检查所有问题点,包含其他默认关闭项
        checkAllWarnings true
        // true--所有warning当做error
        warningsAsErrors true
        // 关闭指定问题检查
        disable 'TypographyFractions','TypographyQuotes'
        // 打开指定问题检查
        enable 'RtlHardcoded','RtlCompat', 'RtlEnabled'
        // 仅检查指定问题
        check 'NewApi', 'InlinedApi'
        // true--error输出文件不包含源码行号
        noLines true
        // true--显示错误的所有发生位置,不截取
        showAll true
        // 回退lint设置(默认规则)
        lintConfig file("default-lint.xml")
        // true--生成txt格式报告(默认false)
        textReport true
        // 重定向输出;可以是文件或'stdout'
        textOutput 'stdout'
        // true--生成XML格式报告
        xmlReport false
        // 指定xml报告文档(默认lint-results.xml)
        //xmlOutput file("lint-report.xml")
        // true--生成HTML报告(带问题解释,源码位置,等)
        htmlReport true
        // html报告可选路径(构建器默认是lint-results.html )
        //htmlOutput file("lint-report.html")
        //  true--所有正式版构建执行规则生成崩溃的lint检查,如果有崩溃问题将停止构建
        checkReleaseBuilds true
        // 在发布版本编译时检查(即使不包含lint目标),指定问题的规则生成崩溃
        fatal 'NewApi', 'InlineApi'
        // 指定问题的规则生成错误
        error 'Wakelock', 'TextViewEdits'
        // 指定问题的规则生成警告
        warning 'ResourceAsColor'
        // 忽略指定问题的规则(同关闭检查)
        ignore 'TypographyQuotes'
    }
}

运行./gradlew lint,检测结果在build/reports/lint/lint.html可查看详情。

lint-result-preview.png

CheckStyle

Java静态代码检测工具,主要用于代码的编码规范检测 。

CheckStyleGralde自带的PluginThe Checkstyle Plugin

通过分析源码,与已知的编码约定进行对比,以html或者xml的形式将结果展示出来。

其原理是使用Antlr库对源码文件做词语发分析生成抽象语法树,遍历整个语法树匹配检测规则。

目前不支持用户自定义检测规则,已有的【100+】规则中,有一部分规则是有属性的支持设置自定义参数。

在module下的build.gradle中添加以下代码:

/**
 * The Checkstyle Plugin
 *
 * Gradle plugin that performs quality checks on your project's Java source files using Checkstyle
 * and generates reports from these checks.
 *
 * Tasks:
 * Run Checkstyle against {rootDir}/src/main/java: ./gradlew checkstyleMain
 * Run Checkstyle against {rootDir}/src/test/java: ./gradlew checkstyleTest
 *
 * Reports:
 * Checkstyle reports can be found in {project.buildDir}/build/reports/checkstyle
 *
 * Configuration:
 * Checkstyle is very configurable. The configuration file is located at {rootDir}/config/checkstyle/checkstyle.xml
 *
 * Additional Documentation:
 * https://docs.gradle.org/current/userguide/checkstyle_plugin.html
 */

apply plugin: 'checkstyle'
checkstyle {
    //configFile = rootProject.file('checkstyle.xml')
    configProperties.checkstyleSuppressionsPath = rootProject.file("suppressions.xml").absolutePath
    // The source sets to be analyzed as part of the check and build tasks.
    // Use 'sourceSets = []' to remove Checkstyle from the check and build tasks.
    //sourceSets = [project.sourceSets.main, project.sourceSets.test]
    // The version of the code quality tool to be used.
    // The most recent version of Checkstyle can be found at https://github.com/checkstyle/checkstyle/releases
    //toolVersion = "8.22"
    // Whether or not to allow the build to continue if there are warnings.
    ignoreFailures = true
    // Whether or not rule violations are to be displayed on the console.
    showViolations = true
}
task projectCheckStyle(type: Checkstyle) {
    group 'verification'
    classpath = files()
    source 'src'
    //include '**/*.java'
    //exclude '**/gen/**'
    reports {
        html {
            enabled = true
            destination file("${project.buildDir}/reports/checkstyle/checkstyle.html")
        }
        xml {
            enabled = true
            destination file("${project.buildDir}/reports/checkstyle/checkstyle.xml")
        }
    }
}
tasks.withType(Checkstyle).each { checkstyleTask ->
    checkstyleTask.doLast {
        reports.all { report ->
            // 检查生成报告中是否有错误
            def outputFile = report.destination
            if (outputFile.exists() && outputFile.text.contains("<error ") && !checkstyleTask.ignoreFailures) {
                throw new GradleException("There were checkstyle errors! For more info check $outputFile")
            }
        }
    }
}
// preBuild的时候,执行projectCheckStyle任务
//project.preBuild.dependsOn projectCheckStyle
project.afterEvaluate {
    if (tasks.findByName("preBuild") != null) {
        project.preBuild.dependsOn projectCheckStyle
        println("project.preBuild.dependsOn projectCheckStyle")
    }
}

默认情况下,Checkstyle插件希望将配置文件放在根项目中,但这可以更改。

<root>
└── config
    └── checkstyle           
        └── checkstyle.xml   //Checkstyle 配置
        └── suppressions.xml //主Checkstyle配置文件

执行preBuild就会执行checkstyle并得到结果。

checkstyle-result-preview.png

支持Kotlin

怎么实现Kotlin的代码检查校验呢?我找到两个富有意义的方法。

1. Detekt — https://github.com/arturbosch/detekt
2. ktlint — https://github.com/shyiko/ktlint

KtLint

添加插件依赖

buildscript {
  dependencies {
    classpath "org.jlleitschuh.gradle:ktlint-gradle:11.0.0"
  }
}

引入插件,完善相关配置:

apply plugin: "org.jlleitschuh.gradle.ktlint"
ktlint {
    android = true
    verbose = true
    outputToConsole = true
    outputColorName = "RED"
    enableExperimentalRules = true
    ignoreFailures = true
    //["final-newline", "max-line-length"]
    disabledRules = []
    reporters {
        reporter "plain"
        reporter "checkstyle"
        reporter "sarif"
        reporter "html"
        reporter "json"
    }
}
project.afterEvaluate {
    if (tasks.findByName("preBuild") != null) {
        project.preBuild.dependsOn tasks.findByName("ktlintCheck")
        println("project.preBuild.dependsOn tasks.findByName(\"ktlintCheck\")")
    }
}

运行prebuild,检测结果在build/reports/ktlint/ktlintMainSourceSetCheck/ktlintMainSourceSetCheck.html可查看详情。

ktlint-result-preview.png

Detekt

添加插件依赖

buildscript {
  dependencies {
        classpath "io.gitlab.arturbosch.detekt:detekt-gradle-plugin:1.22.0"
  }
}

引入插件,完善相关配置(PS:可以在yml文件配置相关的规则):

apply plugin: 'io.gitlab.arturbosch.detekt'
detekt {
    // Version of Detekt that will be used. When unspecified the latest detekt
    // version found will be used. Override to stay on the same version.
    toolVersion = "1.22.0"

    // The directories where detekt looks for source files.
    // Defaults to `files("src/main/java", "src/test/java", "src/main/kotlin", "src/test/kotlin")`.
    source = files(
            "src/main/kotlin",
            "src/main/java"
    )

    // Builds the AST in parallel. Rules are always executed in parallel.
    // Can lead to speedups in larger projects. `false` by default.
    parallel = false

    // Define the detekt configuration(s) you want to use.
    // Defaults to the default detekt configuration.
    config = files("$rootDir/config/detekt/detekt-ruleset.yml")

    // Applies the config files on top of detekt's default config file. `false` by default.
    buildUponDefaultConfig = false

    // Turns on all the rules. `false` by default.
    allRules = false

    // Specifying a baseline file. All findings stored in this file in subsequent runs of detekt.
    //baseline = file("path/to/baseline.xml")

    // Disables all default detekt rulesets and will only run detekt with custom rules
    // defined in plugins passed in with `detektPlugins` configuration. `false` by default.
    disableDefaultRuleSets = false

    // Adds debug output during task execution. `false` by default.
    debug = false

    // If set to `true` the build does not fail when the
    // maxIssues count was reached. Defaults to `false`.
    ignoreFailures = true

    // Android: Don't create tasks for the specified build types (e.g. "release")
    //ignoredBuildTypes = ["release"]

    // Android: Don't create tasks for the specified build flavor (e.g. "production")
    //ignoredFlavors = ["production"]

    // Android: Don't create tasks for the specified build variants (e.g. "productionRelease")
    //ignoredVariants = ["productionRelease"]

    // Specify the base path for file paths in the formatted reports.
    // If not set, all file paths reported will be absolute file path.
    //basePath = projectDir
}
tasks.named("detekt").configure {
    reports {
        // Enable/Disable XML report (default: true)
        xml.required.set(true)
        xml.outputLocation.set(file("build/reports/detekt/detekt.xml"))
        // Enable/Disable HTML report (default: true)
        html.required.set(true)
        html.outputLocation.set(file("build/reports/detekt/detekt.html"))
        // Enable/Disable TXT report (default: true)
        txt.required.set(true)
        txt.outputLocation.set(file("build/reports/detekt/detekt.txt"))
        // Enable/Disable SARIF report (default: false)
        sarif.required.set(true)
        sarif.outputLocation.set(file("build/reports/detekt/detekt.sarif"))
        // Enable/Disable MD report (default: false)
        md.required.set(true)
        md.outputLocation.set(file("build/reports/detekt/detekt.md"))
        custom {
            // The simple class name of your custom report.
            reportId = "CustomJsonReport"
            outputLocation.set(file("build/reports/detekt/detekt.json"))
        }
    }
}
project.afterEvaluate {
    if (tasks.findByName("preBuild") != null) {
        project.preBuild.dependsOn tasks.findByName("detekt")
        println("project.preBuild.dependsOn tasks.findByName(\"detekt\")")
    }
}

运行prebuild,检测结果在build/reports/detekt/detekt.html可查看详情。

detekt-result-preview.png

总结

GitHub Demo

CheckStyle不支持kotlinKtlinDetekt两者对比Ktlint它的规则不可定制,Detekt 工作得很好并且可以定制,尽管插件集成看起来很新。虽然输出的格式都支持html,但显然Detekt输出的结果的阅读体验更好一些。

以上相关的插件因为都支持命令行运行,所以都可以结合Git 钩子,它用于检查即将提交的快照,例如,检查是否有所遗漏,确保测试运行,以及核查代码。

不同团队的代码的风格不尽相同,不同的项目对于代码的规范也不一样。目前项目开发中有很多同学几乎没有用过代码检测工具,但是对于一些重要的项目中代码中存在的缺陷、性能问题、隐藏bug都是零容忍的,所以说静态代码检测工具尤为重要。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,290评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,399评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,021评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,034评论 0 207
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,412评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,651评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,902评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,605评论 0 199
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,339评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,586评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,076评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,400评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,060评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,083评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,851评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,685评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,595评论 2 270

推荐阅读更多精彩内容