Skip to content

Commit

Permalink
Fix indentation change to comments when using --fix (#4260)
Browse files Browse the repository at this point in the history
  • Loading branch information
cavcrosby committed Jul 24, 2024
1 parent 1dbb602 commit 8b3284b
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 7 deletions.
2 changes: 1 addition & 1 deletion examples/playbooks/transform-key-order.transformed.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
- name: Fixture
hosts: localhost
tasks:
# comment before keys
# comment before keys
- name: Task with no_log on top # name comment
no_log: true # no_log comment
ansible.builtin.command: echo hello # command comment
Expand Down
11 changes: 5 additions & 6 deletions src/ansiblelint/yaml_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -1184,17 +1184,16 @@ def _post_process_yaml(
text = text.rstrip("\n") + "\n"

lines = text.splitlines(keepends=True)
full_line_comments: list[tuple[int, str]] = []
full_line_comments: list[tuple[int, str, int]] = []
for i, line in enumerate(lines):
stripped = line.lstrip()
if not stripped:
# blank line. Move on.
continue

space_length = len(line) - len(stripped)

if stripped.startswith("#"):
# got a full line comment
space_length = len(line) - len(stripped)

# allow some full line comments to match the previous indent
if i > 0 and not full_line_comments and space_length:
Expand All @@ -1204,11 +1203,11 @@ def _post_process_yaml(
# if the indent matches the previous line's indent, skip it.
continue

full_line_comments.append((i, stripped))
full_line_comments.append((i, stripped, space_length))
elif full_line_comments:
# end of full line comments so adjust to match indent of this line
spaces = " " * space_length
for index, comment in full_line_comments:
for index, comment, space_length in full_line_comments:
spaces = " " * space_length
lines[index] = spaces + comment
full_line_comments.clear()

Expand Down
6 changes: 6 additions & 0 deletions test/test_yaml_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,12 @@ def load_yaml_formatting_fixtures(fixture_filename: str) -> tuple[str, str, str]
pytest.param("---\nfoo: YES\n", "---\nfoo: true\n", (1, 1), id="9"),
pytest.param("---\nfoo: YES\n", "---\nfoo: YES\n", (1, 2), id="10"),
pytest.param("---\nfoo: YES\n", "---\nfoo: YES\n", None, id="11"),
# pytest.param(
# "---\n # quoted-strings:\n # quote-type: double\n # required: only-when-needed\nignore:\n - secrets.yml\n",
# "---\n # quoted-strings:\n # quote-type: double\n # required: only-when-needed\nignore:\n - secrets.yml\n",
# None,
# id="12",
# ),
),
)
def test_fmt(before: str, after: str, version: tuple[int, int] | None) -> None:
Expand Down

0 comments on commit 8b3284b

Please sign in to comment.