Getting git version information in your C# code

22/02/2023

Did you ever need git-specific information like the latest tag or the current commit inside your C# code? Or even the semantic version number of your current build=

Well, there is an easy solution involving source generators.

Meet GitInfo

From the official GitHub Page:

A fresh and transparent approach to Git information retrieval from MSBuild and Code without using any custom tasks or compiled code and tools, obscure settings, format strings, etc.

The package uses source generators under the hood to create compile-time constant strings with your git information. All of your information are baked into ThisAssembly.Git object:

Console.WriteLine($"Last commit: {ThisAssembly.Git.Commit}");

Which prints in my case: Last commit: 91b050b - also it shows that information when you hover over the property in your code editor of choice:

Tooltip

The reason that works is, that it uses source generators that create this information when you build your project. Well, even when your project gets analyzed, the source generators are invoked. Of course, this will affect your build time a bit (we are not speaking seconds here, but also not nanoseconds). But that also means we don't have to ship the GitInfo assembly to the client at all - as it is a developer dependency. Every string it creates gets baked into the calling assembly.

You can also get the latest tag:

Console.WriteLine($"Latest tag: {ThisAssembly.Git.Tag}");

Or the current semantic version:

Console.WriteLine($"Version: {ThisAssembly.Git.SemVer.Label}");

The library derives the information from your latest tag, default branch and where your current branch was sourced from - like gitversion on the cli.

Conclusion

GitInfo is a very convenient way to show and retrieve git-related information inside your project.

0
An error has occurred. This application may no longer respond until reloaded. Reload x