1. 概述

本文将深入探讨 gradle-lint 插件。首先分析其适用场景,然后逐步讲解插件配置选项,接着演示如何使用预定义规则,最后展示如何生成检查报告。

2. 什么是 Gradle Lint 插件?

Gradle Lint 插件 是专门用于检查 Gradle 配置文件 的工具。它能强制统一构建脚本的结构,保持 Gradle Wrapper 版本最新,防止构建文件中的不良实践,并移除未使用的依赖

实际使用中,我们可以选择预定义规则或编写自定义规则,然后配置插件将它们视为违规或忽略。该检查器会在大多数 Gradle 任务结束时自动运行。

默认情况下,插件不会直接修改代码,而是显示警告信息。这种设计很实用,因为其他 Gradle 任务不会因此失败,且警告会显示在日志末尾,不会被忽略。

此外,gradle-lint 提供了 fixGradleLint 命令来自动修复大部分违规问题。

内部实现上,该插件利用 Groovy AST 和 Gradle Model 来应用检查规则。这也意味着插件与 Groovy AST 紧密耦合,因此不支持 Kotlin 构建脚本

3. 设置

配置 Gradle Lint 插件有三种方式:在 build.gradle 中、通过初始化脚本或使用脚本插件。下面逐一介绍。

3.1. 使用 build.gradle

build.gradle 中添加插件:

plugins {
    id "nebula.lint" version "17.8.0"
}

在多模块项目中,插件必须应用于根项目。以多模块项目为例:

allprojects {
    apply plugin :"nebula.lint"
    gradleLint {
        rules = [] // 后续添加规则
    }
}

后续将在 gradleLint.rules 数组中添加检查规则。

3.2. 使用初始化脚本

通过初始化脚本配置插件:

import com.netflix.nebula.lint.plugin.GradleLintPlugin

initscript {
    repositories { mavenCentral() }
    dependencies {
        classpath 'com.netflix.nebula:gradle-lint-plugin:17.8.0'
    }
}

allprojects {
    apply plugin: GradleLintPlugin
    gradleLint {
        rules=[]
    }
}

将此脚本保存为 lint.gradle,通过 --init-script 参数应用:

./gradlew build --init-script lint.gradle

这种方式的优点是可根据不同环境使用不同初始化脚本,但缺点是每次执行都需要传递 --init-script 参数。

3.3. 使用脚本插件

直接在 build.gradle 中应用脚本插件:

plugins{
    id "nebula.lint" version "17.8.0"
}
apply from: "gradle-lint-intro.gradle"

gradle-lint-intro.gradle 内容会被注入构建脚本:

allprojects {
    apply plugin: "nebula.lint"
    gradleLint {
        rules= []
    }
}

本文将直接在 build.gradle 中配置插件。

4. 配置

4.1. 执行

**执行 Gradle Lint 插件的命令是 ./gradlew lintGradle**。可单独运行或作为其他任务的一部分。

默认情况下,插件会在所有任务结束时自动运行,但以下任务除外:helptasksdependenciesdependencyInsightcomponentsmodelprojectswrapperproperties

./gradlew build

build 任务结束时会调用 ./gradlew lintGradle,检查器将违规作为警告显示。

可通过 skipForTask 方法阻止插件在特定任务中运行

gradleLint {
    skipForTask('build')
}

若要完全禁用插件,使用 alwaysRun 标志:

gradleLint {
    alwaysRun = false
}

这在需要单独执行 ./gradlew lintGradle 时特别有用。

注意:单独运行插件时,违规会被视为错误而非警告

4.2. 规则定义

Gradle Lint 插件支持两类规则配置:违规规则(通过 rulescriticalRules)和忽略规则(使用 excludedRulesignorefixme)。

✅ 违规规则

  • rules:定义规则数组,触发违规时显示警告(单独运行时会导致构建失败)
  • criticalRules违规直接导致任务失败,可通过 criticalLintGradle 任务单独检查:
./gradlew criticalLintGradle -PgradleLint.criticalRules=undeclared-dependency

❌ 忽略规则

  • excludedRules忽略特定规则,常用于从组规则中排除:
gradleLint { 
    rules= ['all-dependency']
    excludedRules= ['undeclared-dependency']
 }
  • ignore临时忽略代码块
