Custom Gradle Task depends on Plugin

305 Views Asked by At

Summary: I want to write a gradle task which depends on a plugin. In particular I want to use the plugin org.hidetake.ssh for my deploy task

I have the following project structure

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

In my main build.gradle I import the plugin and define the Task: 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"
}

And in buildSrc/src/main/package/DeployTask I define it:

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"
            }
        }
    }

}

I get obviously the error message:

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

The problem is, that I can (but dont want to) write the task in the main build.gradle as following (without errors)

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

There are 1 best solutions below

0
On BEST ANSWER

ssh is registered as an extension of the project: https://github.com/int128/gradle-ssh-plugin/blob/master/gradle-ssh-plugin/core/src/main/groovy/org/hidetake/gradle/ssh/plugin/SshPlugin.groovy#L20

So you need to reference the extension in your task like so (untested):

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

        }
    }
}