如何懒惰地配置Gradle任务?

时间:2015-12-17 18:58:26

标签: gradle

我正在尝试配置以下自定义任务:

task antecedeRelease(type: AntecedeReleaseTask) {
  antecedeWithVersion = project.'antecede-with-version'
  antecedeToVersion = project.'antecede-to-version'
}

问题是属性antecede-with-versionantecede-to-version将通过命令行设置-P选项。如果它们未设置且未调用antecedeRelease,则不应导致错误:

$ ./gradlew tasks
org.gradle.api.GradleScriptException: A problem occurred evaluating project ...
Caused by: groovy.lang.MissingPropertyException: Could not find property 'antecede-with-version' on project ...

我可以有条件地定义antecedeRelease任务,只有在定义了这些属性的情况下才定义它,但我希望尽可能保持build.gradle文件的清洁。

2 个答案:

答案 0 :(得分:1)

如果你需要antecedeRelease任务来运行"懒惰" as-in,在配置阶段结束时,或在执行阶段开始时,最好的办法是使用doFirst

task antecedeRelease(type: AntecedeReleaseTask) {
  doFirst {
    antecedeWithVersion = project.'antecede-with-version'
    antecedeToVersion = project.'antecede-to-version'
  }
}

答案 1 :(得分:0)

一个选项可能是使用Groovy的elvis运算符,如下所示:

task antecedeRelease(type: AntecedeReleaseTask) {
  antecedeWithVersion = project.ext.get('antecede-with-version') ?: 'unused'
  antecedeToVersion = project.ext.get('antecede-with-version') ?: 'unused'
}

如果此操作仍然失败,您可以在设置值时考虑project.ext.has('property')