-
Notifications
You must be signed in to change notification settings - Fork 408
/
Copy pathcode_format_fixup.py
executable file
·106 lines (85 loc) · 2.99 KB
/
code_format_fixup.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
#!/usr/bin/env python3
import sys, os
import argparse
def fix_comments(f, o):
space_string = ""
for line in f:
# Skip lines with // comments
if space_string == "" and line.find("//") != -1:
o.write(line)
continue
sc = line.find("/*")
ec = line.find("*/")
# Skip /* foo bar */ comments
if sc != -1 and ec != -1:
o.write(line)
else:
# Start of /* comment */
if sc != -1:
space_string = "".join(" " for i in range(sc + 1))
o.write(line)
elif space_string != "":
# Already in /* comment */
ls = line.lstrip()
# Empty line, write aligned comment prefix
if len(ls) == 0:
o.write(space_string + "*" + "\n")
elif ls[0] != "*":
#
# Fix comments like '********* sth **********'
# to look like ' * ********** sth **********'
#
o.write(space_string + "* " + ls)
else:
# Rest of the /* comment */
o.write(space_string + ls)
else:
# Outside /* comment */
o.write(line)
# Moving outside /* comment */
if ec != -1:
space_string = ""
def fix_template_operators(f, o):
for line in f:
line = line.replace("<<>", "< <>")
line = line.replace("><>", "> <>")
line = line.replace("==<>", "== <>")
line = line.replace("!=<>", "!= <>")
o.write(line)
def main(argv):
parser = argparse.ArgumentParser(description="Tool for fixing clang code formatting")
parser.add_argument(
"--inplace", dest="inplace", action="store_true", help="Inplace edit specified file"
)
parser.add_argument(
"--fix-comments",
dest="fix_comments",
action="store_const",
const="fix_comments",
help="Fix C like box comments",
)
parser.add_argument(
"--fix-template-operators",
dest="fix_template_operators",
action="store_const",
const="fix_template_operators",
help="Fix C++ template operators e.g. operator<<> => operator< <>",
)
parser.add_argument("--input", dest="inputfile", action="store", help="Input file")
parser.add_argument("--output", dest="outputfile", action="store", help="Output file")
args = parser.parse_args(argv[1:])
for p in args.fix_comments, args.fix_template_operators:
if not p:
continue
fin = open(args.inputfile, "r")
if args.inplace:
fout = open(args.inputfile + ".bak", "w")
else:
fout = open(args.outputfile, "w")
eval("" + p + "(fin, fout)")
fin.close()
fout.close()
if args.inplace:
os.rename(args.inputfile + ".bak", args.inputfile)
if __name__ == "__main__":
main(sys.argv)