-
Notifications
You must be signed in to change notification settings - Fork 47
/
cmake.py
273 lines (228 loc) · 9.43 KB
/
cmake.py
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
from __future__ import annotations
import contextlib
import dataclasses
import json
import os
import shutil
import subprocess
import sys
import sysconfig
import textwrap
from pathlib import Path
from typing import TYPE_CHECKING, Generator
from . import __version__
from ._logging import logger
from ._shutil import Run
from .errors import CMakeConfigError, CMakeNotFoundError, FailedLiveProcessError
from .program_search import best_program, get_cmake_programs
if TYPE_CHECKING:
from collections.abc import Mapping, Sequence
from packaging.version import Version
from ._compat.typing import Self
__all__ = ["CMake", "CMaker"]
def __dir__() -> list[str]:
return __all__
DIR = Path(__file__).parent.resolve()
@dataclasses.dataclass(frozen=True)
class CMake:
version: Version
cmake_path: Path
@classmethod
def default_search(
cls, *, minimum_version: Version | None = None, module: bool = True
) -> Self:
candidates = get_cmake_programs(module=module)
cmake_program = best_program(candidates, minimum_version=minimum_version)
if cmake_program is None:
msg = f"Could not find CMake with version >= {minimum_version}"
raise CMakeNotFoundError(msg)
if cmake_program.version is None:
msg = "CMake version undetermined @ {program.path}"
raise CMakeNotFoundError(msg)
return cls(version=cmake_program.version, cmake_path=cmake_program.path)
def __fspath__(self) -> str:
return os.fspath(self.cmake_path)
@dataclasses.dataclass
class CMaker:
cmake: CMake
source_dir: Path
build_dir: Path
build_type: str
module_dirs: list[Path] = dataclasses.field(default_factory=list)
prefix_dirs: list[Path] = dataclasses.field(default_factory=list)
init_cache_file: Path = dataclasses.field(init=False, default=Path())
env: dict[str, str] = dataclasses.field(init=False, default_factory=os.environ.copy)
single_config: bool = not sysconfig.get_platform().startswith("win")
def __post_init__(self) -> None:
self.init_cache_file = self.build_dir / "CMakeInit.txt"
if not self.source_dir.is_dir():
msg = f"source directory {self.source_dir} does not exist"
raise CMakeConfigError(msg)
self.build_dir.mkdir(parents=True, exist_ok=True)
if not self.build_dir.is_dir():
msg = f"build directory {self.build_dir} must be a (creatable) directory"
raise CMakeConfigError(msg)
# If these were the same, the following check could wipe the source directory!
if self.build_dir.resolve() != self.source_dir.resolve():
skbuild_info = self.build_dir / ".skbuild-info.json"
# If building via SDist, this could be pre-filled, so delete it if it exists
with contextlib.suppress(FileNotFoundError):
with skbuild_info.open("r", encoding="utf-8") as f:
info = json.load(f)
cached_source_dir = Path(info["source_dir"])
if cached_source_dir.resolve() != self.source_dir.resolve():
logger.warning(
"Original src {} != {}, wiping build directory",
cached_source_dir,
self.source_dir,
)
shutil.rmtree(self.build_dir)
self.build_dir.mkdir()
with skbuild_info.open("w", encoding="utf-8") as f:
json.dump(self._info_dict(), f, indent=2)
def _info_dict(self) -> dict[str, str]:
"""
Produce an information dict about the current run that can be stored in a json file.
"""
return {
"source_dir": os.fspath(self.source_dir.resolve()),
"build_dir": os.fspath(self.build_dir.resolve()),
"cmake_path": os.fspath(self.cmake),
"skbuild_path": os.fspath(DIR),
"skbuild_version": __version__,
"python_executable": sys.executable,
}
def init_cache(
self, cache_settings: Mapping[str, str | os.PathLike[str] | bool]
) -> None:
with self.init_cache_file.open("w", encoding="utf-8") as f:
for key, value in cache_settings.items():
if isinstance(value, bool):
str_value = "ON" if value else "OFF"
f.write(f'set({key} {str_value} CACHE BOOL "" FORCE)\n')
elif isinstance(value, os.PathLike):
# Convert to CMake's internal path format
str_value = str(value).replace("\\", "/")
f.write(f'set({key} [===[{str_value}]===] CACHE PATH "" FORCE)\n')
else:
f.write(f'set({key} [===[{value}]===] CACHE STRING "" FORCE)\n')
if self.module_dirs:
# Convert to CMake's internal path format, otherwise this breaks try_compile on Windows
module_dirs_str = ";".join(map(str, self.module_dirs)).replace(
"\\", "/"
)
f.write(
f'set(CMAKE_MODULE_PATH [===[{module_dirs_str}]===] CACHE PATH "" FORCE)\n'
)
if self.prefix_dirs:
prefix_dirs_str = ";".join(map(str, self.prefix_dirs)).replace(
"\\", "/"
)
f.write(
f'set(CMAKE_PREFIX_PATH [===[{prefix_dirs_str}]===] CACHE PATH "" FORCE)\n'
)
f.write('set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE "BOTH" CACHE PATH "")\n')
contents = self.init_cache_file.read_text(encoding="utf-8").strip()
logger.debug(
"{}:\n{}",
self.init_cache_file,
textwrap.indent(contents.strip(), " "),
)
def _compute_cmake_args(
self, defines: Mapping[str, str | os.PathLike[str] | bool]
) -> Generator[str, None, None]:
yield f"-S{self.source_dir}"
yield f"-B{self.build_dir}"
if self.init_cache_file.is_file():
yield f"-C{self.init_cache_file}"
if self.single_config and self.build_type:
yield f"-DCMAKE_BUILD_TYPE:STRING={self.build_type}"
for key, value in defines.items():
if isinstance(value, bool):
str_value = "ON" if value else "OFF"
yield f"-D{key}:BOOL={str_value}"
elif isinstance(value, os.PathLike):
str_value = str(value).replace("\\", "/")
yield f"-D{key}:PATH={str_value}"
else:
yield f"-D{key}={value}"
def get_generator(self, *args: str) -> str | None:
"""
Try to get the generator that will be used to build the project. If it's
not set, return None (default generator will be used).
"""
generators = [g for g in args if g.startswith("-G")]
if generators:
return generators[-1][2:]
return self.env.get("CMAKE_GENERATOR", None)
def configure(
self,
*,
defines: Mapping[str, str | os.PathLike[str] | bool] | None = None,
cmake_args: Sequence[str] = (),
) -> None:
_cmake_args = self._compute_cmake_args(defines or {})
all_args = [*_cmake_args, *cmake_args]
gen = self.get_generator(*all_args)
if gen:
self.single_config = gen == "Ninja" or "Makefiles" in gen
try:
Run(env=self.env).live(self.cmake, *all_args)
except subprocess.CalledProcessError:
msg = "CMake configuration failed"
raise FailedLiveProcessError(msg) from None
def _compute_build_args(
self,
*,
verbose: bool,
) -> Generator[str, None, None]:
if verbose:
yield "-v"
if self.build_type and not self.single_config:
yield "--config"
yield self.build_type
def build(
self,
build_args: Sequence[str] = (),
*,
targets: Sequence[str] = (),
verbose: bool = False,
) -> None:
local_args = self._compute_build_args(verbose=verbose)
if not targets:
self._build(*local_args, *build_args)
return
for target in targets:
self._build(*local_args, "--target", target, *build_args)
def _build(self, *args: str) -> None:
try:
Run(env=self.env).live(self.cmake, "--build", self.build_dir, *args)
except subprocess.CalledProcessError:
msg = "CMake build failed"
raise FailedLiveProcessError(msg) from None
def install(
self, prefix: Path, *, strip: bool = False, components: Sequence[str] = ()
) -> None:
opts = ["--prefix", str(prefix)]
if not self.single_config and self.build_type:
opts += ["--config", self.build_type]
if strip:
opts.append("--strip")
if not components:
self._install(opts)
return
for comp in components:
opts_with_comp = [*opts, "--component", comp]
logger.info("Installing component {}", comp)
self._install(opts_with_comp)
def _install(self, opts: Sequence[str]) -> None:
try:
Run(env=self.env).live(
self.cmake,
"--install",
self.build_dir,
*opts,
)
except subprocess.CalledProcessError:
msg = "CMake install failed"
raise FailedLiveProcessError(msg) from None