blob: b33105b04a56da8384e3b215d4e20c084abe2759 [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
Dale Curtis2975c432011-05-03 17:25:20 -07005import json
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07006import os
Ryan Cuiec4d6332011-05-02 14:15:25 -07007import re
Mandeep Singh Bainesa7ffa4b2011-05-03 11:37:02 -07008import sys
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07009import subprocess
10
Don Garrettdba548a2011-05-05 15:17:14 -070011class VerifyException(Exception):
12 pass
Ryan Cuiec4d6332011-05-02 14:15:25 -070013
14# General Helpers
15
16COMMON_INCLUDED_PATHS = [
17 # C++ and friends
18 r".*\.c$", r".*\.cc$", r".*\.cpp$", r".*\.h$", r".*\.m$", r".*\.mm$",
19 r".*\.inl$", r".*\.asm$", r".*\.hxx$", r".*\.hpp$", r".*\.s$", r".*\.S$",
20 # Scripts
21 r".*\.js$", r".*\.py$", r".*\.sh$", r".*\.rb$", r".*\.pl$", r".*\.pm$",
22 # No extension at all, note that ALL CAPS files are black listed in
23 # COMMON_EXCLUDED_LIST below.
24 r"(^|.*?[\\\/])[^.]+$",
25 # Other
26 r".*\.java$", r".*\.mk$", r".*\.am$",
27]
28
29COMMON_EXCLUDED_PATHS = [
Ryan Cui31e0c172011-05-04 21:00:45 -070030 # avoid doing source file checks for kernel
31 r"/src/third_party/kernel/",
32 r"/src/third_party/kernel-next/",
Paul Taysomf8b6e012011-05-09 14:32:42 -070033 r"/src/third_party/ktop/",
34 r"/src/third_party/punybench/",
Ryan Cuiec4d6332011-05-02 14:15:25 -070035 r".*\bexperimental[\\\/].*",
36 r".*\b[A-Z0-9_]{2,}$",
37 r".*[\\\/]debian[\\\/]rules$",
38]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070039
Sean Paul19baef02011-05-05 17:10:31 -040040MIN_GIT_VERSION = [1, 7, 2]
Sean Paulba01d402011-05-05 11:36:23 -040041
Ryan Cui72834d12011-05-05 14:51:33 -070042def _run_command(cmd):
43 """Executes the passed in command and returns raw stdout output."""
44 return subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
45
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070046def _get_hooks_dir():
Ryan Cuiec4d6332011-05-02 14:15:25 -070047 """Returns the absolute path to the repohooks directory."""
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070048 cmd = ['repo', 'forall', 'chromiumos/repohooks', '-c', 'pwd']
Ryan Cui72834d12011-05-05 14:51:33 -070049 return _run_command(cmd).strip()
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070050
Ryan Cuiec4d6332011-05-02 14:15:25 -070051def _match_regex_list(subject, expressions):
52 """Try to match a list of regular expressions to a string.
53
54 Args:
55 subject: The string to match regexes on
56 expressions: A list of regular expressions to check for matches with.
57
58 Returns:
59 Whether the passed in subject matches any of the passed in regexes.
60 """
61 for expr in expressions:
62 if (re.search(expr, subject)):
63 return True
64 return False
65
66def _filter_files(files, include_list, exclude_list=[]):
67 """Filter out files based on the conditions passed in.
68
69 Args:
70 files: list of filepaths to filter
71 include_list: list of regex that when matched with a file path will cause it
72 to be added to the output list unless the file is also matched with a
73 regex in the exclude_list.
74 exclude_list: list of regex that when matched with a file will prevent it
75 from being added to the output list, even if it is also matched with a
76 regex in the include_list.
77
78 Returns:
79 A list of filepaths that contain files matched in the include_list and not
80 in the exclude_list.
81 """
82 filtered = []
83 for f in files:
84 if (_match_regex_list(f, include_list) and
85 not _match_regex_list(f, exclude_list)):
86 filtered.append(f)
87 return filtered
88
89def _report_error(msg, items=None):
90 """Raises an exception with the passed in error message.
91
92 If extra error detail is passed in, it will be appended to the error message.
93
94 Args:
95 msg: Error message header.
96 items: A list of lines that follow the header that give extra error
97 information.
98 """
99 if items:
100 msg += '\n' + '\n'.join(items)
Don Garrettdba548a2011-05-05 15:17:14 -0700101 raise VerifyException(msg)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700102
103
104# Git Helpers
Ryan Cui4725d952011-05-05 15:41:19 -0700105def _get_upstream_branch():
106 """Returns the upstream tracking branch of the current branch.
107
108 Raises:
109 Error if there is no tracking branch
110 """
111 current_branch = _run_command(['git', 'symbolic-ref', 'HEAD']).strip()
112 current_branch = current_branch.replace('refs/heads/', '')
113 if not current_branch:
114 _report_error('Need to be on a tracking branch')
115
116 cfg_option = 'branch.' + current_branch + '.%s'
117 full_upstream = _run_command(['git', 'config', cfg_option % 'merge']).strip()
118 remote = _run_command(['git', 'config', cfg_option % 'remote']).strip()
119 if not remote or not full_upstream:
120 _report_error('Need to be on a tracking branch')
121
122 return full_upstream.replace('heads', 'remotes/' + remote)
123
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700124def _get_diff(commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700125 """Returns the diff for this commit."""
Ryan Cui72834d12011-05-05 14:51:33 -0700126 return _run_command(['git', 'show', commit])
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700127
Ryan Cuiec4d6332011-05-02 14:15:25 -0700128def _get_file_diff(file, commit):
129 """Returns a list of (linenum, lines) tuples that the commit touched."""
Ryan Cui72834d12011-05-05 14:51:33 -0700130 output = _run_command(['git', 'show', '-p', '--no-ext-diff', commit, file])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700131
132 new_lines = []
133 line_num = 0
134 for line in output.splitlines():
135 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
136 if m:
137 line_num = int(m.groups(1)[0])
138 continue
139 if line.startswith('+') and not line.startswith('++'):
140 new_lines.append((line_num, line[1:]))
141 if not line.startswith('-'):
142 line_num += 1
143 return new_lines
144
145def _get_affected_files(commit):
146 """Returns list of absolute filepaths that were modified/added."""
Ryan Cui72834d12011-05-05 14:51:33 -0700147 output = _run_command(['git', 'diff', '--name-status', commit + '^!'])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700148 files = []
149 for statusline in output.splitlines():
150 m = re.match('^(\w)+\t(.+)$', statusline.rstrip())
151 # Ignore deleted files, and return absolute paths of files
152 if (m.group(1)[0] != 'D'):
153 pwd = os.getcwd()
154 files.append(os.path.join(pwd, m.group(2)))
155 return files
156
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700157def _get_commits():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700158 """Returns a list of commits for this review."""
Ryan Cui4725d952011-05-05 15:41:19 -0700159 cmd = ['git', 'log', '%s..' % _get_upstream_branch(), '--format=%H']
Ryan Cui72834d12011-05-05 14:51:33 -0700160 return _run_command(cmd).split()
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700161
Ryan Cuiec4d6332011-05-02 14:15:25 -0700162def _get_commit_desc(commit):
163 """Returns the full commit message of a commit."""
Sean Paul23a2c582011-05-06 13:10:44 -0400164 return _run_command(['git', 'log', '--format=%s%n%n%b', commit + '^!'])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700165
166
167# Common Hooks
168
169def _check_no_long_lines(project, commit):
170 """Checks that there aren't any lines longer than maxlen characters in any of
171 the text files to be submitted.
172 """
173 MAX_LEN = 80
174
175 errors = []
176 files = _filter_files(_get_affected_files(commit),
177 COMMON_INCLUDED_PATHS,
178 COMMON_EXCLUDED_PATHS)
179
180 for afile in files:
181 for line_num, line in _get_file_diff(afile, commit):
182 # Allow certain lines to exceed the maxlen rule.
183 if (len(line) > MAX_LEN and
184 not 'http://' in line and
185 not 'https://' in line and
186 not line.startswith('#define') and
187 not line.startswith('#include') and
188 not line.startswith('#import') and
189 not line.startswith('#pragma') and
190 not line.startswith('#if') and
191 not line.startswith('#endif')):
192 errors.append('%s, line %s, %s chars' % (afile, line_num, len(line)))
193 if len(errors) == 5: # Just show the first 5 errors.
194 break
195
196 if errors:
197 msg = 'Found lines longer than %s characters (first 5 shown):' % MAX_LEN
198 _report_error(msg, errors)
199
200def _check_no_stray_whitespace(project, commit):
201 """Checks that there is no stray whitespace at source lines end."""
202 errors = []
203 files = _filter_files(_get_affected_files(commit),
204 COMMON_INCLUDED_PATHS,
205 COMMON_EXCLUDED_PATHS)
206
207 for afile in files:
208 for line_num, line in _get_file_diff(afile, commit):
209 if line.rstrip() != line:
210 errors.append('%s, line %s' % (afile, line_num))
211 if errors:
212 _report_error('Found line ending with white space in:', errors)
213
214def _check_no_tabs(project, commit):
215 """Checks there are no unexpanded tabs."""
216 TAB_OK_PATHS = [
Doug Anderson0f91cbf2011-05-09 15:56:25 -0700217 r"/src/platform/u-boot-config/",
Ryan Cui31e0c172011-05-04 21:00:45 -0700218 r"/src/third_party/u-boot/",
219 r"/src/third_party/u-boot-next/",
Ryan Cuiec4d6332011-05-02 14:15:25 -0700220 r".*\.ebuild$",
221 r".*\.eclass$",
222 r".*/[M|m]akefile$"
223 ]
224
225 errors = []
226 files = _filter_files(_get_affected_files(commit),
227 COMMON_INCLUDED_PATHS,
228 COMMON_EXCLUDED_PATHS + TAB_OK_PATHS)
229
230 for afile in files:
231 for line_num, line in _get_file_diff(afile, commit):
232 if '\t' in line:
233 errors.append('%s, line %s' % (afile, line_num))
234 if errors:
235 _report_error('Found a tab character in:', errors)
236
237def _check_change_has_test_field(project, commit):
238 """Check for a non-empty 'TEST=' field in the commit message."""
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700239 TEST_RE = r'\n\s*TEST\s*=[^\n]*\S+'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700240
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700241 if not re.search(TEST_RE, _get_commit_desc(commit)):
242 _report_error('Changelist description needs TEST field (after first line)')
Ryan Cuiec4d6332011-05-02 14:15:25 -0700243
244def _check_change_has_bug_field(project, commit):
245 """Check for a non-empty 'BUG=' field in the commit message."""
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700246 BUG_RE = r'\n\s*BUG\s*=[^\n]*\S+'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700247
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700248 if not re.search(BUG_RE, _get_commit_desc(commit)):
249 _report_error('Changelist description needs BUG field (after first line)')
Ryan Cuiec4d6332011-05-02 14:15:25 -0700250
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700251def _check_change_has_proper_changeid(project, commit):
252 """Verify that Change-ID is present in last paragraph of commit message."""
253 desc = _get_commit_desc(commit)
254 loc = desc.rfind('\nChange-Id:')
255 if loc == -1 or re.search('\n\s*\n\s*\S+', desc[loc:]):
256 _report_error('Change-Id must be in last paragraph of description.')
257
Ryan Cuiec4d6332011-05-02 14:15:25 -0700258def _check_license(project, commit):
259 """Verifies the license header."""
260 LICENSE_HEADER = (
261 r".*? Copyright \(c\) 20[-0-9]{2,7} The Chromium OS Authors\. All rights "
262 r"reserved\." "\n"
263 r".*? Use of this source code is governed by a BSD-style license that can "
264 "be\n"
265 r".*? found in the LICENSE file\."
266 "\n"
267 )
268
269 license_re = re.compile(LICENSE_HEADER, re.MULTILINE)
270 bad_files = []
271 files = _filter_files(_get_affected_files(commit),
272 COMMON_INCLUDED_PATHS,
273 COMMON_EXCLUDED_PATHS)
274
275 for f in files:
276 contents = open(f).read()
277 if len(contents) == 0: continue # Ignore empty files
278 if not license_re.search(contents):
279 bad_files.append(f)
280 if bad_files:
281 _report_error('License must match:\n%s\n' % license_re.pattern +
282 'Found a bad license header in these files:',
283 bad_files)
284
285
286# Project-specific hooks
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700287
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700288def _run_checkpatch(project, commit):
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700289 """Runs checkpatch.pl on the given project"""
290 hooks_dir = _get_hooks_dir()
291 cmd = ['%s/checkpatch.pl' % hooks_dir, '-']
292 p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700293 output = p.communicate(_get_diff(commit))[0]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700294 if p.returncode:
Ryan Cuiec4d6332011-05-02 14:15:25 -0700295 _report_error('checkpatch.pl errors/warnings\n\n' + output)
296
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700297
Dale Curtis2975c432011-05-03 17:25:20 -0700298def _run_json_check(project, commit):
299 """Checks that all JSON files are syntactically valid."""
Dale Curtisa039cfd2011-05-04 12:01:05 -0700300 for f in _filter_files(_get_affected_files(commit), [r'.*\.json']):
Dale Curtis2975c432011-05-03 17:25:20 -0700301 try:
302 json.load(open(f))
303 except Exception, e:
304 _report_error('Invalid JSON in %s: %s' % (f, e))
305
306
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700307# Base
308
Ryan Cuie37fe1a2011-05-03 19:00:10 -0700309COMMON_HOOKS = [_check_change_has_bug_field,
310 _check_change_has_test_field,
311 _check_change_has_proper_changeid,
Ryan Cuiec4d6332011-05-02 14:15:25 -0700312 _check_no_stray_whitespace,
Ryan Cui31e0c172011-05-04 21:00:45 -0700313 _check_no_long_lines,
314 _check_license,
315 _check_no_tabs]
Ryan Cuiec4d6332011-05-02 14:15:25 -0700316
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700317def _setup_project_hooks():
318 """Returns a dictionay of callbacks: dict[project] = [callback1, callback2]"""
319 return {
Doug Anderson830216f2011-05-02 10:08:37 -0700320 "chromiumos/third_party/kernel": [_run_checkpatch],
321 "chromiumos/third_party/kernel-next": [_run_checkpatch],
Dale Curtis2975c432011-05-03 17:25:20 -0700322 "chromeos/autotest-tools": [_run_json_check],
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700323 }
324
325def _run_project_hooks(project, hooks):
326 """For each project run its project specific hook from the hooks dictionary"""
Ryan Cui72834d12011-05-05 14:51:33 -0700327 proj_dir = _run_command(['repo', 'forall', project, '-c', 'pwd']).strip()
Ryan Cuiec4d6332011-05-02 14:15:25 -0700328 pwd = os.getcwd()
329 # hooks assume they are run from the root of the project
330 os.chdir(proj_dir)
331
332 project_specific_hooks = []
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700333 if project in hooks:
Ryan Cuiec4d6332011-05-02 14:15:25 -0700334 project_specific_hooks = hooks[project]
335
Ryan Cuifa55df52011-05-06 11:16:55 -0700336 try:
337 commit_list = _get_commits()
Don Garrettdba548a2011-05-05 15:17:14 -0700338 except VerifyException as e:
Ryan Cuifa55df52011-05-06 11:16:55 -0700339 print >> sys.stderr, "ERROR: project *%s*" % project
Don Garrettdba548a2011-05-05 15:17:14 -0700340 print >> sys.stderr, e
Ryan Cuifa55df52011-05-06 11:16:55 -0700341 raise
342
343 for commit in commit_list:
Mandeep Singh Bainesa7ffa4b2011-05-03 11:37:02 -0700344 try:
345 for hook in COMMON_HOOKS + project_specific_hooks:
346 hook(project, commit)
Don Garrettdba548a2011-05-05 15:17:14 -0700347 except VerifyException as e:
Mandeep Singh Bainesa7ffa4b2011-05-03 11:37:02 -0700348 msg = 'ERROR: pre-upload failed: commit=%s, project=%s' % (commit[:8],
349 project)
Don Garrettdba548a2011-05-05 15:17:14 -0700350
Mandeep Singh Bainesa7ffa4b2011-05-03 11:37:02 -0700351 print >> sys.stderr, msg
Don Garrettdba548a2011-05-05 15:17:14 -0700352 print >> sys.stderr
353 print >> sys.stderr, _get_commit_desc(commit)
354 print >> sys.stderr
355 print >> sys.stderr, e
356
Mandeep Singh Bainesa7ffa4b2011-05-03 11:37:02 -0700357 raise
Don Garrettdba548a2011-05-05 15:17:14 -0700358
Ryan Cuiec4d6332011-05-02 14:15:25 -0700359 os.chdir(pwd)
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700360
Ryan Cui72834d12011-05-05 14:51:33 -0700361
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700362# Main
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -0700363
Anush Elangovan63afad72011-03-23 00:41:27 -0700364def main(project_list, **kwargs):
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700365 hooks = _setup_project_hooks()
Don Garrettdba548a2011-05-05 15:17:14 -0700366
367 try:
368 for project in project_list:
369 _run_project_hooks(project, hooks)
370 except VerifyException as e:
371 sys.exit(1)
Anush Elangovan63afad72011-03-23 00:41:27 -0700372
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -0700373if __name__ == '__main__':
374 main()