如何在Azure DevOps中获取两个分支间关联的所有Pull Requests
获取Azure DevOps分支差异提交关联的Pull Requests列表
问题背景
我们的development分支比staging分支领先100次提交,需要获取这些提交对应的Pull Requests(PR)列表。之前调用diffs/commits API仅返回提交信息,无法直接得到关联的PR数据。
解决方案步骤
要实现需求,需要分两步操作:先获取两个分支间的差异提交列表,再遍历每个提交获取其关联的PR,最后去重整理结果。
1. 获取分支差异提交列表
首先调用分支差异API,获取development相对staging的所有领先提交ID:
# 定义基础参数 $orgName = "your-org-name" $projectName = "your-project-name" $repoId = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee" $baseVersion = "staging" $targetVersion = "GBdevelopment" # 与分支对比URL中的目标分支标识一致 $apiVersion = "7.1-preview.1" # 认证头(假设已通过PAT生成) $AzureDevOpsAuthenicationHeader = @{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($yourPAT)"))} # 获取差异提交 $diffUri = "https://dev.azure.com/$orgName/$projectName/_apis/git/repositories/$repoId/diffs/commits?baseVersion=$baseVersion&targetVersion=$targetVersion&api-version=$apiVersion" $diffCommits = Invoke-RestMethod -Uri $diffUri -Method Get -Headers $AzureDevOpsAuthenicationHeader # 提取所有提交ID $commitIds = $diffCommits.commits.id
2. 获取提交关联的PR并去重
遍历每个提交ID,调用提交关联PR的API,收集并去重PR信息:
$relatedPRs = @() foreach ($commitId in $commitIds) { $prUri = "https://dev.azure.com/$orgName/$projectName/_apis/git/repositories/$repoId/commits/$commitId/pullRequests?api-version=$apiVersion" $prs = Invoke-RestMethod -Uri $prUri -Method Get -Headers $AzureDevOpsAuthenicationHeader foreach ($pr in $prs.value) { # 避免重复添加同一PR if (-not ($relatedPRs.PRId -contains $pr.pullRequestId)) { $relatedPRs += [PSCustomObject]@{ PRId = $pr.pullRequestId Title = $pr.title Creator = $pr.createdBy.displayName CreationDate = $pr.creationDate Status = $pr.status WebUrl = $pr.url -replace "_apis/git/repositories/.*?/pullRequests", "_git/$repoName/pullrequest" } } } } # 输出整理后的PR列表 $relatedPRs | Format-Table PRId, Title, Creator, Status, CreationDate -AutoSize
关键说明
diffs/commitsAPI仅返回提交的基础信息,不包含PR关联数据,必须通过commits/{commitId}/pullRequestsAPI单独查询。- 使用较新的API版本(如
7.1-preview.1)确保功能兼容性。 - 去重操作是因为单个PR可能包含多个提交,避免重复展示同一PR。
内容的提问来源于stack exchange,提问作者napsebefya
相关产品推荐
相关产品推荐

