我在Android Studio的build.gradle
脚本中具有以下功能:
def getBuildCommit() {
return ['git', 'rev-parse', 'HEAD'].execute().text.trim()
}
如果
git
不在PATH
上,则此代码将失败并显示错误。我的目标是,如果git
不可用,这应该不会失败,而是返回一个空白字符串,并允许构建正常继续。此代码必须在Windows和Linux主机上都可以运行。有没有一种方法可以在调用它之前首先检查
git
是否存在(类似于linux上的$ which git
)?还是在这样的失败情况下不抛出异常的execute()
的方法?
最佳答案
好吧,您可以将其包装在try / catch块中,如果有异常,则返回空字符串。
但是实际上,就像您在Gradle中一样,无论如何,我都会使用Exec
类型的任务或exec
方法,它们都具有相同的功能。因此,在您的情况下,完整示例将类似于
def getBuildCommit() {
try {
new ByteArrayOutputStream().withStream { out ->
def result = exec {
commandLine 'git', 'rev-parse', 'HEAD'
ignoreExitValue true
standardOutput out
errorOutput = [ write: { Object... args -> } ] as OutputStream
}
return (result.exitValue == 0) ? (out as String).trim() : ''
}
} catch(Exception e) {
return ''
}
}
关于android - 在gradle build脚本中调用程序之前,如何检查程序是否在PATH上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47597514/