From d6e95aafae5a1a3da84bcb78d2f1a4623306ace1 Mon Sep 17 00:00:00 2001 From: Emerson Knapp Date: Mon, 23 Nov 2026 15:36:31 -0800 Subject: [PATCH] feat: format package.xml dependencies into sorted blocks by tag Signed-off-by: Emerson Knapp --- CHANGELOG.md | 11 + README.md | 27 +- .../checkers/xml/__init__.py | 27 +- polymath_code_standard/package_xml_format.py | 255 +++++++++++++++++ pyproject.toml | 2 +- test_files/package.xml | 5 + tests/test_package_xml_format.py | 265 ++++++++++++++++++ uv.lock | 2 +- 8 files changed, 588 insertions(+), 6 deletions(-) create mode 100644 polymath_code_standard/package_xml_format.py create mode 100644 tests/test_package_xml_format.py diff --git a/CHANGELOG.md b/CHANGELOG.md index b99bcf9..1748892 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,17 @@ All notable changes to this project are documented in this file. Releases follow semantic versioning as described in [DEVELOPING.md](./DEVELOPING.md). +## 2.8.0 + +Minor bump: a new formatter in `polymath-xml`. + +### Added + +- `polymath-xml` formats the dependencies of ROS `package.xml` files. + It groups them by tag into blank-line separated blocks in lifecycle order, and sorts each block by package name. + A comment heads a section that stays together within its tag. + A repository with unsorted dependencies gets them rewritten under `--all-files`. + ## 2.7.1 ### Fixed diff --git a/README.md b/README.md index c184ed1..cecff79 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,7 @@ Use only the hooks that apply to your project. --- repos: - repo: https://github.com/polymathrobotics/polymath_code_standard - rev: v2.7.1 + rev: v2.8.0 hooks: # File hygiene for all staged files - id: polymath-general @@ -294,6 +294,31 @@ Validates XML well-formedness and schema compliance. Supports `xml-model` processing instructions and `xsi:noNamespaceSchemaLocation`. Includes a bundled `package_format3.xsd` schema for ROS `package.xml` validation. +Formats the dependencies of format 2 and 3 ROS `package.xml` files. +Each dependency tag gets its own block, separated by blank lines, in this order: +`buildtool_depend`, `buildtool_export_depend`, `build_depend`, `build_export_depend`, `depend`, `exec_depend`, `test_depend`, `doc_depend`. +Each block is sorted by package name. + +A comment between dependencies heads a section. +The section holds the dependencies that follow the comment, up to the next blank line or comment. +The section stays together, sorted, after the uncommented block of its tag. +A comment that applies to a single dependency needs a blank line after that dependency. +A comment at the end of a dependency's line moves with that dependency. + +```xml +ament_cmake + +rclcpp +sensor_msgs + +polymath_launch + + +ros2cli_common_extensions + +ament_cmake_pytest +``` + No arguments. --- diff --git a/polymath_code_standard/checkers/xml/__init__.py b/polymath_code_standard/checkers/xml/__init__.py index ada3314..9214a3d 100644 --- a/polymath_code_standard/checkers/xml/__init__.py +++ b/polymath_code_standard/checkers/xml/__init__.py @@ -3,10 +3,12 @@ import argparse import functools import importlib.resources +from pathlib import Path from lxml import etree from polymath_code_standard.checker import CheckerGroup, Result, check_group +from polymath_code_standard.package_xml_format import format_package_xml_files # Config files bundled alongside this checker CONFIG_DIR = importlib.resources.files(__package__) @@ -68,13 +70,32 @@ def run(self, args: argparse.Namespace) -> list[Result]: return [Result(name='xml-validate', passed=True, skipped=True)] all_errors = [] + valid = [] for f in args.files: - for msg in _validate_xml(f): - all_errors.append(f'{f}: {msg}') + errors = _validate_xml(f) + all_errors.extend(f'{f}: {msg}' for msg in errors) + if not errors: + valid.append(f) return [ Result( name='xml-validate', passed=not all_errors, output='\n'.join(all_errors), - ) + ), + _format_package_xmls([f for f in valid if Path(f).name == 'package.xml']), ] + + +def _format_package_xmls(files: list[str]) -> Result: + if not files: + return Result(name='package-xml-format', passed=True, skipped=True) + errors, changed = [], [] + for filepath, was_changed, error in format_package_xml_files(files): + if error: + errors.append(f'{filepath}: {error}') + elif was_changed: + changed.append(f' {filepath}') + output = errors + if changed: + output += ['Files reformatted — please re-stage and recommit:', *changed] + return Result(name='package-xml-format', passed=not output, output='\n'.join(output)) diff --git a/polymath_code_standard/package_xml_format.py b/polymath_code_standard/package_xml_format.py new file mode 100644 index 0000000..2449f3f --- /dev/null +++ b/polymath_code_standard/package_xml_format.py @@ -0,0 +1,255 @@ +# SPDX-FileCopyrightText: 2026 Polymath Robotics, Inc. +# SPDX-License-Identifier: Apache-2.0 +"""Formatter for the dependency list of a ROS package.xml. + +Dependencies are grouped into blank-line separated blocks, one per tag, in DEPEND_ORDER. +Each block is sorted by package name. + +A comment between dependencies heads a section. +The section holds the dependencies that follow the comment, up to the next blank line or comment. +It stays together, sorted, after the uncommented block of its tag. +All dependencies in a section must share one tag. + +A comment that holds a single dependency element, such as a commented-out dependency, +sorts as that dependency. + +Everything outside the dependency list is left untouched. +Files whose root is not a format 2 or 3 are returned unchanged. + +Raises ValueError if the dependency list cannot be rewritten line by line, +for example when a dependency shares a line with another element. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass, field +from pathlib import Path + +from lxml import etree + +DEPEND_ORDER = ( + 'buildtool_depend', + 'buildtool_export_depend', + 'build_depend', + 'build_export_depend', + 'depend', + 'exec_depend', + 'test_depend', + 'doc_depend', +) + +_COMMENTED_DEPEND = re.compile( + r'\s*<(?P' + '|'.join(DEPEND_ORDER) + r')\b(?P[^>]*)>\s*(?P[^<\s]+)\s*\s*', +) +_CONDITION = re.compile(r'\bcondition\s*=\s*(["\'])(.*?)\1') + + +@dataclass +class _Depend: + tag: str + name: str + condition: str + lines: list[str] + + def sort_key(self) -> tuple[str, str, str]: + return (self.name, self.condition, '\n'.join(self.lines)) + + +@dataclass +class _Section: + comment: list[str] + depends: list[_Depend] = field(default_factory=list) + + +@dataclass +class _Unit: + """One or more whole source lines holding a dependency, a comment, or a dependency with a trailing comment.""" + + first: int + last: int + node: etree._Element + tail: str + + +def _span(node: etree._Element) -> tuple[int, int]: + """Return the 0-based first and last source line of a direct child of the root.""" + text = node.text or '' + if isinstance(node, etree._Comment): + # libxml2 records the line a comment ends on. + return node.sourceline - 1 - text.count('\n'), node.sourceline - 1 + if '\n' in text or len(node): + raise ValueError(f'line {node.sourceline}: <{node.tag}> must fit on one line') + return node.sourceline - 1, node.sourceline - 1 + + +def _is_depend(node: etree._Element) -> bool: + return not isinstance(node, etree._Comment) and node.tag in DEPEND_ORDER + + +def _depend_region(root: etree._Element) -> list[etree._Element]: + """Return the root children from the comments before the first dependency through the last dependency.""" + children = list(root) + indices = [i for i, child in enumerate(children) if _is_depend(child)] + if not indices: + return [] + start, end = indices[0], indices[-1] + while start > 0 and isinstance(children[start - 1], etree._Comment): + start -= 1 + # A comment on the line where the preceding element ends belongs to that element. + while start < indices[0] and '\n' not in _preceding_text(root, children, start): + start += 1 + region = children[start : end + 1] + for node in region: + if not isinstance(node, etree._Comment) and not _is_depend(node): + raise ValueError(f'line {node.sourceline}: <{node.tag}> sits between dependencies') + # A comment trailing the last dependency on its line belongs to it. + while ( + end + 1 < len(children) + and isinstance(children[end + 1], etree._Comment) + and '\n' not in (children[end].tail or '') + ): + end += 1 + region.append(children[end]) + return region + + +def _preceding_text(root: etree._Element, children: list[etree._Element], index: int) -> str: + return (children[index - 1].tail if index else root.text) or '' + + +def _units(root: etree._Element, region: list[etree._Element]) -> list[_Unit]: + children = list(root) + first_index = children.index(region[0]) + if '\n' not in _preceding_text(root, children, first_index): + raise ValueError(f'line {region[0].sourceline}: the first dependency must start its own line') + units: list[_Unit] = [] + for node in region: + first, last = _span(node) + prev = units[-1] if units else None + if prev is not None and '\n' not in prev.tail: + if not isinstance(node, etree._Comment): + raise ValueError(f'line {node.sourceline}: each dependency must be on its own line') + prev.last = last + prev.tail = node.tail or '' + continue + units.append(_Unit(first, last, node, node.tail or '')) + if '\n' not in units[-1].tail: + raise ValueError(f'line {region[-1].sourceline}: the last dependency must end its line') + return units + + +def _commented_depend(node: etree._Element, lines: list[str]) -> _Depend | None: + if not isinstance(node, etree._Comment): + return None + match = _COMMENTED_DEPEND.fullmatch(node.text or '') + if match is None: + return None + condition = _CONDITION.search(match['attrs']) + return _Depend(match['tag'], match['name'], condition[2] if condition else '', lines) + + +def _parse(units: list[_Unit], lines: list[str]) -> tuple[dict[str, list[_Depend]], list[_Section]]: + loose: dict[str, list[_Depend]] = {tag: [] for tag in DEPEND_ORDER} + sections: list[_Section] = [] + section: _Section | None = None + prev_last: int | None = None + for unit in units: + unit_lines = lines[unit.first : unit.last + 1] + if section is not None and prev_last is not None and unit.first > prev_last + 1: + section = None + prev_last = unit.last + depend = _commented_depend(unit.node, unit_lines) + if depend is None and isinstance(unit.node, etree._Comment): + if section is not None and not section.depends: + section.comment.extend(unit_lines) + else: + section = _Section(unit_lines) + sections.append(section) + continue + if depend is None: + depend = _Depend(unit.node.tag, (unit.node.text or '').strip(), unit.node.get('condition', ''), unit_lines) + if section is None: + loose[depend.tag].append(depend) + else: + section.depends.append(depend) + for section in sections: + if not section.depends: + raise ValueError(f'comment "{section.comment[0].strip()}" is not followed by a dependency') + tags = sorted({depend.tag for depend in section.depends}, key=DEPEND_ORDER.index) + if len(tags) > 1: + raise ValueError( + f'comment "{section.comment[0].strip()}" heads dependencies of several kinds ({", ".join(tags)}),' + ' separate them with a blank line' + ) + return loose, sections + + +def _reindent(block: list[str], indent: str) -> list[str]: + return [indent + block[0].lstrip()] + block[1:] + + +def _sorted_lines(depends: list[_Depend], indent: str) -> list[str]: + return [line for depend in sorted(depends, key=_Depend.sort_key) for line in _reindent(depend.lines, indent)] + + +def _render(loose: dict[str, list[_Depend]], sections: list[_Section], indent: str) -> list[str]: + blocks: list[list[str]] = [] + for tag in DEPEND_ORDER: + if loose[tag]: + blocks.append(_sorted_lines(loose[tag], indent)) + for section in sections: + if section.depends[0].tag != tag: + continue + blocks.append(_reindent(section.comment, indent) + _sorted_lines(section.depends, indent)) + out: list[str] = [] + for block in blocks: + if out: + out.append('') + out.extend(block) + return out + + +def format_package_xml(source: str) -> str: + """Return source with its dependency list grouped and sorted. + + Raises ValueError if the source is not well-formed XML or its dependency list cannot be rewritten. + """ + try: + root = etree.fromstring(source.encode('utf-8')) + except etree.XMLSyntaxError as exc: + raise ValueError(str(exc)) from exc + if root.tag != 'package' or root.get('format') not in ('2', '3'): + return source + region = _depend_region(root) + if not region: + return source + lines = source.split('\n') + units = _units(root, region) + loose, sections = _parse(units, lines) + first_line = lines[units[0].first] + indent = first_line[: len(first_line) - len(first_line.lstrip())] + rendered = _render(loose, sections, indent) + return '\n'.join(lines[: units[0].first] + rendered + lines[units[-1].last + 1 :]) + + +def format_package_xml_files(files: list[str]) -> list[tuple[str, bool, str]]: + """Format package.xml files in place. + + Returns [(filepath, was_changed, error_message)] for each file. + error_message is non-empty only on failure; was_changed is False on failure. + """ + results = [] + for filepath in files: + path = Path(filepath) + try: + original = path.read_text(encoding='utf-8') + formatted = format_package_xml(original) + except ValueError as exc: + results.append((filepath, False, str(exc))) + continue + changed = formatted != original + if changed: + path.write_text(formatted, encoding='utf-8') + results.append((filepath, changed, '')) + return results diff --git a/pyproject.toml b/pyproject.toml index 0a925c7..24291c5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "polymath-code-standard" -version = "2.7.1" +version = "2.8.0" description = "Polymath Code Standard pre-commit hooks" requires-python = ">=3.10" dependencies = [ diff --git a/test_files/package.xml b/test_files/package.xml index fe325fa..3f49e3c 100644 --- a/test_files/package.xml +++ b/test_files/package.xml @@ -9,6 +9,11 @@ ament_cmake + rclcpp + std_msgs + + ament_cmake_pytest + ament_cmake diff --git a/tests/test_package_xml_format.py b/tests/test_package_xml_format.py new file mode 100644 index 0000000..6e33d07 --- /dev/null +++ b/tests/test_package_xml_format.py @@ -0,0 +1,265 @@ +# SPDX-FileCopyrightText: 2026 Polymath Robotics, Inc. +# SPDX-License-Identifier: Apache-2.0 +"""Tests for the package.xml dependency formatter.""" + +import argparse +import textwrap + +import pytest + +from polymath_code_standard.checkers.xml import XmlGroup +from polymath_code_standard.package_xml_format import format_package_xml + +HEAD = """\ + + + + pkg + 0.0.0 + Test + A + Apache-2.0 + +""" +TAIL = """ + + ament_cmake + + +""" + + +def package(depends: str) -> str: + return HEAD + textwrap.indent(textwrap.dedent(depends), ' ', lambda line: line.strip() != '') + TAIL + + +def assert_formats(before: str, after: str) -> None: + assert format_package_xml(package(before)) == package(after) + assert format_package_xml(package(after)) == package(after) + + +def test_groups_in_lifecycle_order_and_sorts(): + assert_formats( + """\ + b_test + rclcpp + docs + b_exec + a_test + bed + eigen + bd + bted + a_exec + ament_cmake + """, + """\ + ament_cmake + + bted + + bd + + bed + + eigen + rclcpp + + a_exec + b_exec + + a_test + b_test + + docs + """, + ) + + +def test_merges_blocks_and_normalizes_blank_lines(): + assert_formats( + """\ + b + + + a + + c + """, + """\ + a + b + c + """, + ) + + +def test_condition_breaks_ties_and_attributes_are_kept(): + assert_formats( + """\ + gz_vendor + abc + gz_vendor + """, + """\ + abc + gz_vendor + gz_vendor + """, + ) + + +def test_comment_heads_a_section_after_the_uncommented_block(): + assert_formats( + """\ + + z_launch + y_launch + + b + rclcpp + a + + tool + """, + """\ + rclcpp + + a + b + + + y_launch + z_launch + + + tool + """, + ) + + +def test_multiline_and_stacked_comments_stay_together(): + assert_formats( + """\ + + + b + a + """, + """\ + + + a + b + """, + ) + + +def test_trailing_comment_moves_with_its_dependency(): + assert_formats( + """\ + b + a + """, + """\ + a + b + """, + ) + + +def test_commented_out_dependency_sorts_as_a_dependency(): + assert_formats( + """\ + c + + a + """, + """\ + a + + c + """, + ) + + +def test_comment_after_dependencies_is_left_alone(): + source = package( + """\ + a + + + """ + ) + assert format_package_xml(source) == source + + +def test_reindents_to_first_dependency(): + assert_formats( + """\ + b + a + """, + """\ + a + b + """, + ) + + +def test_section_with_several_kinds_fails(): + source = package( + """\ + + a + b + """ + ) + with pytest.raises(ValueError, match='several kinds'): + format_package_xml(source) + + +def test_comment_without_dependency_fails(): + source = package( + """\ + a + + + b + """ + ) + with pytest.raises(ValueError, match='not followed by a dependency'): + format_package_xml(source) + + +def test_dependencies_sharing_a_line_fail(): + source = package('ba\n') + with pytest.raises(ValueError, match='own line'): + format_package_xml(source) + + +@pytest.mark.parametrize( + 'source', + [ + 'xba\n', + 'ba\n', + package(''), + ], +) +def test_unchanged(source): + assert format_package_xml(source) == source + + +def test_xml_group_reformats_package_xml(tmp_path): + path = tmp_path / 'package.xml' + path.write_text(package('b\na\n')) + other = tmp_path / 'other.xml' + other.write_text(package('b\na\n')) + results = XmlGroup().run(argparse.Namespace(files=[str(path), str(other)])) + formatted = next(r for r in results if r.name == 'package-xml-format') + assert not formatted.passed + assert str(path) in formatted.output + assert path.read_text() == package('a\nb\n') + assert other.read_text() == package('b\na\n') diff --git a/uv.lock b/uv.lock index 7e3bcd0..7b71c35 100644 --- a/uv.lock +++ b/uv.lock @@ -829,7 +829,7 @@ wheels = [ [[package]] name = "polymath-code-standard" -version = "2.7.1" +version = "2.8.0" source = { editable = "." } dependencies = [ { name = "ansible-lint" },