getdeveloperlib.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. from __future__ import print_function
  2. from io import open
  3. import os
  4. import re
  5. import glob
  6. import subprocess
  7. import sys
  8. import unittest
  9. brpath = os.path.normpath(os.path.join(os.path.dirname(__file__), ".."))
  10. #
  11. # Patch parsing functions
  12. #
  13. FIND_INFRA_IN_PATCH = re.compile(r"^\+\$\(eval \$\((host-)?([^-]*)-package\)\)$")
  14. def analyze_patch(patch):
  15. """Parse one patch and return the list of files modified, added or
  16. removed by the patch."""
  17. files = set()
  18. infras = set()
  19. for line in patch:
  20. # If the patch is adding a package, find which infra it is
  21. m = FIND_INFRA_IN_PATCH.match(line)
  22. if m:
  23. infras.add(m.group(2))
  24. if not line.startswith("+++ "):
  25. continue
  26. line.strip()
  27. fname = line[line.find("/") + 1:].strip()
  28. if fname == "dev/null":
  29. continue
  30. files.add(fname)
  31. return (files, infras)
  32. FIND_INFRA_IN_MK = re.compile(r"^\$\(eval \$\((host-)?([^-]*)-package\)\)$")
  33. def fname_get_package_infra(fname):
  34. """Checks whether the file name passed as argument is a Buildroot .mk
  35. file describing a package, and find the infrastructure it's using."""
  36. if not fname.endswith(".mk"):
  37. return None
  38. if not os.path.exists(fname):
  39. return None
  40. with open(fname, "r") as f:
  41. for line in f:
  42. line = line.strip()
  43. m = FIND_INFRA_IN_MK.match(line)
  44. if m:
  45. return m.group(2)
  46. return None
  47. def analyze_patches(patches):
  48. """Parse a list of patches and returns the list of files modified,
  49. added or removed by the patches, as well as the list of package
  50. infrastructures used by those patches (if any)"""
  51. allfiles = set()
  52. allinfras = set()
  53. for patch in patches:
  54. (files, infras) = analyze_patch(patch)
  55. allfiles = allfiles | files
  56. allinfras = allinfras | infras
  57. return (allfiles, allinfras)
  58. #
  59. # Unit-test parsing functions
  60. #
  61. def get_all_test_cases(suite):
  62. """Generate all test-cases from a given test-suite.
  63. :return: (test.module, test.name)"""
  64. if issubclass(type(suite), unittest.TestSuite):
  65. for test in suite:
  66. for res in get_all_test_cases(test):
  67. yield res
  68. else:
  69. yield (suite.__module__, suite.__class__.__name__)
  70. def list_unittests():
  71. """Use the unittest module to retreive all test cases from a given
  72. directory"""
  73. loader = unittest.TestLoader()
  74. suite = loader.discover(os.path.join(brpath, "support", "testing"))
  75. tests = {}
  76. for module, test in get_all_test_cases(suite):
  77. module_path = os.path.join("support", "testing", *module.split('.'))
  78. tests.setdefault(module_path, []).append('%s.%s' % (module, test))
  79. return tests
  80. unittests = {}
  81. #
  82. # DEVELOPERS file parsing functions
  83. #
  84. class Developer:
  85. def __init__(self, name, files):
  86. self.name = name
  87. self.files = files
  88. self.packages = parse_developer_packages(files)
  89. self.architectures = parse_developer_architectures(files)
  90. self.infras = parse_developer_infras(files)
  91. self.runtime_tests = parse_developer_runtime_tests(files)
  92. self.defconfigs = parse_developer_defconfigs(files)
  93. def hasfile(self, f):
  94. for fs in self.files:
  95. if f.startswith(fs):
  96. return True
  97. return False
  98. def __repr__(self):
  99. name = '\'' + self.name.split(' <')[0][:20] + '\''
  100. things = []
  101. if len(self.files):
  102. things.append('{} files'.format(len(self.files)))
  103. if len(self.packages):
  104. things.append('{} pkgs'.format(len(self.packages)))
  105. if len(self.architectures):
  106. things.append('{} archs'.format(len(self.architectures)))
  107. if len(self.infras):
  108. things.append('{} infras'.format(len(self.infras)))
  109. if len(self.runtime_tests):
  110. things.append('{} tests'.format(len(self.runtime_tests)))
  111. if len(self.defconfigs):
  112. things.append('{} defconfigs'.format(len(self.defconfigs)))
  113. if things:
  114. return 'Developer <{} ({})>'.format(name, ', '.join(things))
  115. else:
  116. return 'Developer <' + name + '>'
  117. def parse_developer_packages(fnames):
  118. """Given a list of file patterns, travel through the Buildroot source
  119. tree to find which packages are implemented by those file
  120. patterns, and return a list of those packages."""
  121. packages = set()
  122. for fname in fnames:
  123. for root, dirs, files in os.walk(os.path.join(brpath, fname)):
  124. for f in files:
  125. path = os.path.join(root, f)
  126. if fname_get_package_infra(path):
  127. pkg = os.path.splitext(f)[0]
  128. packages.add(pkg)
  129. return packages
  130. def parse_arches_from_config_in(fname):
  131. """Given a path to an arch/Config.in.* file, parse it to get the list
  132. of BR2_ARCH values for this architecture."""
  133. arches = set()
  134. with open(fname, "r") as f:
  135. parsing_arches = False
  136. for line in f:
  137. line = line.strip()
  138. if line == "config BR2_ARCH":
  139. parsing_arches = True
  140. continue
  141. if parsing_arches:
  142. m = re.match(r"^\s*default \"([^\"]*)\".*", line)
  143. if m:
  144. arches.add(m.group(1))
  145. else:
  146. parsing_arches = False
  147. return arches
  148. def parse_developer_architectures(fnames):
  149. """Given a list of file names, find the ones starting by
  150. 'arch/Config.in.', and use that to determine the architecture a
  151. developer is working on."""
  152. arches = set()
  153. for fname in fnames:
  154. if not re.match(r"^.*/arch/Config\.in\..*$", fname):
  155. continue
  156. arches = arches | parse_arches_from_config_in(fname)
  157. return arches
  158. def parse_developer_infras(fnames):
  159. infras = set()
  160. for fname in fnames:
  161. m = re.match(r"^package/pkg-([^.]*).mk$", fname)
  162. if m:
  163. infras.add(m.group(1))
  164. return infras
  165. def parse_developer_defconfigs(fnames):
  166. """Given a list of file names, returns the config names
  167. corresponding to defconfigs."""
  168. return {os.path.basename(fname[:-10])
  169. for fname in fnames
  170. if fname.endswith('_defconfig')}
  171. def parse_developer_runtime_tests(fnames):
  172. """Given a list of file names, returns the runtime tests
  173. corresponding to the file."""
  174. all_files = []
  175. # List all files recursively
  176. for fname in fnames:
  177. if os.path.isdir(fname):
  178. for root, _dirs, files in os.walk(os.path.join(brpath, fname)):
  179. all_files += [os.path.join(root, f) for f in files]
  180. else:
  181. all_files.append(fname)
  182. # Get all runtime tests
  183. runtimes = set()
  184. for f in all_files:
  185. name = os.path.splitext(f)[0]
  186. if name in unittests:
  187. runtimes |= set(unittests[name])
  188. return runtimes
  189. def parse_developers():
  190. """Parse the DEVELOPERS file and return a list of Developer objects."""
  191. developers = []
  192. linen = 0
  193. global unittests
  194. unittests = list_unittests()
  195. developers_fname = os.path.join(brpath, 'DEVELOPERS')
  196. with open(developers_fname, mode='r', encoding='utf_8') as f:
  197. files = []
  198. name = None
  199. for line in f:
  200. line = line.strip()
  201. if line.startswith("#"):
  202. continue
  203. elif line.startswith("N:"):
  204. if name is not None or len(files) != 0:
  205. print("Syntax error in DEVELOPERS file, line %d" % linen,
  206. file=sys.stderr)
  207. name = line[2:].strip()
  208. elif line.startswith("F:"):
  209. fname = line[2:].strip()
  210. dev_files = glob.glob(os.path.join(brpath, fname))
  211. if len(dev_files) == 0:
  212. print("WARNING: '%s' doesn't match any file" % fname,
  213. file=sys.stderr)
  214. for f in dev_files:
  215. dev_file = os.path.relpath(f, brpath)
  216. dev_file = dev_file.replace(os.sep, '/') # force unix sep
  217. files.append(dev_file)
  218. elif line == "":
  219. if not name:
  220. continue
  221. developers.append(Developer(name, files))
  222. files = []
  223. name = None
  224. else:
  225. print("Syntax error in DEVELOPERS file, line %d: '%s'" % (linen, line),
  226. file=sys.stderr)
  227. return None
  228. linen += 1
  229. # handle last developer
  230. if name is not None:
  231. developers.append(Developer(name, files))
  232. return developers
  233. def check_developers(developers, basepath=None):
  234. """Look at the list of files versioned in Buildroot, and returns the
  235. list of files that are not handled by any developer"""
  236. if basepath is None:
  237. basepath = os.getcwd()
  238. cmd = ["git", "--git-dir", os.path.join(basepath, ".git"), "ls-files"]
  239. files = subprocess.check_output(cmd).decode(sys.stdout.encoding).strip().split("\n")
  240. unhandled_files = []
  241. for f in files:
  242. handled = False
  243. for d in developers:
  244. if d.hasfile(f):
  245. handled = True
  246. break
  247. if not handled:
  248. unhandled_files.append(f)
  249. return unhandled_files