Exit gradle build when System Environment Variable is not set

I would like to know how to exit a gradle build when a particular System Environment Variable is not set. I would like to exit the build in configuration phase or earlier if this is true: System.getenv(‘MyDir’) == null

At the very least, you can do something like:

if (System.getenv('MyDir') == null) {
   throw new GradleException("Please export 'MyDir' <some useful message>")
}

But this is unfriendly because even gradle help and gradle tasks will fail with this message. To make this more friendly, you should only fail if someone tries to execute a task that requires a value for MyDir:

gradle.taskGraph.whenReady { taskGraph ->
    if (taskGraph.hasTask(taskThatUsesMyDir) && System.getenv('MyDir') == null) {
       throw new GradleException("Please export 'MyDir' <some useful message>")
    }
}

But this is a bit of a smell too. Instead of using environment variables, you should probably provide a conventional default and allow people to override that default with a property in their ~/.gradle/gradle.properties file.

Thanks for the response. I may have to opt for the messy for now.