1
votes

This is a bit tricky to explain, but in Azure Pipelines if you have Build Validation policy for a Pull Request the build pipeline will run having the following variables:

System.PullRequest.SourceBranch 

The branch that is being reviewed in a pull request. For example: refs/heads/feature/branch. 


System.PullRequest.TargetBranch

The branch that is the target of a pull request. For example: refs/heads/master. 

But after a Pull Request is completed and the CI triggers a pipeline build on the target branch (refs/head/master) it is no longer possible to view these variables.

I have a npm package where I want, after a successful PR merge, to publish either a new minor or patch version automatically based on if the PR branch starts with either refs/feature/ or refs/bugfix/ respectively.

How can I get the name of the source PR branch in this CI build on the target branch. (Not the PR build validation policy)

1

1 Answers

2
votes

You can use rest api to get the source branchs of the PR.

You can add a script task to call Get Pull Requests Api and specify the searchCriteria to filter the latest Pull Request. Please check below example:

 - powershell: |
        $url = "$(System.TeamFoundationCollectionUri)$(System.TeamProject)/_apis/git/repositories/$(Build.Repository.ID)/pullrequests?searchCriteria.targetRefName=refs/heads/master&searchCriteria.status=completed&'$top=1&api-version=5.1"
        $result = Invoke-RestMethod -Uri $url -Headers @{authorization = "Bearer $(System.AccessToken)"} -Method get
        $branches = $result.value[0]
        echo "##vso[task.setvariable variable=sourceBranch]$($branches.sourceRefName)"

Above scripts will get the latest Pull request that merged to Master branch, and then retrieve the sourceRefName and set it to variable sourceBranch. So that you can refer to the variable $(sourceBranch) in the follow tasks.

Another api you can use to get the sourceRefName is Builds - Get. Since the CI build on the master branch is triggered right after the PR build. You can refer to the PR build id in the master branch CI build by $(Build.BuildId)-1. For example

$buildid = $(Build.BuildId)-1    

$url="$(System.TeamFoundationCollectionUri)$(System.TeamProject)/_apis/build/builds/$buildid?api-version=5.1"

$bresult = Invoke-RestMethod -Uri $prurl -Headers @{authorization = "Bearer $(System.AccessToken)"}  -Method get

$para = $bresult.parameters | ConvertFrom-Json

echo "##vso[task.setvariable variable=sourceBranch]$($para.'system.pullRequest.sourceBranch')"