Best practices for tasks <docs.gradle.org/current/...
# community-support
b
Best practices for tasks docs.gradle.org/current/userguide/best_practices_tasks.html#… shows this piece of code
Copy code
inputs.file(tasks.named<SimplePrintingTask>("helloWorld").map { messageFile })
do you need that in addition to configuring the inputs of the new task or does gradle figure that out automatically if you use an input file with the same path as the other task's output file?
1
j
That code looks wrong. I don't think it works. 🤔 I assume it was meant to configure the inputs and should look like this IMO:
Copy code
tasks.register("translateGood", SimpleTranslationTask) {
    messageFile.set(tasks.named("helloWorld", SimplePrintingTask).flatMap { it.messageFile })
}
Explanation: • First
messageFile
is the one from SimpleTranslationTask • You set that to the
messageFile
output of SimplePrintingTask, preserving both the information which file you want and which task produces it. It's also an unfortunate choice to call it
messageFile
in both example tasks.
b
exactly, that also confused me
but you need to fetch it from the task itself, correct? not just use the same path to the same file and hope it'll be auto detected
j
Yes. The
flatMap
gives you a
Provider<RegularFile>
that not only points at the path, but also has the information which task produces the file.
v
It at most auto-detects under some conditions that you use the output of the other task without dependency or ordering constraint. That's the situation where you get the bad advice by Gradle to add one explicitly.
It will not add automatic task dependencies due to configured paths.
Hence you should never configure paths explicitly, but always wire task outputs to task inputs like Jendrik showed
t
IIUC, this will work because the convention value is the same in both tasks, but Gradle won't automatically detect the dependency (actually, it will and tell you that it's wrong and won't be used and you should fix it (by explicitly configuring the task dependency as shown here): docs.gradle.org/current/userguide/validation_problems.html#…) so you have to tell it, and
inputs.file()
is finer-grained than `dependsOn()`; but this is a bad example anyway. What you should do is indeed configure the input property to the output property of the other task, with a provider value that carries the task dependency.
❤️ 1
v
And someone™ should open a ticket or pull-request to update this bad example
💯 2