Search code examples
androidgradleandroid-gradle-pluginbuild.gradlegradlew

gradle Exec block should not fail for non zero output in


I am writing a gradle task. The task it invokes returns 3 for successful run instead of 3. How do I go about doing this ?

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")
      }
   }
}

It gives the error:

Could not find property 'execResult' on task

I don't want to create a separate task. I want it to be in the exec block. What am I doing wrong?


Solution

  • You're going to need to specify that this task is of type Exec. This is done by specifying the task type like so

    task testExec(type: Exec) {
    
    }
    

    In your specific case, You'll also want to make sure you don't try to get the execResult until the exec has finished this can be done by wrapping the check in a doLast.

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

    Here's an example of executing ls and checking its return value

    task printDirectoryContents(type: Exec) {
    
        workingDir '.'
        commandLine "sh", "-c", "ls"
    
        doLast{
            if (execResult.exitValue == 0) {
                println("It probably succeeded")
    
            }
        }
    }