# This file exposes create_version_source(), a method that generates a file at
# BUILD TIME containing the version information as obtained from Git.
#
# Usage:
#
#   create_version_source(<FILENAME>
#       NAMESPACE <NAMESPACE>
#   )
#
# This will create a C++ source file named FILENAME which exposes a method with
# the following signature:
#
#   const ::khepri::VersionInfo& version() noexcept;
#
# The reference is to an object with global lifetime. If NAMESPACE is provided,
# the method is  placed in that fully-qualified namespace (e.g. "Foo::Bar").
#
# The version information is obtained from the latest git tag that is reachable
# from HEAD (e.g. the first part of `git describe --tags`). Git tags should be
# named according to SemVer e.g. "v1.2.12-whatever", where the "v" is optional,
# and everything after the patch version is ignored. If the minor or patch version
# is missing, 0 is assumed.
#
# A version is "clean" if the tag points exactly at HEAD and the workspace is clean.
# If there are additional commits on top of the tag or the workspace has unstaged or
# uncommitted changes, the version is considered "dirty".
#
# The build commit contains the current commit ID (from `git rev-parse HEAD`).
#
find_package(Git REQUIRED)

set(VERSION_CPP_IN "${CMAKE_CURRENT_LIST_DIR}/GitVersion/version.cpp.in")
set(VERSION_SCRIPT "${CMAKE_CURRENT_LIST_DIR}/GitVersion/version.cmake")
set(GIT_REPO_PATH "${CMAKE_CURRENT_SOURCE_DIR}")

function(create_version_source FILENAME)
    cmake_parse_arguments(VERSION "" "NAMESPACE" "" ${ARGN})
    add_custom_command(
        OUTPUT ${FILENAME}
        COMMAND ${CMAKE_COMMAND} -D SRC=${VERSION_CPP_IN}
                                 -D DST=${FILENAME}
                                 -D GIT_EXECUTABLE=${GIT_EXECUTABLE}
                                 -D REPO=${GIT_REPO_PATH}
                                 -D NAMESPACE=${VERSION_NAMESPACE}
                                 -P ${VERSION_SCRIPT}
        DEPENDS ${VERSION_CPP_IN}
        COMMENT "Creating version source"
    )
endfunction()