我在玩Gradle随附的示例目录,并尝试创建一个简单的任务,该任务运行依赖于另一个脚本的groovy脚本。

该项目的结构如下所示:

.
├── build.gradle
└── src
    ├── main
    │   ├── groovy
    │   │   └── org
    │   │       └── gradle
    │   │           └── Person.groovy
    │   └── resources
    │       ├── resource.txt
    │       └── script.groovy
    └── test
        ├── groovy
        │   └── org
        │       └── gradle
        │           └── PersonTest.groovy
        └── resources
            ├── testResource.txt
            └── testScript.groovy

我在build.gradle中添加了以下任务
task runScript << {
  new GroovyShell().run(file('src/main/resources/script.groovy'))
}

我得到的错误是:
FAILURE: Build failed with an exception.

* Where:
Build file '/gradle/gradle-1.0/samples/groovy/quickstart/build.gradle' line: 13

* What went wrong:
Execution failed for task ':runScript'.
Cause: No such property: person for class: script
script.groovy的内容是:
person.name = person.name[0].toUpperCase() + person.name[1..-1]
Person.groovy的内容是:
包org.gradle
class Person {
    String name

    def Person() {
        getClass().getResourceAsStream('/resource.txt').withStream {InputStream str ->
            name = str.text.trim()
        }
        getClass().getResourceAsStream('/script.groovy').withStream {InputStream str ->
            def shell = new GroovyShell()
            shell.person = this
            shell.evaluate(str.text)
        }
    }
}

问题
我如何添加一个仅运行script.groovy的任务,该任务利用了另一个常规类(Person)

最佳答案

您可以使用buildSrc文件夹,在其中可以保存Groovy / Java源代码,这些源代码将在执行初始构建脚本中的任何任务之前被编译并添加到类路径中。这将使所有这些类可用于任务。您可以在http://gradle.org/docs/current/userguide/organizing_build_logic.html中了解更多信息

关于您的script.grooovy,我只是将代码放入任务本身,而不是通过GroovyShell调用它。如果要外部化任务,可以使用apply命令。

apply from: 'script.gradle'

您可以看一下这个问题:How can I import one Gradle script into another?

10-07 12:04
查看更多