forked from xtensor-stack/xtensor-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcmake_helpers.py
More file actions
339 lines (253 loc) · 10.5 KB
/
cmake_helpers.py
File metadata and controls
339 lines (253 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
"""CMake helpers for xtensor-python.
This module provides CMake compatibility layer functions for projects
that use CMake to build C++ extensions with xtensor-python.
"""
import os
import platform
from pathlib import Path
from typing import Dict, List, Optional, Union
def get_cmake_dir() -> str:
"""Get the directory containing CMake configuration files.
Returns:
Path to the CMake configuration directory
"""
# For now, return the package directory since we don't have CMake files yet
# In a full implementation, this would point to installed CMake config files
package_dir = Path(__file__).parent
return str(package_dir)
def get_cmake_variables() -> Dict[str, str]:
"""Get CMake variables for xtensor-python configuration.
Returns:
Dictionary of CMake variable names and values
"""
from .build_helpers import get_include_dirs
from ._version import get_version_info, get_version_string
variables = {}
# Version information
try:
version_info = get_version_info()
version_string = get_version_string()
variables.update({
"xtensor-python_VERSION": version_string,
"xtensor-python_VERSION_MAJOR": str(version_info.major),
"xtensor-python_VERSION_MINOR": str(version_info.minor),
"xtensor-python_VERSION_PATCH": str(version_info.patch),
})
except Exception:
# Fallback values if version extraction fails
variables.update({
"xtensor-python_VERSION": "0.0.0",
"xtensor-python_VERSION_MAJOR": "0",
"xtensor-python_VERSION_MINOR": "0",
"xtensor-python_VERSION_PATCH": "0",
})
# Include directories
try:
include_dirs = get_include_dirs()
# Convert to CMake list format (semicolon-separated)
variables["xtensor-python_INCLUDE_DIRS"] = ";".join(include_dirs)
# Also provide the main xtensor-python include directory
package_dir = Path(__file__).parent
xtensor_python_include = str(package_dir / "include")
variables["xtensor-python_INCLUDE_DIR"] = xtensor_python_include
except Exception:
variables["xtensor-python_INCLUDE_DIRS"] = ""
variables["xtensor-python_INCLUDE_DIR"] = ""
# Compiler definitions
variables["xtensor-python_DEFINITIONS"] = ";".join([
"FORCE_IMPORT_ARRAY",
"NPY_NO_DEPRECATED_API=NPY_1_7_API_VERSION",
])
# Library information (header-only, so no actual libraries)
variables["xtensor-python_LIBRARIES"] = ""
variables["xtensor-python_LIBRARY_DIRS"] = ""
# CMake target information
variables["xtensor-python_TARGETS"] = "xtensor-python::xtensor-python"
return variables
def generate_cmake_config(output_dir: Union[str, Path]) -> Path:
"""Generate CMake configuration files for xtensor-python.
Args:
output_dir: Directory where CMake config files will be written
Returns:
Path to the generated config file
Raises:
OSError: If files cannot be written
"""
output_dir = Path(output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
# Get CMake variables
variables = get_cmake_variables()
# Generate the main config file
config_content = _generate_config_file_content(variables)
config_file = output_dir / "xtensor-pythonConfig.cmake"
with open(config_file, 'w', encoding='utf-8') as f:
f.write(config_content)
# Generate version file
version_content = _generate_version_file_content(variables)
version_file = output_dir / "xtensor-pythonConfigVersion.cmake"
with open(version_file, 'w', encoding='utf-8') as f:
f.write(version_content)
return config_file
def _generate_config_file_content(variables: Dict[str, str]) -> str:
"""Generate the content for xtensor-pythonConfig.cmake file."""
content = f'''# xtensor-python CMake configuration file
# Generated by xtensor-python Python package
# Version information
set(xtensor-python_VERSION "{variables.get('xtensor-python_VERSION', '0.0.0')}")
set(xtensor-python_VERSION_MAJOR "{variables.get('xtensor-python_VERSION_MAJOR', '0')}")
set(xtensor-python_VERSION_MINOR "{variables.get('xtensor-python_VERSION_MINOR', '0')}")
set(xtensor-python_VERSION_PATCH "{variables.get('xtensor-python_VERSION_PATCH', '0')}")
# Include directories
set(xtensor-python_INCLUDE_DIRS "{variables.get('xtensor-python_INCLUDE_DIRS', '')}")
set(xtensor-python_INCLUDE_DIR "{variables.get('xtensor-python_INCLUDE_DIR', '')}")
# Compiler definitions
set(xtensor-python_DEFINITIONS "{variables.get('xtensor-python_DEFINITIONS', '')}")
# Libraries (header-only library, so empty)
set(xtensor-python_LIBRARIES "")
set(xtensor-python_LIBRARY_DIRS "")
# Find required dependencies
find_package(Python COMPONENTS Interpreter Development REQUIRED)
find_package(pybind11 REQUIRED)
# Find NumPy
if(NOT DEFINED NumPy_INCLUDE_DIR)
execute_process(
COMMAND "${{Python_EXECUTABLE}}" -c "import numpy; print(numpy.get_include())"
OUTPUT_VARIABLE NumPy_INCLUDE_DIR
OUTPUT_STRIP_TRAILING_WHITESPACE
RESULT_VARIABLE NumPy_RESULT
)
if(NOT NumPy_RESULT EQUAL 0)
message(FATAL_ERROR "Could not find NumPy include directory")
endif()
endif()
# Create imported target
if(NOT TARGET xtensor-python::xtensor-python)
add_library(xtensor-python::xtensor-python INTERFACE IMPORTED)
# Set include directories
set_target_properties(xtensor-python::xtensor-python PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES "${{xtensor-python_INCLUDE_DIR}};${{NumPy_INCLUDE_DIR}}"
)
# Set compile definitions
set_target_properties(xtensor-python::xtensor-python PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "FORCE_IMPORT_ARRAY;NPY_NO_DEPRECATED_API=NPY_1_7_API_VERSION"
)
# Set C++ standard requirement
set_target_properties(xtensor-python::xtensor-python PROPERTIES
INTERFACE_COMPILE_FEATURES "cxx_std_17"
)
# Link to pybind11
set_target_properties(xtensor-python::xtensor-python PROPERTIES
INTERFACE_LINK_LIBRARIES "pybind11::pybind11"
)
endif()
# Compatibility variables
set(xtensor-python_FOUND TRUE)
set(XTENSOR_PYTHON_FOUND TRUE)
# Helper function to create xtensor-python extensions
function(xtensor_python_add_module target_name)
cmake_parse_arguments(XTENSOR_PYTHON "" "" "SOURCES" ${{ARGN}})
pybind11_add_module(${{target_name}} ${{XTENSOR_PYTHON_SOURCES}})
target_link_libraries(${{target_name}} PRIVATE xtensor-python::xtensor-python)
# Set additional properties for better performance
target_compile_options(${{target_name}} PRIVATE
$<$<CXX_COMPILER_ID:GNU,Clang>:-O3 -ffast-math>
$<$<CXX_COMPILER_ID:MSVC>:/O2>
)
endfunction()
message(STATUS "Found xtensor-python: ${{xtensor-python_VERSION}}")
'''
return content
def _generate_version_file_content(variables: Dict[str, str]) -> str:
"""Generate the content for xtensor-pythonConfigVersion.cmake file."""
version = variables.get('xtensor-python_VERSION', '0.0.0')
content = f'''# xtensor-python CMake version file
# Generated by xtensor-python Python package
set(PACKAGE_VERSION "{version}")
# Check whether the requested PACKAGE_FIND_VERSION is compatible
if("${{PACKAGE_VERSION}}" VERSION_LESS "${{PACKAGE_FIND_VERSION}}")
set(PACKAGE_VERSION_COMPATIBLE FALSE)
else()
set(PACKAGE_VERSION_COMPATIBLE TRUE)
if("${{PACKAGE_VERSION}}" VERSION_EQUAL "${{PACKAGE_FIND_VERSION}}")
set(PACKAGE_VERSION_EXACT TRUE)
endif()
endif()
'''
return content
def get_cmake_prefix_path() -> List[str]:
"""Get CMake prefix paths for finding xtensor-python.
Returns:
List of paths to add to CMAKE_PREFIX_PATH
"""
paths = []
# Add the package directory
package_dir = Path(__file__).parent
paths.append(str(package_dir))
return paths
def get_cmake_find_commands() -> List[str]:
"""Get CMake commands for finding xtensor-python.
Returns:
List of CMake find_package commands
"""
commands = [
"find_package(xtensor-python REQUIRED)",
"target_link_libraries(your_target PRIVATE xtensor-python::xtensor-python)",
]
return commands
def print_cmake_info():
"""Print CMake configuration information for debugging."""
print("xtensor-python CMake Information")
print("=" * 40)
# CMake directory
cmake_dir = get_cmake_dir()
print(f"CMake directory: {cmake_dir}")
# CMake variables
variables = get_cmake_variables()
print("\nCMake variables:")
for name, value in variables.items():
print(f" {name}: {value}")
# Prefix paths
prefix_paths = get_cmake_prefix_path()
print(f"\nCMake prefix paths:")
for path in prefix_paths:
print(f" {path}")
# Find commands
commands = get_cmake_find_commands()
print(f"\nCMake usage:")
for cmd in commands:
print(f" {cmd}")
def create_cmake_example(output_dir: Union[str, Path]) -> Path:
"""Create an example CMakeLists.txt file showing xtensor-python usage.
Args:
output_dir: Directory where the example will be written
Returns:
Path to the generated example file
"""
output_dir = Path(output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
example_content = '''# Example CMakeLists.txt for xtensor-python
cmake_minimum_required(VERSION 3.12)
project(xtensor_python_example)
# Set C++ standard
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# Find required packages
find_package(Python COMPONENTS Interpreter Development REQUIRED)
find_package(pybind11 REQUIRED)
find_package(xtensor-python REQUIRED)
# Create a pybind11 module
pybind11_add_module(example_module src/example.cpp)
# Link xtensor-python
target_link_libraries(example_module PRIVATE xtensor-python::xtensor-python)
# Alternative: use the helper function
# xtensor_python_add_module(example_module SOURCES src/example.cpp)
# Compiler-specific options for better performance
target_compile_definitions(example_module PRIVATE VERSION_INFO="${EXAMPLE_VERSION_INFO}")
'''
example_file = output_dir / "CMakeLists.txt.example"
with open(example_file, 'w', encoding='utf-8') as f:
f.write(example_content)
return example_file
# Backward compatibility aliases
get_include_dir = get_cmake_dir
get_cmake_include_dirs = lambda: get_cmake_variables().get("xtensor-python_INCLUDE_DIRS", "").split(";")