Reputation: 1
I want to get the branch name in a Azure pipeline. I can get it using:
- script: |
echo "Original Source Branch: $(Build.SourceBranch)"
BRANCH_NAME=${BUILD_SOURCEBRANCH#refs/heads/}
echo "Branch Name: $BRANCH_NAME"
displayName: 'Display source branch name'
But when I create a tag using:
git tag -a v1.0.1 -m "Release version 1.0.1"
git push origin v1.0.1
the branch name is only the tag value as follows:
Does anybody know how I can get the branch name when I created a tag?
I expected to get the branch name, but instead I get the tag value.
Upvotes: 0
Views: 316
Reputation: 5622
The predefined variables Build.SourceBranch
is the branch of the triggering repo the build was queued for. When the pipeline is triggered by a tag, the Build.SourceBranch
should be refs/tags/tagname
.
In my understanding, what you want is the branch name where the tag is created from. If it is, you can use the following powershell script to get the branch name.
- powershell: |
if ("$(Build.SourceBranch)" -like "refs/tags/*") {
$tagName = "$(Build.SourceBranch)" -replace 'refs/tags/', ''
# Get the commit hash of the tag
$tagCommit = git rev-list -n 1 $tagName
# Find the branch that contains the commit
$BRANCH_NAME = git branch -r --contains $tagCommit | Select-String -Pattern 'origin/' | ForEach-Object { $_.Line -replace '.*origin/', '' } | Select-Object -First 1
Write-Output "The tag $tagName was created from branch: $BRANCH_NAME"
} else {
$BRANCH_NAME = "$(Build.SourceBranch)" -replace 'refs/heads/', ''
Write-Output "Branch Name: $BRANCH_NAME"
}
displayName: 'Display source branch name'
Test result:
Upvotes: 0