I agree with the comments that in this case it may be easier to solve your underlying problem than to answer your question directly. Here's how I get branch/version information from git and put it into my programs:
I use this method on a code-base which supports Windows and several linux variants.
Create a CMake macro to extract information from git:
# Get the current Git commit hash
macro(git_information BRANCH_VAR COMMIT_VAR COMMIT_VAR_SHORT)
# Get the branch name
execute_process(
COMMAND git rev-parse --abbrev-ref HEAD
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
OUTPUT_VARIABLE ${BRANCH_VAR}
OUTPUT_STRIP_TRAILING_WHITESPACE
)
MESSAGE(STATUS "GIT: Current branch -> ${${BRANCH_VAR}}")
# Retrigger configuration process each time config file changes
get_filename_component(_cfg_name "${CMAKE_SOURCE_DIR}/.git/refs/heads/${BRANCH}" NAME)
configure_file("${CMAKE_SOURCE_DIR}/.git/refs/heads/${BRANCH}" "${_cfg_name}.tmp")
set_source_files_properties(${_cfg_name}.tmp PROPERTIES GENERATED true)
# Get the head commit
execute_process(
COMMAND git rev-parse HEAD
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
OUTPUT_VARIABLE ${COMMIT_VAR}
OUTPUT_STRIP_TRAILING_WHITESPACE
)
MESSAGE(STATUS "GIT: Current commit -> ${${COMMIT_VAR}}")
# Get the short version of the head commit
execute_process(
COMMAND git rev-parse --short HEAD
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
OUTPUT_VARIABLE ${COMMIT_VAR_SHORT}
OUTPUT_STRIP_TRAILING_WHITESPACE
)
endmacro()
Then call the macro like so in your top-level CMakeLists.txt
:
find_package(Git)
if(GIT_FOUND)
git_information(BRANCH GIT_COMMIT GIT_COMMIT_SHORT)
ELSE()
# as a fallback, use the directory name as the branch name
GET_FILENAME_COMPONENT(BRANCH ${CMAKE_CURRENT_SOURCE_DIR} NAME)
ENDIF()
To actually get the information into the program, I use configure_file
(see the documentation if you're not familiar):
configure_file(include/version.h.in version.h @ONLY NEWLINE_STYLE LF)
and that file looks something like this:
#include <string>
namespace myProg
{
static const std::string BRANCH("@BRANCH@");
static const std::string GIT_COMMIT("@GIT_COMMIT@");
static const std::string GIT_COMMIT_SHORT("@GIT_COMMIT_SHORT@");
}
You can imagine that the macro could be used to pull tag or descriptive information from git as well, by adding additional execute_process
blocks with the appropriate git commands.