check-package 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. #!/usr/bin/env python3
  2. # See utils/checkpackagelib/readme.txt before editing this file.
  3. import argparse
  4. import inspect
  5. import magic
  6. import os
  7. import re
  8. import sys
  9. import checkpackagelib.base
  10. import checkpackagelib.lib_config
  11. import checkpackagelib.lib_defconfig
  12. import checkpackagelib.lib_hash
  13. import checkpackagelib.lib_ignore
  14. import checkpackagelib.lib_mk
  15. import checkpackagelib.lib_patch
  16. import checkpackagelib.lib_python
  17. import checkpackagelib.lib_shellscript
  18. import checkpackagelib.lib_sysv
  19. VERBOSE_LEVEL_TO_SHOW_IGNORED_FILES = 3
  20. flags = None # Command line arguments.
  21. # There are two Python packages called 'magic':
  22. # https://pypi.org/project/file-magic/
  23. # https://pypi.org/project/python-magic/
  24. # Both allow to return a MIME file type, but with a slightly different
  25. # interface. Detect which one of the two we have based on one of the
  26. # attributes.
  27. if hasattr(magic, 'FileMagic'):
  28. # https://pypi.org/project/file-magic/
  29. def get_filetype(fname):
  30. return magic.detect_from_filename(fname).mime_type
  31. else:
  32. # https://pypi.org/project/python-magic/
  33. def get_filetype(fname):
  34. return magic.from_file(fname, mime=True)
  35. def get_ignored_parsers_per_file(intree_only, ignore_filename):
  36. ignored = dict()
  37. entry_base_dir = ''
  38. if not ignore_filename:
  39. return ignored
  40. filename = os.path.abspath(ignore_filename)
  41. entry_base_dir = os.path.join(os.path.dirname(filename))
  42. with open(filename, "r") as f:
  43. for line in f.readlines():
  44. filename, warnings_str = line.split(' ', 1)
  45. warnings = warnings_str.split()
  46. ignored[os.path.join(entry_base_dir, filename)] = warnings
  47. return ignored
  48. def parse_args():
  49. parser = argparse.ArgumentParser()
  50. # Do not use argparse.FileType("r") here because only files with known
  51. # format will be open based on the filename.
  52. parser.add_argument("files", metavar="F", type=str, nargs="*",
  53. help="list of files")
  54. parser.add_argument("--br2-external", "-b", dest='intree_only', action="store_false",
  55. help="do not apply the pathname filters used for intree files")
  56. parser.add_argument("--ignore-list", dest='ignore_filename', action="store",
  57. help='override the default list of ignored warnings')
  58. parser.add_argument("--manual-url", action="store",
  59. default="https://nightly.buildroot.org/",
  60. help="default: %(default)s")
  61. parser.add_argument("--verbose", "-v", action="count", default=0)
  62. parser.add_argument("--quiet", "-q", action="count", default=0)
  63. # Now the debug options in the order they are processed.
  64. parser.add_argument("--include-only", dest="include_list", action="append",
  65. help="run only the specified functions (debug)")
  66. parser.add_argument("--exclude", dest="exclude_list", action="append",
  67. help="do not run the specified functions (debug)")
  68. parser.add_argument("--dry-run", action="store_true", help="print the "
  69. "functions that would be called for each file (debug)")
  70. parser.add_argument("--failed-only", action="store_true", help="print only"
  71. " the name of the functions that failed (debug)")
  72. flags = parser.parse_args()
  73. flags.ignore_list = get_ignored_parsers_per_file(flags.intree_only, flags.ignore_filename)
  74. if flags.failed_only:
  75. flags.dry_run = False
  76. flags.verbose = -1
  77. return flags
  78. def get_lib_from_filetype(fname):
  79. if not os.path.isfile(fname):
  80. return None
  81. filetype = get_filetype(fname)
  82. if filetype == "text/x-shellscript":
  83. return checkpackagelib.lib_shellscript
  84. if filetype in ["text/x-python", "text/x-script.python"]:
  85. return checkpackagelib.lib_python
  86. return None
  87. CONFIG_IN_FILENAME = re.compile(r"Config\.\S*$")
  88. DO_CHECK_INTREE = re.compile(r"|".join([
  89. r".checkpackageignore",
  90. r"Config.in",
  91. r"arch/",
  92. r"board/",
  93. r"boot/",
  94. r"configs/",
  95. r"fs/",
  96. r"linux/",
  97. r"package/",
  98. r"support/",
  99. r"system/",
  100. r"toolchain/",
  101. r"utils/",
  102. ]))
  103. DO_NOT_CHECK_INTREE = re.compile(r"|".join([
  104. r"boot/barebox/barebox\.mk$",
  105. r"fs/common\.mk$",
  106. r"package/alchemy/atom.mk.in$",
  107. r"package/doc-asciidoc\.mk$",
  108. r"package/pkg-\S*\.mk$",
  109. r"support/dependencies/[^/]+\.mk$",
  110. r"support/gnuconfig/config\.",
  111. r"support/kconfig/",
  112. r"support/misc/[^/]+\.mk$",
  113. r"support/testing/tests/.*br2-external/",
  114. r"toolchain/helpers\.mk$",
  115. r"toolchain/toolchain-external/pkg-toolchain-external\.mk$",
  116. ]))
  117. SYSV_INIT_SCRIPT_FILENAME = re.compile(r"/S\d\d[^/]+$")
  118. # For defconfigs: avoid matching kernel, uboot... defconfig files, so
  119. # limit to defconfig files in a configs/ directory, either in-tree or
  120. # in a br2-external tree.
  121. BR_DEFCONFIG_FILENAME = re.compile(r"^(.+/)?configs/[^/]+_defconfig$")
  122. def get_lib_from_filename(fname):
  123. if flags.intree_only:
  124. if DO_CHECK_INTREE.match(fname) is None:
  125. return None
  126. if DO_NOT_CHECK_INTREE.match(fname):
  127. return None
  128. else:
  129. if os.path.basename(fname) == "external.mk" and \
  130. os.path.exists(fname[:-2] + "desc"):
  131. return None
  132. if fname == ".checkpackageignore":
  133. return checkpackagelib.lib_ignore
  134. if CONFIG_IN_FILENAME.search(fname):
  135. return checkpackagelib.lib_config
  136. if BR_DEFCONFIG_FILENAME.search(fname):
  137. return checkpackagelib.lib_defconfig
  138. if fname.endswith(".hash"):
  139. return checkpackagelib.lib_hash
  140. if fname.endswith(".mk") or fname.endswith(".mk.in"):
  141. return checkpackagelib.lib_mk
  142. if fname.endswith(".patch"):
  143. return checkpackagelib.lib_patch
  144. if SYSV_INIT_SCRIPT_FILENAME.search(fname):
  145. return checkpackagelib.lib_sysv
  146. return get_lib_from_filetype(fname)
  147. def common_inspect_rules(m):
  148. # do not call the base class
  149. if m.__name__.startswith("_"):
  150. return False
  151. if flags.include_list and m.__name__ not in flags.include_list:
  152. return False
  153. if flags.exclude_list and m.__name__ in flags.exclude_list:
  154. return False
  155. return True
  156. def is_a_check_function(m):
  157. if not inspect.isclass(m):
  158. return False
  159. if not issubclass(m, checkpackagelib.base._CheckFunction):
  160. return False
  161. return common_inspect_rules(m)
  162. def is_external_tool(m):
  163. if not inspect.isclass(m):
  164. return False
  165. if not issubclass(m, checkpackagelib.base._Tool):
  166. return False
  167. return common_inspect_rules(m)
  168. def print_warnings(warnings, xfail):
  169. # Avoid the need to use 'return []' at the end of every check function.
  170. if warnings is None:
  171. return 0, 0 # No warning generated.
  172. if xfail:
  173. return 0, 1 # Warning not generated, fail expected for this file.
  174. for level, message in enumerate(warnings):
  175. if flags.verbose >= level:
  176. print(message.replace("\t", "< tab >").rstrip())
  177. return 1, 1 # One more warning to count.
  178. def check_file_using_lib(fname):
  179. # Count number of warnings generated and lines processed.
  180. nwarnings = 0
  181. nlines = 0
  182. xfail = flags.ignore_list.get(os.path.abspath(fname), [])
  183. failed = set()
  184. lib = get_lib_from_filename(fname)
  185. if not lib:
  186. if flags.verbose >= VERBOSE_LEVEL_TO_SHOW_IGNORED_FILES:
  187. print("{}: ignored".format(fname))
  188. return nwarnings, nlines
  189. internal_functions = inspect.getmembers(lib, is_a_check_function)
  190. external_tools = inspect.getmembers(lib, is_external_tool)
  191. all_checks = internal_functions + external_tools
  192. if flags.dry_run:
  193. functions_to_run = [c[0] for c in all_checks]
  194. print("{}: would run: {}".format(fname, functions_to_run))
  195. return nwarnings, nlines
  196. objects = [[f"{lib.__name__[16:]}.{c[0]}", c[1](fname, flags.manual_url)] for c in internal_functions]
  197. for name, cf in objects:
  198. warn, fail = print_warnings(cf.before(), name in xfail)
  199. if fail > 0:
  200. failed.add(name)
  201. nwarnings += warn
  202. lastline = ""
  203. with open(fname, "r", errors="surrogateescape") as f:
  204. for lineno, text in enumerate(f):
  205. nlines += 1
  206. for name, cf in objects:
  207. if cf.disable.search(lastline):
  208. continue
  209. line_sts = cf.check_line(lineno + 1, text)
  210. warn, fail = print_warnings(line_sts, name in xfail)
  211. if fail > 0:
  212. failed.add(name)
  213. nwarnings += warn
  214. lastline = text
  215. for name, cf in objects:
  216. warn, fail = print_warnings(cf.after(), name in xfail)
  217. if fail > 0:
  218. failed.add(name)
  219. nwarnings += warn
  220. tools = [[c[0], c[1](fname)] for c in external_tools]
  221. for name, tool in tools:
  222. warn, fail = print_warnings(tool.run(), name in xfail)
  223. if fail > 0:
  224. failed.add(name)
  225. nwarnings += warn
  226. for should_fail in xfail:
  227. if should_fail not in failed:
  228. print("{}:0: {} was expected to fail, did you fix the file and forget to update {}?"
  229. .format(fname, should_fail, flags.ignore_filename))
  230. nwarnings += 1
  231. if flags.failed_only:
  232. if len(failed) > 0:
  233. f = " ".join(sorted(failed))
  234. print("{} {}".format(fname, f))
  235. return nwarnings, nlines
  236. def __main__():
  237. global flags
  238. flags = parse_args()
  239. if flags.intree_only:
  240. # change all paths received to be relative to the base dir
  241. base_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
  242. files_to_check = [os.path.relpath(os.path.abspath(f), base_dir) for f in flags.files]
  243. # move current dir so the script find the files
  244. os.chdir(base_dir)
  245. else:
  246. files_to_check = flags.files
  247. if len(files_to_check) == 0:
  248. print("No files to check style")
  249. sys.exit(1)
  250. # Accumulate number of warnings generated and lines processed.
  251. total_warnings = 0
  252. total_lines = 0
  253. for fname in files_to_check:
  254. nwarnings, nlines = check_file_using_lib(fname)
  255. total_warnings += nwarnings
  256. total_lines += nlines
  257. # The warning messages are printed to stdout and can be post-processed
  258. # (e.g. counted by 'wc'), so for stats use stderr. Wait all warnings are
  259. # printed, for the case there are many of them, before printing stats.
  260. sys.stdout.flush()
  261. if not flags.quiet:
  262. print("{} lines processed".format(total_lines), file=sys.stderr)
  263. print("{} warnings generated".format(total_warnings), file=sys.stderr)
  264. if total_warnings > 0 and not flags.failed_only:
  265. sys.exit(1)
  266. __main__()