check-package 9.6 KB

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