diff --git a/CLAUDE.md b/CLAUDE.md index 00565fe..e42c386 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -47,7 +47,7 @@ or pin to a specific commit: `CPMAddPackage("gh:stlab/cpp-library#") - **`cpp-library.cmake`** (root) — entry point; defines `cpp_library_set_version()` and `cpp_library_enable_dependency_tracking()`, then includes the modules below. `cpp_library_enable_dependency_tracking()` must be called *before* `project()` — it registers `cpp-library-dependency-provider.cmake` via `CMAKE_PROJECT_TOP_LEVEL_INCLUDES` so CMake's dependency-provider hook (3.24+) is active for the `project()` call that follows. - **`cpp-library-setup.cmake`** — the core `cpp_library_setup(...)` function (called from `cpp-library.cmake`, which is why the module split doesn't map 1:1 to files: some logic that requires `project()` to already have run — install, docs, CI templating — is deferred and included lazily inside `cpp_library_setup()` rather than at top-level `include()` time). - **`cpp-library-install.cmake`** — install rules, package `Config.cmake`/`ConfigVersion.cmake` generation, and the `find_dependency()` derivation logic. Only `include()`d inside `cpp_library_setup()` (needs `project()` for `GNUInstallDirs`). -- **`cpp-library-dependency-provider.cmake`** — implements the CMake dependency-provider callback (`SET_DEPENDENCY_PROVIDER`) that intercepts every `find_package()`/`FetchContent_MakeAvailable()` call to record the exact package/version/components used, so `Config.cmake` can regenerate accurate `find_dependency()` calls at install time. State is stored in `GLOBAL` properties (`_CPP_LIBRARY_TRACKED_DEP_*`, `_CPP_LIBRARY_PKG_KEYS`, etc.) — there's no other persistence mechanism, so tests reset these properties between cases (see `tests/install/CMakeLists.txt`). +- **`cpp-library-dependency-provider.cmake`** — implements the CMake dependency-provider callback (`SET_DEPENDENCY_PROVIDER`) that intercepts every `find_package()`/`FetchContent_MakeAvailable()` call to record the exact package/version/components used, so `Config.cmake` can regenerate accurate `find_dependency()` calls at install time. State is stored in `GLOBAL` properties (`_CPP_LIBRARY_TRACKED_DEP_*`, `_CPP_LIBRARY_PKG_KEYS`, etc.) — there's no other persistence mechanism, so tests reset these properties between cases (see `tests/install/CMakeLists.txt`). CPM packages served from `CPM_SOURCE_CACHE` bypass `FetchContent_MakeAvailable()`, so the provider never sees them; the install module resolves CPM packages and their versions from CPM's own registry (`CPM_PACKAGES`, `CPM_PACKAGE__VERSION`) instead. - **`cpp-library-docs.cmake`** — Doxygen + doxygen-awesome-css target (`docs`). - **`cpp-library-ci.cmake`** — generates `.github/workflows/ci.yml` for the *consumer* project from `templates/.github/workflows/ci.yml.in`, substituting the package name. - **`cpp-library-testing.cmake`** — public `cpp_library_copy_runtime_dlls()` helper and backward-compatibility `_cpp_library_setup_testing()` wrapper; test/example executable creation lives in `_cpp_library_setup_executables()` in `cpp-library.cmake`. @@ -62,7 +62,7 @@ or pin to a specific commit: `CPMAddPackage("gh:stlab/cpp-library#") - Creates the library target (`INTERFACE` if no `SOURCES`, else a compiled target respecting `BUILD_SHARED_LIBS`) with `FILE_SET headers`, aliased as `NAMESPACE::CLEAN_NAME`. - Calls `_cpp_library_setup_install()`, which is gated by `${NAMESPACE}_INSTALL` (default `PROJECT_IS_TOP_LEVEL`) and uses `cmake_language(DEFER)` to generate `Config.cmake` and register install-time dependency validation *after* all `target_link_libraries()` calls in the consumer's `CMakeLists.txt` have executed (deferred calls run LIFO — validation is registered first so it executes last, right before config files are written). - If `PROJECT_IS_TOP_LEVEL`: also copies static template files (`.clang-format`, `.gitignore`, `CMakePresets.json`, etc. — skipped if already present unless `CPP_LIBRARY_FORCE_INIT` is set), configures the CI workflow, downloads doctest, and wires up `TESTS`/`EXAMPLES`/`docs`. When consumed as a subproject (not top-level), it returns early after target creation — "lightweight consumer mode". -4. At install time, if any dependency was linked but never went through a tracked `find_package()`/`CPMAddPackage()` call at the top-level scope (e.g. added in a subdirectory), the install step fails with a detailed error (`_cpp_library_setup_install_validation`) rather than silently emitting a broken `Config.cmake`. During plain `configure`/`build` (no install), the same situation is only a warning ("Untracked dependencies"). +4. At install time, if any dependency was linked but is neither in CPM's registry nor recorded by the provider (e.g. brought in by `add_subdirectory()`, or by `find_package()` before `project()`), the install step fails with a detailed error (`_cpp_library_setup_install_validation`) rather than silently emitting a broken `Config.cmake`. During plain `configure`/`build` (no install), the same situation is only a warning ("Untracked dependencies"). ### Naming conventions consumers must follow diff --git a/README.md b/README.md index 24ae097..4a01d53 100644 --- a/README.md +++ b/README.md @@ -679,60 +679,35 @@ During configuration, you may see messages like: ``` -- cpp-library: Untracked dependencies (see: https://github.com/stlab/cpp-library#untracked-dependencies) --- cpp-library: Dependency stlab::copy-on-write (package: stlab-copy-on-write) was not tracked. --- cpp-library: Dependency stlab::enum-ops (package: stlab-enum-ops) was not tracked. +-- cpp-library: Dependency acme::widgets (package: acme-widgets) was not tracked. ``` -**This is expected behavior** when: +cpp-library derives each `find_dependency()` call from two sources: -- Building for development (not installing) -- Using dependencies added from subdirectories (via `CPMAddPackage` in downstream packages) -- Testing locally without installation +- **`CPMAddPackage()`**: CPM's package registry records every package and its version, whether + CPM fetches it, reuses it from `CPM_SOURCE_CACHE`, or adds it from a subdirectory. +- **`find_package()` and `FetchContent_MakeAvailable()`**: The dependency provider records calls + made after `project()`, including versions and components. -**What it means:** - -- These dependencies were not captured by the dependency provider (usually because they were added in a subdirectory) -- cpp-library uses a fallback `find_dependency()` call for these dependencies -- Your build will work correctly -- If you attempt to install, validation will fail to prevent broken package configs - -**When it matters:** - -- **Installing the package**: Installation will fail with a detailed error, preventing broken configs -- **Not installing**: Messages are informational only - your local development builds work fine - -**Solutions** (if you need to install): +The message means neither source accounts for the package that provides a linked target, for +example because the package comes from `add_subdirectory()` or from a `find_package()` call made +before `project()`. -1. **Move dependencies to top-level** (preferred): - - ```cmake - # In your top-level CMakeLists.txt (after project()) - CPMAddPackage("gh:stlab/stlab-copy-on-write@1.1.0") - target_link_libraries(my-library INTERFACE - $ - $>) - ``` - -2. **Manually register dependencies**: +**What it means:** - ```cmake - # After adding the dependency - CPMAddPackage("gh:stlab/stlab-copy-on-write@1.1.0") - cpp_library_map_dependency("stlab::copy-on-write" "stlab-copy-on-write 1.1.0") - target_link_libraries(my-library INTERFACE - $ - $>) - ``` +- cpp-library uses a fallback `find_dependency()` call without a version. +- Development builds work. +- Installation fails with a detailed error, preventing a broken package config. -3. **Use CPM_USE_LOCAL_PACKAGES**: Install dependencies first, then build with local packages: - ```bash - cmake -DCPM_USE_LOCAL_PACKAGES=ON -B build - ``` +**Solution:** Add the dependency with `CPMAddPackage()` or `find_package()` after `project()`, or +map the target explicitly: -**Why this happens:** -The dependency provider (CMake 3.24+) tracks `find_package()` and `CPMAddPackage()` calls at the project scope. When dependencies are added in subdirectories (common with transitive CPM dependencies), they aren't captured at your project's scope. +```cmake +cpp_library_map_dependency("acme::widgets" "acme-widgets 2.1.0") +``` -**Important:** Ensure `cpp_library_enable_dependency_tracking()` is called before `project()` - this is required for any dependency tracking to work. +**Important:** Call `cpp_library_enable_dependency_tracking()` before `project()`; the dependency +provider must be active for `find_package()` tracking. ### CPM Repository Name Mismatch diff --git a/cmake/cpp-library-dependency-provider.cmake b/cmake/cpp-library-dependency-provider.cmake index ed22d49..a6a7827 100644 --- a/cmake/cpp-library-dependency-provider.cmake +++ b/cmake/cpp-library-dependency-provider.cmake @@ -220,47 +220,40 @@ function(_cpp_library_verify_quiet_dependency package_name) endif() endfunction() -# Track a FetchContent_MakeAvailable() call -# This is more complex because we need to extract info from prior FetchContent_Declare() calls -function(_cpp_library_track_fetchcontent) - # FetchContent_MakeAvailable can take multiple package names - foreach(package_name IN LISTS ARGN) - # Try to extract useful information from FetchContent variables - # FetchContent stores info in variables like FETCHCONTENT_SOURCE_DIR_ - # However, for CPM, we need different handling - - # Check if this looks like a CPM-added package - # CPM sets _SOURCE_DIR and _VERSION - string(TOLOWER "${package_name}" package_lower) - string(TOUPPER "${package_name}" package_upper) - string(REPLACE "-" "_" package_var "${package_lower}") - - # Try to get version from various places - set(VERSION "") - if(DEFINED ${package_name}_VERSION AND NOT "${${package_name}_VERSION}" STREQUAL "") - set(VERSION "${${package_name}_VERSION}") - elseif(DEFINED ${package_var}_VERSION AND NOT "${${package_var}_VERSION}" STREQUAL "") - set(VERSION "${${package_var}_VERSION}") - elseif(DEFINED ${package_upper}_VERSION AND NOT "${${package_upper}_VERSION}" STREQUAL "") - set(VERSION "${${package_upper}_VERSION}") - endif() - - # Build find_dependency() call - set(FIND_DEP_CALL "${package_name}") - if(VERSION) - string(APPEND FIND_DEP_CALL " ${VERSION}") - endif() - - # Store the dependency - set_property(GLOBAL PROPERTY "_CPP_LIBRARY_TRACKED_DEP_${package_name}" "${FIND_DEP_CALL}") - - get_property(ALL_DEPS GLOBAL PROPERTY _CPP_LIBRARY_ALL_TRACKED_DEPS) - if(NOT package_name IN_LIST ALL_DEPS) - set_property(GLOBAL APPEND PROPERTY _CPP_LIBRARY_ALL_TRACKED_DEPS "${package_name}") - endif() - - message(DEBUG "cpp-library: Tracked FetchContent(${package_name}) → find_dependency(${FIND_DEP_CALL})") - endforeach() +# Tracks one dependency made available through FetchContent_MakeAvailable() +# - Precondition: package_name is the dependency name; ARGN holds its FetchContent_Declare() +# arguments, which CMake passes to FETCHCONTENT_MAKEAVAILABLE_SERIAL providers +# - Postcondition: package_name is tracked as find_dependency(package_name [version]), where version +# comes from a _VERSION variable when one is already set +# - Note: CPM sets _VERSION after this call; the install module resolves the version +# of CPM packages from CPM's package registry instead +function(_cpp_library_track_fetchcontent package_name) + string(TOLOWER "${package_name}" package_lower) + string(TOUPPER "${package_name}" package_upper) + string(REPLACE "-" "_" package_var "${package_lower}") + + set(VERSION "") + if(DEFINED ${package_name}_VERSION AND NOT "${${package_name}_VERSION}" STREQUAL "") + set(VERSION "${${package_name}_VERSION}") + elseif(DEFINED ${package_var}_VERSION AND NOT "${${package_var}_VERSION}" STREQUAL "") + set(VERSION "${${package_var}_VERSION}") + elseif(DEFINED ${package_upper}_VERSION AND NOT "${${package_upper}_VERSION}" STREQUAL "") + set(VERSION "${${package_upper}_VERSION}") + endif() + + set(FIND_DEP_CALL "${package_name}") + if(VERSION) + string(APPEND FIND_DEP_CALL " ${VERSION}") + endif() + + set_property(GLOBAL PROPERTY "_CPP_LIBRARY_TRACKED_DEP_${package_name}" "${FIND_DEP_CALL}") + + get_property(ALL_DEPS GLOBAL PROPERTY _CPP_LIBRARY_ALL_TRACKED_DEPS) + if(NOT package_name IN_LIST ALL_DEPS) + set_property(GLOBAL APPEND PROPERTY _CPP_LIBRARY_ALL_TRACKED_DEPS "${package_name}") + endif() + + message(DEBUG "cpp-library: Tracked FetchContent(${package_name}) → find_dependency(${FIND_DEP_CALL})") endfunction() # Helper function to retrieve tracked dependency information for a specific package diff --git a/cmake/cpp-library-install.cmake b/cmake/cpp-library-install.cmake index 8558ce6..7d6b96a 100644 --- a/cmake/cpp-library-install.cmake +++ b/cmake/cpp-library-install.cmake @@ -113,6 +113,28 @@ function(_cpp_library_generate_dependencies OUTPUT_VAR TARGET_NAME NAMESPACE) endif() endfunction() +# Returns the find_dependency() arguments for a package added through CPMAddPackage() +# - Postcondition: OUTPUT_VAR is "package_name [version]" if CPM registered package_name in this +# configuration, and empty otherwise; version is included only when CPM recorded a version of +# the form major.minor[.patch[.tweak]] +# - Note: CPM registers every added package, including packages served from CPM_SOURCE_CACHE, +# which bypass FetchContent_MakeAvailable() and therefore the dependency provider +# - Note: without an explicit VERSION, CPM derives the version from the leading digits of +# GIT_TAG (0 for a full commit hash), so an abbreviated hash or branch name yields a +# meaningless value such as "2" or "3."; omitting it is safe, emitting it is not +# - Complexity: O(n) in the number of CPM packages +function(_cpp_library_get_cpm_dependency OUTPUT_VAR package_name) + set(FIND_DEP_CALL "") + if(package_name IN_LIST CPM_PACKAGES) + set(FIND_DEP_CALL "${package_name}") + set(VERSION "${CPM_PACKAGE_${package_name}_VERSION}") + if(VERSION MATCHES "^[0-9]+(\\.[0-9]+)(\\.[0-9]+)?(\\.[0-9]+)?$") + string(APPEND FIND_DEP_CALL " ${VERSION}") + endif() + endif() + set(${OUTPUT_VAR} "${FIND_DEP_CALL}" PARENT_SCOPE) +endfunction() + # Resolve dependency using tracked provider data # - Precondition: LIB is a target name, NAMESPACE is the project namespace # - Postcondition: OUTPUT_VAR contains find_dependency() call syntax or error is raised @@ -141,7 +163,15 @@ function(_cpp_library_resolve_dependency LIB NAMESPACE OUTPUT_VAR) # Look up tracked dependency data get_property(TRACKED_CALL GLOBAL PROPERTY "_CPP_LIBRARY_TRACKED_DEP_${FIND_PACKAGE_NAME}") - + + # A bare tracked name carries no more than CPM's registry, which also records the version + if(NOT TRACKED_CALL OR TRACKED_CALL STREQUAL FIND_PACKAGE_NAME) + _cpp_library_get_cpm_dependency(CPM_CALL "${FIND_PACKAGE_NAME}") + if(CPM_CALL) + set(TRACKED_CALL "${CPM_CALL}") + endif() + endif() + if(TRACKED_CALL) # Found tracked data - use it directly set(${OUTPUT_VAR} "${TRACKED_CALL}" PARENT_SCOPE) @@ -175,10 +205,11 @@ function(_cpp_library_resolve_dependency LIB NAMESPACE OUTPUT_VAR) "\n" "The dependency provider is installed, but this dependency was not captured.\n" "Common causes:\n" - " - find_package() or CPMAddPackage() was called in a subdirectory\n" - " - Dependency was added before project() (must be after)\n" + " - The package was added with add_subdirectory() instead of CPMAddPackage()\n" + " - find_package() was called before project() (must be after)\n" "\n" - "Solution: Ensure dependencies are declared after project() in the top-level CMakeLists.txt.\n" + "Solution: Add the dependency with CPMAddPackage() or find_package() after project(),\n" + "or use cpp_library_map_dependency() to map the target to its package.\n" "\n" "Correct order:\n" " cpp_library_enable_dependency_tracking()\n" @@ -550,10 +581,10 @@ function(_cpp_library_setup_install_validation TARGET_NAME) \"\\n\" \"These dependencies were not captured by the dependency provider.\\n\" \"Common causes:\\n\" - \" - find_package() or CPMAddPackage() was called in a subdirectory\\n\" - \" - Dependency was added before project() (must be after)\\n\" + \" - The package was added with add_subdirectory() instead of CPMAddPackage()\\n\" + \" - find_package() was called before project() (must be after)\\n\" \"\\n\" - \"Solution: Ensure dependencies are declared after project() in the top-level CMakeLists.txt.\\n\" + \"Solution: Add the dependency with CPMAddPackage() or find_package() after project().\\n\" \"Or use cpp_library_map_dependency() to manually register each dependency.\\n\" ) endif() diff --git a/tests/install/CMakeLists.txt b/tests/install/CMakeLists.txt index a5a3557..8b9f8b6 100644 --- a/tests/install/CMakeLists.txt +++ b/tests/install/CMakeLists.txt @@ -60,6 +60,9 @@ macro(run_test TEST_NAME) set_property(GLOBAL PROPERTY "_CPP_LIBRARY_TRACKED_DEP_${dep}") endforeach() set_property(GLOBAL PROPERTY _CPP_LIBRARY_ALL_TRACKED_DEPS "") + + # Clear the CPM package registry + set(CPM_PACKAGES "") endmacro() # Helper macro to set up mock link libraries for a test target @@ -85,6 +88,7 @@ endmacro() # Include the actual tests include(${CMAKE_CURRENT_LIST_DIR}/test_dependency_mapping.cmake) include(${CMAKE_CURRENT_LIST_DIR}/test_dependency_provider.cmake) +include(${CMAKE_CURRENT_LIST_DIR}/test_cpm_registry.cmake) # Print summary message(STATUS "") diff --git a/tests/install/test_cpm_registry.cmake b/tests/install/test_cpm_registry.cmake new file mode 100644 index 0000000..f9aa8d9 --- /dev/null +++ b/tests/install/test_cpm_registry.cmake @@ -0,0 +1,60 @@ +# SPDX-License-Identifier: BSL-1.0 +# +# Unit tests for resolving dependencies added through CPM. +# +# CPM records every added package in `CPM_PACKAGES` and its version in +# `CPM_PACKAGE__VERSION`, including packages served from `CPM_SOURCE_CACHE`, which +# bypass `FetchContent_MakeAvailable()` and therefore the dependency provider. + +run_test("CPM package from source cache without provider tracking") +set(CPM_PACKAGES "cel-runtime") +set(CPM_PACKAGE_cel-runtime_VERSION "1.1.0") +mock_target_links(cpm1_target "cel::runtime") +_cpp_library_generate_dependencies(RESULT cpm1_target "cel" UNVERIFIED) +verify_output("${RESULT}" "find_dependency(cel-runtime 1.1.0)" "CPM cached package resolves with version") +verify_output("${UNVERIFIED}" "" "CPM cached package is verified") + +run_test("CPM package tracked by FetchContent takes CPM version") +_cpp_library_dependency_provider(FETCHCONTENT_MAKEAVAILABLE_SERIAL stlab-enum-ops + SOURCE_DIR /cache/stlab-enum-ops BINARY_DIR /build/_deps/stlab-enum-ops-build + GIT_REPOSITORY https://github.com/stlab/stlab-enum-ops.git GIT_TAG v1.0.0 + EXCLUDE_FROM_ALL SYSTEM) +set(CPM_PACKAGES "stlab-enum-ops") +set(CPM_PACKAGE_stlab-enum-ops_VERSION "1.0.0") +mock_target_links(cpm2_target "stlab::enum-ops") +_cpp_library_generate_dependencies(RESULT cpm2_target "stlab") +verify_output("${RESULT}" "find_dependency(stlab-enum-ops 1.0.0)" "FetchContent-tracked CPM package gains version") + +run_test("FetchContent tracking records only the dependency name") +_cpp_library_dependency_provider(FETCHCONTENT_MAKEAVAILABLE_SERIAL cel-runtime + SOURCE_DIR /cache/cel-runtime GIT_TAG 2dd73e9c26c6d02c79bfb26f82521c62a1bfd079) +_cpp_library_get_all_tracked_deps(TRACKED) +verify_output("${TRACKED}" "cel-runtime" "Declaration arguments are not tracked as packages") + +run_test("CPM package without a derivable version") +set(CPM_PACKAGES "cel-runtime") +set(CPM_PACKAGE_cel-runtime_VERSION "0") +mock_target_links(cpm4_target "cel::runtime") +_cpp_library_generate_dependencies(RESULT cpm4_target "cel" UNVERIFIED) +verify_output("${RESULT}" "find_dependency(cel-runtime)" "CPM placeholder version 0 is omitted") +verify_output("${UNVERIFIED}" "" "Versionless CPM package is verified") + +run_test("CPM version derived from an abbreviated hash or branch") +set(CPM_PACKAGES "cel-runtime;stlab-enum-ops") +set(CPM_PACKAGE_cel-runtime_VERSION "2") +set(CPM_PACKAGE_stlab-enum-ops_VERSION "3.") +mock_target_links(cpm6_target "cel::runtime") +_cpp_library_generate_dependencies(RESULT cpm6_target "cel") +verify_output("${RESULT}" "find_dependency(cel-runtime)" "Single-component tag-derived version is omitted") +mock_target_links(cpm7_target "stlab::enum-ops") +_cpp_library_generate_dependencies(RESULT cpm7_target "stlab") +verify_output("${RESULT}" "find_dependency(stlab-enum-ops)" "Malformed tag-derived version is omitted") + +run_test("Provider find_package tracking takes precedence over CPM registry") +set_property(GLOBAL PROPERTY "_CPP_LIBRARY_TRACKED_DEP_Qt6" "Qt6 6.5.0 COMPONENTS Core") +set_property(GLOBAL APPEND PROPERTY _CPP_LIBRARY_ALL_TRACKED_DEPS "Qt6") +set(CPM_PACKAGES "Qt6") +set(CPM_PACKAGE_Qt6_VERSION "6.5.0") +mock_target_links(cpm5_target "Qt6::Core") +_cpp_library_generate_dependencies(RESULT cpm5_target "mylib") +verify_output("${RESULT}" "find_dependency(Qt6 6.5.0 COMPONENTS Core)" "find_package details are preserved")