Skip to content

Commit bb90277

Browse files
fix: Allow the ; private annotation in import-names/import-namespaces pyproject entries (#2366)
* fix: Allow the `; private` annotation on `import-names`/`import-namespaces` entries Signed-off-by: Edgar Ramírez Mondragón <[email protected]> * Revert changelog --------- Signed-off-by: Edgar Ramírez Mondragón <[email protected]>
1 parent 3a9d853 commit bb90277

5 files changed

Lines changed: 75 additions & 10 deletions

File tree

‎backend/src/hatchling/metadata/core.py‎

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
from hatchling.metadata.utils import (
1010
format_dependency,
11+
is_valid_import_name,
1112
is_valid_project_name,
1213
normalize_project_name,
1314
normalize_requirement,
@@ -1367,7 +1368,7 @@ def import_names(self) -> list[str] | None:
13671368
raise TypeError(message)
13681369

13691370
for i, import_name in enumerate(import_names, 1):
1370-
if not isinstance(import_name, str) or not self.__import_name_is_valid(import_name):
1371+
if not isinstance(import_name, str) or not is_valid_import_name(import_name):
13711372
message = f"Import name #{i} of field `project.import-names` must be a valid import name"
13721373
raise TypeError(message)
13731374

@@ -1401,7 +1402,7 @@ def import_namespaces(self) -> list[str]:
14011402
raise TypeError(message)
14021403

14031404
for i, import_namespace in enumerate(import_namespaces, 1):
1404-
if not isinstance(import_namespace, str) or not self.__import_name_is_valid(import_namespace):
1405+
if not isinstance(import_namespace, str) or not is_valid_import_name(import_namespace):
14051406
message = f"Import namespace #{i} of field `project.import-namespaces` must be a valid import name"
14061407
raise TypeError(message)
14071408

@@ -1446,10 +1447,6 @@ def validate_fields(self) -> None:
14461447
def __classifier_is_private(classifier: str) -> bool:
14471448
return classifier.lower().startswith("private ::")
14481449

1449-
@staticmethod
1450-
def __import_name_is_valid(import_name: str) -> bool:
1451-
return all(module.isidentifier() for module in import_name.split("."))
1452-
14531450

14541451
class HatchMetadata(Generic[PluginManagerBound]):
14551452
def __init__(self, root: str, config: dict[str, dict[str, Any]], plugin_manager: PluginManagerBound) -> None:

‎backend/src/hatchling/metadata/spec.py‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
from typing import TYPE_CHECKING, Any
44

5+
from hatchling.metadata.utils import split_import_name_annotation
6+
57
if TYPE_CHECKING:
68
from collections.abc import Callable
79

@@ -633,12 +635,14 @@ def construct_metadata_file_2_5(metadata: ProjectMetadata, extra_dependencies: t
633635
metadata_file += "Import-Name\n"
634636

635637
for import_name in metadata.core.import_names:
636-
_name = f"{import_name}; private" if import_name.startswith("_") else import_name
638+
name, private = split_import_name_annotation(import_name)
639+
_name = f"{name}; private" if private or name.startswith("_") else name
637640
metadata_file += f"Import-Name: {_name}\n"
638641

639642
if metadata.core.import_namespaces:
640643
for import_namespace in metadata.core.import_namespaces:
641-
_name = f"{import_namespace}; private" if import_namespace.startswith("_") else import_namespace
644+
name, private = split_import_name_annotation(import_namespace)
645+
_name = f"{name}; private" if private or name.startswith("_") else name
642646
metadata_file += f"Import-Namespace: {_name}\n"
643647

644648
if metadata.core.dynamic:

‎backend/src/hatchling/metadata/utils.py‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,27 @@ def normalize_project_name(project_name: str) -> str:
2121
return re.sub(r"[-_.]+", "-", project_name).lower()
2222

2323

24+
def split_import_name_annotation(import_name: str) -> tuple[str, bool]:
25+
# https://packaging.python.org/en/latest/specifications/pyproject-toml/#import-names
26+
# https://packaging.python.org/en/latest/specifications/pyproject-toml/#import-namespaces
27+
#
28+
# An import name MAY be followed by `; private`, with any amount of whitespace surrounding
29+
# the semicolon. Returns the bare name and whether it was annotated private.
30+
if ";" not in import_name:
31+
return import_name, False
32+
33+
name, annotation = import_name.split(";", 1)
34+
return name.strip(), annotation.strip() == "private"
35+
36+
37+
def is_valid_import_name(import_name: str) -> bool:
38+
name, annotated_private = split_import_name_annotation(import_name)
39+
if ";" in import_name and not annotated_private:
40+
return False
41+
42+
return all(module.isidentifier() for module in name.split("."))
43+
44+
2445
def normalize_requirement(requirement: Requirement) -> None:
2546
# Changes to this function affect reproducibility between versions
2647
from packaging.specifiers import SpecifierSet

‎tests/backend/metadata/test_core.py‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1420,7 +1420,7 @@ def test_not_array(self, isolation):
14201420
with pytest.raises(TypeError, match="Field `project.import-names` must be an array"):
14211421
_ = metadata.core.import_names
14221422

1423-
@pytest.mark.parametrize("entry", [5, "1_foo", "foo.1_bar"])
1423+
@pytest.mark.parametrize("entry", [5, "1_foo", "foo.1_bar", "foo ; not-valid"])
14241424
def test_entry_not_valid_import_name(self, isolation, entry):
14251425
metadata = ProjectMetadata(str(isolation), None, {"project": {"import-names": [entry]}})
14261426

@@ -1434,6 +1434,11 @@ def test_correct(self, isolation):
14341434

14351435
assert metadata.core.import_names == ["_foo", "foo"]
14361436

1437+
def test_private_import_name(self, isolation):
1438+
metadata = ProjectMetadata(str(isolation), None, {"project": {"import-names": ["foo", "_foo ; private"]}})
1439+
1440+
assert metadata.core.import_names == ["_foo ; private", "foo"]
1441+
14371442

14381443
class TestImportNamespaces:
14391444
def test_dynamic(self, isolation):
@@ -1453,7 +1458,7 @@ def test_not_array(self, isolation):
14531458
with pytest.raises(TypeError, match="Field `project.import-namespaces` must be an array"):
14541459
_ = metadata.core.import_namespaces
14551460

1456-
@pytest.mark.parametrize("entry", [5, "1_foo", "foo.1_bar"])
1461+
@pytest.mark.parametrize("entry", [5, "1_foo", "foo.1_bar", "foo.bar ; not-valid"])
14571462
def test_entry_not_valid_import_name(self, isolation, entry):
14581463
metadata = ProjectMetadata(str(isolation), None, {"project": {"import-namespaces": [entry]}})
14591464

@@ -1467,6 +1472,15 @@ def test_correct(self, isolation):
14671472

14681473
assert metadata.core.import_namespaces == ["foo", "foo.bar"]
14691474

1475+
def test_private_import_namespace(self, isolation):
1476+
metadata = ProjectMetadata(
1477+
str(isolation),
1478+
None,
1479+
{"project": {"import-namespaces": ["foo", "foo.bar", "foo.bar ; private"]}},
1480+
)
1481+
1482+
assert metadata.core.import_namespaces == ["foo", "foo.bar", "foo.bar ; private"]
1483+
14701484
def test_import_names_and_import_namespaces_conflict(self, isolation):
14711485
metadata = ProjectMetadata(
14721486
str(isolation),

‎tests/backend/metadata/test_spec.py‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2449,6 +2449,35 @@ def test_import_names_private(self, constructor, isolation, helpers):
24492449
"""
24502450
)
24512451

2452+
def test_import_names_explicit_private_annotation(self, constructor, isolation, helpers):
2453+
metadata = ProjectMetadata(
2454+
str(isolation),
2455+
None,
2456+
{
2457+
"project": {
2458+
"name": "pytest",
2459+
"version": "0.1.0",
2460+
# `_pytest ; private` is already annotated and underscore-prefixed, so it must not
2461+
# be annotated a second time; `pytest; private` is annotated despite not being
2462+
# underscore-prefixed, and must be preserved (in canonical `; private` form) rather
2463+
# than dropped.
2464+
"import-names": ["_pytest ; private", "pytest; private"],
2465+
"description": "pytest: simple powerful testing with Python",
2466+
},
2467+
},
2468+
)
2469+
2470+
assert constructor(metadata) == helpers.dedent(
2471+
"""
2472+
Metadata-Version: 2.5
2473+
Name: pytest
2474+
Version: 0.1.0
2475+
Import-Name: _pytest; private
2476+
Import-Name: pytest; private
2477+
Summary: pytest: simple powerful testing with Python
2478+
"""
2479+
)
2480+
24522481
def test_explicit_no_import_names(self, constructor, isolation, helpers):
24532482
metadata = ProjectMetadata(
24542483
str(isolation),

0 commit comments

Comments
 (0)