Getting git version information in your C# code

2/22/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.

git - useful aliases

In this article I'll show you some of my most used git aliases which make my everyday work easier and more productive.

How to hunt down bugs with git bisect

This article will show how you can identify the commit a bug was introduced.

Sometimes it is hard to track down a bug. Your only chance is to exploratory test your code until you find the code in question. I will show you a way how to do this with git. More specific how to use git bisect

C# Source Generators: How to get build information?

Source generators are a powerful feature introduced to C#, allowing developers to generate additional code during the compilation process automatically. They can help reduce boilerplate, improve performance, and simplify your codebase.

This blog post will introduce source generators, discuss how they work, and walk through an example of a source generator for generating build information.

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