如何在gradle任务之间共享代码?

时间:2019-03-02 01:14:41

标签: inheritance gradle groovy build.gradle gradle-task

所以我有一些gradle任务可以和glassfish互动...

task startGlassfish(type:Exec){
    workingDir "${glassfishHome}${File.separator}bin"

    if (System.properties['os.name'].toLowerCase().contains('windows')) {
        commandLine 'cmd', '/c', 'asadmin.bat'
    } else {
        commandLine "./asadmin"
    }

    args "start-domain", "${glassfishDomain}"
}

task stopGlassfish(type:Exec){
    workingDir "${glassfishHome}${File.separator}bin"

    if (System.properties['os.name'].toLowerCase().contains('windows')) {
        commandLine 'cmd', '/c', 'asadmin.bat'
    } else {
        commandLine "./asadmin"
    }

    args "stop-domain", "${glassfishDomain}"
}

task deploy(dependsOn: 'war', type:Exec) {
    workingDir "${glassfishHome}${File.separator}bin"

    if (System.properties['os.name'].toLowerCase().contains('windows')) {
        commandLine 'cmd', '/c', 'asadmin.bat'
    } else {
        commandLine "./asadmin"
    }

    args "deploy", "--force=true", "${war.archivePath}"
}

这是很多不必要的代码重复,我想将其重构为更薄的东西。

我确实尝试过

class GlassfishAsadminTask extends Exec{
    @TaskAction
    def run() {
        workingDir "${glassfishHome}${File.separator}bin"

        if (System.properties['os.name'].toLowerCase().contains('windows')) {
            commandLine 'cmd', '/c', 'asadmin.bat'
        } else {
            commandLine "./asadmin"
        }
    }
}

task startGlassfish(type:GlassfishAsadminTask){

    args "start-domain", "${glassfishDomain}"
}

但是失败

  

任务':startGlassfish'的执行失败。

     

> execCommand == null!

所以我显然是误会了。

如何使它工作?

1 个答案:

答案 0 :(得分:1)

在编写自定义任务类时,建议首先检查原始任务的代码。执行任务的@TaskAction是exec()方法,in AbstractExecTask class

您可以使用以下代码;

class GlassfishAsadminTask extends Exec{
    // arguments that tasks will pass (defined as array)
    @Input
    String[] cmdArguments

    @TaskAction
    public void exec() {
        // access properties with project.proppertyName
        workingDir "${project.glassfishHome}${File.separator}bin"

        if (System.properties['os.name'].toLowerCase().contains('windows')) {
            commandLine 'cmd', '/c', 'asadmin.bat'
        } else {
            commandLine "./asadmin"
        }
        // set args that is set by the task
        args cmdArguments
        super.exec()
    }
}

// A sample task
task startGlassfish(type: GlassfishAsadminTask) {
     cmdArguments = ["start-domain", "${glassfishDomain}"]
}