带有扩展名的自定义 Gradle 插件执行任务未正确使用输入

Custom Gradle Plugin Exec task with extension does not use input properly

我正在关注Writing Custom Plugins section of the Gradle documentation, specifically the part about Getting input from the build。文档提供的以下示例完全符合预期:

apply plugin: GreetingPlugin

greeting.message = 'Hi from Gradle'

class GreetingPlugin implements Plugin<Project> {
    void apply(Project project) {
        // Add the 'greeting' extension object
        project.extensions.create("greeting", GreetingPluginExtension)
        // Add a task that uses the configuration
        project.task('hello') << {
            println project.greeting.message
        }
    }
}

class GreetingPluginExtension {
    def String message = 'Hello from GreetingPlugin'
}

输出:

> gradle -q hello
Hi from Gradle

我想让自定义插件执行外部命令(使用 Exec task), but when changing the task to a type (including types other than Exec such as Copy),构建的输入停止正常工作:

// previous and following sections omitted for brevity
project.task('hello', type: Exec) {
    println project.greeting.message
}

输出:

> gradle -q hello
Hello from GreetingPlugin

有人知道问题出在哪里吗?

这与任务类型无关,这是典型的<<误解。

写的时候

project.task('hello') << {
    println project.greeting.message
}

并执行gradle hello,会发生以下情况:

配置阶段

  1. 应用自定义插件
  2. 创建任务 hello
  3. 设置greeting.message = 'Hi from Gradle'

执行阶段

  1. 运行 空体任务
  2. 执行<<闭包{println project.greeting.message}

在这种情况下输出是来自 Gradle

的 Hi

写的时候

project.task('hello', type: Exec) {
    println project.greeting.message
}

并执行gradle hello,会发生以下情况

配置阶段

  1. 应用自定义插件
  2. 创建 exec 任务 hello
  3. 执行任务初始化关闭println project.greeting.message
  4. set greeting.message = 'Hi from Gradle' (太迟了,在第3步打印出来了)

其余的工作流程并不重要。


所以,小细节很重要。 Here's同题解说


解法:

void apply(Project project) {
    project.afterEvaluate {
        project.task('hello', type: Exec) {
            println project.greeting.message
        }
    }
}