check_build_test_rules.py 17 KB

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