How to make up-to-date check notice non-file arguments in a Gradle Task?

115 views Asked by At

Suppose I have a task class MyTask which reads an input file, does some conversion on it and writes an output file (build.gradle):

class MyTask extends DefaultTask {
    @InputFile File input
    @OutputFile File output
    String conversion

    @TaskAction void generate() {
        def content = input.text
        switch (conversion) {
            case "lower":
                content = content.toLowerCase()
                break;
            case "upper":
                content = content.toUpperCase()
                break;
        }
        output.write content
    }
}

project.task(type: MyTask, "myTask") {
    description = "Convert input to output based on conversion"
    input = file('input.txt')
    output = file('output.txt')
    conversion = "upper"
}

Now this all works fine, when I change input.txt or remove output.txt in the file system it executes again. The problem is that it doesn't execute if I change "upper" to "lower", which is wrong.

I can't (don't want to) put build.gradle in the inputs list because that would be a hack, also wouldn't work if, say, a command line argument changes what gets into the myTask.conversion field. Another one I thought of is to write the value into a file in a setConversion() method and put that on the inputs list, but again, that's a hack.

How can I make gradle notice the change the official way? Also if you know where can I read more about this, don't hold back on links ;)

I read More about Tasks and Writing Custom Plugins, but it gave me no clue.

2

There are 2 answers

1
Opal On BEST ANSWER

Not sure if it's helpful but I'd try:

class MyTask extends DefaultTask {
    @InputFile File input
    @OutputFile File output
    String conversion

    @TaskAction void generate() {
        def content = input.text
        switch (conversion) {
            case "lower":
                content = content.toLowerCase()
                break;
            case "upper":
                content = content.toUpperCase()
                break;
        }
        output.write content
    }

    void setConversion(String conversion) {
       this.inputs.property('conversion', conversion)
       this.conversion = conversion
    }
}

Could you please check it?

0
TWiStErRob On

There is a handy @Input annotation, which is the same as Opal's answer (check its source code), but little more concise:

@Optional @Input String conversion

Here's a Gradle goodness article about this.