-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreindent.py
85 lines (73 loc) · 2.62 KB
/
reindent.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
from sys import argv, exit
if len(argv) < 2:
print("usage: python3 reindent.py <filename> [<filename> ...]")
exit()
keywords = ["if", "else", "elseif", "failure", "unavailable", "object",
"typeobject", "class", "for", "loop", "op", "operation", "function",
"begin", "process", "initially", "enumeration", "record", "recovery"]
specialKeys = ["object", "typeobject", "class", "op", "operation", "function" ]
numSpaces = 4
spaces = numSpaces * " "
def check_if_duplicates(lst):
''' Check if given list contains any duplicates '''
if len(lst) == len(set(lst)):
return False
return True
def custom_split(s):
res = s.split()
isString = False
theString = ""
strStart = 0
i = 0
while i < len(res):
if '"' in res[i].replace('\\"', ''):
if not isString:
theString = ""
strStart = i
else:
theString += res[i]
res = res[:strStart] + [theString] + res[i+1:]
i -= (i - strStart)
isString = not isString
if isString:
theString += res[i] + " "
i += 1
for i in range(len(res)):
if "%" in res[i] and not '"' in res[i]:
res[i] = res[i][0:res[i].find("%")]
break
return res[0:i+1]
for fn in argv[1:]:
if not fn.endswith(".m"):
continue
with open(fn, "r") as f:
lines = f.readlines()
with open(fn, "w") as f:
i = 0
inTypeobject = False
for line in lines:
line = line.strip()
words = custom_split(line.lower())
if words and "%" in words[0]:
f.write((spaces * i) + line)
# one-liner ifs
elif check_if_duplicates(list(filter(lambda x: x in keywords, words))):
f.write((spaces * i) + line)
elif "end" in words and any(w in words for w in specialKeys):
f.write((spaces * i) + line)
elif "end" in words:
inTypeobject = False
i -= 1
f.write((spaces * i) + line)
elif inTypeobject:
f.write((spaces * i) + line)
elif any(kw in words for kw in keywords):
if "else" in words or "elseif" in words:
i -= 1
elif "typeobject" in words:
inTypeobject = True
f.write((spaces * i) + line)
i += 1
else:
f.write((spaces * i) + line)
f.write("\n")