4

I wanted to create a class in /src directory which can access docker and other plugin steps.

So I have a class that looks like this;

class someClassName implements Serializable {
    def env
    def steps
    def docker

    someclassName(env, steps, docker){
        this.step = step
        this.docker = docker
        this.env = env
    }

    def runCommands(String img, List commands){
       docker.image(img).inside {
           commands.each {
             steps.sh it
           }
       }
    }

Now in Jenkinsfile I will have

@Library('name@branch') _
def x = new com.JenkinsLibrary.someClassName(env, steps, docker)
x.runCommands('maven:latest', ['mvn clean', 'mvn test'])

What i dont like is how I have a constructor for each object so that I can call methods that belong to that object. Is there a better object that i can use for my constructor instead of having to use env, steps, docker, etc?

Also, what pipeline steps are available under steps object? same for env?

4

1 回答 1

5

Try sending along the surrounding CPSScript:

class someClassName implements Serializable {
    def script

    someclassName(script){
        this.script = script
    }

    def runCommands(String img, List commands){
        script.docker.image(img).inside {
            commands.each {
                script.sh it
           }
       }
    }
}

and you provide the script by using this in the pipeline script:

@Library('name@branch') _
def x = new com.JenkinsLibrary.someClassName(this)
x.runCommands('maven:latest', ['mvn clean', 'mvn test'])
于 2018-05-05T19:38:54.947 回答