check_rules_yml.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. #!/usr/bin/env python
  2. #
  3. # SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD
  4. # SPDX-License-Identifier: Apache-2.0
  5. """
  6. Check if all rules in rules.yml used or not in CI yaml files.
  7. """
  8. import argparse
  9. import os
  10. import re
  11. import sys
  12. from copy import deepcopy
  13. from typing import Any, Dict, List, Optional, Set, Union
  14. import yaml
  15. from idf_ci_utils import IDF_PATH
  16. ROOT_YML_FP = os.path.join(IDF_PATH, '.gitlab-ci.yml')
  17. def load_yaml(file_path: str) -> Any:
  18. return yaml.load(open(file_path), Loader=yaml.FullLoader)
  19. class YMLConfig:
  20. def __init__(self, root_yml_file_path: str) -> None:
  21. self._config: Optional[Dict] = None
  22. self._all_extends: Optional[Set] = None
  23. self.root_yml = load_yaml(root_yml_file_path)
  24. assert self.root_yml
  25. @staticmethod
  26. def _list(str_or_list: Union[str, List]) -> List:
  27. if isinstance(str_or_list, str):
  28. return [str_or_list]
  29. if isinstance(str_or_list, list):
  30. return str_or_list
  31. raise ValueError(
  32. 'Wrong type: {}. Only supports str or list.'.format(type(str_or_list))
  33. )
  34. @property
  35. def config(self) -> Dict:
  36. if self._config:
  37. return self._config
  38. all_config = dict()
  39. for item in self.root_yml['include']:
  40. all_config.update(load_yaml(os.path.join(IDF_PATH, item)))
  41. self._config = all_config
  42. return self._config
  43. @property
  44. def all_extends(self) -> Set:
  45. if self._all_extends:
  46. return self._all_extends
  47. res = set([])
  48. for v in self.config.values():
  49. if 'extends' in v:
  50. for item in self._list(v['extends']):
  51. if item.startswith('.rules:'):
  52. res.add(item)
  53. self._all_extends = res
  54. return self._all_extends
  55. def exists(self, key: str) -> bool:
  56. if key in self.all_extends:
  57. return True
  58. return False
  59. YML_CONFIG = YMLConfig(ROOT_YML_FP)
  60. def get_needed_rules() -> Set[str]:
  61. return deepcopy(YML_CONFIG.all_extends)
  62. def validate_needed_rules(rules_yml: 'os.PathLike[str]') -> int:
  63. res = 0
  64. needed_rules = deepcopy(YML_CONFIG.all_extends)
  65. with open(rules_yml) as fr:
  66. for index, line in enumerate(fr):
  67. if line.startswith('.rules:'):
  68. key = line.strip().rsplit(':', 1)[0]
  69. if not YML_CONFIG.exists(key):
  70. print(
  71. '{}:{}:WARNING:rule "{}" unused'.format(rules_yml, index, key)
  72. )
  73. else:
  74. needed_rules.remove(key)
  75. if needed_rules:
  76. for item in needed_rules:
  77. print('ERROR: missing rule: "{}"'.format(item))
  78. res = 1
  79. if res == 0:
  80. print('Pass')
  81. return res
  82. def parse_submodule_paths(
  83. gitsubmodules: str = os.path.join(IDF_PATH, '.gitmodules')
  84. ) -> List[str]:
  85. path_regex = re.compile(r'^\s+path = (.+)$', re.MULTILINE)
  86. with open(gitsubmodules, 'r') as f:
  87. data = f.read()
  88. res = []
  89. for item in path_regex.finditer(data):
  90. res.append(item.group(1))
  91. return res
  92. def validate_submodule_patterns() -> int:
  93. submodule_paths = sorted(['.gitmodules'] + parse_submodule_paths())
  94. submodule_paths_in_patterns = sorted(
  95. YML_CONFIG.config.get('.patterns-submodule', [])
  96. )
  97. res = 0
  98. if submodule_paths != submodule_paths_in_patterns:
  99. res = 1
  100. print('please update the pattern ".patterns-submodule"')
  101. should_remove = set(submodule_paths_in_patterns) - set(submodule_paths)
  102. if should_remove:
  103. print(f'- should remove: {should_remove}')
  104. should_add = set(submodule_paths) - set(submodule_paths_in_patterns)
  105. if should_add:
  106. print(f'- should add: {should_add}')
  107. return res
  108. if __name__ == '__main__':
  109. parser = argparse.ArgumentParser(description=__doc__)
  110. parser.add_argument(
  111. 'rules_yml',
  112. nargs='?',
  113. default=os.path.join(IDF_PATH, '.gitlab', 'ci', 'rules.yml'),
  114. help='rules.yml file path',
  115. )
  116. args = parser.parse_args()
  117. exit_code = 0
  118. if validate_needed_rules(args.rules_yml):
  119. exit_code = 1
  120. if validate_submodule_patterns():
  121. exit_code = 1
  122. sys.exit(exit_code)