Skip to content

Commit c2f0aba

Browse files
committed
Strip trailing whitespace in yaml
1 parent 09d15cc commit c2f0aba

2 files changed

Lines changed: 29 additions & 1 deletion

File tree

polymath_code_standard/yaml_format.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -301,6 +301,19 @@ def apply_matrices(source: str, matrices: dict[str, int]) -> str:
301301
# ---------------------------------------------------------------------------
302302

303303

304+
def _strip_trailing_whitespace(text: str) -> str:
305+
"""Strip trailing whitespace from each line, preserving newlines.
306+
307+
Why: yamlfix emits an empty list item as ``- `` (dash + trailing space).
308+
The pre-commit ``trailing-whitespace`` hook would then fight this hook
309+
in a loop. Stripping line-trailing whitespace here makes our output a
310+
fixed point for both hooks. Safe in YAML: literal/folded block scalars
311+
have their per-line trailing whitespace stripped by the parser anyway,
312+
and other contexts never carry meaningful trailing spaces.
313+
"""
314+
return '\n'.join(line.rstrip() for line in text.split('\n'))
315+
316+
304317
def format_yaml(source: str) -> str:
305318
"""Format YAML source, preserving matrix-structured flow sequences.
306319
@@ -312,7 +325,7 @@ def format_yaml(source: str) -> str:
312325
fixed = fix_code(source, _yamlfix_config())
313326
if matrices:
314327
fixed = apply_matrices(fixed, matrices)
315-
return fixed
328+
return _strip_trailing_whitespace(fixed)
316329

317330

318331
def format_yaml_files(files: list[str]) -> list[tuple[str, bool, str]]:

tests/test_yaml_format.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,21 @@ def test_single_line_sequence_preserved(self):
116116
result = format_yaml('tags: [a, b, c]\n')
117117
assert '[a, b, c]' in result
118118

119+
def test_empty_list_item_has_no_trailing_space(self):
120+
# yamlfix emits empty list items as '- ' (dash + space). The
121+
# trailing-whitespace hook would then undo it, leading to a hook
122+
# fight. format_yaml must produce a fixed point: bare '-'.
123+
source = textwrap.dedent("""\
124+
items:
125+
-
126+
-
127+
- x
128+
""")
129+
result = format_yaml(source)
130+
for i, line in enumerate(result.splitlines()):
131+
assert line == line.rstrip(), f'trailing whitespace on line {i}: {line!r}'
132+
assert '\n -\n -\n - x\n' in result
133+
119134

120135
# ---------------------------------------------------------------------------
121136
# format_yaml — matrix preservation

0 commit comments

Comments
 (0)