blob: ed22fb2c9215dbbf093f29ca525c08bb34d33079 [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
Ryan Cuiec4d6332011-05-02 14:15:25 -070011
12# General Helpers
13
14COMMON_INCLUDED_PATHS = [
15 # C++ and friends
16 r".*\.c$", r".*\.cc$", r".*\.cpp$", r".*\.h$", r".*\.m$", r".*\.mm$",
17 r".*\.inl$", r".*\.asm$", r".*\.hxx$", r".*\.hpp$", r".*\.s$", r".*\.S$",
18 # Scripts
19 r".*\.js$", r".*\.py$", r".*\.sh$", r".*\.rb$", r".*\.pl$", r".*\.pm$",
20 # No extension at all, note that ALL CAPS files are black listed in
21 # COMMON_EXCLUDED_LIST below.
22 r"(^|.*?[\\\/])[^.]+$",
23 # Other
24 r".*\.java$", r".*\.mk$", r".*\.am$",
25]
26
27COMMON_EXCLUDED_PATHS = [
Ryan Cui31e0c172011-05-04 21:00:45 -070028 # avoid doing source file checks for kernel
29 r"/src/third_party/kernel/",
30 r"/src/third_party/kernel-next/",
Ryan Cuiec4d6332011-05-02 14:15:25 -070031 r".*\bexperimental[\\\/].*",
32 r".*\b[A-Z0-9_]{2,}$",
33 r".*[\\\/]debian[\\\/]rules$",
34]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070035
Sean Paul19baef02011-05-05 17:10:31 -040036MIN_GIT_VERSION = [1, 7, 2]
Sean Paulba01d402011-05-05 11:36:23 -040037
Ryan Cui72834d12011-05-05 14:51:33 -070038def _run_command(cmd):
39 """Executes the passed in command and returns raw stdout output."""
40 return subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
41
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070042def _get_hooks_dir():
Ryan Cuiec4d6332011-05-02 14:15:25 -070043 """Returns the absolute path to the repohooks directory."""
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070044 cmd = ['repo', 'forall', 'chromiumos/repohooks', '-c', 'pwd']
Ryan Cui72834d12011-05-05 14:51:33 -070045 return _run_command(cmd).strip()
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070046
Ryan Cuiec4d6332011-05-02 14:15:25 -070047def _match_regex_list(subject, expressions):
48 """Try to match a list of regular expressions to a string.
49
50 Args:
51 subject: The string to match regexes on
52 expressions: A list of regular expressions to check for matches with.
53
54 Returns:
55 Whether the passed in subject matches any of the passed in regexes.
56 """
57 for expr in expressions:
58 if (re.search(expr, subject)):
59 return True
60 return False
61
62def _filter_files(files, include_list, exclude_list=[]):
63 """Filter out files based on the conditions passed in.
64
65 Args:
66 files: list of filepaths to filter
67 include_list: list of regex that when matched with a file path will cause it
68 to be added to the output list unless the file is also matched with a
69 regex in the exclude_list.
70 exclude_list: list of regex that when matched with a file will prevent it
71 from being added to the output list, even if it is also matched with a
72 regex in the include_list.
73
74 Returns:
75 A list of filepaths that contain files matched in the include_list and not
76 in the exclude_list.
77 """
78 filtered = []
79 for f in files:
80 if (_match_regex_list(f, include_list) and
81 not _match_regex_list(f, exclude_list)):
82 filtered.append(f)
83 return filtered
84
85def _report_error(msg, items=None):
86 """Raises an exception with the passed in error message.
87
88 If extra error detail is passed in, it will be appended to the error message.
89
90 Args:
91 msg: Error message header.
92 items: A list of lines that follow the header that give extra error
93 information.
94 """
95 if items:
96 msg += '\n' + '\n'.join(items)
97 raise Exception(msg)
98
99
100# Git Helpers
Ryan Cui4725d952011-05-05 15:41:19 -0700101def _get_upstream_branch():
102 """Returns the upstream tracking branch of the current branch.
103
104 Raises:
105 Error if there is no tracking branch
106 """
107 current_branch = _run_command(['git', 'symbolic-ref', 'HEAD']).strip()
108 current_branch = current_branch.replace('refs/heads/', '')
109 if not current_branch:
110 _report_error('Need to be on a tracking branch')
111
112 cfg_option = 'branch.' + current_branch + '.%s'
113 full_upstream = _run_command(['git', 'config', cfg_option % 'merge']).strip()
114 remote = _run_command(['git', 'config', cfg_option % 'remote']).strip()
115 if not remote or not full_upstream:
116 _report_error('Need to be on a tracking branch')
117
118 return full_upstream.replace('heads', 'remotes/' + remote)
119
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700120def _get_diff(commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700121 """Returns the diff for this commit."""
Ryan Cui72834d12011-05-05 14:51:33 -0700122 return _run_command(['git', 'show', commit])
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700123
Ryan Cuiec4d6332011-05-02 14:15:25 -0700124def _get_file_diff(file, commit):
125 """Returns a list of (linenum, lines) tuples that the commit touched."""
Ryan Cui72834d12011-05-05 14:51:33 -0700126 output = _run_command(['git', 'show', '-p', '--no-ext-diff', commit, file])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700127
128 new_lines = []
129 line_num = 0
130 for line in output.splitlines():
131 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
132 if m:
133 line_num = int(m.groups(1)[0])
134 continue
135 if line.startswith('+') and not line.startswith('++'):
136 new_lines.append((line_num, line[1:]))
137 if not line.startswith('-'):
138 line_num += 1
139 return new_lines
140
141def _get_affected_files(commit):
142 """Returns list of absolute filepaths that were modified/added."""
Ryan Cui72834d12011-05-05 14:51:33 -0700143 output = _run_command(['git', 'diff', '--name-status', commit + '^!'])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700144 files = []
145 for statusline in output.splitlines():
146 m = re.match('^(\w)+\t(.+)$', statusline.rstrip())
147 # Ignore deleted files, and return absolute paths of files
148 if (m.group(1)[0] != 'D'):
149 pwd = os.getcwd()
150 files.append(os.path.join(pwd, m.group(2)))
151 return files
152
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700153def _get_commits():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700154 """Returns a list of commits for this review."""
Ryan Cui4725d952011-05-05 15:41:19 -0700155 cmd = ['git', 'log', '%s..' % _get_upstream_branch(), '--format=%H']
Ryan Cui72834d12011-05-05 14:51:33 -0700156 return _run_command(cmd).split()
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700157
Ryan Cuiec4d6332011-05-02 14:15:25 -0700158def _get_commit_desc(commit):
159 """Returns the full commit message of a commit."""
Sean Paul23a2c582011-05-06 13:10:44 -0400160 return _run_command(['git', 'log', '--format=%s%n%n%b', commit + '^!'])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700161
162
163# Common Hooks
164
165def _check_no_long_lines(project, commit):
166 """Checks that there aren't any lines longer than maxlen characters in any of
167 the text files to be submitted.
168 """
169 MAX_LEN = 80
170
171 errors = []
172 files = _filter_files(_get_affected_files(commit),
173 COMMON_INCLUDED_PATHS,
174 COMMON_EXCLUDED_PATHS)
175
176 for afile in files:
177 for line_num, line in _get_file_diff(afile, commit):
178 # Allow certain lines to exceed the maxlen rule.
179 if (len(line) > MAX_LEN and
180 not 'http://' in line and
181 not 'https://' in line and
182 not line.startswith('#define') and
183 not line.startswith('#include') and
184 not line.startswith('#import') and
185 not line.startswith('#pragma') and
186 not line.startswith('#if') and
187 not line.startswith('#endif')):
188 errors.append('%s, line %s, %s chars' % (afile, line_num, len(line)))
189 if len(errors) == 5: # Just show the first 5 errors.
190 break
191
192 if errors:
193 msg = 'Found lines longer than %s characters (first 5 shown):' % MAX_LEN
194 _report_error(msg, errors)
195
196def _check_no_stray_whitespace(project, commit):
197 """Checks that there is no stray whitespace at source lines end."""
198 errors = []
199 files = _filter_files(_get_affected_files(commit),
200 COMMON_INCLUDED_PATHS,
201 COMMON_EXCLUDED_PATHS)
202
203 for afile in files:
204 for line_num, line in _get_file_diff(afile, commit):
205 if line.rstrip() != line:
206 errors.append('%s, line %s' % (afile, line_num))
207 if errors:
208 _report_error('Found line ending with white space in:', errors)
209
210def _check_no_tabs(project, commit):
211 """Checks there are no unexpanded tabs."""
212 TAB_OK_PATHS = [
Ryan Cui31e0c172011-05-04 21:00:45 -0700213 r"/src/third_party/u-boot/",
214 r"/src/third_party/u-boot-next/",
Ryan Cuiec4d6332011-05-02 14:15:25 -0700215 r".*\.ebuild$",
216 r".*\.eclass$",
217 r".*/[M|m]akefile$"
218 ]
219
220 errors = []
221 files = _filter_files(_get_affected_files(commit),
222 COMMON_INCLUDED_PATHS,
223 COMMON_EXCLUDED_PATHS + TAB_OK_PATHS)
224
225 for afile in files:
226 for line_num, line in _get_file_diff(afile, commit):
227 if '\t' in line:
228 errors.append('%s, line %s' % (afile, line_num))
229 if errors:
230 _report_error('Found a tab character in:', errors)
231
232def _check_change_has_test_field(project, commit):
233 """Check for a non-empty 'TEST=' field in the commit message."""
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700234 TEST_RE = r'\n\s*TEST\s*=[^\n]*\S+'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700235
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700236 if not re.search(TEST_RE, _get_commit_desc(commit)):
237 _report_error('Changelist description needs TEST field (after first line)')
Ryan Cuiec4d6332011-05-02 14:15:25 -0700238
239def _check_change_has_bug_field(project, commit):
240 """Check for a non-empty 'BUG=' field in the commit message."""
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700241 BUG_RE = r'\n\s*BUG\s*=[^\n]*\S+'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700242
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700243 if not re.search(BUG_RE, _get_commit_desc(commit)):
244 _report_error('Changelist description needs BUG field (after first line)')
Ryan Cuiec4d6332011-05-02 14:15:25 -0700245
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700246def _check_change_has_proper_changeid(project, commit):
247 """Verify that Change-ID is present in last paragraph of commit message."""
248 desc = _get_commit_desc(commit)
249 loc = desc.rfind('\nChange-Id:')
250 if loc == -1 or re.search('\n\s*\n\s*\S+', desc[loc:]):
251 _report_error('Change-Id must be in last paragraph of description.')
252
Ryan Cuiec4d6332011-05-02 14:15:25 -0700253def _check_license(project, commit):
254 """Verifies the license header."""
255 LICENSE_HEADER = (
256 r".*? Copyright \(c\) 20[-0-9]{2,7} The Chromium OS Authors\. All rights "
257 r"reserved\." "\n"
258 r".*? Use of this source code is governed by a BSD-style license that can "
259 "be\n"
260 r".*? found in the LICENSE file\."
261 "\n"
262 )
263
264 license_re = re.compile(LICENSE_HEADER, re.MULTILINE)
265 bad_files = []
266 files = _filter_files(_get_affected_files(commit),
267 COMMON_INCLUDED_PATHS,
268 COMMON_EXCLUDED_PATHS)
269
270 for f in files:
271 contents = open(f).read()
272 if len(contents) == 0: continue # Ignore empty files
273 if not license_re.search(contents):
274 bad_files.append(f)
275 if bad_files:
276 _report_error('License must match:\n%s\n' % license_re.pattern +
277 'Found a bad license header in these files:',
278 bad_files)
279
280
281# Project-specific hooks
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700282
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700283def _run_checkpatch(project, commit):
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700284 """Runs checkpatch.pl on the given project"""
285 hooks_dir = _get_hooks_dir()
286 cmd = ['%s/checkpatch.pl' % hooks_dir, '-']
287 p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700288 output = p.communicate(_get_diff(commit))[0]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700289 if p.returncode:
Ryan Cuiec4d6332011-05-02 14:15:25 -0700290 _report_error('checkpatch.pl errors/warnings\n\n' + output)
291
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700292
Dale Curtis2975c432011-05-03 17:25:20 -0700293def _run_json_check(project, commit):
294 """Checks that all JSON files are syntactically valid."""
Dale Curtisa039cfd2011-05-04 12:01:05 -0700295 for f in _filter_files(_get_affected_files(commit), [r'.*\.json']):
Dale Curtis2975c432011-05-03 17:25:20 -0700296 try:
297 json.load(open(f))
298 except Exception, e:
299 _report_error('Invalid JSON in %s: %s' % (f, e))
300
301
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700302# Base
303
Ryan Cuie37fe1a2011-05-03 19:00:10 -0700304COMMON_HOOKS = [_check_change_has_bug_field,
305 _check_change_has_test_field,
306 _check_change_has_proper_changeid,
Ryan Cuiec4d6332011-05-02 14:15:25 -0700307 _check_no_stray_whitespace,
Ryan Cui31e0c172011-05-04 21:00:45 -0700308 _check_no_long_lines,
309 _check_license,
310 _check_no_tabs]
Ryan Cuiec4d6332011-05-02 14:15:25 -0700311
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700312def _setup_project_hooks():
313 """Returns a dictionay of callbacks: dict[project] = [callback1, callback2]"""
314 return {
Doug Anderson830216f2011-05-02 10:08:37 -0700315 "chromiumos/third_party/kernel": [_run_checkpatch],
316 "chromiumos/third_party/kernel-next": [_run_checkpatch],
Dale Curtis2975c432011-05-03 17:25:20 -0700317 "chromeos/autotest-tools": [_run_json_check],
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700318 }
319
320def _run_project_hooks(project, hooks):
321 """For each project run its project specific hook from the hooks dictionary"""
Ryan Cui72834d12011-05-05 14:51:33 -0700322 proj_dir = _run_command(['repo', 'forall', project, '-c', 'pwd']).strip()
Ryan Cuiec4d6332011-05-02 14:15:25 -0700323 pwd = os.getcwd()
324 # hooks assume they are run from the root of the project
325 os.chdir(proj_dir)
326
327 project_specific_hooks = []
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700328 if project in hooks:
Ryan Cuiec4d6332011-05-02 14:15:25 -0700329 project_specific_hooks = hooks[project]
330
331 for commit in _get_commits():
Mandeep Singh Bainesa7ffa4b2011-05-03 11:37:02 -0700332 try:
333 for hook in COMMON_HOOKS + project_specific_hooks:
334 hook(project, commit)
335 except:
336 msg = 'ERROR: pre-upload failed: commit=%s, project=%s' % (commit[:8],
337 project)
338 print >> sys.stderr, msg
339 raise
Ryan Cuiec4d6332011-05-02 14:15:25 -0700340 os.chdir(pwd)
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700341
Ryan Cui72834d12011-05-05 14:51:33 -0700342
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700343# Main
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -0700344
Anush Elangovan63afad72011-03-23 00:41:27 -0700345def main(project_list, **kwargs):
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700346 hooks = _setup_project_hooks()
347 for project in project_list:
348 _run_project_hooks(project, hooks)
Anush Elangovan63afad72011-03-23 00:41:27 -0700349
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -0700350if __name__ == '__main__':
351 main()