diff --git a/cmake/gen_version_h.cmake b/cmake/gen_version_h.cmake index d7749aa2670..9e1170d9304 100644 --- a/cmake/gen_version_h.cmake +++ b/cmake/gen_version_h.cmake @@ -2,6 +2,11 @@ cmake_minimum_required(VERSION 3.20.0) +set(ZEPHYR_BASE $ENV{ZEPHYR_BASE} CACHE PATH "Zephyr base") +set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${ZEPHYR_BASE}/cmake/modules) + +include(git) + if(VERSION_TYPE STREQUAL KERNEL) set(BUILD_VERSION_NAME BUILD_VERSION) else() @@ -10,23 +15,7 @@ endif() if(NOT DEFINED ${BUILD_VERSION_NAME}) cmake_path(GET VERSION_FILE PARENT_PATH work_dir) - find_package(Git QUIET) - if(GIT_FOUND) - execute_process( - COMMAND ${GIT_EXECUTABLE} describe --abbrev=12 --always - WORKING_DIRECTORY ${work_dir} - OUTPUT_VARIABLE ${BUILD_VERSION_NAME} - OUTPUT_STRIP_TRAILING_WHITESPACE - ERROR_STRIP_TRAILING_WHITESPACE - ERROR_VARIABLE stderr - RESULT_VARIABLE return_code - ) - if(return_code) - message(STATUS "git describe failed: ${stderr}") - elseif(NOT "${stderr}" STREQUAL "") - message(STATUS "git describe warned: ${stderr}") - endif() - endif() + git_describe(${work_dir} ${BUILD_VERSION_NAME}) endif() include(${ZEPHYR_BASE}/cmake/modules/version.cmake) diff --git a/cmake/modules/git.cmake b/cmake/modules/git.cmake new file mode 100644 index 00000000000..772fd7c669e --- /dev/null +++ b/cmake/modules/git.cmake @@ -0,0 +1,34 @@ +# SPDX-License-Identifier: Apache-2.0 + +include_guard(GLOBAL) + +find_package(Git QUIET) + +# Usage: +# git_describe( ) +# +# Helper function to get a short GIT desciption associated with a directory. +# OUTPUT is set to the output of `git describe --abbrev=12 --always` as run +# from DIR. +# +function(git_describe DIR OUTPUT) + if(GIT_FOUND) + execute_process( + COMMAND ${GIT_EXECUTABLE} describe --abbrev=12 --always + WORKING_DIRECTORY ${DIR} + OUTPUT_VARIABLE DESCRIPTION + OUTPUT_STRIP_TRAILING_WHITESPACE + ERROR_STRIP_TRAILING_WHITESPACE + ERROR_VARIABLE stderr + RESULT_VARIABLE return_code + ) + if(return_code) + message(STATUS "git describe failed: ${stderr}") + elseif(NOT "${stderr}" STREQUAL "") + message(STATUS "git describe warned: ${stderr}") + else() + # Save output + set(${OUTPUT} ${DESCRIPTION} PARENT_SCOPE) + endif() + endif() +endfunction()