How to fail/stop task immediately if some conditions are not met

What is a good way to conditionally execute a task?

I current have a task called “makerpm”, which as the name imply build an rpm. It depends on other tasks which compile and package the jars. This is all working fine, but I’d like to make it so that when executed on a windows machine or a linux machine without rpmbuild, it should fail and not proceed.

what I have is

task makerpm(type: Exec, dependsOn: buildDist){
   onlyIf {
    def ok = false
    ok = hasRpmbuild() //assume this exist
    if(!ok) throw new StopExecutionException("rpmbuild does not exist")
  //other stuff

what I am seeing is, it’ll execute buildDist and at the end, makerpm will fail as rpmbuild does not exist. But what I want to achieve is, makerpm should fail immediate if it fails validation, so that buildDist task is not initiated.

I think this is an incorrect use of onlyIf, any suggestions?


To validate a task before any task has been executed, you can use the ‘taskGraph.whenReady’ callback:

gradle.taskGraph.whenReady { graph ->
    if (graph.hasTask(makerpm) && !hasRpmbuild()) {
        throw new GradleException("rpmbuild does not exist")

Thank you for the pointer Peter, much appreciate it. With that my gradle build script is complete!