check-package 10 KB

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