Gradle sync in Intellij executes closures of task.register

I currently have something like:

tasks.register("complexTest") {
  if (!System.getenv('CLOUD_PROJECT')) {
    throw new GradleException("Must set environment variable CLOUD_PROJECT")
  }
  // ... and some stuff
}

now this works fine from the command line if CLOUD_PROJECT is not set, since we don’t execute the closure on complexTest.

However when sync’ing with intellij, it attempts to configure the task even though it’s not in the current task graph. So sync fails with GradleException: Must set environment variable CLOUD_PROJECT

Is there some way to

  1. detect that a sync is happening and disable this part of my build
  2. make intellij stop deep resolving tasks?

I know I could potentially do, but I want to fail fast

task complexTest {
   doFirst {
      if (!System.getenv('CLOUD_PROJECT')) {
        throw new GradleException("Must set environment variable CLOUD_PROJECT")
      }
    }
}

Perhaps this mechanism was never intended for control flow? And is only a speed optimization?

detect that a sync is happening and disable this part of my build

There’s no direct way to detect if the configuration happens in the context of an IDE synchronization, but you can check the executed tasks. The synchronization doesn’t execute any tasks by default, but there’s an option so it’s only a workaround:

tasks.register("complexTest") {
  if (!gradle.startParameter.taskRequests.isEmpty()) {
    if (!System.getenv('CLOUD_PROJECT')) {
      throw new GradleException("Must set environment variable CLOUD_PROJECT")
    }
  }
}

make intellij stop deep resolving tasks?

I don’t think it’s possible, IDEA realizes the whole task graph when populating the task view.

Perhaps this mechanism was never intended for control flow? And is only a speed optimization?

You are correct, in general, it is better to run assertions at the beginning of the doFirst {} block, because it can only invalidate for the specific task. Your initial proposal basically says that the whole build (i. e. all of the tasks) is invalid if the CLOUD_PROJECT environmental variable is absent. By the way, if you replace the environmental variable with system/project properties, then you can define a default value in gradle.properties and overwrite it via command-line arguments.

Makes sense, thanks for the response.

I was trying to get a whole suite of things to fail early, but I think this is fast enough, given a rebuild will UP-TO-DATE the rest of the tasks I was checking.