idf_ci_utils.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. # internal use only for CI
  2. # some CI related util functions
  3. #
  4. # SPDX-FileCopyrightText: 2020-2023 Espressif Systems (Shanghai) CO LTD
  5. # SPDX-License-Identifier: Apache-2.0
  6. #
  7. import contextlib
  8. import logging
  9. import os
  10. import subprocess
  11. import sys
  12. from typing import Any, List, Optional, Set, Union
  13. IDF_PATH = os.path.abspath(os.getenv('IDF_PATH', os.path.join(os.path.dirname(__file__), '..', '..')))
  14. def get_submodule_dirs(full_path: bool = False) -> List[str]:
  15. """
  16. To avoid issue could be introduced by multi-os or additional dependency,
  17. we use python and git to get this output
  18. :return: List of submodule dirs
  19. """
  20. dirs = []
  21. try:
  22. lines = (
  23. subprocess.check_output(
  24. [
  25. 'git',
  26. 'config',
  27. '--file',
  28. os.path.realpath(os.path.join(IDF_PATH, '.gitmodules')),
  29. '--get-regexp',
  30. 'path',
  31. ]
  32. )
  33. .decode('utf8')
  34. .strip()
  35. .split('\n')
  36. )
  37. for line in lines:
  38. _, path = line.split(' ')
  39. if full_path:
  40. dirs.append(os.path.join(IDF_PATH, path))
  41. else:
  42. dirs.append(path)
  43. except Exception as e: # pylint: disable=W0703
  44. logging.warning(str(e))
  45. return dirs
  46. def _check_git_filemode(full_path: str) -> bool:
  47. try:
  48. stdout = subprocess.check_output(['git', 'ls-files', '--stage', full_path]).strip().decode('utf-8')
  49. except subprocess.CalledProcessError:
  50. return True
  51. mode = stdout.split(' ', 1)[0] # e.g. 100644 for a rw-r--r--
  52. if any([int(i, 8) & 1 for i in mode[-3:]]):
  53. return True
  54. return False
  55. def is_executable(full_path: str) -> bool:
  56. """
  57. os.X_OK will always return true on windows. Use git to check file mode.
  58. :param full_path: file full path
  59. :return: True is it's an executable file
  60. """
  61. if sys.platform == 'win32':
  62. return _check_git_filemode(full_path)
  63. return os.access(full_path, os.X_OK)
  64. def get_git_files(path: str = IDF_PATH, full_path: bool = False) -> List[str]:
  65. """
  66. Get the result of git ls-files
  67. :param path: path to run git ls-files
  68. :param full_path: return full path if set to True
  69. :return: list of file paths
  70. """
  71. try:
  72. # this is a workaround when using under worktree
  73. # if you're using worktree, when running git commit a new environment variable GIT_DIR would be declared,
  74. # the value should be <origin_repo_path>/.git/worktrees/<worktree name>
  75. # This would affect the return value of `git ls-files`, unset this would use the `cwd`value or its parent
  76. # folder if no `.git` folder found in `cwd`.
  77. workaround_env = os.environ.copy()
  78. workaround_env.pop('GIT_DIR', None)
  79. files = (
  80. subprocess.check_output(['git', 'ls-files'], cwd=path, env=workaround_env)
  81. .decode('utf8')
  82. .strip()
  83. .split('\n')
  84. )
  85. except Exception as e: # pylint: disable=W0703
  86. logging.warning(str(e))
  87. files = []
  88. return [os.path.join(path, f) for f in files] if full_path else files
  89. def is_in_directory(file_path: str, folder: str) -> bool:
  90. return os.path.realpath(file_path).startswith(os.path.realpath(folder) + os.sep)
  91. def to_list(s: Any) -> List[Any]:
  92. if isinstance(s, (set, tuple)):
  93. return list(s)
  94. if isinstance(s, list):
  95. return s
  96. return [s]
  97. ##################
  98. # TTFW Utilities #
  99. ##################
  100. def get_ttfw_cases(paths: Union[str, List[str]]) -> List[Any]:
  101. """
  102. Get the test cases from ttfw_idf under the given paths
  103. :param paths: list of paths to search
  104. """
  105. try:
  106. from ttfw_idf.IDFAssignTest import IDFAssignTest
  107. except ImportError:
  108. sys.path.append(os.path.join(IDF_PATH, 'tools', 'ci', 'python_packages'))
  109. from ttfw_idf.IDFAssignTest import IDFAssignTest
  110. # mock CI_JOB_ID if not exists
  111. if not os.environ.get('CI_JOB_ID'):
  112. os.environ['CI_JOB_ID'] = '1'
  113. cases = []
  114. for path in to_list(paths):
  115. assign = IDFAssignTest(path, os.path.join(IDF_PATH, '.gitlab', 'ci', 'target-test.yml'))
  116. with contextlib.redirect_stdout(None): # swallow stdout
  117. try:
  118. cases += assign.search_cases()
  119. except ImportError as e:
  120. logging.error(str(e))
  121. return cases
  122. def get_ttfw_app_paths(paths: Union[str, List[str]], target: Optional[str] = None) -> Set[str]:
  123. """
  124. Get the app paths from ttfw_idf under the given paths
  125. """
  126. from idf_build_apps import CMakeApp
  127. cases = get_ttfw_cases(paths)
  128. res: Set[str] = set()
  129. for case in cases:
  130. if not target or target == case.case_info['target'].lower():
  131. # ttfw has no good way to detect the app path for master-slave tests
  132. # the apps real location may be the sub folder of the test script path
  133. # check if the current folder is an app, if it's not, add all its subfolders if they are apps
  134. # only one level down
  135. _app_dir = case.case_info['app_dir']
  136. if CMakeApp.is_app(_app_dir):
  137. res.add(_app_dir)
  138. else:
  139. for child in os.listdir(_app_dir):
  140. sub_path = os.path.join(_app_dir, child)
  141. if os.path.isdir(sub_path) and CMakeApp.is_app(sub_path):
  142. res.add(sub_path)
  143. return res