hatch-cpp 0.5.2__tar.gz → 0.6.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/PKG-INFO +71 -3
  2. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/README.md +66 -0
  3. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/__init__.py +1 -1
  4. hatch_cpp-0.6.1/hatch_cpp/config.py +316 -0
  5. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/plugin.py +12 -2
  6. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_hatch_build.py +3 -2
  7. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_hook_registration.py +2 -1
  8. hatch_cpp-0.6.1/hatch_cpp/tests/test_project_c_abi_library/cpp/demo.c +5 -0
  9. hatch_cpp-0.6.1/hatch_cpp/tests/test_project_c_abi_library/cpp/extension.c +11 -0
  10. hatch_cpp-0.6.1/hatch_cpp/tests/test_project_c_abi_library/cpp/include/demo/demo.h +22 -0
  11. hatch_cpp-0.6.1/hatch_cpp/tests/test_project_c_abi_library/project/__init__.py +5 -0
  12. hatch_cpp-0.6.1/hatch_cpp/tests/test_project_c_abi_library/pyproject.toml +57 -0
  13. hatch_cpp-0.6.1/hatch_cpp/tests/test_project_cmake_c_abi/CMakeLists.txt +28 -0
  14. hatch_cpp-0.6.1/hatch_cpp/tests/test_project_cmake_c_abi/cpp/demo.c +5 -0
  15. hatch_cpp-0.6.1/hatch_cpp/tests/test_project_cmake_c_abi/cpp/extension.c +11 -0
  16. hatch_cpp-0.6.1/hatch_cpp/tests/test_project_cmake_c_abi/cpp/include/demo/demo.h +22 -0
  17. hatch_cpp-0.6.1/hatch_cpp/tests/test_project_cmake_c_abi/project/__init__.py +5 -0
  18. hatch_cpp-0.6.1/hatch_cpp/tests/test_project_cmake_c_abi/pyproject.toml +50 -0
  19. hatch_cpp-0.6.1/hatch_cpp/tests/test_project_pyodide/pyodide_project/extension.pyi +1 -0
  20. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_projects.py +9 -3
  21. hatch_cpp-0.6.1/hatch_cpp/tests/test_validation.py +216 -0
  22. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_vcpkg_ref.py +10 -0
  23. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/toolchains/cmake.py +5 -18
  24. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/toolchains/common.py +92 -41
  25. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/toolchains/vcpkg.py +4 -4
  26. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/pyproject.toml +8 -6
  27. hatch_cpp-0.5.2/hatch_cpp/config.py +0 -127
  28. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/.gitignore +0 -0
  29. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/LICENSE +0 -0
  30. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/hooks.py +0 -0
  31. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_platform_specific.py +0 -0
  32. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_basic/cpp/project/basic.cpp +0 -0
  33. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_basic/cpp/project/basic.hpp +0 -0
  34. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_basic/project/__init__.py +0 -0
  35. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_basic/pyproject.toml +0 -0
  36. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_cmake/CMakeLists.txt +0 -0
  37. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_cmake/Makefile +0 -0
  38. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_cmake/cpp/project/basic.cpp +0 -0
  39. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_cmake/cpp/project/basic.hpp +0 -0
  40. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_cmake/project/__init__.py +0 -0
  41. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_cmake/project/include/project/basic.hpp +0 -0
  42. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_cmake/pyproject.toml +0 -0
  43. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_cmake_vcpkg/CMakeLists.txt +0 -0
  44. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_cmake_vcpkg/Makefile +0 -0
  45. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_cmake_vcpkg/cpp/project/basic.cpp +0 -0
  46. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_cmake_vcpkg/cpp/project/basic.hpp +0 -0
  47. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_cmake_vcpkg/project/__init__.py +0 -0
  48. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_cmake_vcpkg/project/include/project/basic.hpp +0 -0
  49. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_cmake_vcpkg/pyproject.toml +0 -0
  50. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_cmake_vcpkg/vcpkg.json +0 -0
  51. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_hatch_build/cpp/project/basic.cpp +0 -0
  52. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_hatch_build/cpp/project/basic.hpp +0 -0
  53. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_hatch_build/project/__init__.py +0 -0
  54. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_hatch_build/pyproject.toml +0 -0
  55. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_limited_api/cpp/project/basic.cpp +0 -0
  56. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_limited_api/cpp/project/basic.hpp +0 -0
  57. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_limited_api/project/__init__.py +0 -0
  58. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_limited_api/pyproject.toml +0 -0
  59. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_nanobind/cpp/project/basic.cpp +0 -0
  60. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_nanobind/cpp/project/basic.hpp +0 -0
  61. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_nanobind/project/__init__.py +0 -0
  62. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_nanobind/pyproject.toml +0 -0
  63. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_override_classes/cpp/project/basic.cpp +0 -0
  64. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_override_classes/cpp/project/basic.hpp +0 -0
  65. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_override_classes/project/__init__.py +0 -0
  66. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_override_classes/pyproject.toml +0 -0
  67. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_override_toolchain/cpp/project/basic.cpp +0 -0
  68. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_override_toolchain/cpp/project/basic.hpp +0 -0
  69. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_override_toolchain/project/__init__.py +0 -0
  70. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_override_toolchain/pyproject.toml +0 -0
  71. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_pybind/cpp/project/basic.cpp +0 -0
  72. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_pybind/cpp/project/basic.hpp +0 -0
  73. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_pybind/project/__init__.py +0 -0
  74. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_pybind/pyproject.toml +0 -0
  75. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_pybind_vcpkg/cpp/project/basic.cpp +0 -0
  76. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_pybind_vcpkg/cpp/project/basic.hpp +0 -0
  77. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_pybind_vcpkg/project/__init__.py +0 -0
  78. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_pybind_vcpkg/pyproject.toml +0 -0
  79. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_pybind_vcpkg/vcpkg.json +0 -0
  80. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_pyodide/cpp/extension.cpp +0 -0
  81. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_pyodide/pyodide_project/__init__.py +0 -0
  82. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_project_pyodide/pyproject.toml +0 -0
  83. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/tests/test_structs.py +0 -0
  84. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/toolchains/__init__.py +0 -0
  85. {hatch_cpp-0.5.2 → hatch_cpp-0.6.1}/hatch_cpp/utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: hatch-cpp
