14

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.

pepuch
  • 6,346
  • 7
  • 51
  • 84

2 Answers2

14

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"
}
pepuch
  • 6,346
  • 7
  • 51
  • 84
  • 6
    It's worth noting that the @Input annotation is actually intended to be used by the task's upToDateWhen method to determine if a task needs to be rerun. Chances are pretty decent that this is still correct for your use case, but if it was an unintended side effect you could have merely changed `private String name` to `def String name` and groovy would have taken care of the getters and setters for you. – Josh Gagnon Jun 05 '13 at 14:57
  • As I understand I can remove @Input and change properties to `def String name` and it will also work? – pepuch Jun 05 '13 at 15:07
  • I believe so. In my own custom task I have `def String serviceName` and it works just fine. – Josh Gagnon Jun 05 '13 at 15:09
  • 1
    Just remember that in Groovy one uses `def` instead of types. So it is either `def serviceName` or `String serviceName`. – stigkj Nov 22 '13 at 12:29
  • 1
    Adding to what @JoshGagnon wrote, the [`@Input` documentation](https://docs.gradle.org/current/javadoc/org/gradle/api/tasks/Input.html) says that it should be attached to a property, but is not clear if for Groovy the annotation will be ignored when used for a field. – Marcono1234 Oct 19 '18 at 16:22
7

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.

Ben W
  • 2,469
  • 1
  • 24
  • 24