Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a comment in Azure DevOps PR in case of build failure?

I have a custom build step that fails under certain conditions during my Pull Request build, within Azure DevOps.

I would like to extend it further by raising a PR comment, similar to this sort of thing in GitHub: https://developer.github.com/v3/issues/comments/#create-a-comment

I don't have code samples to add here as I could not find useful examples to build upon. I use PowerShell for my custom build step - how do I achieve this when running a PR build of my branch?

like image 616
Rob McCabe Avatar asked Feb 03 '20 23:02

Rob McCabe


People also ask

What happens if pull request fails in Azure DevOps build failure?

In case of build-failure, the Pull Request won't be allowed to merge. That's it!! Azure DevOps Pull Request build validation pipeline has been set up for .Net 5 project and this policy plus pipeline will ensure only successfully building code is merged to master/main branch.

How do I create a new PR in Azure DevOps?

From the Azure DevOps project website, you can create a new PR from: The Pull requests page. A feature branch pushed to your repo. An existing PR, by using cherry-pick. The Development control in a linked Azure Boards work item.

How to automatically add comments to pull requests in Azure DevOps?

I am afraid there is no such way to automatically add comments to any pull requests created in Azure DevOps within a repository. That because we are currently unable to monitor the creation of pull requests in real time. And there is no similar extension to detect the creation of pull requests.

How do I review Azure DevOps Repos?

To review PRs, you must be a member of the Azure DevOps project the PR is in, with Basic access or higher. If you aren't a project member, get added. For public projects, users granted Stakeholder access have full access to Azure Repos.


Video Answer


2 Answers

I can help with an example. There is a bunch of value in posting custom messages\status to PRs from your pipelines.

First things first, make sure your build service has permissions to contribute to pull requests in your repository.

permissions

Then you want to add a conditional PowerShell step. This one is just based on it being a PR build, but you might want to add a depends on failure for the previous step, based on your workflow.

- 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

So the basic workflow is:

  • Build the Markdown Message
  • Build the JSON Body
  • Post the Message to the 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
}

And you end up with a nice markdown table with custom status information in your PR!

enter image description here

like image 196
Eric Smith Avatar answered Sep 22 '22 14:09

Eric Smith


Building on the great answers already provided, this is the equivalent inline YAML pipeline script:

  - powershell: |
      $body = @"
      {
          "comments": [
            {
              "parentCommentId": 0,
              "content": "Your comment here",
              "commentType": 1
            }
          ],
          "status": 4
        }
      "@
      $url = "$($env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI)$env:SYSTEM_TEAMPROJECTID/_apis/git/repositories/$($env:Build_Repository_Name)/pullRequests/$($env:System_PullRequest_PullRequestId)/threads?api-version=5.1"
      $result = Invoke-RestMethod -Uri $url -Method POST -Headers @{Authorization = "Bearer $(System.AccessToken)"} -Body $Body -ContentType application/json
    displayName: Post comment on PR
like image 39
Bouke Avatar answered Sep 22 '22 14:09

Bouke