我目前将一些旧的巨大Maven 1脚本迁移到Gradle 。 因此,我需要调整旧的Maven 1 / Ant& amp;它的目标逻辑是Gradle。
在阅读了Gradle用户指南以及Gradle任务和方法的一些文章之后,我对编写脚本的方式感到很困惑。
在官方Gradle User Guide, §6.1中,解释了 Gradle任务:
表示构建执行的原子作品
在§6.11中,还解释了我们可以使用方法来组织构建逻辑。
所以,我的问题是:使用它们的正确方法是什么?
我正在创建一个构建脚本,在我看来:
gradle doSomeInternalTechnicalWork
对我来说不正确,因为用户甚至不知道doSomeInternalTechnicalWork
存在
在我看来,它应该不是一项任务。使用前一个逻辑,当我的方法需要调用Gradle任务时遇到问题(比如Java插件的JAR创建)。
我知道I should not call task from task(对于方法中的任务也是如此),但是,看一下这个例子:
task independentTask << {
// initialization stuff
println "doing a lot of initialization"
// using methods to organize build logic, good or not?
doComplexThingsThatTheUserShouldNeverDoHimself()
}
task dependentTask(dependsOn: 'independentTask') << {
println "now that 'independentTask' is done, I can continue to do complex things..."
}
void doComplexThingsThatTheUserShouldNeverDoHimself() {
println "doing really complex things"
// I really need to create my JAR here and not somewhere else
// And I know it's not a good thing to directly call the Action.execute
jar.execute()
println "doing other really complex things"
}
在这种情况下,什么是正确的构建逻辑?
是否应该在一个或多个任务中转换doComplexThingsThatTheUserShouldNeverDoHimself
,以便能够dependsOn
JAR任务?
但这确实意味着有很多任务,可由用户调用,而事实上并非如此。
答案 0 :(得分:2)
经过大量搜索后,我得出结论,当您需要从另一个任务调用任务时,您别无选择,只能依赖任务关系( dependsOn
,mustRunAfter
,finalizedBy
)。
这意味着方法不能用于组织构建逻辑,就像它们用于在Java中构建程序一样,Groovy&amp;有限公司
因此,您无法阻止用户查看(和使用)某些内部任务,这些内部任务通常只应被其他任何内部任务用作依赖项。
以前的构建脚本的“Gradle correct”版本将是:
task dependentTask(dependsOn: 'doComplexThingsThatTheUserShouldNeverDoHimselfPart2') << {
println "now that 'independentTask' is done, I can continue to do complex things..."
}
task doComplexThingsThatTheUserShouldNeverDoHimselfPart2(dependsOn: ['doComplexThingsThatTheUserShouldNeverDoHimselfPart1', 'jar']) << {
println "doing other really complex things"
}
task doComplexThingsThatTheUserShouldNeverDoHimselfPart1(dependsOn: 'independentTask') << {
println "doing really complex things"
}
task independentTask << {
// initialization stuff
println "doing a lot of initialization"
}
或者,任务关系单独声明:
task dependentTask << {
println "now that 'independentTask' is done, I can continue to do complex things..."
}
task independentTask << {
// initialization stuff
println "doing a lot of initialization"
}
task doComplexThingsThatTheUserShouldNeverDoHimselfPart1 << {
println "doing really complex things"
}
task doComplexThingsThatTheUserShouldNeverDoHimselfPart2 << {
println "doing other really complex things"
}
// we declare all tasks relationships separately
dependenTask.dependsOn doComplexThingsThatTheUserShouldNeverDoHimselfPart2
doComplexThingsThatTheUserShouldNeverDoHimselfPart2 dependsOn doComplexThingsThatTheUserShouldNeverDoHimselfPart1, jar
doComplexThingsThatTheUserShouldNeverDoHimselfPart1 dependsOn independentTask
就个人而言,我更喜欢最后一个,关系块更具可读性。