Android コードの静的検査 (lint、Checkstyle、ktlint、Detekt)

Android コードの静的検査 (lint、Checkstyle、ktlint、Detekt)

ここに画像の説明を挿入

プロジェクトの開発プロセス中Android、開発チームは多くの場合、コードの欠陥を見つけて修正するために多くの時間と労力を費やします。

静的コード分析ツールは、開発者がコードの欠陥を迅速かつ効果的に特定し、コード構築プロセス中に修正するのに役立ちます。これにより、ソフトウェアの信頼性が大幅に向上します。

ソフトウェアの開発とテストのコストを節約します。

Android現在使用されている主な言語はkotlin、 、javaおよび であるため、可能な限り両方の言語をサポートする必要があります。

糸くず

Android Studio提供されたコード スキャン ツール。lint チェックを行ってコードを改善する

何を検出できますか?潜在的なバグが含まれているかどうか、および正確性、セキュリティ、パフォーマンス、使いやすさ、利便性、および国際化の点で最適化の改善が必要かどうかは、コードの結び目/品質の問題を見つけ、同時にいくつかの解決策を提供するのに役立ちます. 各質問には、情報の説明と評価があります。

[ 300 以上] の検出ルールをサポートし、、、、、、、、および画像Manifest文件リソースサポートします。XMLJavaKotlinJava字节码Gradle文件Proguard文件Propetty文件

抽象構文ツリー分析に基づいて、経験豊富な LOMBOK-AST、PSI、UAST の 3 つの構文アナライザー。

それは主に次の側面を含みます

  • Correctness: ハードコーディング、古い API の使用など、完全ではないコーディング。
  • Performance: 静的参照、循環参照など、パフォーマンスに影響するエンコーディング。
  • Internationalization: 国際化、リソース参照などを使用せずに漢字を直接使用。
  • Security: 許可されているなどWebView安全でないエンコーディング。JavaScriptInterface

モジュール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詳細に表示できます。

ここに画像の説明を挿入

チェックスタイル

Java主にコードのコーディング標準検出に使用される静的コード検出ツール。

CheckStyleGralde組み込みのPluginCheckstyleプラグイン

ソース コードを分析し、それを既知のコーディング規則と比較することにより、結果がhtmlまたはの形式で表示されます。xml

原理は、Antlrライブラリを使用してソース コード ファイルを分析し、抽象的な構文ツリーを生成し、構文ツリー全体を走査して検出ルールに一致させることです。

現在、ユーザー定義の検出ルールはサポートされていません. 既存の [100+] ルールの中には、属性を持ち、カスタム パラメーターの設定をサポートするルールもあります。

モジュール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、結果が取得されます。

ここに画像の説明を挿入

コトリンのサポート

Kotlin のコード チェックと検証を実装する方法は? 理にかなっている 2 つの方法を見つけました。

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詳細に表示できます。

ここに画像の説明を挿入

検出する

プラグインの依存関係を追加する

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

プラグインを導入し、関連する構成を改善します (追伸: 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詳細に表示できます。

ここに画像の説明を挿入

要約する

GitHub デモ

CheckStyleプラグインの統合は新しいように見えますkotlinそのルールはカスタマイズ可能ではなく、うまく機能し、カスタマイズできます。出力形式はすべてサポートされていますが、出力結果の読み取りエクスペリエンスが優れていることは明らかです。KtlinDetektKtlintDetekthtmlDetekt

上記の関連プラグインはすべてコマンドライン操作をサポートしているため、 Git フックと組み合わせることができます。Gitフックは、送信されるスナップショットをチェックするために使用されます。たとえば、脱落のチェック、テストの実行の確認、およびコードの検証に使用されます。 .

チームが異なればコード スタイルも異なり、プロジェクトが異なればコード仕様も異なります。現在、プロジェクト開発に携わる多くの学生はコード検出ツールをほとんど使用していませんが、重要なプロジェクトのコードに含まれる欠陥、パフォーマンスの問題、および隠れたバグに対してゼロ トレランスを持っているため、静的コード検出ツールは特に重要です。

おすすめ

転載: blog.csdn.net/stven_king/article/details/128448599