Home > Back-end >  Jenkins Groovy: how to extract specific number from parameter in method?
Jenkins Groovy: how to extract specific number from parameter in method?

Time:08-31

I am quite new in Groovy and trying to extract find the best way to write a method that will extract the 3rd number in branch name which is passed as a parameter.

Standard gitBranchName looks like this release-1.2.3

Below is my method and I am wondering what to do with newestTagNumber:

#!/usr/bin/env groovy

def call(gitRepoName, gitBranchName) {
withCredentials([
    string(credentialsId: 'jenkinsuser', variable: 'USER'),
    string(credentialsId: 'jenkinssecret', variable: 'SECRET')]) {
    def commitHash = sh(
      script: 'git rev-parse --short HEAD',
      /*script: 'git rev-parse --symbolic-full-name @{-1} && git rev-parse --abbrev-ref @{-1}' */
      returnStdout: true).trim()
    def repoUrl = "bitbucket.org/cos/${gitRepoName}"

    /* newestTagNumber - this is 3rd number taken from gitBranchName */
    def newestTagNumber = <what_to_add_here?>

    /* nextTagNumber - incremented by 1 */
    def nextTagNumber = newestTagNumber   1

    sh """
      git config user.email "[email protected]"
      git config user.name "jenkins"
      git tag -a release-${nextTagNumber}.t -m 'Create tag release-${nextTagNumber}.t' 
    """
    sh('git push --tags https://${JT_USER}:${JT_SECRET}@'   repoUrl)
  }
}

This is how it will probably work using Regex, but is there a prettier way to do it in Groovy?

[\d]*(\d$)

enter image description here

Thank you guys!

CodePudding user response:

You can simply split the String by "." and get the last digit.

def parts = gitBranchName.split("\\.")
def newestTagNumber = parts[parts.size()-1]

If you are sure you will always get the branch name in this format with 3 decimal points(release-1.2.3) here is a one-liner.

def newestTagNumber = gitBranchName.split("\\.")[2]

CodePudding user response:

@ycr solution is right, but I found even better option if you always want to change the last number (which is my case):

def newestTagNumber = gitBranchName.split("\\.").last()

Thanks!

  • Related