diff --git a/tests/unit/python/utils/update/test_docker_compose.py b/tests/unit/python/utils/update/test_docker_compose.py index f695387ffa..34350a5fe3 100644 --- a/tests/unit/python/utils/update/test_docker_compose.py +++ b/tests/unit/python/utils/update/test_docker_compose.py @@ -425,6 +425,31 @@ class TestComposeBump(unittest.TestCase): original.replace(old, f"rpardini/docker-registry-proxy:{newest}"), ) + def test_a_service_aliasing_an_anchor_outside_the_services_leaves_it_alone(self): + aliased = ( + "x-base: &base\n" + " image: redis:7.4.1\n" + "services:\n" + " direct: *base\n" + " inherited:\n" + " <<: *base\n" + " local: &local\n" + " image: nginx:1.27-alpine\n" + " copy: *local\n" + ) + rel = "ops/aliased.yml" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + _write(root / rel, aliased) + changed = _bump(root, [rel], TAGS) + _reset_cache_for_tests() + after = read_text(str(root / rel)) + + self.assertEqual(changed, [root / rel]) + self.assertEqual( + after, aliased.replace("nginx:1.27-alpine", "nginx:1.29-alpine") + ) + def test_quoted_and_commented_tags_keep_their_quotes_and_comments(self): with tempfile.TemporaryDirectory() as tmp: path = Path(tmp) / "cache.override.yml" diff --git a/utils/update/docker/compose.py b/utils/update/docker/compose.py index b7df512173..d94eb14e88 100644 --- a/utils/update/docker/compose.py +++ b/utils/update/docker/compose.py @@ -89,6 +89,18 @@ def compose_files(repo_root: Path, tracked: Iterable[str]) -> list[str]: return sorted(owned) +def _defined_in_place(key: yaml.Node, value: yaml.Node) -> bool: + """Args: + key: a mapping key node. + value: the node composed for that key. + + Returns: + Whether *value* is written after *key* rather than being an alias, + which composes to the anchored node with that node's source marks. + """ + return value.start_mark.index >= key.end_mark.index + + def _compose_image_lines(raw: str) -> dict[str, int]: """Args: raw: text of a compose file. @@ -96,7 +108,9 @@ def _compose_image_lines(raw: str) -> dict[str, int]: Returns: Each compose service mapped to the 0-indexed line of its ``image`` key, for the keys whose tagged value sits on that line in the one - form ``_IMAGE_VALUE_RE`` rewrites. + form ``_IMAGE_VALUE_RE`` rewrites. A service that aliases a mapping + anchored elsewhere is left out: its line belongs to the anchor, and + rewriting it would move every service merging that anchor as well. """ text_lines = raw.splitlines() root = yaml.compose(raw) @@ -110,7 +124,9 @@ def _compose_image_lines(raw: str) -> dict[str, int]: ) lines: dict[str, int] = {} for service, spec in services.value if services else []: - if not isinstance(spec, yaml.MappingNode): + if not isinstance(spec, yaml.MappingNode) or not _defined_in_place( + service, spec + ): continue for field, value in spec.value: line = field.start_mark.line