0

I am trying to convert all of the scripted pipelines at my workplace into declarative pipeline. I am new to this. I have a scripted pipeline that has 2 methods. I was able to finish the rest of the scripted to declarative but got stuck on methods. Since declarative doesn't really support methods and since i have to use this method multiple times in other declarative pipelines as well, i want to describe this method(s) as a groovy script in a shared library.

My question is, since this is a method from scripted pipeline, can i directly just copy paste my method into the groovy script or does it require exact syntax for groovy I checked the groovy syntax and don't really see much differences there ?

below is one of the the method: Can i just copy this into something like getversion.groovy and call it from my dec pipeline ? or does it need syntax/code changes to put into the groovy script ?

def getProjectVersion(directory) {
   dir(directory) {
      withEnv(["PATH+MAVEN=${env.M3}/bin"]) {
         sh 'rm -f version.txt'
         sh(
               """mvn org.apache.maven.plugins:maven-help-plugin:2.1.1:evaluate \
               -Dexpression=project.version | grep -v '\\[\\|\\D'  > version.txt"""
           )      
           return readFile('version.txt').trim()
}

}

There are some other complex methods as well in some of the other scripted pipelines that i am trying to convert to declarative, so this information would be very helpful.

Thanks

ameya
  • 89
  • 2
  • 10
  • I am able to finish the rest of all the scripted to declarative, but got stuck at methods, Did some research if i can convert the methods but since i have to reuse them in other pipelines also, thought its a good option to convert to shared libraries. I am able to create a repo, and create a vars directory for the shared libraries files, and started with a .groovy file, but just need to know if i can directly copy past the content from scripted pipeline in there. from Doc: The Groovy source files in these directories get the same “CPS transformation” as in Scripted Pipeline. – ameya Feb 20 '18 at 22:56
  • can anyone help ? – ameya Mar 01 '18 at 20:34

1 Answers1

0

If you have not done so already, check Shared Libraries for details. You should be able to use your example by creating vars/getVersion.groovy:

def call(directory) {
   dir(directory) {
    ...  
   }
}

Set up your Shared Library as described in the link and you should be able to call your code in your pipeline:

...
stage('Some stage') {
  steps {
    script {
      versionNumber = getVersion('/directory/of/project/')
    }
  }
}
...

In case your method does not have a return value the call might look like this:

...
stage('Some stage') {
  steps {
    setVersion '/directory/of/project/'
  }
}
...
Steve
  • 71
  • 3