Stamping assemblies with some form of version number as part of a continuous integration build process is incredibly useful when trying to tie a binary back to it's source code commit. When using standard centralised source control systems this is a relatively simple process as each commit has an incremental change set number generated by the server and TeamCity exposes this as an internal variable %build.vcs.number%, but with distributed version control systems this is a little more complicated.
In our scenario we want to take the short hash of a git commit and stamp this onto the compiled assembly. Because the hash is likely to be alpahnumeric we need to make use of the AssemblyInformationalVersion attribute which can hold a string value - ideal for our hash.
Firstly though, we need to prepare the version string in a separate build configuration. This will use some PowerShell to set an internal parameter that we can then consume in dependent build configurations. The sole purpose of this step is to create the build number that has the hash appended to it.
Let's create a build configuration to generate the hash
We'll use some PowerShell to extract the short hash and set this to a variable inside of TeamCity, using the build script interaction syntax
$Hash = "%build.vcs.number%"
$ShortHash = $Hash.substring(0,7)
Write-Host "##teamcity[setParameter name='GitShortHash' value='$ShortHash']"
Now we need to add a parameter to this build configuration to store the hash that we are setting with our PowerShell script dynamically. Call this parameter GitShortHash so it matches our script.
In order to consume and use the version string we've created, we now need to create a second build configuration and add a dependency to the first one. This will not only ensure that a new version number is generated before we perform any continuous build operations, but we can also reach the value that has been generated.
Once we have created the snapshot dependency, we can then consume the parameter from the step that generates the new version string, using the TeamCity dependency syntax %dep.Git_GenerateBuildNumber.GitShortHash%. This will now enable us to use another built in feature of TeamCity, the AssemblyInfo patcher build feature and write to the correct field in the compiled assembly at the point of compilation.