From: Shuanglei Tao Date: Fri, 29 Mar 2024 00:58:02 +0000 (+0800) Subject: cmake: get version from git ref X-Git-Url: http://git.prime8.dev/?a=commitdiff_plain;h=e5fd3f60e5d5cf28190d288bc13e0117d69ff493;p=ttyd.git cmake: get version from git ref --- diff --git a/CMakeLists.txt b/CMakeLists.txt index dc71802..0bf19bc 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,28 +1,16 @@ -cmake_minimum_required(VERSION 2.8.12) - -if(${CMAKE_VERSION} VERSION_LESS "3.12.0") - project(ttyd C) - set(PROJECT_VERSION_MAJOR "1") - set(PROJECT_VERSION_MINOR "7") - set(PROJECT_VERSION_PATCH "4") - set(PROJECT_VERSION "${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH}") -else() - cmake_policy(SET CMP0048 NEW) - project(ttyd VERSION 1.7.4 LANGUAGES C) -endif() +cmake_minimum_required(VERSION 3.12.0) -find_package(Git) -if(GIT_FOUND) - execute_process( - COMMAND ${GIT_EXECUTABLE} --git-dir ${CMAKE_CURRENT_SOURCE_DIR}/.git rev-parse --short HEAD - RESULT_VARIABLE GIT_RET - OUTPUT_VARIABLE GIT_COMMIT - OUTPUT_STRIP_TRAILING_WHITESPACE - ERROR_QUIET - ) - if("${GIT_RET}" STREQUAL "0") - set(PROJECT_VERSION "${PROJECT_VERSION}-${GIT_COMMIT}") - endif() +list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake") + +include(GetGitVersion) + +get_git_version(GIT_VERSION SEM_VER) +get_git_head(GIT_COMMIT) + +project(ttyd VERSION "${SEM_VER}" LANGUAGES C) + +if(NOT "{GIT_COMMIT}" STREQUAL "") + set(PROJECT_VERSION "${PROJECT_VERSION}-${GIT_COMMIT}") endif() set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -D_GNU_SOURCE") diff --git a/cmake/GetGitVersion.cmake b/cmake/GetGitVersion.cmake new file mode 100644 index 0000000..6c8f6c8 --- /dev/null +++ b/cmake/GetGitVersion.cmake @@ -0,0 +1,47 @@ +find_package(Git) + +function(get_git_version var1 var2) + if(GIT_EXECUTABLE) + execute_process( + COMMAND ${GIT_EXECUTABLE} describe --tags --match "[0-9]*.[0-9]*.[0-9]*" --abbrev=8 + WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} + RESULT_VARIABLE status + OUTPUT_VARIABLE GIT_VERSION + ) + if (${status}) + set(GIT_VERSION "0.0.0") + else() + string(STRIP ${GIT_VERSION} GIT_VERSION) + string(REGEX REPLACE "-[0-9]+-g" "-" GIT_VERSION ${GIT_VERSION}) + endif() + else() + set(GIT_VERSION "0.0.0") + endif() + + string(REGEX MATCH "^[0-9]+.[0-9]+.[0-9]+" SEM_VER "${GIT_VERSION}") + + message("-- Git Tag: ${GIT_VERSION}, Sem Ver: ${SEM_VER}") + + set(${var1} ${GIT_VERSION} PARENT_SCOPE) + set(${var2} ${SEM_VER} PARENT_SCOPE) +endfunction() + +function(get_git_head var1) + if(GIT_EXECUTABLE) + execute_process( + COMMAND ${GIT_EXECUTABLE} --git-dir ${CMAKE_CURRENT_SOURCE_DIR}/.git rev-parse --short HEAD + RESULT_VARIABLE status + OUTPUT_VARIABLE GIT_COMMIT + OUTPUT_STRIP_TRAILING_WHITESPACE + ERROR_QUIET + ) + + if(${status}) + set(GIT_COMMIT "unknown") + endif() + + message("-- Git Commit: ${GIT_COMMIT}") + + set(${var1} ${GIT_COMMIT} PARENT_SCOPE) + endif() +endfunction()