checkpatch.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. # Copyright (c) 2011 The Chromium OS Authors.
  2. #
  3. # See file CREDITS for list of people who contributed to this
  4. # project.
  5. #
  6. # This program is free software; you can redistribute it and/or
  7. # modify it under the terms of the GNU General Public License as
  8. # published by the Free Software Foundation; either version 2 of
  9. # the License, or (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program; if not, write to the Free Software
  18. # Foundation, Inc., 59 Temple Place, Suite 330, Boston,
  19. # MA 02111-1307 USA
  20. #
  21. import collections
  22. import command
  23. import gitutil
  24. import os
  25. import re
  26. import sys
  27. import terminal
  28. def FindCheckPatch():
  29. top_level = gitutil.GetTopLevel()
  30. try_list = [
  31. os.getcwd(),
  32. os.path.join(os.getcwd(), '..', '..'),
  33. os.path.join(top_level, 'tools'),
  34. os.path.join(top_level, 'scripts'),
  35. '%s/bin' % os.getenv('HOME'),
  36. ]
  37. # Look in current dir
  38. for path in try_list:
  39. fname = os.path.join(path, 'checkpatch.pl')
  40. if os.path.isfile(fname):
  41. return fname
  42. # Look upwwards for a Chrome OS tree
  43. while not os.path.ismount(path):
  44. fname = os.path.join(path, 'src', 'third_party', 'kernel', 'files',
  45. 'scripts', 'checkpatch.pl')
  46. if os.path.isfile(fname):
  47. return fname
  48. path = os.path.dirname(path)
  49. print >> sys.stderr, ('Cannot find checkpatch.pl - please put it in your ' +
  50. '~/bin directory or use --no-check')
  51. sys.exit(1)
  52. def CheckPatch(fname, verbose=False):
  53. """Run checkpatch.pl on a file.
  54. Returns:
  55. namedtuple containing:
  56. ok: False=failure, True=ok
  57. problems: List of problems, each a dict:
  58. 'type'; error or warning
  59. 'msg': text message
  60. 'file' : filename
  61. 'line': line number
  62. errors: Number of errors
  63. warnings: Number of warnings
  64. checks: Number of checks
  65. lines: Number of lines
  66. stdout: Full output of checkpatch
  67. """
  68. fields = ['ok', 'problems', 'errors', 'warnings', 'checks', 'lines',
  69. 'stdout']
  70. result = collections.namedtuple('CheckPatchResult', fields)
  71. result.ok = False
  72. result.errors, result.warning, result.checks = 0, 0, 0
  73. result.lines = 0
  74. result.problems = []
  75. chk = FindCheckPatch()
  76. item = {}
  77. result.stdout = command.Output(chk, '--no-tree', fname)
  78. #pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE)
  79. #stdout, stderr = pipe.communicate()
  80. # total: 0 errors, 0 warnings, 159 lines checked
  81. # or:
  82. # total: 0 errors, 2 warnings, 7 checks, 473 lines checked
  83. re_stats = re.compile('total: (\\d+) errors, (\d+) warnings, (\d+)')
  84. re_stats_full = re.compile('total: (\\d+) errors, (\d+) warnings, (\d+)'
  85. ' checks, (\d+)')
  86. re_ok = re.compile('.*has no obvious style problems')
  87. re_bad = re.compile('.*has style problems, please review')
  88. re_error = re.compile('ERROR: (.*)')
  89. re_warning = re.compile('WARNING: (.*)')
  90. re_check = re.compile('CHECK: (.*)')
  91. re_file = re.compile('#\d+: FILE: ([^:]*):(\d+):')
  92. for line in result.stdout.splitlines():
  93. if verbose:
  94. print line
  95. # A blank line indicates the end of a message
  96. if not line and item:
  97. result.problems.append(item)
  98. item = {}
  99. match = re_stats_full.match(line)
  100. if not match:
  101. match = re_stats.match(line)
  102. if match:
  103. result.errors = int(match.group(1))
  104. result.warnings = int(match.group(2))
  105. if len(match.groups()) == 4:
  106. result.checks = int(match.group(3))
  107. result.lines = int(match.group(4))
  108. else:
  109. result.lines = int(match.group(3))
  110. elif re_ok.match(line):
  111. result.ok = True
  112. elif re_bad.match(line):
  113. result.ok = False
  114. err_match = re_error.match(line)
  115. warn_match = re_warning.match(line)
  116. file_match = re_file.match(line)
  117. check_match = re_check.match(line)
  118. if err_match:
  119. item['msg'] = err_match.group(1)
  120. item['type'] = 'error'
  121. elif warn_match:
  122. item['msg'] = warn_match.group(1)
  123. item['type'] = 'warning'
  124. elif check_match:
  125. item['msg'] = check_match.group(1)
  126. item['type'] = 'check'
  127. elif file_match:
  128. item['file'] = file_match.group(1)
  129. item['line'] = int(file_match.group(2))
  130. return result
  131. def GetWarningMsg(col, msg_type, fname, line, msg):
  132. '''Create a message for a given file/line
  133. Args:
  134. msg_type: Message type ('error' or 'warning')
  135. fname: Filename which reports the problem
  136. line: Line number where it was noticed
  137. msg: Message to report
  138. '''
  139. if msg_type == 'warning':
  140. msg_type = col.Color(col.YELLOW, msg_type)
  141. elif msg_type == 'error':
  142. msg_type = col.Color(col.RED, msg_type)
  143. elif msg_type == 'check':
  144. msg_type = col.Color(col.MAGENTA, msg_type)
  145. return '%s: %s,%d: %s' % (msg_type, fname, line, msg)
  146. def CheckPatches(verbose, args):
  147. '''Run the checkpatch.pl script on each patch'''
  148. error_count, warning_count, check_count = 0, 0, 0
  149. col = terminal.Color()
  150. for fname in args:
  151. result = CheckPatch(fname, verbose)
  152. if not result.ok:
  153. error_count += result.errors
  154. warning_count += result.warnings
  155. check_count += result.checks
  156. print '%d errors, %d warnings, %d checks for %s:' % (result.errors,
  157. result.warnings, result.checks, col.Color(col.BLUE, fname))
  158. if (len(result.problems) != result.errors + result.warnings +
  159. result.checks):
  160. print "Internal error: some problems lost"
  161. for item in result.problems:
  162. print GetWarningMsg(col, item.get('type', '<unknown>'),
  163. item.get('file', '<unknown>'),
  164. item.get('line', 0), item.get('msg', 'message'))
  165. print
  166. #print stdout
  167. if error_count or warning_count or check_count:
  168. str = 'checkpatch.pl found %d error(s), %d warning(s), %d checks(s)'
  169. color = col.GREEN
  170. if warning_count:
  171. color = col.YELLOW
  172. if error_count:
  173. color = col.RED
  174. print col.Color(color, str % (error_count, warning_count, check_count))
  175. return False
  176. return True