check-package 8.8 KB

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