Msp Msp - 1 month ago 11
Groovy Question

Gradle : Multiple subtasks share the same extension variable object

I have created a custom Gradle plugin like this,

DummyPlugin.java

public class DummyPlugin implements Plugin<Project> {
@Override
public void apply(Project project) {
project.getTasks().create("dummy", DummyTask.class);
project.getExtensions().create("dummy", DummyExtension.class);
}
}


DummyTask.java

public class DummyTask extends Test {
@TaskAction
public void dummy() {
Project project = getProject();
DummyExtension extension = project.getExtensions().findByType(DummyExtension.class);
System.out.println("Env of dummy is " + extension.getEnv());
}
}


DummyExtension.java

public class DummyExtension {
private String env;

public String getEnv() {
return env;
}

public void setEnv(String env) {
this.env = env;
}
}


Now, I have created three tasks for different environments, like this :

apply plugin: 'dummy'

task dummyCI(type: DummyTask) {
dummy {
env = 'ci'
}
}

task dummyDev(type: DummyTask) {
dummy {
env = 'dev'
}
}

task dummyTest(type: DummyTask) {
dummy {
env = 'test'
}
}


But, on running
./gradlew dummyCI
, instead of getting
Env of dummy is ci
, I'm getting
Env of dummy is test
. Same for
./gradlew dummyDev
also.

How do I fix this issue? Thanks.

Answer

You're setting the extension property in the configuration phase which always runs. So each invocation is overriding the previous. To set it in the execution phase, use a doFirst { ... } block. Eg:

task dummyCI(type: DummyTask) {
    doFirst {
        dummy {
            env = 'ci'
        }
    }
}

Or perhaps a better solution is to get rid of the extension object all together and instead add the env property (input?) to the DummyTask