blob: a83ff7cca7e10cf30713396d3170416758951b27 [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/",
Ryan Cuiec4d6332011-05-02 14:15:25 -070033 r".*\bexperimental[\\\/].*",
34 r".*\b[A-Z0-9_]{2,}$",
35 r".*[\\\/]debian[\\\/]rules$",
36]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070037
Sean Paul19baef02011-05-05 17:10:31 -040038MIN_GIT_VERSION = [1, 7, 2]
Sean Paulba01d402011-05-05 11:36:23 -040039
Ryan Cui72834d12011-05-05 14:51:33 -070040def _run_command(cmd):
41 """Executes the passed in command and returns raw stdout output."""
42 return subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
43
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070044def _get_hooks_dir():
Ryan Cuiec4d6332011-05-02 14:15:25 -070045 """Returns the absolute path to the repohooks directory."""
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070046 cmd = ['repo', 'forall', 'chromiumos/repohooks', '-c', 'pwd']
Ryan Cui72834d12011-05-05 14:51:33 -070047 return _run_command(cmd).strip()
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070048
Ryan Cuiec4d6332011-05-02 14:15:25 -070049def _match_regex_list(subject, expressions):
50 """Try to match a list of regular expressions to a string.
51
52 Args:
53 subject: The string to match regexes on
54 expressions: A list of regular expressions to check for matches with.
55
56 Returns:
57 Whether the passed in subject matches any of the passed in regexes.
58 """
59 for expr in expressions:
60 if (re.search(expr, subject)):
61 return True
62 return False
63
64def _filter_files(files, include_list, exclude_list=[]):
65 """Filter out files based on the conditions passed in.
66
67 Args:
68 files: list of filepaths to filter
69 include_list: list of regex that when matched with a file path will cause it
70 to be added to the output list unless the file is also matched with a
71 regex in the exclude_list.
72 exclude_list: list of regex that when matched with a file will prevent it
73 from being added to the output list, even if it is also matched with a
74 regex in the include_list.
75
76 Returns:
77 A list of filepaths that contain files matched in the include_list and not
78 in the exclude_list.
79 """
80 filtered = []
81 for f in files:
82 if (_match_regex_list(f, include_list) and
83 not _match_regex_list(f, exclude_list)):
84 filtered.append(f)
85 return filtered
86
87def _report_error(msg, items=None):
88 """Raises an exception with the passed in error message.
89
90 If extra error detail is passed in, it will be appended to the error message.
91
92 Args:
93 msg: Error message header.
94 items: A list of lines that follow the header that give extra error
95 information.
96 """
97 if items:
98 msg += '\n' + '\n'.join(items)
Don Garrettdba548a2011-05-05 15:17:14 -070099 raise VerifyException(msg)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700100
101
102# Git Helpers
Ryan Cui4725d952011-05-05 15:41:19 -0700103def _get_upstream_branch():
104 """Returns the upstream tracking branch of the current branch.
105
106 Raises:
107 Error if there is no tracking branch
108 """
109 current_branch = _run_command(['git', 'symbolic-ref', 'HEAD']).strip()
110 current_branch = current_branch.replace('refs/heads/', '')
111 if not current_branch:
112 _report_error('Need to be on a tracking branch')
113
114 cfg_option = 'branch.' + current_branch + '.%s'
115 full_upstream = _run_command(['git', 'config', cfg_option % 'merge']).strip()
116 remote = _run_command(['git', 'config', cfg_option % 'remote']).strip()
117 if not remote or not full_upstream:
118 _report_error('Need to be on a tracking branch')
119
120 return full_upstream.replace('heads', 'remotes/' + remote)
121
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700122def _get_diff(commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700123 """Returns the diff for this commit."""
Ryan Cui72834d12011-05-05 14:51:33 -0700124 return _run_command(['git', 'show', commit])
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700125
Ryan Cuiec4d6332011-05-02 14:15:25 -0700126def _get_file_diff(file, commit):
127 """Returns a list of (linenum, lines) tuples that the commit touched."""
Ryan Cui72834d12011-05-05 14:51:33 -0700128 output = _run_command(['git', 'show', '-p', '--no-ext-diff', commit, file])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700129
130 new_lines = []
131 line_num = 0
132 for line in output.splitlines():
133 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
134 if m:
135 line_num = int(m.groups(1)[0])
136 continue
137 if line.startswith('+') and not line.startswith('++'):
138 new_lines.append((line_num, line[1:]))
139 if not line.startswith('-'):
140 line_num += 1
141 return new_lines
142
143def _get_affected_files(commit):
144 """Returns list of absolute filepaths that were modified/added."""
Ryan Cui72834d12011-05-05 14:51:33 -0700145 output = _run_command(['git', 'diff', '--name-status', commit + '^!'])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700146 files = []
147 for statusline in output.splitlines():
148 m = re.match('^(\w)+\t(.+)$', statusline.rstrip())
149 # Ignore deleted files, and return absolute paths of files
150 if (m.group(1)[0] != 'D'):
151 pwd = os.getcwd()
152 files.append(os.path.join(pwd, m.group(2)))
153 return files
154
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700155def _get_commits():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700156 """Returns a list of commits for this review."""
Ryan Cui4725d952011-05-05 15:41:19 -0700157 cmd = ['git', 'log', '%s..' % _get_upstream_branch(), '--format=%H']
Ryan Cui72834d12011-05-05 14:51:33 -0700158 return _run_command(cmd).split()
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700159
Ryan Cuiec4d6332011-05-02 14:15:25 -0700160def _get_commit_desc(commit):
161 """Returns the full commit message of a commit."""
Sean Paul23a2c582011-05-06 13:10:44 -0400162 return _run_command(['git', 'log', '--format=%s%n%n%b', commit + '^!'])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700163
164
165# Common Hooks
166
167def _check_no_long_lines(project, commit):
168 """Checks that there aren't any lines longer than maxlen characters in any of
169 the text files to be submitted.
170 """
171 MAX_LEN = 80
172
173 errors = []
174 files = _filter_files(_get_affected_files(commit),
175 COMMON_INCLUDED_PATHS,
176 COMMON_EXCLUDED_PATHS)
177
178 for afile in files:
179 for line_num, line in _get_file_diff(afile, commit):
180 # Allow certain lines to exceed the maxlen rule.
181 if (len(line) > MAX_LEN and
182 not 'http://' in line and
183 not 'https://' in line and
184 not line.startswith('#define') and
185 not line.startswith('#include') and
186 not line.startswith('#import') and
187 not line.startswith('#pragma') and
188 not line.startswith('#if') and
189 not line.startswith('#endif')):
190 errors.append('%s, line %s, %s chars' % (afile, line_num, len(line)))
191 if len(errors) == 5: # Just show the first 5 errors.
192 break
193
194 if errors:
195 msg = 'Found lines longer than %s characters (first 5 shown):' % MAX_LEN
196 _report_error(msg, errors)
197
198def _check_no_stray_whitespace(project, commit):
199 """Checks that there is no stray whitespace at source lines end."""
200 errors = []
201 files = _filter_files(_get_affected_files(commit),
202 COMMON_INCLUDED_PATHS,
203 COMMON_EXCLUDED_PATHS)
204
205 for afile in files:
206 for line_num, line in _get_file_diff(afile, commit):
207 if line.rstrip() != line:
208 errors.append('%s, line %s' % (afile, line_num))
209 if errors:
210 _report_error('Found line ending with white space in:', errors)
211
212def _check_no_tabs(project, commit):
213 """Checks there are no unexpanded tabs."""
214 TAB_OK_PATHS = [
Doug Anderson0f91cbf2011-05-09 15:56:25 -0700215 r"/src/platform/u-boot-config/",
Ryan Cui31e0c172011-05-04 21:00:45 -0700216 r"/src/third_party/u-boot/",
217 r"/src/third_party/u-boot-next/",
Ryan Cuiec4d6332011-05-02 14:15:25 -0700218 r".*\.ebuild$",
219 r".*\.eclass$",
220 r".*/[M|m]akefile$"
221 ]
222
223 errors = []
224 files = _filter_files(_get_affected_files(commit),
225 COMMON_INCLUDED_PATHS,
226 COMMON_EXCLUDED_PATHS + TAB_OK_PATHS)
227
228 for afile in files:
229 for line_num, line in _get_file_diff(afile, commit):
230 if '\t' in line:
231 errors.append('%s, line %s' % (afile, line_num))
232 if errors:
233 _report_error('Found a tab character in:', errors)
234
235def _check_change_has_test_field(project, commit):
236 """Check for a non-empty 'TEST=' field in the commit message."""
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700237 TEST_RE = r'\n\s*TEST\s*=[^\n]*\S+'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700238
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700239 if not re.search(TEST_RE, _get_commit_desc(commit)):
240 _report_error('Changelist description needs TEST field (after first line)')
Ryan Cuiec4d6332011-05-02 14:15:25 -0700241
242def _check_change_has_bug_field(project, commit):
243 """Check for a non-empty 'BUG=' field in the commit message."""
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700244 BUG_RE = r'\n\s*BUG\s*=[^\n]*\S+'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700245
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700246 if not re.search(BUG_RE, _get_commit_desc(commit)):
247 _report_error('Changelist description needs BUG field (after first line)')
Ryan Cuiec4d6332011-05-02 14:15:25 -0700248
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700249def _check_change_has_proper_changeid(project, commit):
250 """Verify that Change-ID is present in last paragraph of commit message."""
251 desc = _get_commit_desc(commit)
252 loc = desc.rfind('\nChange-Id:')
253 if loc == -1 or re.search('\n\s*\n\s*\S+', desc[loc:]):
254 _report_error('Change-Id must be in last paragraph of description.')
255
Ryan Cuiec4d6332011-05-02 14:15:25 -0700256def _check_license(project, commit):
257 """Verifies the license header."""
258 LICENSE_HEADER = (
259 r".*? Copyright \(c\) 20[-0-9]{2,7} The Chromium OS Authors\. All rights "
260 r"reserved\." "\n"
261 r".*? Use of this source code is governed by a BSD-style license that can "
262 "be\n"
263 r".*? found in the LICENSE file\."
264 "\n"
265 )
266
267 license_re = re.compile(LICENSE_HEADER, re.MULTILINE)
268 bad_files = []
269 files = _filter_files(_get_affected_files(commit),
270 COMMON_INCLUDED_PATHS,
271 COMMON_EXCLUDED_PATHS)
272
273 for f in files:
274 contents = open(f).read()
275 if len(contents) == 0: continue # Ignore empty files
276 if not license_re.search(contents):
277 bad_files.append(f)
278 if bad_files:
279 _report_error('License must match:\n%s\n' % license_re.pattern +
280 'Found a bad license header in these files:',
281 bad_files)
282
283
284# Project-specific hooks
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700285
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700286def _run_checkpatch(project, commit):
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700287 """Runs checkpatch.pl on the given project"""
288 hooks_dir = _get_hooks_dir()
289 cmd = ['%s/checkpatch.pl' % hooks_dir, '-']
290 p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700291 output = p.communicate(_get_diff(commit))[0]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700292 if p.returncode:
Ryan Cuiec4d6332011-05-02 14:15:25 -0700293 _report_error('checkpatch.pl errors/warnings\n\n' + output)
294
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700295
Dale Curtis2975c432011-05-03 17:25:20 -0700296def _run_json_check(project, commit):
297 """Checks that all JSON files are syntactically valid."""
Dale Curtisa039cfd2011-05-04 12:01:05 -0700298 for f in _filter_files(_get_affected_files(commit), [r'.*\.json']):
Dale Curtis2975c432011-05-03 17:25:20 -0700299 try:
300 json.load(open(f))
301 except Exception, e:
302 _report_error('Invalid JSON in %s: %s' % (f, e))
303
304
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700305# Base
306
Ryan Cuie37fe1a2011-05-03 19:00:10 -0700307COMMON_HOOKS = [_check_change_has_bug_field,
308 _check_change_has_test_field,
309 _check_change_has_proper_changeid,
Ryan Cuiec4d6332011-05-02 14:15:25 -0700310 _check_no_stray_whitespace,
Ryan Cui31e0c172011-05-04 21:00:45 -0700311 _check_no_long_lines,
312 _check_license,
313 _check_no_tabs]
Ryan Cuiec4d6332011-05-02 14:15:25 -0700314
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700315def _setup_project_hooks():
316 """Returns a dictionay of callbacks: dict[project] = [callback1, callback2]"""
317 return {
Doug Anderson830216f2011-05-02 10:08:37 -0700318 "chromiumos/third_party/kernel": [_run_checkpatch],
319 "chromiumos/third_party/kernel-next": [_run_checkpatch],
Dale Curtis2975c432011-05-03 17:25:20 -0700320 "chromeos/autotest-tools": [_run_json_check],
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700321 }
322
323def _run_project_hooks(project, hooks):
324 """For each project run its project specific hook from the hooks dictionary"""
Ryan Cui72834d12011-05-05 14:51:33 -0700325 proj_dir = _run_command(['repo', 'forall', project, '-c', 'pwd']).strip()
Ryan Cuiec4d6332011-05-02 14:15:25 -0700326 pwd = os.getcwd()
327 # hooks assume they are run from the root of the project
328 os.chdir(proj_dir)
329
330 project_specific_hooks = []
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700331 if project in hooks:
Ryan Cuiec4d6332011-05-02 14:15:25 -0700332 project_specific_hooks = hooks[project]
333
Ryan Cuifa55df52011-05-06 11:16:55 -0700334 try:
335 commit_list = _get_commits()
Don Garrettdba548a2011-05-05 15:17:14 -0700336 except VerifyException as e:
Ryan Cuifa55df52011-05-06 11:16:55 -0700337 print >> sys.stderr, "ERROR: project *%s*" % project
Don Garrettdba548a2011-05-05 15:17:14 -0700338 print >> sys.stderr, e
Ryan Cuifa55df52011-05-06 11:16:55 -0700339 raise
340
341 for commit in commit_list:
Mandeep Singh Bainesa7ffa4b2011-05-03 11:37:02 -0700342 try:
343 for hook in COMMON_HOOKS + project_specific_hooks:
344 hook(project, commit)
Don Garrettdba548a2011-05-05 15:17:14 -0700345 except VerifyException as e:
Mandeep Singh Bainesa7ffa4b2011-05-03 11:37:02 -0700346 msg = 'ERROR: pre-upload failed: commit=%s, project=%s' % (commit[:8],
347 project)
Don Garrettdba548a2011-05-05 15:17:14 -0700348
Mandeep Singh Bainesa7ffa4b2011-05-03 11:37:02 -0700349 print >> sys.stderr, msg
Don Garrettdba548a2011-05-05 15:17:14 -0700350 print >> sys.stderr
351 print >> sys.stderr, _get_commit_desc(commit)
352 print >> sys.stderr
353 print >> sys.stderr, e
354
Mandeep Singh Bainesa7ffa4b2011-05-03 11:37:02 -0700355 raise
Don Garrettdba548a2011-05-05 15:17:14 -0700356
Ryan Cuiec4d6332011-05-02 14:15:25 -0700357 os.chdir(pwd)
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700358
Ryan Cui72834d12011-05-05 14:51:33 -0700359
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700360# Main
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -0700361
Anush Elangovan63afad72011-03-23 00:41:27 -0700362def main(project_list, **kwargs):
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700363 hooks = _setup_project_hooks()
Don Garrettdba548a2011-05-05 15:17:14 -0700364
365 try:
366 for project in project_list:
367 _run_project_hooks(project, hooks)
368 except VerifyException as e:
369 sys.exit(1)
Anush Elangovan63afad72011-03-23 00:41:27 -0700370
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -0700371if __name__ == '__main__':
372 main()