Debian Codegraph @

utils/scripts/code-formatting

raw
1 #!/usr/bin/env python
2 #
3 # Copyright (C) 2009 Anders Logg
4 #
5 # This file is part of DOLFIN.
6 #
7 # DOLFIN is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Lesser General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # DOLFIN is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Lesser General Public License for more details.
16 #
17 # You should have received a copy of the GNU Lesser General Public License
18 # along with DOLFIN. If not, see <http://www.gnu.org/licenses/>.
19 #
20 # Check and fix coding style in all files (currently very limited)
21 #
22 # Modified by Chris Richardson, 2013
23 #
24 # Last changed: 2013-05-10
25 #
26
27 import os, sys, re, getopt
28
29 # Camelcaps exceptions
30 camelcaps_exceptions = ["cGq", "dGq", # ODE solver
31 "addListener", "addTest", "getRegistry", "makeTest", "wasSuccessful", # cppunit
32 "tagName", "tagNames", "documentElement", "childNodes", # doscstrings
33 "nodeType", "firstChild", "parentNode", # docstrings
34 "doubleArray", "intArray", # swig
35 "fatalError", "xmlChar", "xmlNode", "xmlStrcasecmp", # libxml2
36 "startDocument", "endDocument", "startElement", "endElement"] # libxml2
37
38
39 def camelcaps2underscore(word):
40 "Convert fooBar to foo_bar."
41 new_word = ""
42 for c in word:
43 if c.isupper() and len(new_word) > 0:
44 new_word += "_" + c.lower()
45 else:
46 new_word += c
47 return new_word
48
49 def check_camelcaps(code):
50 "Check for fooBar (should be foo_bar)"
51 problems=[]
52 for i,line in enumerate(code.split("\n")):
53 if(re.search(r"//",line)):
54 continue
55 words = re.findall(r"\b([a-z]+[A-Z][a-z]+)\b", line)
56 for word in words:
57 if word in camelcaps_exceptions:
58 continue
59 if re.match("vtk",word):
60 continue
61 problems.append("[camelCaps ] Line %d: %s"%(i+1,line))
62 return code, problems
63
64 def check_trailing_whitespace(code):
65 "Remove trailing spaces at end of lines."
66 problems = []
67 lines = []
68 for i,line in enumerate(code.split("\n")):
69 new_line = line.rstrip()
70 lines.append(new_line)
71 if new_line == line:
72 continue
73 problems.append("[trailing whitespace] Line %d: %s"%(i+1,line.replace(" ","_").replace("\r","^M")))
74 new_code = "\n".join(lines)
75 if len(new_code) > 0 and not new_code[-1] == "\n":
76 new_code += "\n"
77 return new_code, problems
78
79 def check_tabs(code):
80 "Check for TAB character"
81 problems = []
82 lines =[]
83 for i,line in enumerate(code.split("\n")):
84 if(re.search("\t",line)):
85 problems.append("[tab ] Line %d: %s"%(i+1,line.replace("\t",r"\t ")))
86 lines.append(re.sub("\t"," ",line))
87 else:
88 lines.append(line)
89
90 new_code = "\n".join(lines)
91 if len(new_code) > 0 and not new_code[-1] == "\n":
92 new_code += "\n"
93 return new_code, problems
94
95 def check_symbol_spacing(code):
96 "Add spaces around +,-,= etc."
97 problems = []
98 for i,line in enumerate(code.split("\n")):
99 if(re.search(r"//",line)):
100 continue
101 words = re.findall(r"\b[=|+|-|==]\b", line)
102 if(len(words)>0):
103 problems.append("[symbol spacing ] Line %d: %s"%(i,line))
104 words = re.findall(r"\b,\b", line)
105 if(len(words)>0):
106 problems.append("[comma spacing ] Line %d: %s"%(i,line))
107 return code, problems
108
109 def part_of_dolfin(code):
110 "Look for DOLFIN in file"
111 if re.search("DOLFIN",code):
112 return True
113 else:
114 return False
115
116 def detect_bad_formatting(filename, opts):
117 """Detect where code formatting appears to be wrong.
118 opts Flags:
119 -c for checking camelCaps
120 -w for checking whitespace
121 -s for checking symbol spacing, i.e. =, +, - etc.
122 -wf to fix whitespace errors
123 """
124
125 # Open file
126 f = open(filename, "r")
127 code = f.read()
128 f.close()
129
130 if(not part_of_dolfin(code)):
131 problems = ['[part of dolfin ] Does not contain "DOLFIN" - skipping']
132 else:
133 # Checks
134 problems = []
135 if("-c" in opts):
136 code, p = check_camelcaps(code)
137 problems.extend(p)
138 if("-w" in opts):
139 code, p1 = check_trailing_whitespace(code)
140 problems.extend(p1)
141 code, p2 = check_tabs(code)
142 problems.extend(p2)
143 # Rewrite corrected file (only corrects whitespace errors)
144 if("-f" in opts and (len(p1)!=0 or len(p2)!=0)):
145 problems.append('Rewriting file %s'%filename)
146 f = open(filename, "w")
147 f.write(code)
148 f.close()
149 if("-s" in opts):
150 code, p = check_symbol_spacing(code)
151 problems.extend(p)
152
153 if(len(problems) != 0):
154 print "================================================================================"
155 print filename
156 print "================================================================================"
157 for p in problems:
158 print p
159
160
161 def usage(name):
162 print
163 print name," [-c|-w|-s|-f] path"
164 print "\n Check formatting of code in the folders and subfolders of path\n"
165 print " -c check camelCaps"
166 print " -w check white space and tabs"
167 print " -s check symbol spacing"
168 print " -wf fix whitespace errors"
169 print " default: check all"
170
171 if __name__ == "__main__":
172 try:
173 opts, args = getopt.getopt(sys.argv[1:], "cwsf")
174 except getopt.GetoptError as err:
175 print str(err) # will print something like "option -a not recognized"
176 usage(sys.argv[0])
177 sys.exit(0)
178
179 if(len(args)==0):
180 usage(sys.argv[0])
181 sys.exit(0)
182 filepath = args[0]
183
184 options=[]
185 for opt, arg in opts:
186 options.append(opt)
187
188 if len(options)==0:
189 options=['-c','-w','-s']
190
191 # Iterate over all source files
192 for root, dirs, files in os.walk(filepath):
193 for file in files:
194 if not file.endswith((".cpp", ".h", ".py", ".i")):
195 continue
196 filename = os.path.join(root, file)
197 detect_bad_formatting(filename, options)
198