Debian Codegraph @

tools/distrib/check_include_guards.py

raw
1 #!/usr/bin/env python3
2
3 # Copyright 2016 gRPC authors.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 import argparse
18 import os
19 import os.path
20 import re
21 import subprocess
22 import sys
23
24
25 def build_valid_guard(fpath):
26 prefix = 'GRPC_' if not fpath.startswith('include/') else ''
27 return prefix + '_'.join(
28 fpath.replace('++', 'XX').replace('.', '_').upper().split('/')[1:])
29
30
31 def load(fpath):
32 with open(fpath, 'r') as f:
33 return f.read()
34
35
36 def save(fpath, contents):
37 with open(fpath, 'w') as f:
38 f.write(contents)
39
40
41 class GuardValidator(object):
42
43 def __init__(self):
44 self.ifndef_re = re.compile(r'#ifndef ([A-Z][A-Z_1-9]*)')
45 self.define_re = re.compile(r'#define ([A-Z][A-Z_1-9]*)')
46 self.endif_c_core_re = re.compile(
47 r'#endif /\* (?: *\\\n *)?([A-Z][A-Z_1-9]*) (?:\\\n *)?\*/$')
48 self.endif_re = re.compile(r'#endif // ([A-Z][A-Z_1-9]*)')
49 self.comments_then_includes_re = re.compile(
50 r'^((//.*?$|/\*.*?\*/|[ \r\n\t])*)(([ \r\n\t]|#include .*)*)(#ifndef [^\n]*\n#define [^\n]*\n)',
51 re.DOTALL | re.MULTILINE)
52 self.failed = False
53
54 def _is_c_core_header(self, fpath):
55 return 'include' in fpath and not ('grpc++' in fpath or 'grpcpp'
56 in fpath or 'event_engine' in fpath)
57
58 def fail(self, fpath, regexp, fcontents, match_txt, correct, fix):
59 c_core_header = self._is_c_core_header(fpath)
60 self.failed = True
61 invalid_guards_msg_template = (
62 '{0}: Missing preprocessor guards (RE {1}). '
63 'Please wrap your code around the following guards:\n'
64 '#ifndef {2}\n'
65 '#define {2}\n'
66 '...\n'
67 '... epic code ...\n'
68 '...\n') + ('#endif /* {2} */'
69 if c_core_header else '#endif // {2}')
70 if not match_txt:
71 print(
72 (invalid_guards_msg_template.format(fpath, regexp.pattern,
73 build_valid_guard(fpath))))
74 return fcontents
75
76 print((('{}: Wrong preprocessor guards (RE {}):'
77 '\n\tFound {}, expected {}').format(fpath, regexp.pattern,
78 match_txt, correct)))
79 if fix:
80 print(('Fixing {}...\n'.format(fpath)))
81 fixed_fcontents = re.sub(match_txt, correct, fcontents)
82 if fixed_fcontents:
83 self.failed = False
84 return fixed_fcontents
85 else:
86 print()
87 return fcontents
88
89 def check(self, fpath, fix):
90 c_core_header = self._is_c_core_header(fpath)
91 valid_guard = build_valid_guard(fpath)
92
93 fcontents = load(fpath)
94
95 match = self.ifndef_re.search(fcontents)
96 if not match:
97 print(('something drastically wrong with: %s' % fpath))
98 return False # failed
99 if match.lastindex is None:
100 # No ifndef. Request manual addition with hints
101 self.fail(fpath, match.re, match.string, '', '', False)
102 return False # failed
103
104 # Does the guard end with a '_H'?
105 running_guard = match.group(1)
106 if not running_guard.endswith('_H'):
107 fcontents = self.fail(fpath, match.re, match.string, match.group(1),
108 valid_guard, fix)
109 if fix:
110 save(fpath, fcontents)
111
112 # Is it the expected one based on the file path?
113 if running_guard != valid_guard:
114 fcontents = self.fail(fpath, match.re, match.string, match.group(1),
115 valid_guard, fix)
116 if fix:
117 save(fpath, fcontents)
118
119 # Is there a #define? Is it the same as the #ifndef one?
120 match = self.define_re.search(fcontents)
121 if match.lastindex is None:
122 # No define. Request manual addition with hints
123 self.fail(fpath, match.re, match.string, '', '', False)
124 return False # failed
125
126 # Is the #define guard the same as the #ifndef guard?
127 if match.group(1) != running_guard:
128 fcontents = self.fail(fpath, match.re, match.string, match.group(1),
129 valid_guard, fix)
130 if fix:
131 save(fpath, fcontents)
132
133 # Is there a properly commented #endif?
134 flines = fcontents.rstrip().splitlines()
135 match = self.endif_c_core_re.search('\n'.join(flines[-3:]))
136 if not match and not c_core_header:
137 match = self.endif_re.search('\n'.join(flines[-3:]))
138 if not match:
139 # No endif. Check if we have the last line as just '#endif' and if so
140 # replace it with a properly commented one.
141 if flines[-1] == '#endif':
142 flines[-1] = (
143 '#endif' +
144 (' /* {} */\n'.format(valid_guard)
145 if c_core_header else ' // {}\n'.format(valid_guard)))
146 if fix:
147 fcontents = '\n'.join(flines)
148 save(fpath, fcontents)
149 else:
150 # something else is wrong, bail out
151 self.fail(
152 fpath,
153 self.endif_c_core_re if c_core_header else self.endif_re,
154 flines[-1], '', '', False)
155 elif match.group(1) != running_guard:
156 # Is the #endif guard the same as the #ifndef and #define guards?
157 fcontents = self.fail(fpath, self.endif_re, fcontents,
158 match.group(1), valid_guard, fix)
159 if fix:
160 save(fpath, fcontents)
161
162 match = self.comments_then_includes_re.search(fcontents)
163 assert (match)
164 bad_includes = match.group(3)
165 if bad_includes:
166 print(
167 "includes after initial comments but before include guards in",
168 fpath)
169 if fix:
170 fcontents = fcontents[:match.start(3)] + match.group(
171 5) + match.group(3) + fcontents[match.end(5):]
172 save(fpath, fcontents)
173
174 return not self.failed # Did the check succeed? (ie, not failed)
175
176
177 # find our home
178 ROOT = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), '../..'))
179 os.chdir(ROOT)
180
181 # parse command line
182 argp = argparse.ArgumentParser(description='include guard checker')
183 argp.add_argument('-f', '--fix', default=False, action='store_true')
184 argp.add_argument('--precommit', default=False, action='store_true')
185 args = argp.parse_args()
186
187 grep_filter = r"grep -E '^(include|src/core)/.*\.h$'"
188 if args.precommit:
189 git_command = 'git diff --name-only HEAD'
190 else:
191 git_command = 'git ls-tree -r --name-only -r HEAD'
192
193 FILE_LIST_COMMAND = ' | '.join((git_command, grep_filter))
194
195 # scan files
196 ok = True
197 filename_list = []
198 try:
199 filename_list = subprocess.check_output(FILE_LIST_COMMAND,
200 shell=True).decode().splitlines()
201 # Filter out non-existent files (ie, file removed or renamed)
202 filename_list = (f for f in filename_list if os.path.isfile(f))
203 except subprocess.CalledProcessError:
204 sys.exit(0)
205
206 validator = GuardValidator()
207
208 for filename in filename_list:
209 # Skip check for upb generated code.
210 if (filename.endswith('.upb.h') or filename.endswith('.upb.c') or
211 filename.endswith('.upbdefs.h') or filename.endswith('.upbdefs.c')):
212 continue
213 ok = ok and validator.check(filename, args.fix)
214
215 sys.exit(0 if ok else 1)