Implement setting tabs and spaces for indents

This commit is contained in:
gregorni 2023-08-27 16:45:11 +02:00
parent afba576da0
commit bf3917099a
2 changed files with 24 additions and 6 deletions

View file

@ -41,7 +41,7 @@ class LineType(Enum):
class Format: class Format:
def format(data): def format(data, tab_size=2, insert_space=True):
indent_levels = 0 indent_levels = 0
tokens = tokenizer.tokenize(data) tokens = tokenizer.tokenize(data)
tokenized_str = "" tokenized_str = ""
@ -49,6 +49,7 @@ class Format:
current_line = "" current_line = ""
prev_line_type = None prev_line_type = None
is_child_type = False is_child_type = False
indent_item = " " * tab_size if insert_space else "\t"
def commit_current_line( def commit_current_line(
extra_newlines=1, line_type=prev_line_type, indent_decrease=False extra_newlines=1, line_type=prev_line_type, indent_decrease=False
@ -56,16 +57,18 @@ class Format:
nonlocal tokenized_str, current_line, prev_line_type nonlocal tokenized_str, current_line, prev_line_type
if indent_decrease: if indent_decrease:
tokenized_str = tokenized_str.strip() + "\n" + (indent_levels * " ") tokenized_str = (
tokenized_str.strip() + "\n" + (indent_levels * indent_item)
)
if extra_newlines > 1: if extra_newlines > 1:
tokenized_str = ( tokenized_str = (
tokenized_str.strip() tokenized_str.strip()
+ ("\n" * (extra_newlines)) + ("\n" * (extra_newlines))
+ (" " * (indent_levels - 1)) + (indent_item * (indent_levels - 1))
) )
tokenized_str += current_line + "\n" + (indent_levels * " ") tokenized_str += current_line + "\n" + (indent_levels * indent_item)
current_line = "" current_line = ""
prev_line_type = line_type prev_line_type = line_type
@ -104,7 +107,7 @@ class Format:
tokenized_str = ( tokenized_str = (
tokenized_str.strip() tokenized_str.strip()
+ "\n\n" + "\n\n"
+ (indent_levels * " ") + (indent_levels * indent_item)
) )
last_not_whitespace = item last_not_whitespace = item
continue continue

View file

@ -74,8 +74,23 @@ class BlueprintApp:
"-f", "-f",
"--fix", "--fix",
help="Format the files in place, don't output the diff", help="Format the files in place, don't output the diff",
default=False,
action="store_true", action="store_true",
) )
format.add_argument(
"-t",
"--tabs",
help="Use tabs instead of spaces",
default=False,
action="store_true",
)
format.add_argument(
"-s",
"--spaces",
help="How many spaces should be used per indent",
default=2,
type=int,
)
format.add_argument( format.add_argument(
"inputs", "inputs",
nargs="+", nargs="+",
@ -193,7 +208,7 @@ class BlueprintApp:
for warning in warnings: for warning in warnings:
warning.pretty_print(file.name, data, stream=sys.stderr) warning.pretty_print(file.name, data, stream=sys.stderr)
formatted_str = Format.format(data) formatted_str = Format.format(data, opts.spaces, not opts.tabs)
if data != formatted_str: if data != formatted_str:
happened = "Would reformat" happened = "Would reformat"