Search code examples
groovyjenkins-pipelinejenkins-groovy

Groovy: Usage of 'it' with closures


I wonder how I can pass the implicit variable 'it' to the closure. See the following code:

def myfunc(String name, Closure cl)
{
    println("name: ${name}")
    cl.call()
}

list = ['a', 'b']

list.each
{
    println("it1: ${it}")
}

list.each
{
    myfunc("f1")
    {
        println("it2: ${it}")
    }
}

list.each
{
    p ->
    myfunc("f2")
    {
        println("p: ${p}")
    }
}

The resulting output is:

it1: a
it1: b
name: f1
it2: null
name: f1
it2: null
name: f2
p: a
name: f2
p: b

How can I achieve that in the second version (f1/it2) the implicit variable it is passed to the closure? Currently it is "null". I want to achieve to have 'a', 'b' within 'it' in the second version.

The background of the question is, that within a Jenkins Pipeline, the following code

    mylist = ['a1', 'a2']
    mylist.each {
        dir ("xxxx") {
            echo "it in xxxx is ${it}"
        }
    }

prints out the values 'a1' and 'a2' for it. This does not fit to the understanding that it is bound to the outermost closure.

In case of Jenkins the behaviour seems to be different. I want to achieve the very same behaviour and I am wondering how to do this.

Thanks for all feedback!

Best regards

Mathias


Solution

  • dir from jenkins is not a function - it's a jenkins Step and your groovy function example is not applicable.

    you have to check if it's achievable from groovy-defined custom steps https://rubix.nl/jenkins-creating-a-custom-pipeline-step-in-your-library/

    or think about custom plugin creation.

    btw, here is a source of dir jenkins step: https://github.com/jenkinsci/workflow-basic-steps-plugin/blob/master/src/main/java/org/jenkinsci/plugins/workflow/steps/PushdStep.java