@@ -32,3 +32,57 @@ function(git_describe DIR OUTPUT)
3232 endif ()
3333 endif ()
3434endfunction ()
35+
36+ # Usage:
37+ # git_commit_hash(<dir> <output>)
38+ #
39+ # Helper function to extract the full 160bit git commit hash associated with a directory.
40+ # output is set to the output of `git rev-parse --short=40 HEAD` as run from dir.
41+ #
42+ function (git_commit_hash dir output )
43+ if (GIT_FOUND)
44+ execute_process (
45+ COMMAND ${GIT_EXECUTABLE} rev-parse --short=40 HEAD
46+ WORKING_DIRECTORY ${dir}
47+ OUTPUT_VARIABLE commit_hash
48+ OUTPUT_STRIP_TRAILING_WHITESPACE
49+ ERROR_STRIP_TRAILING_WHITESPACE
50+ ERROR_VARIABLE stderr
51+ RESULT_VARIABLE return_code
52+ )
53+ if (return_code)
54+ message (WARNING "git rev-parse failed: ${stderr} " )
55+ elseif (NOT "${stderr} " STREQUAL "" )
56+ message (WARNING "git rev-parse warned: ${stderr} " )
57+ else ()
58+ # Save output
59+ set (${output} ${commit_hash} PARENT_SCOPE)
60+ endif ()
61+ endif ()
62+ endfunction ()
63+
64+ # Usage:
65+ # git_commit_hash_short(<full_hash> <short_hash> <short_hash_int>)
66+ #
67+ # Helper function to truncate a full GIT commit hash to a value that
68+ # fits in a uint32_t. short_hash_str is set to the first 8 characters of
69+ # full_hash_str, while short_hash_uint32 is the decimal value equivalent of
70+ # 0x${short_hash_str}
71+ #
72+ function (git_commit_hash_short full_hash_str short_hash_str short_hash_uint32)
73+ # Input validation
74+ string (LENGTH "${full_hash_str} " full_hash_str_len)
75+ if (full_hash_str_len LESS 8)
76+ message (FATAL_ERROR "Expected ${full_hash_str} to be at least 8 characters" )
77+ endif ()
78+ if (NOT "${full_hash_str} " MATCHES "^[0-9a-fA-F]+$" )
79+ message (FATAL_ERROR "Expected ${full_hash_str} to be hexadecimal string" )
80+ endif ()
81+ # Extract first 8 characters of hash
82+ string (SUBSTRING ${full_hash_str} 0 8 short_str)
83+ # Convert to a decimal value
84+ math (EXPR short_int "0x${short_str} " OUTPUT_FORMAT DECIMAL)
85+ # Save output
86+ set (${short_hash_str} ${short_str} PARENT_SCOPE)
87+ set (${short_hash_uint32} ${short_int} PARENT_SCOPE)
88+ endfunction ()
0 commit comments