get merged branch name in azure pipelines yaml

Viewed 1950

When merging in a feature branch to the dev branch I want to get the merged branch name in my azure-pipeline.yaml on the build that gets triggered for the dev branch.

Is this possible?

Or when a branch gets deleted in my repo can I kick off a build that containers the delete branch name?

2 Answers

In BitBucket repo, it provides default commit message when trying to merge feature1 into dev branch:

Merged in feature1 (pull request #{PullRequestNumber})

We can access this message via predefined variable $(Build.SourceVersionMessage). And we can use Powershell task to output the Merged Branch Name, we can even use PS task to set variables in scripts so that following steps can also access this value. Here's my working script:

steps:
- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: |
      $SourceVersionMessage = "$(Build.SourceVersionMessage)"
      $SourceBranchName = $SourceVersionMessage.split(" ")[2]

      #Output the Merged Branch Name
      Write-Host $SourceBranchName

      #Set the  `MergedBranchName` variable so that following steps can access the Merged Branch Name
      Write-Host "##vso[task.setvariable variable=MergedBranchName]$SourceBranchName"
      
- script: |
    echo $(MergedBranchName)

The following step can access this value successfully:

enter image description here

If I follow correctly, you're completing a Pull Request that merges a feature branch (source branch) into the develop branch (target branch) and this triggers a build on the develop branch. In the resulting build, you want to get the name of the feature branch? Maybe the feature branch followed a naming convention that is significant that you want to carry forward.

You do have the commit id available to you in the $(Build.SourceVersion) variable, so you should be able to fetch the commit information using the BitBucket REST API. This commit details endpoint can identify the pull-requests for a commit so you should be able to get the source branch information from there.

/2.0/repositories/{workspace}/{repo_slug}/commit/{commit}/pullrequests

You should also be able to fetch the commit message using $(Build.SourceVersionMessage)

Regarding triggering a build when a branch is deleted, there aren't any native triggers in the YAML syntax for this but you can define a trigger that uses a webhook trigger. BitBucket does not seem to expose an event for when branches are deleted.

Related