/
skbuild_read_settings.py
427 lines (368 loc) · 15.4 KB
/
skbuild_read_settings.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
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
from __future__ import annotations
import copy
import dataclasses
import difflib
import os
import platform
import re
import sys
from pathlib import Path
from typing import TYPE_CHECKING, Any
from packaging.specifiers import SpecifierSet
from packaging.version import Version
from .. import __version__
from .._compat import tomllib
from .._logging import logger, rich_print
from ..errors import CMakeConfigError
from .skbuild_model import CMakeSettings, NinjaSettings, ScikitBuildSettings
from .sources import ConfSource, EnvSource, SourceChain, TOMLSource
if TYPE_CHECKING:
from collections.abc import Generator, Mapping
from .._compat.typing import Literal
__all__ = ["SettingsReader"]
def __dir__() -> list[str]:
return __all__
def strtobool(value: str) -> bool:
"""
Converts a environment variable string into a boolean value.
"""
value = value.lower()
if value.isdigit():
return bool(int(value))
return value in {"y", "yes", "on", "true", "t"}
def version_match(value: str, match: str, name: str) -> str:
"""
Returns a non-empty string if a version matches a specifier.
"""
matcher = SpecifierSet(match)
did_match = matcher.contains(value)
return f"{match!r} matched {name} {value}" if did_match else ""
def regex_match(value: str, match: str) -> str:
"""
Returns a non-empty string if a value matches a regex.
"""
did_match = re.compile(match).search(value) is not None
return f"{match!r} matched {value!r}" if did_match else ""
def override_match(
*,
match_all: bool,
current_env: Mapping[str, str] | None,
current_state: Literal[
"sdist", "wheel", "editable", "metadata_wheel", "metadata_editable"
],
python_version: str | None = None,
implementation_name: str | None = None,
implementation_version: str | None = None,
platform_system: str | None = None,
platform_machine: str | None = None,
platform_node: str | None = None,
env: dict[str, str] | None = None,
state: str | None = None,
) -> bool:
matches = []
if current_env is None:
current_env = os.environ
if python_version is not None:
current_python_version = ".".join(str(x) for x in sys.version_info[:2])
match_msg = version_match(current_python_version, python_version, "Python")
matches.append(match_msg)
if implementation_name is not None:
current_impementation_name = sys.implementation.name
match_msg = regex_match(current_impementation_name, implementation_name)
matches.append(match_msg)
if implementation_version is not None:
info = sys.implementation.version
version = f"{info.major}.{info.minor}.{info.micro}"
kind = info.releaselevel
if kind != "final":
version += f"{kind[0]}{info.serial}"
match_msg = version_match(
version, implementation_version, "Python implementation"
)
matches.append(match_msg)
if platform_system is not None:
current_platform_system = sys.platform
match_msg = regex_match(current_platform_system, platform_system)
matches.append(match_msg)
if platform_machine is not None:
current_platform_machine = platform.machine()
match_msg = regex_match(current_platform_machine, platform_machine)
matches.append(match_msg)
if platform_node is not None:
current_platform_node = platform.node()
match_msg = regex_match(current_platform_node, platform_node)
matches.append(match_msg)
if state is not None:
match_msg = regex_match(current_state, state)
matches.append(match_msg)
if env:
for key, value in env.items():
if isinstance(value, bool):
matches.append(
f"env {key} is {value}"
if strtobool(current_env.get(key, "")) == value
else ""
)
elif key not in current_env:
matches.append("")
else:
current_value = current_env.get(key, "")
match_msg = regex_match(current_value, value)
matches.append(match_msg and f"env {key}: {match_msg}")
if not matches:
msg = "At least one override must be provided"
raise ValueError(msg)
if match_all:
matched = all(matches)
if matched:
logger.info("Overrides {}", " and ".join(matches))
else:
matched = any(matches)
if matched:
logger.info("Overrides {}", " or ".join([m for m in matches if m]))
return matched
def _handle_minimum_version(
dc: CMakeSettings | NinjaSettings, minimum_version: Version | None
) -> None:
"""
Handle the minimum version option. Supports scikit-build-core < 0.8 style
minimum_version. Prints an error message and exits.
"""
name = "cmake" if isinstance(dc, CMakeSettings) else "ninja"
version_default = next(
iter(f for f in dataclasses.fields(dc) if f.name == "version")
).default
# Check for minimum_version < 0.8 and the modern version setting
if (
dc.version != version_default
and minimum_version is not None
and minimum_version < Version("0.8")
):
rich_print(
f"[red][bold]ERROR:[/bold] Cannot set {name}.version if minimum-version is set to less than 0.8 (which is where it was introduced)"
)
raise SystemExit(7)
# Backwards compatibility for minimum_version
if dc.minimum_version is not None:
msg = f"Use {name}.version instead of {name}.minimum-version with scikit-build-core >= 0.8"
if minimum_version is None:
rich_print(f"[yellow][bold]WARNING:[/bold] {msg}")
elif minimum_version >= Version("0.8"):
rich_print(f"[red][bold]ERROR:[/bold] {msg}")
raise SystemExit(7)
if dc.version != version_default:
rich_print(
f"[red][bold]ERROR:[/bold] Cannot set both {name}.minimum_version and {name}.version; use version only for scikit-build-core >= 0.8."
)
raise SystemExit(7)
dc.version = SpecifierSet(f">={dc.minimum_version}")
def inherit_join(
value: list[str] | dict[str, str] | str | int | bool,
previous: list[str] | dict[str, str] | str | int | bool | None,
mode: str,
) -> list[str] | dict[str, str] | str | int | bool:
if mode not in {"none", "append", "prepend"}:
msg = "Only 'none', 'append', and 'prepend' supported for inherit"
raise TypeError(msg)
if mode == "none" or previous is None:
return value
if isinstance(previous, list) and isinstance(value, list):
return [*previous, *value] if mode == "append" else [*value, *previous]
if isinstance(previous, dict) and isinstance(value, dict):
return {**previous, **value} if mode == "append" else {**value, **previous}
msg = "Append/prepend modes can only be used on lists or dicts"
raise TypeError(msg)
def process_overides(
tool_skb: dict[str, Any],
state: Literal["sdist", "wheel", "editable", "metadata_wheel", "metadata_editable"],
env: Mapping[str, str] | None = None,
) -> None:
"""
Process overrides into the main dictionary if they match. Modifies the input dictionary.
"""
for override in tool_skb.pop("overrides", []):
matched = True
if_override = override.pop("if", None)
if not if_override:
msg = "At least one 'if' override must be provided"
raise KeyError(msg)
if not isinstance(if_override, dict):
msg = "'if' override must be a table"
raise TypeError(msg)
if "any" in if_override:
any_override = if_override.pop("any")
select = {k.replace("-", "_"): v for k, v in any_override.items()}
matched = override_match(
match_all=False, current_env=env, current_state=state, **select
)
inherit_override = override.pop("inherit", {})
if not isinstance(inherit_override, dict):
msg = "'inherit' override must be a table"
raise TypeError(msg)
select = {k.replace("-", "_"): v for k, v in if_override.items()}
if select:
matched = matched and override_match(
match_all=True, current_env=env, current_state=state, **select
)
if matched:
for key, value in override.items():
inherit1 = inherit_override.get(key, {})
if isinstance(value, dict):
for key2, value2 in value.items():
inherit2 = inherit1.get(key2, "none")
inner = tool_skb.get(key, {})
inner[key2] = inherit_join(
value2, inner.get(key2, None), inherit2
)
tool_skb[key] = inner
else:
inherit_override_tmp = inherit_override or "none"
if isinstance(inherit_override_tmp, dict):
assert not inherit_override_tmp
tool_skb[key] = inherit_join(
value, tool_skb.get(key), inherit_override_tmp
)
class SettingsReader:
def __init__(
self,
pyproject: dict[str, Any],
config_settings: Mapping[str, str | list[str]],
*,
state: Literal[
"sdist", "wheel", "editable", "metadata_wheel", "metadata_editable"
],
extra_settings: Mapping[str, Any] | None = None,
verify_conf: bool = True,
env: Mapping[str, str] | None = None,
) -> None:
self.state = state
pyproject = copy.deepcopy(pyproject)
process_overides(pyproject.get("tool", {}).get("scikit-build", {}), state, env)
toml_srcs = [TOMLSource("tool", "scikit-build", settings=pyproject)]
if extra_settings is not None:
extra_skb = copy.deepcopy(dict(extra_settings))
process_overides(extra_skb, state, env)
toml_srcs.insert(0, TOMLSource(settings=extra_skb))
prefixed = {
k: v for k, v in config_settings.items() if k.startswith("skbuild.")
}
remaining = {
k: v for k, v in config_settings.items() if not k.startswith("skbuild.")
}
self.sources = SourceChain(
EnvSource("SKBUILD"),
ConfSource("skbuild", settings=prefixed, verify=verify_conf),
ConfSource(settings=remaining, verify=verify_conf),
*toml_srcs,
prefixes=["tool", "scikit-build"],
)
self.settings = self.sources.convert_target(ScikitBuildSettings)
if self.settings.minimum_version:
current_version = Version(__version__)
minimum_version = self.settings.minimum_version
if current_version < minimum_version:
msg = (
f"scikit-build-core version {__version__} is too old. "
f"Minimum required version is {self.settings.minimum_version}."
)
raise CMakeConfigError(msg)
if self.settings.editable.rebuild:
if self.settings.editable.mode == "inplace":
rich_print(
"[red][bold]ERROR:[/bold] editable rebuild is incompatible with inplace mode"
)
raise SystemExit(7)
if not self.settings.build_dir:
rich_print(
"[red][bold]ERROR:[/bold] editable mode with rebuild requires build-dir"
)
raise SystemExit(7)
install_policy = (
self.settings.minimum_version is None
or self.settings.minimum_version >= Version("0.5")
)
if self.settings.install.strip is None:
self.settings.install.strip = install_policy
_handle_minimum_version(self.settings.cmake, self.settings.minimum_version)
_handle_minimum_version(self.settings.ninja, self.settings.minimum_version)
def unrecognized_options(self) -> Generator[str, None, None]:
return self.sources.unrecognized_options(ScikitBuildSettings)
def suggestions(self, index: int) -> dict[str, list[str]]:
all_options = list(self.sources[index].all_option_names(ScikitBuildSettings))
result: dict[str, list[str]] = {
k: [] for k in self.sources[index].unrecognized_options(ScikitBuildSettings)
}
for option in result:
possibilities = {
".".join(k.split(".")[: option.count(".") + 1]) for k in all_options
}
result[option] = difflib.get_close_matches(option, possibilities, n=3)
return result
def print_suggestions(self) -> None:
for index in (1, 2, 3):
name = {1: "config-settings", 2: "config-settings", 3: "pyproject.toml"}[
index
]
suggestions_dict = self.suggestions(index)
if suggestions_dict:
rich_print(f"[red][bold]ERROR:[/bold] Unrecognized options in {name}:")
for option, suggestions in suggestions_dict.items():
rich_print(f" [red]{option}", end="")
if suggestions:
sugstr = ", ".join(suggestions)
rich_print(f"[yellow] -> Did you mean: {sugstr}?", end="")
rich_print()
def validate_may_exit(self) -> None:
unrecognized = list(self.unrecognized_options())
if unrecognized:
if self.settings.strict_config:
sys.stdout.flush()
self.print_suggestions()
raise SystemExit(7)
logger.warning("Unrecognized options: {}", ", ".join(unrecognized))
for key, value in self.settings.metadata.items():
if "provider" not in value:
sys.stdout.flush()
rich_print(
f"[red][bold]ERROR:[/bold] provider= must be provided in {key!r}:"
)
raise SystemExit(7)
if not self.settings.experimental and (
"provider-path" in value
or not value["provider"].startswith("scikit_build_core.")
):
sys.stdout.flush()
rich_print(
"[red][bold]ERROR:[/bold] experimental must be enabled currently to use plugins not provided by scikit-build-core"
)
raise SystemExit(7)
for gen in self.settings.generate:
if not gen.template and not gen.template_path:
sys.stdout.flush()
rich_print(
"[red][bold]ERROR:[/bold] template= or template-path= must be provided in generate"
)
raise SystemExit(7)
@classmethod
def from_file(
cls,
pyproject_path: os.PathLike[str] | str,
config_settings: Mapping[str, str | list[str]] | None = None,
*,
state: Literal[
"sdist", "wheel", "editable", "metadata_wheel", "metadata_editable"
] = "sdist",
verify_conf: bool = True,
extra_settings: Mapping[str, Any] | None = None,
env: Mapping[str, str] | None = None,
) -> SettingsReader:
with Path(pyproject_path).open("rb") as f:
pyproject = tomllib.load(f)
return cls(
pyproject,
config_settings or {},
verify_conf=verify_conf,
state=state,
extra_settings=extra_settings,
env=env,
)