check_build_test_rules.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. #!/usr/bin/env python
  2. # SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD
  3. # SPDX-License-Identifier: Apache-2.0
  4. import argparse
  5. import inspect
  6. import os
  7. import re
  8. import sys
  9. from io import StringIO
  10. from pathlib import Path
  11. from typing import Dict, List, Optional, Tuple
  12. from idf_ci_utils import IDF_PATH, get_pytest_cases, get_ttfw_cases
  13. YES = u'\u2713'
  14. NO = u'\u2717'
  15. # | Supported Target | ... |
  16. # | ---------------- | --- |
  17. SUPPORTED_TARGETS_TABLE_REGEX = re.compile(
  18. r'^\|\s*Supported Targets.+$\n^\|(?:\s*|-).+$\n?', re.MULTILINE
  19. )
  20. USUAL_TO_FORMAL = {
  21. 'esp32': 'ESP32',
  22. 'esp32s2': 'ESP32-S2',
  23. 'esp32s3': 'ESP32-S3',
  24. 'esp32c3': 'ESP32-C3',
  25. 'esp32h2': 'ESP32-H2',
  26. 'esp32c2': 'ESP32-C2',
  27. 'linux': 'Linux',
  28. }
  29. FORMAL_TO_USUAL = {
  30. 'ESP32': 'esp32',
  31. 'ESP32-S2': 'esp32s2',
  32. 'ESP32-S3': 'esp32s3',
  33. 'ESP32-C3': 'esp32c3',
  34. 'ESP32-H2': 'esp32h2',
  35. 'ESP32-C2': 'esp32c2',
  36. 'Linux': 'linux',
  37. }
  38. def doublequote(s: str) -> str:
  39. if s.startswith('"') and s.endswith('"'):
  40. return s
  41. return f'"{s}"'
  42. def check_readme(paths: List[str]) -> None:
  43. from idf_build_apps import App, find_apps
  44. from idf_build_apps.constants import SUPPORTED_TARGETS
  45. def get_readme_path(_app: App) -> Optional[str]:
  46. _readme_path = os.path.join(_app.app_dir, 'README.md')
  47. if not os.path.isfile(_readme_path):
  48. _readme_path = os.path.join(_app.app_dir, '..', 'README.md')
  49. if not os.path.isfile(_readme_path):
  50. _readme_path = None # type: ignore
  51. return _readme_path
  52. def _generate_new_support_table_str(_app: App) -> str:
  53. # extra space here
  54. table_headers = [
  55. f'{USUAL_TO_FORMAL[target]}' for target in _app.supported_targets
  56. ]
  57. table_headers = ['Supported Targets'] + table_headers
  58. res = '| ' + ' | '.join(table_headers) + ' |\n'
  59. res += '| ' + ' | '.join(['-' * len(item) for item in table_headers]) + ' |'
  60. return res
  61. def _parse_existing_support_table_str(_app: App) -> Tuple[Optional[str], List[str]]:
  62. _readme_path = get_readme_path(_app)
  63. if not _readme_path:
  64. return None, SUPPORTED_TARGETS
  65. with open(_readme_path) as _fr:
  66. _readme_str = _fr.read()
  67. support_string = SUPPORTED_TARGETS_TABLE_REGEX.findall(_readme_str)
  68. if not support_string:
  69. return None, SUPPORTED_TARGETS
  70. # old style
  71. parts = [
  72. part.strip()
  73. for part in support_string[0].split('\n', 1)[0].split('|')
  74. if part.strip()
  75. ]
  76. return support_string[0].strip(), [FORMAL_TO_USUAL[part] for part in parts[1:]]
  77. def check_enable_build(_app: App, _old_supported_targets: List[str]) -> bool:
  78. if _app.supported_targets == sorted(_old_supported_targets):
  79. return True
  80. _readme_path = get_readme_path(_app)
  81. if_clause = f'IDF_TARGET in [{", ".join([doublequote(target) for target in sorted(_old_supported_targets)])}]'
  82. print(
  83. inspect.cleandoc(
  84. f'''
  85. {_app.app_dir}:
  86. - enable build targets according to the manifest file: {_app.supported_targets}
  87. - enable build targets according to the old Supported Targets table under readme "{_readme_path}": {_old_supported_targets}
  88. If you want to disable some targets, please use the following snippet:
  89. # Please combine this with the original one
  90. #
  91. # Notes:
  92. # - please keep in mind to avoid duplicated folders as yaml keys
  93. # - please use parentheses to group conditions, the "or" and "and" operators could only accept two operands
  94. {_app.app_dir}:
  95. enable:
  96. - if: {if_clause}
  97. temporary: true
  98. reason: <why only enable build jobs for these targets>
  99. '''
  100. )
  101. )
  102. return False
  103. apps = sorted(
  104. find_apps(
  105. paths,
  106. 'all',
  107. recursive=True,
  108. manifest_files=[
  109. str(p) for p in Path(IDF_PATH).glob('**/.build-test-rules.yml')
  110. ],
  111. )
  112. )
  113. exit_code = 0
  114. checked_app_dirs = set()
  115. for app in apps:
  116. if app.app_dir not in checked_app_dirs:
  117. checked_app_dirs.add(app.app_dir)
  118. else:
  119. continue
  120. replace_str, old_supported_targets = _parse_existing_support_table_str(app)
  121. success = check_enable_build(app, old_supported_targets)
  122. if not success:
  123. print(f'check_enable_build failed for app: {app}')
  124. print('-' * 80)
  125. exit_code = 1
  126. readme_path = get_readme_path(app)
  127. # no readme, create a new file
  128. if not readme_path:
  129. with open(os.path.join(app.app_dir, 'README.md'), 'w') as fw:
  130. fw.write(_generate_new_support_table_str(app) + '\n')
  131. print(f'Added new README file: {os.path.join(app.app_dir, "README.md")}')
  132. print('-' * 80)
  133. exit_code = 1
  134. # has old table, but different string
  135. elif replace_str and replace_str != _generate_new_support_table_str(app):
  136. with open(readme_path) as fr:
  137. readme_str = fr.read()
  138. with open(readme_path, 'w') as fw:
  139. fw.write(
  140. readme_str.replace(
  141. replace_str, _generate_new_support_table_str(app)
  142. )
  143. )
  144. print(f'Modified README file: {readme_path}')
  145. print('-' * 80)
  146. exit_code = 1
  147. # does not have old table
  148. elif not replace_str:
  149. with open(readme_path) as fr:
  150. readme_str = fr.read()
  151. with open(readme_path, 'w') as fw:
  152. fw.write(
  153. _generate_new_support_table_str(app) + '\n\n' + readme_str
  154. ) # extra new line
  155. print(f'Modified README file: {readme_path}')
  156. print('-' * 80)
  157. exit_code = 1
  158. sys.exit(exit_code)
  159. def check_test_scripts(paths: List[str]) -> None:
  160. from idf_build_apps import App, find_apps
  161. # takes long time, run only in CI
  162. # dict:
  163. # {
  164. # app_dir: {
  165. # 'script_path': 'path/to/script',
  166. # 'targets': ['esp32', 'esp32s2', 'esp32s3', 'esp32c3', 'esp32h2', 'esp32c2', 'linux'],
  167. # }
  168. # }
  169. def check_enable_test(
  170. _app: App,
  171. _pytest_app_dir_targets_dict: Dict[str, Dict[str, str]],
  172. _ttfw_app_dir_targets_dict: Dict[str, Dict[str, str]],
  173. ) -> bool:
  174. if _app.app_dir in _pytest_app_dir_targets_dict:
  175. test_script_path = _pytest_app_dir_targets_dict[_app.app_dir]['script_path']
  176. actual_verified_targets = sorted(
  177. set(_pytest_app_dir_targets_dict[_app.app_dir]['targets'])
  178. )
  179. elif _app.app_dir in _ttfw_app_dir_targets_dict:
  180. test_script_path = _ttfw_app_dir_targets_dict[_app.app_dir]['script_path']
  181. actual_verified_targets = sorted(
  182. set(_ttfw_app_dir_targets_dict[_app.app_dir]['targets'])
  183. )
  184. else:
  185. return True # no test case
  186. if (
  187. _app.app_dir in _pytest_app_dir_targets_dict
  188. and _app.app_dir in _ttfw_app_dir_targets_dict
  189. ):
  190. print(
  191. f'''
  192. Both pytest and ttfw test cases are found for {_app.app_dir},
  193. please remove one of them.
  194. pytest script: {_pytest_app_dir_targets_dict[_app.app_dir]['script_path']}
  195. ttfw script: {_ttfw_app_dir_targets_dict[_app.app_dir]['script_path']}
  196. '''
  197. )
  198. return False
  199. actual_extra_tested_targets = set(actual_verified_targets) - set(
  200. _app.verified_targets
  201. )
  202. if actual_extra_tested_targets:
  203. print(
  204. inspect.cleandoc(
  205. f'''
  206. {_app.app_dir}:
  207. - enable test targets according to the manifest file: {_app.verified_targets}
  208. - enable test targets according to the test scripts: {actual_verified_targets}
  209. test scripts enabled targets should be a subset of the manifest file declared ones.
  210. Please check the test script: {test_script_path}.
  211. '''
  212. )
  213. )
  214. return False
  215. if actual_verified_targets == _app.verified_targets:
  216. return True
  217. if_clause = f'IDF_TARGET in [{", ".join([doublequote(target) for target in sorted(set(_app.verified_targets) - set(actual_verified_targets))])}]'
  218. print(
  219. inspect.cleandoc(
  220. f'''
  221. {_app.app_dir}:
  222. - enable test targets according to the manifest file: {_app.verified_targets}
  223. - enable test targets according to the test scripts: {actual_verified_targets}
  224. the test scripts enabled test targets should be the same with the manifest file enabled ones. Please check
  225. the test script manually: {test_script_path}.
  226. If you want to enable test targets in the pytest test scripts, please add `@pytest.mark.MISSING_TARGET`
  227. marker above the test case function.
  228. If you want to enable test targets in the ttfw test scripts, please add/extend the keyword `targets` in
  229. the ttfw decorator, e.g. `@ttfw_idf.idf_example_test(..., target=['esp32', 'MISSING_TARGET'])`
  230. If you want to disable the test targets in the manifest file, please modify your manifest file with
  231. the following code snippet:
  232. # Please combine this with the original one
  233. #
  234. # Notes:
  235. # - please keep in mind to avoid duplicated folders as yaml keys
  236. # - please use parentheses to group conditions, the "or" and "and" operators could only accept two operands
  237. {_app.app_dir}:
  238. disable_test:
  239. - if: {if_clause}
  240. temporary: true
  241. reason: <why you disable this test>
  242. '''
  243. )
  244. )
  245. return False
  246. apps = sorted(
  247. find_apps(
  248. paths,
  249. 'all',
  250. recursive=True,
  251. manifest_files=[
  252. str(p) for p in Path(IDF_PATH).glob('**/.build-test-rules.yml')
  253. ],
  254. )
  255. )
  256. exit_code = 0
  257. pytest_cases = get_pytest_cases(paths)
  258. ttfw_cases = get_ttfw_cases(paths)
  259. pytest_app_dir_targets_dict = {}
  260. ttfw_app_dir_targets_dict = {}
  261. for case in pytest_cases:
  262. for pytest_app in case.apps:
  263. app_dir = os.path.relpath(pytest_app.path, IDF_PATH)
  264. if app_dir not in pytest_app_dir_targets_dict:
  265. pytest_app_dir_targets_dict[app_dir] = {
  266. 'script_path': case.path,
  267. 'targets': [pytest_app.target],
  268. }
  269. else:
  270. pytest_app_dir_targets_dict[app_dir]['targets'].append(
  271. pytest_app.target
  272. )
  273. for case in ttfw_cases:
  274. app_dir = case.case_info['app_dir']
  275. if app_dir not in ttfw_app_dir_targets_dict:
  276. ttfw_app_dir_targets_dict[app_dir] = {
  277. 'script_path': case.case_info['script_path'],
  278. 'targets': [case.case_info['target'].lower()],
  279. }
  280. else:
  281. ttfw_app_dir_targets_dict[app_dir]['targets'].append(
  282. case.case_info['target'].lower()
  283. )
  284. checked_app_dirs = set()
  285. for app in apps:
  286. if app.app_dir not in checked_app_dirs:
  287. checked_app_dirs.add(app.app_dir)
  288. else:
  289. continue
  290. success = check_enable_test(
  291. app, pytest_app_dir_targets_dict, ttfw_app_dir_targets_dict
  292. )
  293. if not success:
  294. print(f'check_enable_test failed for app: {app}')
  295. print('-' * 80)
  296. exit_code = 1
  297. continue
  298. sys.exit(exit_code)
  299. def sort_yaml(files: List[str]) -> None:
  300. from ruamel.yaml import YAML, CommentedMap
  301. yaml = YAML()
  302. yaml.indent(mapping=2, sequence=4, offset=2)
  303. yaml.width = 4096 # avoid wrap lines
  304. exit_code = 0
  305. for f in files:
  306. with open(f) as fr:
  307. file_s = fr.read()
  308. fr.seek(0)
  309. file_d: CommentedMap = yaml.load(fr)
  310. sorted_yaml = CommentedMap(dict(sorted(file_d.items())))
  311. file_d.copy_attributes(sorted_yaml)
  312. with StringIO() as s:
  313. yaml.dump(sorted_yaml, s)
  314. string = s.getvalue()
  315. if string != file_s:
  316. with open(f, 'w') as fw:
  317. fw.write(string)
  318. print(
  319. f'Sorted yaml file {f}. Please take a look. sometimes the format is a bit messy'
  320. )
  321. exit_code = 1
  322. sys.exit(exit_code)
  323. if __name__ == '__main__':
  324. parser = argparse.ArgumentParser(description='ESP-IDF apps build/test checker')
  325. action = parser.add_subparsers(dest='action')
  326. _check_readme = action.add_parser('check-readmes')
  327. _check_readme.add_argument('paths', nargs='+', help='check under paths')
  328. _check_test_scripts = action.add_parser('check-test-scripts')
  329. _check_test_scripts.add_argument('paths', nargs='+', help='check under paths')
  330. _sort_yaml = action.add_parser('sort-yaml')
  331. _sort_yaml.add_argument('files', nargs='+', help='all specified yaml files')
  332. arg = parser.parse_args()
  333. # Since this script is executed from the pre-commit hook environment, make sure IDF_PATH is set
  334. os.environ['IDF_PATH'] = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', '..'))
  335. if arg.action == 'sort-yaml':
  336. sort_yaml(arg.files)
  337. else:
  338. check_dirs = set()
  339. for path in arg.paths:
  340. if os.path.isfile(path):
  341. check_dirs.add(os.path.dirname(path))
  342. else:
  343. check_dirs.add(path)
  344. if arg.action == 'check-readmes':
  345. check_readme(list(check_dirs))
  346. elif arg.action == 'check-test-scripts':
  347. check_test_scripts(list(check_dirs))