Home > Enterprise >  How to execute a groovy share library with optional parameters
How to execute a groovy share library with optional parameters

Time:09-17

I'm developing a shared library to execute it from my Jenkinsfile. This library has a function with optional parameters and I want to be able to execute this function with any number of parameters by specifying my value. I've been googling a lot, but couldn't find a good answer, so maybe somebody here could help me. Example: The function looks this way:

def doRequest(def moduleName=env.MODULE_NAME, def environment=env.ENVIRONMENT, def repoName=env.REPO_NAME) {
<some code goes here>
}

If I execute it from my Jenkinsfile this way:

script {
    sendDeploymentStatistics.doRequest service_name
}

the function puts "service_name" value to the moduleName, but how do I specify "repoName" parameter? In Python you would do it somehow like:

function_name(moduleName=service_name, repoName=repo_name)

but in Groovy Jenkinsfile I can't find the right way.

Can anybody please help me to find out the right syntax?

Thank you!

CodePudding user response:

Groovy has the concept of Default Parameters. If you change the order of the parameters, such that the environment comes last:

def doRequest(def moduleName=env.MODULE_NAME, def repoName=env.REPO_NAME, def environment=env.ENVIRONMENT) {
    <some code goes here>
}

Then your call to function_name will take the default value for environment:

function_name(moduleName=service_name, repoName=repo_name)

Groovy however also has some sort of support for Named Parameters. It is not as nice as Python but you can get it to work as follows:

env = [MODULE_NAME: 'foo', ENVIRONMENT: 'bar', REPO_NAME: 'baz']

def doRequest(Map args = [:]) {
    defaultMap = [moduleName: env.MODULE_NAME, environment: env.ENVIRONMENT, repoName: env.REPO_NAME]
    args = defaultMap << args
    return "${args.moduleName} ${args.environment} ${args.repoName}"
}
 
assert 'foo bar baz' == doRequest()
assert 'foo bar qux' == doRequest(repoName: 'qux')
assert '1 2 3' == doRequest(repoName: '3', moduleName: '1', environment: '2')

For Named Parameters you need a parameter of type Map (with a default value of the empty map). Groovy will then map the arguments upon calling the function to entries in a Map.

To use default values you need to create a map with the default values, and merge that defaultMap with the passed-in arguments.

  • Related