3
- Version: 0.5.2
3
+ Version: 0.6.1
4
4
  Summary: Hatch plugin for C++ builds
5
5
  Project-URL: Repository, https://github.com/python-project-templates/hatch-cpp
6
6
  Project-URL: Homepage, https://github.com/python-project-templates/hatch-cpp
@@ -20,7 +20,8 @@ Classifier: Programming Language :: Python :: Implementation :: CPython
20
20
  Classifier: Programming Language :: Python :: Implementation :: PyPy
21
21
  Requires-Python: >=3.10
22
22
  Requires-Dist: hatch-build<0.6,>=0.5
23
- Requires-Dist: hatchling!=1.32.1
23
+ Requires-Dist: hatch-native<0.2,>=0.1.0
24
+ Requires-Dist: hatchling
24
25
  Requires-Dist: pkn
25
26
  Requires-Dist: pydantic
26
27
  Provides-Extra: develop
@@ -29,8 +30,9 @@ Requires-Dist: bump-my-version; extra == 'develop'
29
30
  Requires-Dist: check-dist; extra == 'develop'
30
31
  Requires-Dist: codespell; extra == 'develop'
31
32
  Requires-Dist: hatch-build>=0.3.2; extra == 'develop'
32
- Requires-Dist: hatchling!=1.32.1; extra == 'develop'
33
+ Requires-Dist: hatchling; extra == 'develop'
33
34
  Requires-Dist: mdformat; extra == 'develop'
35
+ Requires-Dist: mdformat-myst; extra == 'develop'
34
36
  Requires-Dist: mdformat-tables>=1; extra == 'develop'
35
37
  Requires-Dist: nanobind; extra == 'develop'
36
38
  Requires-Dist: pybind11; extra == 'develop'
@@ -129,6 +131,72 @@ cmake_env_args = {} # env-specific cmake args to pass
129
131
  include_flags = {} # include flags to pass -D
