1

Can a Groovy source file in Jenkins' Shared Library access a method from a global variable?

my Shared Library structure is:

(root)
+- src                     # Groovy source files
|   +- org
|       +- foo
|           +- CallMethodFromVars.groovy  # for org.foo.CallMethodFromGlobalVars.groovy class
+- vars
|   +- foo.groovy          # for global 'foo' variable

In my class src.org.foo.CallMethodFromVars I would like to access a method call(arg) in vars.foo.groovy

src.org.foo.CallMethodFromVars:

class CallMethodFromVars  {
    String run(){
         //TODO call method vars.foo.groovy.call() here
    }
}

vars.foo.groovy:

def call(arg) {
   doSomething()
}

My research and attempts at solving this so far have failed. Some of the things I tried:

  • import var.*; foo.groovy.call(arg)

  • def method = this.class.classLoader.loadClass('vars.foo'); method.call(arg)

  • def engine = new GroovyScriptEngine("/path-to-library/vars/foo.groovy"); engine.run('call', [arg])

  • def method = library.vars.foo; method.call(arg)

  • def method libraryContext.getVariable("foo"); method.call(arg)

  • method = System.getenv('foo'); method.call(arg)

  • I tried all the above with method() instead of method.call(arg)

Marcin Kulik
  • 845
  • 1
  • 12
  • 28
  • In general you need to pass the Script Context to you class in order to access vars methods or any other built in Jenkins methods. Take a look at the [following answer](https://stackoverflow.com/a/66092978/13110835) it has a very good explanation for your case. – Noam Helmer Mar 01 '23 at 17:00
  • Thanks for your reply, I came across that thread before. Unfortunately it does not answer my question. It shows how to run a class from src folder in Jenkinsfile. However it does not show how to access a class from src folder in a script that is placed in vars folder. – Marcin Kulik Mar 07 '23 at 09:38
  • 1
    In that case use it like you will use it in a pipeline, in your var file import the relevant function `import src.org.foo.CallMethodFromVars` and then use it inside the code. – Noam Helmer Mar 07 '23 at 10:10
  • sorry, I made a mistake replying you, I meant the opposite, to run a function from vars in src, and I tried the import, which I listed in my attempts at solving this – Marcin Kulik Mar 07 '23 at 17:17
  • Take a look at [this](https://github.com/Ableton/python-pipeline-utils/blob/master/src/com/ableton/VirtualEnv.groovy) project, it is a python virtual env implementation for Jenkins. Take a look at the `script` object in the `VirtualEnv` class and how he uses it to call Jenkins defined methods like `sh` and so. In a similar way you can call your vars methods. – Noam Helmer Mar 07 '23 at 17:30

0 Answers0