Gradle optional @Input
Asked Answered
P

2

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
    }

    // ...   
}
Papilloma answered 10/1, 2017 at 10:5 Comment(0)
P
8

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

    // ...    
}
Papilloma answered 25/1, 2017 at 14:48 Comment(1)
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?Riff
U
2
class CustomTask extends DefaultTask {
    void setPreconfig(Closure c) {
        inputs.property("preconfig", c)
    }
    ...
}

@see TaskInputs

Upsilon answered 10/1, 2017 at 10:15 Comment(1)
Well, in this way I also have to declare separate methodPapilloma

© 2022 - 2024 — McMap. All rights reserved.