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']
32 subproject_headers
= []
35 for (i
, l
) in enumerate(lines
):
38 if l
.startswith('#include'):
43 header
= l
[len('#include'):].lstrip()
44 if look_for_api_header
and header
.startswith('"'):
45 api_headers
.append(header
)
46 look_for_api_header
= False
48 if (header
.startswith('<') or header
.startswith('"gtest/') or
49 header
.startswith('"isl/') or header
.startswith('"json/')):
50 system_headers
.append(header
)
52 if (header
.startswith('"clang/') or header
.startswith('"clang-c/') or
53 header
.startswith('"polly/')):
54 subproject_headers
.append(header
)
56 if (header
.startswith('"llvm/') or header
.startswith('"llvm-c/')):
57 llvm_headers
.append(header
)
59 local_headers
.append(header
)
62 # Only allow comments and #defines prior to any includes. If either are
63 # mixed with includes, the order might be sensitive.
66 if l
.startswith('//') or l
.startswith('#define') or l
.startswith('#ifndef'):
72 local_headers
= sorted(set(local_headers
))
73 subproject_headers
= sorted(set(subproject_headers
))
74 llvm_headers
= sorted(set(llvm_headers
))
75 system_headers
= sorted(set(system_headers
))
76 headers
= api_headers
+ local_headers
+ subproject_headers
+ llvm_headers
+ system_headers
77 header_lines
= ['#include ' + h
for h
in headers
]
78 lines
= lines
[:headers_begin
] + header_lines
+ lines
[headers_end
+ 1:]
85 parser
= argparse
.ArgumentParser(description
=__doc__
)
86 parser
.add_argument('files', nargs
='+', type=argparse
.FileType('r+'),
87 help='the source files to sort includes within')
88 args
= parser
.parse_args()
92 if __name__
== '__main__':