blob: eb95d70a0a39752af61af8af9bd5db5550a9bc94 [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 = [
Ryan Cui31e0c172011-05-04 21:00:45 -0700215 r"/src/third_party/u-boot/",
216 r"/src/third_party/u-boot-next/",
Ryan Cuiec4d6332011-05-02 14:15:25 -0700217 r".*\.ebuild$",
218 r".*\.eclass$",
219 r".*/[M|m]akefile$"
220 ]
221
222 errors = []
223 files = _filter_files(_get_affected_files(commit),
224 COMMON_INCLUDED_PATHS,
225 COMMON_EXCLUDED_PATHS + TAB_OK_PATHS)
226
227 for afile in files:
228 for line_num, line in _get_file_diff(afile, commit):
229 if '\t' in line:
230 errors.append('%s, line %s' % (afile, line_num))
231 if errors:
232 _report_error('Found a tab character in:', errors)
233
234def _check_change_has_test_field(project, commit):
235 """Check for a non-empty 'TEST=' field in the commit message."""
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700236 TEST_RE = r'\n\s*TEST\s*=[^\n]*\S+'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700237
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700238 if not re.search(TEST_RE, _get_commit_desc(commit)):
239 _report_error('Changelist description needs TEST field (after first line)')
Ryan Cuiec4d6332011-05-02 14:15:25 -0700240
241def _check_change_has_bug_field(project, commit):
242 """Check for a non-empty 'BUG=' field in the commit message."""
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700243 BUG_RE = r'\n\s*BUG\s*=[^\n]*\S+'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700244
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700245 if not re.search(BUG_RE, _get_commit_desc(commit)):
246 _report_error('Changelist description needs BUG field (after first line)')
Ryan Cuiec4d6332011-05-02 14:15:25 -0700247
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700248def _check_change_has_proper_changeid(project, commit):
249 """Verify that Change-ID is present in last paragraph of commit message."""
250 desc = _get_commit_desc(commit)
251 loc = desc.rfind('\nChange-Id:')
252 if loc == -1 or re.search('\n\s*\n\s*\S+', desc[loc:]):
253 _report_error('Change-Id must be in last paragraph of description.')
254
Ryan Cuiec4d6332011-05-02 14:15:25 -0700255def _check_license(project, commit):
256 """Verifies the license header."""
257 LICENSE_HEADER = (
258 r".*? Copyright \(c\) 20[-0-9]{2,7} The Chromium OS Authors\. All rights "
259 r"reserved\." "\n"
260 r".*? Use of this source code is governed by a BSD-style license that can "
261 "be\n"
262 r".*? found in the LICENSE file\."
263 "\n"
264 )
265
266 license_re = re.compile(LICENSE_HEADER, re.MULTILINE)
267 bad_files = []
268 files = _filter_files(_get_affected_files(commit),
269 COMMON_INCLUDED_PATHS,
270 COMMON_EXCLUDED_PATHS)
271
272 for f in files:
273 contents = open(f).read()
274 if len(contents) == 0: continue # Ignore empty files
275 if not license_re.search(contents):
276 bad_files.append(f)
277 if bad_files:
278 _report_error('License must match:\n%s\n' % license_re.pattern +
279 'Found a bad license header in these files:',
280 bad_files)
281
282
283# Project-specific hooks
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700284
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700285def _run_checkpatch(project, commit):
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700286 """Runs checkpatch.pl on the given project"""
287 hooks_dir = _get_hooks_dir()
288 cmd = ['%s/checkpatch.pl' % hooks_dir, '-']
289 p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700290 output = p.communicate(_get_diff(commit))[0]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700291 if p.returncode:
Ryan Cuiec4d6332011-05-02 14:15:25 -0700292 _report_error('checkpatch.pl errors/warnings\n\n' + output)
293
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700294
Dale Curtis2975c432011-05-03 17:25:20 -0700295def _run_json_check(project, commit):
296 """Checks that all JSON files are syntactically valid."""
Dale Curtisa039cfd2011-05-04 12:01:05 -0700297 for f in _filter_files(_get_affected_files(commit), [r'.*\.json']):
Dale Curtis2975c432011-05-03 17:25:20 -0700298 try:
299 json.load(open(f))
300 except Exception, e:
301 _report_error('Invalid JSON in %s: %s' % (f, e))
302
303
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700304# Base
305
Ryan Cuie37fe1a2011-05-03 19:00:10 -0700306COMMON_HOOKS = [_check_change_has_bug_field,
307 _check_change_has_test_field,
308 _check_change_has_proper_changeid,
Ryan Cuiec4d6332011-05-02 14:15:25 -0700309 _check_no_stray_whitespace,
Ryan Cui31e0c172011-05-04 21:00:45 -0700310 _check_no_long_lines,
311 _check_license,
312 _check_no_tabs]
Ryan Cuiec4d6332011-05-02 14:15:25 -0700313
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700314def _setup_project_hooks():
315 """Returns a dictionay of callbacks: dict[project] = [callback1, callback2]"""
316 return {
Doug Anderson830216f2011-05-02 10:08:37 -0700317 "chromiumos/third_party/kernel": [_run_checkpatch],
318 "chromiumos/third_party/kernel-next": [_run_checkpatch],
Dale Curtis2975c432011-05-03 17:25:20 -0700319 "chromeos/autotest-tools": [_run_json_check],
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700320 }
321
322def _run_project_hooks(project, hooks):
323 """For each project run its project specific hook from the hooks dictionary"""
Ryan Cui72834d12011-05-05 14:51:33 -0700324 proj_dir = _run_command(['repo', 'forall', project, '-c', 'pwd']).strip()
Ryan Cuiec4d6332011-05-02 14:15:25 -0700325 pwd = os.getcwd()
326 # hooks assume they are run from the root of the project
327 os.chdir(proj_dir)
328
329 project_specific_hooks = []
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700330 if project in hooks:
Ryan Cuiec4d6332011-05-02 14:15:25 -0700331 project_specific_hooks = hooks[project]
332
Ryan Cuifa55df52011-05-06 11:16:55 -0700333 try:
334 commit_list = _get_commits()
Don Garrettdba548a2011-05-05 15:17:14 -0700335 except VerifyException as e:
Ryan Cuifa55df52011-05-06 11:16:55 -0700336 print >> sys.stderr, "ERROR: project *%s*" % project
Don Garrettdba548a2011-05-05 15:17:14 -0700337 print >> sys.stderr, e
Ryan Cuifa55df52011-05-06 11:16:55 -0700338 raise
339
340 for commit in commit_list:
Mandeep Singh Bainesa7ffa4b2011-05-03 11:37:02 -0700341 try:
342 for hook in COMMON_HOOKS + project_specific_hooks:
343 hook(project, commit)
Don Garrettdba548a2011-05-05 15:17:14 -0700344 except VerifyException as e:
Mandeep Singh Bainesa7ffa4b2011-05-03 11:37:02 -0700345 msg = 'ERROR: pre-upload failed: commit=%s, project=%s' % (commit[:8],
346 project)
Don Garrettdba548a2011-05-05 15:17:14 -0700347
Mandeep Singh Bainesa7ffa4b2011-05-03 11:37:02 -0700348 print >> sys.stderr, msg
Don Garrettdba548a2011-05-05 15:17:14 -0700349 print >> sys.stderr
350 print >> sys.stderr, _get_commit_desc(commit)
351 print >> sys.stderr
352 print >> sys.stderr, e
353
Mandeep Singh Bainesa7ffa4b2011-05-03 11:37:02 -0700354 raise
Don Garrettdba548a2011-05-05 15:17:14 -0700355
Ryan Cuiec4d6332011-05-02 14:15:25 -0700356 os.chdir(pwd)
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700357
Ryan Cui72834d12011-05-05 14:51:33 -0700358
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700359# Main
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -0700360
Anush Elangovan63afad72011-03-23 00:41:27 -0700361def main(project_list, **kwargs):
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700362 hooks = _setup_project_hooks()
Don Garrettdba548a2011-05-05 15:17:14 -0700363
364 try:
365 for project in project_list:
366 _run_project_hooks(project, hooks)
367 except VerifyException as e:
368 sys.exit(1)
Anush Elangovan63afad72011-03-23 00:41:27 -0700369
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -0700370if __name__ == '__main__':
371 main()