Gradle 中额外属性的范围?

Scope of the extra properties in Gradle?

我有一个类似于这样的 Gradle 脚本:

ext {
  dir = null
}

task init << {
  build()
}

task buildAll(type: Exec){
  workingDir ext.dir
  commandLine 'cmd', '/c', "echo %JAVA_HOME%"
}

def build(){
  ext.dir = "asdf"
  buildAll.execute()
}

当我 运行 脚本时,我得到:

groovy.lang.MissingPropertyException: Cannot get property 'dir' on extra properties extension as it does not exist

无论我如何尝试,我都无法获得从 "ext" 读取 属性 的任务。它可以从方法中看出(比如我示例中的 "build()"),但除了默认任务(我示例中的 "init")之外的任何其他任务都看不到。

我知道 "ext" 属性应该可以从项目内的任何地方访问,所以我做错了什么?

更新: 我试图实现的工作流程(正如 Opal 所要求的):

我有几个环境需要用一个脚本来构建。这些环境中的每一个都列在 CSV 文件中,其中包含一行:<environment>,<version>.

然后脚本需要执行以下操作:

这需要为每个环境执行

额外的属性应该通过 ext 创建,但通过 project 实例引用,根本没有任何实例,所以:project.dirdir,所以第一个更改脚本将是:

ext {
  dir = null
}

task init << {
  build()
}

task buildAll(type: Exec){
  workingDir dir // ext.dir -> dir
  commandLine 'cmd', '/c', "echo %JAVA_HOME%"
}

def build(){
  ext.dir = "asdf"
  buildAll.execute()
}

现在,在执行任何任务或方法之前,将读取和解析脚本,因此 buildAll 的整个主体将在 之前配置 任何其他部分是 运行。因此它总是会失败,因为 dir 属性 没有价值。证明:

ext {
  dir = null
}

task init << {
  build()
}

task buildAll(type: Exec){
  workingDir dir ? dir : project.rootDir 
  commandLine 'cmd', '/c', "echo %JAVA_HOME%"
}

def build(){
  ext.dir = "asdf"
  buildAll.execute()
}