130
132
  ```
131
133
 
134
+ ### Linking an extension against a library
135
+
136
+ A `generic` library can ship next to the extension that links it, in the layout pyarrow uses. List the library first and name it in the extension's `depends`:
137
+
138
+ ```toml
139
+ [[tool.hatch.build.hooks.hatch-cpp.libraries]]
140
+ name = "project/lib/libdemo"
141
+ sources = ["cpp/demo.c"]
142
+ language = "c"
143
+ binding = "generic"
144
+ include-dirs = ["cpp/include"]
145
+ define-macros = ["DEMO_BUILD"]
146
+
147
+ [[tool.hatch.build.hooks.hatch-cpp.libraries]]
148
+ name = "project/extension"
149
+ sources = ["cpp/extension.c"]
150
+ language = "c"
151
+ include-dirs = ["cpp/include"]
152
+ depends = ["project/lib/libdemo"]
153
+ ```
154
+
155
+ The library builds first. On Linux it gets `-soname libdemo.so` and on macOS the install name `@rpath/libdemo.dylib`, unless `extra-link-args` already set one. The extension links the built file and gets an rpath to its directory (`$ORIGIN/lib`, `@loader_path/lib`), so the wheel works wherever it is installed. On Windows the extension links the import library `project/lib/libdemo.lib`, which is packaged next to the DLL. Windows has no rpath, so the package `__init__.py` must call `os.add_dll_directory` on `lib/` before importing the extension, and the library's header must mark its functions `__declspec(dllexport)` when building it and `__declspec(dllimport)` otherwise. `depends` is not supported for Emscripten builds.
156
+
157
+ `library-source` (or `HATCH_CPP_LIBRARY_SOURCE`, which wins) picks how libraries named in `depends` are provided:
158
+
159
+ - `bundled` (default): built and shipped in the wheel as above.
160
+ - `external`: not built. Each one is found under `library-root` (or `HATCH_CPP_LIBRARY_ROOT`) with `lib/` and `include/`, through `pkg-config = "demo"`, or under `$PREFIX`/`$CONDA_PREFIX` (`Library/` on Windows), by its name without the `lib` prefix. The extension links it with `-L`/`-l` and gets no rpath, so the packager supplies the runtime path; this is the mode a conda recipe uses. Validation fields on the entry check the external library.
161
+ - `direct`: not built. Its sources, include directories, and macros are compiled into each entry that depends on it, and no library ships. Use this for Pyodide.
162
+
163
+ `static` and `python-package` are not supported yet.
164
+
165
+ Wheel repair tools need to leave the bundled library in place: `auditwheel repair --exclude 'libdemo.so'`, `delocate-wheel --exclude libdemo`, `delvewheel repair --exclude libdemo.dll`.
166
+
167
+ ### C ABI validation
168
+
169
+ A library that other code links against can be checked after it is built. Validation reads the export table from the binary, so it also works for cross builds and Pyodide. The field names match [hatch-rs](https://github.com/python-project-templates/hatch-rs) and come from [hatch-native](https://github.com/python-project-templates/hatch-native).
170
+
171
+ Set the fields on a `libraries` entry:
172
+
173
+ ```toml
174
+ [[tool.hatch.build.hooks.hatch-cpp.libraries]]
175
+ name = "project/lib/libdemo"
176
+ sources = ["cpp/demo.c"]
177
+ language = "c"
178
+ binding = "generic"
179
+ include-dirs = ["cpp/include"]
180
+ expected-headers = ["cpp/include/demo/demo.h"]
181
+ header-symbol-prefix = "demo_" # every demo_* function in the headers must be exported
182
+ expected-abi-strings = ["DEMO_ABI_VERSION 1"]
183
+ expected-symbols = [] # extra symbols to require
184
+ validate = false # also load the library with ctypes
185
+ ```
186
+
187
+ Or list `artifacts` to validate files that `libraries` does not name, such as the output of a CMake install. Each entry takes the same fields plus `name` and an optional `path` relative to the project root. Without `path`, `name` matches a `libraries` entry, or else the one packaged file called `lib<name>.so`, `lib<name>.dylib`, or `<name>.dll`:
188
+
189
+ ```toml
190
+ [[tool.hatch.build.hooks.hatch-cpp.artifacts]]
191
+ name = "demo"
192
+ expected-headers = ["project/include/demo/demo.h"]
193
+ header-symbol-prefix = "demo_"
194
+ ```
195
+
196
+ `validation-commands` run after the checks, with `{name}`, `{path}`, and `{header}` substituted and `HATCH_CPP_ARTIFACT_NAME` and `HATCH_CPP_ARTIFACT_PATH` in the environment.
197
+
198
+ To record what was packaged, set `artifact-manifest = true` and `artifact-manifest-destination = "project/lib/hatch-cpp-artifacts.json"`. The JSON lists each packaged binary with its role (`python-extension` or `library`), platform, and profile, and is added to the wheel.
199
+
132
200
  ### CLI
133
201
 
134
202
  `hatch-cpp` is integrated with [`hatch-build`](https://github.com/python-project-templates/hatch-build) to allow easy configuration of options via command line:
@@ -83,6 +83,72 @@ cmake_env_args = {} # env-specific cmake args to pass
83
83
  include_flags = {} # include flags to pass -D
84
84
  ```
85
85
 
