-1

I am new to groovy. I am writing a shared library for Jenkins pipeline. I am facing this java.lang.NullPointerException exception. Below is my code:

def call(Map config = [:], env) {
    
            pipeline {
                defaults = [
                        'pipelineStrategy'          : 'deployOnly',
                        'buildSystem'               : 'maven'
                ] + config
        
                environment {
                    BRANCH_NAME = "${GIT_BRANCH.split("/")[1]}"
                }
                boolean autoDeploy = false;
                if (env.BRANCH_NAME.equals('master') || env.BRANCH_NAME.startsWith('hotfix-')){
                    autoDeploy = true;
                }
        }
}

Below are my Jenkins build logs:

java.lang.NullPointerException: Cannot invoke method startsWith() on null object
    at org.codehaus.groovy.runtime.NullObject.invokeMethod(NullObject.java:91)
    at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:48)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.NullCallSite.call(NullCallSite.java:35)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at com.cloudbees.groovy.cps.sandbox.DefaultInvoker.methodCall(DefaultInvoker.java:20)
    at pipelineStrategy.call(pipelineStrategy.groovy:21)
Pritish
  • 658
  • 3
  • 16
  • 38
  • 2
    `env` only exists in Node context. One does not simply wrap some code with `pipeline {` and expects it to work. – MaratC Apr 28 '22 at 09:19
  • To prevent NPE you can try using safe navigation operator `?.` like `env?.BRANCH_NAME?.startsWith('hotfix-')` – SURU Apr 28 '22 at 12:22

2 Answers2

1

The only startsWith() in the code you posted is in

env.BRANCH_NAME.startsWith('hotfix-')

and you are being told that there is a null object. It means that

env.BRANCH_NAME

is null. You will need to think why or how to handle that situation. One way might be to use

String.valueOf(env.BRANCH_NAME).startsWith('hotfix-')
Queeg
  • 7,748
  • 1
  • 16
  • 42
0

You are probably trying to use a multibranch pipeline syntax on a "non-multibranch pipeline"...

This variable is available only for multibranch pipelines.

Juliano Pezzini
  • 131
  • 1
  • 4