如何通过Gradle在Windows上执行Git命令?

3

我有以下代码片段:

def getVersion = { ->
    def stdout = new ByteArrayOutputStream()
    exec {
        commandLine 'git', 'describe', '--tags'
        standardOutput = stdout
    }
    return stdout.toString().trim()
}

每当我调用getVersion()时,就会出现以下错误:

* What went wrong:
A problem occurred evaluating root project 'ForgeWorkspace'.
> Process 'command 'git'' finished with non-zero exit value 128

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 6.442 secs

在我的MacBook Pro上,我从未遇到过这个问题,但在Windows上却遇到了。非常感谢您的帮助!


你可以考虑使用Gradle git插件而不是自己编写代码:https://github.com/ajoberstar/gradle-git(也许它提供了你需要的功能) - cjstehno
如果不必要,我只是不想再添加另一个插件。如果您有一个使用该插件实现我的功能的答案,请在下面放置它。 - T145
2个回答

2

@RaGe几乎是正确的。由于您确实需要使用Windows命令提示符(cmd)来让操作系统在系统路径中搜索git可执行文件,因此整个git命令应作为一个参数传递,该参数跟随/c开关(表示'执行命令')。

因此,以下内容应该有效:

commandLine 'cmd', '/c', 'git describe --tags'

0
在Windows上,commandLine的前两个参数应该是cmd和/c。
//on windows:
commandLine 'cmd', '/c', 'git'...

请点击这里


我添加了 commandLine 'cmd', '/c', 'git', 'describe', '--tags',但仍然得到几乎相同的错误,只是将 'git' 替换为 'cmd'。 - T145
getversion 应该是一个任务吗? - RaGe
不,它应该根据最新的Git发布和提交返回唯一的版本。这个函数在我的MacBook上完美工作,但是在我的Windows机器上却无法正常工作。唯一的问题就是commandLine行。 - T145
请使用 --stacktrace 运行并发布您的堆栈跟踪。 - RaGe
我也会尝试使用git的完整路径,而不仅仅是“'git'”。 - RaGe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接