在 multi-project 中统一 checkstyle 配置并生成聚合报告?

解读

国内一线厂普遍把“静态代码扫描”作为质量门禁的硬性指标,Checkstyle 又是 Java 系项目最轻量的扫描工具之一。
面试官抛出“统一配置 + 聚合报告”这一组合,核心想验证三点:

  1. 你是否理解 configuration on demand + buildSrc/Convention Plugin 的“统一收口”机制;
  2. 你是否能把 Checkstyle Task 的输入/输出声明清楚,让增量构建与远程缓存生效;
  3. 你是否能在 CI 阶段(GitLab-CI / Jenkins Pipeline)里,把分散的 xml/html 结果聚合成一个“可直接归档到 SonarQube 或 GitLab Pages”的总报告,并保证失败 Gate 精准定位到子模块。

答得太浅(只会 allprojects apply plugin)会被认为“脚本式”思维;答得太深(直接撸 ASM 改字节码)又容易被吐槽“过度设计”。国内面试最吃香的套路是“Convention Plugin + Report Aggregation + 质量门禁”三板斧,既展示 Gradle 深度,又落地可抄。

知识点

  1. buildSrc / included build 中的 Convention Plugin(Kotlin DSL 优先),取代 allprojects 脚本块,实现“配置收口”。
  2. CheckstyleExtension 的 toolVersion / configFile / ignoreFailures / reports 属性,以及 Task 输出缓存键(configFile + 源码集合 + 类路径)。
  3. Report 多格式:xml 给 SonarQube,html 给研发自助排查;xmlDestination / htmlDestination 必须声明为 $buildDir/reports/checkstyle/checkstyle.xml,否则 CI 聚合找不到。
  4. 聚合策略:
    • 官方 ReportingAggregator Plugin(孵化中)或自定义 CheckstyleAggregate Task;
    • 利用 Configuration 收集所有子模块的 checkstyle.xml 输出,通过 XSLT 或 Kotlin 脚本合并为 checkstyle-merged.xml;
    • 在 rootProject 新建 TestReport 或 JacocoReport 类似思路的 CheckstyleAggregate Task,输入为子模块 checkstyle.xml,输出为 $rootDir/build/reports/checkstyle/checkstyle-merged.html。
  5. 质量门禁:
    • 使用 Checkstyle 的 -failOnViolation 或 Gradle 的 checkstyleMain.maxErrors = 0;
    • CI 阶段通过 -Pcheckstyle.ignoreFailures=false 显式打开失败开关,保证 MR 无法合并。
  6. 远程构建缓存:
    • 把 configFile 与 checkstyle 版本作为 Task 输入,确保 缓存键稳定;
    • 公司内网搭建 Nginx 缓存节点或 Gradle Enterprise,减少重复扫描。

答案

(以下代码均以 Gradle 8.x + Kotlin DSL + 国内镜像 为基准,可直接抄进项目)

  1. 建立 Convention Plugin
    buildSrc/src/main/kotlin/checkstyle-convention.gradle.kts
plugins {
    id("java-library")
    checkstyle
}

checkstyle {
    toolVersion = "10.12.5"                          // 国内镜像同步的中央仓库版本
    configFile = rootProject.file("config/checkstyle/checkstyle.xml")
    isIgnoreFailures = providers.gradleProperty("checkstyle.ignoreFailures")
                              .map { it.toBoolean() }
                              .getOrElse(true)      // 本地容忍,CI 强制失败
    reports {
        xml.required.set(true)
        html.required.set(true)
    }
}

// 增量 & 缓存加固
tasks.withType<Checkstyle>().configureEach {
    classpath = files()
    inputs.file(configFile).withPropertyName("checkstyleConfig")
    outputs.cacheIf { true }
}
  1. 在根目录放置统一规则
    config/checkstyle/checkstyle.xml(可直接拷贝阿里 p3c 规则,去掉重复 Module-Import 检查,适配 JDK17 新语法)

  2. 所有子模块一键引用
    subprojects { apply(plugin = "checkstyle-convention") }

  3. 聚合报告 Task
    buildSrc/src/main/kotlin/checkstyle-aggregate.gradle.kts

