首页 > 解决方案 > 如何将 git 消息提取为变量和。常规开关块中的正则表达式匹配。(通过詹金斯图书馆)

问题描述

var在一个 groovy 库中有一个试图匹配提交消息并设置要返回的变量,但是它没有正确匹配。

请注意,我已经在一个裸脚本中尝试过这个,我提供message了一个硬编码的字符串。

#!/usr/bin/env groovy

def call(String commitId) {
  message = sh(
      script: "git show -s  --format=%s ${commitId}",
      returnStdout: true
      )
    println "Based on the commit message: \n ${message}"
    switch("${message}") {
      case ~/.*Feature.*/:
        verType = 'minor'
        println "The Next version will be a ${verType} type"
        break
      case ~/^.*(Hot|Bug)fix.*$/:
        verType = 'patch'
        println "The Next version will be a ${verType} type"
        break
      case ~/^.*Release.*$/:
        verType = 'major'
        println "The Next version will be a ${verType} type"
        break
      default:
        verType = 'patch'
        println 'No matches using Patch'
        break
    }
  return verType
}

我已经尝试了文字、“功能”和“发布”的提交 ID,它总是返回默认值。我在 Jenkins 控制台中得到这样的输出:

[Pipeline] sh
+ git show -s --format=%s 1c532309b04909dc4164ecf9b3276104bf5c2bc0
[Pipeline] echo
Based on the commit message: 
 Feature

[Pipeline] echo
No matches using Patch

当我在命令行上运行下面类似的脚本时,它返回“Release”,它向我展示了它是如何将消息传递给语句的。

#!/usr/bin/env groovy

  message = 'Release, creating major release'
    switch(message) {
      case ~/.*Feature.*/:
        verType = 'minor'
        break
      case ~/^.*(Hot|Bug)fix.*$/:
        verType = 'patch'
        break
      case ~/^Release.*$/:
        verType = 'major'
        break
      default:
        verType = 'patch'
        break
    }
    println verType

标签: regexjenkinsgroovy

解决方案


那是因为message包含多行字符串

尝试message = '\nRelease, creating major release'使用您的第二个脚本来重现问题

要修复它,您可以像这样修改您的正则表达式:

/^\s*Release.*$/


推荐阅读