checkpatch.py 5.4 KB

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