简体   繁体   中英

How to get the current Git branch name in a TFS 2013 build?

My goal

I want to include the current Git branch name in the name of my package (that is then deployed via Octopus).

If this was TFS 2015 or 2017, I could just set the Build number format to $(SourceBranchName)-something in the build definition. Or I could use the build variable $(BUILD_SOURCEBRANCHNAME) in my .proj file.

But I am using TFS 2013, so these new variables are not available to me.

How do I achieve the same thing in TFS 2013?

What I've tried

I attempted to get the branch name via a Git command:

<Exec Command="git rev-parse --abbrev-ref HEAD" ContinueOnError="false" IgnoreExitCode="true" ConsoleToMsBuild="true">
  <Output TaskParameter="ConsoleOutput" PropertyName="CurrentGitBranch" />
</Exec>

But the output of this is just HEAD .

I also tried changing the command to:

git symbolic-ref --short HEAD

Which returns fatal: ref HEAD is not a symbolic ref .

So it seems like the checked-out repository on the build server is not pointing to any specific branch.

As pointed out by Martin Ullrich, the current git branch is stored in the build variable TF_BUILD_SOURCEGETVERSION . The value stored is of the following format:

LG:refs/heads/branches/your-branch:71f12206f54365098b2d11cbf08844e82b664594

Not sure what LG is, but the second part is the branch name, and the last part is the commit hash. It's pretty easy to parse this information:

<Target Name="ParseGitInfo">
  <PropertyGroup>
    <GitBranch>$(TF_BUILD_SOURCEGETVERSION.Split(':')[1])</GitBranch>
    <GitBranchName>$(GitBranch.Substring($([MSBuild]::Add($(GitBranch.LastIndexOf('/')), 1))))</GitBranchName>
  </PropertyGroup>  
</Target>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM