Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a groovy class in other jenkins groovy scripts

I have 4 groovy scripts (2 are dsl.groovy scripts):

JobConfig.groovy:

class JobConfig {
    final name

    JobConfig(map) {
        name = map['name']
    }
}

topLevel.groovy:

import JobConfig.*

def doSmthWithJobConfig(final JobConfig config) {
    println(config.name);
}

sublevel1.dsl.groovy:

GroovyShell shell = new GroovyShell()
def topLevelScript = shell.parse(new File("topLevel.groovy"))

def jobConfigs = [
    new JobConfig(name: 'JenkinsTestDSLs'),
    new JobConfig(name: 'JenkinsTestDSLs2')
]

jobConfigs.each {
    topLevelScript.doSmthWithJobConfig(it);
}

sublevel2.dsl.groovy:

GroovyShell shell = new GroovyShell()
def topLevelScript = shell.parse(new File("topLevel.groovy"))

def jobConfigs = [
    new JobConfig(name: 'JenkinsTestDSLs3'),
    new JobConfig(name: 'JenkinsTestDSLs4')
]

jobConfigs.each {
    topLevelScript.doSmthWithJobConfig(it);
}

Now if locally I do:

groovyc JobConfig.groovy

,I get no issues with running the scripts locally.

But on jenkins even if I provide the JobConfig.class at the same place where these scripts are, I can't get it running. I read here that I don't need to do any compiling as long as JobConfig.groovy is on the CLASSPATH. How do I do that with jenkins? Or is there another solution?

like image 270
despot Avatar asked Jul 23 '13 08:07

despot


1 Answers

If you don't want to compile the groovy class(es) and then add the compiled classes to the classpath, you can make use of classes within groovy scripts like this:

Given a groovy class

class GroovyClass {
    def GroovyClass(someParameter) {}

    def aMethod() {}
}

you can use the class in groovy script like this

import hudson.model.*
import java.io.File;
import jenkins.model.Jenkins;

def jenkinsRootDir = build.getEnvVars()["JENKINS_HOME"];
def parent = getClass().getClassLoader()
def loader = new GroovyClassLoader(parent)

def someParameterValue = "abc"

def groovyClass = loader.parseClass(new File(jenkinsRootDir + "/userContent/GroovyScripts/GroovyClass.groovy")).newInstance(someParameterValue)

groovyClass.aMethod()
like image 84
TheEllis Avatar answered Oct 19 '22 21:10

TheEllis