In Gradle 7.2 I have the following build file:
def complexGroovyFunction() {
println "Imagine I do something complex"
if (file("input.txt").exists())
println "I found input.txt so I will use it as input"
else
println "I didn't find input.txt, but I don't need it, it is optional for me"
}
task runComplexGroovyFunction {
inputs.file("input.txt")
doLast this.&complexGroovyFunction
}
input.txt
is meant to be an optional input – the task will rely on its contents if it exists, but still run fine even if it doesn’t. If input.txt
exists, ./gradlew runComplexGroovyFunction
produces this output:
Imagine I do something complex
I found input.txt so I will use it as input
But if input.txt
doesn’t exist, the build fails with Property '$1' specifies file 'input.txt' which doesn't exist
. So how do I make this task input optional?
I thought I could use TaskInputFilePropertyBuilder.optional()
:
task runComplexGroovyFunction {
inputs.file("input.txt").optional()
doLast this.&complexGroovyFunction
}
But the .optional()
part doesn’t do anything, you can the same behaviour with or without it. Do I misunderstand what it is meant to do?
This does work, but seems ugly:
task runComplexGroovyFunction {
if (file("input.txt").exists()) inputs.file("input.txt")
doLast this.&complexGroovyFunction
}
BTW, I posted basically the same question on StackOverflow, no response, so I am trying here.