3 """Script to sort the top-most block of #include lines.
5 Assumes the LLVM coding conventions.
7 Currently, this script only bothers sorting the llvm/... headers. Patches
8 welcome for more functionality, and sorting other header groups.
15 """Sort the #include lines of a specific file."""
17 # Skip files which are under INPUTS trees or test trees.
18 if 'INPUTS/' in f.name or 'test/' in f.name:
21 ext = os.path.splitext(f.name)[1]
22 if ext not in ['.cpp', '.c', '.h', '.inc', '.def']:
26 look_for_api_header = ext in ['.cpp', '.c']
34 for (i, l) in enumerate(lines):
37 if l.startswith('#include'):
42 header = l[len('#include'):].lstrip()
43 if look_for_api_header and header.startswith('"'):
44 api_headers.append(header)
45 look_for_api_header = False
47 if header.startswith('<') or header.startswith('"gtest/'):
48 system_headers.append(header)
50 if (header.startswith('"llvm/') or header.startswith('"llvm-c/') or
51 header.startswith('"clang/') or header.startswith('"clang-c/')):
52 project_headers.append(header)
54 local_headers.append(header)
57 # Only allow comments and #defines prior to any includes. If either are
58 # mixed with includes, the order might be sensitive.
61 if l.startswith('//') or l.startswith('#define') or l.startswith('#ifndef'):
67 local_headers = sorted(set(local_headers))
68 project_headers = sorted(set(project_headers))
69 system_headers = sorted(set(system_headers))
70 headers = api_headers + local_headers + project_headers + system_headers
71 header_lines = ['#include ' + h for h in headers]
72 lines = lines[:headers_begin] + header_lines + lines[headers_end + 1:]
79 parser = argparse.ArgumentParser(description=__doc__)
80 parser.add_argument('files', nargs='+', type=argparse.FileType('r+'),
81 help='the source files to sort includes within')
82 args = parser.parse_args()
86 if __name__ == '__main__':