首页 > 解决方案 > 如果构建失败,如何在 Azure DevOps PR 中创建评论?

问题描述

在 Azure DevOps 中,我有一个自定义构建步骤在我的拉取请求构建期间在某些条件下失败。

我想通过提出 PR 评论来进一步扩展它,类似于 GitHub 中的这类事情: https ://developer.github.com/v3/issues/comments/#create-a-comment

我没有要在此处添加的代码示例,因为我找不到可以构建的有用示例。我将 PowerShell 用于我的自定义构建步骤 - 在运行我的分支的 PR 构建时如何实现这一点?

标签: powershellazure-devopspull-requesttfs-code-review

解决方案


我可以帮忙举个例子。将自定义消息\状态从您的管道发布到 PR 有很多价值。

首先,确保您的构建服务有权为您的存储库中的拉取请求做出贡献。

权限

然后,您要添加条件 PowerShell 步骤。这只是基于它是一个 PR 构建,但您可能希望根据您的工作流程为上一步添加一个取决于失败。

- task: PowerShell@2
  condition: eq(variables['Build.Reason'], 'PullRequest')
  displayName: Post Message to PR
  env:
    SYSTEM_ACCESSTOKEN: $(System.AccessToken)  
  inputs:
      targetType: filePath
      filePath: PostToPR.ps1

所以基本的工作流程是:

  • 构建 Markdown 消息
  • 构建 JSON 主体
  • 将消息发布到 PR

PostToPR.ps1

#Going to create the comment in an Active state, assuming it needs to be resolved
#See https://docs.microsoft.com/en-us/dotnet/api/microsoft.teamfoundation.sourcecontrol.webapi.commentthreadstatus?view=azure-devops-dotnet
$StatusCode = 1 

$Stuff = $env:Build_Repository_Name
$Things = "Other things you might want in the message"

#Build Up a Markdown Message to 
$Markdown = @"
## Markdown Message here
|Column0 |Column1|
|--------|---------|
|$Stuff|$Things|  
"@

#Build the JSON body up
$body = @"
{
    "comments": [
      {
        "parentCommentId": 0,
        "content": "$Markdown",
        "commentType": 1
      }
    ],
    "status": $StatusCode 
  }
"@

Write-Debug $Body
#Post the message to the Pull Request
#https://docs.microsoft.com/en-us/rest/api/azure/devops/git/pull%20request%20threads?view=azure-devops-rest-5.1
try {
    $url = "$($env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI)$env:SYSTEM_TEAMPROJECTID/_apis/git/repositories/$($env:Build_Repository_Name)/pullRequests/$($env:System_PullRequest_PullRequestId)/threads?api-version=5.1"
    Write-Host "URL: $url"
    $response = Invoke-RestMethod -Uri $url -Method POST -Headers @{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"} -Body $Body -ContentType application/json
  if ($response -ne $Null) {
    Write-Host "*******************Bingo*********************************"
  }
}
catch {
  Write-Error $_
  Write-Error $_.Exception.Message
}

最后你会得到一个漂亮的降价表,在你的 PR 中包含自定义状态信息!

在此处输入图像描述


推荐阅读