Issue
I’m building a C# application, using Git as my version control.
Is there a way to automatically embed the last commit hash in the executable when I build my application?
For example, printing the commit hash to console would look something like:
class PrintCommitHash
{
private String lastCommitHash = ?? // What do I put here?
static void Main(string[] args)
{
// Display the version number:
System.Console.WriteLine(lastCommitHash );
}
}
Note that this has to be done at build time, not runtime, as my deployed executable will not have the git repo accessible.
A related question for C++ can be found here.
EDIT
Per @mattanja’s request, I’m posting the git hook script I use in my projects. The setup:
- The hooks are linux shell scripts, which are placed under: path_to_project\.git\hooks
- If you are using msysgit, the hooks folder already contains some sample scripts. In order to make git call them, remove the ‘.sample’ extension from the script name.
- The names of the hook scripts match the event that invokes them. In my case, I modified post-commit and post-merge.
- My AssemblyInfo.cs file is directly under the project path (same level as the .git folder). It contains 23 lines, and I use git to generate the 24th.
As my linux-shelling a bit rusty, the script simply reads the first 23-lines of AssemblyInfo.cs to a temporary file, echos the git hash to the last line, and renames the file back to AssemblyInfo.cs. I’m sure there are better ways of doing this:
#!/bin/sh
cmt=$(git rev-list --max-count=1 HEAD)
head -23 AssemblyInfo.cs > AssemblyInfo.cs.tmp
echo [assembly: AssemblyFileVersion\(\"$cmt\"\)] >> AssemblyInfo.cs.tmp
mv AssemblyInfo.cs.tmp AssemblyInfo.cs
Hope this helps.
Solution
We use tags in git to track versions.
git tag -a v13.3.1 -m "version 13.3.1"
You can get the version with hash from git via:
git describe --long
Our build process puts the git hash in the AssemblyInformationalVersion attribute of the AssemblyInfo.cs file:
[assembly: AssemblyInformationalVersion("13.3.1.74-g5224f3b")]
Once you compile, you can view the version from windows explorer:
You can also get it programmatically via:
var build = ((AssemblyInformationalVersionAttribute)Assembly
.GetAssembly(typeof(YOURTYPE))
.GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false)[0])
.InformationalVersion;
where YOURTYPE is any Type in the Assembly that has the AssemblyInformationalVersion attribute.
Answered By – Handcraftsman
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0