Enforcing Pull Requests title

Viewed 499

I used some GitHub gates for enforcing Pull Requests title by rules. But I didn't find any way to do it on Azure DevOps (the code is hosted on Azure DevOps Repo).

How can I create a PR gate that enforces the Pull Requests title?

2 Answers

You could define a small pipeline with a powershell task which examines the pull request title and checks if it is valid.

Then, you configure your master branch to include that pipeline as part of the Build Validation policy; the pipeline will automatically get run, and automatically gate the PR.

Note; you will have to call the Azure Devops REST API to get hold of the PR name, because while the pull request ID is automatically supplied in the pre-defined system variables, the pull request name is not.

I implemented the very good suggestion by Vince. First I created a simple powershell script (validate_conventional_commit.ps1) to validate if a string complies with the Regex I want to match it with. In this case, I want PR titles to comply with conventional commits.

Param(
    [Parameter(Mandatory = $True)]
    [string]$CommitMessage
)

$Regex="^(fix|feat):"

if ($CommitMessage -match $Regex) {
  Write-Host "The commit message complies with conventional commits."
}
else {
  Throw "Error : Invalid commit message!"
}

Then I created a pipeline to examine the PR title and check if it is valid.

trigger: none

pool:
  vmImage: 'ubuntu-latest'
steps:
  - bash: |
      pr_title="$(curl --silent -u azdo:$SYSTEM_ACCESSTOKEN \
       $(System.CollectionUri)_apis/git/repositories/$(Build.Repository.ID)/pullRequests/$(System.PullRequest.PullRequestId)?api-version=5.1 \
       | jq -r .title)"

      echo "##vso[task.setvariable variable=pr_title;]'$pr_title'"
    env:
      SYSTEM_ACCESSTOKEN: $(System.AccessToken)
    displayName: Extract pull request title

  - task: PowerShell@2
    displayName: 'Validate the PR title, which will be used as the commit message when merging to the target branch'
    inputs:
      targetType: 'filePath'
      filePath: 'validate_conventional_commit.ps1'
      arguments: '$(pr_title)'
      failOnStderr: true

And lastly, I created a PR trigger via a Build Validation branch policy, which will trigger the pipeline when a PR is created against the target branch.

Related