Gradle:从根项目获取所有源集

标签 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 级别执行我的自定义任务。因此,在所有模块构建成功后,我针对所有源集运行我的代码。这是可能的还是我需要在我的项目构建时以某种方式将这些数据从一个模块传递到另一个模块?

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

最佳答案

您可以在 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添加的。

关于Gradle:从根项目获取所有源集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51850156/

相关文章:

android - Gradle 找不到 list 文件

eclipse - 如何使用 eclipse 和 gradle 创建 Java EE 7 应用程序?

gradle - 如何在多个 Gradle 项目之间共享样板 Kotlin 配置?

groovy - 在 gradle 项目中使用 archivesBaseName 没有效果

junit - 在使用 gradle --parallel 运行测试时按顺序运行两个测试类

gradle - 从Gradle任务跟踪(和删除)输出文件

gradle - Gradle 中的任务和插件冲突(无法应用插件 [class 'org.gradle.langu...)

android - 如何在Android库项目中按测试类型分隔源文件?

gradle - 使用gradle构建分发zip文件后,如何复制?

gradle - 如何用Gradle替换log4j2.xml?