Programmatically add Sourceset in Java (csutom) Task?

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:

@TaskAction
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();
  destinationFile.getParentFile().mkdirs();

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

  writer.writeModule(widgets);
}

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");
sourceSets.getByName("main").getResources().srcDir(destinationRoot);

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?

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: ‘com.android.library’

android {
  compileSdkVersion 23
  buildToolsVersion “22.0.1”

defaultConfig {
  minSdkVersion 14
  targetSdkVersion 23
}

sourceSets {
  main {
   java {
    if (OperatingSystem.current().isLinux() && System.getProperty(‘user.name’) == ‘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.