[英]How to filter submodules in gradle to apply appropriate plugin?
I have a multi-module project of which some are Java libraries and others Android libraries. 我有一个多模块项目,其中一些是Java库和其他Android库。 I wanted to apply custom plugins for my sub projects (modules) depending on the project type, so I have done something like this (see below code snippet) in my project root's build.gradle
file. 我想根据项目类型为我的子项目(模块)应用自定义插件,所以我在项目root的build.gradle
文件中做了类似的事情(见下面的代码片段)。 This setup is working but I'm wondering if there is any other way of doing it. 这个设置正在运行,但我想知道是否还有其他方法可以做到这一点。 Gradle suggests Filtering by properties but I get the error Cannot add task 'integTest' as a task with that name already exists
if I try that. Gradle建议按属性过滤,但我收到错误Cannot add task 'integTest' as a task with that name already exists
如果我尝试的话Cannot add task 'integTest' as a task with that name already exists
。 The integTest
is a task I created in customJavaBuild.gradle
and customAndroidBuild.gradle
files. integTest
是我在customJavaBuild.gradle
和customAndroidBuild.gradle
文件中创建的任务。 Any help is appreciated. 任何帮助表示赞赏。 Thanks! 谢谢!
def javaLibraries = ["projA", "projB"]
def androidLibraries = ["projC"]
subprojects {
if (javaLibraries.contains(it.name)) {
apply from: '$rootDir/gradle/customJavaBuild.gradle'
} else if (androidLibraries.contains(it.name)) {
apply from: '$rootDir/gradle/customAndroidBuild.gradle'
} else {
//Apply custom plugin for some other project type.
}
}
Filtering by properties 按属性过滤
subprojects {
project.ext {
projectType = null
}
project.afterEvaluate {
if (project.ext.projectType == 'jar') {
apply from: '$rootDir/gradle/customJavaBuild.gradle'
} else if (project.ext.projectType == 'aar') {
apply from: '$rootDir/gradle/customAndroidBuild.gradle'
} else {
//Apply custom plugin for some other project type.
}
}
}
And I have this extra property ext.projectType = 'jar'
in my sub-modules' (projA, projB, projC) build.gradle
files. 我在我的子模块'(projA,projB,projC) build.gradle
文件中有这个额外的属性ext.projectType = 'jar'
。
The problem is that in your project.afterEvaluate
block you are applying your custom gradle script to the root project
and not to the evaluated sub project
, which causes the error with integTest
task already defined. 问题是在您的project.afterEvaluate
块中,您将自定义gradle脚本应用于root project
而不是应用于已评估的sub project
,这会导致已定义integTest
任务的错误。
You should rewrite your project.afterEvaluate
block with something similar to the following: 您应该使用类似于以下内容的内容重写project.afterEvaluate
块:
subprojects {
project.ext {
projectType = null
}
project.afterEvaluate {
if (project.ext.projectType == 'jar') {
// WARNING : use "project.apply ..." instead of "apply ..." here
project.apply from : "$rootDir/gradle/customJavaBuild.gradle"
} else if (project.ext.projectType == 'aar') {
project.apply from : "$rootDir/gradle/customAndroidBuild.gradle"
} else {
// nothing
}
}
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.