blob: 56b2924a1ac5180ab06f13975bf4e3da8cb76271 [file] [log] [blame]
David Garcia Quintas7d538362016-03-15 14:51:29 -07001#!/usr/bin/env python2.7
2
3# Copyright 2016, Google Inc.
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met:
9#
10# * Redistributions of source code must retain the above copyright
11# notice, this list of conditions and the following disclaimer.
12# * Redistributions in binary form must reproduce the above
13# copyright notice, this list of conditions and the following disclaimer
14# in the documentation and/or other materials provided with the
15# distribution.
16# * Neither the name of Google Inc. nor the names of its
17# contributors may be used to endorse or promote products derived from
18# this software without specific prior written permission.
19#
20# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
32import argparse
33import os
David Garcia Quintasc74f62b2016-04-28 00:56:31 -070034import os.path
David Garcia Quintas7d538362016-03-15 14:51:29 -070035import re
36import sys
37import subprocess
38
39
40def build_valid_guard(fpath):
41 prefix = 'GRPC_' if not fpath.startswith('include/') else ''
42 return prefix + '_'.join(fpath.replace('++', 'XX').replace('.', '_').upper().split('/')[1:])
43
44
45def load(fpath):
46 with open(fpath, 'r') as f:
47 return f.read()
48
49
50def save(fpath, contents):
51 with open(fpath, 'w') as f:
52 f.write(contents)
53
54
55class GuardValidator(object):
56 def __init__(self):
57 self.ifndef_re = re.compile(r'#ifndef ([A-Z][A-Z_1-9]*)')
58 self.define_re = re.compile(r'#define ([A-Z][A-Z_1-9]*)')
David Garcia Quintas93466162016-05-12 16:41:27 -070059 self.endif_c_re = re.compile(r'#endif /\* ([A-Z][A-Z_1-9]*) (?:\\ *\n *)?\*/')
David Garcia Quintas7d538362016-03-15 14:51:29 -070060 self.endif_cpp_re = re.compile(r'#endif // ([A-Z][A-Z_1-9]*)')
61 self.failed = False
62
63 def fail(self, fpath, regexp, fcontents, match_txt, correct, fix):
64 cpp_header = 'grpc++' in fpath
65 self.failed = True
66 invalid_guards_msg_template = (
67 '{0}: Missing preprocessor guards (RE {1}). '
68 'Please wrap your code around the following guards:\n'
69 '#ifndef {2}\n'
70 '#define {2}\n'
71 '...\n'
72 '... epic code ...\n'
73 '...\n') + ('#endif // {2}' if cpp_header else '#endif /* {2} */')
74 if not match_txt:
75 print invalid_guards_msg_template.format(fpath, regexp.pattern,
76 build_valid_guard(fpath))
77 return fcontents
78
79 print ('{}: Wrong preprocessor guards (RE {}):'
80 '\n\tFound {}, expected {}').format(
81 fpath, regexp.pattern, match_txt, correct)
82 if fix:
83 print 'Fixing {}...\n'.format(fpath)
84 fixed_fcontents = re.sub(match_txt, correct, fcontents)
85 if fixed_fcontents:
86 self.failed = False
87 return fixed_fcontents
88 else:
89 print
90 return fcontents
91
92 def check(self, fpath, fix):
93 cpp_header = 'grpc++' in fpath
94 valid_guard = build_valid_guard(fpath)
95
96 fcontents = load(fpath)
97
98 match = self.ifndef_re.search(fcontents)
Craig Tiller666a3622016-04-12 13:46:30 -070099 if not match:
100 print 'something drastically wrong with: %s' % fpath
David Garcia Quintas267684c2016-04-27 18:32:04 -0700101 return False # failed
David Garcia Quintas3c5def52016-03-17 22:26:22 -0700102 if match.lastindex is None:
David Garcia Quintas7d538362016-03-15 14:51:29 -0700103 # No ifndef. Request manual addition with hints
104 self.fail(fpath, match.re, match.string, '', '', False)
David Garcia Quintas3c5def52016-03-17 22:26:22 -0700105 return False # failed
David Garcia Quintas7d538362016-03-15 14:51:29 -0700106
107 # Does the guard end with a '_H'?
108 running_guard = match.group(1)
109 if not running_guard.endswith('_H'):
110 fcontents = self.fail(fpath, match.re, match.string, match.group(1),
111 valid_guard, fix)
David Garcia Quintas3c5def52016-03-17 22:26:22 -0700112 if fix: save(fpath, fcontents)
David Garcia Quintas7d538362016-03-15 14:51:29 -0700113
114 # Is it the expected one based on the file path?
115 if running_guard != valid_guard:
116 fcontents = self.fail(fpath, match.re, match.string, match.group(1),
117 valid_guard, fix)
David Garcia Quintas3c5def52016-03-17 22:26:22 -0700118 if fix: save(fpath, fcontents)
David Garcia Quintas7d538362016-03-15 14:51:29 -0700119
120 # Is there a #define? Is it the same as the #ifndef one?
121 match = self.define_re.search(fcontents)
David Garcia Quintas3c5def52016-03-17 22:26:22 -0700122 if match.lastindex is None:
David Garcia Quintas7d538362016-03-15 14:51:29 -0700123 # No define. Request manual addition with hints
124 self.fail(fpath, match.re, match.string, '', '', False)
David Garcia Quintas3c5def52016-03-17 22:26:22 -0700125 return False # failed
David Garcia Quintas7d538362016-03-15 14:51:29 -0700126
127 # Is the #define guard the same as the #ifndef guard?
128 if match.group(1) != running_guard:
129 fcontents = self.fail(fpath, match.re, match.string, match.group(1),
130 valid_guard, fix)
David Garcia Quintas3c5def52016-03-17 22:26:22 -0700131 if fix: save(fpath, fcontents)
David Garcia Quintas7d538362016-03-15 14:51:29 -0700132
133 # Is there a properly commented #endif?
134 endif_re = self.endif_cpp_re if cpp_header else self.endif_c_re
David Garcia Quintas3c5def52016-03-17 22:26:22 -0700135 flines = fcontents.rstrip().splitlines()
David Garcia Quintas93466162016-05-12 16:41:27 -0700136 match = endif_re.search('\n'.join(flines[-2:]))
David Garcia Quintas3c5def52016-03-17 22:26:22 -0700137 if not match:
David Garcia Quintas7d538362016-03-15 14:51:29 -0700138 # No endif. Check if we have the last line as just '#endif' and if so
139 # replace it with a properly commented one.
David Garcia Quintas7d538362016-03-15 14:51:29 -0700140 if flines[-1] == '#endif':
141 flines[-1] = ('#endif' +
142 (' // {}\n'.format(valid_guard) if cpp_header
143 else ' /* {} */\n'.format(valid_guard)))
David Garcia Quintas3c5def52016-03-17 22:26:22 -0700144 if fix:
145 fcontents = '\n'.join(flines)
146 save(fpath, fcontents)
David Garcia Quintas7d538362016-03-15 14:51:29 -0700147 else:
148 # something else is wrong, bail out
David Garcia Quintas37266f32016-03-18 10:14:14 -0700149 self.fail(fpath, endif_re, flines[-1], '', '', False)
David Garcia Quintas3c5def52016-03-17 22:26:22 -0700150 elif match.group(1) != running_guard:
David Garcia Quintas7d538362016-03-15 14:51:29 -0700151 # Is the #endif guard the same as the #ifndef and #define guards?
David Garcia Quintas37266f32016-03-18 10:14:14 -0700152 fcontents = self.fail(fpath, endif_re, fcontents, match.group(1),
David Garcia Quintas7d538362016-03-15 14:51:29 -0700153 valid_guard, fix)
David Garcia Quintas3c5def52016-03-17 22:26:22 -0700154 if fix: save(fpath, fcontents)
David Garcia Quintas7d538362016-03-15 14:51:29 -0700155
156 return not self.failed # Did the check succeed? (ie, not failed)
157
158# find our home
159ROOT = os.path.abspath(
160 os.path.join(os.path.dirname(sys.argv[0]), '../..'))
161os.chdir(ROOT)
162
163# parse command line
164argp = argparse.ArgumentParser(description='include guard checker')
165argp.add_argument('-f', '--fix',
166 default=False,
167 action='store_true');
168argp.add_argument('--precommit',
169 default=False,
170 action='store_true')
171args = argp.parse_args()
172
173KNOWN_BAD = set([
David Garcia Quintas7f0793a2016-04-25 12:35:58 -0700174 'src/core/ext/lb_policy/grpclb/proto/grpc/lb/v1/load_balancer.pb.h',
Yuchen Zeng7ae31a82016-06-06 14:21:11 -0700175 'include/grpc++/ext/reflection.grpc.pb.h',
176 'include/grpc++/ext/reflection.pb.h',
David Garcia Quintas7d538362016-03-15 14:51:29 -0700177])
178
179
180grep_filter = r"grep -E '^(include|src/core)/.*\.h$'"
181if args.precommit:
182 git_command = 'git diff --name-only HEAD'
183else:
184 git_command = 'git ls-tree -r --name-only -r HEAD'
185
186FILE_LIST_COMMAND = ' | '.join((git_command, grep_filter))
187
188# scan files
189ok = True
190filename_list = []
191try:
192 filename_list = subprocess.check_output(FILE_LIST_COMMAND,
193 shell=True).splitlines()
David Garcia Quintasc74f62b2016-04-28 00:56:31 -0700194 # Filter out non-existent files (ie, file removed or renamed)
195 filename_list = (f for f in filename_list if os.path.isfile(f))
David Garcia Quintas7d538362016-03-15 14:51:29 -0700196except subprocess.CalledProcessError:
197 sys.exit(0)
198
199validator = GuardValidator()
200
201for filename in filename_list:
202 if filename in KNOWN_BAD: continue
203 ok = validator.check(filename, args.fix)
204
205sys.exit(0 if ok else 1)