KIC
KIC

Reputation: 6121

Only execute a task if the executable exists

I try to execute a task only if the executable exists. From what I have found so far one should use the onlyIf but if the binary is not existing the evaluation of the onlyif fails (and so does the task). So how should one really do this. I think this is quite a common use case so there must be some standard solution to this kind of problem or not?

task test(type: Exec) {

    onlyIf {
        def result = exec { 
            ignoreExitValue = true
            commandLine 'wskz', '--help'
        }

        result.exitValue != 0
    }

    commandLine 'wskz', '--help'
}

Upvotes: 2

Views: 949

Answers (1)

user31601
user31601

Reputation: 2610

If you want to check that an executable exists by executing it, you could put a try-catch inside the onlyIf predicate like this.

task test(type: Exec) {

    onlyIf {
        try {
            def result = exec { 
                ignoreExitValue = true
                commandLine 'wskz', '--help'
            }
            result.exitValue != 0
        } catch (Exception e) {
            return false
        }
    }

    commandLine 'wskz', '--help'
}

Trying to execute the program to see whether it 'exists' might not be the best option though.

  • What if the program exists but isn't on your PATH?
  • What if the current user doesn't have permission to execute the program?
  • It might take just as long to execute the program to see if it exists as it would to attempt the full task execution.

I don't know what you would want the behaviour of your build to be in these situation, so I can't propose a definitive alternative. One suggestion would be to simply use File.canExecute() inside your onlyIf, possibly combined with a call to which/where if you need to search the PATH.

Upvotes: 4

Related Questions