Programmatically add Sourceset in Java (csutom) Task?

(Ben Leitner) #1

I’m working on my first-ever custom gradle task. It’s supposed to be a little plugin that will scan Android layout xml files and generate some code. So far, I have a Task class that looks like this:

public void createDaggerModuleForViews() throws Exception {
  Project project = getProject();
  CustomExtension extension =
      project.getExtensions().findByType(CustomExtension .class);

  if (extension == null) {
    extension = new CustomExtension();

  String applicationPackage = extension.getApplicationPackage();

  File getOutputRootDirectory = getOutputRootDirectory(); 
  File destinationFile = getDestinationFile();

  some other code to read the xml files and produce code.
  MyCodeWriter writer = new MyCodeWriter(destinationFile);


Everything seems to be working fine, but I also want the generated code to be automatically added to a sourceset, so as to avoid having to also manually add the sourceset to my build.gradle file.

After some searches, I found the following code snippet:

SourceSetContainer sourceSets = (SourceSetContainer) project.getProperties().get("sourceSets");

but this gives an error that no sourceset “main” is found. In fact, with some logging statements, a call to sourceSets.getAsMap() reveals that the map is empty, and trying project.getRootProject leads to sourceSets being null.

I’ve also tried using a @OutputDirectory-annotated File field on my task class and setting it on construction to the correct directory. This does not help.

Is it possible to dynamically add the sourceSet when my task executes? If so, what’s the correct magic incantation?

(vincestyling) #2

I tried do what you want in XXX.groovy in my project, but I even can’t take the SourceSets object.

So I change my way to achieve the purpose and it worked, below is my configuration.

import org.gradle.internal.os.OperatingSystem

apply plugin: ‘’

android {
  compileSdkVersion 23
  buildToolsVersion “22.0.1”

defaultConfig {
  minSdkVersion 14
  targetSdkVersion 23

sourceSets {
  main {
   java {
    if (OperatingSystem.current().isLinux() && System.getProperty(‘’) == ‘lingyunxiao’) {
     srcDir ‘/home/lingyunxiao/dev/gm-plugin-commands’

you can do just like this, to determinate if your term satisfy then pass to the append sourcesets logic.