You need to enable JavaScript to run this app. 如何通过Azure DevOps REST API根据commit id查询对应分支名称
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Azure DevOps REST API根据commit id查询对应分支名称

解决方案

你当前使用的get_commits接口返回的提交对象本身不包含关联分支信息,需要调用专门的引用查询接口获取,两种实现方式如下:

方式1:使用azure.devops Python SDK实现(推荐)

SDK提供了get_commit_refs方法,可直接查询指定提交关联的所有分支、标签引用,修改后的完整代码如下:

from datetime import datetime

# 原有查询最新提交逻辑,top设置为1即可,不需要查询10条
cm_search_criteria = models.GitQueryCommitsCriteria(history_mode='firstParent', top=1)
commits = git_client.get_commits(repo.id, search_criteria=cm_search_criteria, project=project.name)
if commits:
    latest_commit = commits[0]
    # 原有时间、提交人获取逻辑
    datetimeobj = datetime.strptime(latest_commit.committer.date.strftime("%x"), '%m/%d/%y')
    last_commit_on = datetimeobj.date()
    last_commit_by = latest_commit.committer.email
    
    # 新增:查询提交关联分支
    commit_refs = git_client.get_commit_refs(
        repository_id=repo.id,
        commit_id=latest_commit.commit_id,
        project=project.name,
        filter="heads/" # 过滤仅返回分支引用,去掉该参数会同时返回标签引用
    )
    # 提取分支名称,去掉refs/heads/前缀即可
    related_branches = [ref.name.replace("refs/heads/", "") for ref in commit_refs]
    # 若需要和Azure DevOps UI展示的默认分支一致,可筛选仓库默认分支
    # default_branch = repo.default_branch.replace("refs/heads/", "")
    # ui_show_branch = next((b for b in related_branches if b == default_branch), related_branches[0])

说明:同一个提交可能被合并到多个分支,因此返回的是分支列表,可根据业务需求筛选目标分支。

方式2:直接调用Azure DevOps REST API实现

如果需要直接调用REST API,使用如下接口即可:

  • 请求方法:GET
  • 接口地址:https://dev.azure.com/{组织名称}/{项目名称}/_apis/git/repositories/{仓库ID}/commits/{提交ID}/refs?filter=heads/&api-version=7.1-preview.1

返回结果中value数组的每一项name字段即为refs/heads/分支名格式的分支引用,去掉前缀即可得到实际分支名称。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 12:30:00