I have one common groovy file that contains few const variables and functions... and I also have more groovy files with pipelineJob that use the variables and functions from the common file what is the best way to import all the data from the common file to the other files?
Asked
Active
Viewed 651 times
0
-
have you seen these questions? https://stackoverflow.com/questions/30753874/how-to-use-multiple-classes-in-multiple-files-in-scripts https://stackoverflow.com/questions/9136328/including-a-groovy-script-in-another-groovy and this blog post could also be helpful: http://ikoodi.nl/2012/05/14/groovy-scripting-using-multiple-files/ – rdmueller Dec 04 '20 at 22:03
1 Answers
1
I have not tested this with Jenkins, but if Jenkins executes the Groovy script as if by invoking groovy -cp .... myScript.groovy
it should work:
utils.groovy
:
// notice there's no "def", otherwise the def would be local only
name = 'Joe'
class MyUtils {
static String greeting(String name) {
"Hello $name"
}
}
src/main.groovy
def shell = new GroovyShell(getBinding())
shell.evaluate(new File('utils.groovy'))
println MyUtils.greeting(name)
Running it:
$ groovy src/Main.groovy
Hello Joe
Because the Script
base class by default also has an evaluate
method, your can actually just call that instead of using a GroovyShell
and the result should be identical:
src/main.groovy
evaluate(new File('utils.groovy'))
println MyUtils.greeting(name)
If it doesn't work it's because the Script
base class has been changed , probably... the first approach should work in all cases.

Renato
- 12,940
- 3
- 54
- 85