How to use jenkins's built in method in class?

4280 views jenkins
9

i'm developing jenkins shared library. Directory as below. project - src --- Operations.groovy - vars --- entry.groovy. Now in entry.grooy. My code is as blow

import Operations;
def call(body){

   def operation=new Operation();
   podTemplate(xxxxxx){

     node(nodelabel){
        operation.stage_checkout()
     }
   }


}

And in file Operations.groovy

class Operations {

   def stage_checkout(){
      stage('Checkout') {
          checkout scm
      }
   }
}

When i tried and run it in jenkins and i got error like below.

GitHub has been notified of this commit’s build result

groovy.lang.MissingPropertyException: No such property: scm for class: Operations
Possible solutions: ui
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:53)
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.getProperty(ScriptBytecodeAdapter.java:458)
    at com.cloudbees.groovy.cps.sandbox.DefaultInvoker.getProperty(DefaultInvoker.java:39)
    at 

I think "checkout" is a jenkins plugin built-in method and how can i use it correctly ? is there any correct way or a guide that can help me to use jenkins built-in method correctly ?

Thanks a lot.

answered question

1 Answer

12

You can use built-in Jenkins pipeline steps through the reference to workflow script. You can pass a reference to Operations class through the constructor by passing this object. Consider following example:

vars/entry.groovy :

import Operations;

def call(body){

   def operation=new Operation(this);
   podTemplate(xxxxxx){
     node(nodelabel){
        operation.stage_checkout()
     }
   }
}

src/Operations.groovy :

class Operations {

    private final Script script

    Operations(Script script) {
        this.script = script
    }

    def stage_checkout(){
        script.stage('Checkout') {
            script.checkout script.scm
        }
    }
}

posted this

Have an answer?

JD

Please login first before posting an answer.