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