如何开启 configuration-cache-problems-report.html 并解读警告?

解读

在国内大厂与头部外企的 Android/微服务工程中,configuration cache 已成为 CI 提速的“必选项”。面试官问“怎么开启并读懂 problems-report.html”,核心想验证三件事:

  1. 你是否真的在生产环境打开过开关、而不是只背文档;
  2. 遇到红色警告时能否快速定位“task 访问 TaskContainer/Project 运行时状态”这类违规代码;
  3. 能否给出可落地的修复优先级(先改自己写的 Task,再评估三方插件)。
    回答时务必结合国内主流 AGP 7.x/8.x + Gradle 8.x 场景,用“命令行参数 → 报告文件 → 典型警告 → 修复套路”四步闭环,体现工程化思维。

知识点

  1. configuration-cache 原理:将 Task 图序列化到 <project>/.gradle/configuration-cache/ 目录,下次构建直接反序列化,跳过 DSL 配置阶段,理论提速 30%~50%。
  2. 开启方式:
    • 一次性验证:./gradlew assembleDebug --configuration-cache --configuration-cache-problems=warn
    • 固化到团队:gradle.properties 里写 org.gradle.configuration-cache=true 与 org.gradle.configuration-cache-problems=warn(或 fail)。
  3. 报告位置:每次构建结束自动生成 build/reports/configuration-cache/<timestamp>/configuration-cache-report.html,中文浏览器直接双击即可离线查看。
  4. 警告分级:
    • 红色 —— 违反“Task 不得引用 Project 实例”等硬性约束,必须改;
    • 黄色 —— 使用了 @ReplacedBy、动态属性等“将来可能不兼容”的 API,建议改;
    • 灰色 —— 已兼容但序列化体积大,可暂缓。
  5. 高频违规代码:
    • task.doLast { println(project.name) }
    • task.inputs.file(project.file('local.properties'))
    • 在 buildSrc 或 included build 里执行 project.repositories.add(...)
  6. 修复套路:
    • 用 Task#providers 或 RegularFileProperty 注入;
    • 将 buildSrc 改为 included build 并声明 repository {} 到 settings.gradle.kts;
    • 对三方插件先升版本,再不行用 configuration-cache-problems=warn 暂时灰度。

答案

步骤一:本地一次性验证

./gradlew clean assembleDebug \
  --configuration-cache \
  --configuration-cache-problems=warn \
  --configuration-cache-report-directory=build/reports/cc

构建结束后,控制台会提示
Configuration cache report was written to file:///xxx/build/reports/cc/<timestamp>/configuration-cache-report.html
用 Chrome 打开即可。

步骤二:固化到 CI/团队
在项目根目录 gradle.properties 追加

org.gradle.configuration-cache=true
org.gradle.configuration-cache-problems=warn
# 可选:遇到红色违规直接失败,防止劣化
org.gradle.configuration-cache-problems=fail

提交 MR,让 CI 先跑绿灯。

步骤三:读懂报告

  1. 顶部 Summary 显示 Problems: 12,其中 Errors 3、Warnings 9;
  2. 点击第一条 Error,定位到 Task ':app:generateDebugBuildConfig' 的堆栈,提示
    Invocation of 'Task.project' by task ':app:generateDebugBuildConfig' at execution time is unsupported;
  3. 回到代码,发现
task.generateDebugBuildConfig.doLast {
    println "当前模块:" + project.name
}
  1. 修复:把 project.name 提前到配置阶段,用 task.getProject().getName() 或直接写死字符串;
  2. 重新执行 ./gradlew assembleDebug --configuration-cache,确认 Errors 降为 0;
  3. 对剩余黄色警告,建工单跟踪,迭代三个版本内清零,否则 CI 强制 fail。

拓展思考

  1. 国内项目常因 buildSrc 里写死 maven 账号密码 导致红色错误,可把 repositories 声明下沉到 settings.gradle.kts,并用 dependencyResolutionManagement 统一管理,既兼容 configuration cache 又符合 Maven 私服安全规范。
  2. 若使用 华为 AGP 插件 3.x/4.x 等老版本,官方未适配,可先在 gradle.properties 做模块级黑名单
org.gradle.configuration-cache.internal.task-execution-access-exceptions=module:huawei-agp

然后排期升级,避免“一刀切”关闭导致 CI 提速收益归零。
3. 对于 多项目构建(500+ 模块),建议开启 远程构建缓存 + configuration cache 组合,把序列化产物上传到阿里云 OSS 缓存桶,全链路构建时间从 18 min 降到 5 min,面试时可作为“性能优化”案例亮点。