check_include_style.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 re
  17. import sys
  18. os.chdir(os.path.join(os.path.dirname(sys.argv[0]), '../../..'))
  19. BAD_REGEXES = [
  20. (r'\n#include "include/(.*)"', r'\n#include <\1>'),
  21. (r'\n#include "grpc(.*)"', r'\n#include <grpc\1>'),
  22. ]
  23. fix = sys.argv[1:] == ['--fix']
  24. if fix:
  25. print("FIXING!")
  26. def check_include_style(directory_root):
  27. bad_files = []
  28. for root, dirs, files in os.walk(directory_root):
  29. for filename in files:
  30. path = os.path.join(root, filename)
  31. if os.path.splitext(path)[1] not in ['.c', '.cc', '.h']:
  32. continue
  33. if filename.endswith('.pb.h') or filename.endswith('.pb.c'):
  34. continue
  35. # Skip check for upb generated code.
  36. if (filename.endswith('.upb.h') or filename.endswith('.upb.c') or
  37. filename.endswith('.upbdefs.h') or
  38. filename.endswith('.upbdefs.c')):
  39. continue
  40. with open(path) as f:
  41. text = f.read()
  42. original = text
  43. for regex, replace in BAD_REGEXES:
  44. text = re.sub(regex, replace, text)
  45. if text != original:
  46. bad_files.append(path)
  47. if fix:
  48. with open(path, 'w') as f:
  49. f.write(text)
  50. return bad_files
  51. all_bad_files = []
  52. all_bad_files += check_include_style(os.path.join('src', 'core'))
  53. all_bad_files += check_include_style(os.path.join('src', 'cpp'))
  54. all_bad_files += check_include_style(os.path.join('test', 'core'))
  55. all_bad_files += check_include_style(os.path.join('test', 'cpp'))
  56. all_bad_files += check_include_style(os.path.join('include', 'grpc'))
  57. all_bad_files += check_include_style(os.path.join('include', 'grpcpp'))
  58. if all_bad_files:
  59. for f in all_bad_files:
  60. print("%s has badly formed grpc system header files" % f)
  61. sys.exit(1)