red888
red888

Reputation: 31520

Why does the jenkinsfile use a closure in this way?

It's a common pattern to write Jenkins pipeline code like this:

def call(body) {    
    def config = [:]
    body.resolveStrategy = Closure.DELEGATE_FIRST
    body.delegate = config
    body()
}

I'm not sure how to word this simply, but this closure get implicitly imported and can be called by the file name of the .groovy file it lives in.

I call it like:

MyClosure { myarg = 'sdfsdf' }

I not entirely sure what this is doing. It's doing call(body) and then assigning body as the delegate. so that means the closure I pass it is the delegate, but isn't that just the owner? Wah? me confused.

Upvotes: 19

Views: 13578

Answers (1)

Rob Hales
Rob Hales

Reputation: 5321

When this runs, it is creating an empty map (config). Then it is telling the closure (body) to look at the delegate first to find properties by setting its resolveStrategy to be the constant Closure.DELEGATE_FIRST. Then it assigns the config map as the delegate for the body object.

Now when you execute the body() closure, the variables are scoped to the config map, so now config.myarg = 'sdfsdf'.

Now later in the code you can have easy access to the map of values in config.

body is the owner, and by default is the delegate. But when you switch the delegate to be config, and tell it to use the delegate first, you get the variables config's scope.

Upvotes: 16

Related Questions