check_codeowners.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. #!/usr/bin/env python
  2. #
  3. # Utility script for ESP-IDF developers to work with the CODEOWNERS file.
  4. #
  5. # SPDX-FileCopyrightText: 2020-2021 Espressif Systems (Shanghai) CO LTD
  6. # SPDX-License-Identifier: Apache-2.0
  7. import argparse
  8. import os
  9. import re
  10. import subprocess
  11. import sys
  12. from idf_ci_utils import IDF_PATH
  13. CODEOWNERS_PATH = os.path.join(IDF_PATH, '.gitlab', 'CODEOWNERS')
  14. CODEOWNER_GROUP_PREFIX = '@esp-idf-codeowners/'
  15. def get_all_files():
  16. """
  17. Get list of all file paths in the repository.
  18. """
  19. # only split on newlines, since file names may contain spaces
  20. return subprocess.check_output(['git', 'ls-files'], cwd=IDF_PATH).decode('utf-8').strip().split('\n')
  21. def pattern_to_regex(pattern):
  22. """
  23. Convert the CODEOWNERS path pattern into a regular expression string.
  24. """
  25. orig_pattern = pattern # for printing errors later
  26. # Replicates the logic from normalize_pattern function in Gitlab ee/lib/gitlab/code_owners/file.rb:
  27. if not pattern.startswith('/'):
  28. pattern = '/**/' + pattern
  29. if pattern.endswith('/'):
  30. pattern = pattern + '**/*'
  31. # Convert the glob pattern into a regular expression:
  32. # first into intermediate tokens
  33. pattern = (pattern.replace('**/', ':REGLOB:')
  34. .replace('**', ':INVALID:')
  35. .replace('*', ':GLOB:')
  36. .replace('.', ':DOT:')
  37. .replace('?', ':ANY:'))
  38. if pattern.find(':INVALID:') >= 0:
  39. raise ValueError("Likely invalid pattern '{}': '**' should be followed by '/'".format(orig_pattern))
  40. # then into the final regex pattern:
  41. re_pattern = (pattern.replace(':REGLOB:', '(?:.*/)?')
  42. .replace(':GLOB:', '[^/]*')
  43. .replace(':DOT:', '[.]')
  44. .replace(':ANY:', '.') + '$')
  45. if re_pattern.startswith('/'):
  46. re_pattern = '^' + re_pattern
  47. return re_pattern
  48. def files_by_regex(all_files, regex):
  49. """
  50. Return all files in the repository matching the given regular expresion.
  51. """
  52. return [file for file in all_files if regex.search('/' + file)]
  53. def files_by_pattern(all_files, pattern=None):
  54. """
  55. Return all the files in the repository matching the given CODEOWNERS pattern.
  56. """
  57. if not pattern:
  58. return all_files
  59. return files_by_regex(all_files, re.compile(pattern_to_regex(pattern)))
  60. def action_identify(args):
  61. best_match = []
  62. all_files = get_all_files()
  63. with open(CODEOWNERS_PATH) as f:
  64. for line in f:
  65. line = line.strip()
  66. if not line or line.startswith('#'):
  67. continue
  68. tokens = line.split()
  69. path_pattern = tokens[0]
  70. owners = tokens[1:]
  71. files = files_by_pattern(all_files, path_pattern)
  72. if args.path in files:
  73. best_match = owners
  74. for owner in best_match:
  75. print(owner)
  76. def action_test_pattern(args):
  77. re_pattern = pattern_to_regex(args.pattern)
  78. if args.regex:
  79. print(re_pattern)
  80. return
  81. files = files_by_regex(get_all_files(), re.compile(re_pattern))
  82. for f in files:
  83. print(f)
  84. def action_ci_check(args):
  85. errors = []
  86. def add_error(msg):
  87. errors.append('{}:{}: {}'.format(CODEOWNERS_PATH, line_no, msg))
  88. all_files = get_all_files()
  89. prev_path_pattern = ''
  90. with open(CODEOWNERS_PATH) as f:
  91. for line_no, line in enumerate(f, start=1):
  92. # Skip empty lines and comments
  93. line = line.strip()
  94. if line.startswith('# sort-order-reset'):
  95. prev_path_pattern = ''
  96. if (not line
  97. or line.startswith('#') # comment
  98. or line.startswith('[') # file group
  99. or line.startswith('^[')): # optional file group
  100. continue
  101. # Each line has a form of "<path> <owners>+"
  102. tokens = line.split()
  103. path_pattern = tokens[0]
  104. owners = tokens[1:]
  105. if not owners:
  106. add_error('no owners specified for {}'.format(path_pattern))
  107. # Check that the file is sorted by path patterns
  108. if not in_order(prev_path_pattern, path_pattern):
  109. add_error('file is not sorted: {} < {}'.format(path_pattern, prev_path_pattern))
  110. prev_path_pattern = path_pattern
  111. # Check that the pattern matches at least one file
  112. files = files_by_pattern(all_files, path_pattern)
  113. if not files:
  114. add_error('no files matched by pattern {}'.format(path_pattern))
  115. for o in owners:
  116. # Sanity-check the owner group name
  117. if not o.startswith(CODEOWNER_GROUP_PREFIX):
  118. add_error("owner {} doesn't start with {}".format(o, CODEOWNER_GROUP_PREFIX))
  119. if not errors:
  120. print('No errors found.')
  121. else:
  122. print('Errors found!')
  123. for e in errors:
  124. print(e)
  125. raise SystemExit(1)
  126. def in_order(prev, current):
  127. """
  128. Return True if the ordering is correct for these two lines ('prev' should be before 'current').
  129. Codeowners should be ordered alphabetically, except that order is also significant for the codeowners
  130. syntax (the last matching line has priority).
  131. This means that wildcards are allowed in either order (if wildcard placed first, it's placed before a
  132. more specific pattern as a catch-all fallback. If wildcard placed second, it's to override the match
  133. made on a previous line i.e. '/xyz/**/*.py' to override the owner of the Python files inside /xyz/ ).
  134. """
  135. if not prev:
  136. return True # first element in file
  137. def is_separator(c):
  138. return c in '-_/' # ignore differences between separators for ordering purposes
  139. def is_wildcard(c):
  140. return c in '?*'
  141. # looping until we see a different character
  142. for a,b in zip(prev, current):
  143. if is_separator(a) and is_separator(b):
  144. continue
  145. if is_wildcard(a) or is_wildcard(b):
  146. return True # if the strings matched up to one of them having a wildcard, treat as in order
  147. if a != b:
  148. return b > a
  149. assert a == b
  150. # common substrings up to the common length are the same, so the longer string should be after
  151. return len(current) >= len(prev)
  152. def main():
  153. parser = argparse.ArgumentParser(
  154. sys.argv[0], description='Internal helper script for working with the CODEOWNERS file.'
  155. )
  156. subparsers = parser.add_subparsers(dest='action')
  157. identify = subparsers.add_parser(
  158. 'identify',
  159. help='List the owners of the specified path within IDF.'
  160. "This command doesn't support files inside submodules, or files not added to git repository.",
  161. )
  162. identify.add_argument('path', help='Path of the file relative to the root of the repository')
  163. subparsers.add_parser(
  164. 'ci-check',
  165. help='Check CODEOWNERS file: every line should match at least one file, sanity-check group names, '
  166. 'check that the file is sorted by paths',
  167. )
  168. test_pattern = subparsers.add_parser(
  169. 'test-pattern',
  170. help='Print files in the repository for a given CODEOWNERS pattern. Useful when adding new rules.'
  171. )
  172. test_pattern.add_argument('--regex', action='store_true', help='Print the equivalent regular expression instead of the file list.')
  173. test_pattern.add_argument('pattern', help='Path pattern to get the list of files for')
  174. args = parser.parse_args()
  175. if args.action is None:
  176. parser.print_help()
  177. parser.exit(1)
  178. action_func_name = 'action_' + args.action.replace('-', '_')
  179. action_func = globals()[action_func_name]
  180. action_func(args)
  181. if __name__ == '__main__':
  182. main()