Skip to content

Instantly share code, notes, and snippets.

@nathanchere
Created April 20, 2017 08:44
Show Gist options
  • Save nathanchere/cf4640d781588866742725fcc01b8344 to your computer and use it in GitHub Desktop.
Save nathanchere/cf4640d781588866742725fcc01b8344 to your computer and use it in GitHub Desktop.
Inject git info into your builds

Use this as a pre-build step, either as part of your TeamCity/TFS/etc process or by adding it to the pre-build step of your project, like the following example. Assuming you have the script saved in a directory build located in the same directory as your .sln file:

<Project> 
  <!-- usual other stuff here //-->
  <!-- ... //-->
  <PropertyGroup>
    <PreBuildEvent>powershell -ExecutionPolicy RemoteSigned -File  $(SolutionDir)build\gitinject.ps1 $(ProjectDir)</PreBuildEvent>
  </PropertyGroup>
</Project>
# gitinject.ps1
#
# Used by inject metadata about product version, branch and latest commit into AssemblyInfo.cs
#
# Assumes tag version convention is strictly adhered to as v[x].[y].[z] e.g. "v1.0.4"
$gitinfo = git describe --long --always;
$gitinfo -match 'v(\d+\.\d+\.\d+)-(\d+)-[g](\w+)$';
$gittag = $matches[1];
$gitcount = $matches[2];
$gitinfo = git describe --long --all;
$gitinfo -match '(.*)/(.*)-(\d+)-[g](\w+)$';
$gitsha1 = $matches[4];
$gitbranch = git rev-parse --abbrev-ref HEAD
$fileVersion = "[assembly: AssemblyFileVersion(`"$gittag.$gitcount`")]"
$infoVersion = "[assembly: AssemblyInformationalVersion(`"$gitbranch $gitsha1`")]"
$assemblyfile = "src\Exporthanteraren.Web\Properties\AssemblyInfo.cs";
$mainassemblycontent = get-content $assemblyfile |
Where { $_.Trim(" `t")} | # Clean up all the empty lines while we're at it
%{$_ -replace '\[assembly\: AssemblyFileVersion(.*)]', $fileVersion } |
%{$_ -replace '\[assembly\: AssemblyInformationalVersion(.*)]', $infoVersion } ;
echo "injecting git version info to AssemblyInfo.cs"
$mainassemblycontent > $assemblyfile;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment