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

如何通过Azure DevOps REST API获取Git标签对应的Commit ID

问题:自动化获取Azure DevOps Git两标签间已关闭工作项的困惑

核心问题

我想自动化统计Git仓库两个标签之间所有已关闭的工作项,但遇到两个关键问题:

  • 在Azure DevOps的标签页面能看到标签对应的Commit ID,但通过REST API获取标签时,返回的objectId和实际Commit ID不匹配
  • 所有用于范围查询的API都需要变更集ID或日期范围,但标签API的返回结果里没有关联日期

当前使用的代码

获取标签列表的PowerShell代码

$tagsUrl = "https://dev.azure.com/$Organization/$SystemTeamProject/_apis/git/repositories/$repositoryId/refs?filter=tags/&api-version=7.1-preview.1"
$tagsResponse = Invoke-RestMethod -Uri $tagsUrl -Method Get -Headers $headers
$allTags = $tagsResponse.value | ForEach-Object { $_.name -replace "refs/tags/", "" }

创建标签的PowerShell代码

git tag -a $releaseInfo.ReleaseTag -m "Tagging release branch"
git push -q origin $releaseInfo.ReleaseTag

问题原因与解决方法

为什么objectId不是Commit ID?

你用git tag -a创建的是带注释的标签(annotated tag),这类标签在Git中是独立的对象,包含标签信息、作者、注释等元数据,所以Azure DevOps的refs API返回的objectId是标签对象本身的ID,而非它指向的Commit ID。

如何获取标签对应的Commit ID?

调用Azure DevOps的注释标签详情API,可以直接拿到标签指向的Commit信息:

$targetTagName = "24.2.1.601-RELEASE-CANDIDATE"
$tagDetailUrl = "https://dev.azure.com/$Organization/$SystemTeamProject/_apis/git/repositories/$repositoryId/annotatedtags/$targetTagName?api-version=7.1-preview.1"
$tagDetail = Invoke-RestMethod -Uri $tagDetailUrl -Method Get -Headers $headers
# 提取标签指向的Commit ID
$commitId = $tagDetail.target.objectId

如何获取Commit的日期用于范围查询?

拿到Commit ID后,调用Commit详情API获取提交日期:

$commitDetailUrl = "https://dev.azure.com/$Organization/$SystemTeamProject/_apis/git/repositories/$repositoryId/commits/$commitId?api-version=7.1-preview.1"
$commitDetail = Invoke-RestMethod -Uri $commitDetailUrl -Method Get -Headers $headers
# 提取提交日期
$commitDate = $commitDetail.committer.date

如何获取两标签间的已关闭工作项?

  1. 先获取两个标签对应的Commit ID和日期
  2. 使用commitsBatch API获取两个Commit之间的所有变更集:
    $commitsBatchUrl = "https://dev.azure.com/$Organization/$SystemTeamProject/_apis/git/repositories/$repositoryId/commitsbatch?api-version=7.1-preview.1"
    $body = @{
        compareVersion = @{
            version = "<旧标签的Commit ID>"
            versionType = "commit"
        }
        targetVersion = @{
            version = "<新标签的Commit ID>"
            versionType = "commit"
        }
    } | ConvertTo-Json
    $commitsBetween = Invoke-RestMethod -Uri $commitsBatchUrl -Method Post -Headers $headers -Body $body -ContentType "application/json"
    
  3. 从这些变更集中提取关联的工作项ID,再通过工作项API筛选出状态为“已关闭”的条目;或者直接用工作项查询语言(WIQL)编写查询,筛选关联变更集在两个Commit之间的已关闭工作项。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 07:42:09