8

I have code based on "structured DSL" concept.

// vars/buildStuff.groovy
def call(body) {

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

    node {
        assert env
        assert params
        doStuff()
    }
} 

In this code I can access env and params directly, as expected.

However in the top level Jenkinsfile:

buildStuff {
    someParam=params.SOME_PARAM
    buildId=env.BUILD_ID
}

Causes java.lang.NullPointerException: Cannot get property 'SOME_PARAM' on null object. I have to work around that by writing this as:

buildStuff {
    someParam=this.params.SOME_PARAM
    buildId=this.env.BUILD_ID
}

Why is that the case? According to all examples in Pipelines documentation I should be able to access env and params directly. What am I doing wrong?

vartec
  • 131,205
  • 36
  • 218
  • 244
  • Maybe because of https://jenkins.io/doc/book/pipeline/shared-libraries/#defining-global-variables? global vs object variable? – VonC May 20 '17 at 06:09
  • have you set parameter like this `properties([parameters([string(name: 'BRANCH', defaultValue: 'master')])])` – Zedee.Chen May 20 '17 at 08:53
  • 2
    Your question was an answer for me! :D Was getting a NullPointerException while accessing params. Now I know we need to refer it by `this`. – jacobcs Mar 28 '19 at 19:00

1 Answers1

4

It's an issue with the resolveStrategy.

def config = [:]
body.resolveStrategy = Closure.DELEGATE_FIRST
body.delegate = config

The config you provide resolves any property to its value or null, thus the owner is not queried for it. In you example the owner is just this. That's why it works.

Depending on what you're actually trying to achieve, OWNER_FIRST might be a better strategy. If you cannot change this, better use a data structure without defaults for properties.

tynn
  • 38,113
  • 8
  • 108
  • 143
  • The problem statement is the same for me, but changing the strategy to OWNER_FIRST made no difference for me. It's env that I'm specifically interested in. – Sion Aug 20 '18 at 11:25