• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# - Returns a version string from Git tags
2#
3# This function inspects the annotated git tags for the project and returns a string
4# into a CMake variable
5#
6#  get_git_version(<var>)
7#
8# - Example
9#
10# include(GetGitVersion)
11# get_git_version(GIT_VERSION)
12#
13# Requires CMake 2.8.11+
14find_package(Git)
15
16if(__get_git_version)
17  return()
18endif()
19set(__get_git_version INCLUDED)
20
21function(get_git_version var)
22  if(GIT_EXECUTABLE)
23      execute_process(COMMAND ${GIT_EXECUTABLE} describe --tags --match "v[0-9]*.[0-9]*.[0-9]*" --abbrev=8
24          WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}
25          RESULT_VARIABLE status
26          OUTPUT_VARIABLE GIT_DESCRIBE_VERSION
27          ERROR_QUIET)
28      if(status)
29          set(GIT_DESCRIBE_VERSION "v0.0.0")
30      endif()
31
32      string(STRIP ${GIT_DESCRIBE_VERSION} GIT_DESCRIBE_VERSION)
33      if(GIT_DESCRIBE_VERSION MATCHES v[^-]*-)
34         string(REGEX REPLACE "v([^-]*)-([0-9]+)-.*" "\\1.\\2"  GIT_VERSION ${GIT_DESCRIBE_VERSION})
35      else()
36         string(REGEX REPLACE "v(.*)" "\\1" GIT_VERSION ${GIT_DESCRIBE_VERSION})
37      endif()
38
39      # Work out if the repository is dirty
40      execute_process(COMMAND ${GIT_EXECUTABLE} update-index -q --refresh
41          WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}
42          OUTPUT_QUIET
43          ERROR_QUIET)
44      execute_process(COMMAND ${GIT_EXECUTABLE} diff-index --name-only HEAD --
45          WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}
46          OUTPUT_VARIABLE GIT_DIFF_INDEX
47          ERROR_QUIET)
48      string(COMPARE NOTEQUAL "${GIT_DIFF_INDEX}" "" GIT_DIRTY)
49      if (${GIT_DIRTY})
50          set(GIT_DESCRIBE_VERSION "${GIT_DESCRIBE_VERSION}-dirty")
51      endif()
52      message(STATUS "git version: ${GIT_DESCRIBE_VERSION} normalized to ${GIT_VERSION}")
53  else()
54      set(GIT_VERSION "0.0.0")
55  endif()
56
57  set(${var} ${GIT_VERSION} PARENT_SCOPE)
58endfunction()
59