idf_ci_utils.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. # internal use only for CI
  2. # some CI related util functions
  3. #
  4. # SPDX-FileCopyrightText: 2020-2021 Espressif Systems (Shanghai) CO LTD
  5. # SPDX-License-Identifier: Apache-2.0
  6. #
  7. import functools
  8. import logging
  9. import os
  10. import re
  11. import subprocess
  12. import sys
  13. from typing import List, Optional
  14. IDF_PATH = os.path.abspath(os.getenv('IDF_PATH', os.path.join(os.path.dirname(__file__), '..', '..')))
  15. def get_submodule_dirs(full_path: bool = False) -> List:
  16. """
  17. To avoid issue could be introduced by multi-os or additional dependency,
  18. we use python and git to get this output
  19. :return: List of submodule dirs
  20. """
  21. dirs = []
  22. try:
  23. lines = subprocess.check_output(
  24. ['git', 'config', '--file', os.path.realpath(os.path.join(IDF_PATH, '.gitmodules')),
  25. '--get-regexp', 'path']).decode('utf8').strip().split('\n')
  26. for line in lines:
  27. _, path = line.split(' ')
  28. if full_path:
  29. dirs.append(os.path.join(IDF_PATH, path))
  30. else:
  31. dirs.append(path)
  32. except Exception as e: # pylint: disable=W0703
  33. logging.warning(str(e))
  34. return dirs
  35. def _check_git_filemode(full_path): # type: (str) -> bool
  36. try:
  37. stdout = subprocess.check_output(['git', 'ls-files', '--stage', full_path]).strip().decode('utf-8')
  38. except subprocess.CalledProcessError:
  39. return True
  40. mode = stdout.split(' ', 1)[0] # e.g. 100644 for a rw-r--r--
  41. if any([int(i, 8) & 1 for i in mode[-3:]]):
  42. return True
  43. return False
  44. def is_executable(full_path: str) -> bool:
  45. """
  46. os.X_OK will always return true on windows. Use git to check file mode.
  47. :param full_path: file full path
  48. :return: True is it's an executable file
  49. """
  50. if sys.platform == 'win32':
  51. return _check_git_filemode(full_path)
  52. return os.access(full_path, os.X_OK)
  53. def get_git_files(path: str = IDF_PATH, full_path: bool = False) -> List[str]:
  54. """
  55. Get the result of git ls-files
  56. :param path: path to run git ls-files
  57. :param full_path: return full path if set to True
  58. :return: list of file paths
  59. """
  60. try:
  61. # this is a workaround when using under worktree
  62. # if you're using worktree, when running git commit a new environment variable GIT_DIR would be declared,
  63. # the value should be <origin_repo_path>/.git/worktrees/<worktree name>
  64. # This would effect the return value of `git ls-files`, unset this would use the `cwd`value or its parent
  65. # folder if no `.git` folder found in `cwd`.
  66. workaround_env = os.environ.copy()
  67. workaround_env.pop('GIT_DIR', None)
  68. files = subprocess.check_output(['git', 'ls-files'], cwd=path, env=workaround_env) \
  69. .decode('utf8').strip().split('\n')
  70. except Exception as e: # pylint: disable=W0703
  71. logging.warning(str(e))
  72. files = []
  73. return [os.path.join(path, f) for f in files] if full_path else files
  74. # this function is a commit from
  75. # https://github.com/python/cpython/pull/6299/commits/bfd63120c18bd055defb338c075550f975e3bec1
  76. # In order to solve python https://bugs.python.org/issue9584
  77. # glob pattern does not support brace expansion issue
  78. def _translate(pat: str) -> str:
  79. """Translate a shell PATTERN to a regular expression.
  80. There is no way to quote meta-characters.
  81. """
  82. i, n = 0, len(pat)
  83. res = ''
  84. while i < n:
  85. c = pat[i]
  86. i = i + 1
  87. if c == '*':
  88. res = res + '.*'
  89. elif c == '?':
  90. res = res + '.'
  91. elif c == '[':
  92. j = i
  93. if j < n and pat[j] == '!':
  94. j = j + 1
  95. if j < n and pat[j] == ']':
  96. j = j + 1
  97. while j < n and pat[j] != ']':
  98. j = j + 1
  99. if j >= n:
  100. res = res + '\\['
  101. else:
  102. stuff = pat[i:j]
  103. if '--' not in stuff:
  104. stuff = stuff.replace('\\', r'\\')
  105. else:
  106. chunks = []
  107. k = i + 2 if pat[i] == '!' else i + 1
  108. while True:
  109. k = pat.find('-', k, j)
  110. if k < 0:
  111. break
  112. chunks.append(pat[i:k])
  113. i = k + 1
  114. k = k + 3
  115. chunks.append(pat[i:j])
  116. # Escape backslashes and hyphens for set difference (--).
  117. # Hyphens that create ranges shouldn't be escaped.
  118. stuff = '-'.join(s.replace('\\', r'\\').replace('-', r'\-')
  119. for s in chunks)
  120. # Escape set operations (&&, ~~ and ||).
  121. stuff = re.sub(r'([&~|])', r'\\\1', stuff)
  122. i = j + 1
  123. if stuff[0] == '!':
  124. stuff = '^' + stuff[1:]
  125. elif stuff[0] in ('^', '['):
  126. stuff = '\\' + stuff
  127. res = '%s[%s]' % (res, stuff)
  128. elif c == '{':
  129. # Handling of brace expression: '{PATTERN,PATTERN,...}'
  130. j = 1
  131. while j < n and pat[j] != '}':
  132. j = j + 1
  133. if j >= n:
  134. res = res + '\\{'
  135. else:
  136. stuff = pat[i:j]
  137. i = j + 1
  138. # Find indices of ',' in pattern excluding r'\,'.
  139. # E.g. for r'a\,a,b\b,c' it will be [4, 8]
  140. indices = [m.end() for m in re.finditer(r'[^\\],', stuff)]
  141. # Splitting pattern string based on ',' character.
  142. # Also '\,' is translated to ','. E.g. for r'a\,a,b\b,c':
  143. # * first_part = 'a,a'
  144. # * last_part = 'c'
  145. # * middle_part = ['b,b']
  146. first_part = stuff[:indices[0] - 1].replace(r'\,', ',')
  147. last_part = stuff[indices[-1]:].replace(r'\,', ',')
  148. middle_parts = [
  149. stuff[st:en - 1].replace(r'\,', ',')
  150. for st, en in zip(indices, indices[1:])
  151. ]
  152. # creating the regex from splitted pattern. Each part is
  153. # recursivelly evaluated.
  154. expanded = functools.reduce(
  155. lambda a, b: '|'.join((a, b)),
  156. (_translate(elem) for elem in [first_part] + middle_parts + [last_part])
  157. )
  158. res = '%s(%s)' % (res, expanded)
  159. else:
  160. res = res + re.escape(c)
  161. return res
  162. def translate(pat: str) -> str:
  163. res = _translate(pat)
  164. return r'(?s:%s)\Z' % res
  165. magic_check = re.compile('([*?[{])')
  166. magic_check_bytes = re.compile(b'([*?[{])')
  167. # cpython github PR 6299 ends here
  168. # Here's the code block we're going to use to monkey patch ``glob`` module and ``fnmatch`` modules
  169. # DO NOT monkey patch here, only patch where you really needs
  170. #
  171. # import glob
  172. # import fnmatch
  173. # from idf_ci_utils import magic_check, magic_check_bytes, translate
  174. # glob.magic_check = magic_check
  175. # glob.magic_check_bytes = magic_check_bytes
  176. # fnmatch.translate = translate
  177. def is_in_directory(file_path: str, folder: str) -> bool:
  178. return os.path.realpath(file_path).startswith(os.path.realpath(folder) + os.sep)
  179. def get_pytest_dirs(folder: str, under_dir: Optional[str] = None) -> List[str]:
  180. from io import StringIO
  181. import pytest
  182. from _pytest.nodes import Item
  183. class CollectPlugin:
  184. def __init__(self) -> None:
  185. self.nodes: List[Item] = []
  186. def pytest_collection_modifyitems(self, items: List[Item]) -> None:
  187. for item in items:
  188. self.nodes.append(item)
  189. collector = CollectPlugin()
  190. sys_stdout = sys.stdout
  191. sys.stdout = StringIO() # swallow the output
  192. pytest.main(['--collect-only', folder], plugins=[collector])
  193. sys.stdout = sys_stdout # restore sys.stdout
  194. test_file_paths = set(node.fspath for node in collector.nodes)
  195. if under_dir:
  196. return [os.path.dirname(file) for file in test_file_paths if is_in_directory(file, under_dir)]
  197. return [os.path.dirname(file) for file in test_file_paths]