'How do I make a Task depend on the build.gradle itself?

I have the following build.gradle file. Currently the task generateSources runs every time gradle is executed ("BUILD SUCCESSFUL"). I would instead like it to only execute when the build.gradle file itself changes, so that the build is an incremental build ("UP-TO-DATE")

i.e. I want it's "input" to be the "build.gradle" itself.

How do I do this?

apply plugin: 'java'
apply plugin: 'application'

mainClassName = 'Main'
version = "1.0"

task generateSources() {
    // inputs = ????
    // onlyIf ???
    
    outputs.upToDateWhen { true } // in the real code this is a file
    doFirst {
        println("Hello, World! $project.version")
    }
}

compileJava.dependsOn generateSources

(The code above is simplified to the bare minimum. In reality the task generate some files, and they are configured properly in Task.output)



Solution 1:[1]

There are two ways as I know, finalizedBy and dependsOn The finalizedBy means do this after this task

tasks.named("build") { finalizedBy("myTaskName") }

And the dependsOn means that after build do this task

tasks.named("myTaskName") { dependsOn("build") }

More information about tasks on the official docs

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 George