Skip to content

Commit

Permalink
Preserve newlines before comments
Browse files Browse the repository at this point in the history
Closes #62.
  • Loading branch information
bbannier committed Nov 3, 2023
1 parent 63fc98b commit ac10830
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 4 deletions.
29 changes: 29 additions & 0 deletions tests/test_formatting.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import pathlib
import sys
import unittest
import textwrap

# Sets up sys.path and provides helpers
import testutils as tu
Expand Down Expand Up @@ -62,6 +63,34 @@ def test_index_slice(self):
self.assertEqual(self._format(b"data[1 :1-1];").rstrip(), b"data[1 : 1 - 1];")
self.assertEqual(self._format(b"data[f(): ];").rstrip(), b"data[f() :];")

def test_format_comment_separator(self):
"""Validates that we preserve the separator before a comment. This is a
regression test for #62."""

self.assertEqual(
self._format(b"global x = 42; # Inline.\n"), b"global x = 42; # Inline.\n"
)

code = textwrap.dedent(
"""\
event zeek_init() {}
# Comment on next line.
"""
)

expected = textwrap.dedent(
"""\
event zeek_init()
\t{ }
# Comment on next line.
"""
)

# We split out lines here to work around different line endings on Windows.
self.assertEqual(
self._format(code.encode()).decode().splitlines(), expected.splitlines()
)


class TestFormattingErrors(unittest.TestCase):
def _format(self, content):
Expand Down
13 changes: 9 additions & 4 deletions zeekscript/formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -1336,10 +1336,15 @@ def __init__(self, script, node, ostream, indent=0, hints=None):
class MinorCommentFormatter(CommentFormatter):
def format(self):
node = self.node
# There's something before us and it's not a newline, then
# separate this comment from it with a space:
if node.prev_cst_sibling and not node.prev_cst_sibling.is_nl():
self._write_sp()

# Preserve separator to previous node if any.
if node.prev_cst_sibling:
if node.prev_cst_sibling.is_nl():
# Keep newlines verbatim.
self._write_nl()
else:
# If we are on the same line, normalize to exactly one space.
self._write_sp()

self._format_token() # Write comment itself

Expand Down

0 comments on commit ac10830

Please sign in to comment.