You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jenkins库的Groovy switch块中提取Git提交信息并正则匹配

问题根源

Jenkins的sh步骤开启returnStdout: true参数时,返回的结果会自带命令输出末尾的换行符,也可能存在多余的前后空白字符。你硬编码测试时使用的是无多余空白的纯文本,所以匹配逻辑正常,但从Git命令拿到的message变量包含多余空白,导致正则匹配失败。

解决方法

拿到message后先调用trim()方法移除首尾所有空白字符(换行、空格、制表符等)再传入switch判断即可。

修改后的核心代码如下:

#!/usr/bin/env groovy

def call(String commitId) {
  message = sh(
      script: "git show -s  --format=%s ${commitId}",
      returnStdout: true
      ).trim() // 新增trim()清理空白
  println "Based on the commit message: \n ${message}"
  switch(message) { // 不需要额外做GString插值,直接使用变量即可
    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
}

补充说明

如果需要保留提交信息中间的空白,只清理末尾的换行,可以改用replaceAll(/\n$/, '')方法,仅删除末尾的换行符即可。

内容的提问来源于stack exchange,提问作者Josh Beauregard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 11:06:03