pogorman
pogorman

Reputation: 1711

Closures in JenkinsFile groovy - callbacks or delegate

I want to be able to add a callback as a parameter in a Jenkins Groovy script. I think a closure is what I need, but I don't know how to do it. Here is the output I want:

enter
hello
exit

JenkinsFile:

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
}

This gives me an out put of :

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

Is it possible to get the call order I want?

Update - based on the answer

JenkinsFile:

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
}

Upvotes: 6

Views: 20748

Answers (1)

tftd
tftd

Reputation: 17032

You might have misunderstood how closures work - a closure is an anonymous function which you can pass to another function and execute.

Having said that, in your example you are passing the result of testCl(), which is a String, to mainMethod(). This is wrong, because mainMethod expects a Closure and not a String as the passed argument.

I am not sure what you are trying to achieve, but here is how you could use a Closure:

Jenkinsfile

def rootDir = pwd()
def tools = load "${rootDir}\\patchBuildTools.groovy"
mainMethod() {
    // everything you put here is the closure that will be passed
    // as the argument "body" in the mainMethod() (inside patchBuildTools.groovy)
    echo "hello world from Closure"
}    

patchBuildTools.groovy

def mainMethod(Closure body) {
    println "enter"
    body() // executes the closure passed with mainMethod() from the Jenkinsfile.
    println "exit"
}

Result

enter
hello world from Closure
exit

Upvotes: 18

Related Questions