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

Azure DevOps开启batch:true后,如何获取批次的起始与结束提交哈希?

在Azure DevOps Batch模式下获取批次提交哈希用于MBT差分构建

核心思路

Azure DevOps的batch: true模式本身没有直接提供批次起始/结束提交的预定义变量,但可以通过Git命令或ADO REST API两种方式获取,再将这两个哈希传入MBT实现差分构建。


方法一:用Git命令获取提交范围

这种方式无需额外权限,直接通过Git本地查询即可:

  • 结束提交哈希:直接使用预定义变量$(Build.SourceVersion),它对应批次内的最新提交。
  • 起始提交哈希:基于上次成功构建的提交哈希$(Build.PreviousSuccessfulBuild.SourceVersion)推导,首次构建则用分支的根提交。

示例PowerShell脚本(添加到流水线步骤中):

# 定义结束提交
$endCommit = "$(Build.SourceVersion)"

# 获取起始提交
if ("$(Build.PreviousSuccessfulBuild.SourceVersion)" -ne "") {
    # 从上次成功提交后第一个提交开始
    $startCommit = git rev-list --reverse $(Build.PreviousSuccessfulBuild.SourceVersion)..$endCommit | Select-Object -First 1
} else {
    # 首次构建,取分支根提交
    $startCommit = git rev-parse $(Build.SourceBranchName)^
}

# 将结果设为流水线全局变量,供后续MBT步骤调用
Write-Host "##vso[task.setvariable variable=StartCommit;]$startCommit"
Write-Host "##vso[task.setvariable variable=EndCommit;]$endCommit"

方法二:调用Azure DevOps REST API获取关联提交

通过API直接拉取当前构建绑定的所有提交,精准获取首尾哈希:

  1. 确保流水线的服务账号拥有读取构建提交的权限。
  2. 添加以下PowerShell脚本到流水线:
$orgUri = "$(System.TeamFoundationCollectionUri)"
$projectName = "$(System.TeamProject)"
$buildId = "$(Build.BuildId)"
$accessToken = "$(System.AccessToken)"

# 构建API请求头
$headers = @{
    "Authorization" = "Bearer $accessToken"
    "Content-Type"  = "application/json"
}

# 调用API获取当前构建的所有提交
$apiUrl = "$orgUri$projectName/_apis/build/builds/$buildId/commits?api-version=7.1-preview.1"
$commitResponse = Invoke-RestMethod -Uri $apiUrl -Headers $headers -Method Get

# 提取首尾提交哈希
$startCommit = $commitResponse.value[0].commitId
$endCommit = $commitResponse.value[-1].commitId

# 设置为流水线变量
Write-Host "##vso[task.setvariable variable=StartCommit;]$startCommit"
Write-Host "##vso[task.setvariable variable=EndCommit;]$endCommit"

传入MBT执行差分构建

在后续步骤中,直接调用MBT命令,传入获取到的两个哈希:

mbt describe diff --from $(StartCommit) --to $(EndCommit)

这样就能覆盖批次内的所有提交,确保没有遗漏任何关联构建。


内容的提问来源于stack exchange,提问作者T. Fouchard

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 11:30:17