在 Azure 中,有没有办法在创建/完成拉取请求时使用 repo and/or 分支标记工作项/用户故事?

In Azure is there a way to tag a work item / user story with the repo and/or branch when creating / completing a pull request?

我们的政策是始终link 将工作项/用户故事提交给 PR。有没有办法自动用 repo 名称/分支 PR 合并到的工作项标记?

目前正在手动执行此操作并尝试使其自动化(我们将 git 与 Azure Devops 结合使用)。

是的,有一种方法可以在创建 PR 时自动标记链接的工作项。您可以通过向分支策略添加 build validation 管道来完成此操作。并调用其余 api 来标记构建验证管道中的工作项。请参阅以下步骤:

1,创建构建验证管道。添加脚本任务以调用下面的 rest apis。

Call Pull Request Work Items - List api to get all the linked work item.

Call Work Items - Update api to add the tag to the work items

您可以通过在验证管道中引用预定义变量 $(Build.Repository.Name) 来获取 repo 名称。查看更多 predefined variables here。对于 powershell 任务中的以下示例脚本。

#PR workitem list api
$url = "$(System.TeamFoundationCollectionUri)$(System.TeamProject)/_apis/git/repositories/$(Build.Repository.Name)/pullRequests/$(System.PullRequest.PullRequestId)/workitems?api-version=6.1-preview.1"

$response= Invoke-RestMethod -Uri $url -Headers @{authorization = "Bearer $(System.AccessToken)"} -Method Get

#get all the related workitem ids
$ids = $response.value.id
#get the PR target branch name
$targetBranch = "$(System.PullRequest.TargetBranch)".split("/")[-1]
           
$newTag=  "$(Build.Repository.Name)/$($targetBranch)"

Foreach($id in $ids){

    $wurl = "$(System.TeamFoundationCollectionUri)$(System.TeamProject)/_apis/wit/workitems/$($id)?api-version=6.1-preview.3"

    # call get workitem api to get the existing tags
    $workitem = Invoke-RestMethod -Uri $wurl -Headers @{authorization = "Bearer $(System.AccessToken)"} -Method Get

    $tags = $workitem.fields.'System.Tags' + ";$($newTag)"

    $body =  @(
               @{
                op= "add";
                path= "/fields/System.Tags";
                value= "$($tags)"
              }
             )
    # add tags to work item.
    Invoke-RestMethod -Uri $wurl -Headers @{authorization = "Bearer $(System.AccessToken)"} -Method patch -Body (ConvertTo-Json $body) -ContentType "application/json-patch+json"

}

为了在上面的脚本中使用系统令牌$(System.AccessToken)。您需要为代理作业选中 Allow scripts to access the OAuth token 选项。见下文:

2、为目标分支的分支策略配置构建验证。

进入目标分支的分支策略页面。添加上面的管道作为构建验证管道。见下文:

在分支策略中设置构建验证之后。创建 PR 时。验证管道将被触发并自动将标签添加到工作项。