check_rules_yml.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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 sys
  11. from copy import deepcopy
  12. import yaml
  13. from idf_ci_utils import IDF_PATH
  14. ROOT_YML_FP = os.path.join(IDF_PATH, '.gitlab-ci.yml')
  15. def load_yaml(file_path):
  16. return yaml.load(open(file_path), Loader=yaml.FullLoader)
  17. class YMLConfig:
  18. def __init__(self, root_yml_file_path):
  19. self._config = None
  20. self._all_extends = None
  21. self.root_yml = load_yaml(root_yml_file_path)
  22. assert self.root_yml
  23. @staticmethod
  24. def _list(str_or_list):
  25. if isinstance(str_or_list, str):
  26. return [str_or_list]
  27. if isinstance(str_or_list, list):
  28. return str_or_list
  29. raise ValueError('Wrong type: {}. Only supports str or list.'.format(type(str_or_list)))
  30. @property
  31. def config(self):
  32. if self._config:
  33. return self._config
  34. all_config = dict()
  35. for item in self.root_yml['include']:
  36. if not item.endswith('rules.yml'):
  37. all_config.update(load_yaml(os.path.join(IDF_PATH, item)))
  38. self._config = all_config
  39. return self._config
  40. @property
  41. def all_extends(self):
  42. if self._all_extends:
  43. return self._all_extends
  44. res = set([])
  45. for v in self.config.values():
  46. if 'extends' in v:
  47. for item in self._list(v['extends']):
  48. if item.startswith('.rules:'):
  49. res.add(item)
  50. self._all_extends = res
  51. return self._all_extends
  52. def exists(self, key):
  53. if key in self.all_extends:
  54. return True
  55. return False
  56. def validate(rules_yml):
  57. yml_config = YMLConfig(ROOT_YML_FP)
  58. res = 0
  59. needed_rules = deepcopy(yml_config.all_extends)
  60. with open(rules_yml) as fr:
  61. for index, line in enumerate(fr):
  62. if line.startswith('.rules:'):
  63. key = line.strip().rsplit(':', 1)[0]
  64. if not yml_config.exists(key):
  65. print('{}:{}:WARNING:rule "{}" unused'.format(rules_yml, index, key))
  66. else:
  67. needed_rules.remove(key)
  68. if needed_rules:
  69. for item in needed_rules:
  70. print('ERROR: missing rule: "{}"'.format(item))
  71. res = 1
  72. if res == 0:
  73. print('Pass')
  74. return res
  75. if __name__ == '__main__':
  76. parser = argparse.ArgumentParser(description=__doc__)
  77. parser.add_argument('rules_yml', nargs='?', default=os.path.join(IDF_PATH, '.gitlab', 'ci', 'rules.yml'),
  78. help='rules.yml file path')
  79. args = parser.parse_args()
  80. sys.exit(validate(args.rules_yml))