You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写Gradle Kotlin任务获取Git Commit Hash并保存到文件?

Gradle Kotlin DSL执行Git命令保存提交哈希到文件

你的两种写法都存在参数传递错误:

  • 第一种写法中,commandLine("git rev-parse HEAD > gitReleaseVersion.txt")将整个字符串作为单个命令,Gradle会尝试寻找名为该字符串的可执行文件,同时默认不通过shell解析重定向符号>,因此既不会执行git命令,也不会生成文件。
  • 第二种写法同样错误地将git rev-parse HEAD作为单个命令参数,系统无法找到名为该字符串的程序,因此报"找不到命令"错误。

正确写法1:直接配置Exec任务

不需要嵌套exec调用,直接在任务中配置命令和输出:

task<Exec>("getVersionInfo") {
    // 拆分git命令与参数,Gradle能正确定位git可执行文件
    commandLine("git", "rev-parse", "HEAD")
    // 将命令输出定向到目标文件
    standardOutput = file("gitReleaseVersion.txt").outputStream()
}

正确写法2:在doLast中执行exec

如果需要在任务最后阶段执行,可使用这种方式:

task("getVersionInfo") {
    doLast {
        val targetFile = file("src/main/resources/gitReleaseVersion.txt")
        exec {
            commandLine("git", "rev-parse", "HEAD")
            standardOutput = targetFile.outputStream()
        }
    }
}

可选:通过Shell执行(支持重定向)

如果依赖shell的重定向功能(比如同时处理错误输出),可以指定shell命令执行:

task<Exec>("getVersionInfo") {
    // Linux/macOS用sh -c,Windows用cmd /c
    commandLine("sh", "-c", "git rev-parse HEAD > src/main/resources/gitReleaseVersion.txt")
    // 可选:指定git工作目录,比如项目根目录
    workingDir = project.rootDir
}

执行任务时,直接运行./gradlew getVersionInfo即可生成包含Git提交哈希的文件。

内容的提问来源于stack exchange,提问作者Kaigo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 06:20:10