Skip to content

Commit

Permalink
CMake: use git rev-parse to get GIT_COMMIT_HASH
Browse files Browse the repository at this point in the history
The old approach of reading .git/HEAD does not work when using git
worktrees, where the folder layout looks roughly like:

solvespace.git/                      - bare clone (.git dir)
solvespace.git/work                  - example worktree containing master
solvespage.git/worktrees/work/       - .git dir of worktree
solvespage.git/worktrees/work/HEAD   - actual HEAD ref for master

First attempt was to just get GIT_ROOT from `git rev-parse --git-dir` but
that wasn't enough, since:

1. GIT_ROOT points to solvespage.git/worktrees/work/
2. GIT_ROOT/HEAD points to refs/heads/master
3. GIT_ROOT/refs/heads/master does not exist but the old implementation
   would want to use this to get the sha

so we need two invocations of git rev-parse

1. `git rev-parse --git-dir` to get GIT_DIR
    needed for setting GIT_DEPENDS
2. `git rev-parse HEAD` to get the sha of the worktree's HEAD
  • Loading branch information
herrgahr authored and phkahler committed Jan 11, 2022
1 parent 5efc148 commit f1e47e6
Showing 1 changed file with 2 additions and 22 deletions.
24 changes: 2 additions & 22 deletions cmake/GetGitCommitHash.cmake
Original file line number Diff line number Diff line change
@@ -1,31 +1,11 @@
function(get_git_commit_hash)
get_filename_component(GIT_DESCRIBE_CMAKE_DIR ${CMAKE_CURRENT_LIST_FILE} PATH)
get_filename_component(GIT_ROOT ${GIT_DESCRIBE_CMAKE_DIR} PATH)
set(GIT_DIR "${GIT_ROOT}/.git")
execute_process(COMMAND git rev-parse --git-dir OUTPUT_VARIABLE GIT_DIR OUTPUT_STRIP_TRAILING_WHITESPACE)
execute_process(COMMAND git rev-parse HEAD OUTPUT_VARIABLE HEAD_REF OUTPUT_STRIP_TRAILING_WHITESPACE)

# Add a CMake configure dependency to the currently checked out revision.
set(GIT_DEPENDS ${GIT_DIR}/HEAD)
file(READ ${GIT_DIR}/HEAD HEAD_REF)
if(HEAD_REF MATCHES "ref: (.+)\n")
set(HEAD_REF ${CMAKE_MATCH_1})
if(EXISTS "${GIT_DIR}/${HEAD_REF}")
list(APPEND GIT_DEPENDS ${GIT_DIR}/${HEAD_REF})
file(READ ${GIT_DIR}/${HEAD_REF} HEAD_REF)
elseif(EXISTS "${GIT_DIR}/packed-refs")
list(APPEND GIT_DEPENDS ${GIT_DIR}/packed-refs)
file(READ "${GIT_DIR}/packed-refs" PACKED_REFS)
if(${PACKED_REFS} MATCHES "([0-9a-z]*) ${HEAD_REF}")
set(HEAD_REF ${CMAKE_MATCH_1})
else()
set(HEAD_REF "")
endif()
else()
set(HEAD_REF "")
endif()
endif()
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${GIT_DEPENDS})

string(STRIP ${HEAD_REF} HEAD_REF)
if(HEAD_REF STREQUAL "")
message(WARNING "Cannot determine git HEAD")
else()
Expand Down

0 comments on commit f1e47e6

Please sign in to comment.