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

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可查看概况。

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

CheckStyle

Java静态代码检测东西,首要用于代码的编码标准检测 。

CheckStyleGralde自带的Plugin,The 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并得到成果。

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

支撑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可查看概况。

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

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可查看概况。

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

总结

GitHub Demo

CheckStyle不支撑kotlinKtlinDetekt两者比照Ktlint它的规矩不可定制,Detekt 作业得很好并且能够定制,尽管插件集成看起来很新。尽管输出的格局都支撑html,但显然Detekt输出的成果的阅览体验更好一些。

以上相关的插件因为都支撑命令行运转,所以都能够结合Git 钩子,它用于查看即将提交的快照,例如,查看是否有所遗失,确保测验运转,以及核对代码。

不同团队的代码的风格不尽相同,不同的项目关于代码的标准也不一样。现在项目开发中有许多同学几乎没有用过代码检测东西,但是关于一些重要的项目中代码中存在的缺点、功能问题、隐藏bug都是零忍受的,所以说静态代码检测东西尤为重要。