check_package_name.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #!/usr/bin/env python3
  2. # Copyright 2021 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 os
  16. import sys
  17. os.chdir(os.path.join(os.path.dirname(sys.argv[0]), '../../..'))
  18. # Allowance for overrides for specific files
  19. EXPECTED_NAMES = {
  20. 'src/proto/grpc/channelz': 'channelz',
  21. 'src/proto/grpc/status': 'status',
  22. 'src/proto/grpc/testing': 'testing',
  23. 'src/proto/grpc/testing/duplicate': 'duplicate',
  24. 'src/proto/grpc/lb/v1': 'lb',
  25. 'src/proto/grpc/testing/xds': 'xds',
  26. 'src/proto/grpc/testing/xds/v3': 'xds_v3',
  27. 'src/proto/grpc/core': 'core',
  28. 'src/proto/grpc/health/v1': 'health',
  29. 'src/proto/grpc/reflection/v1alpha': 'reflection',
  30. 'src/proto/grpc/reflection/v1': 'reflection_v1',
  31. }
  32. errors = 0
  33. for root, dirs, files in os.walk('.'):
  34. if root.startswith('./'):
  35. root = root[len('./'):]
  36. # don't check third party
  37. if root.startswith('third_party/'):
  38. continue
  39. # only check BUILD files
  40. if 'BUILD' not in files:
  41. continue
  42. text = open('%s/BUILD' % root).read()
  43. # find a grpc_package clause
  44. pkg_start = text.find('grpc_package(')
  45. if pkg_start == -1:
  46. continue
  47. # parse it, taking into account nested parens
  48. pkg_end = pkg_start + len('grpc_package(')
  49. level = 1
  50. while level == 1:
  51. if text[pkg_end] == ')':
  52. level -= 1
  53. elif text[pkg_end] == '(':
  54. level += 1
  55. pkg_end += 1
  56. # it's a python statement, so evaluate it to pull out the name of the package
  57. name = eval(text[pkg_start:pkg_end],
  58. {'grpc_package': lambda name, **kwargs: name})
  59. # the name should be the path within the source tree, excepting some special
  60. # BUILD files (really we should normalize them too at some point)
  61. # TODO(ctiller): normalize all package names
  62. expected_name = EXPECTED_NAMES.get(root, root)
  63. if name != expected_name:
  64. print("%s/BUILD should define a grpc_package with name=%r, not %r" %
  65. (root, expected_name, name))
  66. errors += 1
  67. if errors != 0:
  68. sys.exit(1)