blob: d913d2b1f3315f9bd91ad885c471d89c6b64f245 [file] [log] [blame]
Doug Anderson44a644f2011-11-02 10:37:37 -07001#!/usr/bin/env python
Jon Salz98255932012-08-18 14:48:02 +08002# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07003# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
Ryan Cui9b651632011-05-11 11:38:58 -07006import ConfigParser
Jon Salz3ee59de2012-08-18 13:54:22 +08007import functools
Dale Curtis2975c432011-05-03 17:25:20 -07008import json
Doug Anderson44a644f2011-11-02 10:37:37 -07009import optparse
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070010import os
Ryan Cuiec4d6332011-05-02 14:15:25 -070011import re
Mandeep Singh Bainesa7ffa4b2011-05-03 11:37:02 -070012import sys
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070013import subprocess
14
Ryan Cui1562fb82011-05-09 11:01:31 -070015from errors import (VerifyException, HookFailure, PrintErrorForProject,
16 PrintErrorsForCommit)
Ryan Cuiec4d6332011-05-02 14:15:25 -070017
Ryan Cuiec4d6332011-05-02 14:15:25 -070018
19COMMON_INCLUDED_PATHS = [
20 # C++ and friends
21 r".*\.c$", r".*\.cc$", r".*\.cpp$", r".*\.h$", r".*\.m$", r".*\.mm$",
22 r".*\.inl$", r".*\.asm$", r".*\.hxx$", r".*\.hpp$", r".*\.s$", r".*\.S$",
23 # Scripts
24 r".*\.js$", r".*\.py$", r".*\.sh$", r".*\.rb$", r".*\.pl$", r".*\.pm$",
25 # No extension at all, note that ALL CAPS files are black listed in
26 # COMMON_EXCLUDED_LIST below.
27 r"(^|.*?[\\\/])[^.]+$",
28 # Other
29 r".*\.java$", r".*\.mk$", r".*\.am$",
30]
31
Ryan Cui1562fb82011-05-09 11:01:31 -070032
Ryan Cuiec4d6332011-05-02 14:15:25 -070033COMMON_EXCLUDED_PATHS = [
Ryan Cui31e0c172011-05-04 21:00:45 -070034 # avoid doing source file checks for kernel
35 r"/src/third_party/kernel/",
36 r"/src/third_party/kernel-next/",
Paul Taysomf8b6e012011-05-09 14:32:42 -070037 r"/src/third_party/ktop/",
38 r"/src/third_party/punybench/",
Ryan Cuiec4d6332011-05-02 14:15:25 -070039 r".*\bexperimental[\\\/].*",
40 r".*\b[A-Z0-9_]{2,}$",
41 r".*[\\\/]debian[\\\/]rules$",
Brian Harringd780d602011-10-18 16:48:08 -070042 # for ebuild trees, ignore any caches and manifest data
43 r".*/Manifest$",
44 r".*/metadata/[^/]*cache[^/]*/[^/]+/[^/]+$",
Doug Anderson5bfb6792011-10-25 16:45:41 -070045
46 # ignore profiles data (like overlay-tegra2/profiles)
47 r".*/overlay-.*/profiles/.*",
Andrew de los Reyes0e679922012-05-02 11:42:54 -070048 # ignore minified js and jquery
49 r".*\.min\.js",
50 r".*jquery.*\.js",
Ryan Cuiec4d6332011-05-02 14:15:25 -070051]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070052
Ryan Cui1562fb82011-05-09 11:01:31 -070053
Ryan Cui9b651632011-05-11 11:38:58 -070054_CONFIG_FILE = 'PRESUBMIT.cfg'
55
56
Doug Anderson44a644f2011-11-02 10:37:37 -070057# Exceptions
58
59
60class BadInvocation(Exception):
61 """An Exception indicating a bad invocation of the program."""
62 pass
63
64
Ryan Cui1562fb82011-05-09 11:01:31 -070065# General Helpers
66
Sean Paulba01d402011-05-05 11:36:23 -040067
Doug Anderson44a644f2011-11-02 10:37:37 -070068def _run_command(cmd, cwd=None, stderr=None):
69 """Executes the passed in command and returns raw stdout output.
70
71 Args:
72 cmd: The command to run; should be a list of strings.
73 cwd: The directory to switch to for running the command.
74 stderr: Can be one of None (print stderr to console), subprocess.STDOUT
75 (combine stderr with stdout), or subprocess.PIPE (ignore stderr).
76
77 Returns:
78 The standard out from the process.
79 """
80 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=stderr, cwd=cwd)
81 return p.communicate()[0]
Ryan Cui72834d12011-05-05 14:51:33 -070082
Ryan Cui1562fb82011-05-09 11:01:31 -070083
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070084def _get_hooks_dir():
Ryan Cuiec4d6332011-05-02 14:15:25 -070085 """Returns the absolute path to the repohooks directory."""
Doug Anderson44a644f2011-11-02 10:37:37 -070086 if __name__ == '__main__':
87 # Works when file is run on its own (__file__ is defined)...
88 return os.path.abspath(os.path.dirname(__file__))
89 else:
90 # We need to do this when we're run through repo. Since repo executes
91 # us with execfile(), we don't get __file__ defined.
92 cmd = ['repo', 'forall', 'chromiumos/repohooks', '-c', 'pwd']
93 return _run_command(cmd).strip()
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070094
Ryan Cui1562fb82011-05-09 11:01:31 -070095
Ryan Cuiec4d6332011-05-02 14:15:25 -070096def _match_regex_list(subject, expressions):
97 """Try to match a list of regular expressions to a string.
98
99 Args:
100 subject: The string to match regexes on
101 expressions: A list of regular expressions to check for matches with.
102
103 Returns:
104 Whether the passed in subject matches any of the passed in regexes.
105 """
106 for expr in expressions:
107 if (re.search(expr, subject)):
108 return True
109 return False
110
Ryan Cui1562fb82011-05-09 11:01:31 -0700111
Ryan Cuiec4d6332011-05-02 14:15:25 -0700112def _filter_files(files, include_list, exclude_list=[]):
113 """Filter out files based on the conditions passed in.
114
115 Args:
116 files: list of filepaths to filter
117 include_list: list of regex that when matched with a file path will cause it
118 to be added to the output list unless the file is also matched with a
119 regex in the exclude_list.
120 exclude_list: list of regex that when matched with a file will prevent it
121 from being added to the output list, even if it is also matched with a
122 regex in the include_list.
123
124 Returns:
125 A list of filepaths that contain files matched in the include_list and not
126 in the exclude_list.
127 """
128 filtered = []
129 for f in files:
130 if (_match_regex_list(f, include_list) and
131 not _match_regex_list(f, exclude_list)):
132 filtered.append(f)
133 return filtered
134
Ryan Cuiec4d6332011-05-02 14:15:25 -0700135
136# Git Helpers
Ryan Cui1562fb82011-05-09 11:01:31 -0700137
138
Ryan Cui4725d952011-05-05 15:41:19 -0700139def _get_upstream_branch():
140 """Returns the upstream tracking branch of the current branch.
141
142 Raises:
143 Error if there is no tracking branch
144 """
145 current_branch = _run_command(['git', 'symbolic-ref', 'HEAD']).strip()
146 current_branch = current_branch.replace('refs/heads/', '')
147 if not current_branch:
Ryan Cui1562fb82011-05-09 11:01:31 -0700148 raise VerifyException('Need to be on a tracking branch')
Ryan Cui4725d952011-05-05 15:41:19 -0700149
150 cfg_option = 'branch.' + current_branch + '.%s'
151 full_upstream = _run_command(['git', 'config', cfg_option % 'merge']).strip()
152 remote = _run_command(['git', 'config', cfg_option % 'remote']).strip()
153 if not remote or not full_upstream:
Ryan Cui1562fb82011-05-09 11:01:31 -0700154 raise VerifyException('Need to be on a tracking branch')
Ryan Cui4725d952011-05-05 15:41:19 -0700155
156 return full_upstream.replace('heads', 'remotes/' + remote)
157
Ryan Cui1562fb82011-05-09 11:01:31 -0700158
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700159def _get_diff(commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700160 """Returns the diff for this commit."""
Ryan Cui72834d12011-05-05 14:51:33 -0700161 return _run_command(['git', 'show', commit])
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700162
Ryan Cui1562fb82011-05-09 11:01:31 -0700163
Jon Salz98255932012-08-18 14:48:02 +0800164def _try_utf8_decode(data):
165 """Attempts to decode a string as UTF-8.
166
167 Returns:
168 The decoded Unicode object, or the original string if parsing fails.
169 """
170 try:
171 return unicode(data, 'utf-8', 'strict')
172 except UnicodeDecodeError:
173 return data
174
175
Ryan Cuiec4d6332011-05-02 14:15:25 -0700176def _get_file_diff(file, commit):
177 """Returns a list of (linenum, lines) tuples that the commit touched."""
Ryan Cui72834d12011-05-05 14:51:33 -0700178 output = _run_command(['git', 'show', '-p', '--no-ext-diff', commit, file])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700179
180 new_lines = []
181 line_num = 0
182 for line in output.splitlines():
183 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
184 if m:
185 line_num = int(m.groups(1)[0])
186 continue
187 if line.startswith('+') and not line.startswith('++'):
Jon Salz98255932012-08-18 14:48:02 +0800188 new_lines.append((line_num, _try_utf8_decode(line[1:])))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700189 if not line.startswith('-'):
190 line_num += 1
191 return new_lines
192
Ryan Cui1562fb82011-05-09 11:01:31 -0700193
Ryan Cuiec4d6332011-05-02 14:15:25 -0700194def _get_affected_files(commit):
195 """Returns list of absolute filepaths that were modified/added."""
Ryan Cui72834d12011-05-05 14:51:33 -0700196 output = _run_command(['git', 'diff', '--name-status', commit + '^!'])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700197 files = []
198 for statusline in output.splitlines():
199 m = re.match('^(\w)+\t(.+)$', statusline.rstrip())
200 # Ignore deleted files, and return absolute paths of files
201 if (m.group(1)[0] != 'D'):
202 pwd = os.getcwd()
203 files.append(os.path.join(pwd, m.group(2)))
204 return files
205
Ryan Cui1562fb82011-05-09 11:01:31 -0700206
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700207def _get_commits():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700208 """Returns a list of commits for this review."""
Ryan Cui4725d952011-05-05 15:41:19 -0700209 cmd = ['git', 'log', '%s..' % _get_upstream_branch(), '--format=%H']
Ryan Cui72834d12011-05-05 14:51:33 -0700210 return _run_command(cmd).split()
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700211
Ryan Cui1562fb82011-05-09 11:01:31 -0700212
Ryan Cuiec4d6332011-05-02 14:15:25 -0700213def _get_commit_desc(commit):
214 """Returns the full commit message of a commit."""
Sean Paul23a2c582011-05-06 13:10:44 -0400215 return _run_command(['git', 'log', '--format=%s%n%n%b', commit + '^!'])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700216
217
218# Common Hooks
219
Ryan Cui1562fb82011-05-09 11:01:31 -0700220
Ryan Cuiec4d6332011-05-02 14:15:25 -0700221def _check_no_long_lines(project, commit):
222 """Checks that there aren't any lines longer than maxlen characters in any of
223 the text files to be submitted.
224 """
225 MAX_LEN = 80
Jon Salz98255932012-08-18 14:48:02 +0800226 SKIP_REGEXP = re.compile('|'.join([
227 r'https?://',
228 r'^#\s*(define|include|import|pragma|if|endif)\b']))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700229
230 errors = []
231 files = _filter_files(_get_affected_files(commit),
232 COMMON_INCLUDED_PATHS,
233 COMMON_EXCLUDED_PATHS)
234
235 for afile in files:
236 for line_num, line in _get_file_diff(afile, commit):
237 # Allow certain lines to exceed the maxlen rule.
Jon Salz98255932012-08-18 14:48:02 +0800238 if (len(line) <= MAX_LEN or SKIP_REGEXP.search(line)):
239 continue
240
241 errors.append('%s, line %s, %s chars' % (afile, line_num, len(line)))
242 if len(errors) == 5: # Just show the first 5 errors.
243 break
Ryan Cuiec4d6332011-05-02 14:15:25 -0700244
245 if errors:
246 msg = 'Found lines longer than %s characters (first 5 shown):' % MAX_LEN
Ryan Cui1562fb82011-05-09 11:01:31 -0700247 return HookFailure(msg, errors)
248
Ryan Cuiec4d6332011-05-02 14:15:25 -0700249
250def _check_no_stray_whitespace(project, commit):
251 """Checks that there is no stray whitespace at source lines end."""
252 errors = []
253 files = _filter_files(_get_affected_files(commit),
254 COMMON_INCLUDED_PATHS,
255 COMMON_EXCLUDED_PATHS)
256
257 for afile in files:
258 for line_num, line in _get_file_diff(afile, commit):
259 if line.rstrip() != line:
260 errors.append('%s, line %s' % (afile, line_num))
261 if errors:
Ryan Cui1562fb82011-05-09 11:01:31 -0700262 return HookFailure('Found line ending with white space in:', errors)
263
Ryan Cuiec4d6332011-05-02 14:15:25 -0700264
265def _check_no_tabs(project, commit):
266 """Checks there are no unexpanded tabs."""
267 TAB_OK_PATHS = [
Ryan Cui31e0c172011-05-04 21:00:45 -0700268 r"/src/third_party/u-boot/",
Ryan Cuiec4d6332011-05-02 14:15:25 -0700269 r".*\.ebuild$",
270 r".*\.eclass$",
Elly Jones5ab34192011-11-15 14:57:06 -0500271 r".*/[M|m]akefile$",
272 r".*\.mk$"
Ryan Cuiec4d6332011-05-02 14:15:25 -0700273 ]
274
275 errors = []
276 files = _filter_files(_get_affected_files(commit),
277 COMMON_INCLUDED_PATHS,
278 COMMON_EXCLUDED_PATHS + TAB_OK_PATHS)
279
280 for afile in files:
281 for line_num, line in _get_file_diff(afile, commit):
282 if '\t' in line:
283 errors.append('%s, line %s' % (afile, line_num))
284 if errors:
Ryan Cui1562fb82011-05-09 11:01:31 -0700285 return HookFailure('Found a tab character in:', errors)
286
Ryan Cuiec4d6332011-05-02 14:15:25 -0700287
288def _check_change_has_test_field(project, commit):
289 """Check for a non-empty 'TEST=' field in the commit message."""
David McMahon8f6553e2011-06-10 15:46:36 -0700290 TEST_RE = r'\nTEST=\S+'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700291
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700292 if not re.search(TEST_RE, _get_commit_desc(commit)):
Ryan Cui1562fb82011-05-09 11:01:31 -0700293 msg = 'Changelist description needs TEST field (after first line)'
294 return HookFailure(msg)
295
Ryan Cuiec4d6332011-05-02 14:15:25 -0700296
297def _check_change_has_bug_field(project, commit):
David McMahon8f6553e2011-06-10 15:46:36 -0700298 """Check for a correctly formatted 'BUG=' field in the commit message."""
Daniel Erat1f064642012-01-10 09:48:20 -0800299 BUG_RE = r'\nBUG=([Nn]one|(chrome-os-partner|chromium|chromium-os):\d+)'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700300
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700301 if not re.search(BUG_RE, _get_commit_desc(commit)):
David McMahon8f6553e2011-06-10 15:46:36 -0700302 msg = ('Changelist description needs BUG field (after first line):\n'
Daniel Erat1f064642012-01-10 09:48:20 -0800303 'BUG=chromium-os:9999 (for public tracker)\n'
David McMahon8f6553e2011-06-10 15:46:36 -0700304 'BUG=chrome-os-partner:9999 (for partner tracker)\n'
Daniel Erat1f064642012-01-10 09:48:20 -0800305 'BUG=chromium:9999 (for browser tracker)\n'
David McMahon8f6553e2011-06-10 15:46:36 -0700306 'BUG=None')
Ryan Cui1562fb82011-05-09 11:01:31 -0700307 return HookFailure(msg)
308
Ryan Cuiec4d6332011-05-02 14:15:25 -0700309
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700310def _check_change_has_proper_changeid(project, commit):
311 """Verify that Change-ID is present in last paragraph of commit message."""
312 desc = _get_commit_desc(commit)
313 loc = desc.rfind('\nChange-Id:')
314 if loc == -1 or re.search('\n\s*\n\s*\S+', desc[loc:]):
Ryan Cui1562fb82011-05-09 11:01:31 -0700315 return HookFailure('Change-Id must be in last paragraph of description.')
316
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700317
Ryan Cuiec4d6332011-05-02 14:15:25 -0700318def _check_license(project, commit):
319 """Verifies the license header."""
320 LICENSE_HEADER = (
David James28766e62012-08-06 17:30:15 -0700321 r".*? Copyright \(c\) 20[-0-9]{2,7} The Chromium OS Authors\. All rights "
Ryan Cuiec4d6332011-05-02 14:15:25 -0700322 r"reserved\." "\n"
323 r".*? Use of this source code is governed by a BSD-style license that can "
324 "be\n"
325 r".*? found in the LICENSE file\."
326 "\n"
327 )
328
329 license_re = re.compile(LICENSE_HEADER, re.MULTILINE)
330 bad_files = []
331 files = _filter_files(_get_affected_files(commit),
332 COMMON_INCLUDED_PATHS,
333 COMMON_EXCLUDED_PATHS)
334
335 for f in files:
336 contents = open(f).read()
337 if len(contents) == 0: continue # Ignore empty files
338 if not license_re.search(contents):
339 bad_files.append(f)
340 if bad_files:
Ryan Cui1562fb82011-05-09 11:01:31 -0700341 return HookFailure('License must match:\n%s\n' % license_re.pattern +
342 'Found a bad license header in these files:',
343 bad_files)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700344
345
346# Project-specific hooks
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700347
Ryan Cui1562fb82011-05-09 11:01:31 -0700348
Anton Staaf815d6852011-08-22 10:08:45 -0700349def _run_checkpatch(project, commit, options=[]):
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700350 """Runs checkpatch.pl on the given project"""
351 hooks_dir = _get_hooks_dir()
Anton Staaf815d6852011-08-22 10:08:45 -0700352 cmd = ['%s/checkpatch.pl' % hooks_dir] + options + ['-']
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700353 p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700354 output = p.communicate(_get_diff(commit))[0]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700355 if p.returncode:
Ryan Cui1562fb82011-05-09 11:01:31 -0700356 return HookFailure('checkpatch.pl errors/warnings\n\n' + output)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700357
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700358
Anton Staaf815d6852011-08-22 10:08:45 -0700359def _run_checkpatch_no_tree(project, commit):
360 return _run_checkpatch(project, commit, ['--no-tree'])
361
Olof Johanssona96810f2012-09-04 16:20:03 -0700362def _kernel_configcheck(project, commit):
363 """Makes sure kernel config changes are not mixed with code changes"""
364 files = _get_affected_files(commit)
365 if not len(_filter_files(files, [r'chromeos/config'])) in [0, len(files)]:
366 return HookFailure('Changes to chromeos/config/ and regular files must '
367 'be in separate commits:\n%s' % '\n'.join(files))
Anton Staaf815d6852011-08-22 10:08:45 -0700368
Dale Curtis2975c432011-05-03 17:25:20 -0700369def _run_json_check(project, commit):
370 """Checks that all JSON files are syntactically valid."""
Dale Curtisa039cfd2011-05-04 12:01:05 -0700371 for f in _filter_files(_get_affected_files(commit), [r'.*\.json']):
Dale Curtis2975c432011-05-03 17:25:20 -0700372 try:
373 json.load(open(f))
374 except Exception, e:
Ryan Cui1562fb82011-05-09 11:01:31 -0700375 return HookFailure('Invalid JSON in %s: %s' % (f, e))
Dale Curtis2975c432011-05-03 17:25:20 -0700376
377
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700378def _check_change_has_branch_field(project, commit):
379 """Check for a non-empty 'BRANCH=' field in the commit message."""
380 BRANCH_RE = r'\nBRANCH=\S+'
381
382 if not re.search(BRANCH_RE, _get_commit_desc(commit)):
383 msg = ('Changelist description needs BRANCH field (after first line)\n'
384 'E.g. BRANCH=none or BRANCH=link,snow')
385 return HookFailure(msg)
386
387
Jon Salz3ee59de2012-08-18 13:54:22 +0800388def _run_project_hook_script(script, project, commit):
389 """Runs a project hook script.
390
391 The script is run with the following environment variables set:
392 PRESUBMIT_PROJECT: The affected project
393 PRESUBMIT_COMMIT: The affected commit
394 PRESUBMIT_FILES: A newline-separated list of affected files
395
396 The script is considered to fail if the exit code is non-zero. It should
397 write an error message to stdout.
398 """
399 env = dict(os.environ)
400 env['PRESUBMIT_PROJECT'] = project
401 env['PRESUBMIT_COMMIT'] = commit
402
403 # Put affected files in an environment variable
404 files = _get_affected_files(commit)
405 env['PRESUBMIT_FILES'] = '\n'.join(files)
406
407 process = subprocess.Popen(script, env=env, shell=True,
408 stdin=open(os.devnull),
409 stdout=subprocess.PIPE)
410 stdout, _ = process.communicate()
411 if process.wait():
412 return HookFailure('Hook script %s failed with code %d%s' %
413 (script, process.returncode,
414 ':\n' + stdout if stdout else ''))
415
416
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700417# Base
418
Ryan Cui1562fb82011-05-09 11:01:31 -0700419
Ryan Cui9b651632011-05-11 11:38:58 -0700420# A list of hooks that are not project-specific
421_COMMON_HOOKS = [
422 _check_change_has_bug_field,
423 _check_change_has_test_field,
424 _check_change_has_proper_changeid,
425 _check_no_stray_whitespace,
426 _check_no_long_lines,
427 _check_license,
428 _check_no_tabs,
429]
Ryan Cuiec4d6332011-05-02 14:15:25 -0700430
Ryan Cui1562fb82011-05-09 11:01:31 -0700431
Ryan Cui9b651632011-05-11 11:38:58 -0700432# A dictionary of project-specific hooks(callbacks), indexed by project name.
433# dict[project] = [callback1, callback2]
434_PROJECT_SPECIFIC_HOOKS = {
Olof Johanssona96810f2012-09-04 16:20:03 -0700435 "chromiumos/third_party/kernel": [_run_checkpatch, _kernel_configcheck],
436 "chromiumos/third_party/kernel-next": [_run_checkpatch,
437 _kernel_configcheck],
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700438 "chromiumos/third_party/u-boot": [_run_checkpatch_no_tree,
439 _check_change_has_branch_field],
440 "chromiumos/platform/ec": [_run_checkpatch_no_tree,
441 _check_change_has_branch_field],
442 "chromeos/platform/ec-private": [_run_checkpatch_no_tree,
443 _check_change_has_branch_field],
444 "chromeos/third_party/coreboot": [_check_change_has_branch_field],
Puneet Kumar57b9c092012-08-14 18:58:29 -0700445 "chromeos/third_party/intel-framework": [_check_change_has_branch_field],
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700446 "chromiumos/platform/vboot_reference": [_check_change_has_branch_field],
447 "chromiumos/platform/mosys": [_check_change_has_branch_field],
448 "chromiumos/third_party/flashrom": [_check_change_has_branch_field],
Dale Curtis2975c432011-05-03 17:25:20 -0700449 "chromeos/autotest-tools": [_run_json_check],
Ryan Cui9b651632011-05-11 11:38:58 -0700450}
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700451
Ryan Cui1562fb82011-05-09 11:01:31 -0700452
Ryan Cui9b651632011-05-11 11:38:58 -0700453# A dictionary of flags (keys) that can appear in the config file, and the hook
454# that the flag disables (value)
455_DISABLE_FLAGS = {
456 'stray_whitespace_check': _check_no_stray_whitespace,
457 'long_line_check': _check_no_long_lines,
458 'cros_license_check': _check_license,
459 'tab_check': _check_no_tabs,
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700460 'branch_check': _check_change_has_branch_field,
Ryan Cui9b651632011-05-11 11:38:58 -0700461}
462
463
Jon Salz3ee59de2012-08-18 13:54:22 +0800464def _get_disabled_hooks(config):
Ryan Cui9b651632011-05-11 11:38:58 -0700465 """Returns a set of hooks disabled by the current project's config file.
466
467 Expects to be called within the project root.
Jon Salz3ee59de2012-08-18 13:54:22 +0800468
469 Args:
470 config: A ConfigParser for the project's config file.
Ryan Cui9b651632011-05-11 11:38:58 -0700471 """
472 SECTION = 'Hook Overrides'
Jon Salz3ee59de2012-08-18 13:54:22 +0800473 if not config.has_section(SECTION):
474 return set()
Ryan Cui9b651632011-05-11 11:38:58 -0700475
476 disable_flags = []
Jon Salz3ee59de2012-08-18 13:54:22 +0800477 for flag in config.options(SECTION):
Ryan Cui9b651632011-05-11 11:38:58 -0700478 try:
479 if not config.getboolean(SECTION, flag): disable_flags.append(flag)
480 except ValueError as e:
481 msg = "Error parsing flag \'%s\' in %s file - " % (flag, _CONFIG_FILE)
482 print msg + str(e)
483
484 disabled_keys = set(_DISABLE_FLAGS.iterkeys()).intersection(disable_flags)
485 return set([_DISABLE_FLAGS[key] for key in disabled_keys])
486
487
Jon Salz3ee59de2012-08-18 13:54:22 +0800488def _get_project_hook_scripts(config):
489 """Returns a list of project-specific hook scripts.
490
491 Args:
492 config: A ConfigParser for the project's config file.
493 """
494 SECTION = 'Hook Scripts'
495 if not config.has_section(SECTION):
496 return []
497
498 hook_names_values = config.items(SECTION)
499 hook_names_values.sort(key=lambda x: x[0])
500 return [x[1] for x in hook_names_values]
501
502
Ryan Cui9b651632011-05-11 11:38:58 -0700503def _get_project_hooks(project):
504 """Returns a list of hooks that need to be run for a project.
505
506 Expects to be called from within the project root.
507 """
Jon Salz3ee59de2012-08-18 13:54:22 +0800508 config = ConfigParser.RawConfigParser()
509 try:
510 config.read(_CONFIG_FILE)
511 except ConfigParser.Error:
512 # Just use an empty config file
513 config = ConfigParser.RawConfigParser()
514
515 disabled_hooks = _get_disabled_hooks(config)
Ryan Cui9b651632011-05-11 11:38:58 -0700516 hooks = [hook for hook in _COMMON_HOOKS if hook not in disabled_hooks]
517
518 if project in _PROJECT_SPECIFIC_HOOKS:
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700519 hooks.extend(hook for hook in _PROJECT_SPECIFIC_HOOKS[project]
520 if hook not in disabled_hooks)
Ryan Cui9b651632011-05-11 11:38:58 -0700521
Jon Salz3ee59de2012-08-18 13:54:22 +0800522 for script in _get_project_hook_scripts(config):
523 hooks.append(functools.partial(_run_project_hook_script, script))
524
Ryan Cui9b651632011-05-11 11:38:58 -0700525 return hooks
526
527
Doug Anderson44a644f2011-11-02 10:37:37 -0700528def _run_project_hooks(project, proj_dir=None):
Ryan Cui1562fb82011-05-09 11:01:31 -0700529 """For each project run its project specific hook from the hooks dictionary.
530
531 Args:
Doug Anderson44a644f2011-11-02 10:37:37 -0700532 project: The name of project to run hooks for.
533 proj_dir: If non-None, this is the directory the project is in. If None,
534 we'll ask repo.
Ryan Cui1562fb82011-05-09 11:01:31 -0700535
536 Returns:
537 Boolean value of whether any errors were ecountered while running the hooks.
538 """
Doug Anderson44a644f2011-11-02 10:37:37 -0700539 if proj_dir is None:
540 proj_dir = _run_command(['repo', 'forall', project, '-c', 'pwd']).strip()
541
Ryan Cuiec4d6332011-05-02 14:15:25 -0700542 pwd = os.getcwd()
543 # hooks assume they are run from the root of the project
544 os.chdir(proj_dir)
545
Ryan Cuifa55df52011-05-06 11:16:55 -0700546 try:
547 commit_list = _get_commits()
Don Garrettdba548a2011-05-05 15:17:14 -0700548 except VerifyException as e:
Ryan Cui1562fb82011-05-09 11:01:31 -0700549 PrintErrorForProject(project, HookFailure(str(e)))
550 os.chdir(pwd)
551 return True
Ryan Cuifa55df52011-05-06 11:16:55 -0700552
Ryan Cui9b651632011-05-11 11:38:58 -0700553 hooks = _get_project_hooks(project)
Ryan Cui1562fb82011-05-09 11:01:31 -0700554 error_found = False
Ryan Cuifa55df52011-05-06 11:16:55 -0700555 for commit in commit_list:
Ryan Cui1562fb82011-05-09 11:01:31 -0700556 error_list = []
Ryan Cui9b651632011-05-11 11:38:58 -0700557 for hook in hooks:
Ryan Cui1562fb82011-05-09 11:01:31 -0700558 hook_error = hook(project, commit)
559 if hook_error:
560 error_list.append(hook_error)
561 error_found = True
562 if error_list:
563 PrintErrorsForCommit(project, commit, _get_commit_desc(commit),
564 error_list)
Don Garrettdba548a2011-05-05 15:17:14 -0700565
Ryan Cuiec4d6332011-05-02 14:15:25 -0700566 os.chdir(pwd)
Ryan Cui1562fb82011-05-09 11:01:31 -0700567 return error_found
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700568
569# Main
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -0700570
Ryan Cui1562fb82011-05-09 11:01:31 -0700571
Anush Elangovan63afad72011-03-23 00:41:27 -0700572def main(project_list, **kwargs):
Doug Anderson06456632012-01-05 11:02:14 -0800573 """Main function invoked directly by repo.
574
575 This function will exit directly upon error so that repo doesn't print some
576 obscure error message.
577
578 Args:
579 project_list: List of projects to run on.
580 kwargs: Leave this here for forward-compatibility.
581 """
Ryan Cui1562fb82011-05-09 11:01:31 -0700582 found_error = False
583 for project in project_list:
Ryan Cui9b651632011-05-11 11:38:58 -0700584 if _run_project_hooks(project):
Ryan Cui1562fb82011-05-09 11:01:31 -0700585 found_error = True
586
587 if (found_error):
588 msg = ('Preupload failed due to errors in project(s). HINTS:\n'
Ryan Cui9b651632011-05-11 11:38:58 -0700589 '- To disable some source style checks, and for other hints, see '
590 '<checkout_dir>/src/repohooks/README\n'
591 '- To upload only current project, run \'repo upload .\'')
Ryan Cui1562fb82011-05-09 11:01:31 -0700592 print >> sys.stderr, msg
Don Garrettdba548a2011-05-05 15:17:14 -0700593 sys.exit(1)
Anush Elangovan63afad72011-03-23 00:41:27 -0700594
Ryan Cui1562fb82011-05-09 11:01:31 -0700595
Doug Anderson44a644f2011-11-02 10:37:37 -0700596def _identify_project(path):
597 """Identify the repo project associated with the given path.
598
599 Returns:
600 A string indicating what project is associated with the path passed in or
601 a blank string upon failure.
602 """
603 return _run_command(['repo', 'forall', '.', '-c', 'echo ${REPO_PROJECT}'],
604 stderr=subprocess.PIPE, cwd=path).strip()
605
606
607def direct_main(args, verbose=False):
608 """Run hooks directly (outside of the context of repo).
609
610 # Setup for doctests below.
611 # ...note that some tests assume that running pre-upload on this CWD is fine.
612 # TODO: Use mock and actually mock out _run_project_hooks() for tests.
613 >>> mydir = os.path.dirname(os.path.abspath(__file__))
614 >>> olddir = os.getcwd()
615
616 # OK to run w/ no arugments; will run with CWD.
617 >>> os.chdir(mydir)
618 >>> direct_main(['prog_name'], verbose=True)
619 Running hooks on chromiumos/repohooks
620 0
621 >>> os.chdir(olddir)
622
623 # Run specifying a dir
624 >>> direct_main(['prog_name', '--dir=%s' % mydir], verbose=True)
625 Running hooks on chromiumos/repohooks
626 0
627
628 # Not a problem to use a bogus project; we'll just get default settings.
629 >>> direct_main(['prog_name', '--dir=%s' % mydir, '--project=X'],verbose=True)
630 Running hooks on X
631 0
632
633 # Run with project but no dir
634 >>> os.chdir(mydir)
635 >>> direct_main(['prog_name', '--project=X'], verbose=True)
636 Running hooks on X
637 0
638 >>> os.chdir(olddir)
639
640 # Try with a non-git CWD
641 >>> os.chdir('/tmp')
642 >>> direct_main(['prog_name'])
643 Traceback (most recent call last):
644 ...
645 BadInvocation: The current directory is not part of a git project.
646
647 # Check various bad arguments...
648 >>> direct_main(['prog_name', 'bogus'])
649 Traceback (most recent call last):
650 ...
651 BadInvocation: Unexpected arguments: bogus
652 >>> direct_main(['prog_name', '--project=bogus', '--dir=bogusdir'])
653 Traceback (most recent call last):
654 ...
655 BadInvocation: Invalid dir: bogusdir
656 >>> direct_main(['prog_name', '--project=bogus', '--dir=/tmp'])
657 Traceback (most recent call last):
658 ...
659 BadInvocation: Not a git directory: /tmp
660
661 Args:
662 args: The value of sys.argv
663
664 Returns:
665 0 if no pre-upload failures, 1 if failures.
666
667 Raises:
668 BadInvocation: On some types of invocation errors.
669 """
670 desc = 'Run Chromium OS pre-upload hooks on changes compared to upstream.'
671 parser = optparse.OptionParser(description=desc)
672
673 parser.add_option('--dir', default=None,
674 help='The directory that the project lives in. If not '
675 'specified, use the git project root based on the cwd.')
676 parser.add_option('--project', default=None,
677 help='The project repo path; this can affect how the hooks '
678 'get run, since some hooks are project-specific. For '
679 'chromite this is chromiumos/chromite. If not specified, '
680 'the repo tool will be used to figure this out based on '
681 'the dir.')
682
683 opts, args = parser.parse_args(args[1:])
684
685 if args:
686 raise BadInvocation('Unexpected arguments: %s' % ' '.join(args))
687
688 # Check/normlaize git dir; if unspecified, we'll use the root of the git
689 # project from CWD
690 if opts.dir is None:
691 git_dir = _run_command(['git', 'rev-parse', '--git-dir'],
692 stderr=subprocess.PIPE).strip()
693 if not git_dir:
694 raise BadInvocation('The current directory is not part of a git project.')
695 opts.dir = os.path.dirname(os.path.abspath(git_dir))
696 elif not os.path.isdir(opts.dir):
697 raise BadInvocation('Invalid dir: %s' % opts.dir)
698 elif not os.path.isdir(os.path.join(opts.dir, '.git')):
699 raise BadInvocation('Not a git directory: %s' % opts.dir)
700
701 # Identify the project if it wasn't specified; this _requires_ the repo
702 # tool to be installed and for the project to be part of a repo checkout.
703 if not opts.project:
704 opts.project = _identify_project(opts.dir)
705 if not opts.project:
706 raise BadInvocation("Repo couldn't identify the project of %s" % opts.dir)
707
708 if verbose:
709 print "Running hooks on %s" % (opts.project)
710
711 found_error = _run_project_hooks(opts.project, proj_dir=opts.dir)
712 if found_error:
713 return 1
714 return 0
715
716
717def _test():
718 """Run any built-in tests."""
719 import doctest
720 doctest.testmod()
721
722
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -0700723if __name__ == '__main__':
Doug Anderson44a644f2011-11-02 10:37:37 -0700724 if sys.argv[1:2] == ["--test"]:
725 _test()
726 exit_code = 0
727 else:
728 prog_name = os.path.basename(sys.argv[0])
729 try:
730 exit_code = direct_main(sys.argv)
731 except BadInvocation, e:
732 print >>sys.stderr, "%s: %s" % (prog_name, str(e))
733 exit_code = 1
734 sys.exit(exit_code)