Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions docs/configuration/config_settings.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,34 @@ The define is left unset when the setting resolves to no value, so
`if(DEFINED ZMQ_PREFIX)` works in CMake, and `-C cmake.define.NAME=...` or
`SKBUILD_CMAKE_DEFINE` still win over the referenced value.

## Passing values to dynamic metadata plugins

A `[[tool.dynamic-metadata]]` entry can map plugin settings to declared settings
with a `tool.scikit-build.config-setting` table. The plugin receives the
resolved value as if it was written in the entry, so the plugin does not need to
know about config-settings:

```toml
[tool.scikit-build.config-setting."torch.variant"]
env = "PYTORCH_VARIANT"

[[tool.dynamic-metadata]]
provider = "torch-deps"
variant = "cpu"
tool.scikit-build.config-setting.variant = "torch.variant"
```

The static value (`"cpu"` above) is used when the setting resolves to no value.
A `default` in the declaration takes precedence over the static value. The
entry's `tool` key is never passed to the plugin, and the mapping cannot set
`provider` or `tool`. Use dotted keys as shown.

The deprecated `tool.scikit-build.metadata` table does not support this.

:::{versionadded} 1.2

:::

## Use in overrides

Declared settings can drive [overrides](./overrides.md) with the
Expand Down
10 changes: 6 additions & 4 deletions docs/configuration/dynamic.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,12 @@ The standard, cross-backend way to configure plugins is the top-level
`dynamic_metadata.provider` entry-point group (scikit-build-core's built-ins
register their module path, e.g. `scikit_build_core.metadata.regex`), or an
inline `{ path, module }` table for a plugin living inside your own project.
Every other key is passed to that plugin as its settings. Entries run **in
order**, so a later entry sees every field an earlier one produced (no
dependency graph, no cycles), and a plugin can read an already-resolved field
with `project[...]`.
Every other key is passed to that plugin as its settings, except `tool`, which
holds backend options such as the
[`tool.scikit-build.config-setting` mapping](./config_settings.md#passing-values-to-dynamic-metadata-plugins).
Entries run **in order**, so a later entry sees every field an earlier one
produced (no dependency graph, no cycles), and a plugin can read an
already-resolved field with `project[...]`.

```toml
[project]
Expand Down
32 changes: 27 additions & 5 deletions src/scikit_build_core/build/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"scikit_build_core.build",
"scikit_build_core.builder._load_provider",
"scikit_build_core.settings.__main__",
"scikit_build_core.settings.skbuild_read_settings",
"typing",
}

Expand All @@ -26,33 +27,45 @@
process_legacy_dynamic_metadata,
)
from scikit_build_core.settings.__main__ import _load_pyproject
from scikit_build_core.settings.skbuild_read_settings import SettingsReader


def main_project_table(args: argparse.Namespace, /) -> None:
"""Get the full project table, including dynamic metadata."""
pyproject = _load_pyproject()
# The reader checks the config-settings as the build backend does.
reader = SettingsReader.from_file(
"pyproject.toml", _parse_config_settings(args.config_settings), state=args.state
)
reader.validate_may_exit()

project = pyproject.get("project", {})
legacy = pyproject.get("tool", {}).get("scikit-build", {}).get("metadata", {})
tool_skb = pyproject.get("tool", {}).get("scikit-build", {})
entries = reader.dynamic_metadata

legacy = tool_skb.get("metadata", {})
if legacy:
project = process_legacy_dynamic_metadata(project, legacy)
entries = pyproject.get("tool", {}).get("dynamic-metadata", [])
if entries:
project = process_dynamic_metadata(project, entries, build_state=args.state)
print(json.dumps(project, indent=2))


def main_requires(args: argparse.Namespace, /) -> None:
def _parse_config_settings(items: list[str]) -> dict[str, str | list[str]]:
config_settings: dict[str, str | list[str]] = {}
for item in args.config_settings:
for item in items:
key, _, value = item.partition("=")
if key not in config_settings:
config_settings[key] = value
elif isinstance(old := config_settings[key], list):
old.append(value)
else:
config_settings[key] = [old, value]
get_requires(args.mode, args.type, config_settings)
return config_settings


def main_requires(args: argparse.Namespace, /) -> None:
get_requires(args.mode, args.type, _parse_config_settings(args.config_settings))


def get_requires(
Expand Down Expand Up @@ -123,6 +136,15 @@ def populate_parser(parser: argparse.ArgumentParser, /) -> None:
default="metadata_wheel",
help="The build state reported to [[tool.dynamic-metadata]] providers",
)
project_table.add_argument(
"-C",
"--config-setting",
dest="config_settings",
action="append",
default=[],
metavar="KEY=VALUE",
help="A package-declared config-setting, for dynamic metadata that references one; can be repeated",
)


def main() -> None:
Expand Down
14 changes: 12 additions & 2 deletions src/scikit_build_core/build/metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@

TYPE_CHECKING = False
if TYPE_CHECKING:
from collections.abc import Mapping
from collections.abc import Mapping, Sequence

from ..builder._load_provider import BuildState
from ..settings.skbuild_model import ScikitBuildSettings
Expand Down Expand Up @@ -84,7 +84,13 @@ def get_standard_metadata(
pyproject_dict: Mapping[str, Any],
settings: ScikitBuildSettings,
build_state: BuildState = "metadata_wheel",
dynamic_metadata_entries: Sequence[Mapping[str, Any]] | None = None,
) -> SkbuildMetadata:
"""
Compute the metadata. ``dynamic_metadata_entries`` replaces the
``[[tool.dynamic-metadata]]`` entries of ``pyproject_dict``; pass
``SettingsReader.dynamic_metadata`` to get its ``tool.scikit-build`` tables applied.
"""
new_pyproject_dict = copy.deepcopy(dict(pyproject_dict))
project = new_pyproject_dict["project"]

Expand All @@ -106,7 +112,11 @@ def get_standard_metadata(
if settings.metadata:
project = process_legacy_dynamic_metadata(project, settings.metadata)

entries = new_pyproject_dict.get("tool", {}).get("dynamic-metadata", [])
entries = (
new_pyproject_dict.get("tool", {}).get("dynamic-metadata", [])
if dynamic_metadata_entries is None
else dynamic_metadata_entries
)
if entries:
project = process_dynamic_metadata(project, entries, build_state)

Expand Down
7 changes: 6 additions & 1 deletion src/scikit_build_core/build/sdist.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,12 @@ def build_sdist(
reproducible = settings.sdist.reproducible
timestamp = get_reproducible_epoch() if reproducible else None

metadata = get_standard_metadata(pyproject, settings, build_state="sdist")
metadata = get_standard_metadata(
pyproject,
settings,
build_state="sdist",
dynamic_metadata_entries=settings_reader.dynamic_metadata,
)
pkg_info = bytes(metadata.as_rfc822())

# Names must be normalized per PEP 625
Expand Down
12 changes: 10 additions & 2 deletions src/scikit_build_core/build/wheel.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@

TYPE_CHECKING = False
if TYPE_CHECKING:
from collections.abc import Iterable, Sequence
from collections.abc import Iterable, Mapping, Sequence

from ..settings.skbuild_model import ScikitBuildSettings

Expand Down Expand Up @@ -271,6 +271,7 @@ def _build_wheel_impl(
state=state,
settings=settings_reader.settings,
pyproject=pyproject,
dynamic_metadata_entries=settings_reader.dynamic_metadata,
)
except FailedLiveProcessError as err:
settings_reader = SettingsReader(
Expand Down Expand Up @@ -300,6 +301,7 @@ def _build_wheel_impl(
state=state,
settings=settings_reader.settings,
pyproject=pyproject,
dynamic_metadata_entries=settings_reader.dynamic_metadata,
)
except FailedLiveProcessError as err2:
err2.msg = settings_reader.settings.messages.after_failure
Expand All @@ -315,12 +317,18 @@ def _build_wheel_impl_impl(
state: Literal["sdist", "wheel", "editable", "metadata_wheel", "metadata_editable"],
settings: ScikitBuildSettings,
pyproject: dict[str, Any],
dynamic_metadata_entries: Sequence[Mapping[str, Any]] | None = None,
) -> WheelImplReturn:
"""
Build a wheel or just prepare metadata (if wheel dir is None). Can be editable.
"""

metadata = get_standard_metadata(pyproject, settings, build_state=state)
metadata = get_standard_metadata(
pyproject,
settings,
build_state=state,
dynamic_metadata_entries=dynamic_metadata_entries,
)

if metadata.version is None:
msg = "project.version is not specified, must be statically present or tool.scikit-build metadata.version.provider configured when dynamic"
Expand Down
7 changes: 4 additions & 3 deletions src/scikit_build_core/builder/_load_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,14 +223,15 @@ def load_dynamic_metadata(
) -> Generator[tuple[DMProtocols, dict[str, Any]], None, None]:
"""Load each ``[[tool.dynamic-metadata]]`` entry's provider in order.
``provider`` is consumed here; the remaining keys are returned as that
provider's plugin settings.
``provider`` is consumed here, and the backend-reserved ``tool`` key is
dropped; the remaining keys are returned as that provider's plugin
settings.
"""
for entry in entries:
if "provider" not in entry:
msg = "Each [[tool.dynamic-metadata]] entry must set a 'provider'"
raise KeyError(msg)
settings = {k: v for k, v in entry.items() if k != "provider"}
settings = {k: v for k, v in entry.items() if k not in {"provider", "tool"}}
provider = load_entry_provider(entry["provider"])
yield provider, settings

Expand Down
9 changes: 5 additions & 4 deletions src/scikit_build_core/builder/get_requires.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,10 +85,11 @@ def _read_pyproject() -> dict[str, Any]:

def _read_dynamic_metadata() -> list[dict[str, Any]]:
"""Read the top-level ``[[tool.dynamic-metadata]]`` entries (0.3)."""
entries: list[dict[str, Any]] = (
_read_pyproject().get("tool", {}).get("dynamic-metadata", [])
)
return entries
try:
# The reader applies the config-setting mappings.
return SettingsReader.from_file("pyproject.toml").dynamic_metadata
except FileNotFoundError:
return []


def _read_variant_table() -> dict[str, Any]:
Expand Down
49 changes: 49 additions & 0 deletions src/scikit_build_core/settings/config_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"load_declarations",
"resolve_config_settings",
"resolve_define_references",
"resolve_metadata_config_settings",
]


Expand Down Expand Up @@ -214,3 +215,51 @@ def resolve_define_references(
del define[key]
else:
define[key] = value


def resolve_metadata_config_settings(
entries: Any, values: "Mapping[str, str | bool | None]"
) -> bool:
"""
Apply ``tool.scikit-build.config-setting`` of each
``[[tool.dynamic-metadata]]`` entry, in place, and remove the reserved
``tool`` key. The table maps a plugin setting to a declared config-setting;
a resolved value replaces the static one, and an unset setting keeps it.
Returns True if an entry has a mapping.
"""
used = False
if not isinstance(entries, list):
return used
for n, entry in enumerate(entries):
if not isinstance(entry, dict) or "tool" not in entry:
continue
context = f"tool.dynamic-metadata[{n}].tool"
tool = entry.pop("tool")
if not isinstance(tool, dict):
rich_error(f"{context} must be a table")
# Other backends' tables are ignored.
skb = tool.get("scikit-build", {})
context += ".scikit-build"
if not isinstance(skb, dict):
rich_error(f"{context} must be a table")
unknown = set(skb) - {"config-setting"}
if unknown:
rich_error(f"{context} has unrecognized keys: {', '.join(sorted(unknown))}")
mapping = skb.get("config-setting", {})
context += ".config-setting"
if not isinstance(mapping, dict):
rich_error(f"{context} must be a table")
used = used or bool(mapping)
for key, name in mapping.items():
if key in {"provider", "tool"}:
rich_error(f"{context} may not set {key!r}")
if not isinstance(name, str):
rich_error(f"{context}.{key} must be a string")
if name not in values:
rich_error(
f"{context}.{key} references undeclared config-setting {name!r}"
)
value = values[name]
if value is not None:
entry[key] = value
return used
13 changes: 13 additions & 0 deletions src/scikit_build_core/settings/skbuild_read_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
load_declarations,
resolve_config_settings,
resolve_define_references,
resolve_metadata_config_settings,
)
from .skbuild_model import (
BuildSettings,
Expand Down Expand Up @@ -340,6 +341,9 @@ def process_table(
self.dynamic_metadata: list[dict[str, Any]] = pyproject.get("tool", {}).get(
"dynamic-metadata", []
)
metadata_mapping = resolve_metadata_config_settings(
self.dynamic_metadata, self.custom_config_settings
)
self.variant: dict[str, Any] = pyproject.get("variant", {})

# Support for cmake.version='CMakeLists.txt'
Expand Down Expand Up @@ -590,6 +594,15 @@ def process_table(
"minimum-version must be at least 1.1 to use tool.scikit-build.config-setting"
)

if (
metadata_mapping
and self.settings.minimum_version is not None
and self.settings.minimum_version < Version("1.2")
):
rich_error(
"minimum-version must be at least 1.2 to use tool.scikit-build.config-setting in tool.dynamic-metadata"
)

if self.settings.sdist.inclusion_mode is not None:
if (
self.settings.minimum_version is not None
Expand Down
Loading
Loading