getdeveloperlib.py 9.2 KB

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