What is TaskInputFilePropertyBuilder.optional() meant to do?

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.

Generally inputs are attached to properties, not just hard-coded if you have custom implementation like this. An optional input means that property can be specified or not. If you specify it as an input and it’s a type like a single file, it still must be a valid input, which would mean that the file exists.

If you want logic based on the file existence, you do have to implement that yourself, but typically you wouldn’t do that through the runtime API and would write a custom task type rather than ad hoc in your build script.

Thanks, I understand your point. Unfortunately there are some misleading StackOverflow answers on this, I will try to get them updated.

I think it would be a good idea to have a way to mark a file as “optional”, or “treatAsBlankIfNonexistent”, or something like that, so the task validation will still pass if the file doesn’t exist, but if it does exist its contents will be considered in up-to-date checks.