gradle 执行块不应因非零输出而失败

gradle Exec block should not fail for non zero output in

我正在编写 gradle 任务。它为成功 运行 而不是 3 调用 returns 3 的任务。我该怎么做呢?

task copyToBuildShare(){
   def robocopySourceDir = "build\outputs\apk"
   def cmd = "robocopy "+ robocopySourceDir + " C:\TEST *.* /MIR /R:5 2>&1"
   exec {
      ignoreExitValue = true
      workingDir '.'
      commandLine "cmd", "/c", cmd
      if (execResult.exitValue == 3) {
         println("It probably succeeded")
      }
   }
}

它给出错误:

Could not find property 'execResult' on task

我不想创建单独的任务。我希望它在 exec 块中。我做错了什么?

您需要指定此任务的类型为 Exec。这是通过像这样指定任务类型来完成的

task testExec(type: Exec) {

}

在您的特定情况下,您还需要确保在 exec 完成之前不要尝试获取 execResult 这可以通过将检查包装在 doLast 中来完成。

task testExec(type: Exec) {
    doLast {
        if (execResult.exitValue == 3) {
            println("It probably succeeded")

        }
    }
}

这是执行 ls 并检查其 return 值

的示例
task printDirectoryContents(type: Exec) {

    workingDir '.'
    commandLine "sh", "-c", "ls"

    doLast{
        if (execResult.exitValue == 0) {
            println("It probably succeeded")

        }
    }
}

project.exec() 有一个 return 类型的 ExecResult 值。

def result = exec {
    ignoreExitValue true 
    executable "cmd"
    args = ["/c", "exit", "1"]
}
println "exit value:"+result.getExitValue()

此处参考:

https://docs.gradle.org/current/dsl/org.gradle.api.Project.html#org.gradle.api.Project:exec(groovy.lang.Closure)