Removed 'not touching files if ok' since it's not working anyway.
[UnsignedByte.git] / src / Core / Editors / fixincludes.py
blob9a01f6997fd569d97b02bfc3eff96636c192ecf7
1 #!/usr/bin/env python
3 def doSortIncludes(name):
4 print('Processing ' + name)
6 try:
7 includesfound = False
9 precontent = []
10 gincludes = []
11 includes = []
12 postcontent = []
14 # Open the file and read it
15 file = open(name)
16 lines = file.readlines()
18 # Parse the content, seperating between includes and 'the rest'
19 for line in lines:
20 if line.startswith('#include <'):
21 gincludes.append(line)
22 includesfound = True
23 elif line.startswith('#include'):
24 includes.append(line)
25 includesfound = True
26 else:
27 if not includesfound:
28 precontent.append(line)
29 else:
30 postcontent.append(line)
31 finally:
32 file.close()
34 # If there are no includes, don't touch the file
35 if len(includes) == 0 and len(gincludes) == 0:
36 return
38 gincludesold = gincludes[:]
39 gincludes.sort()
40 gincludes.append("\n")
42 includesold = includes[:]
43 includes.sort()
44 includes.append("\n")
46 postcontentclean = []
47 cleaning = True
49 # Clean up any leading spaces before the includes
50 for line in postcontent:
51 if cleaning and (len(line) == 0 or line.expandtabs().isspace() ):
52 continue
54 postcontentclean.append(line)
55 cleaning = False
57 # Assemble the resulting file
58 result = precontent + gincludes + includes + postcontent
60 # Write the new and improved file
61 try:
62 fixfile = open(name, 'w')
63 fixfile.writelines(result)
64 finally:
65 fixfile.close()
69 if __name__ == "__main__":
70 import sys
72 filenames = sys.argv
74 if len(filenames) == 1:
75 import glob
76 print("no args, using all *.cpp and *.h files")
78 filenames = glob.glob('*.cpp') + glob.glob('*.h')
81 for filename in filenames[1:]:
82 # doRemoveWhitespace(filename)
83 doSortIncludes(filename)