check_build_test_rules.py 15 KB

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