diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index e7b148c..d331360 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -120,8 +120,9 @@ consumer templates. prefix, the alias strips it. Matching namespace and clean project name collapse to one package name rather than duplicating it. - Consumer versions come from Git tags with a leading `v` removed. - `CPP_LIBRARY_VERSION` overrides Git discovery for source archives and package - managers; missing tags fall back to `0.0.0` with a warning. + `CPP_LIBRARY_VERSION_` overrides Git discovery for the exact CMake + project name. Legacy `CPP_LIBRARY_VERSION` applies only to the top-level project; + missing tags fall back to `0.0.0` with a warning. - Non-namespaced dependency targets need explicit mappings such as `cpp_library_map_dependency(opencv_core "OpenCV 4.8")`. Keep dependency declarations after `project()` in the top-level consumer scope; explicit diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 02e247c..f24014b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -32,6 +32,12 @@ jobs: - name: Run target type tests run: cmake -P tests/setup/test_target_type.cmake + - name: Run independent public header compilation tests + run: cmake -P tests/setup/test_header_checks.cmake + + - name: Run project version override tests + run: cmake -P tests/setup/test_version_override.cmake + - name: Run install directory tests run: cmake -P tests/setup/test_install_dirs.cmake @@ -50,9 +56,35 @@ jobs: # [DEPENDENCY] https://github.com/ilammy/msvc-dev-cmd/releases - uses: ilammy/msvc-dev-cmd@0b201ec74fa43914dc39ae48a89fd1d8cb592756 + - name: Verify documented PowerShell scaffold commands + shell: pwsh + run: | + $work = Join-Path $env:RUNNER_TEMP "cpp-library-powershell-scaffold" + New-Item -ItemType Directory -Path $work | Out-Null + Set-Location $work + $setupUrl = "https://raw.githubusercontent.com/stlab/cpp-library/main/setup.cmake" + Invoke-WebRequest -UseBasicParsing -Uri $setupUrl -OutFile setup.cmake + cmake -P setup.cmake -- ` + --name=my-library ` + --namespace=mycompany ` + --description="My awesome library" ` + --header-only=yes ` + --examples=yes ` + --tests=yes + if ($LASTEXITCODE -ne 0) { throw "Scaffolding failed" } + if (!(Test-Path -LiteralPath "my-library/CMakeLists.txt")) { + throw "The scaffold did not create CMakeLists.txt" + } + - name: Run target type tests run: cmake -P tests/setup/test_target_type.cmake + - name: Run independent public header compilation tests + run: cmake -P tests/setup/test_header_checks.cmake + + - name: Run project version override tests + run: cmake -P tests/setup/test_version_override.cmake + - name: Run install directory tests run: cmake -P tests/setup/test_install_dirs.cmake diff --git a/.scout/memory/index.md b/.scout/memory/index.md index a28079d..6c8567c 100644 --- a/.scout/memory/index.md +++ b/.scout/memory/index.md @@ -5,11 +5,15 @@ - [[knowledge/architecture-overview.md|Architecture Overview]] (concept, 0.80) `architecture-overview` `cpp-library-architecture` `cpp-library-overview` `toolkit-architecture` `cmake-infrastructure-overview` - [[knowledge/consumer-lifecycle-and-template-overwrite-controls.md|Consumer Lifecycle and Template Overwrite Controls]] (decision, 0.75) `template-initialization` `cpp-library-force-init` `project-is-top-level` `lightweight-consumer-mode` `template-copying` - [[knowledge/deferred-install-dependency-validation-and-config-generation.md|Deferred Install Dependency Validation and Config Generation]] (pattern, 0.75) `deferred-install` `install-validation` `untracked-dependencies` `cmake-language-defer` `find-dependency` +- [[knowledge/dependency-mappings-follow-the-exported-target-s-owning-project.md|Dependency mappings follow the exported target's owning project]] (discovery, 0.99) `cmake` `dependency-mappings` `project-scope` `deferred-install` - [[knowledge/dependency-tracking-lifecycle-and-provider-ordering.md|Dependency Tracking Lifecycle and Provider Ordering]] (observation, 0.75) `dependency-tracking` `dependency-provider` `cpp-library-enable-dependency-tracking` `cmake-project-top-level-includes` `set-dependency-provider` - [[knowledge/documentation-setup-and-theme-integration-with-build-docs.md|Documentation Setup and Theme Integration with BUILD_DOCS]] (pattern, 0.75) `build-docs` `doxygen` `doxygen-awesome-css` `documentation-generation` `docs-target` - [[knowledge/generated-ci-package-artifact-check.md|Generated CI package artifact check]] (decision, 0.95) `ci` `packaging` `cmake` +- [[knowledge/installation-supports-separately-installed-dependencies-not-mixed-source-export-workarounds.md|Installation supports separately installed dependencies, not mixed source export workarounds]] (decision, 0.99) `cmake` `installation` `cpm` `supported-boundary` +- [[knowledge/public-header-verification-must-participate-in-the-default-build.md|Public-header verification must participate in the default build]] (pattern, 0.99) `cmake` `header-verification` `testing` `file-sets` - [[knowledge/target-naming-and-alias-deduplication-convention.md|Target Naming and Alias Deduplication Convention]] (pattern, 0.75) `target-naming` `alias-deduplication` `package-name` `clean-name` `cmake-alias-convention` - [[knowledge/testing-and-example-executable-target-generation-gated-by-build-testing.md|Testing and Example Executable Target Generation Gated by BUILD_TESTING]] (pattern, 0.75) `build-testing` `doctest` `testing-setup` `negative-compilation-tests` `runtime-dll-copy` +- [[knowledge/version-overrides-must-not-leak-into-independently-named-subprojects.md|Version overrides must not leak into independently named subprojects]] (decision, 0.99) `cmake` `versions` `project-scope` `package-managers` ## Procedures diff --git a/.scout/memory/knowledge/dependency-mappings-follow-the-exported-target-s-owning-project.md b/.scout/memory/knowledge/dependency-mappings-follow-the-exported-target-s-owning-project.md new file mode 100644 index 0000000..b7a2d4e --- /dev/null +++ b/.scout/memory/knowledge/dependency-mappings-follow-the-exported-target-s-owning-project.md @@ -0,0 +1,18 @@ +--- +title: "Dependency mappings follow the exported target's owning project" +entity_type: discovery +confidence: 0.99 +created: 2026-11-18T23:22:31Z +last_accessed: 2026-11-18T23:22:31Z +last_reinforced: 2026-11-18T23:22:31Z +access_count: 1 +sources: + - "cmake/cpp-library-install.cmake:34-40" + - "cmake/cpp-library-install.cmake:65-68" +tags: ["cmake", "dependency-mappings", "project-scope", "deferred-install"] +tier: knowledge +--- + +# Dependency mappings follow the exported target's owning project + +Explicit dependency mappings are isolated per CMake project. Registration keys GLOBAL properties by SHA256(PROJECT_BINARY_DIR) plus dependency target. Generation must derive PROJECT_BINARY_DIR from the exported target's BINARY_DIR, not from the directory calling the generator. Helper directories and deferred package finalization can generate another project's target; using caller scope leaks or selects the wrong override. Non-project subdirectories share the owning project's mappings; nested and sibling projects do not. Retain the binary-directory identity so separate configurations of the same source project remain distinct. The GLOBAL storage also supports the script-mode mock harness; do not replace it with an unscoped target-only key. diff --git a/.scout/memory/knowledge/installation-supports-separately-installed-dependencies-not-mixed-source-export-workarounds.md b/.scout/memory/knowledge/installation-supports-separately-installed-dependencies-not-mixed-source-export-workarounds.md new file mode 100644 index 0000000..084d9b5 --- /dev/null +++ b/.scout/memory/knowledge/installation-supports-separately-installed-dependencies-not-mixed-source-export-workarounds.md @@ -0,0 +1,19 @@ +--- +title: "Installation supports separately installed dependencies, not mixed source export workarounds" +entity_type: decision +confidence: 0.99 +created: 2026-11-18T23:22:41Z +last_accessed: 2026-11-18T23:22:41Z +last_reinforced: 2026-11-18T23:22:41Z +access_count: 1 +sources: + - "README.md:215-226" + - "README.md:240-245" + - "cmake/cpp-library-install.cmake:70-72" +tags: ["cmake", "installation", "cpm", "supported-boundary"] +tier: knowledge +--- + +# Installation supports separately installed dependencies, not mixed source export workarounds + +The supported installation workflow installs required dependencies separately before configuring the component, then has CPM resolve those installed packages. Installing a component against dependencies fetched from source in that same build is explicitly unsupported. Ordinary source consumption uses ordinary PUBLIC/INTERFACE target links, not BUILD_INTERFACE/INSTALL_INTERFACE wrappers to bypass export checks. CMake validates enabled installation exports during configuration/generation, before cmake --install; source-only builds without installed dependencies should disable component installation. Do not reintroduce the removed special extraction of BUILD_INTERFACE dependencies into installed find_dependency() requirements. CPM_USE_LOCAL_PACKAGES is only a preference and may fall back to source; it does not guarantee this installation precondition. diff --git a/.scout/memory/knowledge/public-header-verification-must-participate-in-the-default-build.md b/.scout/memory/knowledge/public-header-verification-must-participate-in-the-default-build.md new file mode 100644 index 0000000..55ff7c1 --- /dev/null +++ b/.scout/memory/knowledge/public-header-verification-must-participate-in-the-default-build.md @@ -0,0 +1,18 @@ +--- +title: "Public-header verification must participate in the default build" +entity_type: pattern +confidence: 0.99 +created: 2026-11-19T00:38:12Z +last_accessed: 2026-11-19T00:38:12Z +last_reinforced: 2026-11-19T00:38:12Z +access_count: 1 +sources: + - "cpp-library.cmake:314-323" + - "tests/setup/test_header_checks.cmake:151-159" +tags: ["cmake", "header-verification", "testing", "file-sets"] +tier: knowledge +--- + +# Public-header verification must participate in the default build + +cpp_library_setup() enables native CMake VERIFY_INTERFACE_HEADER_SETS only for top-level projects with BUILD_TESTING enabled. Preserve both the target property and the ALL custom target dependency on _verify_interface_header_sets: native verification targets are excluded from the default build, so setting the property alone does not enforce the check. Keep verification based on PUBLIC/INTERFACE header file sets rather than a second header list; this includes generated headers and file sets added after setup. These build-time, per-header checks are separate from configure-time clangd indexing. C++17/20/23 fixtures check the configured standard, public usage requirements, generated-header ordering, and the testing-off/subproject scope boundaries. Platform-specific public headers must guard their contents and be no-ops when unsupported; do not introduce platform-exclusion lists. diff --git a/.scout/memory/knowledge/version-overrides-must-not-leak-into-independently-named-subprojects.md b/.scout/memory/knowledge/version-overrides-must-not-leak-into-independently-named-subprojects.md new file mode 100644 index 0000000..8b8f8b7 --- /dev/null +++ b/.scout/memory/knowledge/version-overrides-must-not-leak-into-independently-named-subprojects.md @@ -0,0 +1,18 @@ +--- +title: "Version overrides must not leak into independently named subprojects" +entity_type: decision +confidence: 0.99 +created: 2026-11-18T23:22:35Z +last_accessed: 2026-11-18T23:22:35Z +last_reinforced: 2026-11-18T23:22:35Z +access_count: 1 +sources: + - "cmake/cpp-library-setup.cmake:5-23" + - "README.md:769-790" +tags: ["cmake", "versions", "project-scope", "package-managers"] +tier: knowledge +--- + +# Version overrides must not leak into independently named subprojects + +Both cpp_library_setup() and cpp_library_set_version() share _cpp_library_get_git_version(). Override precedence is: nonempty CPP_LIBRARY_VERSION_ for the exact case-sensitive CMake project() name (hyphens included); nonempty legacy CPP_LIBRARY_VERSION only for PROJECT_IS_TOP_LEVEL; then the project's Git tag; then the existing warning and 0.0.0 fallback. A cache entry for the legacy variable otherwise leaks through nested directory scopes and incorrectly overwrites dependency ConfigVersion.cmake files. Package managers overriding nested projects must use the scoped variable; do not restore unconditional legacy-variable lookup. Independently named children and siblings must retain their own tags or explicit scoped overrides. diff --git a/CLAUDE.md b/CLAUDE.md index e42c386..23c4917 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -58,7 +58,7 @@ or pin to a specific commit: `CPMAddPackage("gh:stlab/cpp-library#") 2. Consumer calls `project(name)`, then `include(CTest)` if using TESTS/EXAMPLES, then `cpp_library_setup(NAMESPACE ... HEADERS ... [SOURCES ...] [TESTS ...] [EXAMPLES ...])`. 3. `cpp_library_setup()`: - Derives `PACKAGE_NAME` (namespace-prefixed, e.g. `stlab-enum-ops`) and `CLEAN_NAME` (namespace stripped from `PROJECT_NAME`). - - Sets project version from git tags (`_cpp_library_get_git_version`, overridable via `CPP_LIBRARY_VERSION` cache var for package managers without git history). + - Sets project version from git tags (`_cpp_library_get_git_version`, overridable via `CPP_LIBRARY_VERSION_` for the exact CMake project name). Legacy `CPP_LIBRARY_VERSION` applies only to the top-level project. - 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". diff --git a/README.md b/README.md index 4a01d53..5e7c217 100644 --- a/README.md +++ b/README.md @@ -20,13 +20,36 @@ Modern CMake template for C++ libraries with comprehensive infrastructure. - **CI/CD**: [GitHub Actions](https://docs.github.com/en/actions) workflows with multi-platform testing and installation verification - **Dependency Management**: [CPM.cmake](https://github.com/cpm-cmake/CPM.cmake) integration +## Quick reference + +Requires CMake 3.24 or newer. The minimum C++ version defaults to 20; +[`REQUIRES_CPP_VERSION`](#cpp_library_setup) also supports 17 and 23. + +Use this order in your top-level `CMakeLists.txt`: + +| Order | Action | +| --- | --- | +| 1 | Load CPM and cpp-library, as shown in [Manual Setup](#manual-setup). | +| 2 | Call [`cpp_library_enable_dependency_tracking()`](#cpp_library_enable_dependency_tracking) **before `project()`**. | +| 3 | Call `project(... LANGUAGES CXX)`, then declare dependencies with `CPMAddPackage()` or `find_package()`. | +| 4 | Call `include(CTest)` at directory scope to define `BUILD_TESTING`. | +| 5 | Call [`cpp_library_setup()`](#cpp_library_setup), using the [file-resolution conventions](#path-conventions). | + +For custom target setup, see [`cpp_library_set_version()`](#cpp_library_set_version). +For non-namespaced dependency targets, see [dependency mapping](#non-namespaced-target-error). +For automatic standalone header checks, see [public-header compilation](#public-header-compilation). + ## Quick Start The easiest way to create a new library project using cpp-library is with the `setup.cmake` script. This interactive script will guide you through creating a new project with the correct structure, downloading dependencies, and generating all necessary files. +Before you begin, install CMake 3.24 or newer, Git, Ninja, and a C++ compiler +supporting your chosen standard. On Windows with MSVC, run build commands in an +x64 Visual Studio developer environment. + ### Using setup.cmake -**Interactive mode:** +**Bash, interactive mode:** ```bash cmake -P <(curl -sSL https://raw.githubusercontent.com/stlab/cpp-library/main/setup.cmake) @@ -39,6 +62,14 @@ curl -O https://raw.githubusercontent.com/stlab/cpp-library/main/setup.cmake cmake -P setup.cmake ``` +In PowerShell, download and run the script: + +```powershell +$setupUrl = "https://raw.githubusercontent.com/stlab/cpp-library/main/setup.cmake" +Invoke-WebRequest -UseBasicParsing -Uri $setupUrl -OutFile setup.cmake +cmake -P setup.cmake +``` + The script will prompt you for: - **Library name** (e.g., `my-library`) @@ -48,7 +79,7 @@ The script will prompt you for: - **Include examples?** (yes/no) - **Include tests?** (yes/no) -**Non-interactive mode:** +**Bash, non-interactive mode:** ```bash cmake -P setup.cmake -- \ @@ -60,6 +91,18 @@ cmake -P setup.cmake -- \ --tests=yes ``` +In PowerShell, use backticks for line continuation: + +```powershell +cmake -P setup.cmake -- ` + --name=my-library ` + --namespace=mycompany ` + --description="My awesome library" ` + --header-only=yes ` + --examples=yes ` + --tests=yes +``` + The script will: 1. Create the project directory structure @@ -137,6 +180,9 @@ cpp_library_setup( ) ``` +`HEADERS`, `SOURCES`, `TESTS`, and `EXAMPLES` are filenames under their +[standard directories](#path-conventions), not paths from the project root. + These examples are for C++-only projects. If your project also contains C sources, use `project(your-library LANGUAGES C CXX)`. @@ -164,9 +210,22 @@ The library will be automatically fetched and built as part of your project. **Repository Naming:** Your GitHub repository name must match the package name for CPM compatibility (see [Target Naming](#target-naming) for details). -#### Installation (optional) +#### Installation (strongly discouraged) + +Consume libraries from source through [CPMAddPackage](#using-cpmaddpackage-recommended). +Installation is strongly discouraged: an installed package's dependencies might not be +installed or available to a downstream consumer, so its `find_dependency()` calls can fail. +cpp-library does not automatically install dependencies. + +For installation, install required dependencies separately before configuring the +component, and configure CPM to use those installed packages. Installing a component +against dependencies fetched from source in the same build is not supported. +Source consumption requires no special build/install-interface wrappers. +CMake checks installation exports during configuration/generation, before +`cmake --install` runs. For source-only builds without installed dependencies, +disable the component's installation option. -Installation is optional and typically not required when using CPM. If you need to install your library (e.g., for system-wide deployment or use with a package manager): +If system-wide deployment or a package manager requires installation, use: ```bash # Build and install to default system location @@ -178,7 +237,17 @@ cmake --install build/install cmake --install build/install --prefix /opt/mylib ``` -The `install` preset enables `CPM_USE_LOCAL_PACKAGES`, which verifies your generated Config.cmake works correctly. See the [CPM.cmake documentation](https://github.com/cpm-cmake/CPM.cmake#cpm_use_local_packages) for more about using installed packages. +The `install` preset enables `CPM_USE_LOCAL_PACKAGES`, which makes CPM look for +locally installed dependencies before fetching them from source. This setting is a +preference, not a guarantee: ensure CPM resolves the required installed packages +rather than falling back to source. It does not verify your project's installed +package config or dependency closure. See the +[CPM.cmake documentation](https://github.com/cpm-cmake/CPM.cmake#cpm_use_local_packages). + +The generated CI package check verifies only that the root package's +`Config.cmake`, `ConfigVersion.cmake`, and `Targets.cmake` files exist and appear in +the install manifest. It does not load the package or check that its dependencies +are installed. Report installation failures if you encounter them. **Controlling installation**: The uppercase `${NAMESPACE}_INSTALL` option controls whether installation is enabled (defaults to `PROJECT_IS_TOP_LEVEL`). Use `-D${NAMESPACE}_INSTALL=ON/OFF` to override: @@ -187,7 +256,20 @@ cmake -DSTLAB_INSTALL=OFF -B build # Disable install for top-level project cmake -DSTLAB_INSTALL=ON -B build # Enable install for non-top-level (e.g., via CPM) ``` -For independent packages sharing a namespace, specify an option name with `INSTALL_OPTION`: +Libraries must not predeclare or assign their own default to the shared +`${NAMESPACE}_INSTALL` option, including before adding dependencies. Leave its +declaration and default to cpp-library, and preserve the client's chosen value. +Packages within a namespace share this cache option: the first declaration +establishes its default for the build, so a library-specific default can +unintentionally enable or disable installation for other packages in that namespace. + +Omit `INSTALL_OPTION` when installing each package in a separate build, including +dependencies. Each package is then a top-level project, so installation defaults on. + +`INSTALL_OPTION` is an advanced escape hatch for selectively installing packages +within one combined source build. Packages sharing a namespace otherwise share the +same installation switch, so enabling it can select multiple packages. Only when +you need independent switches in that build, give a package its own option name: ```cmake cpp_library_setup( @@ -200,27 +282,44 @@ cpp_library_setup( This package then uses `STLAB_EXECUTION_INSTALL`, independently of `STLAB_INSTALL` or other packages' custom options. Each custom option defaults to that project's `PROJECT_IS_TOP_LEVEL`. -Omitting `INSTALL_OPTION` preserves the shared namespace-level option and its existing behavior. +Specifying `INSTALL_OPTION` names the switch; it does not enable installation, +install dependencies, or change dependency requirements. Specifying `INSTALL_OPTION` without a value is an error. -**Re-exporting CPM dependencies:** When re-exporting dependencies from `CPMAddPackage`, use separate build and install interfaces. CPM creates non-IMPORTED targets that may not be included in your install export: +When installation is enabled, cpp-library installs an existing `${PROJECT_SOURCE_DIR}/LICENSE` +under `${CMAKE_INSTALL_DATADIR}/licenses/`. A missing conventional `LICENSE` +is allowed. To include additional license or notice files, use `LICENSE_FILES`: ```cmake -CPMAddPackage("gh:other-org/some-package@1.0.0") -target_link_libraries(my-library INTERFACE - $ - $>) +cpp_library_setup( + DESCRIPTION "Execution primitives" + NAMESPACE stlab + HEADERS execution.hpp + LICENSE_FILES licenses/CPM-MIT.txt NOTICE +) ``` -cpp-library extracts the build-interface dependency to generate the appropriate `find_dependency()` call. -The install interface preserves transitive linkage; its nested `$<1:...>` expression defers -target resolution to the downstream consumer, allowing the dependency to be installed separately. -Using only `BUILD_INTERFACE` loads the dependency's package but drops its linkage from the -installed target. Dependencies from `find_package()` and system libraries don't need these wrappers. +Relative `LICENSE_FILES` paths are relative to the declaring project's source root; +absolute paths are also accepted. Files keep their basenames in the package's license +directory, including when you customize `CMAKE_INSTALL_DATADIR`. Distinct files must have +distinct basenames; a collision is a configuration error rather than an overwrite. +With installation enabled, +a missing explicitly listed file is a configuration error. `LICENSE_FILES` without a value +is also an error. Disabled installation adds no license install rules. Only the current +package's files are installed; cpp-library does not discover dependency licenses. #### Dependency Handling in Installed Packages -cpp-library automatically generates `find_dependency()` calls in the installed CMake package configuration. Call `cpp_library_enable_dependency_tracking()` before `project()`: +Declare public dependencies with ordinary `target_link_libraries()` calls, using +`INTERFACE` for header-only libraries or `PUBLIC` for compiled libraries. Do not add +build/install-interface wrappers to make source-built dependencies installable. +For installation, clients must +resolve dependencies from their separately installed packages, as described in +[installation guidance](#installation-strongly-discouraged). + +cpp-library automatically generates `find_dependency()` calls in the installed CMake +package configuration. Build-only links do not generate installed requirements. +Call `cpp_library_enable_dependency_tracking()` before `project()`: ```cmake cmake_minimum_required(VERSION 3.24) @@ -260,6 +359,11 @@ cpp_library_map_dependency("opencv_core" "OpenCV 4.5.0") target_link_libraries(my-library INTERFACE opencv_core) ``` +Mappings apply only to libraries declared in the same CMake project, including +subdirectories that do not call `project()`. They override automatic tracking within +that project, but do not affect parent, nested, or sibling projects. Declare a mapping +in each project that needs it. + ### Updating cpp-library To update to a newer version: @@ -296,6 +400,24 @@ Your documentation will be automatically built and deployed to `https://your-org ## API Reference +### `cpp_library_enable_dependency_tracking` + +Registers the dependency provider used to record dependency versions and +components for installed package requirements. Requires CMake 3.24 or newer. + +After loading cpp-library, call it in your top-level `CMakeLists.txt` **before +the literal `project()` call**: + +```cmake +cpp_library_enable_dependency_tracking() +project(my-library LANGUAGES CXX) +``` + +Declare library dependencies after `project()`. Calling the function afterward +doesn't activate the provider retroactively. See [Manual Setup](#manual-setup) +for the complete loading sequence and [Untracked Dependencies](#untracked-dependencies) +for dependency-recording failures. + ### `cpp_library_set_version` ```cmake @@ -317,7 +439,8 @@ The function: - Queries git tags using `git describe --tags --abbrev=0` - Strips the 'v' prefix if present (e.g., `v1.2.3` → `1.2.3`) -- Respects `CPP_LIBRARY_VERSION` cache variable if set (for package managers) +- Respects project-scoped version overrides; the legacy override applies only + to the top-level project (see [Version Management](#version-management)) - Falls back to `0.0.0` if no tag found - Updates all `PROJECT_VERSION*` variables in parent scope @@ -368,16 +491,24 @@ cpp_library_setup( [DOCS_OPTIONS setting_list] # Additive single-line Doxygen assignments [REQUIRES_CPP_VERSION 17|20|23] # C++ version (default: 20) [INSTALL_OPTION option_name] # Independent installation control (default: uppercase NAMESPACE_INSTALL) + [LICENSE_FILES file_list] # Additional project-relative or absolute license/notice files ) ``` **Notes:** - The project name is automatically taken from `PROJECT_NAME` (set by the `project()` command). You must call `project(your-library)` before `cpp_library_setup()`. -- **If you specify `TESTS` or `EXAMPLES`**, call `include(CTest)` after `project()` and before `cpp_library_setup()`. +- Call `include(CTest)` at directory scope after `project()` and before + `cpp_library_setup()` to define `BUILD_TESTING`. It is required if you specify + `TESTS` or `EXAMPLES`. +- Top-level builds with `BUILD_TESTING=ON` automatically perform + [independent public-header compilation](#public-header-compilation). - Version is automatically detected from git tags (see [Version Management](#version-management) for overrides). - Installation is controlled by `INSTALL_OPTION`, or the uppercase `${NAMESPACE}_INSTALL` option when omitted. Options default to `PROJECT_IS_TOP_LEVEL`. +- Enabled installation includes the project-root `LICENSE` when present and any + `LICENSE_FILES`. See [installation guidance](#installation-strongly-discouraged) + for destinations and missing-file behavior. - `cpp_library_setup()` makes the effective `GNUInstallDirs` directory variables available to subsequent caller install rules, including when installation is disabled. - `REQUIRES_CPP_VERSION` sets the minimum C++ standard. Compiled library, test, @@ -520,7 +651,12 @@ This produces: cpp_library_map_dependency(target find_dependency_call) ``` -Maps non-namespaced targets to their package. Required only for targets like `opencv_core` where the package name cannot be inferred. Call this after `find_package()` or `CPMAddPackage()`: +Maps a dependency target to custom `find_dependency()` arguments for the declaring +CMake project only. Mappings override automatic tracking in that project, including +non-project subdirectories; independent projects do not share mappings. +Use this for non-namespaced targets like `opencv_core` where the package name cannot +be inferred, or when automatic tracking needs an override. Call this after +`find_package()` or `CPMAddPackage()`: ```cmake find_package(OpenCV 4.5.0 REQUIRED) @@ -532,13 +668,15 @@ Namespaced targets like `Qt6::Core` and `Boost::filesystem` are tracked automati ### Path Conventions -All file specifications use filenames only, automatically placed in standard directories: +Library and executable file specifications use filenames resolved under standard directories: - **HEADERS**: `include//` (e.g., `your_header.hpp` → `include/your_namespace/your_header.hpp`) - **SOURCES**: `src/` (e.g., `your_library.cpp` → `src/your_library.cpp`; omit for header-only) - **EXAMPLES**: `examples/` (e.g., `example.cpp`, `example_fail.cpp`) - **TESTS**: `tests/` (e.g., `tests.cpp`, `unit_tests.cpp`) +`LICENSE_FILES` accepts paths relative to `${PROJECT_SOURCE_DIR}` or absolute paths. + ### Library Types - **Header-only**: Specify only `HEADERS`, omit `SOURCES` @@ -628,19 +766,54 @@ Version is automatically detected from git tags: - Falls back to `0.0.0` if no tag is found (with warning) - Version used in CMake package config files -For package managers or CI systems building from source archives without git history, you can override the version using the `CPP_LIBRARY_VERSION` cache variable: +For package managers or CI systems building from source archives without Git +history, set `CPP_LIBRARY_VERSION_` to override one project's +version. Replace `` with the exact, case-sensitive name supplied to +that project's `project()` call, including any hyphens. This is the CMake project +name, not the namespace or derived package name. -```bash -cmake -DCPP_LIBRARY_VERSION=1.2.3 -B build -cmake --build build -``` +Both `cpp_library_setup()` and `cpp_library_set_version()` use this precedence: + +1. A non-empty `CPP_LIBRARY_VERSION_` override for that project. +2. A non-empty legacy `CPP_LIBRARY_VERSION` override, only when + `PROJECT_IS_TOP_LEVEL` is true. +3. The project's Git tag, with a leading `v` removed. +4. `0.0.0` with a warning when no tag is found. -This is particularly useful for vcpkg, Conan, or other package managers that don't have access to git tags. +Pass overrides as CMake cache entries when configuring the build. Empty override +values are ignored. Overriding one project's version does not change independently +named nested projects. + +Existing top-level builds using `CPP_LIBRARY_VERSION` continue to work. To override +a nested project, migrate to `CPP_LIBRARY_VERSION_`; the legacy +variable no longer overrides subprojects. A matching project-scoped override takes +precedence over the legacy variable. ### Testing Uses [doctest](https://github.com/doctest/doctest) with CTest integration. Compile-fail tests are automatically detected via `_fail` suffix in filenames. +#### Public-header compilation + +In top-level projects with `BUILD_TESTING=ON`, the normal build compiles each +header in the library's `PUBLIC` and `INTERFACE` CMake header file sets in a +separate translation unit. This includes generated headers and file sets added +after `cpp_library_setup()`. No separate option or duplicate header list is +needed. These checks aren't added when a client consumes your library as a +subproject. + +Each check uses the library's public usage requirements and configured C++ +standard, supporting C++17, C++20, and C++23. It doesn't force every library to +compile in all three modes. Unlike [clangd indexing](#clangd-and-vscode), this +checks that headers compile independently of include order. The checks run +during `cmake --build`, not during configuration or `ctest`. + +Keep every public header self-contained. If a header doesn't apply to the +configured target, guard its platform-specific contents with the C++ +preprocessor. On unsupported targets, the header must be a no-op, apart from +optionally including a configuration header. Don't maintain platform-specific +header exclusions. + ### Template Files cpp-library automatically generates infrastructure files on first configuration and when using the `init` preset: diff --git a/cmake/cpp-library-install.cmake b/cmake/cpp-library-install.cmake index 7d6b96a..a3603cd 100644 --- a/cmake/cpp-library-install.cmake +++ b/cmake/cpp-library-install.cmake @@ -18,9 +18,10 @@ # To extend this list in your project, use cpp_library_map_dependency() to explicitly map additional packages. set(_CPP_LIBRARY_SYSTEM_PACKAGES "Threads" "OpenMP" "ZLIB" "CURL" "OpenSSL") -# Registers a custom dependency mapping for find_dependency() generation +# Registers a project-local dependency mapping for find_dependency() generation. # - Precondition: TARGET is a namespaced target (e.g., "Qt6::Core", "stlab::enum-ops") or non-namespaced (e.g., "opencv_core") -# - Postcondition: FIND_DEPENDENCY_CALL stored for TARGET, used in package config generation +# - Postcondition: FIND_DEPENDENCY_CALL overrides TARGET's requirement only for libraries +# declared in this CMake project, including its non-project subdirectories # - FIND_DEPENDENCY_CALL should be the complete arguments to find_dependency(), including version if needed # - Multiple components of the same package (same name+version+args) are automatically merged into one call # - Examples: @@ -31,9 +32,11 @@ set(_CPP_LIBRARY_SYSTEM_PACKAGES "Threads" "OpenMP" "ZLIB" "CURL" "OpenSSL") # - cpp_library_map_dependency("opencv_core" "OpenCV 4.5.0") # - Note: Most namespaced dependencies work automatically; only use when automatic detection fails or special syntax needed function(cpp_library_map_dependency TARGET FIND_DEPENDENCY_CALL) - set_property(GLOBAL PROPERTY _CPP_LIBRARY_DEPENDENCY_MAP_${TARGET} "${FIND_DEPENDENCY_CALL}") - # Track all mapped targets for cleanup in tests - set_property(GLOBAL APPEND PROPERTY _CPP_LIBRARY_ALL_MAPPED_TARGETS "${TARGET}") + string(SHA256 project_key "${PROJECT_BINARY_DIR}") + set(mapping_property "_CPP_LIBRARY_DEPENDENCY_MAP_${project_key}_${TARGET}") + set_property(GLOBAL PROPERTY "${mapping_property}" "${FIND_DEPENDENCY_CALL}") + # Track property names for cleanup in script-mode tests. + set_property(GLOBAL APPEND PROPERTY _CPP_LIBRARY_ALL_MAPPING_PROPERTIES "${mapping_property}") endfunction() # Generates find_dependency() calls for target's INTERFACE link libraries @@ -58,33 +61,23 @@ function(_cpp_library_generate_dependencies OUTPUT_VAR TARGET_NAME NAMESPACE) set(${OUTPUT_VAR} "" PARENT_SCOPE) return() endif() + + get_target_property(TARGET_BINARY_DIR ${TARGET_NAME} BINARY_DIR) + get_directory_property(MAPPING_PROJECT DIRECTORY "${TARGET_BINARY_DIR}" + DEFINITION PROJECT_BINARY_DIR) + string(SHA256 project_key "${MAPPING_PROJECT}") # Process each linked library foreach(LIB IN LISTS LINK_LIBS) - # Handle BUILD_INTERFACE generator expressions - # When re-exporting dependencies from external packages, they must be wrapped in BUILD_INTERFACE - # to avoid CMake export errors, but we still want to track them for find_dependency() - if(LIB MATCHES "^\\$]+)>$") - set(EXTRACTED_TARGET "${CMAKE_MATCH_1}") - # Only process if it's a namespaced target (external dependency) - # Non-namespaced targets in BUILD_INTERFACE are local build targets - if(EXTRACTED_TARGET MATCHES "::") - set(LIB "${EXTRACTED_TARGET}") - message(DEBUG "cpp-library: Extracted ${LIB} from BUILD_INTERFACE generator expression") - else() - # Skip non-namespaced BUILD_INTERFACE targets (local build targets) - message(DEBUG "cpp-library: Skipping non-namespaced BUILD_INTERFACE target: ${EXTRACTED_TARGET}") - continue() - endif() - elseif(LIB MATCHES "^\\$<") - # Skip other generator expressions (INSTALL_INTERFACE, etc.) + if(LIB MATCHES "^\\$<") continue() endif() set(FIND_DEP_CALL "") # Check for custom mapping first (allows overrides for non-namespaced targets) - get_property(CUSTOM_MAPPING GLOBAL PROPERTY _CPP_LIBRARY_DEPENDENCY_MAP_${LIB}) + get_property(CUSTOM_MAPPING GLOBAL + PROPERTY "_CPP_LIBRARY_DEPENDENCY_MAP_${project_key}_${LIB}") if(CUSTOM_MAPPING) # Use explicit custom mapping @@ -456,6 +449,8 @@ endfunction() # - Supports header-only (INTERFACE) and compiled libraries, uses SameMajorVersion compatibility # - Installation is controlled via INSTALL_OPTION or uppercase ${NAMESPACE}_INSTALL # (defaults to PROJECT_IS_TOP_LEVEL) +# - Installs the project's existing LICENSE and LICENSE_FILES under the package's license directory +# - Missing explicit LICENSE_FILES are configuration errors when installation is enabled function(_cpp_library_setup_install) set(oneValueArgs NAME # Target name (e.g., "stlab-enum-ops") @@ -466,6 +461,7 @@ function(_cpp_library_setup_install) ) set(multiValueArgs HEADERS # List of header file paths (for FILE_SET support check) + LICENSE_FILES # Additional project-relative or absolute license/notice files ) cmake_parse_arguments(ARG "" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) @@ -504,6 +500,32 @@ function(_cpp_library_setup_install) # Include required CMake modules (deferred from top-level to avoid requiring project() before include) include(GNUInstallDirs) include(CMakePackageConfigHelpers) + + set(license_files) + if(EXISTS "${PROJECT_SOURCE_DIR}/LICENSE" AND NOT IS_DIRECTORY "${PROJECT_SOURCE_DIR}/LICENSE") + list(APPEND license_files "${PROJECT_SOURCE_DIR}/LICENSE") + endif() + foreach(license IN LISTS ARG_LICENSE_FILES) + get_filename_component(license_path "${license}" ABSOLUTE BASE_DIR "${PROJECT_SOURCE_DIR}") + if(NOT EXISTS "${license_path}" OR IS_DIRECTORY "${license_path}") + message(FATAL_ERROR "cpp-library: License file not found: ${license_path}") + endif() + list(APPEND license_files "${license_path}") + endforeach() + if(license_files) + list(REMOVE_DUPLICATES license_files) + set(license_names) + foreach(license IN LISTS license_files) + get_filename_component(license_name "${license}" NAME) + if(license_name IN_LIST license_names) + message(FATAL_ERROR + "cpp-library: License files have the same installed name: ${license_name}") + endif() + list(APPEND license_names "${license_name}") + endforeach() + install(FILES ${license_files} + DESTINATION "${CMAKE_INSTALL_DATADIR}/licenses/${ARG_PACKAGE_NAME}") + endif() # Install the library target # For header-only libraries (INTERFACE), this installs the target metadata diff --git a/cmake/cpp-library-setup.cmake b/cmake/cpp-library-setup.cmake index 8e83115..6520910 100644 --- a/cmake/cpp-library-setup.cmake +++ b/cmake/cpp-library-setup.cmake @@ -2,12 +2,14 @@ # # cpp-library-setup.cmake - Core library setup functionality -# Returns version string from CPP_LIBRARY_VERSION cache variable (if set), git tag (with 'v' prefix removed), or -# "0.0.0" fallback +# Returns this project's scoped override, top-level legacy override, Git-tag version, +# or "0.0.0" when no tag is found. function(_cpp_library_get_git_version OUTPUT_VAR) - # If CPP_LIBRARY_VERSION is set (e.g., by vcpkg or other package manager via -DCPP_LIBRARY_VERSION=x.y.z), - # use it instead of trying to query git (which may not be available in source archives) - if(DEFINED CPP_LIBRARY_VERSION AND NOT CPP_LIBRARY_VERSION STREQUAL "") + set(version_override "CPP_LIBRARY_VERSION_${PROJECT_NAME}") + if(DEFINED "${version_override}" AND NOT "${${version_override}}" STREQUAL "") + set(${OUTPUT_VAR} "${${version_override}}" PARENT_SCOPE) + return() + elseif(PROJECT_IS_TOP_LEVEL AND DEFINED CPP_LIBRARY_VERSION AND NOT CPP_LIBRARY_VERSION STREQUAL "") set(${OUTPUT_VAR} "${CPP_LIBRARY_VERSION}" PARENT_SCOPE) return() endif() @@ -71,6 +73,7 @@ function(_cpp_library_setup_core) set(multiValueArgs HEADERS SOURCES + LICENSE_FILES ) cmake_parse_arguments(ARG "" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) @@ -81,6 +84,9 @@ function(_cpp_library_setup_core) if(DEFINED ARG_INSTALL_OPTION) list(APPEND install_args INSTALL_OPTION "${ARG_INSTALL_OPTION}") endif() + if(ARG_LICENSE_FILES) + list(APPEND install_args LICENSE_FILES ${ARG_LICENSE_FILES}) + endif() # Get version from git tags if not provided if(NOT ARG_VERSION) diff --git a/cpp-library.cmake b/cpp-library.cmake index 9a86c31..80f210d 100644 --- a/cpp-library.cmake +++ b/cpp-library.cmake @@ -17,10 +17,9 @@ get_filename_component(CPP_LIBRARY_ROOT "${CMAKE_CURRENT_LIST_FILE}" DIRECTORY) # cpp_library_set_version() # # Now PROJECT_VERSION and related variables are set from git tags # -# The function respects CPP_LIBRARY_VERSION if set (e.g., by package managers), -# otherwise queries git tags, stripping the 'v' prefix if present. +# Uses CPP_LIBRARY_VERSION_ before Git tags, stripping the 'v' prefix +# from tags. Legacy CPP_LIBRARY_VERSION applies only to the top-level project. function(cpp_library_set_version) - # Get version from git tags (respects CPP_LIBRARY_VERSION override) _cpp_library_get_git_version(GIT_VERSION) # Parse version components @@ -41,7 +40,7 @@ function(cpp_library_set_version) set(PROJECT_VERSION_MINOR ${VERSION_MINOR} PARENT_SCOPE) set(PROJECT_VERSION_PATCH ${VERSION_PATCH} PARENT_SCOPE) - message(STATUS "cpp-library: Set project version to ${GIT_VERSION} from git tags") + message(STATUS "cpp-library: Set project version to ${GIT_VERSION}") endfunction() # Enable dependency tracking for accurate find_dependency() generation @@ -164,6 +163,8 @@ endfunction() # - When PROJECT_IS_TOP_LEVEL: also configures templates, testing, and docs # - Installation is controlled by INSTALL_OPTION or uppercase ${NAMESPACE}_INSTALL # (defaults to PROJECT_IS_TOP_LEVEL) +# - Installs an existing project-root LICENSE and optional LICENSE_FILES; relative paths +# are project-root relative, and missing explicit files are errors when installation is enabled function(cpp_library_setup) # Parse arguments set(oneValueArgs @@ -180,6 +181,7 @@ function(cpp_library_setup) DOCS_EXCLUDE_SYMBOLS # Symbols to exclude from docs DOCS_INPUTS # Additional documentation files or directories DOCS_OPTIONS # Single-line Doxygen assignments applied after the template + LICENSE_FILES # Additional project-relative or absolute license/notice files ) cmake_parse_arguments(ARG "" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) @@ -187,7 +189,7 @@ function(cpp_library_setup) if("INSTALL_OPTION" IN_LIST ARG_KEYWORDS_MISSING_VALUES) message(FATAL_ERROR "cpp_library_setup: INSTALL_OPTION requires a value") endif() - foreach(keyword DOCS_INPUTS DOCS_OPTIONS) + foreach(keyword DOCS_INPUTS DOCS_OPTIONS LICENSE_FILES) if(keyword IN_LIST ARG_KEYWORDS_MISSING_VALUES) message(FATAL_ERROR "cpp_library_setup: ${keyword} requires a value") endif() @@ -196,6 +198,9 @@ function(cpp_library_setup) if(DEFINED ARG_INSTALL_OPTION) list(APPEND install_args INSTALL_OPTION "${ARG_INSTALL_OPTION}") endif() + if(ARG_LICENSE_FILES) + list(APPEND install_args LICENSE_FILES ${ARG_LICENSE_FILES}) + endif() # Validate required arguments if(NOT ARG_DESCRIPTION) @@ -311,6 +316,12 @@ function(cpp_library_setup) return() # Early return for lightweight consumer mode endif() + if(BUILD_TESTING) + set_property(TARGET "${ARG_NAME}" PROPERTY VERIFY_INTERFACE_HEADER_SETS ON) + add_custom_target("${ARG_NAME}_check_headers" ALL) + add_dependencies("${ARG_NAME}_check_headers" "${ARG_NAME}_verify_interface_header_sets") + endif() + _cpp_library_setup_package_test("${PACKAGE_NAME}") # Copy static template files (like .clang-format, .gitignore, CMakePresets.json, etc.) diff --git a/templates/.vscode/tasks.json b/templates/.vscode/tasks.json index 297e047..df55722 100644 --- a/templates/.vscode/tasks.json +++ b/templates/.vscode/tasks.json @@ -240,7 +240,7 @@ "$gcc", "$msCompile" ], - "detail": "Release build for installation with CPM_USE_LOCAL_PACKAGES enabled for testing installed packages Requires the CMake Tools extension (ms-vscode.cmake-tools) — without it, this task fails to start.", + "detail": "Release build for installation, preferring locally installed dependencies before fetching. Requires the CMake Tools extension (ms-vscode.cmake-tools) — without it, this task fails to start.", "windows": { "options": { "shell": { diff --git a/templates/CMakePresets.json b/templates/CMakePresets.json index 99ba84a..f6d7e7a 100644 --- a/templates/CMakePresets.json +++ b/templates/CMakePresets.json @@ -77,7 +77,7 @@ { "name": "install", "displayName": "Install Configuration", - "description": "Release build for installation with CPM_USE_LOCAL_PACKAGES enabled for testing installed packages", + "description": "Release build for installation, preferring locally installed dependencies before fetching", "binaryDir": "${sourceDir}/build/install", "generator": "Ninja", "cacheVariables": { diff --git a/tests/install/CMakeLists.txt b/tests/install/CMakeLists.txt index 8b9f8b6..7ab3ebd 100644 --- a/tests/install/CMakeLists.txt +++ b/tests/install/CMakeLists.txt @@ -5,6 +5,7 @@ # Run as: cmake -P tests/install/CMakeLists.txt cmake_minimum_required(VERSION 3.20) +set(PROJECT_BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}") # Include the modules we're testing include(${CMAKE_CURRENT_LIST_DIR}/../../cmake/cpp-library-install.cmake) @@ -29,30 +30,42 @@ function(get_target_property OUTPUT_VAR TARGET PROPERTY) else() set(${OUTPUT_VAR} "NOTFOUND" PARENT_SCOPE) endif() + elseif(PROPERTY STREQUAL "BINARY_DIR") + set(${OUTPUT_VAR} "${CMAKE_CURRENT_BINARY_DIR}" PARENT_SCOPE) else() - # For other properties, return NOTFOUND since we're only mocking INTERFACE_LINK_LIBRARIES set(${OUTPUT_VAR} "NOTFOUND" PARENT_SCOPE) endif() endfunction() +# Supplies the owning project for mock targets without configured directories. +function(get_directory_property OUTPUT_VAR DIRECTORY_KEYWORD DIRECTORY_PATH DEFINITION_KEYWORD VARIABLE) + if(NOT DIRECTORY_KEYWORD STREQUAL "DIRECTORY" + OR NOT DIRECTORY_PATH STREQUAL CMAKE_CURRENT_BINARY_DIR + OR NOT DEFINITION_KEYWORD STREQUAL "DEFINITION" + OR NOT VARIABLE STREQUAL "PROJECT_BINARY_DIR") + message(FATAL_ERROR "Unexpected mock directory lookup: ${ARGN}") + endif() + set(${OUTPUT_VAR} "${PROJECT_BINARY_DIR}" PARENT_SCOPE) +endfunction() + # Helper macro to run a test macro(run_test TEST_NAME) math(EXPR TEST_COUNT "${TEST_COUNT} + 1") message(STATUS "Running test ${TEST_COUNT}: ${TEST_NAME}") # Clear global state before each test - set_property(GLOBAL PROPERTY _CPP_LIBRARY_PKG_KEYS "") get_property(ALL_PKG_KEYS GLOBAL PROPERTY _CPP_LIBRARY_PKG_KEYS) foreach(prop IN LISTS ALL_PKG_KEYS) set_property(GLOBAL PROPERTY "_CPP_LIBRARY_PKG_COMPONENTS_${prop}") endforeach() + set_property(GLOBAL PROPERTY _CPP_LIBRARY_PKG_KEYS "") # Clear all dependency mappings from previous tests - get_property(ALL_MAPPED_TARGETS GLOBAL PROPERTY _CPP_LIBRARY_ALL_MAPPED_TARGETS) - foreach(target IN LISTS ALL_MAPPED_TARGETS) - set_property(GLOBAL PROPERTY _CPP_LIBRARY_DEPENDENCY_MAP_${target}) + get_property(ALL_MAPPING_PROPERTIES GLOBAL PROPERTY _CPP_LIBRARY_ALL_MAPPING_PROPERTIES) + foreach(property IN LISTS ALL_MAPPING_PROPERTIES) + set_property(GLOBAL PROPERTY "${property}") endforeach() - set_property(GLOBAL PROPERTY _CPP_LIBRARY_ALL_MAPPED_TARGETS "") + set_property(GLOBAL PROPERTY _CPP_LIBRARY_ALL_MAPPING_PROPERTIES "") # Clear dependency provider tracking state get_property(ALL_TRACKED_DEPS GLOBAL PROPERTY _CPP_LIBRARY_ALL_TRACKED_DEPS) @@ -89,6 +102,7 @@ endmacro() 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) +include(${CMAKE_CURRENT_LIST_DIR}/test_mapping_scope.cmake) # Print summary message(STATUS "") diff --git a/tests/install/README.md b/tests/install/README.md index 9e85c69..81c5c22 100644 --- a/tests/install/README.md +++ b/tests/install/README.md @@ -27,7 +27,8 @@ The test suite covers: 5. **Custom Mappings**: Manual dependency mappings via `cpp_library_map_dependency()` 6. **Non-namespaced Targets**: Custom mapping for targets like `opencv_core` 7. **Deduplication**: Duplicate components and dependencies removed -8. **Generator Expressions**: BUILD_INTERFACE dependencies skipped +8. **Generator Expressions**: Build-only links, including namespaced and explicitly + mapped targets, do not become installed requirements 9. **Edge Cases**: Empty libraries, different versions, override behavior ## Installation Round Trips @@ -39,8 +40,10 @@ cmake -P tests/install/test_nested_install.cmake ``` On Windows, run it from an x64 Visual Studio developer environment. It builds and -installs nested parent/leaf packages, then builds and runs separate installed -consumers. The leaf is tested as both static and shared, with explicit versioned +installs independent packages in nested directories, then builds and runs installed +consumers. Their local interface target links both installed packages to +exercise transitive linkage without source-built dependency export workarounds. +The leaf is tested as both static and shared, with explicit versioned C ABI exports from a `.def` file for the Windows DLL. The consumers exercise cpp-library's test and example executable setup in diff --git a/tests/install/fixtures/consumer/CMakeLists.txt b/tests/install/fixtures/consumer/CMakeLists.txt index e05a181..fbb935d 100644 --- a/tests/install/fixtures/consumer/CMakeLists.txt +++ b/tests/install/fixtures/consumer/CMakeLists.txt @@ -3,9 +3,13 @@ project(consumer LANGUAGES CXX) include(CTest) include("${TOOLKIT_SOURCE}/cpp-library.cmake") find_package(stlab-parent 1.0.0 REQUIRED) +find_package(stlab-leaf 1.0.0 REQUIRED) +add_library(client-dependencies INTERFACE) +add_library(stlab::client-dependencies ALIAS client-dependencies) +target_link_libraries(client-dependencies INTERFACE stlab::parent stlab::leaf) add_executable(ordinary-consumer tests/consumer.cpp) set_target_properties(ordinary-consumer PROPERTIES CXX_EXTENSIONS ON) -target_link_libraries(ordinary-consumer PRIVATE stlab::parent) +target_link_libraries(ordinary-consumer PRIVATE stlab::client-dependencies) get_target_property(consumer_extensions ordinary-consumer CXX_EXTENSIONS) if(NOT consumer_extensions) message(FATAL_ERROR "Installed library changed consumer dialect") @@ -19,9 +23,9 @@ endif() # These standalone main functions need no doctest headers or runtime. add_library(doctest::doctest INTERFACE IMPORTED) _cpp_library_setup_executables( - NAME parent NAMESPACE stlab TYPE tests EXECUTABLES consumer.cpp) + NAME client-dependencies NAMESPACE stlab TYPE tests EXECUTABLES consumer.cpp) _cpp_library_setup_executables( - NAME parent NAMESPACE stlab TYPE examples EXECUTABLES example.cpp) + NAME client-dependencies NAMESPACE stlab TYPE examples EXECUTABLES example.cpp) set_target_properties(consumer PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/client apps/tests") set_target_properties(example PROPERTIES diff --git a/tests/install/fixtures/consumer/examples/example.cpp b/tests/install/fixtures/consumer/examples/example.cpp index 6c8d566..fa09be3 100644 --- a/tests/install/fixtures/consumer/examples/example.cpp +++ b/tests/install/fixtures/consumer/examples/example.cpp @@ -1,3 +1,4 @@ +#include #include -int main() { return stlab::parent() == 42 ? 0 : 1; } +int main() { return stlab::parent() + stlab::leaf() == 42 ? 0 : 1; } diff --git a/tests/install/fixtures/consumer/tests/consumer.cpp b/tests/install/fixtures/consumer/tests/consumer.cpp index 6c8d566..fa09be3 100644 --- a/tests/install/fixtures/consumer/tests/consumer.cpp +++ b/tests/install/fixtures/consumer/tests/consumer.cpp @@ -1,3 +1,4 @@ +#include #include -int main() { return stlab::parent() == 42 ? 0 : 1; } +int main() { return stlab::parent() + stlab::leaf() == 42 ? 0 : 1; } diff --git a/tests/install/fixtures/nested/CMakeLists.txt b/tests/install/fixtures/nested/CMakeLists.txt index de9b222..3fd5d5f 100644 --- a/tests/install/fixtures/nested/CMakeLists.txt +++ b/tests/install/fixtures/nested/CMakeLists.txt @@ -14,22 +14,32 @@ if(LEGACY_OPTIONS) elseif(MISSING_INSTALL_OPTION) set(install_args INSTALL_OPTION) endif() +set(license_args) +if(LICENSE_TEST) + set(license_args LICENSE_FILES "licenses/parent notice.txt" + "${CMAKE_CURRENT_SOURCE_DIR}/licenses/absolute notice.txt") +endif() +if(MISSING_LICENSE) + set(license_args LICENSE_FILES missing-notice.txt) +elseif(EMPTY_LICENSE_FILES) + set(license_args LICENSE_FILES) +elseif(COLLIDING_LICENSE_FILES) + set(license_args LICENSE_FILES licenses/LICENSE) +elseif(DUPLICATE_LICENSE_FILES) + list(APPEND license_args LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE") +endif() cpp_library_setup( DESCRIPTION "Parent package fixture" NAMESPACE stlab HEADERS parent.hpp + ${license_args} ${install_args}) if(EXCLUDE_LEAF_FROM_ALL) add_subdirectory(leaf EXCLUDE_FROM_ALL) else() add_subdirectory(leaf) endif() -# Resolve the installed target downstream, even when leaf is not exported in this build. -target_link_libraries(parent INTERFACE - $ - $>) -cpp_library_map_dependency("stlab::leaf" "stlab-leaf 1.0.0") if(INVALID_PACKAGE STREQUAL "parent") add_library(UnknownParent::dep INTERFACE IMPORTED) - target_link_libraries(parent INTERFACE $) + target_link_libraries(parent INTERFACE UnknownParent::dep) endif() diff --git a/tests/install/fixtures/nested/include/stlab/parent.hpp b/tests/install/fixtures/nested/include/stlab/parent.hpp index f1a108f..9f0ec95 100644 --- a/tests/install/fixtures/nested/include/stlab/parent.hpp +++ b/tests/install/fixtures/nested/include/stlab/parent.hpp @@ -1,6 +1,5 @@ #pragma once -#include namespace stlab { -inline int parent() { return 20 + leaf(); } +inline int parent() { return 20; } } diff --git a/tests/install/fixtures/nested/leaf/CMakeLists.txt b/tests/install/fixtures/nested/leaf/CMakeLists.txt index 7586bea..66cef9b 100644 --- a/tests/install/fixtures/nested/leaf/CMakeLists.txt +++ b/tests/install/fixtures/nested/leaf/CMakeLists.txt @@ -1,15 +1,20 @@ include("${TOOLKIT_SOURCE}/cpp-library.cmake") project(leaf LANGUAGES CXX) -set(CPP_LIBRARY_VERSION 1.0.0) +set(CPP_LIBRARY_VERSION_leaf 1.0.0) set(install_args INSTALL_OPTION STLAB_LEAF_INSTALL) if(LEGACY_OPTIONS) set(install_args) endif() +set(license_args) +if(LICENSE_TEST) + set(license_args LICENSE_FILES "licenses/leaf notice.txt") +endif() cpp_library_setup( DESCRIPTION "Leaf package fixture" NAMESPACE stlab HEADERS leaf.hpp SOURCES leaf.cpp + ${license_args} ${install_args}) if(PACKAGE_TEST_EXTRA) add_subdirectory(extra EXCLUDE_FROM_ALL) @@ -35,5 +40,5 @@ target_include_directories(leaf PUBLIC target_compile_definitions(leaf PRIVATE LEAF_BUILD) if(INVALID_PACKAGE STREQUAL "leaf") add_library(UnknownLeaf::dep INTERFACE IMPORTED) - target_link_libraries(leaf INTERFACE $) + target_link_libraries(leaf INTERFACE UnknownLeaf::dep) endif() diff --git a/tests/install/fixtures/nested/leaf/extra/CMakeLists.txt b/tests/install/fixtures/nested/leaf/extra/CMakeLists.txt index b93986a..44734a1 100644 --- a/tests/install/fixtures/nested/leaf/extra/CMakeLists.txt +++ b/tests/install/fixtures/nested/leaf/extra/CMakeLists.txt @@ -1,7 +1,7 @@ cmake_minimum_required(VERSION 3.24) include("${TOOLKIT_SOURCE}/cpp-library.cmake") project(extra LANGUAGES CXX) -set(CPP_LIBRARY_VERSION 1.0.0) +set(CPP_LIBRARY_VERSION_extra 1.0.0) cpp_library_setup( DESCRIPTION "Transitive packaging dependency fixture" NAMESPACE stlab diff --git a/tests/install/test_dependency_mapping.cmake b/tests/install/test_dependency_mapping.cmake index 63ac1c7..cba60de 100644 --- a/tests/install/test_dependency_mapping.cmake +++ b/tests/install/test_dependency_mapping.cmake @@ -109,12 +109,16 @@ mock_target_links(test13_target) _cpp_library_generate_dependencies(RESULT test13_target "mylib") verify_output("${RESULT}" "" "Test 13") -# Test 14: Generator expressions should be skipped +# Test 14: Build-only links must not become installed package requirements run_test("Generator expressions skipped") set_property(GLOBAL PROPERTY _CPP_LIBRARY_PROVIDER_INSTALLED TRUE) -mock_target_links(test14_target "Threads::Threads" "$") +set_property(GLOBAL PROPERTY "_CPP_LIBRARY_TRACKED_DEP_BuildOnly" "BuildOnly 1.0 CONFIG") +cpp_library_map_dependency("MappedBuildOnly::dep" "MappedBuildOnly 2.0 CONFIG") +mock_target_links(test14_target "Threads::Threads" "$" + "$" "$" + "$>") _cpp_library_generate_dependencies(RESULT test14_target "mylib") -verify_output("${RESULT}" "find_dependency(Threads)" "Test 14") +verify_output("${RESULT}" "find_dependency(Threads)" "Build-only dependencies are not installed requirements") # Test 15: Multiple Boost components (same package, different components) run_test("Boost with multiple components") @@ -154,3 +158,20 @@ _cpp_library_generate_dependencies(RESULT test18_target "stlab") set(EXPECTED "find_dependency(stlab-enum-ops 1.0.0)\nfind_dependency(Qt6 6.5.0 COMPONENTS Core Widgets)\nfind_dependency(OpenCV 4.5.0)\nfind_dependency(Threads)\nfind_dependency(OpenMP)") verify_output("${RESULT}" "${EXPECTED}" "Test 18") +set_property(GLOBAL PROPERTY _CPP_LIBRARY_PKG_KEYS "ResetProbe<|>1.0<|>" "OtherProbe<|>2.0<|>") +set_property(GLOBAL PROPERTY "_CPP_LIBRARY_PKG_COMPONENTS_ResetProbe<|>1.0<|>" Core) +set_property(GLOBAL PROPERTY "_CPP_LIBRARY_PKG_COMPONENTS_OtherProbe<|>2.0<|>" Network) +get_property(previous_package_keys GLOBAL PROPERTY _CPP_LIBRARY_PKG_KEYS) + +run_test("Component state does not survive the next case") +foreach(key IN LISTS previous_package_keys) + get_property(remaining_components GLOBAL PROPERTY "_CPP_LIBRARY_PKG_COMPONENTS_${key}") + verify_output("${remaining_components}" "" "Previous package components were cleared") +endforeach() +get_property(provider_installed GLOBAL PROPERTY _CPP_LIBRARY_PROVIDER_INSTALLED) +verify_output("${provider_installed}" "TRUE" "Provider fixture remains installed") +cpp_library_map_dependency("ResetProbe::Widgets" "ResetProbe 1.0 COMPONENTS Widgets") +mock_target_links(reset_probe "ResetProbe::Widgets") +_cpp_library_generate_dependencies(RESULT reset_probe "mylib") +verify_output("${RESULT}" "find_dependency(ResetProbe 1.0 COMPONENTS Widgets)" "Next case has only its own components") + diff --git a/tests/install/test_mapping_scope.cmake b/tests/install/test_mapping_scope.cmake new file mode 100644 index 0000000..e5fff76 --- /dev/null +++ b/tests/install/test_mapping_scope.cmake @@ -0,0 +1,103 @@ +# SPDX-License-Identifier: BSL-1.0 +# +# Included by the dependency-mapping harness; configures real nested projects. +run_test("Dependency mappings stay within their owning project") +get_filename_component(toolkit_source "${CMAKE_CURRENT_LIST_DIR}/../.." ABSOLUTE) +string(RANDOM LENGTH 16 ALPHABET 0123456789abcdef test_id) +set(mapping_root "${toolkit_source}/build/mapping-scope-${test_id}") +file(MAKE_DIRECTORY "${mapping_root}/source/child/helper" "${mapping_root}/source/sibling") +file(WRITE "${mapping_root}/source/CMakeLists.txt" [=[ +cmake_minimum_required(VERSION 3.24) +include("${TOOLKIT_SOURCE}/cpp-library.cmake") +cpp_library_enable_dependency_tracking() +project(parent LANGUAGES CXX) +include("${TOOLKIT_SOURCE}/cmake/cpp-library-install.cmake") +add_library(cel::parser INTERFACE IMPORTED GLOBAL) +set(CPM_PACKAGES cel-parser) +set(CPM_PACKAGE_cel-parser_VERSION 1.1.0) +add_library(parent INTERFACE) +target_link_libraries(parent INTERFACE cel::parser) +if(PARENT_OVERRIDE) + cpp_library_map_dependency("cel::parser" "cel-parser 1.2.0 CONFIG") +endif() +_cpp_library_generate_dependencies(before parent cel) +add_subdirectory(child) +add_subdirectory(sibling) +_cpp_library_generate_dependencies(after parent cel) +if(NOT "${before}" STREQUAL "${after}") + message(FATAL_ERROR "Nested mappings changed parent: '${before}' -> '${after}'") +endif() +_cpp_library_setup_install(NAME parent PACKAGE_NAME cel-parent VERSION 1.0.0 + NAMESPACE cel INSTALL_OPTION PARENT_INSTALL) +]=]) +file(WRITE "${mapping_root}/source/child/CMakeLists.txt" [=[ +project(child LANGUAGES CXX) +add_library(child INTERFACE) +target_link_libraries(child INTERFACE cel::parser) +add_subdirectory(helper) +_cpp_library_generate_dependencies(result child cel) +if(NOT result STREQUAL "find_dependency(cel-parser 1.0.2 CONFIG)") + message(FATAL_ERROR "Child lost its project mapping: '${result}'") +endif() +_cpp_library_setup_install(NAME child PACKAGE_NAME cel-child VERSION 1.0.0 + NAMESPACE cel INSTALL_OPTION CHILD_INSTALL) +]=]) +file(WRITE "${mapping_root}/source/child/helper/CMakeLists.txt" [=[ +cpp_library_map_dependency("cel::parser" "cel-parser 1.0.2 CONFIG") +# Resolve a different project's target from this helper directory. +_cpp_library_generate_dependencies(result parent cel) +if(PARENT_OVERRIDE) + set(expected "find_dependency(cel-parser 1.2.0 CONFIG)") +else() + set(expected "find_dependency(cel-parser 1.1.0)") +endif() +if(NOT result STREQUAL expected) + message(FATAL_ERROR "Target ownership was ignored: '${result}', expected '${expected}'") +endif() +]=]) +file(WRITE "${mapping_root}/source/sibling/CMakeLists.txt" [=[ +project(sibling LANGUAGES CXX) +add_library(sibling INTERFACE) +target_link_libraries(sibling INTERFACE cel::parser) +_cpp_library_generate_dependencies(result sibling cel) +if(NOT result STREQUAL "find_dependency(cel-parser 1.1.0)") + message(FATAL_ERROR "Sibling inherited another project's mapping: '${result}'") +endif() +_cpp_library_setup_install(NAME sibling PACKAGE_NAME cel-sibling VERSION 1.0.0 + NAMESPACE cel INSTALL_OPTION SIBLING_INSTALL) +]=]) +foreach(parent_override OFF ON) + set(binary "${mapping_root}/build-${parent_override}") + execute_process(COMMAND "${CMAKE_COMMAND}" + -S "${mapping_root}/source" -B "${binary}" + "-DTOOLKIT_SOURCE=${toolkit_source}" "-DPARENT_OVERRIDE=${parent_override}" + -DPARENT_INSTALL=ON -DCHILD_INSTALL=ON -DSIBLING_INSTALL=ON + RESULT_VARIABLE result OUTPUT_VARIABLE out ERROR_VARIABLE err) + if(NOT result EQUAL 0) + message(STATUS "Nested mapping diagnostics:\n${out}\n${err}") + endif() + verify_output("${result}" "0" "Nested mapping configure (${parent_override})") + if(result EQUAL 0) + if(parent_override) + set(parent_dependency "find_dependency(cel-parser 1.2.0 CONFIG)") + else() + set(parent_dependency "find_dependency(cel-parser 1.1.0)") + endif() + foreach(package parent child sibling) + if(package STREQUAL "parent") + set(config "${binary}/cel-parentConfig.cmake") + set(expected "${parent_dependency}") + elseif(package STREQUAL "child") + set(config "${binary}/child/cel-childConfig.cmake") + set(expected "find_dependency(cel-parser 1.0.2 CONFIG)") + else() + set(config "${binary}/sibling/cel-siblingConfig.cmake") + set(expected "find_dependency(cel-parser 1.1.0)") + endif() + file(READ "${config}" content) + string(REGEX MATCHALL "find_dependency\\([^\n]*\\)" actual "${content}") + verify_output("${actual}" "${expected}" "Deferred ${package} mapping (${parent_override})") + endforeach() + endif() +endforeach() +file(REMOVE_RECURSE "${mapping_root}") diff --git a/tests/install/test_nested_install.cmake b/tests/install/test_nested_install.cmake index a85eba3..52a5643 100644 --- a/tests/install/test_nested_install.cmake +++ b/tests/install/test_nested_install.cmake @@ -24,7 +24,7 @@ function(run_command) endif() endfunction() -# Checks generated/installed package artifacts, including the dependency direction. +# Checks generated/installed package artifacts and dependency requirements. function(check_package prefix package present dependencies) set(config_dir "${prefix}/lib/cmake/stlab-${package}") foreach(suffix Config.cmake ConfigVersion.cmake Targets.cmake) @@ -52,12 +52,61 @@ function(run_case name parent_installed leaf_installed shared) set(prefix "${case_root}/prefix") file(MAKE_DIRECTORY "${source}") file(COPY "${CMAKE_CURRENT_LIST_DIR}/fixtures/nested/" DESTINATION "${source}") + if(NOT name STREQUAL "no-licenses") + file(WRITE "${source}/LICENSE" "parent license\n") + endif() + if(NOT name STREQUAL "no-licenses" AND NOT name STREQUAL "no-leaf-license") + file(WRITE "${source}/leaf/LICENSE" "leaf license\n") + endif() + file(MAKE_DIRECTORY "${source}/licenses" "${source}/leaf/licenses") + file(WRITE "${source}/licenses/parent notice.txt" "parent notice\n") + file(WRITE "${source}/licenses/absolute notice.txt" "absolute notice\n") + file(WRITE "${source}/leaf/licenses/leaf notice.txt" "leaf notice\n") run_command("${CMAKE_COMMAND}" -S "${source}" -B "${binary}" -G Ninja - "-DTOOLKIT_SOURCE=${toolkit_source}" "-DBUILD_SHARED_LIBS=${shared}" ${ARGN}) + "-DTOOLKIT_SOURCE=${toolkit_source}" "-DBUILD_SHARED_LIBS=${shared}" -DLICENSE_TEST=ON ${ARGN}) run_command("${CMAKE_COMMAND}" --build "${binary}") run_command("${CMAKE_COMMAND}" --install "${binary}" --prefix "${prefix}") - check_package("${prefix}" parent "${parent_installed}" "find_dependency(stlab-leaf 1.0.0)") + check_package("${prefix}" parent "${parent_installed}" "") check_package("${prefix}" leaf "${leaf_installed}" "") + set(datadir share) + if(name STREQUAL "custom-datadir") + set(datadir "custom data") + endif() + foreach(package parent leaf) + set(license_dir "${prefix}/${datadir}/licenses/stlab-${package}") + if(NOT ${package}_installed) + if(EXISTS "${license_dir}") + message(FATAL_ERROR "Unselected package licenses installed: ${license_dir}") + endif() + continue() + endif() + set(license_files "${package} notice.txt") + if(package STREQUAL "parent") + list(APPEND license_files "absolute notice.txt") + endif() + if(EXISTS "${source}/${package}/LICENSE" OR + (package STREQUAL "parent" AND EXISTS "${source}/LICENSE")) + list(APPEND license_files LICENSE) + elseif(EXISTS "${license_dir}/LICENSE") + message(FATAL_ERROR "Absent project license was installed: ${license_dir}/LICENSE") + endif() + foreach(filename IN LISTS license_files) + if(NOT EXISTS "${license_dir}/${filename}") + message(FATAL_ERROR "Missing package license: ${license_dir}/${filename}") + endif() + file(READ "${license_dir}/${filename}" actual) + if(filename STREQUAL "LICENSE") + set(expected "${package} license\n") + elseif(filename STREQUAL "absolute notice.txt") + set(expected "absolute notice\n") + else() + set(expected "${package} notice\n") + endif() + if(NOT actual STREQUAL expected) + message(FATAL_ERROR "Wrong license content in ${license_dir}/${filename}: '${actual}'") + endif() + endforeach() + endforeach() if(parent_installed AND leaf_installed) set(consumer "${case_root}/consumer") file(MAKE_DIRECTORY "${consumer}") @@ -115,7 +164,7 @@ function(run_invalid_case invalid clean target) run_command("${CMAKE_COMMAND}" "-DCMAKE_INSTALL_PREFIX=${prefix}" -DCMAKE_INSTALL_LOCAL_ONLY=TRUE -P "${${clean}_binary}/cmake_install.cmake") if(clean STREQUAL "parent") - check_package("${prefix}" parent TRUE "find_dependency(stlab-leaf 1.0.0)") + check_package("${prefix}" parent TRUE "") else() check_package("${prefix}" leaf TRUE "") endif() @@ -152,23 +201,50 @@ if(DEFINED CASE) run_case(legacy-off FALSE FALSE OFF -DLEGACY_OPTIONS=ON -DSTLAB_INSTALL=OFF) elseif(CASE STREQUAL "legacy-defaults") run_case(legacy-defaults TRUE TRUE OFF -DLEGACY_OPTIONS=ON) + elseif(CASE STREQUAL "custom-datadir") + run_case(custom-datadir TRUE TRUE OFF -DSTLAB_LEAF_INSTALL=ON "-DCMAKE_INSTALL_DATADIR=custom data") + elseif(CASE STREQUAL "no-licenses") + run_case(no-licenses TRUE TRUE OFF -DSTLAB_LEAF_INSTALL=ON) + elseif(CASE STREQUAL "no-leaf-license") + run_case(no-leaf-license TRUE TRUE OFF -DSTLAB_LEAF_INSTALL=ON) + elseif(CASE STREQUAL "duplicate-license-files") + run_case(duplicate-license-files TRUE TRUE OFF -DSTLAB_LEAF_INSTALL=ON -DDUPLICATE_LICENSE_FILES=ON) + elseif(CASE STREQUAL "disabled-missing-license") + run_case(disabled-missing-license FALSE FALSE OFF + -DSTLAB_PARENT_INSTALL=OFF -DSTLAB_LEAF_INSTALL=OFF -DMISSING_LICENSE=ON) elseif(CASE STREQUAL "invalid-parent") run_invalid_case(parent leaf UnknownParent::dep) elseif(CASE STREQUAL "invalid-leaf") run_invalid_case(leaf parent UnknownLeaf::dep) - elseif(CASE STREQUAL "missing-option") - set(source "${test_root}/missing-option/source") + elseif(CASE STREQUAL "missing-option" OR CASE STREQUAL "missing-license" + OR CASE STREQUAL "empty-license-files" OR CASE STREQUAL "colliding-license-files") + set(source "${test_root}/${CASE}/source") file(MAKE_DIRECTORY "${source}") file(COPY "${CMAKE_CURRENT_LIST_DIR}/fixtures/nested/" DESTINATION "${source}") - execute_process(COMMAND "${CMAKE_COMMAND}" -S "${source}" -B "${test_root}/missing-option/build" - -G Ninja "-DTOOLKIT_SOURCE=${toolkit_source}" -DMISSING_INSTALL_OPTION=ON + if(CASE STREQUAL "missing-option") + set(option -DMISSING_INSTALL_OPTION=ON) + set(diagnostic "cpp_library_setup: INSTALL_OPTION requires a value") + elseif(CASE STREQUAL "missing-license") + set(option -DMISSING_LICENSE=ON) + set(diagnostic "cpp-library: License file not found:") + elseif(CASE STREQUAL "empty-license-files") + set(option -DEMPTY_LICENSE_FILES=ON) + set(diagnostic "cpp_library_setup: LICENSE_FILES requires a value") + else() + file(MAKE_DIRECTORY "${source}/licenses") + file(WRITE "${source}/LICENSE" "project license\n") + file(WRITE "${source}/licenses/LICENSE" "other license\n") + set(option -DCOLLIDING_LICENSE_FILES=ON) + set(diagnostic "cpp-library: License files have the same installed name:") + endif() + execute_process(COMMAND "${CMAKE_COMMAND}" -S "${source}" -B "${test_root}/${CASE}/build" + -G Ninja "-DTOOLKIT_SOURCE=${toolkit_source}" ${option} RESULT_VARIABLE result OUTPUT_VARIABLE out ERROR_VARIABLE err) - set(diagnostic "cpp_library_setup: INSTALL_OPTION requires a value") string(FIND "${out}\n${err}" "${diagnostic}" found) if(result EQUAL 0 OR found LESS 0) message(FATAL_ERROR "Expected diagnostic '${diagnostic}':\n${out}\n${err}") endif() - message(STATUS "PASS missing-option: ${diagnostic}") + message(STATUS "PASS ${CASE}: ${diagnostic}") else() message(FATAL_ERROR "Unknown test case: ${CASE}") endif() @@ -176,7 +252,9 @@ if(DEFINED CASE) endif() foreach(case both both-shared parent-only leaf-only custom-defaults legacy-on legacy-off legacy-defaults - invalid-parent invalid-leaf missing-option) + custom-datadir no-licenses no-leaf-license disabled-missing-license + duplicate-license-files colliding-license-files + invalid-parent invalid-leaf missing-option missing-license empty-license-files) execute_process(COMMAND "${CMAKE_COMMAND}" "-DCASE=${case}" "-Dtest_root=${test_root}" -P "${CMAKE_CURRENT_LIST_FILE}" RESULT_VARIABLE result OUTPUT_VARIABLE out ERROR_VARIABLE err) @@ -190,4 +268,4 @@ file(REMOVE_RECURSE "${test_root}") if(failed_cases) message(FATAL_ERROR "Nested install cases failed: ${failed_cases}") endif() -message(STATUS "All 11 nested install cases passed!") +message(STATUS "All nested install cases passed!") diff --git a/tests/setup/fixtures/clangd/nested/CMakeLists.txt b/tests/setup/fixtures/clangd/nested/CMakeLists.txt index 8b1ec2e..919f830 100644 --- a/tests/setup/fixtures/clangd/nested/CMakeLists.txt +++ b/tests/setup/fixtures/clangd/nested/CMakeLists.txt @@ -1,5 +1,5 @@ project(nested LANGUAGES CXX) -set(CPP_LIBRARY_VERSION 1.0.0) +set(CPP_LIBRARY_VERSION_nested 1.0.0) set(NESTED_INSTALL OFF CACHE BOOL "" FORCE) cpp_library_setup(DESCRIPTION "Nested header-only fixture" NAMESPACE nested HEADERS api.hpp REQUIRES_CPP_VERSION 20) diff --git a/tests/setup/test_header_checks.cmake b/tests/setup/test_header_checks.cmake new file mode 100644 index 0000000..9bd30ac --- /dev/null +++ b/tests/setup/test_header_checks.cmake @@ -0,0 +1,161 @@ +# SPDX-License-Identifier: BSL-1.0 +# +# Run as: cmake -P tests/setup/test_header_checks.cmake + +cmake_minimum_required(VERSION 3.24) + +get_filename_component(toolkit_source "${CMAKE_CURRENT_LIST_DIR}/../.." ABSOLUTE) +string(RANDOM LENGTH 16 ALPHABET 0123456789abcdef test_id) +set(test_root "${toolkit_source}/build/header-checks-${test_id}") +set(source "${test_root}/source") +file(MAKE_DIRECTORY "${source}/library/include/fixture" "${source}/library/src" + "${source}/library/usage") +file(WRITE "${source}/CMakeLists.txt" [=[ +cmake_minimum_required(VERSION 3.24) +project(consumer LANGUAGES CXX) +add_subdirectory(library) +]=]) +file(WRITE "${source}/library/CMakeLists.txt" [=[ +cmake_minimum_required(VERSION 3.24) +include("${TOOLKIT_SOURCE}/cpp-library.cmake") +project(checked LANGUAGES CXX) +include(CTest) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(source_args) +if(COMPILED) + set(source_args SOURCES library.cpp) + set(usage PUBLIC) +else() + set(usage INTERFACE) +endif() +foreach(header dependent late) + if((header STREQUAL "dependent" AND BAD_PRIMARY) OR + (header STREQUAL "late" AND BAD_LATE)) + set(include "") + else() + set(include "#include \n") + endif() + file(WRITE "${CMAKE_CURRENT_SOURCE_DIR}/include/fixture/${header}.hpp" + "#pragma once\n${include}using ${header}_integer = std::uint32_t;\n") +endforeach() +cpp_library_setup(DESCRIPTION "Independent public headers" NAMESPACE fixture + HEADERS api.hpp platform.hpp dependent.hpp + REQUIRES_CPP_VERSION "${CMAKE_CXX_STANDARD}" ${source_args}) + +add_library(public_requirements INTERFACE) +target_include_directories(public_requirements INTERFACE "${CMAKE_CURRENT_SOURCE_DIR}/usage") +target_compile_definitions(public_requirements INTERFACE + REQUIRED_PUBLIC_VALUE=42 "REQUIRED_STANDARD=${CMAKE_CXX_STANDARD}") +target_link_libraries(checked ${usage} public_requirements) + +set(generated "${CMAKE_CURRENT_BINARY_DIR}/generated include/fixture/generated.hpp") +add_custom_command(OUTPUT "${generated}" + COMMAND "${CMAKE_COMMAND}" "-DOUTPUT=${generated}" + -P "${CMAKE_CURRENT_SOURCE_DIR}/generate.cmake" + VERBATIM) +add_custom_target(generate_header DEPENDS "${generated}") +add_dependencies(checked generate_header) +target_sources(checked ${usage} FILE_SET extra_headers TYPE HEADERS + BASE_DIRS "${CMAKE_CURRENT_SOURCE_DIR}/include" "${CMAKE_CURRENT_BINARY_DIR}/generated include" + FILES "${CMAKE_CURRENT_SOURCE_DIR}/include/fixture/late.hpp" "${generated}") +]=]) +file(WRITE "${source}/library/generate.cmake" [=[ +get_filename_component(directory "${OUTPUT}" DIRECTORY) +file(MAKE_DIRECTORY "${directory}") +file(WRITE "${OUTPUT}" "#pragma once\n#define FIXTURE_PLATFORM_AVAILABLE 0\n") +]=]) +file(WRITE "${source}/library/usage/public_requirement.hpp" "#pragma once\n") +file(WRITE "${source}/library/include/fixture/api.hpp" [=[ +#pragma once +#include +#include +#include +#include + +static_assert(REQUIRED_PUBLIC_VALUE == 42); +static_assert(std::optional{42}.value() == 42); +#if defined(_MSVC_LANG) +#define FIXTURE_CPLUSPLUS _MSVC_LANG +#else +#define FIXTURE_CPLUSPLUS __cplusplus +#endif +#if REQUIRED_STANDARD >= 20 +static_assert(FIXTURE_CPLUSPLUS >= 202002L); +#endif +#if REQUIRED_STANDARD == 23 +static_assert(FIXTURE_CPLUSPLUS > 202002L); +#endif +]=]) +file(WRITE "${source}/library/include/fixture/platform.hpp" [=[ +#pragma once +#include +#if FIXTURE_PLATFORM_AVAILABLE +#include +#endif +]=]) +file(WRITE "${source}/library/src/library.cpp" [=[ +#include +#include +#include +]=]) + +# Builds a fixture and checks automatic header verification or its scope boundary. +function(run_case name) + cmake_parse_arguments(ARG "COMPILED;BAD_PRIMARY;BAD_LATE;TESTING_OFF;NESTED" "STANDARD" "" ${ARGN}) + if(NOT ARG_STANDARD) + set(ARG_STANDARD 20) + endif() + if(ARG_NESTED) + set(project_source "${source}") + set(project_binary "${test_root}/${name}/library") + else() + set(project_source "${source}/library") + set(project_binary "${test_root}/${name}") + endif() + if(ARG_TESTING_OFF) + set(testing OFF) + else() + set(testing ON) + endif() + execute_process(COMMAND "${CMAKE_COMMAND}" -S "${project_source}" -B "${test_root}/${name}" + -G Ninja "-DTOOLKIT_SOURCE=${toolkit_source}" "-DCMAKE_CXX_STANDARD=${ARG_STANDARD}" + "-DCOMPILED=${ARG_COMPILED}" "-DBAD_PRIMARY=${ARG_BAD_PRIMARY}" "-DBAD_LATE=${ARG_BAD_LATE}" + "-DBUILD_TESTING=${testing}" -DBUILD_DOCS=OFF -DFIXTURE_INSTALL=OFF + -DCPP_LIBRARY_VERSION=1.0.0 -DCPP_LIBRARY_VERSION_checked=1.0.0 + RESULT_VARIABLE result OUTPUT_VARIABLE out ERROR_VARIABLE err) + if(NOT result EQUAL 0) + message(FATAL_ERROR "${name}: configure failed:\n${out}\n${err}") + endif() + execute_process(COMMAND "${CMAKE_COMMAND}" --build "${test_root}/${name}" + RESULT_VARIABLE result OUTPUT_VARIABLE out ERROR_VARIABLE err) + if((ARG_BAD_PRIMARY OR ARG_BAD_LATE) AND NOT ARG_TESTING_OFF AND NOT ARG_NESTED) + if(ARG_BAD_PRIMARY) + set(broken_header dependent.hpp) + else() + set(broken_header late.hpp) + endif() + string(FIND "${out}\n${err}" "${broken_header}" found) + if(result EQUAL 0 OR found LESS 0) + message(FATAL_ERROR + "${name}: normal build did not reject ${broken_header}:\n${out}\n${err}") + endif() + elseif(NOT result EQUAL 0) + message(FATAL_ERROR "${name}: build failed:\n${out}\n${err}") + elseif(NOT ARG_TESTING_OFF AND NOT ARG_NESTED AND + NOT EXISTS "${project_binary}/generated include/fixture/generated.hpp") + message(FATAL_ERROR "${name}: generated public header was not built") + endif() + message(STATUS "PASS ${name}") +endfunction() + +run_case(broken_interface BAD_PRIMARY) +run_case(broken_compiled COMPILED BAD_LATE) +foreach(standard 17 20 23) + run_case(interface_${standard} STANDARD "${standard}") + run_case(compiled_${standard} COMPILED STANDARD "${standard}") +endforeach() +run_case(testing_off BAD_PRIMARY TESTING_OFF) +run_case(subproject COMPILED BAD_LATE NESTED) + +file(REMOVE_RECURSE "${test_root}") +message(STATUS "All independent header compilation cases passed!") diff --git a/tests/setup/test_version_override.cmake b/tests/setup/test_version_override.cmake new file mode 100644 index 0000000..d418beb --- /dev/null +++ b/tests/setup/test_version_override.cmake @@ -0,0 +1,138 @@ +# SPDX-License-Identifier: BSL-1.0 +# +# Run as: cmake -P tests/setup/test_version_override.cmake + +cmake_minimum_required(VERSION 3.24) + +get_filename_component(toolkit_source "${CMAKE_CURRENT_LIST_DIR}/../.." ABSOLUTE) +string(RANDOM LENGTH 16 ALPHABET 0123456789abcdef test_id) +set(test_root "${toolkit_source}/build/version-override-${test_id}") +set(source "${test_root}/source") +file(MAKE_DIRECTORY "${source}") + +# Runs fixture setup commands and reports their diagnostics on failure. +function(run_command) + execute_process(COMMAND ${ARGV} + RESULT_VARIABLE result OUTPUT_VARIABLE out ERROR_VARIABLE err) + if(NOT result EQUAL 0) + message(FATAL_ERROR "Command failed (${result}): ${ARGV}\n${out}\n${err}") + endif() +endfunction() + +file(WRITE "${source}/assert-version.cmake" [=[ +# Checks the current project's published version and its numeric components. +function(assert_project_version) + set(expected "${EXPECTED_${PROJECT_NAME}}") + if(NOT PROJECT_VERSION STREQUAL expected) + message(FATAL_ERROR "${PROJECT_NAME}: expected ${expected}, got '${PROJECT_VERSION}'") + endif() + set(components "${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH}") + if(NOT components STREQUAL expected) + message(FATAL_ERROR "${PROJECT_NAME}: wrong version components '${components}'") + endif() +endfunction() +]=]) + +set(project_template [=[ +cmake_minimum_required(VERSION 3.24) +include("${TOOLKIT_SOURCE}/cpp-library.cmake") +if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR) + cpp_library_enable_dependency_tracking() +endif() +project(@project_name@ LANGUAGES CXX) +include("${CMAKE_SOURCE_DIR}/assert-version.cmake") +cpp_library_set_version() +assert_project_version() +set(source_args) +if(PROJECT_NAME STREQUAL "child-version") + set(source_args SOURCES version.cpp) +endif() +cpp_library_setup(DESCRIPTION "Version isolation fixture" NAMESPACE fixture + HEADERS version.hpp ${source_args}) +assert_project_version() +add_subdirectory(helper) +]=]) + +foreach(project_name parent-version child-version sibling-version) + if(project_name STREQUAL "parent-version") + set(project_source "${source}") + set(tag v0.8.0) + elseif(project_name STREQUAL "child-version") + set(project_source "${source}/child") + set(tag v1.1.0) + else() + set(project_source "${source}/sibling") + set(tag v2.3.4) + endif() + file(MAKE_DIRECTORY "${project_source}/include/fixture" "${project_source}/src" + "${project_source}/helper") + file(WRITE "${project_source}/include/fixture/version.hpp" "#pragma once\n") + file(WRITE "${project_source}/src/version.cpp" "int version_fixture() { return 0; }\n") + string(CONFIGURE "${project_template}" project_contents @ONLY) + file(WRITE "${project_source}/CMakeLists.txt" "${project_contents}") + file(WRITE "${project_source}/helper/CMakeLists.txt" [=[ +cpp_library_set_version() +assert_project_version() +]=]) + run_command(git -C "${project_source}" init --quiet) + run_command(git -C "${project_source}" -c user.name=cpp-library + -c user.email=cpp-library@example.invalid -c commit.gpgsign=false + -c "core.hooksPath=${test_root}/no-hooks" + commit --allow-empty --quiet -m "Version fixture" + -m "Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>") + run_command(git -C "${project_source}" -c tag.gpgSign=false tag "${tag}") +endforeach() +file(APPEND "${source}/CMakeLists.txt" [=[ +add_subdirectory(child) +add_subdirectory(sibling) +assert_project_version() +]=]) + +# Checks a generated version file without installing or consuming the package. +function(check_config_version path expected) + include("${path}") + if(NOT PACKAGE_VERSION STREQUAL expected) + message(FATAL_ERROR "${path}: expected ${expected}, got '${PACKAGE_VERSION}'") + endif() +endfunction() + +set(failed_cases) + +# Configures independent projects and checks their generated package versions. +function(run_case name parent_version child_version sibling_version) + set(binary "${test_root}/${name}") + execute_process(COMMAND "${CMAKE_COMMAND}" -S "${source}" -B "${binary}" -G Ninja + "-DTOOLKIT_SOURCE=${toolkit_source}" + "-DEXPECTED_parent-version=${parent_version}" + "-DEXPECTED_child-version=${child_version}" + "-DEXPECTED_sibling-version=${sibling_version}" + -DBUILD_TESTING=OFF -DBUILD_DOCS=OFF -DFIXTURE_INSTALL=ON ${ARGN} + RESULT_VARIABLE result OUTPUT_VARIABLE out ERROR_VARIABLE err) + if(NOT result EQUAL 0) + message(STATUS "FAIL ${name}:\n${out}\n${err}") + list(APPEND failed_cases "${name}") + else() + check_config_version("${binary}/fixture-parent-versionConfigVersion.cmake" "${parent_version}") + check_config_version("${binary}/child/fixture-child-versionConfigVersion.cmake" "${child_version}") + check_config_version("${binary}/sibling/fixture-sibling-versionConfigVersion.cmake" "${sibling_version}") + message(STATUS "PASS ${name}: ${parent_version}; ${child_version}; ${sibling_version}") + endif() + set(failed_cases "${failed_cases}" PARENT_SCOPE) +endfunction() + +run_case(git_tags 0.8.0 1.1.0 2.3.4) +run_case(legacy_top_level_only 0.1.0 1.1.0 2.3.4 -DCPP_LIBRARY_VERSION=0.1.0) +run_case(scoped_overrides 0.2.0 1.5.0 2.3.4 + -DCPP_LIBRARY_VERSION_parent-version=0.2.0 -DCPP_LIBRARY_VERSION_child-version=1.5.0) +run_case(scoped_precedence 0.3.0 1.6.0 2.3.4 -DCPP_LIBRARY_VERSION=0.1.0 + -DCPP_LIBRARY_VERSION_parent-version=0.3.0 -DCPP_LIBRARY_VERSION_child-version=1.6.0) +run_case(empty_scoped_fallback 0.1.0 1.1.0 2.3.4 -DCPP_LIBRARY_VERSION=0.1.0 + -DCPP_LIBRARY_VERSION_parent-version= -DCPP_LIBRARY_VERSION_child-version=) +run_case(case_sensitive_names 0.8.0 1.1.0 2.3.4 + -DCPP_LIBRARY_VERSION_PARENT-VERSION=9.9.9 -DCPP_LIBRARY_VERSION_CHILD-VERSION=9.9.9) + +file(REMOVE_RECURSE "${test_root}") +if(failed_cases) + message(FATAL_ERROR "Version override cases failed: ${failed_cases}") +endif() +message(STATUS "All project version override cases passed!")