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