Gradle 9中exec的替代方案:获取Git提交次数作为构建号
Gradle 9 替代旧 exec 方法获取 Git 提交次数的方案
Gradle 9 移除了原 Project 类下的 exec 闭包方法,官方推荐使用 ExecOperations API 来替代,这是 Gradle 7.0+ 引入的标准化执行外部命令的方式,更适配新版本的构建逻辑,也支持配置缓存等特性。
基础实现代码(Groovy DSL)
// 从项目服务中获取 ExecOperations 实例 def execOperations = project.services.get(ExecOperations) def getCommitCount = { -> def stdout = new ByteArrayOutputStream() execOperations.exec { spec -> spec.commandLine 'git', 'rev-list', '--count', 'HEAD' spec.standardOutput = stdout } return stdout.toString().trim().toInteger() }
带错误处理的增强版
如果需要兼容 Git 环境不存在、仓库未初始化等异常场景,可以添加退出码检查:
def execOperations = project.services.get(ExecOperations) def getCommitCount = { -> def stdout = new ByteArrayOutputStream() def execResult = execOperations.exec { spec -> spec.commandLine 'git', 'rev-list', '--count', 'HEAD' spec.standardOutput = stdout // 允许命令执行失败,避免直接中断构建 spec.isIgnoreExitValue = true } // 检查命令执行状态,失败时返回默认值 if (execResult.exitValue != 0) { return 0 } return stdout.toString().trim().toInteger() }
Kotlin DSL 版本
若使用 Kotlin 编写构建脚本,语法调整如下:
val execOperations = project.services.get(ExecOperations::class.java) fun getCommitCount(): Int { val stdout = ByteArrayOutputStream() val result = execOperations.exec { commandLine("git", "rev-list", "--count", "HEAD") standardOutput = stdout isIgnoreExitValue = true } return if (result.exitValue == 0) { stdout.toString().trim().toInt() } else { 0 } }
关键说明
ExecOperations是 Gradle 提供的服务类,通过project.services.get()获取实例,这是新版本中执行外部命令的标准方式- 核心的 Git 统计逻辑保持不变,仅切换了命令执行的入口,确保原有功能不受影响
内容的提问来源于stack exchange,提问作者digitalfootmark
相关产品推荐
相关产品推荐

