check-package 11 KB

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