Conditional logic in gradle build to only execute certain code when a specific task is running
<p>So, I am using a plugin in my gradle build (the plugin is org.flywaydb.flyway but that is not really relevant). I want to validate the caller has passed in a runtime parameter when tasks from this plugin are executing but not when other tasks are executing.</p>

<p>I pass options to the flyway plugin based on a supplied parameter. I want an error to be returned when a flywayTask is being executed and no parameter is supplied. When a non-flyway task is being run, I do not want to validate if the parameter is supplied.</p>

<pre><code>gradle -PmyParam=myValue flywayMigration
</code></pre>

<p>=> should run code and there should be no error</p>

<pre><code>gradle flywayMigration
</code></pre>

<p>=> should run code and should produce error (as no parameter supplied)</p>

<pre><code>gradle jar
</code></pre>

<p>=> should not run code and no error should be produced</p>

<p>I have been reading about gradle configuration and execution which is fine but I still can't find a way to only run the code when the flyway plugin is bveing executed OR specific flyway tasks are being executed.</p>

<p>This is my current code:</p>

<pre><code>if(gradle.taskGraph.hasTask("flywayMigrate")) {
    flyway {

        def dbCode, dbUser, dbPassword, dbUrl

        if (!project.hasProperty("db_env")) {
            throw new GradleException("Expected db_env property to be supplied for migration task. Can be passed" +
                    " at command line e.g. [gradle -Pdb_env=ex1 flywayMigrate]")

        } else {
            // do stuff

        }

        user = balh
        password = blah
        url = blah
        driver = 'oracle.jdbc.OracleDriver'
        cleanDisabled = true
        baselineOnMigrate = true
        baselineVersion = '1.0.0'

    }
}
</code></pre>

<p>To be clear, I only want this code:</p>

<pre><code>if (!project.hasProperty("db_env")
</code></pre>

<p>to run for flyway tasks.</p>

<p>The code above throws this error:</p>

<pre><code>Task information is not available, as this task execution graph has not been populated.
</code></pre>

<p>I've tried a few things here, any advice would be appreciated.</p>