skip to Main Content
En Attach Git Commit Into You Assenbly Header

Attach git commit SHA1 hash to your assembly

Let’s say you are one man-army, single developer who develops next-great-thing-on-desktop. You have only one client for whom you send each day latest build to test.

After sometime you started getting bug reports, and you want to easily tell which version was used, down to commit build.

You do not want to invest into complex build system, so you can use this small trick to include SHA1 hash from HEAD into your assembly.

Everything is done by Visual Studio.

First thing is T4 Text Transformation, small gem hidden in Visual Studio. It can be used to generate text or code while building.

(On Project) -> Add -> New Item -> General -> Text Template

And enter this code:

It searches where solution is placed, for .git folder, then it reads .git/HEAD file for current branch path. Lastly it gets HEAD from file which was specified in .git/HEAD.

For given SHA1 class is generated, which looks like this:

Note, couple things:

  • Generated file have extension .tt.cs, which should be added to .gitignore file.
  • Namespace should be changed in .tt file.

Class is generated only when .tt file is changed. This is default Visual Studio behavior! You can override this using Visual Studio extension Auto T4.

Usage

Usage of this class couldn’t be simpler.

For example you can attach that information to AssemblyInfo.cs by specifying attribute:

Thanks to that you can see that information by right-clicking on assembly then Properties->Details->Product Version.

assembly_detalis

Another way could be displaying that information in About section of your application.

  • Patryk Pękała

    Mam mokro od tych informacji,dziękuję serdecznie

  • Dobry pomysł, pamiętam kolega kiedyś zrobił coś podobnego na MSBuildzie ale było to strasznie nieczytelne. W Twoim rozwiązaniu użycie T4 dało o wiele bardziej czytelny kod. Mi trochę przeszkadza tutaj referencja do EnvDTE ale to jak komuś nie pasuje da radę łatwo obejść (https://stackoverflow.com/a/1352996/1779504), poza tym to podoba mi się to rozwiązanie.

Back To Top