From afba576da0eb8d9e19b23c1f21c17796e4919a62 Mon Sep 17 00:00:00 2001 From: gregorni Date: Thu, 24 Aug 2023 17:05:25 +0200 Subject: [PATCH] Formatter: Insert newline before some child types --- blueprintcompiler/formatter.py | 24 ++++++++++++++++-------- blueprintcompiler/main.py | 3 ++- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/blueprintcompiler/formatter.py b/blueprintcompiler/formatter.py index df00ae0..726c0e3 100644 --- a/blueprintcompiler/formatter.py +++ b/blueprintcompiler/formatter.py @@ -48,19 +48,20 @@ class Format: last_not_whitespace = tokens[0] current_line = "" prev_line_type = None + is_child_type = False def commit_current_line( - extra_newlines=0, line_type=prev_line_type, indent_decrease=False + extra_newlines=1, line_type=prev_line_type, indent_decrease=False ): nonlocal tokenized_str, current_line, prev_line_type if indent_decrease: tokenized_str = tokenized_str.strip() + "\n" + (indent_levels * " ") - if extra_newlines > 0: + if extra_newlines > 1: tokenized_str = ( tokenized_str.strip() - + ("\n" * (extra_newlines + 1)) + + ("\n" * (extra_newlines)) + (" " * (indent_levels - 1)) ) @@ -99,6 +100,12 @@ class Format: is_child_type = (current_line + "[").startswith("[") if is_child_type: NO_WHITESPACE_BEFORE.append("]") + if str(last_not_whitespace) not in OPENING_TOKENS: + tokenized_str = ( + tokenized_str.strip() + + "\n\n" + + (indent_levels * " ") + ) last_not_whitespace = item continue else: @@ -107,7 +114,7 @@ class Format: indent_levels += 1 commit_current_line( - 0 if prev_line_type == LineType.CHILD_TYPE else 1, + 1 if prev_line_type == LineType.CHILD_TYPE else 2, LineType.BLOCK_OPEN, ) @@ -115,7 +122,6 @@ class Format: if str_item == "]": if is_child_type: NO_WHITESPACE_BEFORE.remove("]") - is_child_type = False indent_levels += 1 else: WHITESPACE_AFTER.append(",") @@ -123,13 +129,15 @@ class Format: indent_levels -= 1 commit_current_line( - 0, + 1, LineType.CHILD_TYPE - if current_line.startswith("[") + if is_child_type else LineType.BLOCK_CLOSE, - True, + not is_child_type, ) + is_child_type = False + else: commit_current_line() diff --git a/blueprintcompiler/main.py b/blueprintcompiler/main.py index 749d8ea..5b52472 100644 --- a/blueprintcompiler/main.py +++ b/blueprintcompiler/main.py @@ -207,6 +207,7 @@ class BlueprintApp: a_lines = data.splitlines(keepends=True) b_lines = formatted_str.splitlines(keepends=True) diff_lines = [] + for line in difflib.unified_diff( a_lines, b_lines, fromfile=file.name, tofile=file.name, n=5 ): @@ -220,7 +221,7 @@ class BlueprintApp: diff_lines.append("\\ No newline at end of file\n") print( - f"\n{Colors.BOLD}{happened} {file.name}{Colors.CLEAR}:\n\n"+ "".join(diff_lines) + f"{''.join(diff_lines)}\n{Colors.BOLD}{happened} {file.name}{Colors.CLEAR}\n" ) formatted_files += 1