blob: 38ba3d0aea6a366503211023bb1ad8cb7bf81802 [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 Cui72834d12011-05-05 14:51:33 -0700101
Sean Paulba01d402011-05-05 11:36:23 -0400102def _check_git_version():
103 """Checks the git version installed, dies if it is insufficient"""
104 cmd = ['git', '--version']
105 output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
Sean Paul19baef02011-05-05 17:10:31 -0400106 m = re.match('(git version )([0-9]+\.[0-9]+\.[0-9]+).*\n', output)
Sean Paulba01d402011-05-05 11:36:23 -0400107 if not m or not m.group(2):
108 _report_error('Failed to get git version, git output=' + output)
109
110 version = m.group(2).split('.')
111 version = map(lambda x: int(x), version)
112 for v, mv in zip(version, MIN_GIT_VERSION):
113 if v < mv:
114 _report_error('Invalid version of git (' + m.group(2) + '), you need '
115 + 'at least version '
116 + ''.join([`num` + '.' for num in MIN_GIT_VERSION]))
117 elif v > mv:
118 break
Ryan Cuiec4d6332011-05-02 14:15:25 -0700119
Ryan Cui4725d952011-05-05 15:41:19 -0700120def _get_upstream_branch():
121 """Returns the upstream tracking branch of the current branch.
122
123 Raises:
124 Error if there is no tracking branch
125 """
126 current_branch = _run_command(['git', 'symbolic-ref', 'HEAD']).strip()
127 current_branch = current_branch.replace('refs/heads/', '')
128 if not current_branch:
129 _report_error('Need to be on a tracking branch')
130
131 cfg_option = 'branch.' + current_branch + '.%s'
132 full_upstream = _run_command(['git', 'config', cfg_option % 'merge']).strip()
133 remote = _run_command(['git', 'config', cfg_option % 'remote']).strip()
134 if not remote or not full_upstream:
135 _report_error('Need to be on a tracking branch')
136
137 return full_upstream.replace('heads', 'remotes/' + remote)
138
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700139def _get_diff(commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700140 """Returns the diff for this commit."""
Ryan Cui72834d12011-05-05 14:51:33 -0700141 return _run_command(['git', 'show', commit])
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700142
Ryan Cuiec4d6332011-05-02 14:15:25 -0700143def _get_file_diff(file, commit):
144 """Returns a list of (linenum, lines) tuples that the commit touched."""
Ryan Cui72834d12011-05-05 14:51:33 -0700145 output = _run_command(['git', 'show', '-p', '--no-ext-diff', commit, file])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700146
147 new_lines = []
148 line_num = 0
149 for line in output.splitlines():
150 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
151 if m:
152 line_num = int(m.groups(1)[0])
153 continue
154 if line.startswith('+') and not line.startswith('++'):
155 new_lines.append((line_num, line[1:]))
156 if not line.startswith('-'):
157 line_num += 1
158 return new_lines
159
160def _get_affected_files(commit):
161 """Returns list of absolute filepaths that were modified/added."""
Ryan Cui72834d12011-05-05 14:51:33 -0700162 output = _run_command(['git', 'diff', '--name-status', commit + '^!'])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700163 files = []
164 for statusline in output.splitlines():
165 m = re.match('^(\w)+\t(.+)$', statusline.rstrip())
166 # Ignore deleted files, and return absolute paths of files
167 if (m.group(1)[0] != 'D'):
168 pwd = os.getcwd()
169 files.append(os.path.join(pwd, m.group(2)))
170 return files
171
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700172def _get_commits():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700173 """Returns a list of commits for this review."""
Ryan Cui4725d952011-05-05 15:41:19 -0700174 cmd = ['git', 'log', '%s..' % _get_upstream_branch(), '--format=%H']
Ryan Cui72834d12011-05-05 14:51:33 -0700175 return _run_command(cmd).split()
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700176
Ryan Cuiec4d6332011-05-02 14:15:25 -0700177def _get_commit_desc(commit):
178 """Returns the full commit message of a commit."""
Ryan Cui72834d12011-05-05 14:51:33 -0700179 return _run_command(['git', 'log', '--format=%B', commit + '^!'])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700180
181
182# Common Hooks
183
184def _check_no_long_lines(project, commit):
185 """Checks that there aren't any lines longer than maxlen characters in any of
186 the text files to be submitted.
187 """
188 MAX_LEN = 80
189
190 errors = []
191 files = _filter_files(_get_affected_files(commit),
192 COMMON_INCLUDED_PATHS,
193 COMMON_EXCLUDED_PATHS)
194
195 for afile in files:
196 for line_num, line in _get_file_diff(afile, commit):
197 # Allow certain lines to exceed the maxlen rule.
198 if (len(line) > MAX_LEN and
199 not 'http://' in line and
200 not 'https://' in line and
201 not line.startswith('#define') and
202 not line.startswith('#include') and
203 not line.startswith('#import') and
204 not line.startswith('#pragma') and
205 not line.startswith('#if') and
206 not line.startswith('#endif')):
207 errors.append('%s, line %s, %s chars' % (afile, line_num, len(line)))
208 if len(errors) == 5: # Just show the first 5 errors.
209 break
210
211 if errors:
212 msg = 'Found lines longer than %s characters (first 5 shown):' % MAX_LEN
213 _report_error(msg, errors)
214
215def _check_no_stray_whitespace(project, commit):
216 """Checks that there is no stray whitespace at source lines end."""
217 errors = []
218 files = _filter_files(_get_affected_files(commit),
219 COMMON_INCLUDED_PATHS,
220 COMMON_EXCLUDED_PATHS)
221
222 for afile in files:
223 for line_num, line in _get_file_diff(afile, commit):
224 if line.rstrip() != line:
225 errors.append('%s, line %s' % (afile, line_num))
226 if errors:
227 _report_error('Found line ending with white space in:', errors)
228
229def _check_no_tabs(project, commit):
230 """Checks there are no unexpanded tabs."""
231 TAB_OK_PATHS = [
Ryan Cui31e0c172011-05-04 21:00:45 -0700232 r"/src/third_party/u-boot/",
233 r"/src/third_party/u-boot-next/",
Ryan Cuiec4d6332011-05-02 14:15:25 -0700234 r".*\.ebuild$",
235 r".*\.eclass$",
236 r".*/[M|m]akefile$"
237 ]
238
239 errors = []
240 files = _filter_files(_get_affected_files(commit),
241 COMMON_INCLUDED_PATHS,
242 COMMON_EXCLUDED_PATHS + TAB_OK_PATHS)
243
244 for afile in files:
245 for line_num, line in _get_file_diff(afile, commit):
246 if '\t' in line:
247 errors.append('%s, line %s' % (afile, line_num))
248 if errors:
249 _report_error('Found a tab character in:', errors)
250
251def _check_change_has_test_field(project, commit):
252 """Check for a non-empty 'TEST=' field in the commit message."""
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700253 TEST_RE = r'\n\s*TEST\s*=[^\n]*\S+'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700254
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700255 if not re.search(TEST_RE, _get_commit_desc(commit)):
256 _report_error('Changelist description needs TEST field (after first line)')
Ryan Cuiec4d6332011-05-02 14:15:25 -0700257
258def _check_change_has_bug_field(project, commit):
259 """Check for a non-empty 'BUG=' field in the commit message."""
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700260 BUG_RE = r'\n\s*BUG\s*=[^\n]*\S+'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700261
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700262 if not re.search(BUG_RE, _get_commit_desc(commit)):
263 _report_error('Changelist description needs BUG field (after first line)')
Ryan Cuiec4d6332011-05-02 14:15:25 -0700264
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700265def _check_change_has_proper_changeid(project, commit):
266 """Verify that Change-ID is present in last paragraph of commit message."""
267 desc = _get_commit_desc(commit)
268 loc = desc.rfind('\nChange-Id:')
269 if loc == -1 or re.search('\n\s*\n\s*\S+', desc[loc:]):
270 _report_error('Change-Id must be in last paragraph of description.')
271
Ryan Cuiec4d6332011-05-02 14:15:25 -0700272def _check_license(project, commit):
273 """Verifies the license header."""
274 LICENSE_HEADER = (
275 r".*? Copyright \(c\) 20[-0-9]{2,7} The Chromium OS Authors\. All rights "
276 r"reserved\." "\n"
277 r".*? Use of this source code is governed by a BSD-style license that can "
278 "be\n"
279 r".*? found in the LICENSE file\."
280 "\n"
281 )
282
283 license_re = re.compile(LICENSE_HEADER, re.MULTILINE)
284 bad_files = []
285 files = _filter_files(_get_affected_files(commit),
286 COMMON_INCLUDED_PATHS,
287 COMMON_EXCLUDED_PATHS)
288
289 for f in files:
290 contents = open(f).read()
291 if len(contents) == 0: continue # Ignore empty files
292 if not license_re.search(contents):
293 bad_files.append(f)
294 if bad_files:
295 _report_error('License must match:\n%s\n' % license_re.pattern +
296 'Found a bad license header in these files:',
297 bad_files)
298
299
300# Project-specific hooks
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700301
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700302def _run_checkpatch(project, commit):
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700303 """Runs checkpatch.pl on the given project"""
304 hooks_dir = _get_hooks_dir()
305 cmd = ['%s/checkpatch.pl' % hooks_dir, '-']
306 p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700307 output = p.communicate(_get_diff(commit))[0]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700308 if p.returncode:
Ryan Cuiec4d6332011-05-02 14:15:25 -0700309 _report_error('checkpatch.pl errors/warnings\n\n' + output)
310
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700311
Dale Curtis2975c432011-05-03 17:25:20 -0700312def _run_json_check(project, commit):
313 """Checks that all JSON files are syntactically valid."""
Dale Curtisa039cfd2011-05-04 12:01:05 -0700314 for f in _filter_files(_get_affected_files(commit), [r'.*\.json']):
Dale Curtis2975c432011-05-03 17:25:20 -0700315 try:
316 json.load(open(f))
317 except Exception, e:
318 _report_error('Invalid JSON in %s: %s' % (f, e))
319
320
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700321# Base
322
Ryan Cuie37fe1a2011-05-03 19:00:10 -0700323COMMON_HOOKS = [_check_change_has_bug_field,
324 _check_change_has_test_field,
325 _check_change_has_proper_changeid,
Ryan Cuiec4d6332011-05-02 14:15:25 -0700326 _check_no_stray_whitespace,
Ryan Cui31e0c172011-05-04 21:00:45 -0700327 _check_no_long_lines,
328 _check_license,
329 _check_no_tabs]
Ryan Cuiec4d6332011-05-02 14:15:25 -0700330
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700331def _setup_project_hooks():
332 """Returns a dictionay of callbacks: dict[project] = [callback1, callback2]"""
333 return {
Doug Anderson830216f2011-05-02 10:08:37 -0700334 "chromiumos/third_party/kernel": [_run_checkpatch],
335 "chromiumos/third_party/kernel-next": [_run_checkpatch],
Dale Curtis2975c432011-05-03 17:25:20 -0700336 "chromeos/autotest-tools": [_run_json_check],
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700337 }
338
339def _run_project_hooks(project, hooks):
340 """For each project run its project specific hook from the hooks dictionary"""
Ryan Cui72834d12011-05-05 14:51:33 -0700341 proj_dir = _run_command(['repo', 'forall', project, '-c', 'pwd']).strip()
Ryan Cuiec4d6332011-05-02 14:15:25 -0700342 pwd = os.getcwd()
343 # hooks assume they are run from the root of the project
344 os.chdir(proj_dir)
345
346 project_specific_hooks = []
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700347 if project in hooks:
Ryan Cuiec4d6332011-05-02 14:15:25 -0700348 project_specific_hooks = hooks[project]
349
350 for commit in _get_commits():
Mandeep Singh Bainesa7ffa4b2011-05-03 11:37:02 -0700351 try:
352 for hook in COMMON_HOOKS + project_specific_hooks:
353 hook(project, commit)
354 except:
355 msg = 'ERROR: pre-upload failed: commit=%s, project=%s' % (commit[:8],
356 project)
357 print >> sys.stderr, msg
358 raise
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):
Sean Paulba01d402011-05-05 11:36:23 -0400365 _check_git_version()
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700366 hooks = _setup_project_hooks()
367 for project in project_list:
368 _run_project_hooks(project, hooks)
Anush Elangovan63afad72011-03-23 00:41:27 -0700369
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -0700370if __name__ == '__main__':
371 main()