Added a EditorSocial.
[UnsignedByte.git] / src / fixincludes.py
blobf0874abd4b02457dd70aaf6ef21ed6d41602f4ba
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('//NOSORT'):
21 return
23 if line.startswith('#include <'):
24 gincludes.append(line)
25 includesfound = True
26 elif line.startswith('#include'):
27 includes.append(line)
28 includesfound = True
29 else:
30 if not includesfound:
31 precontent.append(line)
32 else:
33 postcontent.append(line)
34 finally:
35 file.close()
37 # If there are no includes, don't touch the file
38 if len(includes) == 0 and len(gincludes) == 0:
39 return
41 if len(gincludes) > 0:
42 gincludes.sort()
43 gincludes.append("\n")
45 if len(includes) > 0:
46 includes.sort()
47 includes.append("\n")
49 precontentclean = []
50 cleaning = True
52 precontent.reverse()
54 # Clean up any trailing spaces before the includes
55 for line in precontent:
56 if cleaning and (len(line) == 0 or line.expandtabs().isspace() ):
57 continue
59 precontentclean.append(line)
60 cleaning = False
62 # Reverse the content again
63 precontentclean.reverse()
64 precontentclean.append("\n")
66 postcontentclean = []
67 cleaning = True
69 # Clean up any leading spaces after the includes
70 for line in postcontent:
71 if cleaning and (len(line) == 0 or line.expandtabs().isspace() ):
72 continue
74 postcontentclean.append(line)
75 cleaning = False
77 # Assemble the resulting file
78 result = precontentclean + gincludes + includes + postcontentclean
80 # Write the new and improved file
81 try:
82 fixfile = open(name, 'w')
83 fixfile.writelines(result)
84 finally:
85 fixfile.close()
89 if __name__ == "__main__":
90 import sys
92 filenames = sys.argv
94 if len(filenames) == 1:
95 import glob
96 print("no args, using all *.cpp and *.h files")
98 filenames = filenames[0:1] + glob.glob('*.cpp') + glob.glob('*.h')
101 for filename in filenames[1:]:
102 # doRemoveWhitespace(filename)
103 doSortIncludes(filename)