I want to implement build id to about dialog of application that uses git. I know unix command to get a build id from git, but I have no idea how to grab it during build.
3 Answers
Probably easiest way to do it is to use pre-build events. Solution is to call git command, dump output to a text file, include that file as a resource and load resource in C# code.
Add prebuild.cmd to your project directory with the following content:
cd %1
git log -n 1 --format=format:"%%h" HEAD > %2
Go to your project properties, tab Build Events and enter following command as pre-build event command line:
"$(ProjectDir)prebuild.cmd" "$(ProjectDir)" "$(ProjectDir)revision.txt"
Create an empty revision.txt file in your project directory (or run a build once). Add it to your project and set Embedded Resource build action for it. It also makes sense to add this file to .gitignore because it is auto-generated.
In your C# project add a new utility class:
public static class GitRevisionProvider
{
public static string GetHash()
{
using(var stream = Assembly.GetExecutingAssembly()
.GetManifestResourceStream(
"DEFAULT_NAMESPACE" + "." + "revision.txt"))
using(var reader = new StreamReader(stream))
{
return reader.ReadLine();
}
}
}
Don't forget to replace DEFAULT_NAMESPACE with default namespace of your project (it is prepended to resource names and there is no generic way to get that, you'll have to hard-code it).
This solution assumes that path to git exists in %PATH% environment variable.
3 Comments
git describe --always --dirty --tags instead of git log...Based on max's answer here's an alternative solution that doesn't create a resource but directly creates the class file from the prebuild.cmd.
Add prebuild.cmd to your project directory with this content:
@echo off
cd %1
for /F "delims=" %%i in ('git describe --always --dirty --tags') do set git_revision=%%i
echo public static class Git> %2
echo {>> %2
echo public static string GetRevision()>> %2
echo {>> %2
echo return "%git_revision%";>> %2
echo }>> %2
echo }>> %2
Go to your project properties, tab Build Events and enter the following command as pre-build event command line:
"$(ProjectDir)prebuild.cmd" "$(ProjectDir)" "$(ProjectDir)Git.cs"
Create an empty Git.cs file in your project directory (or run a build once) and add (Existing Item...) it to your project. Also add Git.cs to .gitignore because it is auto-generated.