Home > Net >  How do I make a Task depend on the build.gradle itself?
How do I make a Task depend on the build.gradle itself?

Time:02-03

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)

CodePudding user response:

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

CodePudding user response:

It turns out you can just put an input-dependency on the project file object itself with something like inputs.file project.buildFile.

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

mainClassName = 'Main'
version = "1.0"

task generateSources() {
    
    inputs.file project.buildFile // only rebuild when _this_ build.gradle changes
    
    outputs.upToDateWhen { true } // in the real code this is a file
    doFirst {
        println("Hello, World! $project.version")
    }
}

compileJava.dependsOn generateSources
  •  Tags:  
  • Related