简体   繁体   English

从 Groovy/Jenkins 中的类传递闭包

[英]Passing closures from a class in Groovy/Jenkins

I'm trying to create a JobGenerator class that will pass a build step down to the calling instance.我正在尝试创建一个 JobGenerator 类,它将构建步骤向下传递给调用实例。 I'm running into an issue where if I get this error when I try to run this:我遇到了一个问题,如果我在尝试运行时遇到此错误:

hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: org.jenkinsci.plugins.workflow.cps.CpsClosure2.build() is applicable for argument types: (java.util.LinkedHashMap) values: [[job:FooJob]] hudson.remoting.ProxyException:groovy.lang.MissingMethodException:无方法签名:org.jenkinsci.plugins.workflow.cps.CpsClosure2.build() 适用于参数类型:(java.util.LinkedHashMap) 值:[[job] :FooJob]]

class BuildGenerator implements Serializable {     

static def generateJob() {
    return  [
            "TestJob",
            { ->
                build(
                        job: 'FooJob'
                )
            },
    ]
  }        
}        

node(){
    def tasks = [:]
    def label
    def task

    stage("Build") {
        def generator = new BuildGenerator()            
        tasks["Testing"] = generator.generateJob()[1]
        parallel tasks
    }
}

If I remove the generateJob function outside of the class then it works fine.如果我在类之外删除 generateJob 函数,那么它工作正常。 What am I doing wrong with closures here?我在这里关闭有什么问题? I'm new to groovy/jenkins world.我是 groovy/jenkins 世界的新手。

Well... This is the way Groovy/Jenkins pipeline work.嗯……这就是 Groovy/Jenkins 管道的工作方式。 build is available inside node as the rest of steps and functions. buildnode内部可用,作为其余的步骤和功能。 If you wish to access these you have to pass the CPS instance to the method, like this (or use constructor to pass the instance only once):如果你想访问这些你必须将 CPS 实例传递给方法,像这样(或使用构造函数只传递一次实例):

class BuildGenerator implements Serializable {     

static def generateJob(script) {
    return  [
            "TestJob",
            { ->
                script.build(
                        job: 'FooJob'
                )
            },
    ]
  }        
}        

node(){
    def tasks = [:]
    def label
    def task

    stage("Build") {
        def generator = new BuildGenerator()            
        tasks["Testing"] = generator.generateJob(this)[1]
        parallel tasks
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM