checkpatch.py 5.3 KB

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