如何提取 git 消息作为变量并。 groovy 开关块中的正则表达式匹配。 (通过詹金斯图书馆)

How to extract git message as a variable and. regex match in a groovy switch block. (via jenkins library)

我在 groovy 库中有一个 var 试图匹配提交消息并将变量设置为 return 但是它没有正确匹配。

请注意,我已经在一个裸脚本中尝试过此操作,我在其中提供 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,它始终是 return 的默认值。 我在 Jenkins 控制台中得到这样的输出:

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

[Pipeline] echo
No matches using Patch

当我 运行 在命令行上使用下面的类似脚本时,它 return 的“释放”告诉我它是如何将消息传递给语句的。

#!/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

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

尝试 message = '\nRelease, creating major release' 在你的第二个脚本上重现问题

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

/^\s*Release.*$/

问题就像@dagget 在我的 message 变量中所说的那样。但是当我找到答案时我没有看到他的post。所以我想我会 post 工作版本作为答案。我使用 String.trim() 函数删除了前导换行符。

这是我的工作代码。

#!/usr/bin/env groovy

def call(String commitId) {
  String message = sh(
      script: "git show -s  --format=%s ${commitId}",
      returnStdout: true
      )
    println "Based on the commit message: \n ${message.trim()}"
    switch("${message.trim()}") {
      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
}