Gareth Lennox

Simple version numbers with git

Each .net project has a version number (4 dotted numbers, e.g. 1.0.0.0). While you could leave it like that, it would ideally point back a unique revision in your source control system.

Unfortunately, they need to be a number, so you cannot dump the git hash in there and be done.

There are some projects that do this for you automatically (like MSBuild Versioning), but for small projects this is typically a bit overboard.

I usually just create a windows batch file, version.bat in the root of my projects, with the following content:

SET version=0
FOR /F "tokens=1" %%a IN ('git rev-list master') DO SET /A version+=1
FOR /F "tokens=*" %%a IN ('git rev-parse HEAD') DO SET commit=%%a
echo [assembly: System.Reflection.AssemblyVersion("1.0.%version%")] > src\AssemblyVersion.cs
echo [assembly: System.Reflection.AssemblyDescription("Compiled from %commit%")] >> src\AssemblyVersion.cs

This just gets a version number from git (basically the number of commits) and the current commit’s hash and pushes it into a AssemblyVersion.cs file that I include with my project.

Yes, using the number of commits as a version number has issues if you deploy code from different places (you will get different version numbers because of merges), but remember – this is for small projects that you’d deploy from one place and that you’d typically not have a build server.

I usually have a build.bat file that first calls the version.bat one, and then calls msbuild to build the solution.

If you have a mbuild file, you could just pass in the version number and commit hash as parameters (but then, rather use MSBuild Versioning linked above).

Comments are closed.