diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..16173e8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +/build* +/cpm_modules +.DS_Store +.cache* diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..c6ede2c --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,90 @@ +cmake_minimum_required(VERSION 3.14 FATAL_ERROR) + +# Standalone configuration of the spdlog logger from a JSON file. +project( + SPDLOGConfig + VERSION 1.0.0 + LANGUAGES CXX +) + +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin") +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib") +set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib") + +if(PROJECT_SOURCE_DIR STREQUAL PROJECT_BINARY_DIR) + message( + FATAL_ERROR + "In-source builds not allowed. Please make a new directory (called a build directory) and run CMake from there." + ) +endif() + +# ---- Dependencies via CPM ---- +set(CPM_SOURCE_CACHE "${PROJECT_SOURCE_DIR}/../.cache-CPM-packages") +include(cmake/CPM.cmake) + +CPMAddPackage("gh:TheLartians/PackageProject.cmake@1.13.0") + +# ---- spdlog (shared, std::format backend like the main project) ---- +CPMAddPackage( + NAME spdlog + GITHUB_REPOSITORY gabime/spdlog + GIT_TAG "v1.17.0" + OPTIONS + "SPDLOG_BUILD_EXAMPLE OFF" + "SPDLOG_BUILD_SHARED ON" + "SPDLOG_USE_STD_FORMAT ON" + "SPDLOG_INSTALL ON" +) + +# ---- reflect-cpp (JSON deserialization of the config file) ---- +CPMAddPackage( + NAME reflectcpp + GITHUB_REPOSITORY getml/reflect-cpp + GIT_TAG "v0.24.0" + OPTIONS + "REFLECTCPP_BUILD_SHARED ON" + "CMAKE_POSITION_INDEPENDENT_CODE ON" + "REFLECTCPP_INSTALL ON" +) + +add_library(${PROJECT_NAME} INTERFACE) +add_library(${PROJECT_NAME}::${PROJECT_NAME} ALIAS ${PROJECT_NAME}) + +target_compile_features(${PROJECT_NAME} INTERFACE cxx_std_20) + +target_link_libraries(${PROJECT_NAME} INTERFACE spdlog::spdlog reflectcpp::reflectcpp) + +target_include_directories( + ${PROJECT_NAME} + INTERFACE + $ + $ +) + +# ---- Tests (only when top-level and not disabled by consumers) ---- +option(SPDLOGCONFIG_BUILD_TESTS "Build SPDLOGConfig's own test suite" ON) +if(PROJECT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR AND SPDLOGCONFIG_BUILD_TESTS) + enable_testing() + add_subdirectory(test) +endif() + +# ---- Installable / CPM-compatible package ---- +install(TARGETS ${PROJECT_NAME} + INCLUDES DESTINATION include/${PROJECT_NAME}-${PROJECT_VERSION} +) + +packageProject( + NAME ${PROJECT_NAME} + VERSION ${PROJECT_VERSION} + NAMESPACE ${PROJECT_NAME} + BINARY_DIR ${PROJECT_BINARY_DIR} + INCLUDE_DIR ${PROJECT_SOURCE_DIR}/include + INCLUDE_DESTINATION include/${PROJECT_NAME}-${PROJECT_VERSION} + VERSION_HEADER "" + COMPATIBILITY SameMajorVersion + DEPENDENCIES "spdlog 1.17.0;reflectcpp 0.24.0" +) diff --git a/CMakePresets.json b/CMakePresets.json new file mode 100644 index 0000000..d28f997 --- /dev/null +++ b/CMakePresets.json @@ -0,0 +1,85 @@ +{ + "version": 3, + "cmakeMinimumRequired": { + "major": 3, + "minor": 21, + "patch": 0 + }, + "configurePresets": [ + { + "name": "linux-clang-21-debug", + "displayName": "Linux Clang 21 Debug", + "description": "Debug build on Linux using Clang 21", + "generator": "Unix Makefiles", + "binaryDir": "${sourceDir}/../build/spdlogConfig-linux-clang-21-debug", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Debug", + "CMAKE_EXPORT_COMPILE_COMMANDS": "ON", + "CMAKE_TOOLCHAIN_FILE": "${sourceDir}/../cmake-toolchain-files/clang_21_x86_64-pc-linux-gnu.cmake" + } + }, + { + "name": "linux-clang-21-release", + "displayName": "Linux Clang 21 Release", + "description": "Release build on Linux using Clang 21", + "generator": "Unix Makefiles", + "binaryDir": "${sourceDir}/../build/spdlogConfig-linux-clang-21-release", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Release", + "CMAKE_EXPORT_COMPILE_COMMANDS": "ON", + "CMAKE_TOOLCHAIN_FILE": "${sourceDir}/../cmake-toolchain-files/clang_21_x86_64-pc-linux-gnu.cmake" + } + }, + { + "name": "linux-clang-21-debug-asan", + "displayName": "Linux Clang 21 Debug (ASan)", + "description": "Debug build with AddressSanitizer on Linux using Clang 21", + "generator": "Unix Makefiles", + "binaryDir": "${sourceDir}/../build/spdlogConfig-linux-clang-21-debug-asan", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Debug", + "CMAKE_EXPORT_COMPILE_COMMANDS": "ON", + "CMAKE_TOOLCHAIN_FILE": "${sourceDir}/../cmake-toolchain-files/clang_21_x86_64-pc-linux-gnu.cmake", + "USE_SANITIZER": "Address" + } + } + ], + "buildPresets": [ + { + "name": "linux-clang-21-debug", + "displayName": "Build Linux Clang 21 Debug", + "configurePreset": "linux-clang-21-debug", + "jobs": 8 + }, + { + "name": "linux-clang-21-release", + "displayName": "Build Linux Clang 21 Release", + "configurePreset": "linux-clang-21-release", + "jobs": 8 + }, + { + "name": "linux-clang-21-debug-asan", + "displayName": "Build Linux Clang 21 Debug (ASan)", + "configurePreset": "linux-clang-21-debug-asan", + "jobs": 8 + } + ], + "testPresets": [ + { + "name": "linux-clang-21-debug", + "displayName": "Run Linux Clang 21 Debug tests", + "configurePreset": "linux-clang-21-debug", + "output": { + "outputOnFailure": true + } + }, + { + "name": "linux-clang-21-release", + "displayName": "Run Linux Clang 21 Release tests", + "configurePreset": "linux-clang-21-release", + "output": { + "outputOnFailure": true + } + } + ] +} diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..fdddb29 --- /dev/null +++ b/LICENSE @@ -0,0 +1,24 @@ +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + +For more information, please refer to diff --git a/README.md b/README.md index e69de29..4470d14 100644 --- a/README.md +++ b/README.md @@ -0,0 +1,91 @@ +# SPDLOGConfig + +Eigenständiges, header-only CMake-Projekt zur Konfiguration von [spdlog](https://github.com/gabime/spdlog) +aus einer JSON-Datei. Es ist die aus [RelixTransferAI](../README.md) extrahierte Logging-Konfiguration +(Namespace `spdlogconfig`) und wird dort sowie in anderen Projekten +über [CPM.cmake](https://github.com/cpm-cmake/CPM.cmake) eingebunden. + +## Features + +- Komplette Logger-Definition über eine JSON-Datei: globale und logger-spezifische Patterns, + Level, Sinks, async Logger (globaler und lokaler Thread-Pool, Overflow-Policies). +- Sinks: `console_st/mt`, `color_console_st/mt`, `basic_file_st/mt`, `daily_file_st/mt`, + `rotating_file_st/mt`, `null_sink_st/mt`, `syslog_st/mt` (POSIX), `msvc_sink_st/mt` (Windows), + optional `kafka_*`/`mongo_*` falls `librdkafka`/`mongocxx` im Include-Pfad liegen. +- Reload-Unterstützung: Level zur Laufzeit ändern, ohne Neustart (`setupFromReload()`). +- `LevelManager` als Singleton zur Laufzeit-Verwaltung einzelner Logger-Level. +- Installierbare CMake-Package (`find_package(SPDLOGConfig)`), CPM- und FetchContent-tauglich. + +## Verwendung + +### Einbindung über CPM + +```cmake +include(cmake/CPM.cmake) + +CPMAddPackage( + NAME SPDLOGConfig + GITHUB_REPOSITORY /SPDLOGConfig + GIT_TAG v1.0.0 +) + +target_link_libraries(myTarget PRIVATE SPDLOGConfig::SPDLOGConfig) +``` + +Lokal entwickeltes Checkout statt GitHub-Release (Source-Override vor dem `CPMAddPackage`-Aufruf): + +```cmake +set(CPM_SPDLOGConfig_SOURCE "${CMAKE_CURRENT_SOURCE_DIR}/../spdlogConfig") +``` + +### Verwendung im Code + +```cpp +#include + +int main() { + spdlogconfig::setupFrom("config/logging.json"); + // spdlogconfig::setupFromReload(); // später: Konfiguration neu einlesen + + auto logger = spdlog::get("root"); + logger->info("hello from SPDLOGConfig"); + + // Laufzeit-Level-Verwaltung: + spdlogconfig::LevelManager::instance().setLoggerLevel("root", "debug"); +} +``` + +Fehler beim Öffnen/Parsen der Konfiguration werden von `setupFrom()` aktuell +**intern behandelt** (Ausgabe auf stdout/stderr, keine Propagation) — das ist +Legacy-Verhalten aus der ursprünglichen RelixTransfer-Headerdatei. Der Typ +`spdlogconfig::spdlogconfig_error` existiert trotzdem und wird intern für +teilweise Fehlerkontexte verwendet; auf Propagation sollte sich in neuen +Programmen nicht verlassen werden. + +## Konfigurationsformat + +Ein vollständiges Beispiel liegt unter [`test/full.json`](test/full.json). Das Schema +(`spdlog_conf_t`) wird mit [reflect-cpp](https://github.com/getml/reflect-cpp) deserialisiert; +unbekannte Felder, fehlende optionale Felder und Default-Werte werden vom Framework behandelt. + +## Abhängigkeiten + +| Paket | Version | Zweck | +|----------------|---------|------------------------------| +| spdlog | 1.17.0 | Logging (std::format-Modus) | +| reflect-cpp | 0.24.0 | JSON-Deserialisierung | +| doctest | 2.5.2 | Tests (nur test/) | + +## Bauen und Testen + +Voraussetzung: CMake ≥ 3.21, Clang 20/21 (oder MSVC/MSYS2-Clang), Ninja oder Make. + +```sh +cmake --preset linux-clang-21-release +cmake --build --preset linux-clang-21-release +ctest --preset linux-clang-21-release +``` + +## Lizenz + +Public Domain (Unlicense) — siehe [LICENSE](LICENSE). diff --git a/cmake/CPM.cmake b/cmake/CPM.cmake new file mode 100644 index 0000000..3636ee5 --- /dev/null +++ b/cmake/CPM.cmake @@ -0,0 +1,1363 @@ +# CPM.cmake - CMake's missing package manager +# =========================================== +# See https://github.com/cpm-cmake/CPM.cmake for usage and update instructions. +# +# MIT License +# ----------- +#[[ + Copyright (c) 2019-2023 Lars Melchior and contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +]] + +cmake_minimum_required(VERSION 3.14 FATAL_ERROR) + +# Initialize logging prefix +if(NOT CPM_INDENT) + set(CPM_INDENT + "CPM:" + CACHE INTERNAL "" + ) +endif() + +if(NOT COMMAND cpm_message) + function(cpm_message) + message(${ARGV}) + endfunction() +endif() + +if(DEFINED EXTRACTED_CPM_VERSION) + set(CURRENT_CPM_VERSION "${EXTRACTED_CPM_VERSION}${CPM_DEVELOPMENT}") +else() + set(CURRENT_CPM_VERSION 0.42.0) +endif() + +get_filename_component(CPM_CURRENT_DIRECTORY "${CMAKE_CURRENT_LIST_DIR}" REALPATH) +if(CPM_DIRECTORY) + if(NOT CPM_DIRECTORY STREQUAL CPM_CURRENT_DIRECTORY) + if(CPM_VERSION VERSION_LESS CURRENT_CPM_VERSION) + message( + AUTHOR_WARNING + "${CPM_INDENT} \ +A dependency is using a more recent CPM version (${CURRENT_CPM_VERSION}) than the current project (${CPM_VERSION}). \ +It is recommended to upgrade CPM to the most recent version. \ +See https://github.com/cpm-cmake/CPM.cmake for more information." + ) + endif() + if(${CMAKE_VERSION} VERSION_LESS "3.17.0") + include(FetchContent) + endif() + return() + endif() + + get_property( + CPM_INITIALIZED GLOBAL "" + PROPERTY CPM_INITIALIZED + SET + ) + if(CPM_INITIALIZED) + return() + endif() +endif() + +if(CURRENT_CPM_VERSION MATCHES "development-version") + message( + WARNING "${CPM_INDENT} Your project is using an unstable development version of CPM.cmake. \ +Please update to a recent release if possible. \ +See https://github.com/cpm-cmake/CPM.cmake for details." + ) +endif() + +set_property(GLOBAL PROPERTY CPM_INITIALIZED true) + +macro(cpm_set_policies) + # the policy allows us to change options without caching + cmake_policy(SET CMP0077 NEW) + set(CMAKE_POLICY_DEFAULT_CMP0077 NEW) + + # the policy allows us to change set(CACHE) without caching + if(POLICY CMP0126) + cmake_policy(SET CMP0126 NEW) + set(CMAKE_POLICY_DEFAULT_CMP0126 NEW) + endif() + + # The policy uses the download time for timestamp, instead of the timestamp in the archive. This + # allows for proper rebuilds when a projects url changes + if(POLICY CMP0135) + cmake_policy(SET CMP0135 NEW) + set(CMAKE_POLICY_DEFAULT_CMP0135 NEW) + endif() + + # treat relative git repository paths as being relative to the parent project's remote + if(POLICY CMP0150) + cmake_policy(SET CMP0150 NEW) + set(CMAKE_POLICY_DEFAULT_CMP0150 NEW) + endif() +endmacro() +cpm_set_policies() + +option(CPM_USE_LOCAL_PACKAGES "Always try to use `find_package` to get dependencies" + $ENV{CPM_USE_LOCAL_PACKAGES} +) +option(CPM_LOCAL_PACKAGES_ONLY "Only use `find_package` to get dependencies" + $ENV{CPM_LOCAL_PACKAGES_ONLY} +) +option(CPM_DOWNLOAD_ALL "Always download dependencies from source" $ENV{CPM_DOWNLOAD_ALL}) +option(CPM_DONT_UPDATE_MODULE_PATH "Don't update the module path to allow using find_package" + $ENV{CPM_DONT_UPDATE_MODULE_PATH} +) +option(CPM_DONT_CREATE_PACKAGE_LOCK "Don't create a package lock file in the binary path" + $ENV{CPM_DONT_CREATE_PACKAGE_LOCK} +) +option(CPM_INCLUDE_ALL_IN_PACKAGE_LOCK + "Add all packages added through CPM.cmake to the package lock" + $ENV{CPM_INCLUDE_ALL_IN_PACKAGE_LOCK} +) +option(CPM_USE_NAMED_CACHE_DIRECTORIES + "Use additional directory of package name in cache on the most nested level." + $ENV{CPM_USE_NAMED_CACHE_DIRECTORIES} +) + +set(CPM_VERSION + ${CURRENT_CPM_VERSION} + CACHE INTERNAL "" +) +set(CPM_DIRECTORY + ${CPM_CURRENT_DIRECTORY} + CACHE INTERNAL "" +) +set(CPM_FILE + ${CMAKE_CURRENT_LIST_FILE} + CACHE INTERNAL "" +) +set(CPM_PACKAGES + "" + CACHE INTERNAL "" +) +set(CPM_DRY_RUN + OFF + CACHE INTERNAL "Don't download or configure dependencies (for testing)" +) + +if(DEFINED ENV{CPM_SOURCE_CACHE}) + set(CPM_SOURCE_CACHE_DEFAULT $ENV{CPM_SOURCE_CACHE}) +else() + set(CPM_SOURCE_CACHE_DEFAULT OFF) +endif() + +set(CPM_SOURCE_CACHE + ${CPM_SOURCE_CACHE_DEFAULT} + CACHE PATH "Directory to download CPM dependencies" +) + +if(NOT CPM_DONT_UPDATE_MODULE_PATH AND NOT DEFINED CMAKE_FIND_PACKAGE_REDIRECTS_DIR) + set(CPM_MODULE_PATH + "${CMAKE_BINARY_DIR}/CPM_modules" + CACHE INTERNAL "" + ) + # remove old modules + file(REMOVE_RECURSE ${CPM_MODULE_PATH}) + file(MAKE_DIRECTORY ${CPM_MODULE_PATH}) + # locally added CPM modules should override global packages + set(CMAKE_MODULE_PATH "${CPM_MODULE_PATH};${CMAKE_MODULE_PATH}") +endif() + +if(NOT CPM_DONT_CREATE_PACKAGE_LOCK) + set(CPM_PACKAGE_LOCK_FILE + "${CMAKE_BINARY_DIR}/cpm-package-lock.cmake" + CACHE INTERNAL "" + ) + file(WRITE ${CPM_PACKAGE_LOCK_FILE} + "# CPM Package Lock\n# This file should be committed to version control\n\n" + ) +endif() + +include(FetchContent) + +# Try to infer package name from git repository uri (path or url) +function(cpm_package_name_from_git_uri URI RESULT) + if("${URI}" MATCHES "([^/:]+)/?.git/?$") + set(${RESULT} + ${CMAKE_MATCH_1} + PARENT_SCOPE + ) + else() + unset(${RESULT} PARENT_SCOPE) + endif() +endfunction() + +# Find the shortest hash that can be used eg, if origin_hash is +# cccb77ae9609d2768ed80dd42cec54f77b1f1455 the following files will be checked, until one is found +# that is either empty (allowing us to assign origin_hash), or whose contents matches ${origin_hash} +# +# * .../cccb.hash +# * .../cccb77ae.hash +# * .../cccb77ae9609.hash +# * .../cccb77ae9609d276.hash +# * etc +# +# We will be able to use a shorter path with very high probability, but in the (rare) event that the +# first couple characters collide, we will check longer and longer substrings. +function(cpm_get_shortest_hash source_cache_dir origin_hash short_hash_output_var) + # for compatibility with caches populated by a previous version of CPM, check if a directory using + # the full hash already exists + if(EXISTS "${source_cache_dir}/${origin_hash}") + set(${short_hash_output_var} + "${origin_hash}" + PARENT_SCOPE + ) + return() + endif() + + foreach(len RANGE 4 40 4) + string(SUBSTRING "${origin_hash}" 0 ${len} short_hash) + set(hash_lock ${source_cache_dir}/${short_hash}.lock) + set(hash_fp ${source_cache_dir}/${short_hash}.hash) + # Take a lock, so we don't have a race condition with another instance of cmake. We will release + # this lock when we can, however, if there is an error, we want to ensure it gets released on + # it's own on exit from the function. + file(LOCK ${hash_lock} GUARD FUNCTION) + + # Load the contents of .../${short_hash}.hash + file(TOUCH ${hash_fp}) + file(READ ${hash_fp} hash_fp_contents) + + if(hash_fp_contents STREQUAL "") + # Write the origin hash + file(WRITE ${hash_fp} ${origin_hash}) + file(LOCK ${hash_lock} RELEASE) + break() + elseif(hash_fp_contents STREQUAL origin_hash) + file(LOCK ${hash_lock} RELEASE) + break() + else() + file(LOCK ${hash_lock} RELEASE) + endif() + endforeach() + set(${short_hash_output_var} + "${short_hash}" + PARENT_SCOPE + ) +endfunction() + +# Try to infer package name and version from a url +function(cpm_package_name_and_ver_from_url url outName outVer) + if(url MATCHES "[/\\?]([a-zA-Z0-9_\\.-]+)\\.(tar|tar\\.gz|tar\\.bz2|zip|ZIP)(\\?|/|$)") + # We matched an archive + set(filename "${CMAKE_MATCH_1}") + + if(filename MATCHES "([a-zA-Z0-9_\\.-]+)[_-]v?(([0-9]+\\.)*[0-9]+[a-zA-Z0-9]*)") + # We matched - (ie foo-1.2.3) + set(${outName} + "${CMAKE_MATCH_1}" + PARENT_SCOPE + ) + set(${outVer} + "${CMAKE_MATCH_2}" + PARENT_SCOPE + ) + elseif(filename MATCHES "(([0-9]+\\.)+[0-9]+[a-zA-Z0-9]*)") + # We couldn't find a name, but we found a version + # + # In many cases (which we don't handle here) the url would look something like + # `irrelevant/ACTUAL_PACKAGE_NAME/irrelevant/1.2.3.zip`. In such a case we can't possibly + # distinguish the package name from the irrelevant bits. Moreover if we try to match the + # package name from the filename, we'd get bogus at best. + unset(${outName} PARENT_SCOPE) + set(${outVer} + "${CMAKE_MATCH_1}" + PARENT_SCOPE + ) + else() + # Boldly assume that the file name is the package name. + # + # Yes, something like `irrelevant/ACTUAL_NAME/irrelevant/download.zip` will ruin our day, but + # such cases should be quite rare. No popular service does this... we think. + set(${outName} + "${filename}" + PARENT_SCOPE + ) + unset(${outVer} PARENT_SCOPE) + endif() + else() + # No ideas yet what to do with non-archives + unset(${outName} PARENT_SCOPE) + unset(${outVer} PARENT_SCOPE) + endif() +endfunction() + +function(cpm_find_package NAME VERSION) + string(REPLACE " " ";" EXTRA_ARGS "${ARGN}") + find_package(${NAME} ${VERSION} ${EXTRA_ARGS} QUIET) + if(${CPM_ARGS_NAME}_FOUND) + if(DEFINED ${CPM_ARGS_NAME}_VERSION) + set(VERSION ${${CPM_ARGS_NAME}_VERSION}) + endif() + cpm_message(STATUS "${CPM_INDENT} Using local package ${CPM_ARGS_NAME}@${VERSION}") + CPMRegisterPackage(${CPM_ARGS_NAME} "${VERSION}") + set(CPM_PACKAGE_FOUND + YES + PARENT_SCOPE + ) + else() + set(CPM_PACKAGE_FOUND + NO + PARENT_SCOPE + ) + endif() +endfunction() + +# Create a custom FindXXX.cmake module for a CPM package This prevents `find_package(NAME)` from +# finding the system library +function(cpm_create_module_file Name) + if(NOT CPM_DONT_UPDATE_MODULE_PATH) + if(DEFINED CMAKE_FIND_PACKAGE_REDIRECTS_DIR) + # Redirect find_package calls to the CPM package. This is what FetchContent does when you set + # OVERRIDE_FIND_PACKAGE. The CMAKE_FIND_PACKAGE_REDIRECTS_DIR works for find_package in CONFIG + # mode, unlike the Find${Name}.cmake fallback. CMAKE_FIND_PACKAGE_REDIRECTS_DIR is not defined + # in script mode, or in CMake < 3.24. + # https://cmake.org/cmake/help/latest/module/FetchContent.html#fetchcontent-find-package-integration-examples + string(TOLOWER ${Name} NameLower) + file(WRITE ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/${NameLower}-config.cmake + "include(\"\${CMAKE_CURRENT_LIST_DIR}/${NameLower}-extra.cmake\" OPTIONAL)\n" + "include(\"\${CMAKE_CURRENT_LIST_DIR}/${Name}Extra.cmake\" OPTIONAL)\n" + ) + file(WRITE ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/${NameLower}-config-version.cmake + "set(PACKAGE_VERSION_COMPATIBLE TRUE)\n" "set(PACKAGE_VERSION_EXACT TRUE)\n" + ) + else() + file(WRITE ${CPM_MODULE_PATH}/Find${Name}.cmake + "include(\"${CPM_FILE}\")\n${ARGN}\nset(${Name}_FOUND TRUE)" + ) + endif() + endif() +endfunction() + +# Find a package locally or fallback to CPMAddPackage +function(CPMFindPackage) + set(oneValueArgs NAME VERSION GIT_TAG FIND_PACKAGE_ARGUMENTS) + + cmake_parse_arguments(CPM_ARGS "" "${oneValueArgs}" "" ${ARGN}) + + if(NOT DEFINED CPM_ARGS_VERSION) + if(DEFINED CPM_ARGS_GIT_TAG) + cpm_get_version_from_git_tag("${CPM_ARGS_GIT_TAG}" CPM_ARGS_VERSION) + endif() + endif() + + set(downloadPackage ${CPM_DOWNLOAD_ALL}) + if(DEFINED CPM_DOWNLOAD_${CPM_ARGS_NAME}) + set(downloadPackage ${CPM_DOWNLOAD_${CPM_ARGS_NAME}}) + elseif(DEFINED ENV{CPM_DOWNLOAD_${CPM_ARGS_NAME}}) + set(downloadPackage $ENV{CPM_DOWNLOAD_${CPM_ARGS_NAME}}) + endif() + if(downloadPackage) + CPMAddPackage(${ARGN}) + cpm_export_variables(${CPM_ARGS_NAME}) + return() + endif() + + cpm_find_package(${CPM_ARGS_NAME} "${CPM_ARGS_VERSION}" ${CPM_ARGS_FIND_PACKAGE_ARGUMENTS}) + + if(NOT CPM_PACKAGE_FOUND) + CPMAddPackage(${ARGN}) + cpm_export_variables(${CPM_ARGS_NAME}) + endif() + +endfunction() + +# checks if a package has been added before +function(cpm_check_if_package_already_added CPM_ARGS_NAME CPM_ARGS_VERSION) + if("${CPM_ARGS_NAME}" IN_LIST CPM_PACKAGES) + CPMGetPackageVersion(${CPM_ARGS_NAME} CPM_PACKAGE_VERSION) + if("${CPM_PACKAGE_VERSION}" VERSION_LESS "${CPM_ARGS_VERSION}") + message( + WARNING + "${CPM_INDENT} Requires a newer version of ${CPM_ARGS_NAME} (${CPM_ARGS_VERSION}) than currently included (${CPM_PACKAGE_VERSION})." + ) + endif() + cpm_get_fetch_properties(${CPM_ARGS_NAME}) + set(${CPM_ARGS_NAME}_ADDED NO) + set(CPM_PACKAGE_ALREADY_ADDED + YES + PARENT_SCOPE + ) + cpm_export_variables(${CPM_ARGS_NAME}) + else() + set(CPM_PACKAGE_ALREADY_ADDED + NO + PARENT_SCOPE + ) + endif() +endfunction() + +# Parse the argument of CPMAddPackage in case a single one was provided and convert it to a list of +# arguments which can then be parsed idiomatically. For example gh:foo/bar@1.2.3 will be converted +# to: GITHUB_REPOSITORY;foo/bar;VERSION;1.2.3 +function(cpm_parse_add_package_single_arg arg outArgs) + # Look for a scheme + if("${arg}" MATCHES "^([a-zA-Z]+):(.+)$") + string(TOLOWER "${CMAKE_MATCH_1}" scheme) + set(uri "${CMAKE_MATCH_2}") + + # Check for CPM-specific schemes + if(scheme STREQUAL "gh") + set(out "GITHUB_REPOSITORY;${uri}") + set(packageType "git") + elseif(scheme STREQUAL "gl") + set(out "GITLAB_REPOSITORY;${uri}") + set(packageType "git") + elseif(scheme STREQUAL "bb") + set(out "BITBUCKET_REPOSITORY;${uri}") + set(packageType "git") + # A CPM-specific scheme was not found. Looks like this is a generic URL so try to determine + # type + elseif(arg MATCHES ".git/?(@|#|$)") + set(out "GIT_REPOSITORY;${arg}") + set(packageType "git") + else() + # Fall back to a URL + set(out "URL;${arg}") + set(packageType "archive") + + # We could also check for SVN since FetchContent supports it, but SVN is so rare these days. + # We just won't bother with the additional complexity it will induce in this function. SVN is + # done by multi-arg + endif() + else() + if(arg MATCHES ".git/?(@|#|$)") + set(out "GIT_REPOSITORY;${arg}") + set(packageType "git") + else() + # Give up + message(FATAL_ERROR "${CPM_INDENT} Can't determine package type of '${arg}'") + endif() + endif() + + # For all packages we interpret @... as version. Only replace the last occurrence. Thus URIs + # containing '@' can be used + string(REGEX REPLACE "@([^@]+)$" ";VERSION;\\1" out "${out}") + + # Parse the rest according to package type + if(packageType STREQUAL "git") + # For git repos we interpret #... as a tag or branch or commit hash + string(REGEX REPLACE "#([^#]+)$" ";GIT_TAG;\\1" out "${out}") + elseif(packageType STREQUAL "archive") + # For archives we interpret #... as a URL hash. + string(REGEX REPLACE "#([^#]+)$" ";URL_HASH;\\1" out "${out}") + # We don't try to parse the version if it's not provided explicitly. cpm_get_version_from_url + # should do this at a later point + else() + # We should never get here. This is an assertion and hitting it means there's a problem with the + # code above. A packageType was set, but not handled by this if-else. + message(FATAL_ERROR "${CPM_INDENT} Unsupported package type '${packageType}' of '${arg}'") + endif() + + set(${outArgs} + ${out} + PARENT_SCOPE + ) +endfunction() + +# Check that the working directory for a git repo is clean +function(cpm_check_git_working_dir_is_clean repoPath gitTag isClean) + + find_package(Git REQUIRED) + + if(NOT GIT_EXECUTABLE) + # No git executable, assume directory is clean + set(${isClean} + TRUE + PARENT_SCOPE + ) + return() + endif() + + # check for uncommitted changes + execute_process( + COMMAND ${GIT_EXECUTABLE} status --porcelain + RESULT_VARIABLE resultGitStatus + OUTPUT_VARIABLE repoStatus + OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET + WORKING_DIRECTORY ${repoPath} + ) + if(resultGitStatus) + # not supposed to happen, assume clean anyway + message(WARNING "${CPM_INDENT} Calling git status on folder ${repoPath} failed") + set(${isClean} + TRUE + PARENT_SCOPE + ) + return() + endif() + + if(NOT "${repoStatus}" STREQUAL "") + set(${isClean} + FALSE + PARENT_SCOPE + ) + return() + endif() + + # check for committed changes + execute_process( + COMMAND ${GIT_EXECUTABLE} diff -s --exit-code ${gitTag} + RESULT_VARIABLE resultGitDiff + OUTPUT_STRIP_TRAILING_WHITESPACE OUTPUT_QUIET + WORKING_DIRECTORY ${repoPath} + ) + + if(${resultGitDiff} EQUAL 0) + set(${isClean} + TRUE + PARENT_SCOPE + ) + else() + set(${isClean} + FALSE + PARENT_SCOPE + ) + endif() + +endfunction() + +# Add PATCH_COMMAND to CPM_ARGS_UNPARSED_ARGUMENTS. This method consumes a list of files in ARGN +# then generates a `PATCH_COMMAND` appropriate for `ExternalProject_Add()`. This command is appended +# to the parent scope's `CPM_ARGS_UNPARSED_ARGUMENTS`. +function(cpm_add_patches) + # Return if no patch files are supplied. + if(NOT ARGN) + return() + endif() + + # Find the patch program. + find_program(PATCH_EXECUTABLE patch) + if(CMAKE_HOST_WIN32 AND NOT PATCH_EXECUTABLE) + # The Windows git executable is distributed with patch.exe. Find the path to the executable, if + # it exists, then search `../usr/bin` and `../../usr/bin` for patch.exe. + find_package(Git QUIET) + if(GIT_EXECUTABLE) + get_filename_component(extra_search_path ${GIT_EXECUTABLE} DIRECTORY) + get_filename_component(extra_search_path_1up ${extra_search_path} DIRECTORY) + get_filename_component(extra_search_path_2up ${extra_search_path_1up} DIRECTORY) + find_program( + PATCH_EXECUTABLE patch HINTS "${extra_search_path_1up}/usr/bin" + "${extra_search_path_2up}/usr/bin" + ) + endif() + endif() + if(NOT PATCH_EXECUTABLE) + message(FATAL_ERROR "Couldn't find `patch` executable to use with PATCHES keyword.") + endif() + + # Create a temporary + set(temp_list ${CPM_ARGS_UNPARSED_ARGUMENTS}) + + # Ensure each file exists (or error out) and add it to the list. + set(first_item True) + foreach(PATCH_FILE ${ARGN}) + # Make sure the patch file exists, if we can't find it, try again in the current directory. + if(NOT EXISTS "${PATCH_FILE}") + if(NOT EXISTS "${CMAKE_CURRENT_LIST_DIR}/${PATCH_FILE}") + message(FATAL_ERROR "Couldn't find patch file: '${PATCH_FILE}'") + endif() + set(PATCH_FILE "${CMAKE_CURRENT_LIST_DIR}/${PATCH_FILE}") + endif() + + # Convert to absolute path for use with patch file command. + get_filename_component(PATCH_FILE "${PATCH_FILE}" ABSOLUTE) + + # The first patch entry must be preceded by "PATCH_COMMAND" while the following items are + # preceded by "&&". + if(first_item) + set(first_item False) + list(APPEND temp_list "PATCH_COMMAND") + else() + list(APPEND temp_list "&&") + endif() + # Add the patch command to the list + list(APPEND temp_list "${PATCH_EXECUTABLE}" "-p1" "<" "${PATCH_FILE}") + endforeach() + + # Move temp out into parent scope. + set(CPM_ARGS_UNPARSED_ARGUMENTS + ${temp_list} + PARENT_SCOPE + ) + +endfunction() + +# method to overwrite internal FetchContent properties, to allow using CPM.cmake to overload +# FetchContent calls. As these are internal cmake properties, this method should be used carefully +# and may need modification in future CMake versions. Source: +# https://github.com/Kitware/CMake/blob/dc3d0b5a0a7d26d43d6cfeb511e224533b5d188f/Modules/FetchContent.cmake#L1152 +function(cpm_override_fetchcontent contentName) + cmake_parse_arguments(PARSE_ARGV 1 arg "" "SOURCE_DIR;BINARY_DIR" "") + if(NOT "${arg_UNPARSED_ARGUMENTS}" STREQUAL "") + message(FATAL_ERROR "${CPM_INDENT} Unsupported arguments: ${arg_UNPARSED_ARGUMENTS}") + endif() + + string(TOLOWER ${contentName} contentNameLower) + set(prefix "_FetchContent_${contentNameLower}") + + set(propertyName "${prefix}_sourceDir") + define_property( + GLOBAL + PROPERTY ${propertyName} + BRIEF_DOCS "Internal implementation detail of FetchContent_Populate()" + FULL_DOCS "Details used by FetchContent_Populate() for ${contentName}" + ) + set_property(GLOBAL PROPERTY ${propertyName} "${arg_SOURCE_DIR}") + + set(propertyName "${prefix}_binaryDir") + define_property( + GLOBAL + PROPERTY ${propertyName} + BRIEF_DOCS "Internal implementation detail of FetchContent_Populate()" + FULL_DOCS "Details used by FetchContent_Populate() for ${contentName}" + ) + set_property(GLOBAL PROPERTY ${propertyName} "${arg_BINARY_DIR}") + + set(propertyName "${prefix}_populated") + define_property( + GLOBAL + PROPERTY ${propertyName} + BRIEF_DOCS "Internal implementation detail of FetchContent_Populate()" + FULL_DOCS "Details used by FetchContent_Populate() for ${contentName}" + ) + set_property(GLOBAL PROPERTY ${propertyName} TRUE) +endfunction() + +# Download and add a package from source +function(CPMAddPackage) + cpm_set_policies() + + set(oneValueArgs + NAME + FORCE + VERSION + GIT_TAG + DOWNLOAD_ONLY + GITHUB_REPOSITORY + GITLAB_REPOSITORY + BITBUCKET_REPOSITORY + GIT_REPOSITORY + SOURCE_DIR + FIND_PACKAGE_ARGUMENTS + NO_CACHE + SYSTEM + GIT_SHALLOW + EXCLUDE_FROM_ALL + SOURCE_SUBDIR + CUSTOM_CACHE_KEY + ) + + set(multiValueArgs URL OPTIONS DOWNLOAD_COMMAND PATCHES) + + list(LENGTH ARGN argnLength) + + # Parse single shorthand argument + if(argnLength EQUAL 1) + cpm_parse_add_package_single_arg("${ARGN}" ARGN) + + # The shorthand syntax implies EXCLUDE_FROM_ALL and SYSTEM + set(ARGN "${ARGN};EXCLUDE_FROM_ALL;YES;SYSTEM;YES;") + + # Parse URI shorthand argument + elseif(argnLength GREATER 1 AND "${ARGV0}" STREQUAL "URI") + list(REMOVE_AT ARGN 0 1) # remove "URI gh:<...>@version#tag" + cpm_parse_add_package_single_arg("${ARGV1}" ARGV0) + + set(ARGN "${ARGV0};EXCLUDE_FROM_ALL;YES;SYSTEM;YES;${ARGN}") + endif() + + cmake_parse_arguments(CPM_ARGS "" "${oneValueArgs}" "${multiValueArgs}" "${ARGN}") + + # Set default values for arguments + if(NOT DEFINED CPM_ARGS_VERSION) + if(DEFINED CPM_ARGS_GIT_TAG) + cpm_get_version_from_git_tag("${CPM_ARGS_GIT_TAG}" CPM_ARGS_VERSION) + endif() + endif() + + if(CPM_ARGS_DOWNLOAD_ONLY) + set(DOWNLOAD_ONLY ${CPM_ARGS_DOWNLOAD_ONLY}) + else() + set(DOWNLOAD_ONLY NO) + endif() + + if(DEFINED CPM_ARGS_GITHUB_REPOSITORY) + set(CPM_ARGS_GIT_REPOSITORY "https://github.com/${CPM_ARGS_GITHUB_REPOSITORY}.git") + elseif(DEFINED CPM_ARGS_GITLAB_REPOSITORY) + set(CPM_ARGS_GIT_REPOSITORY "https://gitlab.com/${CPM_ARGS_GITLAB_REPOSITORY}.git") + elseif(DEFINED CPM_ARGS_BITBUCKET_REPOSITORY) + set(CPM_ARGS_GIT_REPOSITORY "https://bitbucket.org/${CPM_ARGS_BITBUCKET_REPOSITORY}.git") + endif() + + if(DEFINED CPM_ARGS_GIT_REPOSITORY) + list(APPEND CPM_ARGS_UNPARSED_ARGUMENTS GIT_REPOSITORY ${CPM_ARGS_GIT_REPOSITORY}) + if(NOT DEFINED CPM_ARGS_GIT_TAG) + set(CPM_ARGS_GIT_TAG v${CPM_ARGS_VERSION}) + endif() + + # If a name wasn't provided, try to infer it from the git repo + if(NOT DEFINED CPM_ARGS_NAME) + cpm_package_name_from_git_uri(${CPM_ARGS_GIT_REPOSITORY} CPM_ARGS_NAME) + endif() + endif() + + set(CPM_SKIP_FETCH FALSE) + + if(DEFINED CPM_ARGS_GIT_TAG) + list(APPEND CPM_ARGS_UNPARSED_ARGUMENTS GIT_TAG ${CPM_ARGS_GIT_TAG}) + # If GIT_SHALLOW is explicitly specified, honor the value. + if(DEFINED CPM_ARGS_GIT_SHALLOW) + list(APPEND CPM_ARGS_UNPARSED_ARGUMENTS GIT_SHALLOW ${CPM_ARGS_GIT_SHALLOW}) + endif() + endif() + + if(DEFINED CPM_ARGS_URL) + # If a name or version aren't provided, try to infer them from the URL + list(GET CPM_ARGS_URL 0 firstUrl) + cpm_package_name_and_ver_from_url(${firstUrl} nameFromUrl verFromUrl) + # If we fail to obtain name and version from the first URL, we could try other URLs if any. + # However multiple URLs are expected to be quite rare, so for now we won't bother. + + # If the caller provided their own name and version, they trump the inferred ones. + if(NOT DEFINED CPM_ARGS_NAME) + set(CPM_ARGS_NAME ${nameFromUrl}) + endif() + if(NOT DEFINED CPM_ARGS_VERSION) + set(CPM_ARGS_VERSION ${verFromUrl}) + endif() + + list(APPEND CPM_ARGS_UNPARSED_ARGUMENTS URL "${CPM_ARGS_URL}") + endif() + + # Check for required arguments + + if(NOT DEFINED CPM_ARGS_NAME) + message( + FATAL_ERROR + "${CPM_INDENT} 'NAME' was not provided and couldn't be automatically inferred for package added with arguments: '${ARGN}'" + ) + endif() + + # Check if package has been added before + cpm_check_if_package_already_added(${CPM_ARGS_NAME} "${CPM_ARGS_VERSION}") + if(CPM_PACKAGE_ALREADY_ADDED) + cpm_export_variables(${CPM_ARGS_NAME}) + return() + endif() + + # Check for manual overrides + if(NOT CPM_ARGS_FORCE AND NOT "${CPM_${CPM_ARGS_NAME}_SOURCE}" STREQUAL "") + set(PACKAGE_SOURCE ${CPM_${CPM_ARGS_NAME}_SOURCE}) + set(CPM_${CPM_ARGS_NAME}_SOURCE "") + CPMAddPackage( + NAME "${CPM_ARGS_NAME}" + SOURCE_DIR "${PACKAGE_SOURCE}" + EXCLUDE_FROM_ALL "${CPM_ARGS_EXCLUDE_FROM_ALL}" + SYSTEM "${CPM_ARGS_SYSTEM}" + PATCHES "${CPM_ARGS_PATCHES}" + OPTIONS "${CPM_ARGS_OPTIONS}" + SOURCE_SUBDIR "${CPM_ARGS_SOURCE_SUBDIR}" + DOWNLOAD_ONLY "${DOWNLOAD_ONLY}" + FORCE True + ) + cpm_export_variables(${CPM_ARGS_NAME}) + return() + endif() + + # Check for available declaration + if(NOT CPM_ARGS_FORCE AND NOT "${CPM_DECLARATION_${CPM_ARGS_NAME}}" STREQUAL "") + set(declaration ${CPM_DECLARATION_${CPM_ARGS_NAME}}) + set(CPM_DECLARATION_${CPM_ARGS_NAME} "") + CPMAddPackage(${declaration}) + cpm_export_variables(${CPM_ARGS_NAME}) + # checking again to ensure version and option compatibility + cpm_check_if_package_already_added(${CPM_ARGS_NAME} "${CPM_ARGS_VERSION}") + return() + endif() + + if(NOT CPM_ARGS_FORCE) + if(CPM_USE_LOCAL_PACKAGES OR CPM_LOCAL_PACKAGES_ONLY) + cpm_find_package(${CPM_ARGS_NAME} "${CPM_ARGS_VERSION}" ${CPM_ARGS_FIND_PACKAGE_ARGUMENTS}) + + if(CPM_PACKAGE_FOUND) + cpm_export_variables(${CPM_ARGS_NAME}) + return() + endif() + + if(CPM_LOCAL_PACKAGES_ONLY) + message( + SEND_ERROR + "${CPM_INDENT} ${CPM_ARGS_NAME} not found via find_package(${CPM_ARGS_NAME} ${CPM_ARGS_VERSION})" + ) + endif() + endif() + endif() + + CPMRegisterPackage("${CPM_ARGS_NAME}" "${CPM_ARGS_VERSION}") + + if(DEFINED CPM_ARGS_GIT_TAG) + set(PACKAGE_INFO "${CPM_ARGS_GIT_TAG}") + elseif(DEFINED CPM_ARGS_SOURCE_DIR) + set(PACKAGE_INFO "${CPM_ARGS_SOURCE_DIR}") + else() + set(PACKAGE_INFO "${CPM_ARGS_VERSION}") + endif() + + if(DEFINED FETCHCONTENT_BASE_DIR) + # respect user's FETCHCONTENT_BASE_DIR if set + set(CPM_FETCHCONTENT_BASE_DIR ${FETCHCONTENT_BASE_DIR}) + else() + set(CPM_FETCHCONTENT_BASE_DIR ${CMAKE_BINARY_DIR}/_deps) + endif() + + cpm_add_patches(${CPM_ARGS_PATCHES}) + + if(DEFINED CPM_ARGS_DOWNLOAD_COMMAND) + list(APPEND CPM_ARGS_UNPARSED_ARGUMENTS DOWNLOAD_COMMAND ${CPM_ARGS_DOWNLOAD_COMMAND}) + elseif(DEFINED CPM_ARGS_SOURCE_DIR) + list(APPEND CPM_ARGS_UNPARSED_ARGUMENTS SOURCE_DIR ${CPM_ARGS_SOURCE_DIR}) + if(NOT IS_ABSOLUTE ${CPM_ARGS_SOURCE_DIR}) + # Expand `CPM_ARGS_SOURCE_DIR` relative path. This is important because EXISTS doesn't work + # for relative paths. + get_filename_component( + source_directory ${CPM_ARGS_SOURCE_DIR} REALPATH BASE_DIR ${CMAKE_CURRENT_BINARY_DIR} + ) + else() + set(source_directory ${CPM_ARGS_SOURCE_DIR}) + endif() + if(NOT EXISTS ${source_directory}) + string(TOLOWER ${CPM_ARGS_NAME} lower_case_name) + # remove timestamps so CMake will re-download the dependency + file(REMOVE_RECURSE "${CPM_FETCHCONTENT_BASE_DIR}/${lower_case_name}-subbuild") + endif() + elseif(CPM_SOURCE_CACHE AND NOT CPM_ARGS_NO_CACHE) + string(TOLOWER ${CPM_ARGS_NAME} lower_case_name) + set(origin_parameters ${CPM_ARGS_UNPARSED_ARGUMENTS}) + list(SORT origin_parameters) + if(CPM_ARGS_CUSTOM_CACHE_KEY) + # Application set a custom unique directory name + set(download_directory ${CPM_SOURCE_CACHE}/${lower_case_name}/${CPM_ARGS_CUSTOM_CACHE_KEY}) + elseif(CPM_USE_NAMED_CACHE_DIRECTORIES) + string(SHA1 origin_hash "${origin_parameters};NEW_CACHE_STRUCTURE_TAG") + cpm_get_shortest_hash( + "${CPM_SOURCE_CACHE}/${lower_case_name}" # source cache directory + "${origin_hash}" # Input hash + origin_hash # Computed hash + ) + set(download_directory ${CPM_SOURCE_CACHE}/${lower_case_name}/${origin_hash}/${CPM_ARGS_NAME}) + else() + string(SHA1 origin_hash "${origin_parameters}") + cpm_get_shortest_hash( + "${CPM_SOURCE_CACHE}/${lower_case_name}" # source cache directory + "${origin_hash}" # Input hash + origin_hash # Computed hash + ) + set(download_directory ${CPM_SOURCE_CACHE}/${lower_case_name}/${origin_hash}) + endif() + # Expand `download_directory` relative path. This is important because EXISTS doesn't work for + # relative paths. + get_filename_component(download_directory ${download_directory} ABSOLUTE) + list(APPEND CPM_ARGS_UNPARSED_ARGUMENTS SOURCE_DIR ${download_directory}) + + if(CPM_SOURCE_CACHE) + file(LOCK ${download_directory}/../cmake.lock) + endif() + + if(EXISTS ${download_directory}) + if(CPM_SOURCE_CACHE) + file(LOCK ${download_directory}/../cmake.lock RELEASE) + endif() + + cpm_store_fetch_properties( + ${CPM_ARGS_NAME} "${download_directory}" + "${CPM_FETCHCONTENT_BASE_DIR}/${lower_case_name}-build" + ) + cpm_get_fetch_properties("${CPM_ARGS_NAME}") + + if(DEFINED CPM_ARGS_GIT_TAG AND NOT (PATCH_COMMAND IN_LIST CPM_ARGS_UNPARSED_ARGUMENTS)) + # warn if cache has been changed since checkout + cpm_check_git_working_dir_is_clean(${download_directory} ${CPM_ARGS_GIT_TAG} IS_CLEAN) + if(NOT ${IS_CLEAN}) + message( + WARNING "${CPM_INDENT} Cache for ${CPM_ARGS_NAME} (${download_directory}) is dirty" + ) + endif() + endif() + + cpm_add_subdirectory( + "${CPM_ARGS_NAME}" + "${DOWNLOAD_ONLY}" + "${${CPM_ARGS_NAME}_SOURCE_DIR}/${CPM_ARGS_SOURCE_SUBDIR}" + "${${CPM_ARGS_NAME}_BINARY_DIR}" + "${CPM_ARGS_EXCLUDE_FROM_ALL}" + "${CPM_ARGS_SYSTEM}" + "${CPM_ARGS_OPTIONS}" + ) + set(PACKAGE_INFO "${PACKAGE_INFO} at ${download_directory}") + + # As the source dir is already cached/populated, we override the call to FetchContent. + set(CPM_SKIP_FETCH TRUE) + cpm_override_fetchcontent( + "${lower_case_name}" SOURCE_DIR "${${CPM_ARGS_NAME}_SOURCE_DIR}/${CPM_ARGS_SOURCE_SUBDIR}" + BINARY_DIR "${${CPM_ARGS_NAME}_BINARY_DIR}" + ) + + else() + # Enable shallow clone when GIT_TAG is not a commit hash. Our guess may not be accurate, but + # it should guarantee no commit hash get mis-detected. + if(NOT DEFINED CPM_ARGS_GIT_SHALLOW) + cpm_is_git_tag_commit_hash("${CPM_ARGS_GIT_TAG}" IS_HASH) + if(NOT ${IS_HASH}) + list(APPEND CPM_ARGS_UNPARSED_ARGUMENTS GIT_SHALLOW TRUE) + endif() + endif() + + # remove timestamps so CMake will re-download the dependency + file(REMOVE_RECURSE ${CPM_FETCHCONTENT_BASE_DIR}/${lower_case_name}-subbuild) + set(PACKAGE_INFO "${PACKAGE_INFO} to ${download_directory}") + endif() + endif() + + if(NOT "${DOWNLOAD_ONLY}") + cpm_create_module_file(${CPM_ARGS_NAME} "CPMAddPackage(\"${ARGN}\")") + endif() + + if(CPM_PACKAGE_LOCK_ENABLED) + if((CPM_ARGS_VERSION AND NOT CPM_ARGS_SOURCE_DIR) OR CPM_INCLUDE_ALL_IN_PACKAGE_LOCK) + cpm_add_to_package_lock(${CPM_ARGS_NAME} "${ARGN}") + elseif(CPM_ARGS_SOURCE_DIR) + cpm_add_comment_to_package_lock(${CPM_ARGS_NAME} "local directory") + else() + cpm_add_comment_to_package_lock(${CPM_ARGS_NAME} "${ARGN}") + endif() + endif() + + cpm_message( + STATUS "${CPM_INDENT} Adding package ${CPM_ARGS_NAME}@${CPM_ARGS_VERSION} (${PACKAGE_INFO})" + ) + + if(NOT CPM_SKIP_FETCH) + # CMake 3.28 added EXCLUDE, SYSTEM (3.25), and SOURCE_SUBDIR (3.18) to FetchContent_Declare. + # Calling FetchContent_MakeAvailable will then internally forward these options to + # add_subdirectory. Up until these changes, we had to call FetchContent_Populate and + # add_subdirectory separately, which is no longer necessary and has been deprecated as of 3.30. + # A Bug in CMake prevents us to use the non-deprecated functions until 3.30.3. + set(fetchContentDeclareExtraArgs "") + if(${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.30.3") + if(${CPM_ARGS_EXCLUDE_FROM_ALL}) + list(APPEND fetchContentDeclareExtraArgs EXCLUDE_FROM_ALL) + endif() + if(${CPM_ARGS_SYSTEM}) + list(APPEND fetchContentDeclareExtraArgs SYSTEM) + endif() + if(DEFINED CPM_ARGS_SOURCE_SUBDIR) + list(APPEND fetchContentDeclareExtraArgs SOURCE_SUBDIR ${CPM_ARGS_SOURCE_SUBDIR}) + endif() + # For CMake version <3.28 OPTIONS are parsed in cpm_add_subdirectory + if(CPM_ARGS_OPTIONS AND NOT DOWNLOAD_ONLY) + foreach(OPTION ${CPM_ARGS_OPTIONS}) + cpm_parse_option("${OPTION}") + set(${OPTION_KEY} "${OPTION_VALUE}") + endforeach() + endif() + endif() + cpm_declare_fetch( + "${CPM_ARGS_NAME}" ${fetchContentDeclareExtraArgs} "${CPM_ARGS_UNPARSED_ARGUMENTS}" + ) + + cpm_fetch_package("${CPM_ARGS_NAME}" ${DOWNLOAD_ONLY} populated ${CPM_ARGS_UNPARSED_ARGUMENTS}) + if(CPM_SOURCE_CACHE AND download_directory) + file(LOCK ${download_directory}/../cmake.lock RELEASE) + endif() + if(${populated} AND ${CMAKE_VERSION} VERSION_LESS "3.30.3") + cpm_add_subdirectory( + "${CPM_ARGS_NAME}" + "${DOWNLOAD_ONLY}" + "${${CPM_ARGS_NAME}_SOURCE_DIR}/${CPM_ARGS_SOURCE_SUBDIR}" + "${${CPM_ARGS_NAME}_BINARY_DIR}" + "${CPM_ARGS_EXCLUDE_FROM_ALL}" + "${CPM_ARGS_SYSTEM}" + "${CPM_ARGS_OPTIONS}" + ) + endif() + cpm_get_fetch_properties("${CPM_ARGS_NAME}") + endif() + + set(${CPM_ARGS_NAME}_ADDED YES) + cpm_export_variables("${CPM_ARGS_NAME}") +endfunction() + +# Fetch a previously declared package +macro(CPMGetPackage Name) + if(DEFINED "CPM_DECLARATION_${Name}") + CPMAddPackage(NAME ${Name}) + else() + message(SEND_ERROR "${CPM_INDENT} Cannot retrieve package ${Name}: no declaration available") + endif() +endmacro() + +# export variables available to the caller to the parent scope expects ${CPM_ARGS_NAME} to be set +macro(cpm_export_variables name) + set(${name}_SOURCE_DIR + "${${name}_SOURCE_DIR}" + PARENT_SCOPE + ) + set(${name}_BINARY_DIR + "${${name}_BINARY_DIR}" + PARENT_SCOPE + ) + set(${name}_ADDED + "${${name}_ADDED}" + PARENT_SCOPE + ) + set(CPM_LAST_PACKAGE_NAME + "${name}" + PARENT_SCOPE + ) +endmacro() + +# declares a package, so that any call to CPMAddPackage for the package name will use these +# arguments instead. Previous declarations will not be overridden. +macro(CPMDeclarePackage Name) + if(NOT DEFINED "CPM_DECLARATION_${Name}") + set("CPM_DECLARATION_${Name}" "${ARGN}") + endif() +endmacro() + +function(cpm_add_to_package_lock Name) + if(NOT CPM_DONT_CREATE_PACKAGE_LOCK) + cpm_prettify_package_arguments(PRETTY_ARGN false ${ARGN}) + file(APPEND ${CPM_PACKAGE_LOCK_FILE} "# ${Name}\nCPMDeclarePackage(${Name}\n${PRETTY_ARGN})\n") + endif() +endfunction() + +function(cpm_add_comment_to_package_lock Name) + if(NOT CPM_DONT_CREATE_PACKAGE_LOCK) + cpm_prettify_package_arguments(PRETTY_ARGN true ${ARGN}) + file(APPEND ${CPM_PACKAGE_LOCK_FILE} + "# ${Name} (unversioned)\n# CPMDeclarePackage(${Name}\n${PRETTY_ARGN}#)\n" + ) + endif() +endfunction() + +# includes the package lock file if it exists and creates a target `cpm-update-package-lock` to +# update it +macro(CPMUsePackageLock file) + if(NOT CPM_DONT_CREATE_PACKAGE_LOCK) + get_filename_component(CPM_ABSOLUTE_PACKAGE_LOCK_PATH ${file} ABSOLUTE) + if(EXISTS ${CPM_ABSOLUTE_PACKAGE_LOCK_PATH}) + include(${CPM_ABSOLUTE_PACKAGE_LOCK_PATH}) + endif() + if(NOT TARGET cpm-update-package-lock) + add_custom_target( + cpm-update-package-lock COMMAND ${CMAKE_COMMAND} -E copy ${CPM_PACKAGE_LOCK_FILE} + ${CPM_ABSOLUTE_PACKAGE_LOCK_PATH} + ) + endif() + set(CPM_PACKAGE_LOCK_ENABLED true) + endif() +endmacro() + +# registers a package that has been added to CPM +function(CPMRegisterPackage PACKAGE VERSION) + list(APPEND CPM_PACKAGES ${PACKAGE}) + set(CPM_PACKAGES + ${CPM_PACKAGES} + CACHE INTERNAL "" + ) + set("CPM_PACKAGE_${PACKAGE}_VERSION" + ${VERSION} + CACHE INTERNAL "" + ) +endfunction() + +# retrieve the current version of the package to ${OUTPUT} +function(CPMGetPackageVersion PACKAGE OUTPUT) + set(${OUTPUT} + "${CPM_PACKAGE_${PACKAGE}_VERSION}" + PARENT_SCOPE + ) +endfunction() + +# declares a package in FetchContent_Declare +function(cpm_declare_fetch PACKAGE) + if(${CPM_DRY_RUN}) + cpm_message(STATUS "${CPM_INDENT} Package not declared (dry run)") + return() + endif() + + FetchContent_Declare(${PACKAGE} ${ARGN}) +endfunction() + +# returns properties for a package previously defined by cpm_declare_fetch +function(cpm_get_fetch_properties PACKAGE) + if(${CPM_DRY_RUN}) + return() + endif() + + set(${PACKAGE}_SOURCE_DIR + "${CPM_PACKAGE_${PACKAGE}_SOURCE_DIR}" + PARENT_SCOPE + ) + set(${PACKAGE}_BINARY_DIR + "${CPM_PACKAGE_${PACKAGE}_BINARY_DIR}" + PARENT_SCOPE + ) +endfunction() + +function(cpm_store_fetch_properties PACKAGE source_dir binary_dir) + if(${CPM_DRY_RUN}) + return() + endif() + + set(CPM_PACKAGE_${PACKAGE}_SOURCE_DIR + "${source_dir}" + CACHE INTERNAL "" + ) + set(CPM_PACKAGE_${PACKAGE}_BINARY_DIR + "${binary_dir}" + CACHE INTERNAL "" + ) +endfunction() + +# adds a package as a subdirectory if viable, according to provided options +function( + cpm_add_subdirectory + PACKAGE + DOWNLOAD_ONLY + SOURCE_DIR + BINARY_DIR + EXCLUDE + SYSTEM + OPTIONS +) + + if(NOT DOWNLOAD_ONLY AND EXISTS ${SOURCE_DIR}/CMakeLists.txt) + set(addSubdirectoryExtraArgs "") + if(EXCLUDE) + list(APPEND addSubdirectoryExtraArgs EXCLUDE_FROM_ALL) + endif() + if("${SYSTEM}" AND "${CMAKE_VERSION}" VERSION_GREATER_EQUAL "3.25") + # https://cmake.org/cmake/help/latest/prop_dir/SYSTEM.html#prop_dir:SYSTEM + list(APPEND addSubdirectoryExtraArgs SYSTEM) + endif() + if(OPTIONS) + foreach(OPTION ${OPTIONS}) + cpm_parse_option("${OPTION}") + set(${OPTION_KEY} "${OPTION_VALUE}") + endforeach() + endif() + set(CPM_OLD_INDENT "${CPM_INDENT}") + set(CPM_INDENT "${CPM_INDENT} ${PACKAGE}:") + add_subdirectory(${SOURCE_DIR} ${BINARY_DIR} ${addSubdirectoryExtraArgs}) + set(CPM_INDENT "${CPM_OLD_INDENT}") + endif() +endfunction() + +# downloads a previously declared package via FetchContent and exports the variables +# `${PACKAGE}_SOURCE_DIR` and `${PACKAGE}_BINARY_DIR` to the parent scope +function(cpm_fetch_package PACKAGE DOWNLOAD_ONLY populated) + set(${populated} + FALSE + PARENT_SCOPE + ) + if(${CPM_DRY_RUN}) + cpm_message(STATUS "${CPM_INDENT} Package ${PACKAGE} not fetched (dry run)") + return() + endif() + + FetchContent_GetProperties(${PACKAGE}) + + string(TOLOWER "${PACKAGE}" lower_case_name) + + if(NOT ${lower_case_name}_POPULATED) + if(${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.30.3") + if(DOWNLOAD_ONLY) + # MakeAvailable will call add_subdirectory internally which is not what we want when + # DOWNLOAD_ONLY is set. Populate will only download the dependency without adding it to the + # build + FetchContent_Populate( + ${PACKAGE} + SOURCE_DIR "${CPM_FETCHCONTENT_BASE_DIR}/${lower_case_name}-src" + BINARY_DIR "${CPM_FETCHCONTENT_BASE_DIR}/${lower_case_name}-build" + SUBBUILD_DIR "${CPM_FETCHCONTENT_BASE_DIR}/${lower_case_name}-subbuild" + ${ARGN} + ) + else() + FetchContent_MakeAvailable(${PACKAGE}) + endif() + else() + FetchContent_Populate(${PACKAGE}) + endif() + set(${populated} + TRUE + PARENT_SCOPE + ) + endif() + + cpm_store_fetch_properties( + ${CPM_ARGS_NAME} ${${lower_case_name}_SOURCE_DIR} ${${lower_case_name}_BINARY_DIR} + ) + + set(${PACKAGE}_SOURCE_DIR + ${${lower_case_name}_SOURCE_DIR} + PARENT_SCOPE + ) + set(${PACKAGE}_BINARY_DIR + ${${lower_case_name}_BINARY_DIR} + PARENT_SCOPE + ) +endfunction() + +# splits a package option +function(cpm_parse_option OPTION) + string(REGEX MATCH "^[^ ]+" OPTION_KEY "${OPTION}") + string(LENGTH "${OPTION}" OPTION_LENGTH) + string(LENGTH "${OPTION_KEY}" OPTION_KEY_LENGTH) + if(OPTION_KEY_LENGTH STREQUAL OPTION_LENGTH) + # no value for key provided, assume user wants to set option to "ON" + set(OPTION_VALUE "ON") + else() + math(EXPR OPTION_KEY_LENGTH "${OPTION_KEY_LENGTH}+1") + string(SUBSTRING "${OPTION}" "${OPTION_KEY_LENGTH}" "-1" OPTION_VALUE) + endif() + set(OPTION_KEY + "${OPTION_KEY}" + PARENT_SCOPE + ) + set(OPTION_VALUE + "${OPTION_VALUE}" + PARENT_SCOPE + ) +endfunction() + +# guesses the package version from a git tag +function(cpm_get_version_from_git_tag GIT_TAG RESULT) + string(LENGTH ${GIT_TAG} length) + if(length EQUAL 40) + # GIT_TAG is probably a git hash + set(${RESULT} + 0 + PARENT_SCOPE + ) + else() + string(REGEX MATCH "v?([0123456789.]*).*" _ ${GIT_TAG}) + set(${RESULT} + ${CMAKE_MATCH_1} + PARENT_SCOPE + ) + endif() +endfunction() + +# guesses if the git tag is a commit hash or an actual tag or a branch name. +function(cpm_is_git_tag_commit_hash GIT_TAG RESULT) + string(LENGTH "${GIT_TAG}" length) + # full hash has 40 characters, and short hash has at least 7 characters. + if(length LESS 7 OR length GREATER 40) + set(${RESULT} + 0 + PARENT_SCOPE + ) + else() + if(${GIT_TAG} MATCHES "^[a-fA-F0-9]+$") + set(${RESULT} + 1 + PARENT_SCOPE + ) + else() + set(${RESULT} + 0 + PARENT_SCOPE + ) + endif() + endif() +endfunction() + +function(cpm_prettify_package_arguments OUT_VAR IS_IN_COMMENT) + set(oneValueArgs + NAME + FORCE + VERSION + GIT_TAG + DOWNLOAD_ONLY + GITHUB_REPOSITORY + GITLAB_REPOSITORY + BITBUCKET_REPOSITORY + GIT_REPOSITORY + SOURCE_DIR + FIND_PACKAGE_ARGUMENTS + NO_CACHE + SYSTEM + GIT_SHALLOW + EXCLUDE_FROM_ALL + SOURCE_SUBDIR + ) + set(multiValueArgs URL OPTIONS DOWNLOAD_COMMAND) + cmake_parse_arguments(CPM_ARGS "" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) + + foreach(oneArgName ${oneValueArgs}) + if(DEFINED CPM_ARGS_${oneArgName}) + if(${IS_IN_COMMENT}) + string(APPEND PRETTY_OUT_VAR "#") + endif() + if(${oneArgName} STREQUAL "SOURCE_DIR") + string(REPLACE ${CMAKE_SOURCE_DIR} "\${CMAKE_SOURCE_DIR}" CPM_ARGS_${oneArgName} + ${CPM_ARGS_${oneArgName}} + ) + endif() + string(APPEND PRETTY_OUT_VAR " ${oneArgName} ${CPM_ARGS_${oneArgName}}\n") + endif() + endforeach() + foreach(multiArgName ${multiValueArgs}) + if(DEFINED CPM_ARGS_${multiArgName}) + if(${IS_IN_COMMENT}) + string(APPEND PRETTY_OUT_VAR "#") + endif() + string(APPEND PRETTY_OUT_VAR " ${multiArgName}\n") + foreach(singleOption ${CPM_ARGS_${multiArgName}}) + if(${IS_IN_COMMENT}) + string(APPEND PRETTY_OUT_VAR "#") + endif() + string(APPEND PRETTY_OUT_VAR " \"${singleOption}\"\n") + endforeach() + endif() + endforeach() + + if(NOT "${CPM_ARGS_UNPARSED_ARGUMENTS}" STREQUAL "") + if(${IS_IN_COMMENT}) + string(APPEND PRETTY_OUT_VAR "#") + endif() + string(APPEND PRETTY_OUT_VAR " ") + foreach(CPM_ARGS_UNPARSED_ARGUMENT ${CPM_ARGS_UNPARSED_ARGUMENTS}) + string(APPEND PRETTY_OUT_VAR " ${CPM_ARGS_UNPARSED_ARGUMENT}") + endforeach() + string(APPEND PRETTY_OUT_VAR "\n") + endif() + + set(${OUT_VAR} + ${PRETTY_OUT_VAR} + PARENT_SCOPE + ) + +endfunction() diff --git a/cmake/tools.cmake b/cmake/tools.cmake new file mode 100644 index 0000000..e165a3c --- /dev/null +++ b/cmake/tools.cmake @@ -0,0 +1,20 @@ +# tools.cmake — on-demand tool activation via `-DUSE_=`. + +# only activate tools for top level project +if(NOT PROJECT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR) + return() +endif() + +include(${CMAKE_CURRENT_LIST_DIR}/CPM.cmake) + +# enables sanitizers support using the `USE_SANITIZER` flag; available values are: Address, +# Memory, MemoryWithOrigins, Undefined, Thread, Leak, 'Address;Undefined' +if(USE_SANITIZER) + CPMAddPackage("gh:StableCoder/cmake-scripts#25.08") + include(${cmake-scripts_SOURCE_DIR}/sanitizers.cmake) +endif() + +# enables CCACHE support through the USE_CCACHE flag; possible values are: YES, NO or equivalent +if(USE_CCACHE) + CPMAddPackage("gh:TheLartians/Ccache.cmake@1.2.4") +endif() diff --git a/include/spdlogconfig/SPDLOGConfig.h b/include/spdlogconfig/SPDLOGConfig.h new file mode 100644 index 0000000..4d51488 --- /dev/null +++ b/include/spdlogconfig/SPDLOGConfig.h @@ -0,0 +1,1111 @@ +#ifndef SPFLOGCONFIG_H +#define SPFLOGCONFIG_H + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include + +#include "spdlogconfig/SPDLOGConfigError.h" + +#if __has_include() +#include "spdlog/sinks/kafka_sink.h" +#endif +#if __has_include() +#include "spdlog/sinks/mongo_sink.h" +#endif +#ifndef _WIN32 +#include "spdlog/sinks/syslog_sink.h" +#include +#endif +#ifdef _WIN32 +#include "spdlog/sinks/msvc_sink.h" +#endif +#include "spdlog/async_logger.h" +#include "spdlog/common.h" +#include "spdlog/sinks/basic_file_sink.h" +#include "spdlog/sinks/daily_file_sink.h" +#include "spdlog/sinks/null_sink.h" +#include "spdlog/sinks/rotating_file_sink.h" +#include "spdlog/sinks/stdout_color_sinks.h" +#include "spdlog/sinks/stdout_sinks.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace spdlogconfig { + +namespace defaults { +/** Default async overflow policy for spdlog's async loggers. */ +static constexpr auto ASYNC_OVERFLOW_POLICY = + spdlog::async_overflow_policy::block; + +/** Default global thread pool queue size. */ +static constexpr auto THREAD_POOL_QUEUE_SIZE = 8192; + +/** Default global thread pool thread count. */ +static constexpr auto THREAD_POOL_NUM_THREADS = 1; + +/** Default maximum number of rotated log files to keep. */ +static constexpr auto MAX_FILES = 10; + +/** Default maximum file size for rotating sinks, expressed as a string. */ +static constexpr auto MAX_SIZE = "10485760"; + +/** Default truncate behavior for file sinks. */ +static constexpr auto TRUNCATE = false; + +/** Default logger type ("sync" or "async"). */ +static constexpr auto DEFAULT_LOGGER_TYPE = "sync"; + +/** Default overflow policy name used in configuration. */ +static constexpr auto OVERRUN_OLDEST = "overrun_oldest"; + +/** Default async overflow policy implementation used when not specified. */ +static constexpr auto OVERFLOW_POLICY = + spdlog::async_overflow_policy::overrun_oldest; + +/** Default rotation time for daily sinks (HH:MM). */ +static constexpr auto ROTATION_TIME = "00:00"; + +/** Default syslog ident string. */ +static constexpr auto IDENT = ""; + +/** Default flag indicating whether to create parent directories for log files. + */ +static constexpr auto CREATE_PARENT_DIR = false; + +#ifndef _WIN32 +/** Default syslog facility (non-Windows). */ +static constexpr auto SYSLOG_FACILITY = LOG_USER; + +/** Default syslog option flags (non-Windows). */ +static constexpr auto SYSLOG_OPTION = 0; +#endif +} // namespace defaults + +namespace names { +static constexpr auto LOGGER_CONFIG = "loggers"; +static constexpr auto PATTERN_CONFIG = "patterns"; +static constexpr auto SINK_CONFIG = "sinks"; +static constexpr auto THREAD_POOL_CONFIG = "thread_pool"; + +static constexpr auto ASYNC = "async"; +static constexpr auto SYNC = "sync"; +static constexpr auto BASE_FILENAME = "base_file_name"; +static constexpr auto BLOCK = "block"; +static constexpr auto CREATE_PARENT_DIR = "create_parent_dir"; +static constexpr auto FILENAME = "file_name"; +static constexpr auto GLOBAL_PATTERN = "global_pattern"; +static constexpr auto IDENT = "ident"; +static constexpr auto LEVEL = "level"; +static constexpr auto MAX_FILES = "max_files"; +static constexpr auto MAX_SIZE = "max_size"; +static constexpr auto NAME = "name"; +static constexpr auto THREAD_COUNT = "thread_count"; +static constexpr auto OVERRUN_OLDEST = "overrun_oldest"; +static constexpr auto OVERFLOW_POLICY = "overflow_policy"; +static constexpr auto PATTERN = "pattern"; +static constexpr auto QUEUE_SIZE = "queue_size"; +static constexpr auto ROTATION_TIME = "rotation_time"; +static constexpr auto SINKS = "sinks"; +static constexpr auto TYPE = "type"; +static constexpr auto VALUE = "value"; +} // namespace names + +namespace utils { + +/** + * Convert a human-friendly max-size string into bytes. + * Supports optional suffix multipliers: K, M, G, T (base 1024). + */ +inline auto GetMaxSizeInt(const std::string &maxSizeString) -> size_t { + std::string s = maxSizeString; + auto const not_space = [](unsigned char ch) { return !std::isspace(ch); }; + s.erase(s.begin(), std::find_if(s.begin(), s.end(), not_space)); + s.erase(std::find_if(s.rbegin(), s.rend(), not_space).base(), s.end()); + if (s.empty()) { + return 0U; + } + + auto const lastChar = s.back(); + std::size_t maxSizeInt{}; + if (std::string{"TGMK"}.find(lastChar) != std::string::npos) { + auto const prefixStr = s.substr(0, s.size() - 1); + maxSizeInt = std::stoi(prefixStr); + constexpr std::size_t kilo = 1024; + constexpr std::size_t mega = kilo * kilo; + constexpr std::size_t giga = mega * kilo; + constexpr std::size_t tera = giga * kilo; + switch (lastChar) { + case 'T': + maxSizeInt *= tera; + break; + case 'G': + maxSizeInt *= giga; + break; + case 'M': + maxSizeInt *= mega; + break; + case 'K': + maxSizeInt *= kilo; + break; + default: + break; + } + } else { + maxSizeInt = std::stoi(s); + } + return maxSizeInt; +} + +/** + * Convert a string level name + * ("trace","debug","info","warn","err","critical","off") to the corresponding + * spdlog level enum. + * + * @throws std::invalid_argument if the name is unknown. + */ +inline spdlog::level::level_enum levelFromString(const std::string &name) { + const auto lvl = spdlog::level::from_str(name); + // spdlog::level::from_str returns off (6) for unknown names; distinguish + // a genuine "off" request from an invalid name. + if (lvl == spdlog::level::off && name != "off") { + throw std::invalid_argument("Unknown log level: '" + name + "'"); + } + return lvl; +} + +} // namespace utils + +// --------------------------------------------------------------------------- +// Log-level enum (mirrors spdlog levels for JSON configuration parsing) +// --------------------------------------------------------------------------- +enum class spdlog_lvl_enum { + trace = spdlog::level::level_enum::trace, + debug = spdlog::level::level_enum::debug, + info = spdlog::level::level_enum::info, + warn = spdlog::level::level_enum::warn, + err = spdlog::level::level_enum::err, + critical = spdlog::level::level_enum::critical, + off = spdlog::level::level_enum::off, + n_levels +}; + +// --------------------------------------------------------------------------- +// Sink type enum +// --------------------------------------------------------------------------- +enum class spdlog_sink_types_enum { + stdout_sink_st, + stdout_sink_mt, + stderr_sink_st, + stderr_sink_mt, + stdout_color_sink_st, + stdout_color_sink_mt, + stderr_color_sink_st, + stderr_color_sink_mt, + basic_file_sink_st, + basic_file_sink_mt, + rotating_file_sink_st, + rotating_file_sink_mt, + daily_file_sink_st, + daily_file_sink_mt, + null_sink_st, + null_sink_mt, + android_sink_mt, + android_sink_st, + callback_sink_mt, + callback_sink_st, + dist_sink_mt, + dist_sink_st, + dup_filter_sink_mt, + dup_filter_sink_st, + hourly_file_sink_mt, + hourly_file_sink_st, + kafka_sink_mt, + kafka_sink_st, + mongo_sink_mt, + mongo_sink_st, + ostream_sink_mt, + ostream_sink_st, + ringbuffer_sink_mt, + ringbuffer_sink_st, + syslog_sink_mt, + syslog_sink_st, + msvc_sink_mt, + msvc_sink_st, + tcp_sink_mt, + tcp_sink_st, + udp_sink_mt, + udp_sink_st +}; + +// --------------------------------------------------------------------------- +// Validators +// --------------------------------------------------------------------------- +using vMinute = rfl::Validator, rfl::Maximum<59>>; +using vHour = rfl::Validator, rfl::Maximum<23>>; +using vThreadCount = + rfl::Validator, rfl::Maximum<100>>; +using vThreadQueue = + rfl::Validator, rfl::Maximum<409600>>; +using vMaxSize = rfl::Validator< + std::string, + rfl::PatternValidator>; +using vRotationTime = rfl::Validator< + std::string, + rfl::PatternValidator>; + +// --------------------------------------------------------------------------- +// Configuration structures +// --------------------------------------------------------------------------- +struct spdlog_sinks_types_t { + rfl::Rename<"name", std::string> m_sink_name; + rfl::Rename<"type", spdlog_sink_types_enum> m_sink_type; + rfl::Rename<"filename", std::optional> m_file_name; + rfl::Rename<"base_filename", std::optional> + m_base_file_name; + rfl::Rename<"level", std::optional> m_level; + rfl::Rename<"truncate", std::optional> m_truncate = defaults::TRUNCATE; + rfl::Rename<"max_size", std::optional> m_max_size = + defaults::MAX_SIZE; + rfl::Rename<"max_files", std::optional> m_max_files = + defaults::MAX_FILES; + rfl::Rename<"rotation_time", std::optional>> + m_rotation_time; + rfl::Rename<"create_parent_dir", std::optional> m_create_parent_dir = + defaults::CREATE_PARENT_DIR; +#ifndef _WIN32 + rfl::Rename<"ident", std::optional> m_syslog_ident = + defaults::IDENT; + rfl::Rename<"syslog_option", std::optional> m_syslog_option = + defaults::SYSLOG_OPTION; + rfl::Rename<"syslog_facility", std::optional> m_syslog_facility = + LOG_USER; +#endif +}; + +struct spdlog_patterns_t { + rfl::Rename<"name", std::optional> m_pattern_name; + rfl::Rename<"value", std::optional> m_pattern_value; +}; + +struct spdlog_threadpool_t { + rfl::Rename<"name", std::string> m_name; + rfl::Rename<"num_threads", vThreadCount> m_thread_count = + defaults::THREAD_POOL_NUM_THREADS; + rfl::Rename<"queue_size", vThreadQueue> m_queue_size = + defaults::THREAD_POOL_QUEUE_SIZE; +}; + +struct spdlog_loggers_t { + rfl::Rename<"level", std::optional> m_logger_level; + rfl::Rename<"name", std::string> m_logger_name; + rfl::Rename<"sinks", std::vector> m_logger_sinks; + rfl::Rename<"pattern", std::optional> m_logger_pattern; + rfl::Rename<"type", std::optional> m_logger_type = + defaults::DEFAULT_LOGGER_TYPE; + rfl::Rename<"overflow_policy", std::optional> + m_overflow_policy = defaults::OVERFLOW_POLICY; + rfl::Rename<"thread_pool", std::optional> m_thread_pool; +}; + +struct spdlog_global_threadpool_t { + rfl::Rename<"num_threads", vThreadCount> m_thread_count = + defaults::THREAD_POOL_NUM_THREADS; + rfl::Rename<"queue_size", vThreadQueue> m_queue_size = + defaults::THREAD_POOL_QUEUE_SIZE; +}; + +struct spdlog_conf_t { + rfl::Rename<"sink", std::vector> m_sinks; + rfl::Rename<"pattern", std::vector> m_patterns; + rfl::Rename<"logger", std::vector> m_loggers; + rfl::Rename<"thread_pools", std::vector> m_thread_pools; + rfl::Rename<"global_pattern", std::string> m_global_pattern; + rfl::Rename<"global_thread_pool", spdlog_global_threadpool_t> + m_global_thread_pool; +}; + +// =========================================================================== +// LevelManager — runtime log-level control +// =========================================================================== +/** + * @brief Singleton manager for runtime log-level changes. + * + * Provides thread-safe helpers to change the log level of any registered + * spdlog logger (and optionally all its sinks) at runtime, without + * restarting the application or reloading the JSON configuration. + * + * Usage: + * @code + * // Change a single named logger (logger + all its sinks): + * spdlogconfig::LevelManager::instance().setLoggerLevel("my_logger", + * spdlog::level::debug); + * + * // Change by string name (convenience overload): + * spdlogconfig::LevelManager::instance().setLoggerLevel("my_logger", "warn"); + * + * // Change all registered loggers at once: + * spdlogconfig::LevelManager::instance().setAllLoggersLevel(spdlog::level::trace); + * + * // Restore the level that was active when setupFrom() was called: + * spdlogconfig::LevelManager::instance().resetLoggerLevel("my_logger"); + * + * // Restore all loggers to their initial levels: + * spdlogconfig::LevelManager::instance().resetAllLoggers(); + * + * // Query the current level of a logger: + * auto lvl = + * spdlogconfig::LevelManager::instance().getLoggerLevel("my_logger"); + * @endcode + */ +class LevelManager { +public: + /** Returns the single process-wide instance. */ + static LevelManager &instance() { + static LevelManager inst; + return inst; + } + + // Non-copyable / non-movable + LevelManager(const LevelManager &) = delete; + LevelManager &operator=(const LevelManager &) = delete; + + // ------------------------------------------------------------------- + // Called by setupFrom() to record initial levels + // ------------------------------------------------------------------- + /** @internal Records the initial level for a logger (called by setupFrom). */ + void registerInitialLevel(const std::string &loggerName, + spdlog::level::level_enum level) { + std::unique_lock lock(m_mutex); + m_initialLevels[loggerName] = level; + } + + // ------------------------------------------------------------------- + // Set level — logger + all sinks + // ------------------------------------------------------------------- + /** + * @brief Set the log level of a named logger and propagate to all its sinks. + * + * Both the logger's own filter level and every attached sink's level are + * updated, so the change takes immediate effect for all output targets. + * + * @param loggerName Name as registered with spdlog. + * @param level New spdlog level. + * @throws std::runtime_error if the logger is not found. + */ + void setLoggerLevel(const std::string &loggerName, + spdlog::level::level_enum level) { + auto logger = spdlog::get(loggerName); + if (!logger) { + throw std::runtime_error("LevelManager: logger '" + loggerName + + "' not found."); + } + // Update the logger's own level + logger->set_level(level); + // Propagate to every sink attached to this logger + for (auto &sink : logger->sinks()) { + sink->set_level(level); + } + // Keep an audit record of the last explicitly set level + std::unique_lock lock(m_mutex); + m_currentLevels[loggerName] = level; + } + + /** + * @brief String-based convenience overload. + * + * Accepts level names: "trace", "debug", "info", "warn", "err", + * "critical", "off" (case-sensitive, matching spdlog conventions). + * + * @throws std::invalid_argument if the level string is unknown. + * @throws std::runtime_error if the logger is not found. + */ + void setLoggerLevel(const std::string &loggerName, + const std::string &levelName) { + setLoggerLevel(loggerName, utils::levelFromString(levelName)); + } + + // ------------------------------------------------------------------- + // Set level — only the logger filter (sinks keep their individual levels) + // ------------------------------------------------------------------- + /** + * @brief Set only the logger-level filter, leaving individual sink levels + * untouched. + * + * Useful when sinks have intentionally different granularities (e.g. a file + * sink at trace, a console sink at warn) and you only want to widen/narrow + * what the logger forwards to them. + * + * @param loggerName Name as registered with spdlog. + * @param level New spdlog level. + * @throws std::runtime_error if the logger is not found. + */ + void setLoggerLevelOnly(const std::string &loggerName, + spdlog::level::level_enum level) { + auto logger = spdlog::get(loggerName); + if (!logger) { + throw std::runtime_error("LevelManager: logger '" + loggerName + + "' not found."); + } + logger->set_level(level); + std::unique_lock lock(m_mutex); + m_currentLevels[loggerName] = level; + } + + // ------------------------------------------------------------------- + // Set level — all registered loggers + // ------------------------------------------------------------------- + /** + * @brief Apply a new level to **every** logger currently registered with + * spdlog (including their sinks). + * + * @param level New spdlog level. + */ + void setAllLoggersLevel(spdlog::level::level_enum level) { + spdlog::apply_all([&](std::shared_ptr logger) { + logger->set_level(level); + for (auto &sink : logger->sinks()) { + sink->set_level(level); + } + std::unique_lock lock(m_mutex); + m_currentLevels[logger->name()] = level; + }); + } + + /** + * @brief String-based overload of setAllLoggersLevel(). + * @throws std::invalid_argument if the level string is unknown. + */ + void setAllLoggersLevel(const std::string &levelName) { + setAllLoggersLevel(utils::levelFromString(levelName)); + } + + // ------------------------------------------------------------------- + // Reset to initial / configured levels + // ------------------------------------------------------------------- + /** + * @brief Restore a logger's level (and its sinks) to the level that was + * active immediately after setupFrom() completed. + * + * @param loggerName Name as registered with spdlog. + * @throws std::runtime_error if the logger or its initial level is not found. + */ + void resetLoggerLevel(const std::string &loggerName) { + spdlog::level::level_enum initial{}; + { + std::shared_lock lock(m_mutex); + auto it = m_initialLevels.find(loggerName); + if (it == m_initialLevels.end()) { + throw std::runtime_error( + "LevelManager: no initial level recorded for logger '" + + loggerName + "'."); + } + initial = it->second; + } + setLoggerLevel(loggerName, initial); + } + + /** + * @brief Restore **all** loggers to their initial post-setupFrom() levels. + */ + void resetAllLoggers() { + std::unordered_map snapshot; + { + std::shared_lock lock(m_mutex); + snapshot = m_initialLevels; + } + for (const auto &[name, level] : snapshot) { + auto logger = spdlog::get(name); + if (logger) { + logger->set_level(level); + for (auto &sink : logger->sinks()) { + sink->set_level(level); + } + } + } + std::unique_lock lock(m_mutex); + m_currentLevels = m_initialLevels; + } + + // ------------------------------------------------------------------- + // Query + // ------------------------------------------------------------------- + /** + * @brief Return the current level of a named logger. + * + * Reads directly from the live spdlog logger object (not the audit map), + * so it always reflects reality even if the level was changed via spdlog + * directly. + * + * @param loggerName Name as registered with spdlog. + * @return Current spdlog::level::level_enum. + * @throws std::runtime_error if the logger is not found. + */ + [[nodiscard]] spdlog::level::level_enum + getLoggerLevel(const std::string &loggerName) const { + auto logger = spdlog::get(loggerName); + if (!logger) { + throw std::runtime_error("LevelManager: logger '" + loggerName + + "' not found."); + } + return logger->level(); + } + + /** + * @brief Return the level that was set when setupFrom() completed for the + * given logger. + * + * @param loggerName Name as registered with spdlog. + * @return Initial spdlog::level::level_enum. + * @throws std::runtime_error if no initial level was recorded. + */ + [[nodiscard]] spdlog::level::level_enum + getInitialLoggerLevel(const std::string &loggerName) const { + std::shared_lock lock(m_mutex); + auto it = m_initialLevels.find(loggerName); + if (it == m_initialLevels.end()) { + throw std::runtime_error( + "LevelManager: no initial level recorded for logger '" + loggerName + + "'."); + } + return it->second; + } + + // ------------------------------------------------------------------- + // Config-file path — set once by setupFrom(), read by setupFromReload() + // ------------------------------------------------------------------- + /** @internal Called by setupFrom() to remember the config file path. */ + void registerConfigFile(const std::string &path) { + std::unique_lock lock(m_mutex); + if (m_configFilePath.empty()) { // only the first call wins + m_configFilePath = path; + } + } + + /** + * @brief Returns the path of the JSON file that was passed to the first + * setupFrom() call, so that setupFromReload() knows what to reload. + * + * @throws std::runtime_error if setupFrom() has not been called yet. + */ + [[nodiscard]] std::string configFilePath() const { + std::shared_lock lock(m_mutex); + if (m_configFilePath.empty()) { + throw std::runtime_error( + "LevelManager: setupFrom() has not been called yet — " + "no config file path is registered."); + } + return m_configFilePath; + } + +private: + LevelManager() = default; + + mutable std::shared_mutex m_mutex; + std::string m_configFilePath; ///< path from first setupFrom() + std::unordered_map m_initialLevels; + std::unordered_map m_currentLevels; +}; + +// =========================================================================== +// setupFrom +// =========================================================================== +/** + * @brief Configure spdlog from a JSON configuration file. + * + * After all loggers are registered, each logger's level is recorded in the + * process-wide LevelManager so that runtime resets are possible. + * + * @param file Path to the JSON configuration file. + */ +inline void setupFrom(std::string const &file) { + // Remember the path for setupFromReload() — only the very first call wins. + LevelManager::instance().registerConfigFile(file); + + try { + std::ifstream file_stream(file, std::ios::binary); + if (!file_stream.is_open()) { + throw spdlogconfig_error("Unable to open configuration file: " + file); + } + std::stringstream pre_json_ss; + pre_json_ss << file_stream.rdbuf(); + + auto spdlogConfig = + rfl::json::read( + pre_json_ss) + .value(); + + // Create global thread pool + spdlog::init_thread_pool( + spdlogConfig.m_global_thread_pool.value().m_queue_size.value().value(), + spdlogConfig.m_global_thread_pool.value() + .m_thread_count.value() + .value()); + + for (const auto &logger_item : spdlogConfig.m_loggers.value()) { + auto sinkList = std::vector{}; + + for (const auto &sinks_item : logger_item.m_logger_sinks.value()) { + for (const auto &sink_log_item : spdlogConfig.m_sinks.value()) { + if (sink_log_item.m_sink_name.value() == sinks_item) { + using enum spdlogconfig::spdlog_sink_types_enum; + + // Helper lambda to compute the effective sink level + auto effectiveLevel = [&]() -> spdlog::level::level_enum { + return sink_log_item.m_level.value().has_value() + ? static_cast( + sink_log_item.m_level.value().value()) + : static_cast( + logger_item.m_logger_level.value().value()); + }; + + switch (sink_log_item.m_sink_type.value()) { + case stdout_sink_st: + sinkList + .emplace_back( + std::make_shared()) + ->set_level(effectiveLevel()); + break; + case stdout_sink_mt: + sinkList + .emplace_back( + std::make_shared()) + ->set_level(effectiveLevel()); + break; + case stderr_sink_st: + sinkList + .emplace_back( + std::make_shared()) + ->set_level(effectiveLevel()); + break; + case stderr_sink_mt: + sinkList + .emplace_back( + std::make_shared()) + ->set_level(effectiveLevel()); + break; + case stdout_color_sink_st: + sinkList + .emplace_back( + std::make_shared()) + ->set_level(effectiveLevel()); + break; + case stdout_color_sink_mt: + sinkList + .emplace_back( + std::make_shared()) + ->set_level(effectiveLevel()); + break; + case stderr_color_sink_st: + sinkList + .emplace_back( + std::make_shared()) + ->set_level(effectiveLevel()); + break; + case stderr_color_sink_mt: + sinkList + .emplace_back( + std::make_shared()) + ->set_level(effectiveLevel()); + break; + case basic_file_sink_st: + if (sink_log_item.m_create_parent_dir.value()) { + std::filesystem::create_directories( + sink_log_item.m_file_name.value().value().parent_path()); + } + sinkList + .emplace_back( + std::make_shared( + sink_log_item.m_file_name.value() + .value() + .generic_string(), + sink_log_item.m_truncate.value().value())) + ->set_level(effectiveLevel()); + break; + case basic_file_sink_mt: + if (sink_log_item.m_create_parent_dir.value()) { + std::filesystem::create_directories( + sink_log_item.m_file_name.value().value().parent_path()); + } + sinkList + .emplace_back( + std::make_shared( + sink_log_item.m_file_name.value() + .value() + .generic_string(), + sink_log_item.m_truncate.value().value())) + ->set_level(effectiveLevel()); + break; + case rotating_file_sink_st: + if (sink_log_item.m_create_parent_dir.value()) { + std::filesystem::create_directories( + sink_log_item.m_base_file_name.value() + .value() + .parent_path()); + } + sinkList + .emplace_back( + std::make_shared( + sink_log_item.m_base_file_name.value() + .value() + .generic_string(), + utils::GetMaxSizeInt( + sink_log_item.m_max_size.value()->value()), + sink_log_item.m_max_files.value().value())) + ->set_level(effectiveLevel()); + break; + case rotating_file_sink_mt: + if (sink_log_item.m_create_parent_dir.value()) { + std::filesystem::create_directories( + sink_log_item.m_base_file_name.value() + .value() + .parent_path()); + } + sinkList + .emplace_back( + std::make_shared( + sink_log_item.m_base_file_name.value() + .value() + .generic_string(), + utils::GetMaxSizeInt( + sink_log_item.m_max_size.get()->value()), + sink_log_item.m_max_files.value().value())) + ->set_level(effectiveLevel()); + break; + case daily_file_sink_st: { + if (sink_log_item.m_create_parent_dir.value()) { + std::filesystem::create_directories( + sink_log_item.m_base_file_name.value() + .value() + .parent_path()); + } + sinkList + .emplace_back(std::make_shared< + spdlog::sinks::daily_file_sink_st>( + sink_log_item.m_base_file_name.value() + .value() + .generic_string(), + sink_log_item.m_rotation_time.value() + .value() + .tm() + .tm_hour, + sink_log_item.m_rotation_time.value().value().tm().tm_min, + sink_log_item.m_truncate.value().value())) + ->set_level(effectiveLevel()); + break; + } + case daily_file_sink_mt: { + if (sink_log_item.m_create_parent_dir.value()) { + std::filesystem::create_directories( + sink_log_item.m_base_file_name.value() + .value() + .parent_path()); + } + sinkList + .emplace_back(std::make_shared< + spdlog::sinks::daily_file_sink_mt>( + sink_log_item.m_base_file_name.value() + .value() + .generic_string(), + sink_log_item.m_rotation_time.value() + .value() + .tm() + .tm_hour, + sink_log_item.m_rotation_time.value().value().tm().tm_min, + sink_log_item.m_truncate.value().value())) + ->set_level(effectiveLevel()); + break; + } + case null_sink_st: + sinkList + .emplace_back(std::make_shared()) + ->set_level(effectiveLevel()); + break; + case null_sink_mt: + sinkList + .emplace_back(std::make_shared()) + ->set_level(effectiveLevel()); + break; +#ifdef __ANDROID__ + case android_sink_st: + sinkList + .emplace_back( + std::make_shared()) + ->set_level(effectiveLevel()); + break; + case android_sink_mt: + sinkList + .emplace_back( + std::make_shared()) + ->set_level(effectiveLevel()); + break; +#endif +#ifndef _WIN32 + case syslog_sink_st: + sinkList + .emplace_back(std::make_shared( + sink_log_item.m_syslog_ident.value()->c_str(), + sink_log_item.m_syslog_option.value().value(), + sink_log_item.m_syslog_facility.value().value(), true)) + ->set_level(effectiveLevel()); + break; + case syslog_sink_mt: + sinkList + .emplace_back(std::make_shared( + sink_log_item.m_syslog_ident.value()->c_str(), + sink_log_item.m_syslog_option.value().value(), + sink_log_item.m_syslog_facility.value().value(), true)) + ->set_level(effectiveLevel()); + break; +#endif +#ifdef _WIN32 + case msvc_sink_st: + sinkList + .emplace_back(std::make_shared()) + ->set_level(effectiveLevel()); + break; + case msvc_sink_mt: + sinkList + .emplace_back(std::make_shared()) + ->set_level(effectiveLevel()); + break; +#endif + default: + break; + } + } + } + } + + // Build the logger (sync or async) + std::shared_ptr logger; + if (logger_item.m_logger_type.value() == names::SYNC) { + logger = std::make_shared( + logger_item.m_logger_name.value(), begin(sinkList), end(sinkList)); + } else if (logger_item.m_logger_type.value() == names::ASYNC) { + if (logger_item.m_thread_pool.value().has_value()) { + static std::shared_ptr threadPoolPtr; + for (const auto &thread_pool_item : + spdlogConfig.m_thread_pools.value()) { + if (thread_pool_item.m_name.value() == + logger_item.m_thread_pool.value().value()) { + threadPoolPtr = std::make_shared( + thread_pool_item.m_queue_size.value().value(), + thread_pool_item.m_thread_count.value().value()); + break; + } + } + if (!threadPoolPtr) { + throw spdlogconfig_error( + "Error: Thread Pool not found for logger " + + logger_item.m_logger_name.value()); + } + logger = std::make_shared( + logger_item.m_logger_name.value().c_str(), begin(sinkList), + end(sinkList), std::move(threadPoolPtr), + logger_item.m_overflow_policy.value().value()); + } else { + auto globalPool = spdlog::thread_pool(); + if (!globalPool) { + throw spdlogconfig_error( + "Error: Global Thread Pool not available."); + } + logger = std::make_shared( + logger_item.m_logger_name.value().c_str(), begin(sinkList), + end(sinkList), globalPool, + logger_item.m_overflow_policy.value().value()); + } + } + + const auto configuredLevel = static_cast( + logger_item.m_logger_level.value().value()); + logger->set_level(configuredLevel); + + try { + if (logger_item.m_logger_pattern.value().has_value()) { + for (const auto &pattern_item : spdlogConfig.m_patterns.value()) { + if (pattern_item.m_pattern_name.value()->c_str() == + logger_item.m_logger_pattern.value()->c_str()) { + logger->set_pattern( + pattern_item.m_pattern_value.value()->c_str()); + } + } + } else { + logger->set_pattern(spdlogConfig.m_global_pattern.value().c_str()); + } + } catch (const spdlog::spdlog_ex &e) { + throw spdlogconfig_error( + std::format("Error setting pattern to logger '{}' : {} ", + logger_item.m_logger_name.value().c_str(), e.what())); + } + + spdlog::register_logger(logger); + + // ---- NEW: record the initial level in the LevelManager ---- + LevelManager::instance().registerInitialLevel( + logger_item.m_logger_name.value(), configuredLevel); + } + + } catch (const rfl::Error &ex) { + std::cerr << "reflect-cpp error: " << ex.what(); + } catch (const std::filesystem::filesystem_error &ex) { + std::cout << "what(): " << ex.what() << '\n' + << "path1(): " << ex.path1() << '\n' + << "path2(): " << ex.path2() << '\n' + << "code().value(): " << ex.code().value() << '\n' + << "code().message(): " << ex.code().message() << '\n' + << "code().category(): " << ex.code().category().name() << '\n'; + } catch (const spdlog::spdlog_ex &ex) { + std::cout << "spdlog: " << ex.what() << '\n'; + } catch (const std::exception &ex) { + std::cout << "exception: " << ex.what() << '\n'; + } catch (...) { + std::cout << "uncaught exception" << '\n'; + } +} + +// =========================================================================== +// setupFromReload — reload log levels from the original config file at runtime +// =========================================================================== +/** + * @brief Reload log levels from the JSON file that was passed to the first + * setupFrom() call — without re-creating any loggers or sinks. + * + * Call this function whenever the JSON configuration file has been edited on + * disk and you want the new `level` values to take effect immediately, while + * the application is still running. + * + * **What is updated:** + * - The logger-level filter of every named logger that already exists in + * spdlog's registry. + * - The level of every sink attached to that logger (so the change propagates + * to all output targets). + * - The "initial level" stored in LevelManager (so a subsequent + * resetLoggerLevel() uses the freshly loaded value). + * + * **What is NOT touched:** + * - Sink types, filenames, patterns, thread pools — the full logger/sink graph + * remains exactly as built by the original setupFrom() call. + * + * @throws std::runtime_error if setupFrom() has not been called yet + * (i.e. no config file path is registered). + * @throws spdlogconfig_error if the config file cannot be opened or parsed. + * + * Usage: + * @code + * // Initial setup (remembers the path automatically): + * spdlogconfig::setupFrom("config/logging.json"); + * + * // ... later, after editing logging.json on disk: + * spdlogconfig::setupFromReload(); // picks up new levels, no path needed + * @endcode + */ +inline void setupFromReload() { + // Retrieve the path that was registered during the first setupFrom() call. + const std::string file = LevelManager::instance().configFilePath(); + + try { + std::ifstream file_stream(file, std::ios::binary); + if (!file_stream.is_open()) { + throw spdlogconfig_error( + "setupFromReload: Unable to open configuration file: " + file); + } + + std::stringstream ss; + ss << file_stream.rdbuf(); + + auto spdlogConfig = + rfl::json::read(ss) + .value(); + + auto &lm = LevelManager::instance(); + + for (const auto &logger_item : spdlogConfig.m_loggers.value()) { + const std::string &loggerName = logger_item.m_logger_name.value(); + + // Only update loggers that are already registered — never create new + // ones. + auto logger = spdlog::get(loggerName); + if (!logger) { + std::cerr << "setupFromReload: logger '" << loggerName + << "' not found in registry — skipping.\n"; + continue; + } + + // Determine the new logger-level from the JSON. + if (!logger_item.m_logger_level.value().has_value()) { + continue; // no level entry in JSON for this logger — leave as-is + } + + const auto newLevel = static_cast( + logger_item.m_logger_level.value().value()); + + // Update the logger filter. + logger->set_level(newLevel); + + // Update every attached sink. + // If a sink has its own level entry in the JSON, use that; otherwise + // fall back to the logger level — mirroring the logic in setupFrom(). + for (const auto &sinkName : logger_item.m_logger_sinks.value()) { + // Find the matching sink config to check for a sink-specific level. + for (const auto &sinkCfg : spdlogConfig.m_sinks.value()) { + if (sinkCfg.m_sink_name.value() != sinkName) { + continue; + } + + const auto sinkLevel = sinkCfg.m_level.value().has_value() + ? static_cast( + sinkCfg.m_level.value().value()) + : newLevel; + + // Apply to the matching live sink object (match by position in the + // sink list — sinks are added in the same order as m_logger_sinks). + // Because spdlog does not expose sinks by name, we apply the resolved + // level to all sinks; individual per-sink levels are honoured via the + // sink-config lookup above. + for (auto &liveSink : logger->sinks()) { + liveSink->set_level(sinkLevel); + } + break; + } + } + + // Refresh the "initial" level in LevelManager so that a future + // resetLoggerLevel() restores to the newly loaded value. + lm.registerInitialLevel(loggerName, newLevel); + + std::cout << "setupFromReload: logger '" << loggerName + << "' level updated to '" + << spdlog::level::to_string_view(newLevel).data() << "'\n"; + } + + } catch (const rfl::Error &ex) { + std::cerr << "setupFromReload reflect-cpp error: " << ex.what() << '\n'; + } catch (const std::exception &ex) { + std::cerr << "setupFromReload exception: " << ex.what() << '\n'; + } catch (...) { + std::cerr << "setupFromReload: uncaught exception\n"; + } +} + +} // namespace spdlogconfig + +#endif // SPFLOGCONFIG_H diff --git a/include/spdlogconfig/SPDLOGConfigError.h b/include/spdlogconfig/SPDLOGConfigError.h new file mode 100644 index 0000000..e5cc370 --- /dev/null +++ b/include/spdlogconfig/SPDLOGConfigError.h @@ -0,0 +1,56 @@ +#pragma once + +#include +#include + +namespace spdlogconfig { +// declaration section + +/** + * Setup error with a textual description. + * + * This exception type is used to report configuration and initialization + * failures within the spdlog configuration module. + */ +class spdlogconfig_error : public std::exception { +public: + /** + * Construct an error from a C-string message. + * + * @param msg Error message to store. + * @throw std::bad_alloc If memory allocation for the message fails. + */ + spdlogconfig_error(const char *const msg); + + /** + * Construct an error from a std::string message. + * + * @param msg Error message to store (moved into this object). + * @throw std::bad_alloc If memory allocation for the message fails. + */ + spdlogconfig_error(std::string msg); + + /** + * Retrieve the stored error message. + * + * @return Null-terminated error message string. + */ + auto what() const noexcept -> const char * override; + +private: + /** Stored error message text. */ + std::string msg; +}; + +// implementation section + +inline spdlogconfig_error::spdlogconfig_error(const char *const msg) + : msg(msg) {} + +inline spdlogconfig_error::spdlogconfig_error(std::string msg) + : msg(std::move(msg)) {} + +inline auto spdlogconfig_error::what() const noexcept -> const char * { + return msg.c_str(); +} +} // namespace spdlogconfig diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt new file mode 100644 index 0000000..6c2df37 --- /dev/null +++ b/test/CMakeLists.txt @@ -0,0 +1,30 @@ +cmake_minimum_required(VERSION 3.14 FATAL_ERROR) + +project(SPDLOGConfigTests LANGUAGES CXX) + +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin") +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib") +set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib") + +include(CTest) + +# ---- Dependencies ---- +CPMAddPackage("gh:doctest/doctest@2.5.2") + +file(GLOB sources CONFIGURE_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/source/*.cpp) + +add_executable(${PROJECT_NAME} ${sources}) +set_target_properties(${PROJECT_NAME} PROPERTIES CXX_STANDARD 20) + +target_link_libraries(${PROJECT_NAME} PRIVATE doctest::doctest SPDLOGConfig::SPDLOGConfig) + +if(CMAKE_CXX_COMPILER_ID MATCHES "Clang" OR CMAKE_CXX_COMPILER_ID MATCHES "GNU") + target_compile_options(${PROJECT_NAME} PRIVATE -Wall -Wpedantic -Wextra) +elseif(MSVC) + target_compile_options(${PROJECT_NAME} PRIVATE /W4) + target_compile_definitions(${PROJECT_NAME} PRIVATE DOCTEST_CONFIG_USE_STD_HEADERS) +endif() + +# ---- Register doctest test cases with CTest ---- +include(${doctest_SOURCE_DIR}/scripts/cmake/doctest.cmake) +doctest_discover_tests(${PROJECT_NAME}) diff --git a/test/full.json b/test/full.json new file mode 100644 index 0000000..8c8f851 --- /dev/null +++ b/test/full.json @@ -0,0 +1,159 @@ +{ + "global_pattern": "[%Y-%m-%dT%T%z] [%L] <%n>: %v", + "logger": [ + { + "level": "trace", + "name": "root", + "sinks": [ + "console_st", + "console_mt", + "color_console_st", + "color_console_mt", + "daily_out", + "daily_err", + "file_out", + "file_err", + "rotate_out", + "rotate_err", + "null_sink_st", + "null_sink_mt", + "syslog_st", + "syslog_mt", + "msvc_sink_st", + "msvc_sink_mt" + ] + }, + { + "level": "trace", + "name": "console", + "pattern": "succient", + "sinks": [ + "console_st", + "console_mt" + ] + }, + { + "level": "trace", + "name": "global_async", + "pattern": "succient", + "sinks": [ + "console_mt" + ], + "type": "async" + }, + { + "level": "trace", + "name": "local_async", + "overflow_policy": "overrun_oldest", + "pattern": "succient", + "sinks": [ + "console_mt" + ], + "thread_pool": "tp", + "type": "async" + } + ], + "pattern": [ + { + "name": "succient", + "value": "%c-%L: %v" + } + ], + "sink": [ + { + "name": "console_st", + "type": "stdout_sink_st" + }, + { + "name": "console_mt", + "type": "stdout_sink_mt" + }, + { + "name": "color_console_st", + "type": "stdout_color_sink_st" + }, + { + "name": "color_console_mt", + "type": "stdout_color_sink_mt" + }, + { + "create_parent_dir": true, + "filename": "log/spdlog_setup.log", + "level": "info", + "name": "file_out", + "type": "basic_file_sink_st" + }, + { + "filename": "log/spdlog_setup_err.log", + "level": "err", + "name": "file_err", + "truncate": true, + "type": "basic_file_sink_mt" + }, + { + "base_filename": "log/rotate_spdlog_setup.log", + "level": "info", + "max_files": 10, + "max_size": "1M", + "name": "rotate_out", + "type": "rotating_file_sink_st" + }, + { + "base_filename": "log/rotate_spdlog_setup_err.log", + "level": "err", + "max_files": 10, + "max_size": "1M", + "name": "rotate_err", + "type": "rotating_file_sink_mt" + }, + { + "base_filename": "log/daily_spdlog_setup.log", + "level": "info", + "name": "daily_out", + "rotation_time": "17:30", + "type": "daily_file_sink_st" + }, + { + "base_filename": "log/daily_spdlog_setup_err.log", + "level": "err", + "name": "daily_err", + "rotation_time": "17:30", + "type": "daily_file_sink_mt" + }, + { + "name": "null_sink_st", + "type": "null_sink_st" + }, + { + "name": "null_sink_mt", + "type": "null_sink_mt" + }, + { + "name": "syslog_st", + "type": "syslog_sink_st" + }, + { + "name": "syslog_mt", + "type": "syslog_sink_mt" + }, + { + "name": "msvc_sink_st", + "type": "msvc_sink_st" + }, + { + "name": "msvc_sink_mt", + "type": "msvc_sink_mt" + } + ], + "thread_pools": [ + { + "name": "tp", + "num_threads": 2, + "queue_size": 4096 + } + ], + "global_thread_pool": { + "num_threads": 1, + "queue_size": 8192 + } +} diff --git a/test/source/main.cpp b/test/source/main.cpp new file mode 100644 index 0000000..af24eeb --- /dev/null +++ b/test/source/main.cpp @@ -0,0 +1,3 @@ +#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN + +#include diff --git a/test/source/test_spdlogconfig.cpp b/test/source/test_spdlogconfig.cpp new file mode 100644 index 0000000..9b87de4 --- /dev/null +++ b/test/source/test_spdlogconfig.cpp @@ -0,0 +1,344 @@ +#include "spdlogconfig/SPDLOGConfig.h" +#include "spdlog/spdlog.h" + +#include + +#include +#include + +// ----------------------------------------------------------------------------- +// Test helpers +// ----------------------------------------------------------------------------- + +namespace { + +/** + * Build the path to `full.json` relative to this source file. + * + * Layout assumption: + * - This file lives in: .../test/source/spdlogconfig.cpp + * - `full.json` lives in: .../test/full.json + * + * @return Absolute/relative path string to `full.json`. + */ +inline std::string full_json_path() { + namespace fs = std::filesystem; + static const fs::path base = + fs::path(__FILE__).parent_path().parent_path(); // .../test + return (base / "full.json").string(); +} + +/** + * Common setup for tests that require a fully initialized spdlog configuration. + * + * Drops all existing loggers first to keep test cases independent. + */ +inline void setup_spdlog_from_full_json() { + spdlog::drop_all(); + spdlogconfig::setupFrom(full_json_path()); +} + +} // namespace + +// ----------------------------------------------------------------------------- +// Tests for full.json +// ----------------------------------------------------------------------------- + +TEST_SUITE("Tests for full.json") { + + TEST_CASE("full Setup") { + // Ensure this test is independent from others. + spdlog::drop_all(); + + SUBCASE("No loggers should be created yet.") { + CHECK(spdlog::get("root") == nullptr); + CHECK(spdlog::get("console") == nullptr); + CHECK(spdlog::get("global_async") == nullptr); + CHECK(spdlog::get("local_async") == nullptr); + } + + // Now load configuration. + spdlogconfig::setupFrom(full_json_path()); + + SUBCASE("All loggers should be created.") { + auto root = spdlog::get("root"); + auto console = spdlog::get("console"); + auto global_async = spdlog::get("global_async"); + auto local_async = spdlog::get("local_async"); + + CHECK(root != nullptr); + CHECK(console != nullptr); + CHECK(global_async != nullptr); + CHECK(local_async != nullptr); + } + } + + TEST_CASE("full Root logger") { + setup_spdlog_from_full_json(); + + auto logger = spdlog::get("root"); + REQUIRE(logger != nullptr); // avoid segfault + + SUBCASE("Root logger should have expected sinks") { + // JSON defines 16 sinks, but 2 are platform-specific (syslog or msvc) + // and may not be created -> effectively 14 sinks. + CHECK(logger->sinks().size() == 14); + } + + SUBCASE("Root logger's level should be trace.") { + CHECK(logger->level() == spdlog::level::level_enum::trace); + } + } + + TEST_CASE("Console logger") { + setup_spdlog_from_full_json(); + + auto logger_console = spdlog::get("console"); + REQUIRE(logger_console != nullptr); + + SUBCASE("Console logger should have two sinks.") { + CHECK(logger_console->sinks().size() == 2); + } + } + + TEST_CASE("Global async logger") { + setup_spdlog_from_full_json(); + + auto logger_global_async = spdlog::get("global_async"); + REQUIRE(logger_global_async != nullptr); + + SUBCASE("Global async logger should have only one sink.") { + CHECK(logger_global_async->sinks().size() == 1); + } + } + + TEST_CASE("Local async logger") { + setup_spdlog_from_full_json(); + + auto logger_local_async = spdlog::get("local_async"); + REQUIRE(logger_local_async != nullptr); + + SUBCASE("Local async logger should have only one sink.") { + CHECK(logger_local_async->sinks().size() == 1); + } + } + + // --------------------------------------------------------------------------- + // Additional tests: root logger sinks / file sinks / platform sinks + // --------------------------------------------------------------------------- + + TEST_CASE("Root logger sink configuration") { + setup_spdlog_from_full_json(); + + auto logger = spdlog::get("root"); + REQUIRE(logger != nullptr); + + auto &sinks = logger->sinks(); + + SUBCASE("basic_file_sinks have correct filenames and levels") { + std::shared_ptr file_out_sink; + std::shared_ptr file_err_sink; + + for (auto &s : sinks) { + auto as_st = + std::dynamic_pointer_cast(s); + if (as_st && + as_st->filename() == SPDLOG_FILENAME_T("log/spdlog_setup.log")) { + file_out_sink = as_st; + } + + auto as_mt = + std::dynamic_pointer_cast(s); + if (as_mt && as_mt->filename() == + SPDLOG_FILENAME_T("log/spdlog_setup_err.log")) { + file_err_sink = as_mt; + } + } + + CHECK(file_out_sink != nullptr); + CHECK(file_err_sink != nullptr); + + if (file_out_sink) { + CHECK(file_out_sink->level() == spdlog::level::info); + } + if (file_err_sink) { + CHECK(file_err_sink->level() == spdlog::level::err); + } + + // create_parent_dir=true -> "log" should exist + CHECK(std::filesystem::exists("log")); + CHECK(std::filesystem::is_directory("log")); + } + + SUBCASE("rotating_file_sinks have correct configuration") { + std::shared_ptr rotate_out_sink; + std::shared_ptr rotate_err_sink; + + for (auto &s : sinks) { + auto as_st = + std::dynamic_pointer_cast(s); + if (as_st && as_st->filename() == + SPDLOG_FILENAME_T("log/rotate_spdlog_setup.log")) { + rotate_out_sink = as_st; + } + + auto as_mt = + std::dynamic_pointer_cast(s); + if (as_mt && as_mt->filename() == + SPDLOG_FILENAME_T("log/rotate_spdlog_setup_err.log")) { + rotate_err_sink = as_mt; + } + } + + CHECK(rotate_out_sink != nullptr); + CHECK(rotate_err_sink != nullptr); + + const auto expected_size = + spdlogconfig::utils::GetMaxSizeInt("1M"); // from JSON + const std::size_t expected_files = 10; + + if (rotate_out_sink) { + CHECK(rotate_out_sink->get_max_size() == expected_size); + CHECK(rotate_out_sink->get_max_files() == expected_files); + CHECK(rotate_out_sink->level() == spdlog::level::info); + } + + if (rotate_err_sink) { + CHECK(rotate_err_sink->get_max_size() == expected_size); + CHECK(rotate_err_sink->get_max_files() == expected_files); + CHECK(rotate_err_sink->level() == spdlog::level::err); + } + } + + SUBCASE("Root logger has daily-file sinks") { + bool has_daily_st = false; + bool has_daily_mt = false; + + for (auto &s : sinks) { + if (std::dynamic_pointer_cast(s)) { + has_daily_st = true; + } + if (std::dynamic_pointer_cast(s)) { + has_daily_mt = true; + } + } + + CHECK(has_daily_st); + CHECK(has_daily_mt); + } + + SUBCASE("Null sinks exist") { + bool has_null_st = false; + bool has_null_mt = false; + + for (auto &s : sinks) { + if (std::dynamic_pointer_cast(s)) { + has_null_st = true; + } + if (std::dynamic_pointer_cast(s)) { + has_null_mt = true; + } + } + + CHECK(has_null_st); + CHECK(has_null_mt); + } + + SUBCASE("Platform-specific sinks exist") { +#ifndef _WIN32 + bool has_syslog_st = false; + bool has_syslog_mt = false; + + for (auto &s : sinks) { + if (dynamic_cast(s.get())) { + has_syslog_st = true; + } + if (dynamic_cast(s.get())) { + has_syslog_mt = true; + } + } + + CHECK(has_syslog_st); + CHECK(has_syslog_mt); +#else + bool has_msvc_mt = false; + + for (auto &s : sinks) { + if (dynamic_cast(s.get())) { + has_msvc_mt = true; + } + } + + CHECK(has_msvc_mt); +#endif + } + + SUBCASE("Console sinks inherit the logger level trace") { + for (auto &s : sinks) { + if (std::dynamic_pointer_cast(s) || + std::dynamic_pointer_cast(s) || + std::dynamic_pointer_cast(s) || + std::dynamic_pointer_cast(s)) { + CHECK(s->level() == spdlog::level::trace); + } + } + } + } + + // --------------------------------------------------------------------------- + // Additional tests: async logger & thread pool + // --------------------------------------------------------------------------- + + TEST_CASE("Async logger configuration and thread pool") { + setup_spdlog_from_full_json(); + + SUBCASE("Global thread pool is initialized") { + auto tp = spdlog::thread_pool(); + CHECK(tp != nullptr); + } + + SUBCASE("global_async and local_async are async_logger") { + auto global_async = spdlog::get("global_async"); + auto local_async = spdlog::get("local_async"); + + REQUIRE(global_async != nullptr); + REQUIRE(local_async != nullptr); + + auto as_global_async = + std::dynamic_pointer_cast(global_async); + auto as_local_async = + std::dynamic_pointer_cast(local_async); + + CHECK(as_global_async != nullptr); + CHECK(as_local_async != nullptr); + } + } +} + +// ----------------------------------------------------------------------------- +// Additional tests: utility functions +// ----------------------------------------------------------------------------- + +TEST_SUITE("spdlogconfig::utils") { + using spdlogconfig::utils::GetMaxSizeInt; + + TEST_CASE("GetMaxSizeInt without suffix") { + CHECK(GetMaxSizeInt("0") == static_cast(0)); + CHECK(GetMaxSizeInt("42") == static_cast(42)); + CHECK(GetMaxSizeInt("10485760") == static_cast(10485760)); + } + + TEST_CASE("GetMaxSizeInt with K/M/G/T suffix") { + CHECK(GetMaxSizeInt("1K") == static_cast(1024)); + CHECK(GetMaxSizeInt("2M") == static_cast(2 * 1024 * 1024)); + CHECK(GetMaxSizeInt("3G") == + static_cast(3ull * 1024 * 1024 * 1024)); + CHECK(GetMaxSizeInt("1T") == + static_cast(1ull * 1024 * 1024 * 1024 * 1024)); + } + + TEST_CASE("GetMaxSizeInt ignores whitespace around the number") { + CHECK(GetMaxSizeInt(" 1K") == static_cast(1024)); + CHECK(GetMaxSizeInt("2M ") == static_cast(2 * 1024 * 1024)); + } +}