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