blob: a8c1288d4bf906a2cd1aecc392617610a80ba47f [file] [log] [blame]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001# Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5import os
Ryan Cuiec4d6332011-05-02 14:15:25 -07006import re
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07007import subprocess
8
Ryan Cuiec4d6332011-05-02 14:15:25 -07009
10# General Helpers
11
12COMMON_INCLUDED_PATHS = [
13 # C++ and friends
14 r".*\.c$", r".*\.cc$", r".*\.cpp$", r".*\.h$", r".*\.m$", r".*\.mm$",
15 r".*\.inl$", r".*\.asm$", r".*\.hxx$", r".*\.hpp$", r".*\.s$", r".*\.S$",
16 # Scripts
17 r".*\.js$", r".*\.py$", r".*\.sh$", r".*\.rb$", r".*\.pl$", r".*\.pm$",
18 # No extension at all, note that ALL CAPS files are black listed in
19 # COMMON_EXCLUDED_LIST below.
20 r"(^|.*?[\\\/])[^.]+$",
21 # Other
22 r".*\.java$", r".*\.mk$", r".*\.am$",
23]
24
25COMMON_EXCLUDED_PATHS = [
26 # avoid doing source file checks for kernel
27 r"/src/third_party/kernel/",
28 r"/src/third_party/kernel-next/",
29 r".*\bexperimental[\\\/].*",
30 r".*\b[A-Z0-9_]{2,}$",
31 r".*[\\\/]debian[\\\/]rules$",
32]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070033
34def _get_hooks_dir():
Ryan Cuiec4d6332011-05-02 14:15:25 -070035 """Returns the absolute path to the repohooks directory."""
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070036 cmd = ['repo', 'forall', 'chromiumos/repohooks', '-c', 'pwd']
37 return subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0].strip()
38
Ryan Cuiec4d6332011-05-02 14:15:25 -070039def _match_regex_list(subject, expressions):
40 """Try to match a list of regular expressions to a string.
41
42 Args:
43 subject: The string to match regexes on
44 expressions: A list of regular expressions to check for matches with.
45
46 Returns:
47 Whether the passed in subject matches any of the passed in regexes.
48 """
49 for expr in expressions:
50 if (re.search(expr, subject)):
51 return True
52 return False
53
54def _filter_files(files, include_list, exclude_list=[]):
55 """Filter out files based on the conditions passed in.
56
57 Args:
58 files: list of filepaths to filter
59 include_list: list of regex that when matched with a file path will cause it
60 to be added to the output list unless the file is also matched with a
61 regex in the exclude_list.
62 exclude_list: list of regex that when matched with a file will prevent it
63 from being added to the output list, even if it is also matched with a
64 regex in the include_list.
65
66 Returns:
67 A list of filepaths that contain files matched in the include_list and not
68 in the exclude_list.
69 """
70 filtered = []
71 for f in files:
72 if (_match_regex_list(f, include_list) and
73 not _match_regex_list(f, exclude_list)):
74 filtered.append(f)
75 return filtered
76
77def _report_error(msg, items=None):
78 """Raises an exception with the passed in error message.
79
80 If extra error detail is passed in, it will be appended to the error message.
81
82 Args:
83 msg: Error message header.
84 items: A list of lines that follow the header that give extra error
85 information.
86 """
87 if items:
88 msg += '\n' + '\n'.join(items)
89 raise Exception(msg)
90
91
92# Git Helpers
93
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -070094def _get_diff(commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -070095 """Returns the diff for this commit."""
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -070096 cmd = ['git', 'show', commit]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070097 return subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
98
Ryan Cuiec4d6332011-05-02 14:15:25 -070099def _get_file_diff(file, commit):
100 """Returns a list of (linenum, lines) tuples that the commit touched."""
101 cmd = ['git', 'show', '-p', '--no-ext-diff', commit, file]
102 output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
103
104 new_lines = []
105 line_num = 0
106 for line in output.splitlines():
107 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
108 if m:
109 line_num = int(m.groups(1)[0])
110 continue
111 if line.startswith('+') and not line.startswith('++'):
112 new_lines.append((line_num, line[1:]))
113 if not line.startswith('-'):
114 line_num += 1
115 return new_lines
116
117def _get_affected_files(commit):
118 """Returns list of absolute filepaths that were modified/added."""
119 cmd = ['git', 'diff', '--name-status', commit + '^!']
120 output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
121 files = []
122 for statusline in output.splitlines():
123 m = re.match('^(\w)+\t(.+)$', statusline.rstrip())
124 # Ignore deleted files, and return absolute paths of files
125 if (m.group(1)[0] != 'D'):
126 pwd = os.getcwd()
127 files.append(os.path.join(pwd, m.group(2)))
128 return files
129
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700130def _get_commits():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700131 """Returns a list of commits for this review."""
132 cmd = ['git', 'log', 'm/master..', '--format=%H']
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700133 commits = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
134 return commits.split()
135
Ryan Cuiec4d6332011-05-02 14:15:25 -0700136def _get_commit_desc(commit):
137 """Returns the full commit message of a commit."""
138 cmd = ['git', 'log', '--format=%B', commit + '^!']
139 description = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
140 return description.splitlines()
141
142
143# Common Hooks
144
145def _check_no_long_lines(project, commit):
146 """Checks that there aren't any lines longer than maxlen characters in any of
147 the text files to be submitted.
148 """
149 MAX_LEN = 80
150
151 errors = []
152 files = _filter_files(_get_affected_files(commit),
153 COMMON_INCLUDED_PATHS,
154 COMMON_EXCLUDED_PATHS)
155
156 for afile in files:
157 for line_num, line in _get_file_diff(afile, commit):
158 # Allow certain lines to exceed the maxlen rule.
159 if (len(line) > MAX_LEN and
160 not 'http://' in line and
161 not 'https://' in line and
162 not line.startswith('#define') and
163 not line.startswith('#include') and
164 not line.startswith('#import') and
165 not line.startswith('#pragma') and
166 not line.startswith('#if') and
167 not line.startswith('#endif')):
168 errors.append('%s, line %s, %s chars' % (afile, line_num, len(line)))
169 if len(errors) == 5: # Just show the first 5 errors.
170 break
171
172 if errors:
173 msg = 'Found lines longer than %s characters (first 5 shown):' % MAX_LEN
174 _report_error(msg, errors)
175
176def _check_no_stray_whitespace(project, commit):
177 """Checks that there is no stray whitespace at source lines end."""
178 errors = []
179 files = _filter_files(_get_affected_files(commit),
180 COMMON_INCLUDED_PATHS,
181 COMMON_EXCLUDED_PATHS)
182
183 for afile in files:
184 for line_num, line in _get_file_diff(afile, commit):
185 if line.rstrip() != line:
186 errors.append('%s, line %s' % (afile, line_num))
187 if errors:
188 _report_error('Found line ending with white space in:', errors)
189
190def _check_no_tabs(project, commit):
191 """Checks there are no unexpanded tabs."""
192 TAB_OK_PATHS = [
193 r"/src/third_party/u-boot/",
194 r"/src/third_party/u-boot-next/",
195 r".*\.ebuild$",
196 r".*\.eclass$",
197 r".*/[M|m]akefile$"
198 ]
199
200 errors = []
201 files = _filter_files(_get_affected_files(commit),
202 COMMON_INCLUDED_PATHS,
203 COMMON_EXCLUDED_PATHS + TAB_OK_PATHS)
204
205 for afile in files:
206 for line_num, line in _get_file_diff(afile, commit):
207 if '\t' in line:
208 errors.append('%s, line %s' % (afile, line_num))
209 if errors:
210 _report_error('Found a tab character in:', errors)
211
212def _check_change_has_test_field(project, commit):
213 """Check for a non-empty 'TEST=' field in the commit message."""
214 TEST_RE = r'^\s*TEST\s*=\s*\S+.*$'
215
216 found_field = False
217 for line in _get_commit_desc(commit):
218
219 if re.match(TEST_RE, line):
220 found_field = True
221 break
222
223 if not found_field:
224 _report_error('Changelist description needs TEST field')
225
226def _check_change_has_bug_field(project, commit):
227 """Check for a non-empty 'BUG=' field in the commit message."""
228 BUG_RE = r'^\s*BUG\s*=\s*\S+.*$'
229
230 found_field = False
231 for line in _get_commit_desc(commit):
232 if re.match(BUG_RE, line):
233 found_field = True
234 break
235
236 if not found_field:
237 _report_error('Changelist description needs BUG field')
238
239def _check_license(project, commit):
240 """Verifies the license header."""
241 LICENSE_HEADER = (
242 r".*? Copyright \(c\) 20[-0-9]{2,7} The Chromium OS Authors\. All rights "
243 r"reserved\." "\n"
244 r".*? Use of this source code is governed by a BSD-style license that can "
245 "be\n"
246 r".*? found in the LICENSE file\."
247 "\n"
248 )
249
250 license_re = re.compile(LICENSE_HEADER, re.MULTILINE)
251 bad_files = []
252 files = _filter_files(_get_affected_files(commit),
253 COMMON_INCLUDED_PATHS,
254 COMMON_EXCLUDED_PATHS)
255
256 for f in files:
257 contents = open(f).read()
258 if len(contents) == 0: continue # Ignore empty files
259 if not license_re.search(contents):
260 bad_files.append(f)
261 if bad_files:
262 _report_error('License must match:\n%s\n' % license_re.pattern +
263 'Found a bad license header in these files:',
264 bad_files)
265
266
267# Project-specific hooks
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700268
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700269def _run_checkpatch(project, commit):
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700270 """Runs checkpatch.pl on the given project"""
271 hooks_dir = _get_hooks_dir()
272 cmd = ['%s/checkpatch.pl' % hooks_dir, '-']
273 p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700274 output = p.communicate(_get_diff(commit))[0]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700275 if p.returncode:
Ryan Cuiec4d6332011-05-02 14:15:25 -0700276 _report_error('checkpatch.pl errors/warnings\n\n' + output)
277
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700278
279# Base
280
Ryan Cuiec4d6332011-05-02 14:15:25 -0700281COMMON_HOOKS = [_check_no_long_lines,
282 _check_no_stray_whitespace,
283 _check_no_tabs,
284 _check_change_has_test_field,
285 _check_change_has_bug_field,
286 _check_license]
287
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700288def _setup_project_hooks():
289 """Returns a dictionay of callbacks: dict[project] = [callback1, callback2]"""
290 return {
Doug Anderson830216f2011-05-02 10:08:37 -0700291 "chromiumos/third_party/kernel": [_run_checkpatch],
292 "chromiumos/third_party/kernel-next": [_run_checkpatch],
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700293 }
294
295def _run_project_hooks(project, hooks):
296 """For each project run its project specific hook from the hooks dictionary"""
297 cmd = ['repo', 'forall', project, '-c', 'pwd']
298 proj_dir = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
299 proj_dir = proj_dir.strip()
Ryan Cuiec4d6332011-05-02 14:15:25 -0700300 pwd = os.getcwd()
301 # hooks assume they are run from the root of the project
302 os.chdir(proj_dir)
303
304 project_specific_hooks = []
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700305 if project in hooks:
Ryan Cuiec4d6332011-05-02 14:15:25 -0700306 project_specific_hooks = hooks[project]
307
308 for commit in _get_commits():
309 for hook in COMMON_HOOKS + project_specific_hooks:
310 hook(project, commit)
311 os.chdir(pwd)
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700312
313# Main
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -0700314
Anush Elangovan63afad72011-03-23 00:41:27 -0700315def main(project_list, **kwargs):
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700316 hooks = _setup_project_hooks()
317 for project in project_list:
318 _run_project_hooks(project, hooks)
Anush Elangovan63afad72011-03-23 00:41:27 -0700319
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -0700320if __name__ == '__main__':
321 main()