首先,我是自动化的新手,所以请原谅我的任何错误。
我们目前使用 Azure DevOps 存储库(从 TFS 迁移)。在 DevOps 中,我们有一个“主要”存储库。典型的工作是,开发人员创建他们的分支,一旦准备就绪,他们将其分支推送到远程 DevOps 存储库(例如
git push -u origin itsp2187
)。
一旦进入 DevOps,开发人员将创建一个 PR,一旦获得批准,PR 就完成了(合并到远程主分支)。
我想做的是当 PR 合并到 DevOps 主分支时能够做一些事情。我需要使用合并 PR 中的信息更新外部数据库(例如,执行 PR 合并的用户、发生这种情况的日期和时间、PR 标题以及任何描述(如果可能))。
我应该使用什么样的软件来完成此任务?这可能吗?我听说 Github 中使用了 Actions,我听说 Azure 中使用了管道和 Webhook。这些是一样的吗?或者这些软件或其他软件中的任何一个最适合这种需求吗?
合并 PR 时,提交历史记录中会有一条默认的 Commit 消息,如
Merged PR xx: The pull request title
。
注意:如果您使用该解决方案并想要自定义合并提交消息,请保留关键字
Merged PR xx:
基于此消息,我们可以创建一个管道,仅当 Commit 消息 (
$(Build.SourceVersionMessage)
) 包含关键字 Merged PR
时才会运行。在管道中,我们在 PowerShell 任务中使用 REST API Get Pull Request By Id。
以下是我的测试步骤:
trigger:
- main
pool:
vmImage: Windows-latest
jobs:
- job: A
condition: eq(contains(variables['Build.SourceVersionMessage'], 'Merged PR'), True)
steps:
- task: PowerShell@2
inputs:
targetType: 'inline'
script: |
# Set your Azure DevOps organization, project, repository information
$organization = "your organization name"
$project = "your project name"
$repositoryId = "your repo name" # repo name or repo id
$token="$(PAT)"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f "",$token)))
# get pullRequestId from the $(Build.SourceVersionMessage)
$string = "$(Build.SourceVersionMessage)"
$splitString = $string.Split(" ")
$pullRequestId = $splitString[2].Replace(":", "")
Write-Host "pullRequestId is $pullRequestId"
# Invoke the REST API to get the pull request
$uri = "https://dev.azure.com/$organization/$project/_apis/git/repositories/$repositoryId/pullRequests/$pullRequestId"+"?api-version=7.1-preview.1"
$uri
try {
$Response = Invoke-RestMethod -Uri $uri -Method Get -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}
$Response | ConvertTO-Json
} catch {
Write-Host "Error retrieving infornation of Pull Request $pullRequestId : $_"
exit 1
}
Merged PR
,则作业将被跳过。
webhook 的 YAML 管道触发器与拉取请求更新事件一起使用。
详细步骤:
"https://dev.azure.com/<ADO Organization>/_apis/public/distributedtask/webhooks/<WebHook Name>?api-version=6.0-preview"
。 WebHook 名称是您在服务连接中设置的名称。
trigger: none
resources:
webhooks:
- webhook: MyWebhookTrigger ### Webhook name
connection: MyWebhookConnection ### Incoming webhook service connection name
filters:
- path: resource.status
value: completed
steps:
- task: PowerShell@2
inputs:
targetType: 'inline'
### JSON payload data is available in the form of ${{ parameters.<WebhookAlias>.<JSONPath>}}
script: |
Write-Host "user who executed the PR merge: ${{ parameters.MyWebhookTrigger.resource.createdBy.displayName}}"
Write-Host "creationDate: ${{ parameters.MyWebhookTrigger.resource.creationDate}}"
Write-Host "closedDate: ${{ parameters.MyWebhookTrigger.resource.closedDate}}"
Write-Host "PR title: ${{ parameters.MyWebhookTrigger.resource.title}}"
Write-Host "description: ${{ parameters.MyWebhookTrigger.resource.description}}"
测试结果: