powershell - 如果构建失败,如何在 Azure DevOps PR 中创建评论?
问题描述
在 Azure DevOps 中,我有一个自定义构建步骤在我的拉取请求构建期间在某些条件下失败。
我想通过提出 PR 评论来进一步扩展它,类似于 GitHub 中的这类事情: https ://developer.github.com/v3/issues/comments/#create-a-comment
我没有要在此处添加的代码示例,因为我找不到可以构建的有用示例。我将 PowerShell 用于我的自定义构建步骤 - 在运行我的分支的 PR 构建时如何实现这一点?
解决方案
我可以帮忙举个例子。将自定义消息\状态从您的管道发布到 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 中包含自定义状态信息!
推荐阅读
- c# - .Net ComException 调用 UserPrincipal.FindByIdentity (0x80005000)
- javascript - 如何使用 v-if 检查 .vue 中的 vue 对象是否为空
- python - 编写修改列表的函数的 Pythonic 方式?
- php - 仅计算包含帖子摘录的帖子
- c++ - 单击 Push 按钮应使用 Qt C++ 在不同窗口中显示绘图
- splunk - 报告是否可以从 splunk 手动通过电子邮件发送
- c++ - 在 C++ 中比较不相等的数组或字符串的方法
- mysql - 基于 ASP 经典 ODBC 查询中返回的数据量的服务器错误
- java - 我可以使用默认的 oauth2 客户端添加/更改授权请求的其他参数吗
- javascript - Firefox 保留在滚动动画中添加的类