Search code examples
tagsazure-pipelinesbranchcommitgit-branch

How to get git branch at commit with tag at run Azure pipeline?


In Azure Pipeline is possible use predefined build variables (DevOps Services) Build.SourceBranch and Build.SourceBranchName but their values at case commit with tag are tags.

In doc. https://learn.microsoft.com/en-us/azure/devops/pipelines/build/variables?view=azure-devops&tabs=yaml#build-variables-devops-services is written

  • When your pipeline is triggered by a tag: refs/tags/your-tag-name
  • The name of the branch in the triggering repo the build was queued for. Git repo branch or pull request: The last path segment in the ref. For example, in refs/heads/master this value is master. In refs/heads/feature/tools this value is tools.
  • this my observation: but in case commit with tag is the last path segment of Build.SourceBranch, so your-tag-name

Solution

  • As it is described in the document. If the pipeline is triggered by a tag. Then variables Build.SourceBranch and Build.SourceBranchName will be the tag name.

    However, you can use git commands(git branch -r --contains $(Build.SourceBranchName) | grep -v $(Build.SourceVersion)) to retrieve the branch name that the tag points to.

    If you want to use the branch name as variable, You can define a variable use the logging commands(echo "##vso[task.setvariable variable=CurrentBranch]$branch"). For below example:

    - powershell: |
         #get the branch name
         $branch = git branch -r --contains $(Build.SourceBranchName) | grep -v $(Build.SourceVersion)
         
         #define varialbe CurrentBranch to hold the value.
         echo "##vso[task.setvariable variable=CurrentBranch]$branch" 
    
    - powershell: echo "$(CurrentBranch)"  #use the branch name in the following steps by referring to $(CurrentBranch)