check_namespace_qualification.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  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. import argparse
  16. import os
  17. import os.path
  18. import re
  19. import subprocess
  20. import sys
  21. # TODO(hork): dedupe args/load/validate/save code with other check scripts.
  22. def load(fpath):
  23. with open(fpath, 'r') as f:
  24. return f.readlines()
  25. def save(fpath, contents):
  26. with open(fpath, 'w') as f:
  27. f.write(contents)
  28. class QualificationValidator(object):
  29. def __init__(self):
  30. self.fully_qualified_re = re.compile(r'([ (<])::(grpc[A-Za-z_:])')
  31. self.using_re = re.compile(
  32. r'(using +|using +[A-Za-z_]+ *= *|namespace [A-Za-z_]+ *= *)::')
  33. self.define_re = re.compile(r'^#define')
  34. def check(self, fpath, fix):
  35. fcontents = load(fpath)
  36. failed = False
  37. for (i, line) in enumerate(fcontents):
  38. if not self.fully_qualified_re.search(line):
  39. continue
  40. # skip `using` statements
  41. if self.using_re.search(line):
  42. continue
  43. # skip `#define` statements
  44. if self.define_re.search(line):
  45. continue
  46. # fully-qualified namespace found, which may be unnecessary
  47. if fix:
  48. fcontents[i] = self.fully_qualified_re.sub(r'\1\2', line)
  49. else:
  50. print("Found in %s:%d - %s" % (fpath, i, line.strip()))
  51. failed = True
  52. if fix:
  53. save(fpath, ''.join(fcontents))
  54. return not failed
  55. IGNORED_FILES = [
  56. # TODO(hork): rename symbols to avoid the need for fully-qualified names
  57. "src/cpp/common/core_codegen.cc",
  58. # TODO(hork): This could be a breaking change for users that define their
  59. # own (possibly nested) `grpc.*` namespaces that contain conflicting
  60. # symbols. It may be worth trying to land this change at some point, as
  61. # users would be better off using unique namespaces.
  62. "src/compiler/cpp_generator.cc",
  63. # multi-line #define statements are not handled
  64. "src/core/lib/gprpp/global_config_env.h",
  65. "src/core/lib/profiling/timers.h",
  66. ]
  67. # find our home
  68. ROOT = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), '../..'))
  69. os.chdir(ROOT)
  70. # parse command line
  71. argp = argparse.ArgumentParser(
  72. description='c++ namespace full qualification checker')
  73. argp.add_argument('-f', '--fix', default=False, action='store_true')
  74. argp.add_argument('--precommit', default=False, action='store_true')
  75. args = argp.parse_args()
  76. grep_filter = r"grep -E '^(include|src|test).*\.(h|cc)$'"
  77. if args.precommit:
  78. git_command = 'git diff --name-only HEAD'
  79. else:
  80. git_command = 'git ls-tree -r --name-only -r HEAD'
  81. FILE_LIST_COMMAND = ' | '.join((git_command, grep_filter))
  82. # scan files
  83. ok = True
  84. filename_list = []
  85. try:
  86. filename_list = subprocess.check_output(FILE_LIST_COMMAND,
  87. shell=True).decode().splitlines()
  88. # Filter out non-existent files (ie, file removed or renamed)
  89. filename_list = (f for f in filename_list if os.path.isfile(f))
  90. except subprocess.CalledProcessError:
  91. sys.exit(0)
  92. validator = QualificationValidator()
  93. for filename in filename_list:
  94. # Skip check for upb generated code and ignored files.
  95. if (filename.endswith('.upb.h') or filename.endswith('.upb.c') or
  96. filename.endswith('.upbdefs.h') or
  97. filename.endswith('.upbdefs.c') or filename in IGNORED_FILES):
  98. continue
  99. ok = validator.check(filename, args.fix) and ok
  100. sys.exit(0 if ok else 1)