From 82be152c34e42f87061f3cebe60ad2de7e99a88e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20S=C5=82omkowski?= Date: Thu, 16 Jun 2016 02:37:44 +0200 Subject: [PATCH] Add feature to remove excessive newlines. --- nginxfmt.py | 12 ++++++++++-- test_nginxfmt.py | 14 +++++++++++--- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/nginxfmt.py b/nginxfmt.py index e1381c8..a611ac4 100755 --- a/nginxfmt.py +++ b/nginxfmt.py @@ -62,7 +62,10 @@ def perform_indentation(lines): if not line.startswith("#") and line.endswith('}') and current_indent > 0: current_indent -= 1 - indented_lines.append(current_indent * INDENTATION + line) + if line != "": + indented_lines.append(current_indent * INDENTATION + line) + else: + indented_lines.append("") if not line.startswith("#") and line.endswith('{'): current_indent += 1 @@ -76,7 +79,12 @@ def format_config_file(contents): lines = join_opening_bracket(lines) lines = perform_indentation(lines) - return '\n'.join(lines) + '\n' + text = '\n'.join(lines) + + for pattern, substitute in ((r'\n{3,}', '\n\n\n'), (r'^\n', ''), (r'\n$', '')): + text = re.sub(pattern, substitute, text, re.MULTILINE) + + return text + '\n' if __name__ == "__main__": diff --git a/test_nginxfmt.py b/test_nginxfmt.py index 20c0b70..5162972 100644 --- a/test_nginxfmt.py +++ b/test_nginxfmt.py @@ -70,15 +70,23 @@ class TestFormatter(unittest.TestCase): self.assertEqual('lorem ipsum " foo bar zip " or " dd aa " mi', strip_line(' lorem ipsum " foo bar zip " or \t " dd aa " mi')) - def test_indentation(self): + def test_empty_lines_removal(self): self._check_formatting( - " foo bar {\n" + + "\n foo bar {\n" + " lorem ipsum;\n" + - "}", + "}\n\n\n", "foo bar {\n" + " lorem ipsum;\n" + "}\n") + self._check_formatting( + "\n foo bar {\n\n\n\n\n\n" + + " lorem ipsum;\n" + + "}\n\n\n", + "foo bar {\n\n\n" + + " lorem ipsum;\n" + + "}\n") + self._check_formatting( " foo bar {\n" + " lorem ipsum;\n" +