How to implement git id or build to c # application

I want to implement the build id before the application dialog using git. I know a unix command to get the build id from git, but I have no idea how to grab it during build.

+3


source to share


3 answers


Probably the easiest way to do this is using pre-build events. The solution is to call the command git

, dump the dump to a text file, include that file as a resource, and load the resource into 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 the following command at the command prompt:

"$(ProjectDir)prebuild.cmd" "$(ProjectDir)" "$(ProjectDir)revision.txt"

      



Create an empty file revision.txt

in your project directory (or run the 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 automatically 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();
        }
    }
}

      

Remember to replace DEFAULT_NAMESPACE

with your project's default namespace (it is appended to the resource names and there is no general way to get it, you will have to hard-code it).

This solution assumes that the path to git

exists in an environment variable %PATH%

.

+6


source


if you are using Nant you need to do a set of tasks to get the git id



after that you can execute regex and get id and set to property.

0


source


Based on max's answer here's an alternative solution that doesn't create a resource, but directly creates a class file from prebuild.cmd

.

Add prebuild.cmd

to the 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 the project properties tab Build Events

and enter the following command at the command prompt:

"$(ProjectDir)prebuild.cmd" "$(ProjectDir)" "$(ProjectDir)Git.cs"

      

Create an empty file Git.cs

in your project directory (or run the build once) and add (Existing Item ...) to your project. Also add Git.cs

in .gitignore

because it autogenerates.

0


source







All Articles