有没有办法在点击 Pull Request 中的完成按钮后在 Azure DevOps 中获取 Pull Request ID

问题描述 投票:0回答:2

我在创建 PR 后正在执行管道流,并且在单击完成按钮后需要获取拉取请求 ID。

我使用 $(System.PullRequest.PullRequestId) 来获取值,但它始终是空值,并给出错误输出“System.PullRequest.PullRequestId:找不到命令

创建一个简单的经典管道,如下所示,需要在分支策略 -> 状态检查中调用。

注意: 使用相同的变量 $(System.PullRequest.PullRequestId) 我可以在完成之前获取 ID,即当 PR 处于活动状态时。

azure-devops azure-devops-rest-api azure-devops-pipelines
2个回答
3
投票

Ad @CodeCaster在评论中表示,仅当构建由于受分支策略影响的 Git PR 而运行时,变量

$(System.PullRequest.PullRequestId)
才会被初始化。

但是,您可以通过 Rest API 使用小 PS 脚本获取最后完成的 PR ID:

$header = @{ Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"  }
$url = "$(System.TeamFoundationCollectionUri)$(System.TeamProject)/_apis/git/repositories/$(Build.Repository.Name)/pullrequests/?searchCriteria.status=3&top=50&searchCriteria.targetRefName=refs/heads/master&api-version=6.1"
$pullRequests = Invoke-RestMethod -Uri $url -Method Get -Headers $header -ContentType application/json
Write-Host "Last PR completed to master is: $($pullRequests.value[0].pullRequestId)"

只需将

master
中的
$url
替换为你的目标分支名称即可。

结果:

如果您使用经典编辑器或将令牌添加到 YAML 任务,请不要忘记启用访问令牌。


0
投票

唯一的方法是使用正则表达式从合并提交消息中提取 PR ID。 可以使用 CI 中的

$(Build.SourceVersionMessage)
环境变量(合并 PR 后的 CI)来获取合并提交消息,然后我使用
Merged PR (\d*):.*
正则表达式来提取 PR Id。

我看到合并提交消息通常生成为

Merged PR [PR ID]: [PR Title]
例如
Merged PR 123456: My first PR in the world of coding :)

© www.soinside.com 2019 - 2024. All rights reserved.