Skip to content

Commit 9d2d903

Browse files
committed
fixes
1 parent fe8ebe7 commit 9d2d903

File tree

1 file changed

+75
-118
lines changed

1 file changed

+75
-118
lines changed

src/tfdocs/utils.py

Lines changed: 75 additions & 118 deletions
Original file line numberDiff line numberDiff line change
@@ -59,132 +59,89 @@ def match_type_constructors(string):
5959

6060

6161
def format_block(content):
62-
start_braces = ["{", "[", "("]
63-
end_braces = ["}", "]", ")"]
64-
65-
if match_type_constructors(content):
66-
content_str = content.rstrip()
67-
indent = 4
68-
tokens = []
69-
current_token = []
70-
71-
# Tokenize the input
72-
for char in content_str:
73-
if char in start_braces + end_braces + [","]:
74-
if current_token:
75-
tokens.append("".join(current_token).strip())
76-
current_token = []
77-
tokens.append(char)
78-
else:
79-
current_token.append(char)
80-
if current_token:
81-
tokens.append("".join(current_token).strip())
62+
input_str = content.strip()
63+
64+
if "{" not in input_str:
65+
return input_str
66+
67+
def add_missing_commas(s):
68+
return re.sub(r'([}\]"\w])(\s+)(\w+\s*=)', r'\1,\2\3', s)
8269

83-
# Format the tokens
70+
def smart_split(s):
8471
result = []
85-
prev_item = None
86-
87-
for item in tokens:
88-
if item in start_braces:
89-
if match_type_constructors(prev_item):
90-
result.append(item)
91-
else:
92-
result.append(item)
93-
indent += 2
94-
result.append("\n" + " " * indent)
95-
elif item == ",":
96-
result.append(item)
97-
elif item in end_braces:
98-
if prev_item in end_braces:
99-
result.append(item)
100-
else:
101-
indent -= 2
102-
result.append("\n" + " " * indent + item)
72+
current = ''
73+
depth = 0
74+
for char in s:
75+
if char in '{[':
76+
depth += 1
77+
elif char in '}]':
78+
depth -= 1
79+
if char == ',' and depth == 0:
80+
result.append(current.strip())
81+
current = ''
10382
else:
104-
if prev_item:
105-
if match_type_constructors(prev_item) and match_type_constructors(item):
106-
result.append(item)
107-
else:
108-
result.append("\n" + " " * indent + item)
109-
else:
110-
result.append(item)
111-
112-
if item not in start_braces + [","]:
113-
prev_item = item
114-
115-
return "".join(result)
116-
117-
# Handle non-type constructor case
118-
content_str = content.rstrip()
119-
indent = 2
120-
result = []
121-
brace_flag = False
122-
content_flag = 0
123-
124-
for char in content_str:
125-
if char in start_braces + end_braces:
126-
brace_flag = True
127-
char = char.strip()
128-
if char in end_braces:
129-
indent -= 2
130-
result.extend(["\n", " " * indent, char])
83+
current += char
84+
if current.strip():
85+
result.append(current.strip())
86+
return result
87+
88+
def format_object_block(block_content, indent_level=2):
89+
indent = " " * indent_level
90+
items = smart_split(block_content.strip())
91+
92+
if len(items) == 1 and len(block_content.strip()) < 40:
93+
return "{ " + block_content.strip() + " }"
94+
95+
formatted_str = "{\n"
96+
for i, item in enumerate(items):
97+
if "=" not in item:
98+
continue
99+
key, val = map(str.strip, item.split("=", 1))
100+
comma = "," if i < len(items) - 1 else ""
101+
if val.startswith("{") and val.endswith("}"):
102+
val = format_object_block(val[1:-1], indent_level + 1)
103+
formatted_str += f"{indent}{key} = {val}{comma}\n"
131104
else:
132-
result.append(char)
133-
if char in start_braces:
134-
indent += 2
135-
result.extend(["\n", " " * indent])
136-
elif char == "," and brace_flag:
137-
result.extend([char, "\n", " " * indent])
138-
else:
139-
if content_flag >= 1 and char.strip():
140-
content_flag = 2
141-
elif char == "=":
142-
content_flag = 1
143-
result.append(char)
105+
formatted_str += f"{indent}{key} = {val}{comma}\n"
106+
formatted_str += " " * (indent_level - 1) + "}"
107+
return formatted_str
144108

145-
formatted = "".join(result)
146-
147-
# Handle special case for assignments
148-
if content_flag == 1:
149-
left, right = formatted.split("=", 1)
150-
right = right.replace("\n", "").replace("\r", "").replace(" ", "")
151-
return f"{left}= {right}"
152-
153-
return formatted
109+
def add_indent_after_first_line(s):
110+
lines = s.splitlines()
111+
if len(lines) <= 1:
112+
return s
113+
return lines[0] + "\n" + "\n".join(" " + line for line in lines[1:])
114+
115+
nested_match = re.match(r'(\w+\s*\(\s*\w+\s*\(\s*){(.*)}(\s*\)\s*\))', input_str)
116+
if nested_match:
117+
prefix, body, suffix = nested_match.groups()
118+
body_fixed = add_missing_commas(body)
119+
formatted_body = format_object_block(body_fixed)
120+
return add_indent_after_first_line(f"{prefix}{formatted_body}{suffix}")
121+
122+
if input_str.startswith("{") and input_str.endswith("}"):
123+
inner = input_str[1:-1]
124+
inner_fixed = add_missing_commas(inner)
125+
formatted = format_object_block(inner_fixed, indent_level=1)
126+
return add_indent_after_first_line(formatted)
127+
128+
return input_str
154129

155130

156131
def construct_tf_variable(content):
157-
default_str = (
158-
f' default = {content.pop("default")}\n' if "default" in content else ""
159-
)
160-
161-
type_override = (
162-
f" #tfdocs: type={content['type_override']}" + "\n"
163-
if content["type_override"]
164-
else ""
165-
)
166-
167-
formatted_default_str = format_block(default_str)
168-
default_str = formatted_default_str + "\n" if formatted_default_str else ""
169-
170-
type_str = format_block(content["type"])
171-
172-
template = (
173-
'variable "{name}" {{\n'
174-
"{type_override}"
175-
" type = {type}\n"
176-
" description = {description}\n"
177-
"{default}"
178-
"}}\n\n"
179-
)
180-
181-
return template.format(
182-
name=content["name"],
183-
type_override=type_override,
184-
type=type_str,
185-
description=content["description"],
186-
default=default_str,
187-
)
132+
lines = [f'variable "{content["name"]}" {{']
133+
134+
if content["type_override"]:
135+
lines.append(f' #tfdocs: type={content["type_override"].strip()}')
136+
137+
lines.append(f' type = {format_block(content["type"].strip())}')
138+
lines.append(f' description = {content["description"].strip()}')
139+
140+
if "default" in content:
141+
lines.append(f' default = {format_block(content["default"].strip())}')
142+
143+
lines.append("}")
144+
return "\n".join(lines)
188145

189146

190147
def construct_tf_file(content):

0 commit comments

Comments
 (0)