checkpatch.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. # SPDX-License-Identifier: GPL-2.0+
  2. # Copyright (c) 2011 The Chromium OS Authors.
  3. #
  4. import collections
  5. import command
  6. import gitutil
  7. import os
  8. import re
  9. import sys
  10. import terminal
  11. def FindCheckPatch():
  12. top_level = gitutil.GetTopLevel()
  13. try_list = [
  14. os.getcwd(),
  15. os.path.join(os.getcwd(), '..', '..'),
  16. os.path.join(top_level, 'tools'),
  17. os.path.join(top_level, 'scripts'),
  18. '%s/bin' % os.getenv('HOME'),
  19. ]
  20. # Look in current dir
  21. for path in try_list:
  22. fname = os.path.join(path, 'checkpatch.pl')
  23. if os.path.isfile(fname):
  24. return fname
  25. # Look upwwards for a Chrome OS tree
  26. while not os.path.ismount(path):
  27. fname = os.path.join(path, 'src', 'third_party', 'kernel', 'files',
  28. 'scripts', 'checkpatch.pl')
  29. if os.path.isfile(fname):
  30. return fname
  31. path = os.path.dirname(path)
  32. sys.exit('Cannot find checkpatch.pl - please put it in your ' +
  33. '~/bin directory or use --no-check')
  34. def CheckPatch(fname, verbose=False):
  35. """Run checkpatch.pl on a file.
  36. Returns:
  37. namedtuple containing:
  38. ok: False=failure, True=ok
  39. problems: List of problems, each a dict:
  40. 'type'; error or warning
  41. 'msg': text message
  42. 'file' : filename
  43. 'line': line number
  44. errors: Number of errors
  45. warnings: Number of warnings
  46. checks: Number of checks
  47. lines: Number of lines
  48. stdout: Full output of checkpatch
  49. """
  50. fields = ['ok', 'problems', 'errors', 'warnings', 'checks', 'lines',
  51. 'stdout']
  52. result = collections.namedtuple('CheckPatchResult', fields)
  53. result.ok = False
  54. result.errors, result.warning, result.checks = 0, 0, 0
  55. result.lines = 0
  56. result.problems = []
  57. chk = FindCheckPatch()
  58. item = {}
  59. result.stdout = command.Output(chk, '--no-tree', fname,
  60. raise_on_error=False)
  61. #pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE)
  62. #stdout, stderr = pipe.communicate()
  63. # total: 0 errors, 0 warnings, 159 lines checked
  64. # or:
  65. # total: 0 errors, 2 warnings, 7 checks, 473 lines checked
  66. re_stats = re.compile('total: (\\d+) errors, (\d+) warnings, (\d+)')
  67. re_stats_full = re.compile('total: (\\d+) errors, (\d+) warnings, (\d+)'
  68. ' checks, (\d+)')
  69. re_ok = re.compile('.*has no obvious style problems')
  70. re_bad = re.compile('.*has style problems, please review')
  71. re_error = re.compile('ERROR: (.*)')
  72. re_warning = re.compile('WARNING: (.*)')
  73. re_check = re.compile('CHECK: (.*)')
  74. re_file = re.compile('#\d+: FILE: ([^:]*):(\d+):')
  75. for line in result.stdout.splitlines():
  76. if verbose:
  77. print(line)
  78. # A blank line indicates the end of a message
  79. if not line and item:
  80. result.problems.append(item)
  81. item = {}
  82. match = re_stats_full.match(line)
  83. if not match:
  84. match = re_stats.match(line)
  85. if match:
  86. result.errors = int(match.group(1))
  87. result.warnings = int(match.group(2))
  88. if len(match.groups()) == 4:
  89. result.checks = int(match.group(3))
  90. result.lines = int(match.group(4))
  91. else:
  92. result.lines = int(match.group(3))
  93. elif re_ok.match(line):
  94. result.ok = True
  95. elif re_bad.match(line):
  96. result.ok = False
  97. err_match = re_error.match(line)
  98. warn_match = re_warning.match(line)
  99. file_match = re_file.match(line)
  100. check_match = re_check.match(line)
  101. if err_match:
  102. item['msg'] = err_match.group(1)
  103. item['type'] = 'error'
  104. elif warn_match:
  105. item['msg'] = warn_match.group(1)
  106. item['type'] = 'warning'
  107. elif check_match:
  108. item['msg'] = check_match.group(1)
  109. item['type'] = 'check'
  110. elif file_match:
  111. item['file'] = file_match.group(1)
  112. item['line'] = int(file_match.group(2))
  113. return result
  114. def GetWarningMsg(col, msg_type, fname, line, msg):
  115. '''Create a message for a given file/line
  116. Args:
  117. msg_type: Message type ('error' or 'warning')
  118. fname: Filename which reports the problem
  119. line: Line number where it was noticed
  120. msg: Message to report
  121. '''
  122. if msg_type == 'warning':
  123. msg_type = col.Color(col.YELLOW, msg_type)
  124. elif msg_type == 'error':
  125. msg_type = col.Color(col.RED, msg_type)
  126. elif msg_type == 'check':
  127. msg_type = col.Color(col.MAGENTA, msg_type)
  128. return '%s:%d: %s: %s\n' % (fname, line, msg_type, msg)
  129. def CheckPatches(verbose, args):
  130. '''Run the checkpatch.pl script on each patch'''
  131. error_count, warning_count, check_count = 0, 0, 0
  132. col = terminal.Color()
  133. for fname in args:
  134. result = CheckPatch(fname, verbose)
  135. if not result.ok:
  136. error_count += result.errors
  137. warning_count += result.warnings
  138. check_count += result.checks
  139. print('%d errors, %d warnings, %d checks for %s:' % (result.errors,
  140. result.warnings, result.checks, col.Color(col.BLUE, fname)))
  141. if (len(result.problems) != result.errors + result.warnings +
  142. result.checks):
  143. print("Internal error: some problems lost")
  144. for item in result.problems:
  145. sys.stderr.write(
  146. GetWarningMsg(col, item.get('type', '<unknown>'),
  147. item.get('file', '<unknown>'),
  148. item.get('line', 0), item.get('msg', 'message')))
  149. print
  150. #print(stdout)
  151. if error_count or warning_count or check_count:
  152. str = 'checkpatch.pl found %d error(s), %d warning(s), %d checks(s)'
  153. color = col.GREEN
  154. if warning_count:
  155. color = col.YELLOW
  156. if error_count:
  157. color = col.RED
  158. print(col.Color(color, str % (error_count, warning_count, check_count)))
  159. return False
  160. return True