Jenkins pipeline - change class name of loaded scripts

Viewed 536

I have a Jenkins Pipeline project which loads several Groovy scripts. When I run this pipeline, Jenkins names these scripts' classes Script1, Script2, and so on. These names are displayed when replaying a build. They also appear on exception stack traces. I find this confusing, especially when there is more than a couple of scripts.

Is there any way of setting these names from the pipeline or -preferably- from within the scripts themselves? So far I tried manipulating the scripts' metaClass:

this.metaClass.name = 'Foo'                //fails, doesn't find metaClass property
this.class.metaClass.name = 'Foo'          //doesn't fail but has no apparent effect
this.class.metaClass.simpleName = 'Foo'    //idem
this.class.metaClass.canonicalName = 'Foo' //idem

NOTE: I am well aware of Jenkins shared libraries. This question is meant to focus on loaded scripts alone.

2 Answers

No, there is currently no way to change the generated class name for a loaded script.

  • The name generation comes from the load step implementation class LoadStepExecution.

    String clazz = execution.getNextScriptName(step.getPath());
    
  • In CpsFlowExecution, the script name is generated from the calling generateScriptName() on the shell which is a CpsGroovyShell. This invocationand removes the .groovy suffix.

    public String getNextScriptName(String path) {
        return shell.generateScriptName().replaceFirst("[.]groovy$", "");
    }
    
  • The CpsGroovyShell generates the class name, which is where the Script1.groovy, Script2.groovy, etc. get created from

    @Override
    protected synchronized String generateScriptName() {
        if (execution!=null)
            return "Script" + (execution.loadedScripts.size()+1) + ".groovy";
        else
            return super.generateScriptName();
    }
    

Maybe this will be of some help to some users. By chance I managed to force the name of the script class when explicitly creating a class inside the script, like:

class MyOwnScriptClass {
    def someClassMember() {
    }
}

return new MyOwnScriptClass()

After loading that file it shows me MyOwnScriptClass as class name - for the object which is returned by that script - not the script itself. However for my purposes this is sufficient.

Related