Home > Net >  How can I get the GitVersion version into my binary?
How can I get the GitVersion version into my binary?

Time:11-20

I am using GitVersion to version my C#.NET application. My application also has a -V option, to show the current version of the binary.

How can I get data from GitVersion into my application, so that it is updated each time I build?

CodePudding user response:

I got it using a combination of a PowerShell script and a pre-build event:

The script is as follows (saved as gitversion.ps1 in the project dir:

$gitVersionJson = dotnet gitversion /output json
$By = [System.Text.Encoding]::Unicode.GetBytes($gitVersionJson)
$output =[Convert]::ToBase64String($By)

"using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;

class GitVersion {
    private static Dictionary<string, object> _values;
    private static Dictionary<string, object> Values {
        get {
            if (_values == null) {              
                byte[] data = Convert.FromBase64String(""$output"");
                string decodedString = Encoding.Unicode.GetString(data);
                _values = JsonSerializer.Deserialize<Dictionary<string, object>>(decodedString);
            }

            return _values;
        }
    }

    public static object MajorMinorPatch {
        get {
            return Values[""MajorMinorPatch""];
        }
    }

}
" | Out-File GitVersion.cs

"Generated GitVersion.cs" | Write-Output

Then in as a pre-build event, I added this in the Build settings:

powershell -ExecutionPolicy Bypass -NoProfile -NonInteractive -File "$(ProjectDir)gitversion.ps1" 

Or in myproject.csproj:

<Target Name="PreBuild" BeforeTargets="PreBuildEvent">
   <Exec Command="powershell -ExecutionPolicy Bypass -NoProfile -NonInteractive -File &quot;$(ProjectDir)gitversion.ps1&quot; " />
</Target>

This will create a GitVersion class, you can use in your code:

Console.WriteLine(GitVersion.MajorMinorPatch);
  • Related