check-package 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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.lib_config
  10. import checkpackagelib.lib_hash
  11. import checkpackagelib.lib_mk
  12. import checkpackagelib.lib_patch
  13. VERBOSE_LEVEL_TO_SHOW_IGNORED_FILES = 3
  14. flags = None # Command line arguments.
  15. def parse_args():
  16. parser = argparse.ArgumentParser()
  17. # Do not use argparse.FileType("r") here because only files with known
  18. # format will be open based on the filename.
  19. parser.add_argument("files", metavar="F", type=str, nargs="*",
  20. help="list of files")
  21. parser.add_argument("--br2-external", "-b", dest='intree_only', action="store_false",
  22. help="do not apply the pathname filters used for intree files")
  23. parser.add_argument("--manual-url", action="store",
  24. default="http://nightly.buildroot.org/",
  25. help="default: %(default)s")
  26. parser.add_argument("--verbose", "-v", action="count", default=0)
  27. parser.add_argument("--quiet", "-q", action="count", default=0)
  28. # Now the debug options in the order they are processed.
  29. parser.add_argument("--include-only", dest="include_list", action="append",
  30. help="run only the specified functions (debug)")
  31. parser.add_argument("--exclude", dest="exclude_list", action="append",
  32. help="do not run the specified functions (debug)")
  33. parser.add_argument("--dry-run", action="store_true", help="print the "
  34. "functions that would be called for each file (debug)")
  35. return parser.parse_args()
  36. CONFIG_IN_FILENAME = re.compile(r"Config\.\S*$")
  37. DO_CHECK_INTREE = re.compile(r"|".join([
  38. r"Config.in",
  39. r"arch/",
  40. r"boot/",
  41. r"fs/",
  42. r"linux/",
  43. r"package/",
  44. r"system/",
  45. r"toolchain/",
  46. ]))
  47. DO_NOT_CHECK_INTREE = re.compile(r"|".join([
  48. r"boot/barebox/barebox\.mk$",
  49. r"fs/common\.mk$",
  50. r"package/doc-asciidoc\.mk$",
  51. r"package/pkg-\S*\.mk$",
  52. r"toolchain/helpers\.mk$",
  53. r"toolchain/toolchain-external/pkg-toolchain-external\.mk$",
  54. ]))
  55. def get_lib_from_filename(fname):
  56. if flags.intree_only:
  57. if DO_CHECK_INTREE.match(fname) is None:
  58. return None
  59. if DO_NOT_CHECK_INTREE.match(fname):
  60. return None
  61. else:
  62. if os.path.basename(fname) == "external.mk" and \
  63. os.path.exists(fname[:-2] + "desc"):
  64. return None
  65. if CONFIG_IN_FILENAME.search(fname):
  66. return checkpackagelib.lib_config
  67. if fname.endswith(".hash"):
  68. return checkpackagelib.lib_hash
  69. if fname.endswith(".mk"):
  70. return checkpackagelib.lib_mk
  71. if fname.endswith(".patch"):
  72. return checkpackagelib.lib_patch
  73. return None
  74. def is_a_check_function(m):
  75. if not inspect.isclass(m):
  76. return False
  77. # do not call the base class
  78. if m.__name__.startswith("_"):
  79. return False
  80. if flags.include_list and m.__name__ not in flags.include_list:
  81. return False
  82. if flags.exclude_list and m.__name__ in flags.exclude_list:
  83. return False
  84. return True
  85. def print_warnings(warnings):
  86. # Avoid the need to use 'return []' at the end of every check function.
  87. if warnings is None:
  88. return 0 # No warning generated.
  89. for level, message in enumerate(warnings):
  90. if flags.verbose >= level:
  91. print(message.replace("\t", "< tab >").rstrip())
  92. return 1 # One more warning to count.
  93. def check_file_using_lib(fname):
  94. # Count number of warnings generated and lines processed.
  95. nwarnings = 0
  96. nlines = 0
  97. lib = get_lib_from_filename(fname)
  98. if not lib:
  99. if flags.verbose >= VERBOSE_LEVEL_TO_SHOW_IGNORED_FILES:
  100. print("{}: ignored".format(fname))
  101. return nwarnings, nlines
  102. classes = inspect.getmembers(lib, is_a_check_function)
  103. if flags.dry_run:
  104. functions_to_run = [c[0] for c in classes]
  105. print("{}: would run: {}".format(fname, functions_to_run))
  106. return nwarnings, nlines
  107. objects = [c[1](fname, flags.manual_url) for c in classes]
  108. for cf in objects:
  109. nwarnings += print_warnings(cf.before())
  110. if six.PY3:
  111. f = open(fname, "r", errors="surrogateescape")
  112. else:
  113. f = open(fname, "r")
  114. lastline = ""
  115. for lineno, text in enumerate(f.readlines()):
  116. nlines += 1
  117. for cf in objects:
  118. if cf.disable.search(lastline):
  119. continue
  120. nwarnings += print_warnings(cf.check_line(lineno + 1, text))
  121. lastline = text
  122. f.close()
  123. for cf in objects:
  124. nwarnings += print_warnings(cf.after())
  125. return nwarnings, nlines
  126. def __main__():
  127. global flags
  128. flags = parse_args()
  129. if flags.intree_only:
  130. # change all paths received to be relative to the base dir
  131. base_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
  132. files_to_check = [os.path.relpath(os.path.abspath(f), base_dir) for f in flags.files]
  133. # move current dir so the script find the files
  134. os.chdir(base_dir)
  135. else:
  136. files_to_check = flags.files
  137. if len(files_to_check) == 0:
  138. print("No files to check style")
  139. sys.exit(1)
  140. # Accumulate number of warnings generated and lines processed.
  141. total_warnings = 0
  142. total_lines = 0
  143. for fname in files_to_check:
  144. nwarnings, nlines = check_file_using_lib(fname)
  145. total_warnings += nwarnings
  146. total_lines += nlines
  147. # The warning messages are printed to stdout and can be post-processed
  148. # (e.g. counted by 'wc'), so for stats use stderr. Wait all warnings are
  149. # printed, for the case there are many of them, before printing stats.
  150. sys.stdout.flush()
  151. if not flags.quiet:
  152. print("{} lines processed".format(total_lines), file=sys.stderr)
  153. print("{} warnings generated".format(total_warnings), file=sys.stderr)
  154. if total_warnings > 0:
  155. sys.exit(1)
  156. __main__()