自定义 Gradle 任务取决于插件

Custom Gradle Task depends on Plugin

总结:我想写一个 gradle 依赖插件的任务。特别是我想将插件 org.hidetake.ssh 用于我的部署任务

我有以下项目结构

build.gradle
settings.gradle
some-modules/
|-- src/...
buildSrc/
|-- src/
|-- |-- main/groovy/package/DeployTask
|-- build.gradle

在我的主 build.gradle 中,我导入插件并定义任务: build.gradle

plugins {
    id 'idea'
    id 'org.hidetake.ssh' version '2.10.1'
}

...

remotes {
    dev {
        host = findProperty("server.dev.host")
        user = findProperty("server.dev.user")
        identity = file(findProperty("server.dev.identity_file") ?: "${System.properties['user.home']}/.ssh/id_rsa")
    }
}

import org.irrigation.gradle.DeployTask

task deploy(type: DeployTask) {
    description = "Deploys to Server"
}

buildSrc/src/main/package/DeployTask中我定义它:

class DeployTask extends DefaultTask {
    @Input
    @Option(option = "env", description = "Configures the environment to be used")
    String environment = "dev";

    @Input
    @Option(option = "branch", description = "Configures the branch which should be deployed")
    String branch = "master";

    @TaskAction
    void deploy() {
        ssh.run {
            session(ssh.remotes[environment]) {
                execute "echo test"
            }
        }
    }

}

我明显收到错误信息:

Execution failed for task ':deploy'.
> Could not get unknown property 'ssh' for task ':deploy' of type org.irrigation.gradle.DeployTask.

问题是,我可以(但不想)在主 build.gradle 中编写任务如下(没有错误)

task deploy(type: DeployTask) {
    doLast {
        ssh.run {
            session(ssh.remotes[environment]) {
                execute "echo test"
            }
        }
    }
}

ssh 注册为项目的扩展:https://github.com/int128/gradle-ssh-plugin/blob/master/gradle-ssh-plugin/core/src/main/groovy/org/hidetake/gradle/ssh/plugin/SshPlugin.groovy#L20

所以你需要像这样在你的任务中引用扩展(未经测试):

@TaskAction
void deploy() {
    doLast {
        getProject().getExtensions().getByType(Service.class).run {

        }
    }
}