Task with dependsOn a file


(Mike Cooper) #1

I have a simple task like this:

task generateJava(type: JavaExec) {
....
}

I want to be able to add a dependency so this task is run whenever a specific file under the project changes.

How do I do that?


(Benny Akesson) #2

Hi!

You do this by declaring the file as an input of the task, e.g.

inputs.file ‘path to file’

For a more general discussion about declaring inputs and outputs of tasks, please refer to Section 17.9 in the Gradle user guide:
https://docs.gradle.org/current/userguide/more_about_tasks.html

Good luck!


(Mike Cooper) #3

Thanks for the pointer to using inputs.file. I see that I must also give outputs as well so gradle knows what to compare the inputs to.

My challenge is that my custom task takes an input file and generates a number of output files (java source files). I don’t know the names of the files.

I tried this:

task generateJava(type: JavaExec) {
  inputs.file 'ecore.xml'
  outputs.dir 'src-gen'
  main = "..."
  args "--outdir", "src-gen"
}

When the task is run it creates multiple .java files under “src-gen/org/acme/my/class/*.java”

If I run “gradle generateJava” twice, my java class (main) gets run each time. I’m expecting that the second time just to see gradle output “generateJava: UP-TO-DATE”.

Any suggestions on how to give the proper “outputs” value in this case?


(Benny Akesson) #4

Hi!

I am a Gradle Newbie and so I cannot say for sure, but the user guide suggests in Section 17.9.2 that your solution should work. However, I often find the user guide lacking important information. Unfortunately, I cannot help you further for the moment. Let’s hope someone else can step in and clarify how setting a directory as an output works and why it does not work for you.


(Andreas Axelsson) #5

You can use the onlyIf predicate to create custom logic for when the task should run. I’m modifying a file based on some properties, and I use the onlyIf statement to skip the task if the changes have already been applied.