idf_ci_utils.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. # internal use only for CI
  2. # some CI related util functions
  3. #
  4. # Copyright 2020 Espressif Systems (Shanghai) PTE LTD
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. #
  18. import functools
  19. import logging
  20. import os
  21. import re
  22. import subprocess
  23. import sys
  24. IDF_PATH = os.path.abspath(os.getenv('IDF_PATH', os.path.join(os.path.dirname(__file__), '..', '..')))
  25. def get_submodule_dirs(full_path=False): # type: (bool) -> list
  26. """
  27. To avoid issue could be introduced by multi-os or additional dependency,
  28. we use python and git to get this output
  29. :return: List of submodule dirs
  30. """
  31. dirs = []
  32. try:
  33. lines = subprocess.check_output(
  34. ['git', 'config', '--file', os.path.realpath(os.path.join(IDF_PATH, '.gitmodules')),
  35. '--get-regexp', 'path']).decode('utf8').strip().split('\n')
  36. for line in lines:
  37. _, path = line.split(' ')
  38. if full_path:
  39. dirs.append(os.path.join(IDF_PATH, path))
  40. else:
  41. dirs.append(path)
  42. except Exception as e: # pylint: disable=W0703
  43. logging.warning(str(e))
  44. return dirs
  45. def _check_git_filemode(full_path): # type: (str) -> bool
  46. try:
  47. stdout = subprocess.check_output(['git', 'ls-files', '--stage', full_path]).strip().decode('utf-8')
  48. except subprocess.CalledProcessError:
  49. return True
  50. mode = stdout.split(' ', 1)[0] # e.g. 100644 for a rw-r--r--
  51. if any([int(i, 8) & 1 for i in mode[-3:]]):
  52. return True
  53. return False
  54. def is_executable(full_path): # type: (str) -> bool
  55. """
  56. os.X_OK will always return true on windows. Use git to check file mode.
  57. :param full_path: file full path
  58. :return: True is it's an executable file
  59. """
  60. if sys.platform == 'win32':
  61. return _check_git_filemode(full_path)
  62. return os.access(full_path, os.X_OK)
  63. def get_git_files(path=IDF_PATH, full_path=False): # type: (str, bool) -> list[str]
  64. """
  65. Get the result of git ls-files
  66. :param path: path to run git ls-files
  67. :param full_path: return full path if set to True
  68. :return: list of file paths
  69. """
  70. try:
  71. files = subprocess.check_output(['git', 'ls-files'], cwd=path).decode('utf8').strip().split('\n')
  72. except Exception as e: # pylint: disable=W0703
  73. logging.warning(str(e))
  74. files = []
  75. return [os.path.join(path, f) for f in files] if full_path else files
  76. # this function is a commit from
  77. # https://github.com/python/cpython/pull/6299/commits/bfd63120c18bd055defb338c075550f975e3bec1
  78. # In order to solve python https://bugs.python.org/issue9584
  79. # glob pattern does not support brace expansion issue
  80. def _translate(pat): # type: (str) -> str
  81. """Translate a shell PATTERN to a regular expression.
  82. There is no way to quote meta-characters.
  83. """
  84. i, n = 0, len(pat)
  85. res = ''
  86. while i < n:
  87. c = pat[i]
  88. i = i + 1
  89. if c == '*':
  90. res = res + '.*'
  91. elif c == '?':
  92. res = res + '.'
  93. elif c == '[':
  94. j = i
  95. if j < n and pat[j] == '!':
  96. j = j + 1
  97. if j < n and pat[j] == ']':
  98. j = j + 1
  99. while j < n and pat[j] != ']':
  100. j = j + 1
  101. if j >= n:
  102. res = res + '\\['
  103. else:
  104. stuff = pat[i:j]
  105. if '--' not in stuff:
  106. stuff = stuff.replace('\\', r'\\')
  107. else:
  108. chunks = []
  109. k = i + 2 if pat[i] == '!' else i + 1
  110. while True:
  111. k = pat.find('-', k, j)
  112. if k < 0:
  113. break
  114. chunks.append(pat[i:k])
  115. i = k + 1
  116. k = k + 3
  117. chunks.append(pat[i:j])
  118. # Escape backslashes and hyphens for set difference (--).
  119. # Hyphens that create ranges shouldn't be escaped.
  120. stuff = '-'.join(s.replace('\\', r'\\').replace('-', r'\-')
  121. for s in chunks)
  122. # Escape set operations (&&, ~~ and ||).
  123. stuff = re.sub(r'([&~|])', r'\\\1', stuff)
  124. i = j + 1
  125. if stuff[0] == '!':
  126. stuff = '^' + stuff[1:]
  127. elif stuff[0] in ('^', '['):
  128. stuff = '\\' + stuff
  129. res = '%s[%s]' % (res, stuff)
  130. elif c == '{':
  131. # Handling of brace expression: '{PATTERN,PATTERN,...}'
  132. j = 1
  133. while j < n and pat[j] != '}':
  134. j = j + 1
  135. if j >= n:
  136. res = res + '\\{'
  137. else:
  138. stuff = pat[i:j]
  139. i = j + 1
  140. # Find indices of ',' in pattern excluding r'\,'.
  141. # E.g. for r'a\,a,b\b,c' it will be [4, 8]
  142. indices = [m.end() for m in re.finditer(r'[^\\],', stuff)]
  143. # Splitting pattern string based on ',' character.
  144. # Also '\,' is translated to ','. E.g. for r'a\,a,b\b,c':
  145. # * first_part = 'a,a'
  146. # * last_part = 'c'
  147. # * middle_part = ['b,b']
  148. first_part = stuff[:indices[0] - 1].replace(r'\,', ',')
  149. last_part = stuff[indices[-1]:].replace(r'\,', ',')
  150. middle_parts = [
  151. stuff[st:en - 1].replace(r'\,', ',')
  152. for st, en in zip(indices, indices[1:])
  153. ]
  154. # creating the regex from splitted pattern. Each part is
  155. # recursivelly evaluated.
  156. expanded = functools.reduce(
  157. lambda a, b: '|'.join((a, b)),
  158. (_translate(elem) for elem in [first_part] + middle_parts + [last_part])
  159. )
  160. res = '%s(%s)' % (res, expanded)
  161. else:
  162. res = res + re.escape(c)
  163. return res
  164. def translate(pat): # type: (str) -> str
  165. res = _translate(pat)
  166. return r'(?s:%s)\Z' % res
  167. magic_check = re.compile('([*?[{])')
  168. magic_check_bytes = re.compile(b'([*?[{])')
  169. # cpython github PR 6299 ends here
  170. # Here's the code block we're going to use to monkey patch ``glob`` module and ``fnmatch`` modules
  171. # DO NOT monkey patch here, only patch where you really needs
  172. #
  173. # import glob
  174. # import fnmatch
  175. # from idf_ci_utils import magic_check, magic_check_bytes, translate
  176. # glob.magic_check = magic_check
  177. # glob.magic_check_bytes = magic_check_bytes
  178. # fnmatch.translate = translate