Define a variable and set it to a default value if something goes wrong during definition

I have the following code in my build.gradle

Contents in version.properties are:

buildVersion=1.2.3
  • Value of $v variable during the Gradle build is coming as: 1.2.3
  • Value of $artifactoryVersion variable in JENKINS build is coming as: 1.2.3.1, 1.2.3.2, 1.2.3.x ... and so on where the 4th digit is Jenkins BUILD_NUMBER available to gradle build script during Jenkins build.

BUT, when I'm running this build.gradle on my desktop where I dont have BUILD_NUMBER variable available or set in my ENVIRONMENT variables, I get an error saying trim() can't work on null. (as there's no BUILD_NUMBER for Desktop/local build).

I'm trying to find a way i.e.

  1. What should I code in my script so that if BUILD_NUMBER is not available, then instead of gradle build processing failing for an error, it'd set jenkinsBuild = "0" (hard coded) otherwise, pick what it gets during Jenkins build.

    For ex: in Bash, we set a variable var1=${BUILD_NUMBER:-"0"} which will set var1 to a valid Jenkins BUILD number if it's available and set to a value, otherwise if it's NULL, then var1 = "0".

  2. I DON'T want to have each developer/user set this BUILD_NUMBER in some property file. All I want is, if this variable doesn't exist, then the code should put "0" in jenkinsBuilds variable and doesn't error out during desktop builds. I know during Jenkins build, it's working fine.

// Build Script
def fname = new File( 'version.properties' )
Properties props = new Properties()
props.load( new FileInputStream( fname ) )
def v = props.get( 'buildVersion' )


def env = System.getenv()
def jenkinsBuild = env['BUILD_NUMBER'].trim()
if( jenkinsBuild.length() > 0 ) {
  artifactoryVersion = "$v.$jenkinsBuild"
}

Solution 1:

All you need is some regular Java/Groovy code:

def jenkinsBuild = System.getenv("BUILD_NUMBER") ?: "0"

The code above uses Groovy's "elvis" operator, and is a shorthand for the following code, which uses Java's ternary operator:

def buildNumber = System.getenv("BUILD_NUMBER")
def jenkinsBuild = buildNumber != null ? buildNumber : "0"

Solution 2:

Here's the answer to using a Java plain object (JDK8):

public class Sample {

    private String region;
    private String fruit;

    public Sample() {
        region = System.getenv().getOrDefault("REGION", null);
        fruit = System.getenv().getOrDefault("FRUIT", "apple");
    }
}