86
+ ### Linking an extension against a library
87
+
88
+ A `generic` library can ship next to the extension that links it, in the layout pyarrow uses. List the library first and name it in the extension's `depends`:
89
+
90
+ ```toml
91
+ [[tool.hatch.build.hooks.hatch-cpp.libraries]]
92
+ name = "project/lib/libdemo"
93
+ sources = ["cpp/demo.c"]
94
+ language = "c"
95
+ binding = "generic"
96
+ include-dirs = ["cpp/include"]
97
+ define-macros = ["DEMO_BUILD"]
98
+
99
+ [[tool.hatch.build.hooks.hatch-cpp.libraries]]
100
+ name = "project/extension"
101
+ sources = ["cpp/extension.c"]
102
+ language = "c"
103
+ include-dirs = ["cpp/include"]
104
+ depends = ["project/lib/libdemo"]
105
+ ```
106
+
107
+ The library builds first. On Linux it gets `-soname libdemo.so` and on macOS the install name `@rpath/libdemo.dylib`, unless `extra-link-args` already set one. The extension links the built file and gets an rpath to its directory (`$ORIGIN/lib`, `@loader_path/lib`), so the wheel works wherever it is installed. On Windows the extension links the import library `project/lib/libdemo.lib`, which is packaged next to the DLL. Windows has no rpath, so the package `__init__.py` must call `os.add_dll_directory` on `lib/` before importing the extension, and the library's header must mark its functions `__declspec(dllexport)` when building it and `__declspec(dllimport)` otherwise. `depends` is not supported for Emscripten builds.
108
+
109
+ `library-source` (or `HATCH_CPP_LIBRARY_SOURCE`, which wins) picks how libraries named in `depends` are provided:
110
+
111
+ - `bundled` (default): built and shipped in the wheel as above.
112
+ - `external`: not built. Each one is found under `library-root` (or `HATCH_CPP_LIBRARY_ROOT`) with `lib/` and `include/`, through `pkg-config = "demo"`, or under `$PREFIX`/`$CONDA_PREFIX` (`Library/` on Windows), by its name without the `lib` prefix. The extension links it with `-L`/`-l` and gets no rpath, so the packager supplies the runtime path; this is the mode a conda recipe uses. Validation fields on the entry check the external library.
113
+ - `direct`: not built. Its sources, include directories, and macros are compiled into each entry that depends on it, and no library ships. Use this for Pyodide.
114
+
115
+ `static` and `python-package` are not supported yet.
116
+
117
+ Wheel repair tools need to leave the bundled library in place: `auditwheel repair --exclude 'libdemo.so'`, `delocate-wheel --exclude libdemo`, `delvewheel repair --exclude libdemo.dll`.
118
+
119
+ ### C ABI validation
120
+
121
+ A library that other code links against can be checked after it is built. Validation reads the export table from the binary, so it also works for cross builds and Pyodide. The field names match [hatch-rs](https://github.com/python-project-templates/hatch-rs) and come from [hatch-native](https://github.com/python-project-templates/hatch-native).
122
+
123
+ Set the fields on a `libraries` entry:
124
+
125
+ ```toml
126
+ [[tool.hatch.build.hooks.hatch-cpp.libraries]]
127
+ name = "project/lib/libdemo"
128
+ sources = ["cpp/demo.c"]
129
+ language = "c"
130
+ binding = "generic"
131
+ include-dirs = ["cpp/include"]
132
+ expected-headers = ["cpp/include/demo/demo.h"]
133
+ header-symbol-prefix = "demo_" # every demo_* function in the headers must be exported
134
+ expected-abi-strings = ["DEMO_ABI_VERSION 1"]
135
+ expected-symbols = [] # extra symbols to require
136
+ validate = false # also load the library with ctypes
137
+ ```
138
+
139
+ Or list `artifacts` to validate files that `libraries` does not name, such as the output of a CMake install. Each entry takes the same fields plus `name` and an optional `path` relative to the project root. Without `path`, `name` matches a `libraries` entry, or else the one packaged file called `lib<name>.so`, `lib<name>.dylib`, or `<name>.dll`:
140
+
141
+ ```toml
142
+ [[tool.hatch.build.hooks.hatch-cpp.artifacts]]
143
+ name = "demo"
144
+ expected-headers = ["project/include/demo/demo.h"]
145
+ header-symbol-prefix = "demo_"
146
+ ```
147
+
148
+ `validation-commands` run after the checks, with `{name}`, `{path}`, and `{header}` substituted and `HATCH_CPP_ARTIFACT_NAME` and `HATCH_CPP_ARTIFACT_PATH` in the environment.
149
+
150
+ To record what was packaged, set `artifact-manifest = true` and `artifact-manifest-destination = "project/lib/hatch-cpp-artifacts.json"`. The JSON lists each packaged binary with its role (`python-extension` or `library`), platform, and profile, and is added to the wheel.
151
+
86
152
  ### CLI
87
153
 
88
154
  `hatch-cpp` is integrated with [`hatch-build`](https://github.com/python-project-templates/hatch-build) to allow easy configuration of options via command line:
@@ -1,4 +1,4 @@
1
- __version__ = "0.5.2"
1
+ __version__ = "0.6.1"
2
2
 
3
3
  from .config import *
4
4
  from .hooks import *
@@ -0,0 +1,316 @@
1
+ from __future__ import annotations
2
+
3
+ from importlib.machinery import EXTENSION_SUFFIXES
4
+ from os import environ, system as system_call
5
+ from pathlib import Path
6
+
7
+ from hatch_native import (
8
+ ExternalLibrary,
9
+ LibraryValidationConfig,
10
+ check_exports,
11
+ check_headers,
12
+ prefixed_header_symbols,
13
+ resolve_external_library,
14
+ resolve_library_source,
15
+ run_validation_command,
16
+ shared_library_name,
17
+ write_artifact_manifest,
18
+ )
19
+ from pkn import getSimpleLogger
20
+ from pydantic import AliasChoices, BaseModel, Field, PrivateAttr, model_validator
21
+
22
+ from .toolchains import (
23
+ BuildType,
24
+ HatchCppArtifact,
25
+ HatchCppCmakeConfiguration,
26
+ HatchCppLibrary,
27
+ HatchCppPlatform,
28
+ HatchCppVcpkgConfiguration,
29
+ Toolchain,
30
+ )
31
+
32
+ __all__ = (
33
+ "HatchCppBuildConfig",
34
+ "HatchCppBuildPlan",
35
+ )
36
+
37
+
38
+ log = getSimpleLogger("hatch_cpp")
39
+
40
+
41
+ class HatchCppBuildConfig(BaseModel):
42
+ """Build config values for Hatch C++ Builder."""
43
+
44
+ verbose: bool | None = Field(default=False)
45
+ skip: bool | None = Field(default=False)
46
+ name: str | None = Field(default=None)
47
+ libraries: list[HatchCppLibrary] = Field(default_factory=list)
48
+ cmake: HatchCppCmakeConfiguration | None = Field(default=None)
49
+ platform: HatchCppPlatform = Field(default_factory=HatchCppPlatform.default)
50
+ vcpkg: HatchCppVcpkgConfiguration | None = Field(default_factory=HatchCppVcpkgConfiguration)
51
+ library_source: str = Field(
52
+ default="bundled",
53
+ validation_alias=AliasChoices("library-source", "library_source"),
54
+ description="How libraries named in depends are provided: bundled, external, or direct. Overridden by HATCH_CPP_LIBRARY_SOURCE.",
55
+ )
56
+ artifacts: list[HatchCppArtifact] = Field(default_factory=list)
57
+ artifact_manifest: bool = Field(default=False, validation_alias=AliasChoices("artifact-manifest", "artifact_manifest"))
58
+ artifact_manifest_destination: str | None = Field(
59
+ default=None,
60
+ validation_alias=AliasChoices("artifact-manifest-destination", "artifact_manifest_destination"),
61
+ description="Wheel-relative path of the artifact manifest JSON, such as project/lib/hatch-cpp-artifacts.json.",
62
+ )
63
+
64
+ @model_validator(mode="wrap")
65
+ @classmethod
66
+ def validate_model(cls, data, handler):
67
+ if "toolchain" in data:
68
+ data["platform"] = HatchCppPlatform.platform_for_toolchain(data["toolchain"])
69
+ data.pop("toolchain")
70
+ elif "platform" not in data:
71
+ data["platform"] = HatchCppPlatform.default()
72
+ if "cc" in data:
73
+ data["platform"].cc = data["cc"]
74
+ data.pop("cc")
75
+ if "cxx" in data:
76
+ data["platform"].cxx = data["cxx"]
77
+ data.pop("cxx")
78
+ if "ld" in data:
79
+ data["platform"].ld = data["ld"]
80
+ data.pop("ld")
81
+ if "vcpkg" in data and data["vcpkg"] == "false":
82
+ data["vcpkg"] = None
83
+ model = handler(data)
84
+ if model.cmake and model.libraries:
85
+ raise ValueError("Must not provide libraries when using cmake toolchain.")
86
+ declared: dict[str, HatchCppLibrary] = {}
87
+ for library in model.libraries:
88
+ if library.python_package is not None:
89
+ raise ValueError(f"Library '{library.name}' sets python-package, which hatch-cpp does not support yet.")
90
+ for name in library.depends:
91
+ if name not in declared or declared[name].binding != "generic":
92
+ raise ValueError(f"Library '{library.name}' depends on '{name}', which must be a generic library declared before it.")
93
+ declared[library.name] = library
94
+ if model.artifact_manifest and not model.artifact_manifest_destination:
95
+ raise ValueError("artifact-manifest requires artifact-manifest-destination.")
96
+ return model
97
+
98
+
99
+ class HatchCppBuildPlan(HatchCppBuildConfig):
100
+ build_type: BuildType = "release"
101
+ commands: list[str] = Field(default_factory=list)
102
+
103
+ _active_toolchains: list[Toolchain] = []
104
+ _external_libraries: dict[str, ExternalLibrary] = PrivateAttr(default_factory=dict)
105
+ _skipped_libraries: set[str] = PrivateAttr(default_factory=set)
106
+
107
+ def built_libraries(self) -> list[HatchCppLibrary]:
108
+ """Libraries this build compiles; external and direct mode skip the ones other entries depend on."""
109
+ return [library for library in self.libraries if library.name not in self._skipped_libraries]
110
+
111
+ def _resolve_external(self, library: HatchCppLibrary) -> ExternalLibrary:
112
+ root = environ.get("HATCH_CPP_LIBRARY_ROOT") or (str(library.library_root) if library.library_root is not None else None)
113
+ name = Path(library.name).name
114
+ if name.startswith("lib") and len(name) > 3:
115
+ name = name[3:]
116
+ return resolve_external_library(
117
+ name,
118
+ label=library.name,
119
+ platform=self.platform.platform,
120
+ root_env_var="HATCH_CPP_LIBRARY_ROOT",
121
+ root=Path(root).resolve() if root else None,
122
+ pkg_config=library.pkg_config,
123
+ )
124
+
125
+ def _consumer(self, library: HatchCppLibrary, source: str) -> tuple[HatchCppLibrary, list[HatchCppLibrary]]:
126
+ """The library to compile and the libraries it links, after applying the library-source mode to its depends."""
127
+ dependencies = [next(other for other in self.libraries if other.name == name) for name in library.depends]
128
+ if not dependencies or source == "bundled":
129
+ return library, dependencies
130
+ if source == "external":
131
+ externals = [self._external_libraries[dependency.name] for dependency in dependencies]
132
+ return library.model_copy(
133
+ update={
134
+ "include_dirs": [*library.include_dirs, *(str(external.include_dir) for external in externals if external.include_dir)],
135
+ "library_dirs": [*library.library_dirs, *(str(external.library_dir) for external in externals)],
136
+ "libraries": [*library.libraries, *(external.link_name for external in externals)],
137
+ }
138
+ ), []
139
+ return library.model_copy(
140
+ update={
141
+ "sources": [*library.sources, *(path for dependency in dependencies for path in dependency.sources)],
142
+ "include_dirs": [*library.include_dirs, *(path for dependency in dependencies for path in dependency.include_dirs)],
143
+ "define_macros": [*library.define_macros, *(macro for dependency in dependencies for macro in dependency.define_macros)],
144
+ }
145
+ ), []
146
+
147
+ def generate(self):
148
+ self.commands = []
149
+
150
+ # Check for env var overrides
151
+ vcpkg_override = environ.get("HATCH_CPP_VCPKG")
152
+ cmake_override = environ.get("HATCH_CPP_CMAKE")
153
+
154
+ # Evaluate toolchains
155
+ if vcpkg_override == "1":
156
+ if self.vcpkg:
157
+ self._active_toolchains.append("vcpkg")
158
+ else:
159
+ log.warning("HATCH_CPP_VCPKG=1 set but no vcpkg configuration found; ignoring.")
160
+ elif vcpkg_override != "0" and self.vcpkg and self.vcpkg.vcpkg and Path(self.vcpkg.vcpkg).exists():
161
+ self._active_toolchains.append("vcpkg")
162
+
163
+ if self.libraries:
164
+ self._active_toolchains.append("vanilla")
165
+ elif cmake_override == "1":
166
+ if self.cmake:
167
+ self._active_toolchains.append("cmake")
168
+ else:
169
+ log.warning("HATCH_CPP_CMAKE=1 set but no cmake configuration found; ignoring.")
170
+ elif cmake_override != "0" and self.cmake:
171
+ self._active_toolchains.append("cmake")
172
+
173
+ # Collect toolchain commands
174
+ if "vcpkg" in self._active_toolchains:
175
+ assert self.vcpkg is not None
176
+ self.commands.extend(self.vcpkg.generate(self))
177
+
178
+ if "vanilla" in self._active_toolchains:
179
+ if "vcpkg" in self._active_toolchains:
180
+ log.warning("vcpkg toolchain is active; ensure that your compiler is configured to use vcpkg includes and libs.")
181
+
182
+ source = resolve_library_source(self.library_source, env_var="HATCH_CPP_LIBRARY_SOURCE")
183
+ if source == "static":
184
+ raise ValueError("library-source 'static' is not supported by hatch-cpp; use bundled, external, or direct.")
185
+ linked = {name for library in self.libraries for name in library.depends}
186
+ self._external_libraries = {}
187
+ self._skipped_libraries = set() if source == "bundled" else linked
188
+ for library_index, library in enumerate(self.libraries):
189
+ if library.name in self._skipped_libraries:
190
+ if source == "external":
191
+ self._external_libraries[library.name] = self._resolve_external(library)
192
+ continue
193
+ library, dependencies = self._consumer(library, source)
194
+ compile_flags = self.platform.get_compile_flags(library, self.build_type)
195
+ link_flags = self.platform.get_link_flags(library, self.build_type, dependencies)
196
+ compiler = self.platform.cc if library.language == "c" else self.platform.cxx
197
+ if self.platform.platform == "emscripten":
198
+ objects = []
199
+ for source_index, source in enumerate(library.sources):
200
+ obj = f"build/hatch-cpp/{library_index}-{source_index}-{Path(source).stem}.o"
201
+ objects.append(obj)
202
+ self.commands.append(f"{compiler} -c {source} {compile_flags} -o {obj}")
203
+ self.commands.append(f"{compiler} {' '.join(objects)} {link_flags}")
204
+ else:
205
+ self.commands.append(f"{compiler} {' '.join(library.sources)} {compile_flags} {link_flags}")
206
+
207
+ if "cmake" in self._active_toolchains:
208
+ assert self.cmake is not None
209
+ self.commands.extend(self.cmake.generate(self))
210
+
211
+ return self.commands
212
+
213
+ def execute(self):
214
+ if self.platform.platform == "emscripten" and "vanilla" in self._active_toolchains:
215
+ Path("build/hatch-cpp").mkdir(parents=True, exist_ok=True)
216
+ if "vanilla" in self._active_toolchains:
217
+ for library in self.built_libraries():
218
+ Path(self._library_output(library)).parent.mkdir(parents=True, exist_ok=True)
219
+ for command in self.commands:
220
+ ret = system_call(command)
221
+ if ret != 0:
222
+ raise RuntimeError(f"hatch-cpp build command failed with exit code {ret}: {command}")
223
+ return self.commands
224
+
225
+ def cleanup(self):
226
+ if self.platform.platform == "win32":
227
+ for temp_obj in Path(".").glob("*.obj"):
228
+ temp_obj.unlink()
229
+
230
+ def _library_output(self, library: HatchCppLibrary) -> str:
231
+ return library.get_qualified_name(self.platform.platform)
232
+
233
+ def _artifact_path(self, artifact: HatchCppArtifact, packaged: list[str]) -> str:
234
+ if artifact.path:
235
+ return artifact.path
236
+ library = next((library for library in self.libraries if library.name == artifact.name), None)
237
+ if library is not None:
238
+ return self._library_output(library)
239
+ filename = shared_library_name(Path(artifact.name).name, platform=self.platform.platform)
240
+ matches = [path for path in packaged if Path(path).name == filename]
241
+ if len(matches) != 1:
242
+ found = ", ".join(matches) if matches else "none"
243
+ raise FileNotFoundError(f"Artifact '{artifact.name}' needs a path: expected one packaged '{filename}', found {found}.")
244
+ return matches[0]
245
+
246
+ def validation_targets(self, packaged: list[str]) -> list[tuple[str, LibraryValidationConfig, str]]:
247
+ """Libraries with validation fields set, plus every `artifacts` entry, as (label, config, project-relative path)."""
248
+ targets: list[tuple[str, LibraryValidationConfig, str]] = []
249
+ for library in self.libraries:
250
+ if not _has_validation(library):
251
+ continue
252
+ if library.name in self._external_libraries:
253
+ targets.append((library.name, library, str(self._external_libraries[library.name].library)))
254
+ elif library.name not in self._skipped_libraries:
255
+ targets.append((library.name, library, self._library_output(library)))
256
+ targets.extend((artifact.name, artifact, self._artifact_path(artifact, packaged)) for artifact in self.artifacts)
257
+ return targets
258
+
259
+ def validate_artifacts(self, root: Path, packaged: list[str]) -> None:
260
+ """Check headers, ABI strings, and exports of each validation target, then run its validation commands."""
261
+ for label, config, relative in self.validation_targets(packaged):
262
+ library = root / relative
263
+ if not library.is_file():
264
+ raise FileNotFoundError(f"Artifact '{label}' library was not built: {relative}")
265
+ headers = check_headers(config.expected_headers, config.expected_abi_strings, base=root, label=label)
266
+ expected = list(dict.fromkeys([*config.expected_symbols, *prefixed_header_symbols(headers, config.header_symbol_prefix, label=label)]))
267
+ check_exports(library, expected=expected, load=config.validate_artifact, label=label, display_path=relative)
268
+ tokens = {"name": label, "path": str(library), "header": str(headers[0]) if headers else ""}
269
+ for command in config.validation_commands:
270
+ env = {**environ, **{key: value.format(**tokens) for key, value in command.env.items()}}
271
+ env.update({"HATCH_CPP_ARTIFACT_NAME": label, "HATCH_CPP_ARTIFACT_PATH": str(library)})
272
+ cwd = root / command.working_directory if command.working_directory else root
273
+ run_validation_command([value.format(**tokens) for value in command.command], cwd=cwd, env=env, label=label)
274
+
275
+ def write_manifest(self, root: Path, packaged: list[str]) -> str | None:
276
+ """Write the manifest of packaged binaries under the project root and return its relative path."""
277
+ if not self.artifact_manifest:
278
+ return None
279
+ assert self.artifact_manifest_destination is not None
280
+ records = [
281
+ {
282
+ "name": Path(path).name,
283
+ "role": _artifact_role(path, self.platform.platform),
284
+ "platform": self.platform.platform,
285
+ "profile": self.build_type,
286
+ "destination": Path(path).as_posix(),
287
+ }
288
+ for path in sorted(packaged)
289
+ ]
290
+ write_artifact_manifest(root / self.artifact_manifest_destination, module=self.name or "", records=records)
291
+ return self.artifact_manifest_destination
292
+
293
+
294
+ def _has_validation(config: LibraryValidationConfig) -> bool:
295
+ return bool(
296
+ config.expected_symbols
297
+ or config.expected_headers
298
+ or config.expected_abi_strings
299
+ or config.header_symbol_prefix
300
+ or config.validate_artifact
301
+ or config.validation_commands
302
+ )
303
+
304
+
305
+ def _artifact_role(path: str, platform: str) -> str:
306
+ """Classify a packaged binary: a Python extension module or a plain shared library."""
307
+ filename = Path(path).name
308
+ if filename.endswith(".pyd"):
309
+ return "python-extension"
310
+ if platform != "win32" and filename.startswith("lib"):
311
+ return "library"
312
+ if any(filename.endswith(suffix) for suffix in EXTENSION_SUFFIXES if suffix != ".so") or ".abi3." in filename:
313
+ return "python-extension"
314
+ if filename.endswith(".so") and platform in ("linux", "darwin", "emscripten"):
315
+ return "python-extension"
316
+ return "library"
@@ -88,9 +88,12 @@ class HatchCppBuildHook(BuildHookInterface):
88
88
 
89
89
  if build_plan.libraries:
90
90
  # force include libraries
91
- for library in build_plan.libraries:
91
+ for library in build_plan.built_libraries():
92
92
  name = library.get_qualified_name(build_plan.platform.platform)
93
93
  build_data["force_include"][name] = name
94
+ import_library = Path(name).with_suffix(".lib")
95
+ if build_plan.platform.platform == "win32" and library.binding == "generic" and import_library.is_file():
96
+ build_data["force_include"][import_library.as_posix()] = import_library.as_posix()
94
97
 
95
98
  build_data["pure_python"] = False
96
99
  machine = platform_machine()
@@ -101,9 +104,10 @@ class HatchCppBuildHook(BuildHookInterface):
101
104
  machine,
102
105
  version_major,
103
106
  version_minor,
104
- all(lib.py_limited_api for lib in build_plan.libraries),
107
+ all(lib.py_limited_api for lib in build_plan.built_libraries()),
105
108
  )
106
109
  else:
110
+ assert build_plan.cmake is not None
107
111
  build_data["pure_python"] = False
108
112
  machine = platform_machine()
109
113
  version_major = version_info.major
@@ -119,5 +123,11 @@ class HatchCppBuildHook(BuildHookInterface):
119
123
  if path.suffix in (".pyd", ".dll", ".so", ".dylib"):
120
124
  build_data["force_include"][str(path)] = str(path)
121
125
 
126
+ packaged = list(build_data["force_include"])
127
+ build_plan.validate_artifacts(Path(self.root), packaged)
128
+ manifest = build_plan.write_manifest(Path(self.root), packaged)
129
+ if manifest is not None:
130
+ build_data["force_include"][manifest] = manifest
131
+
122
132
  for path in build_data["force_include"]:
123
133
  self._logger.info(f"Force include: {path}")
@@ -1,3 +1,4 @@
1
+ from importlib import import_module
1
2
  from os import listdir
2
3
  from pathlib import Path
3
4
  from shutil import rmtree
@@ -41,6 +42,6 @@ class TestHatchBuild:
41
42
  # import
42
43
  here = Path(__file__).parent / project
43
44
  path.insert(0, str(here))
44
- import project.extension
45
+ extension = import_module("project.extension")
45
46
 
46
- assert project.extension.hello() == "A string"
47
+ assert extension.hello() == "A string"
@@ -1,4 +1,5 @@
1
1
  from hatchling.builders.hooks.plugin.interface import BuildHookInterface
2
+ from hatchling.metadata.core import ProjectMetadata
2
3
 
3
4
  from hatch_cpp.hooks import hatch_register_build_hook
4
5
 
@@ -10,7 +11,7 @@ def test_registered_build_hook_accepts_hatchling_configuration(tmp_path):
10
11
  root=str(tmp_path),
11
12
  config=config,
12
13
  build_config=None,
13
- metadata=None,
14
+ metadata=ProjectMetadata(str(tmp_path), None, {"project": {"name": "project", "version": "0.1.0"}}),
14
15
  directory=str(tmp_path),
15
16
  target_name="wheel",
16
17
  )
