Micah Potter
Micah Potter

Reputation: 103

WorkflowScript.with in Jenkins

I have a class in a jenkins shared library that stores the instance of a WorkflowScript class from a jenkins pipeline script as shown below.

def myTools = new my.org.MyTools(this)

the constructore of MyTools just stores the instance of WorkflowScript like this...

MyTools(script){
    this.script = script
}

then I have a method that tries to use groovy's .with on script but fails...

myMethod(){
    script.with{
        node{
            echo "I want to be able to use pipeline syntax here"
            sh 'echo "without using script. in front of each command"'
        }
    }
}

But when I run this i get the following error...

hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: org.jenkinsci.plugins.workflow.cps.CpsClosure2.node() is applicable for argument types: (org.jenkinsci.plugins.workflow.cps.CpsClosure2) values: [org.jenkinsci.plugins.workflow.cps.CpsClosure2@855f14e]
Possible solutions: clone(), use([Ljava.lang.Object;), notify(), wait(), call(), run()
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:58)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:54)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite
.java:113)

I would have expected the inside of the script.with closure to have access to all of the same stuff as script., but it looks like it only has access to methods of java.lang.Object. Is it possible to get the script.with closure to function with the same context of script.?

Upvotes: 4

Views: 4703

Answers (2)

RainingChain
RainingChain

Reputation: 7746

class MyTools {
    def script

    def myMethod(){
        def closure = {
            echo "I want to be able to use pipeline syntax here!"
        }
        closure.setDelegate(this.script)
        closure()
    }
}

stage('XXX') {
    steps {
        script {
            def myTools = new MyTools(script:this)
            myTools.myMethod()
        }
    }
}

Upvotes: 0

daggett
daggett

Reputation: 28564

for groovy closure possible to specify strategy which the closure uses to resolve methods and properties

there are options: DELEGATE_FIRST, DELEGATE_ONLY, OWNER_FIRST (default), OWNER_ONLY, TO_SELF

i think the pipeline script has a special strategy, and in your class there is a default one.

Upvotes: 3

Related Questions