-
Notifications
You must be signed in to change notification settings - Fork 0
/
PythonSpaceLines.py
200 lines (140 loc) · 5.01 KB
/
PythonSpaceLines.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
import logging
import os
import re
import sys
from json import dump, dumps
from typing import List, Union
class CodeSection:
def __init__(self, indentedLine: str, parent: "CodeSection" = None):
self.children: List["CodeSection"] = []
self.text: str = indentedLine.strip()
if self.text in {"]", "}", ")"}:
self.level = len(indentedLine) - len(indentedLine.lstrip())
else:
self.level: int = len(indentedLine) - len(indentedLine.lstrip())
self.parent: "CodeSection" = parent
self.prev: "CodeSection" = None
def AddChildren(self, nodes: List["CodeSection"]):
if not nodes:
return
childLevel = nodes[0].level
while nodes:
node = nodes[0]
if node.level < self.level:
# Node belongs to a higher level; let the parent handle it
return
elif node.level == childLevel:
child = nodes.pop(0)
child.parent = self
self.children.append(child)
elif node.level > childLevel:
if not self.children:
raise Exception("Cannot add child to a node without a parent.")
self.children[-1].AddChildren(nodes)
else:
# node.level < childLevel
return
def AsDict(self) -> Union[dict, str]:
if len(self.children) > 1:
return {self.text: [child.AsDict() for child in self.children]}
elif len(self.children) == 1:
return {self.text: self.children[0].AsDict()}
else:
return self.text
def PrintTree(section: CodeSection, indent: int = 0):
if section.text.strip() != "":
print(f"{" " * indent}{section.text} (Level {section.level})")
else:
print()
for child in section.children:
PrintTree(child, indent + 4)
def TraverseTree(section: CodeSection):
if section.prev and (
section.text.strip() == ")"
or section.text.strip() == "]"
or section.text.strip() == "}"
):
section.level = section.prev.level
if section.parent:
section.parent.children.remove(section)
section.parent = section.prev.parent
if section.parent:
section.parent.children.append(section)
for child in section.children:
TraverseTree(child)
def FormatNewlines(filePath):
logging.basicConfig(level=logging.DEBUG, format="%(levelname)s: %(message)s")
if not os.path.isfile(filePath):
logging.error(f"File not found - {filePath}")
sys.exit(1)
with open(filePath, "r") as file:
codeContent = file.read()
def LogAffectedLines(pattern, description):
matches = list(
re.finditer(pattern, codeContent, flags=re.MULTILINE | re.DOTALL)
)
if matches:
lineNumbers = sorted(
set(codeContent.count("\n", 0, match.start()) + 1 for match in matches)
)
logging.debug(f"Applying pattern for {description}: {pattern}")
logging.debug(f" Lines affected: {lineNumbers}")
patternClassDocstring = r"(\bclass\s+\w+.*:)(\n\s*\"\"\")"
LogAffectedLines(patternClassDocstring, "Class declaration followed by docstring")
codeContent = re.sub(patternClassDocstring, r"\1\2", codeContent)
splitLines = codeContent.splitlines()
nodes = []
previousNode = None
prevLevel = 0
for line in codeContent.strip().splitlines():
if line.strip():
node = CodeSection(line)
node.prev = previousNode
previousNode = node
prevLevel = node.level
else:
node = CodeSection(" " * prevLevel)
node.prev = previousNode
nodes.append(node)
# Create root section
root = CodeSection("root")
# Build the tree
root.AddChildren(nodes)
TraverseTree(root)
# Convert the tree to a dictionary
treeDict = root.AsDict()["root"]
print("Tree as Dictionary:")
print(dumps(treeDict, indent=4))
with open("out.json", "w") as file:
dump(
treeDict,
file,
indent=2,
)
print("\nVisual Representation:")
PrintTree(root)
insertLineAfterKeywords = [
"if",
"elif",
"else",
"while",
"with",
"try",
"except",
"finally",
"return",
]
patternTrailingNewlines = r"\n+$"
if re.search(patternTrailingNewlines, codeContent):
logging.debug("Removed trailing blank lines at the end of the file.")
codeContent = re.sub(patternTrailingNewlines, "\n", codeContent)
with open(filePath, "w") as file:
file.write(codeContent)
if __name__ == "__main__":
filePath = os.path.abspath(__file__)
# if len(sys.argv) != 2:
# print("Usage: python PythonSpaceLines.py <filePath>")
# print(f"Received arguments: {sys.argv}")
# sys.exit(1)
# FormatNewlines(sys.argv[1])
FormatNewlines(filePath)