plugins { base }

val aggregate = tasks.register("checkstyleAggregate") {
    group = "verification"
    description = "聚合所有子模块的 checkstyle.xml 并生成单一 html 报告"

    val allReports = files(subprojects.map { it.buildDir.resolve("reports/checkstyle/checkstyle.xml") })
    inputs.files(allReports).withPropertyName("allCheckstyleXml")
    val mergedXml = layout.buildDirectory.file("reports/checkstyle/checkstyle-merged.xml")
    val mergedHtml = layout.buildDirectory.file("reports/checkstyle/checkstyle-merged.html")
    outputs.files(mergedXml, mergedHtml)

    doLast {
        val xmls = allReports.filter { it.exists() }
        val aggregated = xmls.map { it.readText() }
                             .joinToString("\n") { it.substringAfter("<?xml version=\"1.0\"?>") }
        mergedXml.get().asFile.apply {
            parentFile.mkdirs()
            writeText("""<?xml version="1.0"?>
                |<checkstyle version="10.12.5">
                |$aggregated
                |</checkstyle>""".trimMargin())
        }
        // 简单 XSLT 转 html,可直接用 checkstyle 官方 xsl
        val html = javax.xml.transform.TransformerFactory.newInstance()
            .newTransformer(javax.xml.transform.stream.StreamSource(rootProject.file("config/checkstyle/checkstyle-simple.xsl")))
        html.transform(
            javax.xml.transform.stream.StreamSource(mergedXml.get().asFile),
            javax.xml.transform.stream.StreamResult(mergedHtml.get().asFile)
        )
    }
}

// 让 check 生命周期依赖聚合任务
tasks.check { dependsOn(aggregate) }
  1. CI 模板(GitLab-CI 片段,国内镜像加速)
checkstyle:
  stage: verify
  image: registry.cn-hangzhou.aliyuncs.com/gradle/gradle:8.5-jdk17
  script:
    - ./gradlew checkstyleAggregate -Pcheckstyle.ignoreFailures=false --build-cache
  artifacts:
    reports:
      checkstyle:
        - build/reports/checkstyle/checkstyle-merged.xml
    paths:
      - build/reports/checkstyle/
    expire_in: 7 days
  only:
    - merge_requests
    - main

至此,本地增量扫描秒级完成,CI 阶段自动聚合,MR 页面可直接浏览 html,SonarQube 通过 xml 做二次分析,质量门禁失败即阻断合并,完全符合国内“快、稳、可抄”的落地标准。

拓展思考

  1. 多规则集动态切换:国内很多团队要求“阿里 p3c + 自定义公司规则”并存,可通过 Checkstyle 的 <module name="SuppressionFilter"> 与 Gradle 的 SourceSet 级 Task 实现“同一套代码,两套报告”,并在 GitLab MR 标签里动态选择。
  2. 与 SpotBugs/PMD 统一门户:利用 Gradle 的 Reporting API,把 Checkstyle/SpotBugs/PMD 的 html 再聚合成 “质量总览” 单页,Nginx 静态托管,版本 diff 高亮,让面试官一眼看出你对 “生态整合” 的掌控力。
  3. 远程缓存命中率调优:国内大厂内网 Gradle Enterprise 或 阿里 Cloud Toolkit 已支持 Checkstyle Task 缓存命中统计,通过 Build Scan 发现 configFile 时间戳抖动或 规则文件里隐藏时间注释导致缓存失效,可进一步把 configFile 抽成独立 jar 并 版本化发布,缓存命中率从 70% 提到 95%,面试时甩出这个数字,直接秒掉只会背八股文的竞争者。