How can I get the Git build number and embed it in a file?

Viewed 24640

I want to introduce a versioning constant grabbed from the version in Git. I know how to do this -- in a very hackish way in svn --

any ideas on how to do this with Git?

6 Answers

This is how I have done it. Note: Python code to get revision came from this post.

BuildInfo.hpp

#ifndef BUILDINFO_HPP_
#define BUILDINFO_HPP_

struct BuildInfo
{
    static const char Name[];
    static const char GitRevision[];
};

#endif

(Auto Generated) BuildInfo.cpp

#include "BuildInfo.hpp"

const char BuildInfo::Name[] = "MyAppNAme";
const char BuildInfo::GitRevision[] = "5e854351b342acff6a3481d9106076df379c449a";

GenerateBuildInfo.py. Python script to generate BuildInfo.cpp. Note that this could be easily adapted to get short or long revision numbers or other repository info. It could also be converted to generate C code rather than cpp so is compatible with both.

import sys
import os
import subprocess

#args: [0]: this script path [1]: Output file name [2]: Application name string

# Return the git revision as a string
def git_version():
    def _minimal_ext_cmd(cmd):
        # construct minimal environment
        env = {}
        for k in ['SYSTEMROOT', 'PATH']:
            v = os.environ.get(k)
            if v is not None:
                env[k] = v
        # LANGUAGE is used on win32
        env['LANGUAGE'] = 'C'
        env['LANG'] = 'C'
        env['LC_ALL'] = 'C'
        out = subprocess.Popen(cmd, stdout = subprocess.PIPE, env=env).communicate()[0]
        return out

    try:
        out = _minimal_ext_cmd(['git', 'rev-parse', 'HEAD'])
        GIT_REVISION = out.strip().decode('ascii')
    except OSError:
        GIT_REVISION = "Unknown"

    return GIT_REVISION

if len(sys.argv) < 2 :
    exit("No output file name argument provided")
elif len(sys.argv) >= 3 :
    name = sys.argv[2]
else :
    name = ""

revision = git_version()
if (revision == "Unknown") :
    exit("Cant get git revision")

with open(sys.argv[1], "w") as f :
    f.write('#include "BuildInfo.hpp"\r\n\r\n')
    f.write('const char BuildInfo::Name[] = "' + name + '";\r\n')
    f.write('const char BuildInfo::GitRevision[] = "' + revision + '";\r\n')
    f.close()

To use the build info

#include "BuildInfo.hpp"
...
PrintRevision(BuildInfo::GitRevision);

To generate BuildInfo.cpp, in a post build step I call (from eclipse IDE in this case)

python ${ProjDirPath}/build/GenerateBuildInfo.py ${ProjDirPath}/src/BuildInfo.cpp ${ProjName}
Related