From 5151b36250f8bdbb2c4a06a26c8f1fdffed41f8e Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 25 Nov 2026 16:23:54 +0000 Subject: [PATCH] fix(release): bump a setuptools dynamic attr version in its module MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit pkgmgr release skipped pyproject.toml when [project].dynamic lists version and [tool.setuptools.dynamic] reads it from a module attribute, so a tag could move to X.Y.Z while the wheel kept the old version. read_pyproject_version and update_pyproject_version now resolve the attr module through [tool.setuptools].package-dir and read or rewrite its version literal; a module without that literal aborts the release before any file is written. 🎯 Fix: 95 % 💥 Break: 3 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 92 🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 % Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 --- src/pkgmgr/actions/release/files/pyproject.py | 37 +++++++++- src/pkgmgr/core/version/source.py | 59 +++++++++++++++- .../unit/pkgmgr/actions/release/test_files.py | 69 +++++++++++++++++++ 3 files changed, 162 insertions(+), 3 deletions(-) diff --git a/src/pkgmgr/actions/release/files/pyproject.py b/src/pkgmgr/actions/release/files/pyproject.py index 0a88938..bffb212 100644 --- a/src/pkgmgr/actions/release/files/pyproject.py +++ b/src/pkgmgr/actions/release/files/pyproject.py @@ -8,6 +8,36 @@ try: except ImportError: import tomli as tomllib # type: ignore +from pkgmgr.core.version.source import dynamic_version_source, version_literal + + +def update_module_version( + path: str, name: str, new_version: str, preview: bool +) -> None: + """ + Args: + path: the module file that holds the version literal. + name: the attribute assigned the version, e.g. __version__. + new_version: the version to write. + preview: print the change instead of writing it. + + Raises: + RuntimeError: the file holds no `name = "..."` literal. + """ + with open(path, encoding="utf-8") as f: + content = f.read() + new_content, count = version_literal(name).subn( + lambda mm: f"{mm.group(1)}{new_version}{mm.group(3)}", content, count=1 + ) + if count == 0: + raise RuntimeError(f"Missing {name} literal in {path}") + if preview: + print(f"[PREVIEW] Would update {name} in {path} to {new_version}") + return + with open(path, "w", encoding="utf-8") as f: + f.write(new_content) + print(f"Updated {name} in {path} to {new_version}") + def update_pyproject_version( pyproject_path: str, new_version: str, preview: bool = False @@ -23,7 +53,12 @@ def update_pyproject_version( print(f"[WARN] Could not read pyproject.toml: {exc}") return - project = tomllib.loads(content).get("project") + data = tomllib.loads(content) + project = data.get("project") + source = dynamic_version_source(pyproject_path, data) + if source is not None: + update_module_version(*source, new_version, preview) + return if project is None or "version" in project.get("dynamic", []): print("[INFO] pyproject.toml declares no static version, skipping.") return diff --git a/src/pkgmgr/core/version/source.py b/src/pkgmgr/core/version/source.py index dbf0a1b..bd35391 100644 --- a/src/pkgmgr/core/version/source.py +++ b/src/pkgmgr/core/version/source.py @@ -9,11 +9,59 @@ import yaml from pkgmgr.core.repository.paths import resolve_repo_paths +def version_literal(name: str) -> re.Pattern[str]: + """ + Args: + name: the module attribute holding the version, e.g. __version__. + + Returns: + A pattern whose groups are the assignment up to the opening quote, the + version and the closing quote of `name = "X.Y.Z"`. + """ + return re.compile(rf"""(?m)^(\s*{re.escape(name)}\s*=\s*["'])([^"']+)(["'])""") + + +def dynamic_version_source(pyproject_path: str, data: dict) -> tuple[str, str] | None: + """ + Args: + pyproject_path: the pyproject.toml file. + data: its parsed content. + + Returns: + (module file, attribute name) that setuptools reads the version from + when [project].dynamic lists version and [tool.setuptools.dynamic] + sets version = {attr = "pkg.module.NAME"}, with + [tool.setuptools].package-dir applied; None otherwise. + """ + project = data.get("project") or {} + if "version" not in project.get("dynamic", []): + return None + setuptools = (data.get("tool") or {}).get("setuptools") or {} + attr = ((setuptools.get("dynamic") or {}).get("version") or {}).get("attr") + if not isinstance(attr, str) or "." not in attr: + return None + module, _, name = attr.rpartition(".") + parts = module.split(".") + dirs = setuptools.get("package-dir") or {} + if parts[0] in dirs: + base = os.path.join(dirs[parts[0]], *parts[1:]) + else: + base = os.path.join(dirs.get("", ""), *parts) + root = os.path.dirname(os.path.abspath(pyproject_path)) + for candidate in (f"{base}.py", os.path.join(base, "__init__.py")): + path = os.path.join(root, candidate) + if os.path.isfile(path): + return path, name + return None + + def read_pyproject_version(repo_dir: str) -> str | None: """ Read the version from pyproject.toml in repo_dir, if present. - Expects a PEP 621-style [project] table with a 'version' field. + Expects a PEP 621-style [project] table with a 'version' field, or a + dynamic version that setuptools reads from a module attribute + (dynamic_version_source()). """ paths = resolve_repo_paths(repo_dir) path = paths.pyproject_toml @@ -30,7 +78,14 @@ def read_pyproject_version(repo_dir: str) -> str | None: data = tomllib.load(f) project = data.get("project") or {} version = project.get("version") - return str(version).strip() if version else None + if version: + return str(version).strip() + source = dynamic_version_source(path, data) + if source is None: + return None + with open(source[0], encoding="utf-8") as f: + match = version_literal(source[1]).search(f.read()) + return match.group(2).strip() if match else None except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError): return None diff --git a/tests/unit/pkgmgr/actions/release/test_files.py b/tests/unit/pkgmgr/actions/release/test_files.py index 5410b4c..4c63a7d 100644 --- a/tests/unit/pkgmgr/actions/release/test_files.py +++ b/tests/unit/pkgmgr/actions/release/test_files.py @@ -140,6 +140,75 @@ class TestUpdatePyprojectVersion(unittest.TestCase): self.assertEqual(content, original) + def write_dynamic_attr_project(self, tmpdir: str, module: str) -> str: + with open(os.path.join(tmpdir, "pyproject.toml"), "w", encoding="utf-8") as f: + f.write( + textwrap.dedent( + """ + [project] + name = "quality" + dynamic = ["version"] + + [tool.setuptools] + package-dir = {"" = "src"} + + [tool.setuptools.dynamic] + version = {attr = "quality.__version__"} + """ + ).lstrip() + ) + os.makedirs(os.path.join(tmpdir, "src", "quality")) + path = os.path.join(tmpdir, "src", "quality", "__init__.py") + with open(path, "w", encoding="utf-8") as f: + f.write(module) + return path + + def test_a_dynamic_attr_version_is_bumped_in_its_module_and_read_back(self) -> None: + from pkgmgr.core.version.source import read_pyproject_version + + with tempfile.TemporaryDirectory() as tmpdir: + module = self.write_dynamic_attr_project( + tmpdir, '"""Quality."""\n\n__version__ = "0.1.0"\n' + ) + with open(os.path.join(tmpdir, "pyproject.toml"), encoding="utf-8") as f: + before = f.read() + self.assertEqual(read_pyproject_version(tmpdir), "0.1.0") + + update_pyproject_version( + os.path.join(tmpdir, "pyproject.toml"), "0.2.0", preview=False + ) + + with open(module, encoding="utf-8") as f: + self.assertEqual(f.read(), '"""Quality."""\n\n__version__ = "0.2.0"\n') + with open(os.path.join(tmpdir, "pyproject.toml"), encoding="utf-8") as f: + self.assertEqual(f.read(), before) + self.assertEqual(read_pyproject_version(tmpdir), "0.2.0") + + def test_a_dynamic_attr_version_preview_writes_nothing(self) -> None: + with tempfile.TemporaryDirectory() as tmpdir: + module = self.write_dynamic_attr_project(tmpdir, "__version__ = '0.1.0'\n") + + update_pyproject_version( + os.path.join(tmpdir, "pyproject.toml"), "0.2.0", preview=True + ) + + with open(module, encoding="utf-8") as f: + self.assertEqual(f.read(), "__version__ = '0.1.0'\n") + + def test_a_dynamic_attr_module_without_the_literal_raises(self) -> None: + with tempfile.TemporaryDirectory() as tmpdir: + self.write_dynamic_attr_project( + tmpdir, + "from importlib.metadata import version\n__version__ = version('quality')\n", + ) + + with self.assertRaises(RuntimeError) as cm: + update_pyproject_version( + os.path.join(tmpdir, "pyproject.toml"), "0.2.0", preview=False + ) + + self.assertIn("Missing __version__ literal", str(cm.exception)) + def test_update_pyproject_version_missing_file_is_skipped(self) -> None: with tempfile.TemporaryDirectory() as tmpdir: path = os.path.join(tmpdir, "pyproject.toml")