pepuch
pepuch

Reputation: 6516

Pass properties to custom gradle task

How can I pass properties to gradle custom task? In ant It will look like this:

public class MyCustomTask extends Task {

    private String name;
    private String version;

    @Override
    public void execute() throws BuildException {
        // do the job
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setVersion(String version) {
        this.version = version;
    }

}

How to do it in gradle?

class MyCustomTask extends DefaultTask {

    private String name
    private String version

    @TaskAction
    def build() {
        // do the job
    }

}

Properties name and version are required and user needs to pass them to task.

Upvotes: 14

Views: 17206

Answers (2)

Ben W
Ben W

Reputation: 2479

You can use -P option to pass command line arguments.

For ex:

public class MyCustomTask extends DefaultTask {

    String name;
    String version;

    @TaskAction
    public void execute() throws BuildException {
        // do the job
    }
}

Gradle task

 task exampleTask(type: MyCustomTask) {
    name = project.property("name")
    version = project.property("version")
} 

Gradle command

gradle -Pname="My name" -Pversion="1.2.3"

Check https://docs.gradle.org/current/userguide/gradle_command_line.html for all command line options for Gradle.

Upvotes: 7

pepuch
pepuch

Reputation: 6516

I found the solution:

class MyCustomTask extends DefaultTask {

    @Input
    String name
    @Input
    String version

    @TaskAction
    def build() {
        // do the job
        println name
        println version
    }

}

Example use:

task exampleTask(type: MyCustomTask) {
    name = "MyName"
    version = "1.0"
}

Upvotes: 14

Related Questions