Remove leading newlines.
[UnsignedByte.git] / src / Core / Editors / fixincludes.py
blob5220c7c28601de5b89bd23af738330db7fa205a9
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 if len(gincludes) > 0:
39 gincludes.sort()
40 gincludes.append("\n")
42 if len(includes) > 0:
43 includes.sort()
44 includes.append("\n")
46 precontentclean = []
47 cleaning = True
49 precontent.reverse()
51 # Clean up any trailing spaces before the includes
52 for line in precontent:
53 if cleaning and (len(line) == 0 or line.expandtabs().isspace() ):
54 continue
56 precontentclean.append(line)
57 cleaning = False
59 # Reverse the content again
60 precontentclean.reverse()
61 precontentclean.append("\n")
63 postcontentclean = []
64 cleaning = True
66 # Clean up any leading spaces after the includes
67 for line in postcontent:
68 if cleaning and (len(line) == 0 or line.expandtabs().isspace() ):
69 continue
71 postcontentclean.append(line)
72 cleaning = False
74 # Assemble the resulting file
75 result = precontentclean + gincludes + includes + postcontentclean
77 # Write the new and improved file
78 try:
79 fixfile = open(name, 'w')
80 fixfile.writelines(result)
81 finally:
82 fixfile.close()
86 if __name__ == "__main__":
87 import sys
89 filenames = sys.argv
91 if len(filenames) == 1:
92 import glob
93 print("no args, using all *.cpp and *.h files")
95 filenames = glob.glob('*.cpp') + glob.glob('*.h')
98 for filename in filenames[1:]:
99 # doRemoveWhitespace(filename)
100 doSortIncludes(filename)