我正在编写一个插件来为我目前工作的内部用例做一些自定义文件索引。
做了一些修改,我发现我可以在 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/