forked from llvm/llvm-project
- Notifications
You must be signed in to change notification settings - Fork 339
/
Copy pathsort_includes.py
executable file
·93 lines (80 loc) · 2.79 KB
/
sort_includes.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#!/usr/bin/env python
"""Script to sort the top-most block of #include lines.
Assumes the LLVM coding conventions.
Currently, this script only bothers sorting the llvm/... headers. Patches
welcome for more functionality, and sorting other header groups.
"""
importargparse
importos
defsort_includes(f):
"""Sort the #include lines of a specific file."""
# Skip files which are under INPUTS trees or test trees.
if'INPUTS/'inf.nameor'test/'inf.name:
return
ext=os.path.splitext(f.name)[1]
ifextnotin ['.cpp', '.c', '.h', '.inc', '.def']:
return
lines=f.readlines()
look_for_api_header=extin ['.cpp', '.c']
found_headers=False
headers_begin=0
headers_end=0
api_headers= []
local_headers= []
subproject_headers= []
llvm_headers= []
system_headers= []
for (i, l) inenumerate(lines):
ifl.strip() =='':
continue
ifl.startswith('#include'):
ifnotfound_headers:
headers_begin=i
found_headers=True
headers_end=i
header=l[len('#include'):].lstrip()
iflook_for_api_headerandheader.startswith('"'):
api_headers.append(header)
look_for_api_header=False
continue
if (header.startswith('<') orheader.startswith('"gtest/') or
header.startswith('"isl/') orheader.startswith('"json/')):
system_headers.append(header)
continue
if (header.startswith('"clang/') orheader.startswith('"clang-c/') or
header.startswith('"polly/')):
subproject_headers.append(header)
continue
if (header.startswith('"llvm/') orheader.startswith('"llvm-c/')):
llvm_headers.append(header)
continue
local_headers.append(header)
continue
# Only allow comments and #defines prior to any includes. If either are
# mixed with includes, the order might be sensitive.
iffound_headers:
break
ifl.startswith('//') orl.startswith('#define') orl.startswith('#ifndef'):
continue
break
ifnotfound_headers:
return
local_headers=sorted(set(local_headers))
subproject_headers=sorted(set(subproject_headers))
llvm_headers=sorted(set(llvm_headers))
system_headers=sorted(set(system_headers))
headers=api_headers+local_headers+subproject_headers+llvm_headers+system_headers
header_lines= ['#include '+hforhinheaders]
lines=lines[:headers_begin] +header_lines+lines[headers_end+1:]
f.seek(0)
f.truncate()
f.writelines(lines)
defmain():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('files', nargs='+', type=argparse.FileType('r+'),
help='the source files to sort includes within')
args=parser.parse_args()
forfinargs.files:
sort_includes(f)
if__name__=='__main__':
main()