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

如何在Azure DevOps中获取PR实际提交消息以实现语义化版本控制

解决Azure DevOps流水线中获取PR实际提交消息的问题

针对Squash合并场景

当PR采用squash合并时,Azure DevOps默认会生成带Merge pull request的合并消息,或者用PR标题作为压缩后的提交消息。你可以通过以下两种方式获取符合要求的提交内容:

方式1:直接使用Azure DevOps预定义变量

Azure DevOps提供了Build.SourceVersionMessage变量,它直接存储了触发流水线的提交消息,无需执行Git命令。修改你的流水线脚本如下:

- script: |
    COMMIT_MSG="$(Build.SourceVersionMessage)"
    echo "Commit message: $COMMIT_MSG"
    if [[ $COMMIT_MSG =~ ^(feat|fix|chore|docs|style|refactor|test|build|ci|perf) ]]; then
      echo "Commit message type is valid"
    else
      echo "Error: Commit message must start with one of the following: feat, fix, chore, docs, style, refactor, test, build, ci, perf"
      exit 1
    fi
  displayName: 'Check commit message type'

注:如果你的squash合并配置为使用PR标题作为提交消息,确保PR标题符合语义化格式即可。

方式2:通过Git命令提取squash提交中的原始消息

squash合并的提交正文里会包含所有被压缩的原始提交记录,你可以从中提取符合格式的消息:

- script: |
    # 检查当前提交是否为squash合并提交
    if git log -1 --format=%B | grep -q "Squash commit of the following"; then
      # 提取第一条符合语义化格式的原始提交消息
      COMMIT_MSG=$(git log -1 --format=%B | grep -E "^(feat|fix|chore|docs|style|refactor|test|build|ci|perf)" | head -n1)
    else
      COMMIT_MSG=$(git log -1 --format=%s)
    fi
    echo "Commit message: $COMMIT_MSG"
    if [[ -z $COMMIT_MSG || ! $COMMIT_MSG =~ ^(feat|fix|chore|docs|style|refactor|test|build|ci|perf) ]]; then
      echo "Error: Commit message must start with one of the following: feat, fix, chore, docs, style, refactor, test, build, ci, perf"
      exit 1
    fi
  displayName: 'Check commit message type'

针对Rebase合并场景

使用rebase合并时,流水线触发的是rebase后的最后一个原始提交,正常情况下git log -1能拿到正确的消息。如果仍出现合并消息,检查你的分支策略配置:

  • 确保rebase合并时不生成额外的合并提交,保留原始提交记录
  • 优先使用Build.SourceVersionMessage变量获取提交消息,避免Git命令的环境差异

从源头管控的方案

如果想避免后期检查的麻烦,建议在Azure DevOps仓库中配置分支策略:

  • 安装Commit Message Checker类的扩展,开启提交消息格式验证,阻止不符合格式的提交推送到分支
  • 设置PR合并前的验证步骤,直接检查PR标题(squash合并时会用它作为提交消息)是否符合语义化格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 09:20:14