From 9f99cd0f04e72faad1f4aa24de9a0a6b4e85abbc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89rico=20Andrei?= Date: Thu, 3 Dec 2026 17:21:02 +0100 Subject: [PATCH] Keep comments in pyproject.toml when updating dependencies The dependencies, constraint-dependencies and classifiers arrays were rebuilt from scratch on every update, which dropped the comments written on their entries. The arrays are now edited in place: a changed entry keeps its line and its trailing comment, removed entries are removed, and new entries are appended. Comments elsewhere in the file are kept because the document is no longer replaced. Refs #91 --- news/91.bugfix | 1 + src/repoplone/utils/dependencies/pyproject.py | 84 +++++++++++++++---- tests/_resources/pyproject/comments.toml | 27 ++++++ .../dependencies/test_utils_pyproject.py | 66 +++++++++++++++ 4 files changed, 160 insertions(+), 18 deletions(-) create mode 100644 news/91.bugfix create mode 100644 tests/_resources/pyproject/comments.toml diff --git a/news/91.bugfix b/news/91.bugfix new file mode 100644 index 0000000..79d1315 --- /dev/null +++ b/news/91.bugfix @@ -0,0 +1 @@ +`repoplone deps constraints`, and `repoplone deps upgrade` for a Python component, keep the comments in `pyproject.toml` on the dependencies, constraints and classifiers they update instead of dropping them. @ericof diff --git a/src/repoplone/utils/dependencies/pyproject.py b/src/repoplone/utils/dependencies/pyproject.py index 9646f79..4bc6cfc 100644 --- a/src/repoplone/utils/dependencies/pyproject.py +++ b/src/repoplone/utils/dependencies/pyproject.py @@ -1,4 +1,6 @@ +from collections.abc import Callable from packaging.requirements import Requirement +from packaging.utils import canonicalize_name from pathlib import Path from repoplone import _types as t from repoplone.utils._requests import get_remote_data @@ -225,29 +227,73 @@ def _update_dependency(data: tomlkit.TOMLDocument, package: str, version: str) - # Removing a non-existent source is a no-op, so this is always safe. _uv_remove_source_package(data, package) project = _get_project_table(data) - deps = tomlkit.array() - deps.multiline(True) - project_dependencies = _get_project_dependencies(data) - for dep_name in project_dependencies: - if dep_name == package: - dep = package if from_branch else f"{package}=={version}" + dependencies = project.get("dependencies") + if dependencies is None: + dependencies = tomlkit.array() + dependencies.multiline(True) + project["dependencies"] = dependencies + dep = package if from_branch else f"{package}=={version}" + # Edit the entry in place so its line keeps its trailing comment. + for index, current in enumerate(list(dependencies)): + if Requirement(str(current)).name == package: + dependencies[index] = dep + + +def _constraint_key(line: str) -> str: + """Return the canonical package name of a constraint specifier.""" + return canonicalize_name(Requirement(line).name) + + +def _sync_array( + array: items.Array, desired: list[str], key_of: Callable[[str], str] +) -> None: + """Make an existing array hold the desired entries, editing it in place. + + An entry whose key matches a desired entry keeps its position and its + comments; its value is replaced when it differs. Entries without a desired + match are removed, and desired entries missing from the array are appended. + + :param array: Array to update in place. + :param desired: Entries the array must hold. + :param key_of: Function returning the identity of an entry. + """ + pending: dict[str, list[str]] = {} + for value in dict.fromkeys(desired): + pending.setdefault(key_of(value), []).append(value) + to_remove: list[int] = [] + for index, current in enumerate(list(array)): + candidates = pending.get(key_of(str(current))) + if not candidates: + to_remove.append(index) + elif str(current) in candidates: + candidates.remove(str(current)) else: - # Keep dependency as stated before - dep = str(project_dependencies[dep_name]) - deps.append(dep) - project.update({"dependencies": deps}) + array[index] = candidates.pop(0) + for index in reversed(to_remove): + del array[index] + for values in pending.values(): + for value in values: + array.append(value) def _update_constraints(data: tomlkit.TOMLDocument, raw_constraints: list[str]) -> None: """Write resolved constraints into ``[tool.uv] constraint-dependencies``. + An existing array is edited in place: changed entries keep their line and + comments, removed entries are dropped and new ones are appended. A missing + array is created sorted. + :param data: Parsed ``pyproject.toml`` document to mutate. - :param raw_constraints: Constraint specifiers to write (sorted on output). + :param raw_constraints: Constraint specifiers to write. """ tool_uv = _ensure_uv_table(data) - # We should sort items here to maintain consistency - constraints = multiline_array_from_iter(raw_constraints, True, True) - tool_uv.update({"constraint-dependencies": constraints}) + existing = tool_uv.get("constraint-dependencies") + if existing is None: + tool_uv["constraint-dependencies"] = multiline_array_from_iter( + raw_constraints, True, True + ) + return + _sync_array(existing, raw_constraints, _constraint_key) def _add_versions_to_classifiers( @@ -306,10 +352,12 @@ def _update_classifiers( # Add updated Plone version classifiers _add_versions_to_classifiers(classifiers, "Framework :: Plone ::", plone_versions) - # Sorting and deduplicating - new_classifiers = multiline_array_from_iter(classifiers, True, True) - # Update project classifiers - project.update({"classifiers": new_classifiers}) + existing = project.get("classifiers") + if existing is None: + project["classifiers"] = multiline_array_from_iter(classifiers, True, True) + return + # Edit the existing array so comments on the classifiers that stay survive + _sync_array(existing, sorted(classifiers), str) def _parse_pyproject(src: str) -> tomlkit.TOMLDocument: diff --git a/tests/_resources/pyproject/comments.toml b/tests/_resources/pyproject/comments.toml new file mode 100644 index 0000000..4436a80 --- /dev/null +++ b/tests/_resources/pyproject/comments.toml @@ -0,0 +1,27 @@ +# Header comment: this file is maintained by the team. + +[build-system] +requires = ["setuptools>=70"] # build backend + +[project] +name = "demo" +version = "0.0.0" +dependencies = [ + "Products.CMFPlone==6.1.0", # pinned for the site + # keep the add-on on the same release line + "plone.api>=2.0", +] +classifiers = [ + "Framework :: Plone :: 6.0", + # the Python versions the tests cover + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Development Status :: 4 - Beta", # kept by hand +] + +[tool.uv] +constraint-dependencies = [ + "Zope==5.9", # pinned by the Plone release + # separator + "plone.restapi==9.0.0", +] diff --git a/tests/utils/dependencies/test_utils_pyproject.py b/tests/utils/dependencies/test_utils_pyproject.py index fd7b214..115d503 100644 --- a/tests/utils/dependencies/test_utils_pyproject.py +++ b/tests/utils/dependencies/test_utils_pyproject.py @@ -431,3 +431,69 @@ def test_update_pyproject_without_versions(pyproject_path): constraints = list(data["tool"]["uv"]["constraint-dependencies"]) assert "Zope==5.10" in constraints assert pyproject_utils.python_versions(data) == before + + +@pytest.fixture +def commented_pyproject(get_resource_file, tmp_path) -> Path: + """Copy of a pyproject.toml whose comments must survive an update.""" + pyproject = tmp_path / "pyproject.toml" + pyproject.write_text(get_resource_file("pyproject/comments.toml").read_text()) + return pyproject + + +def test_update_pyproject_keeps_inline_comment_on_changed_dependency( + commented_pyproject, +): + """The changed pin keeps its line and its trailing comment.""" + pyproject_utils.update_pyproject( + commented_pyproject, "Products.CMFPlone", "6.1.1", ["Zope==5.9"] + ) + text = commented_pyproject.read_text() + assert ' "Products.CMFPlone==6.1.1", # pinned for the site\n' in text + assert "6.1.0" not in text + + +def test_update_pyproject_keeps_whole_line_comments_in_constraints( + commented_pyproject, +): + """Constraints are edited in place: changed kept, removed dropped, new appended.""" + pyproject_utils.update_pyproject( + commented_pyproject, + "Products.CMFPlone", + "6.1.0", + ["Zope==5.10", "plone.volto==1.0.0"], + ) + text = commented_pyproject.read_text() + assert ' "Zope==5.10", # pinned by the Plone release\n' in text + assert " # separator\n" in text + data = pyproject_utils.parse_pyproject(commented_pyproject) + constraints = list(data["tool"]["uv"]["constraint-dependencies"]) + assert constraints == ["Zope==5.10", "plone.volto==1.0.0"] + + +def test_update_pyproject_keeps_comments_in_classifiers(commented_pyproject): + """Comments on classifiers that stay survive a classifier refresh.""" + pyproject_utils.update_pyproject( + commented_pyproject, + "Products.CMFPlone", + "6.1.0", + ["Zope==5.9"], + python_versions=["3.12", "3.13"], + plone_versions=["6.1"], + ) + text = commented_pyproject.read_text() + assert " # the Python versions the tests cover\n" in text + assert ' "Development Status :: 4 - Beta", # kept by hand\n' in text + assert "Framework :: Plone :: 6.0" not in text + assert "Framework :: Plone :: 6.1" in text + + +def test_update_pyproject_keeps_comments_outside_arrays(commented_pyproject): + """Comments before tables and after array entries are not dropped.""" + pyproject_utils.update_pyproject( + commented_pyproject, "Products.CMFPlone", "6.1.1", ["Zope==5.9"] + ) + text = commented_pyproject.read_text() + assert text.startswith("# Header comment: this file is maintained by the team.\n") + assert 'requires = ["setuptools>=70"] # build backend\n' in text + assert " # keep the add-on on the same release line\n" in text