swarajd
swarajd

Reputation: 1007

multiple jenkins shared libraries with the same function

I am trying to import multiple jenkins libraries in a Jenkinsfile, but I've come across the issue of "what if both libraries share a function?" For example, if I have library A and library B, and both of those libraries have function helloWorld, how would I properly differentiate those two functions in the Jenkinsfile?

Let's assume I am importing the libraries like this:

#!groovy
import ...
import ...
import ...

library identifier: 'A@master', retriever: modernSCM(
  [$class: 'GitSCMSource',
   remote: '<the github link for A>'])

library identifier: 'B@master', retriever: modernSCM(
  [$class: 'GitSCMSource',
   remote: '<the github link for B>'])

// rest of the jenkinsfile

How would I be able to use the helloWorld function from both libraries? Is there a way to call A.helloWorld and B.helloWorld in this Jenkinsfile?

edit: helloWorld in this example would be from the vars folder. I'd like to call the same function even when it exists in both libraries' vars folder.

Upvotes: 1

Views: 3175

Answers (2)

Sudarsan Bandi
Sudarsan Bandi

Reputation: 49

I am looking for this solution. It's possible to take the backup of function from global vars before it's overridden from other shared library so that I can call whichever version of function needed in the next steps.

library 'lib_A'
def A_helloWorld = helloWorld
library 'lib_B'
//dynamic loading of lib_B overrides the global vars helloWorld with lib_B
def B_helloWorld = helloWorld

//call  A_helloWorld
A_helloWorld()
//to call  B_helloWorld either helloWorld or B_helloWorld
B_helloWorld()

Upvotes: 0

Marcin Kłopotek
Marcin Kłopotek

Reputation: 5931

According to Jenkins Shared Libraries documentation, in the §Loading Libraries Dynamically section you can find you can assign a loaded library into a variable, then you can use the variable as a qualifier:

def A = library identifier: 'A@master', retriever: modernSCM(
    [$class: 'GitSCMSource', remote: '<the github link for A>']
)
def B = library identifier: 'B@master', retriever: modernSCM(
    [$class: 'GitSCMSource', remote: '<the github link for B>']
)

A.helloWorld()
B.helloWorld()

Upvotes: 1

Related Questions