[SOLVED] Extract git commit hash with cmd.exe

I’m trying to use the Projucer “Post Export Shell Command” to write the current git hash to a file in the form:

#define GIT_COMMIT_ID "3c5f09ab"

In bash no problemo, but cmd.exe is giving me headaches. I managed to execute it in PowerShell, but the Projucer seems to be using cmd.exe only. The PowerShell command would be

"#define GIT_COMMIT_ID `"$(git --git-dir %%1%%\.git rev-parse --short HEAD)`"" > %%1%%\Source\GitCommitId.h

but in cmd I’ve only managed to output the hash itself, like so:

git --git-dir %%1%%\.git rev-parse --short HEAD > %%1%%\Source\GitCommitId.h

which doesn’t help either, because I still need to prepend the #define GIT_COMMIT_ID . Any cmd wizards out here who know how to achieve this?

You can call powershell from cmd:

powershell.exe "Write-Host 'Hello, World!'"

Ok, but then I’m running into big troubles with escape characters. My original powershell command had an quote-escape in it, which I would need to double escape in this case. Even when ommiting that (I can fix it in C++ by writing a hex instead of a string), I’m running into troubles. This command does what I want when executed in the shell itself

powershell.exe "Write-Host \"#define GIT_COMMIT_ID 0x$(git --git-dir %%1%%\.git rev-parse --short HEAD)\"" > %%1%%\Source\GitCommitId.h
#define GIT_COMMIT_ID 0x35fa794a

but writes garbage when being executed from the Projucer.

Write-Host \#define GIT_COMMIT_ID 0x\

I think there is another layer of quotes being inserted or escapes are interpreted differently.

Probably the cleaner solution would be to concat the strings somehow in the original cmd command instead of invoking powershell in the first place.

You could try using the -command argument with powershell which doesn’t require the command to be wrapped in quotes:

>powershell.exe -command Write-Host "Hello, World!"

Or you could save the command to a file (.ps1) and execute it from the cmd:

>powershell.exe "& "./script.ps1""
1 Like

Ayyy, got it working, thank you very much! The final command is

powershell.exe -command "#define GIT_COMMIT_ID `"$(git --git-dir %%1%%\.git rev-parse --short HEAD)`"" > %%1%%\Source\GitCommitId.h

EDIT: This one even works with the escaped quotes, adjusted the command to define a string again.

1 Like

Awesome, happy to help :slight_smile:

1 Like

I’m curious about the use case for this?

I want to display the commit hash along with the version inside the “about” section of my plugin. Therefore I need to somehow incorporate it into code. The reason I want to do this is so testers can report which exact commit they’re on, in case they’re using a nightly build.

3 Likes