Gradle:从根项目中获取所有sourceSet

时间:2018-08-14 21:41:58

标签: gradle gradle-plugin

我正在编写一个插件来为我们目前在内部工作的用例做一些自定义文件索引。

进行一些修补,我发现我可以在rootProject的buildSrc中创建任务/插件,将任务通过以下方式应用于每个模块

subprojects {
    apply plugin: MyCustomIndexerPlugin
}

我的插件的实现如下所示,并且可以在单个模块的上下文中正常工作:

@Override
public void apply(Project project) {
    Convention convention = project.getConvention();
    System.out.println("Working: " + project.getName());
    JavaPluginConvention javaPluginConvention = convention.getPlugin(JavaPluginConvention.class);
    SourceSetContainer sourceSets = javaPluginConvention.getSourceSets();

    TaskContainer taskContainer = project.getTasks();
    MyCustomIndexerTask myCustomIndexerTask = taskContainer.create("myCustomIndexerTask", MyCustomIndexerTask.class, task -> task.setSourceSetContainer(sourceSets));

    Task build = taskContainer.getByName("build");
    build.dependsOn(myCustomIndexerTask);
}

这是我的任务:

@TaskAction
public void taskAction() {
    SortedMap<String, SourceSet> asMap = getSourceSetContainer().getAsMap();
    for (String sourceSetName : asMap.keySet()) {
        SourceSet sourceSet = asMap.get(sourceSetName);
        Set<File> files = sourceSet.getAllJava().getFiles();
        for (File file : files) {
            System.out.println(sourceSetName + " -> " + file);
        }
    }
}

这可以(一定程度上)作为概念证明,但是我想让我的自定义任务在rootProject级别执行。因此,在所有模块成功构建之后,我将针对所有sourceSet运行我的代码。这是否可能,或者我需要在项目构建时以某种方式将数据从一个模块传递到另一个模块?

我很难找到合适的文档来执行需要执行的正确元编码。

1 个答案:

答案 0 :(得分:1)

您可以在rootProject的build.gradle文件中应用插件。 然后,您可以执行以下操作:

@Override
def apply(Project project) {
  if (project != project.rootProject) { throw new IllegalStateException("Can only be applied to rootProject") }
  def myCustomIndexerTask = taskContainer.create("myCustomIndexerTask", MyCustomIndexerTask.class)
  project.tasks.getByName("build").dependsOn myCustomIndexerTask

  project.subprojects.each { sp ->
    sp.whenPluginAdded(JavaPlugin) { jp ->
      def javaPluginConvention = sp.getConvention().getPlugin(JavaPluginConvention)
      def sourceSets = javaPluginConvention.getSourceSets()
      myCustomIndexerTask.addSourceSetContainer(sourceSets)
    }
  }
}

在自定义任务中,您将需要遍历所有添加的SourceSetContainers

相关问题