blob: 9c23a70e001e8311466b747e047ebc5bc5798bb8 [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 Quintas3c5def52016-03-17 22:26:22 -0700101 if match.lastindex is None:
David Garcia Quintas7d538362016-03-15 14:51:29 -0700102 # No ifndef. Request manual addition with hints
103 self.fail(fpath, match.re, match.string, '', '', False)
David Garcia Quintas3c5def52016-03-17 22:26:22 -0700104 return False # failed
David Garcia Quintas7d538362016-03-15 14:51:29 -0700105
106 # Does the guard end with a '_H'?
107 running_guard = match.group(1)
108 if not running_guard.endswith('_H'):
109 fcontents = self.fail(fpath, match.re, match.string, match.group(1),
110 valid_guard, fix)
David Garcia Quintas3c5def52016-03-17 22:26:22 -0700111 if fix: save(fpath, fcontents)
David Garcia Quintas7d538362016-03-15 14:51:29 -0700112
113 # Is it the expected one based on the file path?
114 if running_guard != valid_guard:
115 fcontents = self.fail(fpath, match.re, match.string, match.group(1),
116 valid_guard, fix)
David Garcia Quintas3c5def52016-03-17 22:26:22 -0700117 if fix: save(fpath, fcontents)
David Garcia Quintas7d538362016-03-15 14:51:29 -0700118
119 # Is there a #define? Is it the same as the #ifndef one?
120 match = self.define_re.search(fcontents)
David Garcia Quintas3c5def52016-03-17 22:26:22 -0700121 if match.lastindex is None:
David Garcia Quintas7d538362016-03-15 14:51:29 -0700122 # No define. Request manual addition with hints
123 self.fail(fpath, match.re, match.string, '', '', False)
David Garcia Quintas3c5def52016-03-17 22:26:22 -0700124 return False # failed
David Garcia Quintas7d538362016-03-15 14:51:29 -0700125
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)
David Garcia Quintas3c5def52016-03-17 22:26:22 -0700130 if fix: save(fpath, fcontents)
David Garcia Quintas7d538362016-03-15 14:51:29 -0700131
132 # Is there a properly commented #endif?
133 endif_re = self.endif_cpp_re if cpp_header else self.endif_c_re
David Garcia Quintas3c5def52016-03-17 22:26:22 -0700134 flines = fcontents.rstrip().splitlines()
David Garcia Quintas93466162016-05-12 16:41:27 -0700135 match = endif_re.search('\n'.join(flines[-2:]))
David Garcia Quintas3c5def52016-03-17 22:26:22 -0700136 if not match:
David Garcia Quintas7d538362016-03-15 14:51:29 -0700137 # No endif. Check if we have the last line as just '#endif' and if so
138 # replace it with a properly commented one.
David Garcia Quintas7d538362016-03-15 14:51:29 -0700139 if flines[-1] == '#endif':
140 flines[-1] = ('#endif' +
141 (' // {}\n'.format(valid_guard) if cpp_header
142 else ' /* {} */\n'.format(valid_guard)))
David Garcia Quintas3c5def52016-03-17 22:26:22 -0700143 if fix:
144 fcontents = '\n'.join(flines)
145 save(fpath, fcontents)
David Garcia Quintas7d538362016-03-15 14:51:29 -0700146 else:
147 # something else is wrong, bail out
David Garcia Quintas37266f32016-03-18 10:14:14 -0700148 self.fail(fpath, endif_re, flines[-1], '', '', False)
David Garcia Quintas3c5def52016-03-17 22:26:22 -0700149 elif match.group(1) != running_guard:
David Garcia Quintas7d538362016-03-15 14:51:29 -0700150 # Is the #endif guard the same as the #ifndef and #define guards?
David Garcia Quintas37266f32016-03-18 10:14:14 -0700151 fcontents = self.fail(fpath, endif_re, fcontents, match.group(1),
David Garcia Quintas7d538362016-03-15 14:51:29 -0700152 valid_guard, fix)
David Garcia Quintas3c5def52016-03-17 22:26:22 -0700153 if fix: save(fpath, fcontents)
David Garcia Quintas7d538362016-03-15 14:51:29 -0700154
155 return not self.failed # Did the check succeed? (ie, not failed)
156
157# find our home
158ROOT = os.path.abspath(
159 os.path.join(os.path.dirname(sys.argv[0]), '../..'))
160os.chdir(ROOT)
161
162# parse command line
163argp = argparse.ArgumentParser(description='include guard checker')
164argp.add_argument('-f', '--fix',
165 default=False,
166 action='store_true');
167argp.add_argument('--precommit',
168 default=False,
169 action='store_true')
170args = argp.parse_args()
171
172KNOWN_BAD = set([
David Garcia Quintas7f0793a2016-04-25 12:35:58 -0700173 'src/core/ext/lb_policy/grpclb/proto/grpc/lb/v1/load_balancer.pb.h',
David Garcia Quintas7d538362016-03-15 14:51:29 -0700174])
175
176
177grep_filter = r"grep -E '^(include|src/core)/.*\.h$'"
178if args.precommit:
179 git_command = 'git diff --name-only HEAD'
180else:
181 git_command = 'git ls-tree -r --name-only -r HEAD'
182
183FILE_LIST_COMMAND = ' | '.join((git_command, grep_filter))
184
185# scan files
186ok = True
187filename_list = []
188try:
189 filename_list = subprocess.check_output(FILE_LIST_COMMAND,
190 shell=True).splitlines()
David Garcia Quintasc74f62b2016-04-28 00:56:31 -0700191 # Filter out non-existent files (ie, file removed or renamed)
192 filename_list = (f for f in filename_list if os.path.isfile(f))
David Garcia Quintas7d538362016-03-15 14:51:29 -0700193except subprocess.CalledProcessError:
194 sys.exit(0)
195
196validator = GuardValidator()
197
198for filename in filename_list:
199 if filename in KNOWN_BAD: continue
200 ok = validator.check(filename, args.fix)
201
202sys.exit(0 if ok else 1)