英文:
How to call a Gradle task in all subprojects?
问题
好的,以下是您要求的翻译内容:
假设我有一个Gradle项目的层次结构,其中一些项目应用了`java`插件:
根目录
projA
projA1
projA2 (java)
projB
projB1 (java)
projB2
projB21 (java)
projB22 (java)
projC (java)
我想要在所有具有此任务的子项目中执行`test`任务: `:projA:projA2:test`, `:projB:projB1:test`和 `:projC:test`。可能我将来会添加更多的项目,我不想手动维护所有子项目中所有测试任务的列表。我该如何实现?
我脑海中浮现出一种方法,类似于以下内容:
// 在根目录中,我遍历所有子项目,根据名称查找任务,从而创建并配置任务
tasks.register("testAll") {
dependsOn subprojects.findResults { it.tasks.findByName("test") }
}
我不喜欢这种方法,因为它违反了[任务配置避免](https://docs.gradle.org/current/userguide/task_configuration_avoidance.html)的风格。
另一个选项是遍历子项目并检查是否应用了`java`插件:
// 在根目录中
tasks.register("testAll") {
dependsOn subprojects.findAll { it.plugins.hasPlugin("java") }.collect { it.tasks.named("test") }
}
这个方法也可以工作,但我觉得可能有更简单的方法...
**编辑1**:抱歉,我忘记了一个重要细节 - 我需要在项目的子树中运行测试。例如,沿着路径 `:projB` 的所有项目。
英文:
Say, I have a hierarchy of Gradle projects and some of them have java
plugin applied:
root
projA
projA1
projA2 (java)
projB
projB1 (java)
projB2
projB21 (java)
projB22 (java)
projC (java)
I want to execute the test
task in all subprojects where this task exists: :projA:projA2:test
, :projB:projB1:test
and :projC:test
. Probably I will add more projects in future and I don't want to manually support a list of all test tasks in all subprojects. How can I achieve it?
One thing that came to my mind is something like the following:
// In root I iterate over all subprojects and find the task by name causing
// its creation and configuration
tasks.register("testAll") {
dependsOn subprojects.findResults { it.tasks.findByName("test") }
}
I don't like this approach as it goes against task configuration avoidance style.
Another option is to iterate over subprojects and check if the java
plugin is applied there:
// In root
tasks.register("testAll") {
dependsOn subprojects.findAll { it.plugins.hasPlugin("java") }.collect { it.tasks.named("test") }
}
It works but I have a filling that I miss something simpler...
EDIT 1: Sorry for that but I forgot one important detail - I need to run tests in a subtree of projects. Say, everything down the path :projB
.
答案1
得分: 2
除非我理解错了,你想要为所有的子模块运行测试。
你只需要……这样做。
./gradlew clean test
这会在所有已经配置好的子项目中运行测试任务。
如果你需要在特定的子项目中运行任务,从根项目开始,你可以指定你想要运行任务的子项目。
./gradlew clean :projB:test
如果你的子项目有一个需要在测试之后运行的任务,你可以在你的 subprojects
块中这样做。
subprojects {
myTask.dependsOn("test")
}
英文:
Unless I'm missing something, you want to run tests for all of your submodules.
You can just...do that.
./gradlew clean test
This will run the test task in all of the subprojects that have it sufficiently configured.
If you need to run the tasks in a specific subproject, from the root project you can specify the subproject you want to run the task.
./gradlew clean :projB:test
If your subprojects have a task that needs to run after test, then you can do this in your subprojects
block.
subprojects {
myTask.dependsOn("test")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论