【问题标题】:Closures in JenkinsFile groovy - callbacks or delegateJenkinsFile groovy 中的闭包 - 回调或委托
【发布时间】:2018-10-29 02:11:17
【问题描述】:

我希望能够在 Jenkins Groovy 脚本中添加回调作为参数。我认为关闭是我需要的,但我不知道该怎么做。这是我想要的输出:

enter
hello
exit

Jenkins 文件:

def rootDir = pwd()
def tools = load "${rootDir}\\patchBuildTools.groovy"
mainMethod(tools.testCl("hello"))

patchBuildTools.groovy

def mainMethod(Closure test) {
    println "enter"
    test()
    println "exit"
}


def testCl(String message) {
    println message
}

这给了我一个输出:

hello
enter
java.lang.NullPointerException: Cannot invoke method call() on null object

是否可以得到我想要的调用顺序?

更新 - 基于答案

Jenkins 文件:

def rootDir = pwd()
def tools = load "${rootDir}\\patchBuildTools.groovy"
mainMethod("enter", "exit")
{
  this.testCl("hello")
}

patchBuildTools.groovy

def mainMethod(String msg1, String ms2, Closure test) {
  println msg1
  test()
  println ms2
}



def testCl(String message) {
    println message
}

【问题讨论】:

    标签: jenkins groovy closures jenkins-pipeline


    【解决方案1】:

    您可能误解了闭包的工作原理 - 闭包是一个匿名函数,您可以将其传递给另一个函数并执行。

    话虽如此,在您的示例中,您将testCl() 的结果(即String)传递给mainMethod()。这是错误的,因为 mainMethod 期望 Closure 而不是 String 作为传递的参数。

    我不确定您要达到什么目的,但这里是您可以使用Closure 的方法:

    Jenkinsfile

    def rootDir = pwd()
    def tools = load "${rootDir}\\patchBuildTools.groovy"
    mainMethod() {
        echo "hello world from Closure"
    }    
    

    patchBuildTools.groovy

    def mainMethod(Closure body) {
        println "enter"
        body() // this executes the closure, which you passed when you called `mainMethod() { ... }` in the scripted pipeline
        println "exit"
    }
    

    结果

    enter
    hello world from Closure
    exit
    

    【讨论】:

      猜你喜欢
      • 2013-07-14
      • 1970-01-01
      • 2019-10-08
      • 2014-06-20
      • 2013-07-07
      • 1970-01-01
      • 1970-01-01
      • 2019-06-23
      • 1970-01-01
      相关资源
      最近更新 更多