check_naked_includes.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #!/usr/bin/env python3
  2. # Copyright 2022 gRPC authors.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. # Check for includes of the form `#include "bar.h"` - i.e. not including the subdirectory. We require instead `#include "foo/bar.h"`.
  16. import argparse
  17. import os
  18. import re
  19. import sys
  20. # find our home
  21. ROOT = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), '../..'))
  22. os.chdir(ROOT)
  23. # parse command line
  24. argp = argparse.ArgumentParser(description='include guard checker')
  25. argp.add_argument('-f', '--fix', default=False, action='store_true')
  26. args = argp.parse_args()
  27. # error count
  28. errors = 0
  29. CHECK_SUBDIRS = [
  30. 'src/core',
  31. 'src/cpp',
  32. 'test/core',
  33. 'test/cpp',
  34. ]
  35. for subdir in CHECK_SUBDIRS:
  36. for root, dirs, files in os.walk(subdir):
  37. for f in files:
  38. if f.endswith('.h') or f.endswith('.cc'):
  39. fpath = os.path.join(root, f)
  40. output = open(fpath, 'r').readlines()
  41. changed = False
  42. for (i, line) in enumerate(output):
  43. m = re.match(r'^#include "([^"]*)"(.*)', line)
  44. if not m:
  45. continue
  46. include = m.group(1)
  47. if '/' in include:
  48. continue
  49. expect_path = os.path.join(root, include)
  50. trailing = m.group(2)
  51. if not os.path.exists(expect_path):
  52. continue
  53. changed = True
  54. errors += 1
  55. output[i] = '#include "{0}"{1}\n'.format(
  56. expect_path, trailing)
  57. print("Found naked include '{0}' in {1}".format(
  58. include, fpath))
  59. if changed and args.fix:
  60. open(fpath, 'w').writelines(output)
  61. if errors > 0:
  62. print('{} errors found.'.format(errors))
  63. sys.exit(1)