5

How can I provide an optional property for task?

class CustomTask extends DefaultTask {

    @Input
    Closure preconfig

    // ...    
}

This way obligates user to provide preconfig closure as parameter when defining task with CustomTask type.

How can I achieve declarative way other than defining methods to set properties?

class CustomTask extends DefaultTask {

    @Input
    Closure preconfig

    def preconfig(Closure c){
        this.preconfig = c
    }

    // ...   
}
Andrii Abramov
  • 10,019
  • 9
  • 74
  • 96

2 Answers2

7

Actually, I found a solution in assigning default value to the @Input fields.

Example:

class CustomTask extends DefaultTask {

    @Input
    Closure preconfig = null // or { } <- empty closure

    // ...    
}

And then check if the @Input variable is not null:

// ...

@TaskAction
def action(){
    if (preconfig) { preconfig() }
}

// ...

Also there is useful annotation @Optional:

class CustomTask extends DefaultTask {

    @Input @Optional
    Closure preconfig

    // ...    
}
Andrii Abramov
  • 10,019
  • 9
  • 74
  • 96
  • can I also use the `@Optional` in a build.gradle file? For example if I have something like: task npmBuild (type: Exec) { inputs.dir './src' ... , can I make this optional? – bersling Jan 17 '19 at 13:18
2
class CustomTask extends DefaultTask {
    void setPreconfig(Closure c) {
        inputs.property("preconfig", c)
    }
    ...
}

@see TaskInputs

lance-java
  • 25,497
  • 4
  • 59
  • 101