Skip to content

Commit afc7206

Browse files
committed
use build for dist name
1 parent f0c0b17 commit afc7206

File tree

3 files changed

+23
-118
lines changed

3 files changed

+23
-118
lines changed

.generator/cli.py

Lines changed: 14 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,9 @@
2525
import yaml
2626
from datetime import datetime
2727
from pathlib import Path
28-
from typing import Dict, List, Optional
29-
from distutils.core import run_setup
28+
from typing import Dict, List
3029

31-
import tomli
30+
import build.util
3231

3332
try:
3433
import synthtool
@@ -549,59 +548,22 @@ def _verify_library_namespace(library_id: str, repo: str):
549548
)
550549

551550

552-
def _get_setup_dist_name(library_id: str, repo: str) -> Optional[str]:
553-
"""Gets the library distribution name from a `setup.py` file.
554-
555-
Tries to execute `run_setup` on the file and extract the 'name'
556-
property. Logs and returns None on any exception.
557-
558-
Args:
559-
library_id(str): id of the library.
560-
repo(str): This directory will contain all directories that make up a
561-
library, the .librarian folder, and any global file declared in
562-
the config.yaml.
563-
564-
Returns:
565-
Optional[str]: The library distribution name if found and parsed, otherwise None.
551+
def _get_library_dist_name(library_id: str, repo: str) -> str:
566552
"""
567-
try:
568-
dist = run_setup(f"{repo}/packages/{library_id}/setup.py")
569-
return dist.get_name()
570-
except Exception as e:
571-
logger.debug(
572-
f"failed to get distribution name for `{library_id}` from `setup.py` : {e}",
573-
exc_info=True,
574-
)
575-
return None
576-
577-
578-
def _get_toml_dist_name(library_id: str, repo: str) -> Optional[str]:
579-
"""Gets the library distribution name from a `pyproject.toml` file.
580-
581-
Parses the TOML file and safely accesses the name from the
582-
[project] table using `.get()`. Logs and returns None on any
583-
exception (e.g., FileNotFoundError, TOMLDecodeError).
553+
Gets the package name by programmatically building the metadata.
584554
585555
Args:
586-
library_id(str): id of the library.
587-
repo(str): This directory will contain all directories that make up a
556+
library_id: id of the library.
557+
repo: This directory will contain all directories that make up a
588558
library, the .librarian folder, and any global file declared in
589559
the config.yaml.
590560
591561
Returns:
592-
Optional[str]: The library distribution name if found and parsed, otherwise None.
562+
str: The library name string if found, otherwise None.
593563
"""
594-
try:
595-
pyproject_toml_file = Path(f"{repo}/packages/{library_id}/pyproject.toml")
596-
with open(pyproject_toml_file, "rb") as f:
597-
data = tomli.load(f)
598-
return data.get("project", {}).get("name")
599-
except Exception as e:
600-
logger.debug(
601-
f"failed to get distribution name for `{library_id}` from `pyproject.toml` : {e}",
602-
exc_info=True,
603-
)
604-
return None
564+
library_path = f"{repo}/packages/{library_id}"
565+
metadata = build.util.project_wheel_metadata(library_path)
566+
return metadata.get("name")
605567

606568

