I know this question is old, but I just came across it because I'm trying to do the same thing. The one other answer here shows how to create a new Git tag every time a version file changes, but I and the OP want to do the reverse: Update a code file to contain a new version number every time I create a new Git tag for a "release." Here's how I did it in my C++ project:
First, create a header file called, for example, include/myproj/git_version.hpp
that defines some constants:
#pragma once
namespace myproject {
extern const int MAJOR_VERSION;
extern const int MINOR_VERSION;
extern const int PATCH_VERSION;
extern const int COMMITS_AHEAD_OF_VERSION;
extern const char* VERSION_STRING;
extern const char* VERSION_STRING_PLUS_COMMITS;
}
Second, create a pre-commit hook (.git/hooks/pre-commit
) that generates the corresponding .cpp file defining the constants, using the output of git describe
:
#!/bin/bash
version_regex='v([0-9]+)\.([0-9]+)\.?([0-9]*)-([0-9]+)-g([0-9|a-z]+)'
git_string=$(git describe --tags --long)
if [[ $git_string =~ $version_regex ]]; then
major_version="${BASH_REMATCH[1]}"
minor_version="${BASH_REMATCH[2]}"
patch_version="${BASH_REMATCH[3]}"
commits_ahead="${BASH_REMATCH[4]}"
else
echo "Error: git describe did not output a valid version string. Unable to update git_version.cpp" >&2
exit 1
fi
version_num="${major_version}.${minor_version}.${patch_version}"
version_num_plus_commits="${version_num}+${commits_ahead}"
# Working directory of a git hook is always the root of the repo
cat > $(pwd)/src/git_version.cpp <<EOM
#include <myproject/git_version.hpp>
namespace myproject {
const int MAJOR_VERSION = $major_version;
const int MINOR_VERSION = $minor_version;
const int PATCH_VERSION = $patch_version;
const int COMMITS_AHEAD_OF_VERSION = $commits_ahead;
const char* VERSION_STRING = "${version_num}";
const char* VERSION_STRING_PLUS_COMMITS = "${version_num_plus_commits}";
}
EOM
git add $(pwd)/src/git_version.cpp
Note that the updated version of the git_constants.cpp file will be included as part of the commit, so any commit based on a new tag will also include a constants file reflecting the version in that tag.
This isn't perfect, because it requires you to create a new commit to update the constants file even if all you want to do is create a new tag (which otherwise wouldn't require a new commit). On the other hand, it does allow your in-code version number to track the number of commits, which is more fine-grained than the tagged versions alone.