Skip to content

Commit

Permalink
fix sort_simple_yaml.py to handle comments with space before #
Browse files Browse the repository at this point in the history
  • Loading branch information
r-downing committed Oct 31, 2023
1 parent cc94673 commit 4baf093
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions pre_commit_hooks/sort_simple_yaml.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,22 @@
from __future__ import annotations

import argparse
import re
from typing import Sequence


QUOTES = ["'", '"']


def _is_comment(line: str) -> bool:
"""Tell if a YAML line is a comment, starting with spaces and a #.
:param line: line of text
:return: True if line is a yaml comment
"""
return re.search(r'^\s*#', line) is not None


def sort(lines: list[str]) -> list[str]:
"""Sort a YAML file in alphabetical order, keeping blocks together.
Expand Down Expand Up @@ -55,7 +65,7 @@ def parse_block(lines: list[str], header: bool = False) -> list[str]:
:return: list of lines that form the single block
"""
block_lines = []
while lines and lines[0] and (not header or lines[0].startswith('#')):
while lines and lines[0] and (not header or _is_comment(lines[0])):
block_lines.append(lines.pop(0))
return block_lines

Expand Down Expand Up @@ -90,7 +100,7 @@ def first_key(lines: list[str]) -> str:
'foo'
"""
for line in lines:
if line.startswith('#'):
if _is_comment(line):
continue
if any(line.startswith(quote) for quote in QUOTES):
return line[1:]
Expand Down

0 comments on commit 4baf093

Please sign in to comment.