check_rules_yml.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2021 Espressif Systems (Shanghai) CO LTD
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """
  17. Check if all rules in rules.yml used or not in CI yaml files.
  18. """
  19. import argparse
  20. import os
  21. import sys
  22. from copy import deepcopy
  23. import yaml
  24. from idf_ci_utils import IDF_PATH
  25. ROOT_YML_FP = os.path.join(IDF_PATH, '.gitlab-ci.yml')
  26. def load_yaml(file_path):
  27. return yaml.load(open(file_path), Loader=yaml.FullLoader)
  28. class YMLConfig:
  29. def __init__(self, root_yml_file_path):
  30. self._config = None
  31. self._all_extends = None
  32. self.root_yml = load_yaml(root_yml_file_path)
  33. assert self.root_yml
  34. @staticmethod
  35. def _list(str_or_list):
  36. if isinstance(str_or_list, str):
  37. return [str_or_list]
  38. if isinstance(str_or_list, list):
  39. return str_or_list
  40. raise ValueError('Wrong type: {}. Only supports str or list.'.format(type(str_or_list)))
  41. @property
  42. def config(self):
  43. if self._config:
  44. return self._config
  45. all_config = dict()
  46. for item in self.root_yml['include']:
  47. if not item.endswith('rules.yml'):
  48. all_config.update(load_yaml(os.path.join(IDF_PATH, item)))
  49. self._config = all_config
  50. return self._config
  51. @property
  52. def all_extends(self):
  53. if self._all_extends:
  54. return self._all_extends
  55. res = set([])
  56. for v in self.config.values():
  57. if 'extends' in v:
  58. for item in self._list(v['extends']):
  59. if item.startswith('.rules:'):
  60. res.add(item)
  61. self._all_extends = res
  62. return self._all_extends
  63. def exists(self, key):
  64. if key in self.all_extends:
  65. return True
  66. return False
  67. def validate(rules_yml):
  68. yml_config = YMLConfig(ROOT_YML_FP)
  69. res = 0
  70. needed_rules = deepcopy(yml_config.all_extends)
  71. with open(rules_yml) as fr:
  72. for index, line in enumerate(fr):
  73. if line.startswith('.rules:'):
  74. key = line.strip().rsplit(':', 1)[0]
  75. if not yml_config.exists(key):
  76. print('{}:{}:WARNING:rule "{}" unused'.format(rules_yml, index, key))
  77. else:
  78. needed_rules.remove(key)
  79. if needed_rules:
  80. for item in needed_rules:
  81. print('ERROR: missing rule: "{}"'.format(item))
  82. res = 1
  83. if res == 0:
  84. print('Pass')
  85. return res
  86. if __name__ == '__main__':
  87. parser = argparse.ArgumentParser(description=__doc__)
  88. parser.add_argument('rules_yml', nargs='?', default=os.path.join(IDF_PATH, '.gitlab', 'ci', 'rules.yml'),
  89. help='rules.yml file path')
  90. args = parser.parse_args()
  91. sys.exit(validate(args.rules_yml))