Search code examples
gradlegradle-task

Gradle Copy task always UP-TO-DATE


I've seen this question posted numerous times, but I've not yet found an answer that matches my specific use case.

I'm created a bunch of config files from a template, after iterating over a config file containing environment properties.

The problem is that if I amend src/properties/ENV.gradle with some new values, it's ignored when I call the task on the basis that it's already "UP-TO-DATE". I'm not using doFirst or doLast, which is one of the common reasons this happens.

My workaround so far is to include

outputs.upToDateWhen { false }

which forces the config files to be recreated every single time regardless of what Gradle calculates, but it feels like an awful hack. Is there a better way?

Here's the code:

task createConfigs

def addTemplateTasks(aProject, env, config) {
    aProject.with {
        task "templateCopy_${env}"(type: Copy) {
            from "src/templates"
            include "server.config.template"
            into "${buildDir}"
            rename { file -> "server.config.${env}" }
            expand(regionConfig)

        }
        createConfigs.dependsOn "templateCopy_${env}"
    }
}

def envFile = new File("${project.projectDir}/src/properties/ENV.gradle")
def envConfig = new ConfigSlurper().parse(envFile.text)
envConfig.each { env, config ->
    addTemplateTasks(project, env, config)
}

SOLUTION: My case was a bit specific in that I was expecting the Copy task to notice "config" changing, without telling it explicitly care about it (see accepted answer below). Here's the change that fixed the problem:

def addTemplateTasks(aProject, env, config) {
    aProject.with {
        task "templateCopy_${env}"(type: Copy) {
            inputs.property("environmentConfig", config)

The first arg (in quotes) is the name for this property, the second is the actual value.

Now, when I change a property in the ENV.gradle file and run "gradle -i", I see this:

Task ':component-foo:templateCopy_DEV' is not up-to-date because:
  Value of input property 'environmentConfig' has changed for task ':component-foo:templateCopy_DEV'

Solution

  • The only input of your copy task, is the src/templates directory. Unless the content of src/templates doesn't change an the copied outputs are still present, your task will be considered UP-TO-DATE.

    The problem is that your copy task actually has a second input which Gradle doesn't know about: Your config/regionConfig object.

    Try to add the config object (or a hash of the objects values) to the inputs of the copy task using inputs.property or inputs.properties.