Gabriel Wu
Gabriel Wu

Reputation: 2086

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

I'm developing a Jenkins shared library.

Directory structure as below:

project
- src
--- Operations.groovy
- vars
--- entry.groovy

Now in entry.groovy my code is:

import Operations;
def call(body) {

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

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

And in Operations.groovy:

class Operations {

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

When I tried and run it in Jenkins, 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. Is there any correct way or a guide that can help me to use Jenkins built-in method correctly?

Upvotes: 8

Views: 2246

Answers (1)

Szymon Stepniak
Szymon Stepniak

Reputation: 42184

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); // passing a reference to workflow script

   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
        }
    }
}

Upvotes: 9

Related Questions