|
1 | 1 | from __future__ import annotations |
2 | 2 |
|
| 3 | +from json import dumps |
3 | 4 | from logging import getLogger |
4 | 5 | from os import getenv |
| 6 | +from pathlib import Path |
| 7 | +from tempfile import NamedTemporaryFile |
5 | 8 |
|
| 9 | +from hatchling.builders.hooks.plugin.interface import BuildHookInterface |
6 | 10 | from hatchling.metadata.plugin.interface import MetadataHookInterface |
7 | 11 |
|
8 | 12 | from .structs import HatchMultiConfig |
9 | 13 |
|
10 | | -__all__ = ("HatchMultiMetadataHook",) |
| 14 | +__all__ = ("HatchMultiBuildHook", "HatchMultiMetadataHook") |
11 | 15 |
|
12 | 16 |
|
13 | | -class HatchMultiMetadataHook(MetadataHookInterface): |
| 17 | +class HatchMultiBuildHook(BuildHookInterface): |
14 | 18 | """The hatch-multi build hook.""" |
15 | 19 |
|
| 20 | + PLUGIN_NAME = "hatch-multi" |
| 21 | + _temporary_project_file: Path | None = None |
| 22 | + |
| 23 | + def initialize(self, version: str, build_data: dict) -> None: |
| 24 | + if self.target_name != "sdist": |
| 25 | + return |
| 26 | + |
| 27 | + configured_name = self.metadata.config["project"]["name"] |
| 28 | + package_name = self.metadata.core.raw_name |
| 29 | + if package_name == configured_name: |
| 30 | + return |
| 31 | + |
| 32 | + project_file = Path(self.root, "pyproject.toml") |
| 33 | + lines = project_file.read_text(encoding="utf-8").splitlines(keepends=True) |
| 34 | + in_project_table = False |
| 35 | + for index, line in enumerate(lines): |
| 36 | + stripped_line = line.strip() |
| 37 | + if stripped_line.startswith("[") and stripped_line.endswith("]"): |
| 38 | + in_project_table = stripped_line == "[project]" |
| 39 | + elif in_project_table: |
| 40 | + key, separator, _value = line.partition("=") |
| 41 | + if separator and key.strip() == "name": |
| 42 | + newline = "\n" if line.endswith("\n") else "" |
| 43 | + lines[index] = f"{key}= {dumps(package_name)}{newline}" |
| 44 | + break |
| 45 | + |
| 46 | + with NamedTemporaryFile(mode="w", encoding="utf-8", suffix=".toml", delete=False) as temporary_project_file: |
| 47 | + temporary_project_file.writelines(lines) |
| 48 | + self._temporary_project_file = Path(temporary_project_file.name) |
| 49 | + |
| 50 | + build_data["force_include"].pop(str(project_file), None) |
| 51 | + build_data["force_include"][str(self._temporary_project_file)] = "pyproject.toml" |
| 52 | + |
| 53 | + def finalize(self, version: str, build_data: dict, artifact_path: str) -> None: |
| 54 | + if self._temporary_project_file is not None: |
| 55 | + self._temporary_project_file.unlink() |
| 56 | + self._temporary_project_file = None |
| 57 | + |
| 58 | + |
| 59 | +class HatchMultiMetadataHook(MetadataHookInterface): |
| 60 | + """The hatch-multi metadata hook.""" |
| 61 | + |
16 | 62 | PLUGIN_NAME = "hatch-multi" |
17 | 63 | _logger = getLogger(__name__) |
18 | 64 |
|
|
0 commit comments