blob: 467dc043bbb4ef2e3d6bdf72c1ca5f825b58b38d [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
Dale Curtis2975c432011-05-03 17:25:20 -07007import json
Doug Anderson44a644f2011-11-02 10:37:37 -07008import optparse
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07009import os
Ryan Cuiec4d6332011-05-02 14:15:25 -070010import re
Mandeep Singh Bainesa7ffa4b2011-05-03 11:37:02 -070011import sys
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070012import subprocess
13
Ryan Cui1562fb82011-05-09 11:01:31 -070014from errors import (VerifyException, HookFailure, PrintErrorForProject,
15 PrintErrorsForCommit)
Ryan Cuiec4d6332011-05-02 14:15:25 -070016
Ryan Cuiec4d6332011-05-02 14:15:25 -070017
18COMMON_INCLUDED_PATHS = [
19 # C++ and friends
20 r".*\.c$", r".*\.cc$", r".*\.cpp$", r".*\.h$", r".*\.m$", r".*\.mm$",
21 r".*\.inl$", r".*\.asm$", r".*\.hxx$", r".*\.hpp$", r".*\.s$", r".*\.S$",
22 # Scripts
23 r".*\.js$", r".*\.py$", r".*\.sh$", r".*\.rb$", r".*\.pl$", r".*\.pm$",
24 # No extension at all, note that ALL CAPS files are black listed in
25 # COMMON_EXCLUDED_LIST below.
26 r"(^|.*?[\\\/])[^.]+$",
27 # Other
28 r".*\.java$", r".*\.mk$", r".*\.am$",
29]
30
Ryan Cui1562fb82011-05-09 11:01:31 -070031
Ryan Cuiec4d6332011-05-02 14:15:25 -070032COMMON_EXCLUDED_PATHS = [
Ryan Cui31e0c172011-05-04 21:00:45 -070033 # avoid doing source file checks for kernel
34 r"/src/third_party/kernel/",
35 r"/src/third_party/kernel-next/",
Paul Taysomf8b6e012011-05-09 14:32:42 -070036 r"/src/third_party/ktop/",
37 r"/src/third_party/punybench/",
Ryan Cuiec4d6332011-05-02 14:15:25 -070038 r".*\bexperimental[\\\/].*",
39 r".*\b[A-Z0-9_]{2,}$",
40 r".*[\\\/]debian[\\\/]rules$",
Brian Harringd780d602011-10-18 16:48:08 -070041 # for ebuild trees, ignore any caches and manifest data
42 r".*/Manifest$",
43 r".*/metadata/[^/]*cache[^/]*/[^/]+/[^/]+$",
Doug Anderson5bfb6792011-10-25 16:45:41 -070044
45 # ignore profiles data (like overlay-tegra2/profiles)
46 r".*/overlay-.*/profiles/.*",
Andrew de los Reyes0e679922012-05-02 11:42:54 -070047 # ignore minified js and jquery
48 r".*\.min\.js",
49 r".*jquery.*\.js",
Ryan Cuiec4d6332011-05-02 14:15:25 -070050]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070051
Ryan Cui1562fb82011-05-09 11:01:31 -070052
Ryan Cui9b651632011-05-11 11:38:58 -070053_CONFIG_FILE = 'PRESUBMIT.cfg'
54
55
Doug Anderson44a644f2011-11-02 10:37:37 -070056# Exceptions
57
58
59class BadInvocation(Exception):
60 """An Exception indicating a bad invocation of the program."""
61 pass
62
63
Ryan Cui1562fb82011-05-09 11:01:31 -070064# General Helpers
65
Sean Paulba01d402011-05-05 11:36:23 -040066
Doug Anderson44a644f2011-11-02 10:37:37 -070067def _run_command(cmd, cwd=None, stderr=None):
68 """Executes the passed in command and returns raw stdout output.
69
70 Args:
71 cmd: The command to run; should be a list of strings.
72 cwd: The directory to switch to for running the command.
73 stderr: Can be one of None (print stderr to console), subprocess.STDOUT
74 (combine stderr with stdout), or subprocess.PIPE (ignore stderr).
75
76 Returns:
77 The standard out from the process.
78 """
79 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=stderr, cwd=cwd)
80 return p.communicate()[0]
Ryan Cui72834d12011-05-05 14:51:33 -070081
Ryan Cui1562fb82011-05-09 11:01:31 -070082
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070083def _get_hooks_dir():
Ryan Cuiec4d6332011-05-02 14:15:25 -070084 """Returns the absolute path to the repohooks directory."""
Doug Anderson44a644f2011-11-02 10:37:37 -070085 if __name__ == '__main__':
86 # Works when file is run on its own (__file__ is defined)...
87 return os.path.abspath(os.path.dirname(__file__))
88 else:
89 # We need to do this when we're run through repo. Since repo executes
90 # us with execfile(), we don't get __file__ defined.
91 cmd = ['repo', 'forall', 'chromiumos/repohooks', '-c', 'pwd']
92 return _run_command(cmd).strip()
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070093
Ryan Cui1562fb82011-05-09 11:01:31 -070094
Ryan Cuiec4d6332011-05-02 14:15:25 -070095def _match_regex_list(subject, expressions):
96 """Try to match a list of regular expressions to a string.
97
98 Args:
99 subject: The string to match regexes on
100 expressions: A list of regular expressions to check for matches with.
101
102 Returns:
103 Whether the passed in subject matches any of the passed in regexes.
104 """
105 for expr in expressions:
106 if (re.search(expr, subject)):
107 return True
108 return False
109
Ryan Cui1562fb82011-05-09 11:01:31 -0700110
Ryan Cuiec4d6332011-05-02 14:15:25 -0700111def _filter_files(files, include_list, exclude_list=[]):
112 """Filter out files based on the conditions passed in.
113
114 Args:
115 files: list of filepaths to filter
116 include_list: list of regex that when matched with a file path will cause it
117 to be added to the output list unless the file is also matched with a
118 regex in the exclude_list.
119 exclude_list: list of regex that when matched with a file will prevent it
120 from being added to the output list, even if it is also matched with a
121 regex in the include_list.
122
123 Returns:
124 A list of filepaths that contain files matched in the include_list and not
125 in the exclude_list.
126 """
127 filtered = []
128 for f in files:
129 if (_match_regex_list(f, include_list) and
130 not _match_regex_list(f, exclude_list)):
131 filtered.append(f)
132 return filtered
133
Ryan Cuiec4d6332011-05-02 14:15:25 -0700134
135# Git Helpers
Ryan Cui1562fb82011-05-09 11:01:31 -0700136
137
Ryan Cui4725d952011-05-05 15:41:19 -0700138def _get_upstream_branch():
139 """Returns the upstream tracking branch of the current branch.
140
141 Raises:
142 Error if there is no tracking branch
143 """
144 current_branch = _run_command(['git', 'symbolic-ref', 'HEAD']).strip()
145 current_branch = current_branch.replace('refs/heads/', '')
146 if not current_branch:
Ryan Cui1562fb82011-05-09 11:01:31 -0700147 raise VerifyException('Need to be on a tracking branch')
Ryan Cui4725d952011-05-05 15:41:19 -0700148
149 cfg_option = 'branch.' + current_branch + '.%s'
150 full_upstream = _run_command(['git', 'config', cfg_option % 'merge']).strip()
151 remote = _run_command(['git', 'config', cfg_option % 'remote']).strip()
152 if not remote or not full_upstream:
Ryan Cui1562fb82011-05-09 11:01:31 -0700153 raise VerifyException('Need to be on a tracking branch')
Ryan Cui4725d952011-05-05 15:41:19 -0700154
155 return full_upstream.replace('heads', 'remotes/' + remote)
156
Ryan Cui1562fb82011-05-09 11:01:31 -0700157
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700158def _get_diff(commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700159 """Returns the diff for this commit."""
Ryan Cui72834d12011-05-05 14:51:33 -0700160 return _run_command(['git', 'show', commit])
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700161
Ryan Cui1562fb82011-05-09 11:01:31 -0700162
Jon Salz98255932012-08-18 14:48:02 +0800163def _try_utf8_decode(data):
164 """Attempts to decode a string as UTF-8.
165
166 Returns:
167 The decoded Unicode object, or the original string if parsing fails.
168 """
169 try:
170 return unicode(data, 'utf-8', 'strict')
171 except UnicodeDecodeError:
172 return data
173
174
Ryan Cuiec4d6332011-05-02 14:15:25 -0700175def _get_file_diff(file, commit):
176 """Returns a list of (linenum, lines) tuples that the commit touched."""
Ryan Cui72834d12011-05-05 14:51:33 -0700177 output = _run_command(['git', 'show', '-p', '--no-ext-diff', commit, file])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700178
179 new_lines = []
180 line_num = 0
181 for line in output.splitlines():
182 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
183 if m:
184 line_num = int(m.groups(1)[0])
185 continue
186 if line.startswith('+') and not line.startswith('++'):
Jon Salz98255932012-08-18 14:48:02 +0800187 new_lines.append((line_num, _try_utf8_decode(line[1:])))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700188 if not line.startswith('-'):
189 line_num += 1
190 return new_lines
191
Ryan Cui1562fb82011-05-09 11:01:31 -0700192
Ryan Cuiec4d6332011-05-02 14:15:25 -0700193def _get_affected_files(commit):
194 """Returns list of absolute filepaths that were modified/added."""
Ryan Cui72834d12011-05-05 14:51:33 -0700195 output = _run_command(['git', 'diff', '--name-status', commit + '^!'])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700196 files = []
197 for statusline in output.splitlines():
198 m = re.match('^(\w)+\t(.+)$', statusline.rstrip())
199 # Ignore deleted files, and return absolute paths of files
200 if (m.group(1)[0] != 'D'):
201 pwd = os.getcwd()
202 files.append(os.path.join(pwd, m.group(2)))
203 return files
204
Ryan Cui1562fb82011-05-09 11:01:31 -0700205
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700206def _get_commits():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700207 """Returns a list of commits for this review."""
Ryan Cui4725d952011-05-05 15:41:19 -0700208 cmd = ['git', 'log', '%s..' % _get_upstream_branch(), '--format=%H']
Ryan Cui72834d12011-05-05 14:51:33 -0700209 return _run_command(cmd).split()
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700210
Ryan Cui1562fb82011-05-09 11:01:31 -0700211
Ryan Cuiec4d6332011-05-02 14:15:25 -0700212def _get_commit_desc(commit):
213 """Returns the full commit message of a commit."""
Sean Paul23a2c582011-05-06 13:10:44 -0400214 return _run_command(['git', 'log', '--format=%s%n%n%b', commit + '^!'])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700215
216
217# Common Hooks
218
Ryan Cui1562fb82011-05-09 11:01:31 -0700219
Ryan Cuiec4d6332011-05-02 14:15:25 -0700220def _check_no_long_lines(project, commit):
221 """Checks that there aren't any lines longer than maxlen characters in any of
222 the text files to be submitted.
223 """
224 MAX_LEN = 80
Jon Salz98255932012-08-18 14:48:02 +0800225 SKIP_REGEXP = re.compile('|'.join([
226 r'https?://',
227 r'^#\s*(define|include|import|pragma|if|endif)\b']))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700228
229 errors = []
230 files = _filter_files(_get_affected_files(commit),
231 COMMON_INCLUDED_PATHS,
232 COMMON_EXCLUDED_PATHS)
233
234 for afile in files:
235 for line_num, line in _get_file_diff(afile, commit):
236 # Allow certain lines to exceed the maxlen rule.
Jon Salz98255932012-08-18 14:48:02 +0800237 if (len(line) <= MAX_LEN or SKIP_REGEXP.search(line)):
238 continue
239
240 errors.append('%s, line %s, %s chars' % (afile, line_num, len(line)))
241 if len(errors) == 5: # Just show the first 5 errors.
242 break
Ryan Cuiec4d6332011-05-02 14:15:25 -0700243
244 if errors:
245 msg = 'Found lines longer than %s characters (first 5 shown):' % MAX_LEN
Ryan Cui1562fb82011-05-09 11:01:31 -0700246 return HookFailure(msg, errors)
247
Ryan Cuiec4d6332011-05-02 14:15:25 -0700248
249def _check_no_stray_whitespace(project, commit):
250 """Checks that there is no stray whitespace at source lines end."""
251 errors = []
252 files = _filter_files(_get_affected_files(commit),
253 COMMON_INCLUDED_PATHS,
254 COMMON_EXCLUDED_PATHS)
255
256 for afile in files:
257 for line_num, line in _get_file_diff(afile, commit):
258 if line.rstrip() != line:
259 errors.append('%s, line %s' % (afile, line_num))
260 if errors:
Ryan Cui1562fb82011-05-09 11:01:31 -0700261 return HookFailure('Found line ending with white space in:', errors)
262
Ryan Cuiec4d6332011-05-02 14:15:25 -0700263
264def _check_no_tabs(project, commit):
265 """Checks there are no unexpanded tabs."""
266 TAB_OK_PATHS = [
Ryan Cui31e0c172011-05-04 21:00:45 -0700267 r"/src/third_party/u-boot/",
Ryan Cuiec4d6332011-05-02 14:15:25 -0700268 r".*\.ebuild$",
269 r".*\.eclass$",
Elly Jones5ab34192011-11-15 14:57:06 -0500270 r".*/[M|m]akefile$",
271 r".*\.mk$"
Ryan Cuiec4d6332011-05-02 14:15:25 -0700272 ]
273
274 errors = []
275 files = _filter_files(_get_affected_files(commit),
276 COMMON_INCLUDED_PATHS,
277 COMMON_EXCLUDED_PATHS + TAB_OK_PATHS)
278
279 for afile in files:
280 for line_num, line in _get_file_diff(afile, commit):
281 if '\t' in line:
282 errors.append('%s, line %s' % (afile, line_num))
283 if errors:
Ryan Cui1562fb82011-05-09 11:01:31 -0700284 return HookFailure('Found a tab character in:', errors)
285
Ryan Cuiec4d6332011-05-02 14:15:25 -0700286
287def _check_change_has_test_field(project, commit):
288 """Check for a non-empty 'TEST=' field in the commit message."""
David McMahon8f6553e2011-06-10 15:46:36 -0700289 TEST_RE = r'\nTEST=\S+'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700290
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700291 if not re.search(TEST_RE, _get_commit_desc(commit)):
Ryan Cui1562fb82011-05-09 11:01:31 -0700292 msg = 'Changelist description needs TEST field (after first line)'
293 return HookFailure(msg)
294
Ryan Cuiec4d6332011-05-02 14:15:25 -0700295
296def _check_change_has_bug_field(project, commit):
David McMahon8f6553e2011-06-10 15:46:36 -0700297 """Check for a correctly formatted 'BUG=' field in the commit message."""
Daniel Erat1f064642012-01-10 09:48:20 -0800298 BUG_RE = r'\nBUG=([Nn]one|(chrome-os-partner|chromium|chromium-os):\d+)'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700299
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700300 if not re.search(BUG_RE, _get_commit_desc(commit)):
David McMahon8f6553e2011-06-10 15:46:36 -0700301 msg = ('Changelist description needs BUG field (after first line):\n'
Daniel Erat1f064642012-01-10 09:48:20 -0800302 'BUG=chromium-os:9999 (for public tracker)\n'
David McMahon8f6553e2011-06-10 15:46:36 -0700303 'BUG=chrome-os-partner:9999 (for partner tracker)\n'
Daniel Erat1f064642012-01-10 09:48:20 -0800304 'BUG=chromium:9999 (for browser tracker)\n'
David McMahon8f6553e2011-06-10 15:46:36 -0700305 'BUG=None')
Ryan Cui1562fb82011-05-09 11:01:31 -0700306 return HookFailure(msg)
307
Ryan Cuiec4d6332011-05-02 14:15:25 -0700308
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700309def _check_change_has_proper_changeid(project, commit):
310 """Verify that Change-ID is present in last paragraph of commit message."""
311 desc = _get_commit_desc(commit)
312 loc = desc.rfind('\nChange-Id:')
313 if loc == -1 or re.search('\n\s*\n\s*\S+', desc[loc:]):
Ryan Cui1562fb82011-05-09 11:01:31 -0700314 return HookFailure('Change-Id must be in last paragraph of description.')
315
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700316
Ryan Cuiec4d6332011-05-02 14:15:25 -0700317def _check_license(project, commit):
318 """Verifies the license header."""
319 LICENSE_HEADER = (
David James28766e62012-08-06 17:30:15 -0700320 r".*? Copyright \(c\) 20[-0-9]{2,7} The Chromium OS Authors\. All rights "
Ryan Cuiec4d6332011-05-02 14:15:25 -0700321 r"reserved\." "\n"
322 r".*? Use of this source code is governed by a BSD-style license that can "
323 "be\n"
324 r".*? found in the LICENSE file\."
325 "\n"
326 )
327
328 license_re = re.compile(LICENSE_HEADER, re.MULTILINE)
329 bad_files = []
330 files = _filter_files(_get_affected_files(commit),
331 COMMON_INCLUDED_PATHS,
332 COMMON_EXCLUDED_PATHS)
333
334 for f in files:
335 contents = open(f).read()
336 if len(contents) == 0: continue # Ignore empty files
337 if not license_re.search(contents):
338 bad_files.append(f)
339 if bad_files:
Ryan Cui1562fb82011-05-09 11:01:31 -0700340 return HookFailure('License must match:\n%s\n' % license_re.pattern +
341 'Found a bad license header in these files:',
342 bad_files)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700343
344
345# Project-specific hooks
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700346
Ryan Cui1562fb82011-05-09 11:01:31 -0700347
Anton Staaf815d6852011-08-22 10:08:45 -0700348def _run_checkpatch(project, commit, options=[]):
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700349 """Runs checkpatch.pl on the given project"""
350 hooks_dir = _get_hooks_dir()
Anton Staaf815d6852011-08-22 10:08:45 -0700351 cmd = ['%s/checkpatch.pl' % hooks_dir] + options + ['-']
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700352 p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700353 output = p.communicate(_get_diff(commit))[0]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700354 if p.returncode:
Ryan Cui1562fb82011-05-09 11:01:31 -0700355 return HookFailure('checkpatch.pl errors/warnings\n\n' + output)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700356
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700357
Anton Staaf815d6852011-08-22 10:08:45 -0700358def _run_checkpatch_no_tree(project, commit):
359 return _run_checkpatch(project, commit, ['--no-tree'])
360
361
Dale Curtis2975c432011-05-03 17:25:20 -0700362def _run_json_check(project, commit):
363 """Checks that all JSON files are syntactically valid."""
Dale Curtisa039cfd2011-05-04 12:01:05 -0700364 for f in _filter_files(_get_affected_files(commit), [r'.*\.json']):
Dale Curtis2975c432011-05-03 17:25:20 -0700365 try:
366 json.load(open(f))
367 except Exception, e:
Ryan Cui1562fb82011-05-09 11:01:31 -0700368 return HookFailure('Invalid JSON in %s: %s' % (f, e))
Dale Curtis2975c432011-05-03 17:25:20 -0700369
370
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700371def _check_change_has_branch_field(project, commit):
372 """Check for a non-empty 'BRANCH=' field in the commit message."""
373 BRANCH_RE = r'\nBRANCH=\S+'
374
375 if not re.search(BRANCH_RE, _get_commit_desc(commit)):
376 msg = ('Changelist description needs BRANCH field (after first line)\n'
377 'E.g. BRANCH=none or BRANCH=link,snow')
378 return HookFailure(msg)
379
380
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700381# Base
382
Ryan Cui1562fb82011-05-09 11:01:31 -0700383
Ryan Cui9b651632011-05-11 11:38:58 -0700384# A list of hooks that are not project-specific
385_COMMON_HOOKS = [
386 _check_change_has_bug_field,
387 _check_change_has_test_field,
388 _check_change_has_proper_changeid,
389 _check_no_stray_whitespace,
390 _check_no_long_lines,
391 _check_license,
392 _check_no_tabs,
393]
Ryan Cuiec4d6332011-05-02 14:15:25 -0700394
Ryan Cui1562fb82011-05-09 11:01:31 -0700395
Ryan Cui9b651632011-05-11 11:38:58 -0700396# A dictionary of project-specific hooks(callbacks), indexed by project name.
397# dict[project] = [callback1, callback2]
398_PROJECT_SPECIFIC_HOOKS = {
Doug Anderson830216f2011-05-02 10:08:37 -0700399 "chromiumos/third_party/kernel": [_run_checkpatch],
400 "chromiumos/third_party/kernel-next": [_run_checkpatch],
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700401 "chromiumos/third_party/u-boot": [_run_checkpatch_no_tree,
402 _check_change_has_branch_field],
403 "chromiumos/platform/ec": [_run_checkpatch_no_tree,
404 _check_change_has_branch_field],
405 "chromeos/platform/ec-private": [_run_checkpatch_no_tree,
406 _check_change_has_branch_field],
407 "chromeos/third_party/coreboot": [_check_change_has_branch_field],
Puneet Kumar57b9c092012-08-14 18:58:29 -0700408 "chromeos/third_party/intel-framework": [_check_change_has_branch_field],
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700409 "chromiumos/platform/vboot_reference": [_check_change_has_branch_field],
410 "chromiumos/platform/mosys": [_check_change_has_branch_field],
411 "chromiumos/third_party/flashrom": [_check_change_has_branch_field],
Dale Curtis2975c432011-05-03 17:25:20 -0700412 "chromeos/autotest-tools": [_run_json_check],
Ryan Cui9b651632011-05-11 11:38:58 -0700413}
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700414
Ryan Cui1562fb82011-05-09 11:01:31 -0700415
Ryan Cui9b651632011-05-11 11:38:58 -0700416# A dictionary of flags (keys) that can appear in the config file, and the hook
417# that the flag disables (value)
418_DISABLE_FLAGS = {
419 'stray_whitespace_check': _check_no_stray_whitespace,
420 'long_line_check': _check_no_long_lines,
421 'cros_license_check': _check_license,
422 'tab_check': _check_no_tabs,
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700423 'branch_check': _check_change_has_branch_field,
Ryan Cui9b651632011-05-11 11:38:58 -0700424}
425
426
427def _get_disabled_hooks():
428 """Returns a set of hooks disabled by the current project's config file.
429
430 Expects to be called within the project root.
431 """
432 SECTION = 'Hook Overrides'
433 config = ConfigParser.RawConfigParser()
434 try:
435 config.read(_CONFIG_FILE)
436 flags = config.options(SECTION)
437 except ConfigParser.Error:
438 return set([])
439
440 disable_flags = []
441 for flag in flags:
442 try:
443 if not config.getboolean(SECTION, flag): disable_flags.append(flag)
444 except ValueError as e:
445 msg = "Error parsing flag \'%s\' in %s file - " % (flag, _CONFIG_FILE)
446 print msg + str(e)
447
448 disabled_keys = set(_DISABLE_FLAGS.iterkeys()).intersection(disable_flags)
449 return set([_DISABLE_FLAGS[key] for key in disabled_keys])
450
451
452def _get_project_hooks(project):
453 """Returns a list of hooks that need to be run for a project.
454
455 Expects to be called from within the project root.
456 """
457 disabled_hooks = _get_disabled_hooks()
458 hooks = [hook for hook in _COMMON_HOOKS if hook not in disabled_hooks]
459
460 if project in _PROJECT_SPECIFIC_HOOKS:
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700461 hooks.extend(hook for hook in _PROJECT_SPECIFIC_HOOKS[project]
462 if hook not in disabled_hooks)
Ryan Cui9b651632011-05-11 11:38:58 -0700463
464 return hooks
465
466
Doug Anderson44a644f2011-11-02 10:37:37 -0700467def _run_project_hooks(project, proj_dir=None):
Ryan Cui1562fb82011-05-09 11:01:31 -0700468 """For each project run its project specific hook from the hooks dictionary.
469
470 Args:
Doug Anderson44a644f2011-11-02 10:37:37 -0700471 project: The name of project to run hooks for.
472 proj_dir: If non-None, this is the directory the project is in. If None,
473 we'll ask repo.
Ryan Cui1562fb82011-05-09 11:01:31 -0700474
475 Returns:
476 Boolean value of whether any errors were ecountered while running the hooks.
477 """
Doug Anderson44a644f2011-11-02 10:37:37 -0700478 if proj_dir is None:
479 proj_dir = _run_command(['repo', 'forall', project, '-c', 'pwd']).strip()
480
Ryan Cuiec4d6332011-05-02 14:15:25 -0700481 pwd = os.getcwd()
482 # hooks assume they are run from the root of the project
483 os.chdir(proj_dir)
484
Ryan Cuifa55df52011-05-06 11:16:55 -0700485 try:
486 commit_list = _get_commits()
Don Garrettdba548a2011-05-05 15:17:14 -0700487 except VerifyException as e:
Ryan Cui1562fb82011-05-09 11:01:31 -0700488 PrintErrorForProject(project, HookFailure(str(e)))
489 os.chdir(pwd)
490 return True
Ryan Cuifa55df52011-05-06 11:16:55 -0700491
Ryan Cui9b651632011-05-11 11:38:58 -0700492 hooks = _get_project_hooks(project)
Ryan Cui1562fb82011-05-09 11:01:31 -0700493 error_found = False
Ryan Cuifa55df52011-05-06 11:16:55 -0700494 for commit in commit_list:
Ryan Cui1562fb82011-05-09 11:01:31 -0700495 error_list = []
Ryan Cui9b651632011-05-11 11:38:58 -0700496 for hook in hooks:
Ryan Cui1562fb82011-05-09 11:01:31 -0700497 hook_error = hook(project, commit)
498 if hook_error:
499 error_list.append(hook_error)
500 error_found = True
501 if error_list:
502 PrintErrorsForCommit(project, commit, _get_commit_desc(commit),
503 error_list)
Don Garrettdba548a2011-05-05 15:17:14 -0700504
Ryan Cuiec4d6332011-05-02 14:15:25 -0700505 os.chdir(pwd)
Ryan Cui1562fb82011-05-09 11:01:31 -0700506 return error_found
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700507
508# Main
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -0700509
Ryan Cui1562fb82011-05-09 11:01:31 -0700510
Anush Elangovan63afad72011-03-23 00:41:27 -0700511def main(project_list, **kwargs):
Doug Anderson06456632012-01-05 11:02:14 -0800512 """Main function invoked directly by repo.
513
514 This function will exit directly upon error so that repo doesn't print some
515 obscure error message.
516
517 Args:
518 project_list: List of projects to run on.
519 kwargs: Leave this here for forward-compatibility.
520 """
Ryan Cui1562fb82011-05-09 11:01:31 -0700521 found_error = False
522 for project in project_list:
Ryan Cui9b651632011-05-11 11:38:58 -0700523 if _run_project_hooks(project):
Ryan Cui1562fb82011-05-09 11:01:31 -0700524 found_error = True
525
526 if (found_error):
527 msg = ('Preupload failed due to errors in project(s). HINTS:\n'
Ryan Cui9b651632011-05-11 11:38:58 -0700528 '- To disable some source style checks, and for other hints, see '
529 '<checkout_dir>/src/repohooks/README\n'
530 '- To upload only current project, run \'repo upload .\'')
Ryan Cui1562fb82011-05-09 11:01:31 -0700531 print >> sys.stderr, msg
Don Garrettdba548a2011-05-05 15:17:14 -0700532 sys.exit(1)
Anush Elangovan63afad72011-03-23 00:41:27 -0700533
Ryan Cui1562fb82011-05-09 11:01:31 -0700534
Doug Anderson44a644f2011-11-02 10:37:37 -0700535def _identify_project(path):
536 """Identify the repo project associated with the given path.
537
538 Returns:
539 A string indicating what project is associated with the path passed in or
540 a blank string upon failure.
541 """
542 return _run_command(['repo', 'forall', '.', '-c', 'echo ${REPO_PROJECT}'],
543 stderr=subprocess.PIPE, cwd=path).strip()
544
545
546def direct_main(args, verbose=False):
547 """Run hooks directly (outside of the context of repo).
548
549 # Setup for doctests below.
550 # ...note that some tests assume that running pre-upload on this CWD is fine.
551 # TODO: Use mock and actually mock out _run_project_hooks() for tests.
552 >>> mydir = os.path.dirname(os.path.abspath(__file__))
553 >>> olddir = os.getcwd()
554
555 # OK to run w/ no arugments; will run with CWD.
556 >>> os.chdir(mydir)
557 >>> direct_main(['prog_name'], verbose=True)
558 Running hooks on chromiumos/repohooks
559 0
560 >>> os.chdir(olddir)
561
562 # Run specifying a dir
563 >>> direct_main(['prog_name', '--dir=%s' % mydir], verbose=True)
564 Running hooks on chromiumos/repohooks
565 0
566
567 # Not a problem to use a bogus project; we'll just get default settings.
568 >>> direct_main(['prog_name', '--dir=%s' % mydir, '--project=X'],verbose=True)
569 Running hooks on X
570 0
571
572 # Run with project but no dir
573 >>> os.chdir(mydir)
574 >>> direct_main(['prog_name', '--project=X'], verbose=True)
575 Running hooks on X
576 0
577 >>> os.chdir(olddir)
578
579 # Try with a non-git CWD
580 >>> os.chdir('/tmp')
581 >>> direct_main(['prog_name'])
582 Traceback (most recent call last):
583 ...
584 BadInvocation: The current directory is not part of a git project.
585
586 # Check various bad arguments...
587 >>> direct_main(['prog_name', 'bogus'])
588 Traceback (most recent call last):
589 ...
590 BadInvocation: Unexpected arguments: bogus
591 >>> direct_main(['prog_name', '--project=bogus', '--dir=bogusdir'])
592 Traceback (most recent call last):
593 ...
594 BadInvocation: Invalid dir: bogusdir
595 >>> direct_main(['prog_name', '--project=bogus', '--dir=/tmp'])
596 Traceback (most recent call last):
597 ...
598 BadInvocation: Not a git directory: /tmp
599
600 Args:
601 args: The value of sys.argv
602
603 Returns:
604 0 if no pre-upload failures, 1 if failures.
605
606 Raises:
607 BadInvocation: On some types of invocation errors.
608 """
609 desc = 'Run Chromium OS pre-upload hooks on changes compared to upstream.'
610 parser = optparse.OptionParser(description=desc)
611
612 parser.add_option('--dir', default=None,
613 help='The directory that the project lives in. If not '
614 'specified, use the git project root based on the cwd.')
615 parser.add_option('--project', default=None,
616 help='The project repo path; this can affect how the hooks '
617 'get run, since some hooks are project-specific. For '
618 'chromite this is chromiumos/chromite. If not specified, '
619 'the repo tool will be used to figure this out based on '
620 'the dir.')
621
622 opts, args = parser.parse_args(args[1:])
623
624 if args:
625 raise BadInvocation('Unexpected arguments: %s' % ' '.join(args))
626
627 # Check/normlaize git dir; if unspecified, we'll use the root of the git
628 # project from CWD
629 if opts.dir is None:
630 git_dir = _run_command(['git', 'rev-parse', '--git-dir'],
631 stderr=subprocess.PIPE).strip()
632 if not git_dir:
633 raise BadInvocation('The current directory is not part of a git project.')
634 opts.dir = os.path.dirname(os.path.abspath(git_dir))
635 elif not os.path.isdir(opts.dir):
636 raise BadInvocation('Invalid dir: %s' % opts.dir)
637 elif not os.path.isdir(os.path.join(opts.dir, '.git')):
638 raise BadInvocation('Not a git directory: %s' % opts.dir)
639
640 # Identify the project if it wasn't specified; this _requires_ the repo
641 # tool to be installed and for the project to be part of a repo checkout.
642 if not opts.project:
643 opts.project = _identify_project(opts.dir)
644 if not opts.project:
645 raise BadInvocation("Repo couldn't identify the project of %s" % opts.dir)
646
647 if verbose:
648 print "Running hooks on %s" % (opts.project)
649
650 found_error = _run_project_hooks(opts.project, proj_dir=opts.dir)
651 if found_error:
652 return 1
653 return 0
654
655
656def _test():
657 """Run any built-in tests."""
658 import doctest
659 doctest.testmod()
660
661
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -0700662if __name__ == '__main__':
Doug Anderson44a644f2011-11-02 10:37:37 -0700663 if sys.argv[1:2] == ["--test"]:
664 _test()
665 exit_code = 0
666 else:
667 prog_name = os.path.basename(sys.argv[0])
668 try:
669 exit_code = direct_main(sys.argv)
670 except BadInvocation, e:
671 print >>sys.stderr, "%s: %s" % (prog_name, str(e))
672 exit_code = 1
673 sys.exit(exit_code)