@@ -0,0 +1,5 @@
1
+ #include "demo/demo.h"
2
+
3
+ int demo_abi_version(void) { return DEMO_ABI_VERSION; }
4
+
5
+ int demo_answer(void) { return 42; }
@@ -0,0 +1,11 @@
1
+ #include <Python.h>
2
+
3
+ #include "demo/demo.h"
4
+
5
+ static PyObject *answer(PyObject *self, PyObject *args) { return PyLong_FromLong(demo_answer()); }
6
+
7
+ static PyMethodDef methods[] = {{"answer", answer, METH_NOARGS, NULL}, {NULL, NULL, 0, NULL}};
8
+
9
+ static struct PyModuleDef module = {PyModuleDef_HEAD_INIT, "extension", NULL, -1, methods};
10
+
11
+ PyMODINIT_FUNC PyInit_extension(void) { return PyModule_Create(&module); }
@@ -0,0 +1,22 @@
1
+ #pragma once
2
+
3
+ #define DEMO_ABI_VERSION 1
4
+
5
+ #if defined(_WIN32) && defined(DEMO_BUILD)
6
+ #define DEMO_API __declspec(dllexport)
7
+ #elif defined(_WIN32)
8
+ #define DEMO_API __declspec(dllimport)
9
+ #else
10
+ #define DEMO_API __attribute__((visibility("default")))
11
+ #endif
12
+
13
+ #ifdef __cplusplus
14
+ extern "C" {
15
+ #endif
16
+
17
+ DEMO_API int demo_abi_version(void);
18
+ DEMO_API int demo_answer(void);
19
+
20
+ #ifdef __cplusplus
21
+ }
22
+ #endif
@@ -0,0 +1,5 @@
1
+ import os
2
+ import sys
3
+
4
+ if sys.platform == "win32":
5
+ os.add_dll_directory(os.path.join(os.path.dirname(__file__), "lib"))