简体   繁体   English

Jenkins Groovy:如何从方法中的参数中提取特定数字?

[英]Jenkins Groovy: how to extract specific number from parameter in method?

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.我在 Groovy 中很新,并试图提取找到编写方法的最佳方法,该方法将提取作为参数传递的分支名称中的第三个数字。

Standard gitBranchName looks like this release-1.2.3标准gitBranchName看起来像这个release-1.2.3

Below is my method and I am wondering what to do with newestTagNumber :下面是我的方法,我想知道如何处理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 "example@example.com"
      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?这可能是它使用正则表达式的工作方式,但是在 Groovy 中是否有更漂亮的方法呢?

[\d]*(\d$)

在此处输入图像描述

Thank you guys!感谢你们!

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.如果您确定您将始终以这种格式获得分支名称,带有 3 个小数点( release-1.2.3 ),这里是单行的。

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

@ycr solution is right, but I found even better option if you always want to change the last number (which is my case): @ycr 解决方案是正确的,但是如果您总是想更改最后一个数字(这是我的情况),我发现了更好的选择:

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

Thanks!谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM