Imported Upstream version 1.36.0
[platform/upstream/grpc.git] / tools / distrib / check_include_guards.py
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 sys
22 import subprocess
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.failed = False
50
51     def fail(self, fpath, regexp, fcontents, match_txt, correct, fix):
52         c_core_header = 'include' in fpath and not ('grpc++' in fpath or
53                                                     'grpcpp' in fpath)
54         self.failed = True
55         invalid_guards_msg_template = (
56             '{0}: Missing preprocessor guards (RE {1}). '
57             'Please wrap your code around the following guards:\n'
58             '#ifndef {2}\n'
59             '#define {2}\n'
60             '...\n'
61             '... epic code ...\n'
62             '...\n') + ('#endif /* {2} */'
63                         if c_core_header else '#endif  // {2}')
64         if not match_txt:
65             print(
66                 invalid_guards_msg_template.format(fpath, regexp.pattern,
67                                                    build_valid_guard(fpath)))
68             return fcontents
69
70         print(('{}: Wrong preprocessor guards (RE {}):'
71                '\n\tFound {}, expected {}').format(fpath, regexp.pattern,
72                                                    match_txt, correct))
73         if fix:
74             print('Fixing {}...\n'.format(fpath))
75             fixed_fcontents = re.sub(match_txt, correct, fcontents)
76             if fixed_fcontents:
77                 self.failed = False
78             return fixed_fcontents
79         else:
80             print()
81         return fcontents
82
83     def check(self, fpath, fix):
84         c_core_header = 'include' in fpath and not ('grpc++' in fpath or
85                                                     'grpcpp' in fpath)
86         valid_guard = build_valid_guard(fpath)
87
88         fcontents = load(fpath)
89
90         match = self.ifndef_re.search(fcontents)
91         if not match:
92             print('something drastically wrong with: %s' % fpath)
93             return False  # failed
94         if match.lastindex is None:
95             # No ifndef. Request manual addition with hints
96             self.fail(fpath, match.re, match.string, '', '', False)
97             return False  # failed
98
99         # Does the guard end with a '_H'?
100         running_guard = match.group(1)
101         if not running_guard.endswith('_H'):
102             fcontents = self.fail(fpath, match.re, match.string, match.group(1),
103                                   valid_guard, fix)
104             if fix:
105                 save(fpath, fcontents)
106
107         # Is it the expected one based on the file path?
108         if running_guard != valid_guard:
109             fcontents = self.fail(fpath, match.re, match.string, match.group(1),
110                                   valid_guard, fix)
111             if fix:
112                 save(fpath, fcontents)
113
114         # Is there a #define? Is it the same as the #ifndef one?
115         match = self.define_re.search(fcontents)
116         if match.lastindex is None:
117             # No define. Request manual addition with hints
118             self.fail(fpath, match.re, match.string, '', '', False)
119             return False  # failed
120
121         # Is the #define guard the same as the #ifndef guard?
122         if match.group(1) != running_guard:
123             fcontents = self.fail(fpath, match.re, match.string, match.group(1),
124                                   valid_guard, fix)
125             if fix:
126                 save(fpath, fcontents)
127
128         # Is there a properly commented #endif?
129         flines = fcontents.rstrip().splitlines()
130         match = self.endif_c_core_re.search('\n'.join(flines[-3:]))
131         if not match and not c_core_header:
132             match = self.endif_re.search('\n'.join(flines[-3:]))
133         if not match:
134             # No endif. Check if we have the last line as just '#endif' and if so
135             # replace it with a properly commented one.
136             if flines[-1] == '#endif':
137                 flines[-1] = (
138                     '#endif' +
139                     (' /* {} */\n'.format(valid_guard)
140                      if c_core_header else '  // {}\n'.format(valid_guard)))
141                 if fix:
142                     fcontents = '\n'.join(flines)
143                     save(fpath, fcontents)
144             else:
145                 # something else is wrong, bail out
146                 self.fail(
147                     fpath,
148                     self.endif_c_core_re if c_core_header else self.endif_re,
149                     flines[-1], '', '', False)
150         elif match.group(1) != running_guard:
151             # Is the #endif guard the same as the #ifndef and #define guards?
152             fcontents = self.fail(fpath, endif_re, fcontents, match.group(1),
153                                   valid_guard, fix)
154             if fix:
155                 save(fpath, fcontents)
156
157         return not self.failed  # Did the check succeed? (ie, not failed)
158
159
160 # find our home
161 ROOT = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), '../..'))
162 os.chdir(ROOT)
163
164 # parse command line
165 argp = argparse.ArgumentParser(description='include guard checker')
166 argp.add_argument('-f', '--fix', default=False, action='store_true')
167 argp.add_argument('--precommit', default=False, action='store_true')
168 args = argp.parse_args()
169
170 grep_filter = r"grep -E '^(include|src/core)/.*\.h$'"
171 if args.precommit:
172     git_command = 'git diff --name-only HEAD'
173 else:
174     git_command = 'git ls-tree -r --name-only -r HEAD'
175
176 FILE_LIST_COMMAND = ' | '.join((git_command, grep_filter))
177
178 # scan files
179 ok = True
180 filename_list = []
181 try:
182     filename_list = subprocess.check_output(FILE_LIST_COMMAND,
183                                             shell=True).decode().splitlines()
184     # Filter out non-existent files (ie, file removed or renamed)
185     filename_list = (f for f in filename_list if os.path.isfile(f))
186 except subprocess.CalledProcessError:
187     sys.exit(0)
188
189 validator = GuardValidator()
190
191 for filename in filename_list:
192     # Skip check for upb generated code.
193     if (filename.endswith('.upb.h') or filename.endswith('.upb.c') or
194             filename.endswith('.upbdefs.h') or filename.endswith('.upbdefs.c')):
195         continue
196     ok = ok and validator.check(filename, args.fix)
197
198 sys.exit(0 if ok else 1)