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

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

但这失败了

Execution failed for task ':startGlassfish'.

> execCommand == null!



因此,我显然误会了一些东西。

我该如何工作?

最佳答案

编写自定义任务类时,建议先检查原始任务的代码。执行任务的@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}"]
}

关于inheritance - 如何在gradle任务之间共享代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54954344/

相关文章:

inheritance - 如何通过扩展正在使用的类来扩展模块?

groovy - Gradle zip 插件,如何在 zip 中创建空文件夹?

groovy - 这个 Groovy 闭包 token '->' 有名字或昵称吗?

Grails .save(刷新 : true) behaves the same with . save()

python - python类继承的基本用法

c++ - 实例化从 Base 私有(private)或 protected 继承的派生类

c++ - 为什么我的构造函数没有像应有的那样初始化其父类(super class)属性?

java - 带有yml配置文件的gradle jar文件未从dockerfile执行

android - 应用程序ID和程序包ID不同,当用户对其进行更新时会崩溃

grails - 如何找出 gvm 安装 groovy 的位置?