组织 Gradle 构建逻辑的任务或方法之间的最佳选择是什么?

What's the best choice between tasks or methods to organize your Gradle build logic?

我目前正在 将一些旧的大型 Maven 1 脚本迁移到 Gradle。 因此,我需要将旧的 Maven 1/Ant 及其目标逻辑调整为 Gradle。

在阅读了 Gradle 用户指南和一些关于 Gradle 任务和方法的文章后,我对编写脚本的方式感到很困惑.

官方Gradle User Guide, §6.1中解释说,一个Gradle任务:

represents some atomic piece of work which a build performs

§6.11中也说明了我们可以使用方法来组织我们的构建逻辑.

所以,我的问题是:使用它们的正确方法是什么?

我正在创建构建脚本,所以,我认为:

使用前面的逻辑,当我的方法需要调用 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"
}

在这种情况下,什么是正确的构建逻辑?

是否应该在 1 个或多个任务中转换 doComplexThingsThatTheUserShouldNeverDoHimself,以便能够 dependsOn JAR 任务?
但这意味着确实有很多任务可由用户调用,而事实上,情况不应该如此。

经过大量搜索后,我得出结论,当您需要从另一个任务调用一个任务时,您别无选择,只能依赖任务关系dependsOnmustRunAfterfinalizedBy)。

这意味着方法不能像在 Java、Groovy & Co.[=15= 中用于构建程序的方式那样用于组织构建逻辑]

因此,您不能阻止用户查看(和使用)一些内部任务,这些任务通常只应被其他一些任务用作依赖项。

前一个构建脚本的 "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

就我个人而言,我更喜欢最后一个,关系块更具可读性。