607569
def _verify_library_dist_name(library_id: str, repo: str):
@@ -618,22 +580,12 @@ def _verify_library_dist_name(library_id: str, repo: str):
618580
the config.yaml.
619581
620582
Raises:
621-
ValueError: If no valid config file is found, or if a name
622-
in an existing file does not match the `library_id`.
583+
ValueError: If a name in an existing config file does not match the `library_id`.
623584
"""
624-
setup_dist_name = _get_setup_dist_name(library_id, repo)
625-
toml_dist_name = _get_toml_dist_name(library_id, repo)
626-
if setup_dist_name is None and toml_dist_name is None:
627-
raise ValueError(
628-
f"No valid `setup.py` or `pyproject.toml found for `{library_id}`."
629-
)
630-
if setup_dist_name is not None and setup_dist_name != library_id:
631-
raise ValueError(
632-
f"The distribution name `{setup_dist_name} in `setup.py` does not match folder `{library_id}`"
633-
)
634-
if toml_dist_name is not None and toml_dist_name != library_id:
585+
dist_name = _get_library_dist_name(library_id, repo)
586+
if dist_name != library_id:
635587
raise ValueError(
636-
f"The distribution name `{toml_dist_name} in `pyproject.toml` does not match folder `{library_id}`"
588+
f"The distribution name `{dist_name}` does not match the folder `{library_id}`."
637589
)
638590

639591

.generator/requirements-test.in

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,5 +17,3 @@ pytest-cov
1717
pytest-mock
1818
gcp-synthtool @ git+https://github.com/googleapis/synthtool@5aa438a342707842d11fbbb302c6277fbf9e4655
1919
starlark-pyo3>=2025.1
20-
# TODO(https://github.com/googleapis/google-cloud-python/issues/14443): tomli is part of the standard library for Python 3.11. Remove once we use 3.11+ for librarian.
21-
tomli

.generator/test_cli.py

Lines changed: 9 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -37,12 +37,11 @@
3737
_copy_files_needed_for_post_processing,
3838
_create_main_version_header,
3939
_determine_bazel_rule,
40+
_get_library_dist_name,
4041
_determine_library_namespace,
4142
_get_library_id,
4243
_get_libraries_to_prepare_for_release,
4344
_get_previous_version,
44-
_get_setup_dist_name,
45-
_get_toml_dist_name,
4645
_locate_and_extract_artifact,
4746
_process_changelog,
4847
_process_version_file,
@@ -926,66 +925,22 @@ def test_determine_library_namespace_fails_not_subpath():
926925
_determine_library_namespace(gapic_parent_path, pkg_root_path)
927926

928927

929-
def test_get_setup_dist_name_exists(mocker):
930-
"""Tests that a valid library distribution name exists in `pyproject.toml`."""
931-
mock_dist = MagicMock()
932-
mock_dist.get_name.return_value = "my-lib"
933-
mocker.patch("cli.run_setup", return_value=mock_dist)
934-
assert _get_setup_dist_name("my-lib", "repo") == "my-lib"
935-
936-
937-
def test_get_setup_dist_name_file_not_found(caplog):
938-
"""Tests that distribution name is None if `setup.py` does not exist."""
939-
caplog.set_level(logging.DEBUG)
940-
assert _get_setup_dist_name("my-lib", "repo") is None
941-
assert len(caplog.records) == 1
942-
943-
944-
def test_get_toml_dist_name_exists(mocker):
945-
"""Tests that a valid library distribution name exists in `pyproject.toml`."""
946-
mock_data = {"project": {"name": "my-lib"}}
947-
mocker.patch("tomli.load", return_value=mock_data)
948-
mocker.patch("builtins.open", mocker.mock_open(read_data=b"fake toml data"))
949-
assert _get_toml_dist_name("my-lib", "repo") == "my-lib"
950-
951-
952-
def test_get_toml_dist_name_file_not_found(caplog):
953-
"""Tests that distribution name is None if `pyproject.toml` does not exist."""
954-
caplog.set_level(logging.DEBUG)
955-
assert _get_toml_dist_name("my-lib", "repo") is None
956-
assert len(caplog.records) == 1
928+
def test_get_library_dist_name_success(mocker):
929+
mock_metadata = {"name": "my-lib", "version": "1.0.0"}
930+
mocker.patch("build.util.project_wheel_metadata", return_value=mock_metadata)
931+
assert _get_library_dist_name("my-lib", "repo") == "my-lib"
957932

958933

959934
def test_verify_library_dist_name_setup_success(mocker):
960935
"""Tests success when a library distribution name in setup.py is valid."""
961-
mock_setup_file = mocker.patch("cli._get_setup_dist_name", return_value="my-lib")
936+
mock_setup_file = mocker.patch("cli._get_library_dist_name", return_value="my-lib")
962937
_verify_library_dist_name("my-lib", "repo")
963938
mock_setup_file.assert_called_once_with("my-lib", "repo")
964939

965940

966-
def test_verify_library_dist_name_setup_success(mocker):
967-
"""Tests success when a library distribution name in toml is valid."""
968-
mock_toml_file = mocker.patch("cli._get_toml_dist_name", return_value="my-lib")
969-
_verify_library_dist_name("my-lib", "repo")
970-
mock_toml_file.assert_called_once_with("my-lib", "repo")
971-
972-
973-
def test_verify_library_dist_name_fail():
974-
"""Tests failure when a library does not have a `setup.py` or `pyproject.toml`."""
975-
with pytest.raises(ValueError):
976-
_verify_library_dist_name("my-lib", "repo")
977-
978-
979-
def test_verify_library_dist_name_setup_fail(mocker):
980-
"""Tests failure when a library has an invalid distribution name in `setup.py`."""
981-
mocker.patch("cli._get_setup_dist_name", return_value="invalid-lib-name")
982-
with pytest.raises(ValueError):
983-
_verify_library_dist_name("my-lib", "repo")
984-
985-
986-
def test_verify_library_dist_name_toml_fail(mocker):
987-
"""Tests failure when a library has an invalid distribution name in `pyproject.toml`."""
988-
mocker.patch("cli._get_toml_dist_name", return_value="invalid-lib-name")
941+
def test_verify_library_dist_name_fail(mocker):
942+
"""Tests failure when a library-id does not match the libary distribution name."""
943+
mocker.patch("cli._get_library_dist_name", return_value="invalid-lib")
989944
with pytest.raises(ValueError):
990945
_verify_library_dist_name("my-lib", "repo")
991946

0 commit comments

Comments
 (0)