check_naked_includes.py
Go to the documentation of this file.
1 #!/usr/bin/env python3
2 
3 # Copyright 2022 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 # Check for includes of the form `#include "bar.h"` - i.e. not including the subdirectory. We require instead `#include "foo/bar.h"`.
18 
19 import argparse
20 import os
21 import re
22 import sys
23 
24 # find our home
25 ROOT = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), '../..'))
26 os.chdir(ROOT)
27 
28 # parse command line
29 argp = argparse.ArgumentParser(description='include guard checker')
30 argp.add_argument('-f', '--fix', default=False, action='store_true')
31 args = argp.parse_args()
32 
33 # error count
34 errors = 0
35 
36 CHECK_SUBDIRS = [
37  'src/core',
38  'src/cpp',
39  'test/core',
40  'test/cpp',
41 ]
42 
43 for subdir in CHECK_SUBDIRS:
44  for root, dirs, files in os.walk(subdir):
45  for f in files:
46  if f.endswith('.h') or f.endswith('.cc'):
47  fpath = os.path.join(root, f)
48  output = open(fpath, 'r').readlines()
49  changed = False
50  for (i, line) in enumerate(output):
51  m = re.match(r'^#include "([^"]*)"(.*)', line)
52  if not m:
53  continue
54  include = m.group(1)
55  if '/' in include:
56  continue
57  expect_path = os.path.join(root, include)
58  trailing = m.group(2)
59  if not os.path.exists(expect_path):
60  continue
61  changed = True
62  errors += 1
63  output[i] = '#include "{0}"{1}\n'.format(
64  expect_path, trailing)
65  print("Found naked include '{0}' in {1}".format(
66  include, fpath))
67  if changed and args.fix:
68  open(fpath, 'w').writelines(output)
69 
70 if errors > 0:
71  print('{} errors found.'.format(errors))
72  sys.exit(1)
http2_test_server.format
format
Definition: http2_test_server.py:118
open
#define open
Definition: test-fs.c:46


grpc
Author(s):
autogenerated on Fri May 16 2025 02:57:53