blob: b5215e3eadff2ae7e62a74b0f99817b6ed59bae5 [file] [log] [blame]
Doug Anderson44a644f2011-11-02 10:37:37 -07001#!/usr/bin/env python
David James28766e62012-08-06 17:30:15 -07002# Copyright (c) 2011 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
Ryan Cuiec4d6332011-05-02 14:15:25 -0700163def _get_file_diff(file, commit):
164 """Returns a list of (linenum, lines) tuples that the commit touched."""
Ryan Cui72834d12011-05-05 14:51:33 -0700165 output = _run_command(['git', 'show', '-p', '--no-ext-diff', commit, file])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700166
167 new_lines = []
168 line_num = 0
169 for line in output.splitlines():
170 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
171 if m:
172 line_num = int(m.groups(1)[0])
173 continue
174 if line.startswith('+') and not line.startswith('++'):
175 new_lines.append((line_num, line[1:]))
176 if not line.startswith('-'):
177 line_num += 1
178 return new_lines
179
Ryan Cui1562fb82011-05-09 11:01:31 -0700180
Ryan Cuiec4d6332011-05-02 14:15:25 -0700181def _get_affected_files(commit):
182 """Returns list of absolute filepaths that were modified/added."""
Ryan Cui72834d12011-05-05 14:51:33 -0700183 output = _run_command(['git', 'diff', '--name-status', commit + '^!'])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700184 files = []
185 for statusline in output.splitlines():
186 m = re.match('^(\w)+\t(.+)$', statusline.rstrip())
187 # Ignore deleted files, and return absolute paths of files
188 if (m.group(1)[0] != 'D'):
189 pwd = os.getcwd()
190 files.append(os.path.join(pwd, m.group(2)))
191 return files
192
Ryan Cui1562fb82011-05-09 11:01:31 -0700193
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700194def _get_commits():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700195 """Returns a list of commits for this review."""
Ryan Cui4725d952011-05-05 15:41:19 -0700196 cmd = ['git', 'log', '%s..' % _get_upstream_branch(), '--format=%H']
Ryan Cui72834d12011-05-05 14:51:33 -0700197 return _run_command(cmd).split()
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700198
Ryan Cui1562fb82011-05-09 11:01:31 -0700199
Ryan Cuiec4d6332011-05-02 14:15:25 -0700200def _get_commit_desc(commit):
201 """Returns the full commit message of a commit."""
Sean Paul23a2c582011-05-06 13:10:44 -0400202 return _run_command(['git', 'log', '--format=%s%n%n%b', commit + '^!'])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700203
204
205# Common Hooks
206
Ryan Cui1562fb82011-05-09 11:01:31 -0700207
Ryan Cuiec4d6332011-05-02 14:15:25 -0700208def _check_no_long_lines(project, commit):
209 """Checks that there aren't any lines longer than maxlen characters in any of
210 the text files to be submitted.
211 """
212 MAX_LEN = 80
213
214 errors = []
215 files = _filter_files(_get_affected_files(commit),
216 COMMON_INCLUDED_PATHS,
217 COMMON_EXCLUDED_PATHS)
218
219 for afile in files:
220 for line_num, line in _get_file_diff(afile, commit):
221 # Allow certain lines to exceed the maxlen rule.
222 if (len(line) > MAX_LEN and
223 not 'http://' in line and
224 not 'https://' in line and
225 not line.startswith('#define') and
226 not line.startswith('#include') and
227 not line.startswith('#import') and
228 not line.startswith('#pragma') and
229 not line.startswith('#if') and
230 not line.startswith('#endif')):
231 errors.append('%s, line %s, %s chars' % (afile, line_num, len(line)))
232 if len(errors) == 5: # Just show the first 5 errors.
233 break
234
235 if errors:
236 msg = 'Found lines longer than %s characters (first 5 shown):' % MAX_LEN
Ryan Cui1562fb82011-05-09 11:01:31 -0700237 return HookFailure(msg, errors)
238
Ryan Cuiec4d6332011-05-02 14:15:25 -0700239
240def _check_no_stray_whitespace(project, commit):
241 """Checks that there is no stray whitespace at source lines end."""
242 errors = []
243 files = _filter_files(_get_affected_files(commit),
244 COMMON_INCLUDED_PATHS,
245 COMMON_EXCLUDED_PATHS)
246
247 for afile in files:
248 for line_num, line in _get_file_diff(afile, commit):
249 if line.rstrip() != line:
250 errors.append('%s, line %s' % (afile, line_num))
251 if errors:
Ryan Cui1562fb82011-05-09 11:01:31 -0700252 return HookFailure('Found line ending with white space in:', errors)
253
Ryan Cuiec4d6332011-05-02 14:15:25 -0700254
255def _check_no_tabs(project, commit):
256 """Checks there are no unexpanded tabs."""
257 TAB_OK_PATHS = [
Ryan Cui31e0c172011-05-04 21:00:45 -0700258 r"/src/third_party/u-boot/",
Ryan Cuiec4d6332011-05-02 14:15:25 -0700259 r".*\.ebuild$",
260 r".*\.eclass$",
Elly Jones5ab34192011-11-15 14:57:06 -0500261 r".*/[M|m]akefile$",
262 r".*\.mk$"
Ryan Cuiec4d6332011-05-02 14:15:25 -0700263 ]
264
265 errors = []
266 files = _filter_files(_get_affected_files(commit),
267 COMMON_INCLUDED_PATHS,
268 COMMON_EXCLUDED_PATHS + TAB_OK_PATHS)
269
270 for afile in files:
271 for line_num, line in _get_file_diff(afile, commit):
272 if '\t' in line:
273 errors.append('%s, line %s' % (afile, line_num))
274 if errors:
Ryan Cui1562fb82011-05-09 11:01:31 -0700275 return HookFailure('Found a tab character in:', errors)
276
Ryan Cuiec4d6332011-05-02 14:15:25 -0700277
278def _check_change_has_test_field(project, commit):
279 """Check for a non-empty 'TEST=' field in the commit message."""
David McMahon8f6553e2011-06-10 15:46:36 -0700280 TEST_RE = r'\nTEST=\S+'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700281
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700282 if not re.search(TEST_RE, _get_commit_desc(commit)):
Ryan Cui1562fb82011-05-09 11:01:31 -0700283 msg = 'Changelist description needs TEST field (after first line)'
284 return HookFailure(msg)
285
Ryan Cuiec4d6332011-05-02 14:15:25 -0700286
287def _check_change_has_bug_field(project, commit):
David McMahon8f6553e2011-06-10 15:46:36 -0700288 """Check for a correctly formatted 'BUG=' field in the commit message."""
Daniel Erat1f064642012-01-10 09:48:20 -0800289 BUG_RE = r'\nBUG=([Nn]one|(chrome-os-partner|chromium|chromium-os):\d+)'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700290
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700291 if not re.search(BUG_RE, _get_commit_desc(commit)):
David McMahon8f6553e2011-06-10 15:46:36 -0700292 msg = ('Changelist description needs BUG field (after first line):\n'
Daniel Erat1f064642012-01-10 09:48:20 -0800293 'BUG=chromium-os:9999 (for public tracker)\n'
David McMahon8f6553e2011-06-10 15:46:36 -0700294 'BUG=chrome-os-partner:9999 (for partner tracker)\n'
Daniel Erat1f064642012-01-10 09:48:20 -0800295 'BUG=chromium:9999 (for browser tracker)\n'
David McMahon8f6553e2011-06-10 15:46:36 -0700296 'BUG=None')
Ryan Cui1562fb82011-05-09 11:01:31 -0700297 return HookFailure(msg)
298
Ryan Cuiec4d6332011-05-02 14:15:25 -0700299
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700300def _check_change_has_proper_changeid(project, commit):
301 """Verify that Change-ID is present in last paragraph of commit message."""
302 desc = _get_commit_desc(commit)
303 loc = desc.rfind('\nChange-Id:')
304 if loc == -1 or re.search('\n\s*\n\s*\S+', desc[loc:]):
Ryan Cui1562fb82011-05-09 11:01:31 -0700305 return HookFailure('Change-Id must be in last paragraph of description.')
306
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700307
Ryan Cuiec4d6332011-05-02 14:15:25 -0700308def _check_license(project, commit):
309 """Verifies the license header."""
310 LICENSE_HEADER = (
David James28766e62012-08-06 17:30:15 -0700311 r".*? Copyright \(c\) 20[-0-9]{2,7} The Chromium OS Authors\. All rights "
Ryan Cuiec4d6332011-05-02 14:15:25 -0700312 r"reserved\." "\n"
313 r".*? Use of this source code is governed by a BSD-style license that can "
314 "be\n"
315 r".*? found in the LICENSE file\."
316 "\n"
317 )
318
319 license_re = re.compile(LICENSE_HEADER, re.MULTILINE)
320 bad_files = []
321 files = _filter_files(_get_affected_files(commit),
322 COMMON_INCLUDED_PATHS,
323 COMMON_EXCLUDED_PATHS)
324
325 for f in files:
326 contents = open(f).read()
327 if len(contents) == 0: continue # Ignore empty files
328 if not license_re.search(contents):
329 bad_files.append(f)
330 if bad_files:
Ryan Cui1562fb82011-05-09 11:01:31 -0700331 return HookFailure('License must match:\n%s\n' % license_re.pattern +
332 'Found a bad license header in these files:',
333 bad_files)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700334
335
336# Project-specific hooks
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700337
Ryan Cui1562fb82011-05-09 11:01:31 -0700338
Anton Staaf815d6852011-08-22 10:08:45 -0700339def _run_checkpatch(project, commit, options=[]):
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700340 """Runs checkpatch.pl on the given project"""
341 hooks_dir = _get_hooks_dir()
Anton Staaf815d6852011-08-22 10:08:45 -0700342 cmd = ['%s/checkpatch.pl' % hooks_dir] + options + ['-']
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700343 p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700344 output = p.communicate(_get_diff(commit))[0]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700345 if p.returncode:
Ryan Cui1562fb82011-05-09 11:01:31 -0700346 return HookFailure('checkpatch.pl errors/warnings\n\n' + output)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700347
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700348
Anton Staaf815d6852011-08-22 10:08:45 -0700349def _run_checkpatch_no_tree(project, commit):
350 return _run_checkpatch(project, commit, ['--no-tree'])
351
352
Dale Curtis2975c432011-05-03 17:25:20 -0700353def _run_json_check(project, commit):
354 """Checks that all JSON files are syntactically valid."""
Dale Curtisa039cfd2011-05-04 12:01:05 -0700355 for f in _filter_files(_get_affected_files(commit), [r'.*\.json']):
Dale Curtis2975c432011-05-03 17:25:20 -0700356 try:
357 json.load(open(f))
358 except Exception, e:
Ryan Cui1562fb82011-05-09 11:01:31 -0700359 return HookFailure('Invalid JSON in %s: %s' % (f, e))
Dale Curtis2975c432011-05-03 17:25:20 -0700360
361
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700362def _check_change_has_branch_field(project, commit):
363 """Check for a non-empty 'BRANCH=' field in the commit message."""
364 BRANCH_RE = r'\nBRANCH=\S+'
365
366 if not re.search(BRANCH_RE, _get_commit_desc(commit)):
367 msg = ('Changelist description needs BRANCH field (after first line)\n'
368 'E.g. BRANCH=none or BRANCH=link,snow')
369 return HookFailure(msg)
370
371
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700372# Base
373
Ryan Cui1562fb82011-05-09 11:01:31 -0700374
Ryan Cui9b651632011-05-11 11:38:58 -0700375# A list of hooks that are not project-specific
376_COMMON_HOOKS = [
377 _check_change_has_bug_field,
378 _check_change_has_test_field,
379 _check_change_has_proper_changeid,
380 _check_no_stray_whitespace,
381 _check_no_long_lines,
382 _check_license,
383 _check_no_tabs,
384]
Ryan Cuiec4d6332011-05-02 14:15:25 -0700385
Ryan Cui1562fb82011-05-09 11:01:31 -0700386
Ryan Cui9b651632011-05-11 11:38:58 -0700387# A dictionary of project-specific hooks(callbacks), indexed by project name.
388# dict[project] = [callback1, callback2]
389_PROJECT_SPECIFIC_HOOKS = {
Doug Anderson830216f2011-05-02 10:08:37 -0700390 "chromiumos/third_party/kernel": [_run_checkpatch],
391 "chromiumos/third_party/kernel-next": [_run_checkpatch],
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700392 "chromiumos/third_party/u-boot": [_run_checkpatch_no_tree,
393 _check_change_has_branch_field],
394 "chromiumos/platform/ec": [_run_checkpatch_no_tree,
395 _check_change_has_branch_field],
396 "chromeos/platform/ec-private": [_run_checkpatch_no_tree,
397 _check_change_has_branch_field],
398 "chromeos/third_party/coreboot": [_check_change_has_branch_field],
399 "chromiumos/platform/vboot_reference": [_check_change_has_branch_field],
400 "chromiumos/platform/mosys": [_check_change_has_branch_field],
401 "chromiumos/third_party/flashrom": [_check_change_has_branch_field],
Dale Curtis2975c432011-05-03 17:25:20 -0700402 "chromeos/autotest-tools": [_run_json_check],
Ryan Cui9b651632011-05-11 11:38:58 -0700403}
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700404
Ryan Cui1562fb82011-05-09 11:01:31 -0700405
Ryan Cui9b651632011-05-11 11:38:58 -0700406# A dictionary of flags (keys) that can appear in the config file, and the hook
407# that the flag disables (value)
408_DISABLE_FLAGS = {
409 'stray_whitespace_check': _check_no_stray_whitespace,
410 'long_line_check': _check_no_long_lines,
411 'cros_license_check': _check_license,
412 'tab_check': _check_no_tabs,
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700413 'branch_check': _check_change_has_branch_field,
Ryan Cui9b651632011-05-11 11:38:58 -0700414}
415
416
417def _get_disabled_hooks():
418 """Returns a set of hooks disabled by the current project's config file.
419
420 Expects to be called within the project root.
421 """
422 SECTION = 'Hook Overrides'
423 config = ConfigParser.RawConfigParser()
424 try:
425 config.read(_CONFIG_FILE)
426 flags = config.options(SECTION)
427 except ConfigParser.Error:
428 return set([])
429
430 disable_flags = []
431 for flag in flags:
432 try:
433 if not config.getboolean(SECTION, flag): disable_flags.append(flag)
434 except ValueError as e:
435 msg = "Error parsing flag \'%s\' in %s file - " % (flag, _CONFIG_FILE)
436 print msg + str(e)
437
438 disabled_keys = set(_DISABLE_FLAGS.iterkeys()).intersection(disable_flags)
439 return set([_DISABLE_FLAGS[key] for key in disabled_keys])
440
441
442def _get_project_hooks(project):
443 """Returns a list of hooks that need to be run for a project.
444
445 Expects to be called from within the project root.
446 """
447 disabled_hooks = _get_disabled_hooks()
448 hooks = [hook for hook in _COMMON_HOOKS if hook not in disabled_hooks]
449
450 if project in _PROJECT_SPECIFIC_HOOKS:
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700451 hooks.extend(hook for hook in _PROJECT_SPECIFIC_HOOKS[project]
452 if hook not in disabled_hooks)
Ryan Cui9b651632011-05-11 11:38:58 -0700453
454 return hooks
455
456
Doug Anderson44a644f2011-11-02 10:37:37 -0700457def _run_project_hooks(project, proj_dir=None):
Ryan Cui1562fb82011-05-09 11:01:31 -0700458 """For each project run its project specific hook from the hooks dictionary.
459
460 Args:
Doug Anderson44a644f2011-11-02 10:37:37 -0700461 project: The name of project to run hooks for.
462 proj_dir: If non-None, this is the directory the project is in. If None,
463 we'll ask repo.
Ryan Cui1562fb82011-05-09 11:01:31 -0700464
465 Returns:
466 Boolean value of whether any errors were ecountered while running the hooks.
467 """
Doug Anderson44a644f2011-11-02 10:37:37 -0700468 if proj_dir is None:
469 proj_dir = _run_command(['repo', 'forall', project, '-c', 'pwd']).strip()
470
Ryan Cuiec4d6332011-05-02 14:15:25 -0700471 pwd = os.getcwd()
472 # hooks assume they are run from the root of the project
473 os.chdir(proj_dir)
474
Ryan Cuifa55df52011-05-06 11:16:55 -0700475 try:
476 commit_list = _get_commits()
Don Garrettdba548a2011-05-05 15:17:14 -0700477 except VerifyException as e:
Ryan Cui1562fb82011-05-09 11:01:31 -0700478 PrintErrorForProject(project, HookFailure(str(e)))
479 os.chdir(pwd)
480 return True
Ryan Cuifa55df52011-05-06 11:16:55 -0700481
Ryan Cui9b651632011-05-11 11:38:58 -0700482 hooks = _get_project_hooks(project)
Ryan Cui1562fb82011-05-09 11:01:31 -0700483 error_found = False
Ryan Cuifa55df52011-05-06 11:16:55 -0700484 for commit in commit_list:
Ryan Cui1562fb82011-05-09 11:01:31 -0700485 error_list = []
Ryan Cui9b651632011-05-11 11:38:58 -0700486 for hook in hooks:
Ryan Cui1562fb82011-05-09 11:01:31 -0700487 hook_error = hook(project, commit)
488 if hook_error:
489 error_list.append(hook_error)
490 error_found = True
491 if error_list:
492 PrintErrorsForCommit(project, commit, _get_commit_desc(commit),
493 error_list)
Don Garrettdba548a2011-05-05 15:17:14 -0700494
Ryan Cuiec4d6332011-05-02 14:15:25 -0700495 os.chdir(pwd)
Ryan Cui1562fb82011-05-09 11:01:31 -0700496 return error_found
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700497
498# Main
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -0700499
Ryan Cui1562fb82011-05-09 11:01:31 -0700500
Anush Elangovan63afad72011-03-23 00:41:27 -0700501def main(project_list, **kwargs):
Doug Anderson06456632012-01-05 11:02:14 -0800502 """Main function invoked directly by repo.
503
504 This function will exit directly upon error so that repo doesn't print some
505 obscure error message.
506
507 Args:
508 project_list: List of projects to run on.
509 kwargs: Leave this here for forward-compatibility.
510 """
Ryan Cui1562fb82011-05-09 11:01:31 -0700511 found_error = False
512 for project in project_list:
Ryan Cui9b651632011-05-11 11:38:58 -0700513 if _run_project_hooks(project):
Ryan Cui1562fb82011-05-09 11:01:31 -0700514 found_error = True
515
516 if (found_error):
517 msg = ('Preupload failed due to errors in project(s). HINTS:\n'
Ryan Cui9b651632011-05-11 11:38:58 -0700518 '- To disable some source style checks, and for other hints, see '
519 '<checkout_dir>/src/repohooks/README\n'
520 '- To upload only current project, run \'repo upload .\'')
Ryan Cui1562fb82011-05-09 11:01:31 -0700521 print >> sys.stderr, msg
Don Garrettdba548a2011-05-05 15:17:14 -0700522 sys.exit(1)
Anush Elangovan63afad72011-03-23 00:41:27 -0700523
Ryan Cui1562fb82011-05-09 11:01:31 -0700524
Doug Anderson44a644f2011-11-02 10:37:37 -0700525def _identify_project(path):
526 """Identify the repo project associated with the given path.
527
528 Returns:
529 A string indicating what project is associated with the path passed in or
530 a blank string upon failure.
531 """
532 return _run_command(['repo', 'forall', '.', '-c', 'echo ${REPO_PROJECT}'],
533 stderr=subprocess.PIPE, cwd=path).strip()
534
535
536def direct_main(args, verbose=False):
537 """Run hooks directly (outside of the context of repo).
538
539 # Setup for doctests below.
540 # ...note that some tests assume that running pre-upload on this CWD is fine.
541 # TODO: Use mock and actually mock out _run_project_hooks() for tests.
542 >>> mydir = os.path.dirname(os.path.abspath(__file__))
543 >>> olddir = os.getcwd()
544
545 # OK to run w/ no arugments; will run with CWD.
546 >>> os.chdir(mydir)
547 >>> direct_main(['prog_name'], verbose=True)
548 Running hooks on chromiumos/repohooks
549 0
550 >>> os.chdir(olddir)
551
552 # Run specifying a dir
553 >>> direct_main(['prog_name', '--dir=%s' % mydir], verbose=True)
554 Running hooks on chromiumos/repohooks
555 0
556
557 # Not a problem to use a bogus project; we'll just get default settings.
558 >>> direct_main(['prog_name', '--dir=%s' % mydir, '--project=X'],verbose=True)
559 Running hooks on X
560 0
561
562 # Run with project but no dir
563 >>> os.chdir(mydir)
564 >>> direct_main(['prog_name', '--project=X'], verbose=True)
565 Running hooks on X
566 0
567 >>> os.chdir(olddir)
568
569 # Try with a non-git CWD
570 >>> os.chdir('/tmp')
571 >>> direct_main(['prog_name'])
572 Traceback (most recent call last):
573 ...
574 BadInvocation: The current directory is not part of a git project.
575
576 # Check various bad arguments...
577 >>> direct_main(['prog_name', 'bogus'])
578 Traceback (most recent call last):
579 ...
580 BadInvocation: Unexpected arguments: bogus
581 >>> direct_main(['prog_name', '--project=bogus', '--dir=bogusdir'])
582 Traceback (most recent call last):
583 ...
584 BadInvocation: Invalid dir: bogusdir
585 >>> direct_main(['prog_name', '--project=bogus', '--dir=/tmp'])
586 Traceback (most recent call last):
587 ...
588 BadInvocation: Not a git directory: /tmp
589
590 Args:
591 args: The value of sys.argv
592
593 Returns:
594 0 if no pre-upload failures, 1 if failures.
595
596 Raises:
597 BadInvocation: On some types of invocation errors.
598 """
599 desc = 'Run Chromium OS pre-upload hooks on changes compared to upstream.'
600 parser = optparse.OptionParser(description=desc)
601
602 parser.add_option('--dir', default=None,
603 help='The directory that the project lives in. If not '
604 'specified, use the git project root based on the cwd.')
605 parser.add_option('--project', default=None,
606 help='The project repo path; this can affect how the hooks '
607 'get run, since some hooks are project-specific. For '
608 'chromite this is chromiumos/chromite. If not specified, '
609 'the repo tool will be used to figure this out based on '
610 'the dir.')
611
612 opts, args = parser.parse_args(args[1:])
613
614 if args:
615 raise BadInvocation('Unexpected arguments: %s' % ' '.join(args))
616
617 # Check/normlaize git dir; if unspecified, we'll use the root of the git
618 # project from CWD
619 if opts.dir is None:
620 git_dir = _run_command(['git', 'rev-parse', '--git-dir'],
621 stderr=subprocess.PIPE).strip()
622 if not git_dir:
623 raise BadInvocation('The current directory is not part of a git project.')
624 opts.dir = os.path.dirname(os.path.abspath(git_dir))
625 elif not os.path.isdir(opts.dir):
626 raise BadInvocation('Invalid dir: %s' % opts.dir)
627 elif not os.path.isdir(os.path.join(opts.dir, '.git')):
628 raise BadInvocation('Not a git directory: %s' % opts.dir)
629
630 # Identify the project if it wasn't specified; this _requires_ the repo
631 # tool to be installed and for the project to be part of a repo checkout.
632 if not opts.project:
633 opts.project = _identify_project(opts.dir)
634 if not opts.project:
635 raise BadInvocation("Repo couldn't identify the project of %s" % opts.dir)
636
637 if verbose:
638 print "Running hooks on %s" % (opts.project)
639
640 found_error = _run_project_hooks(opts.project, proj_dir=opts.dir)
641 if found_error:
642 return 1
643 return 0
644
645
646def _test():
647 """Run any built-in tests."""
648 import doctest
649 doctest.testmod()
650
651
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -0700652if __name__ == '__main__':
Doug Anderson44a644f2011-11-02 10:37:37 -0700653 if sys.argv[1:2] == ["--test"]:
654 _test()
655 exit_code = 0
656 else:
657 prog_name = os.path.basename(sys.argv[0])
658 try:
659 exit_code = direct_main(sys.argv)
660 except BadInvocation, e:
661 print >>sys.stderr, "%s: %s" % (prog_name, str(e))
662 exit_code = 1
663 sys.exit(exit_code)