dependencies {
    testImplementation('junit:junit:4.13.1')
    gradleLint.ignore('dependency-parentheses') {
        implementation("software.amazon.awssdk:sts")
    }
}
  • fixme设置过期时间的临时忽略:
gradleLint.fixme('2029-04-23', 'dependency-parentheses') {
    implementation('software.amazon.awssdk:sts')
}

⚠️ 重要提示ignorefixme 仅对已解析的依赖有效,对构建文件中的未解析声明无效:

dependencies {
    gradleLint.ignore('unused-dependency') {
        implementation "software.amazon.awssdk:sts" // 不会生效
    }
}

4.3. 覆盖配置属性

可通过命令行覆盖配置属性,使用 -PgradleLint 前缀:

./gradlew lintGradle -PgradleLint.excludedRules=unused-dependency

这等同于在配置文件中设置 excludedRules=["unused-dependency"]多值用逗号分隔,在 CI 环境中特别实用。

5. 内置规则

Gradle Lint 插件提供多种内置规则,下面介绍两个常用规则。

5.1. 最小依赖版本规则

minimum-dependency-version 规则检查依赖版本是否低于预设值:

gradleLint { 
    rules= ['minimum-dependency-version'] 
}

通过命令行设置最小版本(当前版本配置文件暂不支持):

./gradlew lintGradle -PgradleLint.minVersions=junit:junit:5.0.0

当检测到低于 5.0.0 的 JUnit 版本时:

> Task :lintGradle FAILED

This project contains lint violations. A complete listing of the violations follows.
Because none were serious, the build's overall status was unaffected.

warning   minimum-dependency-version         junit:junit is below the minimum version of 5.0.0 (no auto-fix available). See https://github.com/nebula-plugins/gradle-lint-plugin/wiki/Minimum-Dependency-Version-Rule for more details

? 1 problem (0 errors, 1 warning)

To apply fixes automatically, run fixGradleLint, review, and commit the changes.

运行 ./gradlew fixGradleLint 会自动将 JUnit 版本更新到 5.0.0。

5.2. 未声明依赖规则

undeclared-dependency 规则确保代码中直接使用的传递依赖被显式声明:

gradleLint { 
    rules= ['undeclared-dependency'] 
}

执行 lintGradle 任务:

> Task :lintGradle FAILED

This project contains lint violations. A complete listing of the violations follows. 
Because none were serious, the build's overall status was unaffected.

warning   undeclared-dependency              one or more classes in org.hamcrest:hamcrest-core:1.3 are required by your code directly

warning   undeclared-dependency              one or more classes in org.apache.httpcomponents:httpcore:4.4.13 are required by your code directly

? 2 problems (0 errors, 2 warnings)

To apply fixes automatically, run fixGradleLint, review, and commit the changes.

运行 fixGradleLint 后自动添加缺失依赖:

> Task :fixLintGradle

This project contains lint violations. A complete listing of my attempt to fix them follows. Please review and commit the changes.

fixed          undeclared-dependency              one or more classes in org.hamcrest:hamcrest-core:1.3 are required by your code directly

fixed          undeclared-dependency              one or more classes in org.apache.httpcomponents:httpcore:4.4.13 are required by your code directly

Corrected 2 lint problems

⚠️ 注意:当前版本不支持自定义规则,需 fork 项目添加。同时注意部分规则(如 archaic-wrapper)已被移除,但文档尚未更新。

6. 生成报告

通过 generateGradleLintReport 任务生成报告:

./gradlew generateGradleLintReport

默认生成 HTML 格式报告,保存在 build/reports/gradleLint 目录,文件名格式为 {项目名}.html

支持其他格式:

gradleLint {
    reportFormat = 'text'  // 可选:xml/text
    reportOnlyFixableViolations = true
}

reportOnlyFixableViolations=true 时,报告仅包含可修复的违规项。

7. 结论

本文深入探讨了 gradle-lint 插件,从核心功能到配置选项,再到内置规则和报告生成。该插件能有效规范 Gradle 构建脚本,提升项目维护性。但需注意其对 Kotlin 脚本的支持限制,以及部分规则已过时的问题。

本文代码示例可在 GitHub 获取。


原始标题:Intro to Gradle Lint Plugin | Baeldung

» 下一篇: Java Weekly, 第508期