check-package 9.7 KB

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