blob: f730563584e03a5865c0853104cab3a88c4e6c1e [file] [log] [blame]
Doug Anderson44a644f2011-11-02 10:37:37 -07001#!/usr/bin/env python
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07002# Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
3# 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/.*",
Ryan Cuiec4d6332011-05-02 14:15:25 -070047]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070048
Ryan Cui1562fb82011-05-09 11:01:31 -070049
Ryan Cui9b651632011-05-11 11:38:58 -070050_CONFIG_FILE = 'PRESUBMIT.cfg'
51
52
Doug Anderson44a644f2011-11-02 10:37:37 -070053# Exceptions
54
55
56class BadInvocation(Exception):
57 """An Exception indicating a bad invocation of the program."""
58 pass
59
60
Ryan Cui1562fb82011-05-09 11:01:31 -070061# General Helpers
62
Sean Paulba01d402011-05-05 11:36:23 -040063
Doug Anderson44a644f2011-11-02 10:37:37 -070064def _run_command(cmd, cwd=None, stderr=None):
65 """Executes the passed in command and returns raw stdout output.
66
67 Args:
68 cmd: The command to run; should be a list of strings.
69 cwd: The directory to switch to for running the command.
70 stderr: Can be one of None (print stderr to console), subprocess.STDOUT
71 (combine stderr with stdout), or subprocess.PIPE (ignore stderr).
72
73 Returns:
74 The standard out from the process.
75 """
76 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=stderr, cwd=cwd)
77 return p.communicate()[0]
Ryan Cui72834d12011-05-05 14:51:33 -070078
Ryan Cui1562fb82011-05-09 11:01:31 -070079
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070080def _get_hooks_dir():
Ryan Cuiec4d6332011-05-02 14:15:25 -070081 """Returns the absolute path to the repohooks directory."""
Doug Anderson44a644f2011-11-02 10:37:37 -070082 if __name__ == '__main__':
83 # Works when file is run on its own (__file__ is defined)...
84 return os.path.abspath(os.path.dirname(__file__))
85 else:
86 # We need to do this when we're run through repo. Since repo executes
87 # us with execfile(), we don't get __file__ defined.
88 cmd = ['repo', 'forall', 'chromiumos/repohooks', '-c', 'pwd']
89 return _run_command(cmd).strip()
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070090
Ryan Cui1562fb82011-05-09 11:01:31 -070091
Ryan Cuiec4d6332011-05-02 14:15:25 -070092def _match_regex_list(subject, expressions):
93 """Try to match a list of regular expressions to a string.
94
95 Args:
96 subject: The string to match regexes on
97 expressions: A list of regular expressions to check for matches with.
98
99 Returns:
100 Whether the passed in subject matches any of the passed in regexes.
101 """
102 for expr in expressions:
103 if (re.search(expr, subject)):
104 return True
105 return False
106
Ryan Cui1562fb82011-05-09 11:01:31 -0700107
Ryan Cuiec4d6332011-05-02 14:15:25 -0700108def _filter_files(files, include_list, exclude_list=[]):
109 """Filter out files based on the conditions passed in.
110
111 Args:
112 files: list of filepaths to filter
113 include_list: list of regex that when matched with a file path will cause it
114 to be added to the output list unless the file is also matched with a
115 regex in the exclude_list.
116 exclude_list: list of regex that when matched with a file will prevent it
117 from being added to the output list, even if it is also matched with a
118 regex in the include_list.
119
120 Returns:
121 A list of filepaths that contain files matched in the include_list and not
122 in the exclude_list.
123 """
124 filtered = []
125 for f in files:
126 if (_match_regex_list(f, include_list) and
127 not _match_regex_list(f, exclude_list)):
128 filtered.append(f)
129 return filtered
130
Ryan Cuiec4d6332011-05-02 14:15:25 -0700131
132# Git Helpers
Ryan Cui1562fb82011-05-09 11:01:31 -0700133
134
Ryan Cui4725d952011-05-05 15:41:19 -0700135def _get_upstream_branch():
136 """Returns the upstream tracking branch of the current branch.
137
138 Raises:
139 Error if there is no tracking branch
140 """
141 current_branch = _run_command(['git', 'symbolic-ref', 'HEAD']).strip()
142 current_branch = current_branch.replace('refs/heads/', '')
143 if not current_branch:
Ryan Cui1562fb82011-05-09 11:01:31 -0700144 raise VerifyException('Need to be on a tracking branch')
Ryan Cui4725d952011-05-05 15:41:19 -0700145
146 cfg_option = 'branch.' + current_branch + '.%s'
147 full_upstream = _run_command(['git', 'config', cfg_option % 'merge']).strip()
148 remote = _run_command(['git', 'config', cfg_option % 'remote']).strip()
149 if not remote or not full_upstream:
Ryan Cui1562fb82011-05-09 11:01:31 -0700150 raise VerifyException('Need to be on a tracking branch')
Ryan Cui4725d952011-05-05 15:41:19 -0700151
152 return full_upstream.replace('heads', 'remotes/' + remote)
153
Ryan Cui1562fb82011-05-09 11:01:31 -0700154
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700155def _get_diff(commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700156 """Returns the diff for this commit."""
Ryan Cui72834d12011-05-05 14:51:33 -0700157 return _run_command(['git', 'show', commit])
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700158
Ryan Cui1562fb82011-05-09 11:01:31 -0700159
Ryan Cuiec4d6332011-05-02 14:15:25 -0700160def _get_file_diff(file, commit):
161 """Returns a list of (linenum, lines) tuples that the commit touched."""
Ryan Cui72834d12011-05-05 14:51:33 -0700162 output = _run_command(['git', 'show', '-p', '--no-ext-diff', commit, file])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700163
164 new_lines = []
165 line_num = 0
166 for line in output.splitlines():
167 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
168 if m:
169 line_num = int(m.groups(1)[0])
170 continue
171 if line.startswith('+') and not line.startswith('++'):
172 new_lines.append((line_num, line[1:]))
173 if not line.startswith('-'):
174 line_num += 1
175 return new_lines
176
Ryan Cui1562fb82011-05-09 11:01:31 -0700177
Ryan Cuiec4d6332011-05-02 14:15:25 -0700178def _get_affected_files(commit):
179 """Returns list of absolute filepaths that were modified/added."""
Ryan Cui72834d12011-05-05 14:51:33 -0700180 output = _run_command(['git', 'diff', '--name-status', commit + '^!'])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700181 files = []
182 for statusline in output.splitlines():
183 m = re.match('^(\w)+\t(.+)$', statusline.rstrip())
184 # Ignore deleted files, and return absolute paths of files
185 if (m.group(1)[0] != 'D'):
186 pwd = os.getcwd()
187 files.append(os.path.join(pwd, m.group(2)))
188 return files
189
Ryan Cui1562fb82011-05-09 11:01:31 -0700190
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700191def _get_commits():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700192 """Returns a list of commits for this review."""
Ryan Cui4725d952011-05-05 15:41:19 -0700193 cmd = ['git', 'log', '%s..' % _get_upstream_branch(), '--format=%H']
Ryan Cui72834d12011-05-05 14:51:33 -0700194 return _run_command(cmd).split()
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700195
Ryan Cui1562fb82011-05-09 11:01:31 -0700196
Ryan Cuiec4d6332011-05-02 14:15:25 -0700197def _get_commit_desc(commit):
198 """Returns the full commit message of a commit."""
Sean Paul23a2c582011-05-06 13:10:44 -0400199 return _run_command(['git', 'log', '--format=%s%n%n%b', commit + '^!'])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700200
201
202# Common Hooks
203
Ryan Cui1562fb82011-05-09 11:01:31 -0700204
Ryan Cuiec4d6332011-05-02 14:15:25 -0700205def _check_no_long_lines(project, commit):
206 """Checks that there aren't any lines longer than maxlen characters in any of
207 the text files to be submitted.
208 """
209 MAX_LEN = 80
210
211 errors = []
212 files = _filter_files(_get_affected_files(commit),
213 COMMON_INCLUDED_PATHS,
214 COMMON_EXCLUDED_PATHS)
215
216 for afile in files:
217 for line_num, line in _get_file_diff(afile, commit):
218 # Allow certain lines to exceed the maxlen rule.
219 if (len(line) > MAX_LEN and
220 not 'http://' in line and
221 not 'https://' in line and
222 not line.startswith('#define') and
223 not line.startswith('#include') and
224 not line.startswith('#import') and
225 not line.startswith('#pragma') and
226 not line.startswith('#if') and
227 not line.startswith('#endif')):
228 errors.append('%s, line %s, %s chars' % (afile, line_num, len(line)))
229 if len(errors) == 5: # Just show the first 5 errors.
230 break
231
232 if errors:
233 msg = 'Found lines longer than %s characters (first 5 shown):' % MAX_LEN
Ryan Cui1562fb82011-05-09 11:01:31 -0700234 return HookFailure(msg, errors)
235
Ryan Cuiec4d6332011-05-02 14:15:25 -0700236
237def _check_no_stray_whitespace(project, commit):
238 """Checks that there is no stray whitespace at source lines end."""
239 errors = []
240 files = _filter_files(_get_affected_files(commit),
241 COMMON_INCLUDED_PATHS,
242 COMMON_EXCLUDED_PATHS)
243
244 for afile in files:
245 for line_num, line in _get_file_diff(afile, commit):
246 if line.rstrip() != line:
247 errors.append('%s, line %s' % (afile, line_num))
248 if errors:
Ryan Cui1562fb82011-05-09 11:01:31 -0700249 return HookFailure('Found line ending with white space in:', errors)
250
Ryan Cuiec4d6332011-05-02 14:15:25 -0700251
252def _check_no_tabs(project, commit):
253 """Checks there are no unexpanded tabs."""
254 TAB_OK_PATHS = [
Ryan Cui31e0c172011-05-04 21:00:45 -0700255 r"/src/third_party/u-boot/",
Ryan Cuiec4d6332011-05-02 14:15:25 -0700256 r".*\.ebuild$",
257 r".*\.eclass$",
Elly Jones5ab34192011-11-15 14:57:06 -0500258 r".*/[M|m]akefile$",
259 r".*\.mk$"
Ryan Cuiec4d6332011-05-02 14:15:25 -0700260 ]
261
262 errors = []
263 files = _filter_files(_get_affected_files(commit),
264 COMMON_INCLUDED_PATHS,
265 COMMON_EXCLUDED_PATHS + TAB_OK_PATHS)
266
267 for afile in files:
268 for line_num, line in _get_file_diff(afile, commit):
269 if '\t' in line:
270 errors.append('%s, line %s' % (afile, line_num))
271 if errors:
Ryan Cui1562fb82011-05-09 11:01:31 -0700272 return HookFailure('Found a tab character in:', errors)
273
Ryan Cuiec4d6332011-05-02 14:15:25 -0700274
275def _check_change_has_test_field(project, commit):
276 """Check for a non-empty 'TEST=' field in the commit message."""
David McMahon8f6553e2011-06-10 15:46:36 -0700277 TEST_RE = r'\nTEST=\S+'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700278
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700279 if not re.search(TEST_RE, _get_commit_desc(commit)):
Ryan Cui1562fb82011-05-09 11:01:31 -0700280 msg = 'Changelist description needs TEST field (after first line)'
281 return HookFailure(msg)
282
Ryan Cuiec4d6332011-05-02 14:15:25 -0700283
284def _check_change_has_bug_field(project, commit):
David McMahon8f6553e2011-06-10 15:46:36 -0700285 """Check for a correctly formatted 'BUG=' field in the commit message."""
286 BUG_RE = r'\nBUG=([Nn]one|(chrome-os-partner|chromium-os):\d+)'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700287
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700288 if not re.search(BUG_RE, _get_commit_desc(commit)):
David McMahon8f6553e2011-06-10 15:46:36 -0700289 msg = ('Changelist description needs BUG field (after first line):\n'
290 'BUG=chromium-os:99999 (for public tracker)\n'
291 'BUG=chrome-os-partner:9999 (for partner tracker)\n'
292 'BUG=None')
Ryan Cui1562fb82011-05-09 11:01:31 -0700293 return HookFailure(msg)
294
Ryan Cuiec4d6332011-05-02 14:15:25 -0700295
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700296def _check_change_has_proper_changeid(project, commit):
297 """Verify that Change-ID is present in last paragraph of commit message."""
298 desc = _get_commit_desc(commit)
299 loc = desc.rfind('\nChange-Id:')
300 if loc == -1 or re.search('\n\s*\n\s*\S+', desc[loc:]):
Ryan Cui1562fb82011-05-09 11:01:31 -0700301 return HookFailure('Change-Id must be in last paragraph of description.')
302
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700303
Ryan Cuiec4d6332011-05-02 14:15:25 -0700304def _check_license(project, commit):
305 """Verifies the license header."""
306 LICENSE_HEADER = (
307 r".*? Copyright \(c\) 20[-0-9]{2,7} The Chromium OS Authors\. All rights "
308 r"reserved\." "\n"
309 r".*? Use of this source code is governed by a BSD-style license that can "
310 "be\n"
311 r".*? found in the LICENSE file\."
312 "\n"
313 )
314
315 license_re = re.compile(LICENSE_HEADER, re.MULTILINE)
316 bad_files = []
317 files = _filter_files(_get_affected_files(commit),
318 COMMON_INCLUDED_PATHS,
319 COMMON_EXCLUDED_PATHS)
320
321 for f in files:
322 contents = open(f).read()
323 if len(contents) == 0: continue # Ignore empty files
324 if not license_re.search(contents):
325 bad_files.append(f)
326 if bad_files:
Ryan Cui1562fb82011-05-09 11:01:31 -0700327 return HookFailure('License must match:\n%s\n' % license_re.pattern +
328 'Found a bad license header in these files:',
329 bad_files)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700330
331
332# Project-specific hooks
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700333
Ryan Cui1562fb82011-05-09 11:01:31 -0700334
Anton Staaf815d6852011-08-22 10:08:45 -0700335def _run_checkpatch(project, commit, options=[]):
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700336 """Runs checkpatch.pl on the given project"""
337 hooks_dir = _get_hooks_dir()
Anton Staaf815d6852011-08-22 10:08:45 -0700338 cmd = ['%s/checkpatch.pl' % hooks_dir] + options + ['-']
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700339 p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700340 output = p.communicate(_get_diff(commit))[0]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700341 if p.returncode:
Ryan Cui1562fb82011-05-09 11:01:31 -0700342 return HookFailure('checkpatch.pl errors/warnings\n\n' + output)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700343
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700344
Anton Staaf815d6852011-08-22 10:08:45 -0700345def _run_checkpatch_no_tree(project, commit):
346 return _run_checkpatch(project, commit, ['--no-tree'])
347
348
Dale Curtis2975c432011-05-03 17:25:20 -0700349def _run_json_check(project, commit):
350 """Checks that all JSON files are syntactically valid."""
Dale Curtisa039cfd2011-05-04 12:01:05 -0700351 for f in _filter_files(_get_affected_files(commit), [r'.*\.json']):
Dale Curtis2975c432011-05-03 17:25:20 -0700352 try:
353 json.load(open(f))
354 except Exception, e:
Ryan Cui1562fb82011-05-09 11:01:31 -0700355 return HookFailure('Invalid JSON in %s: %s' % (f, e))
Dale Curtis2975c432011-05-03 17:25:20 -0700356
357
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700358# Base
359
Ryan Cui1562fb82011-05-09 11:01:31 -0700360
Ryan Cui9b651632011-05-11 11:38:58 -0700361# A list of hooks that are not project-specific
362_COMMON_HOOKS = [
363 _check_change_has_bug_field,
364 _check_change_has_test_field,
365 _check_change_has_proper_changeid,
366 _check_no_stray_whitespace,
367 _check_no_long_lines,
368 _check_license,
369 _check_no_tabs,
370]
Ryan Cuiec4d6332011-05-02 14:15:25 -0700371
Ryan Cui1562fb82011-05-09 11:01:31 -0700372
Ryan Cui9b651632011-05-11 11:38:58 -0700373# A dictionary of project-specific hooks(callbacks), indexed by project name.
374# dict[project] = [callback1, callback2]
375_PROJECT_SPECIFIC_HOOKS = {
Doug Anderson830216f2011-05-02 10:08:37 -0700376 "chromiumos/third_party/kernel": [_run_checkpatch],
377 "chromiumos/third_party/kernel-next": [_run_checkpatch],
Anton Staaf815d6852011-08-22 10:08:45 -0700378 "chromiumos/third_party/u-boot": [_run_checkpatch_no_tree],
Che-Liang Chiou1eb0ab62011-10-20 16:14:38 +0800379 "chromiumos/platform/u-boot-vboot-integration": [_run_checkpatch_no_tree],
Vincent Palatin0162e722011-12-07 23:57:47 +0000380 "chromeos/vendor/ec-internal/blizzard": [_run_checkpatch_no_tree],
Dale Curtis2975c432011-05-03 17:25:20 -0700381 "chromeos/autotest-tools": [_run_json_check],
Ryan Cui9b651632011-05-11 11:38:58 -0700382}
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700383
Ryan Cui1562fb82011-05-09 11:01:31 -0700384
Ryan Cui9b651632011-05-11 11:38:58 -0700385# A dictionary of flags (keys) that can appear in the config file, and the hook
386# that the flag disables (value)
387_DISABLE_FLAGS = {
388 'stray_whitespace_check': _check_no_stray_whitespace,
389 'long_line_check': _check_no_long_lines,
390 'cros_license_check': _check_license,
391 'tab_check': _check_no_tabs,
392}
393
394
395def _get_disabled_hooks():
396 """Returns a set of hooks disabled by the current project's config file.
397
398 Expects to be called within the project root.
399 """
400 SECTION = 'Hook Overrides'
401 config = ConfigParser.RawConfigParser()
402 try:
403 config.read(_CONFIG_FILE)
404 flags = config.options(SECTION)
405 except ConfigParser.Error:
406 return set([])
407
408 disable_flags = []
409 for flag in flags:
410 try:
411 if not config.getboolean(SECTION, flag): disable_flags.append(flag)
412 except ValueError as e:
413 msg = "Error parsing flag \'%s\' in %s file - " % (flag, _CONFIG_FILE)
414 print msg + str(e)
415
416 disabled_keys = set(_DISABLE_FLAGS.iterkeys()).intersection(disable_flags)
417 return set([_DISABLE_FLAGS[key] for key in disabled_keys])
418
419
420def _get_project_hooks(project):
421 """Returns a list of hooks that need to be run for a project.
422
423 Expects to be called from within the project root.
424 """
425 disabled_hooks = _get_disabled_hooks()
426 hooks = [hook for hook in _COMMON_HOOKS if hook not in disabled_hooks]
427
428 if project in _PROJECT_SPECIFIC_HOOKS:
429 hooks.extend(_PROJECT_SPECIFIC_HOOKS[project])
430
431 return hooks
432
433
Doug Anderson44a644f2011-11-02 10:37:37 -0700434def _run_project_hooks(project, proj_dir=None):
Ryan Cui1562fb82011-05-09 11:01:31 -0700435 """For each project run its project specific hook from the hooks dictionary.
436
437 Args:
Doug Anderson44a644f2011-11-02 10:37:37 -0700438 project: The name of project to run hooks for.
439 proj_dir: If non-None, this is the directory the project is in. If None,
440 we'll ask repo.
Ryan Cui1562fb82011-05-09 11:01:31 -0700441
442 Returns:
443 Boolean value of whether any errors were ecountered while running the hooks.
444 """
Doug Anderson44a644f2011-11-02 10:37:37 -0700445 if proj_dir is None:
446 proj_dir = _run_command(['repo', 'forall', project, '-c', 'pwd']).strip()
447
Ryan Cuiec4d6332011-05-02 14:15:25 -0700448 pwd = os.getcwd()
449 # hooks assume they are run from the root of the project
450 os.chdir(proj_dir)
451
Ryan Cuifa55df52011-05-06 11:16:55 -0700452 try:
453 commit_list = _get_commits()
Don Garrettdba548a2011-05-05 15:17:14 -0700454 except VerifyException as e:
Ryan Cui1562fb82011-05-09 11:01:31 -0700455 PrintErrorForProject(project, HookFailure(str(e)))
456 os.chdir(pwd)
457 return True
Ryan Cuifa55df52011-05-06 11:16:55 -0700458
Ryan Cui9b651632011-05-11 11:38:58 -0700459 hooks = _get_project_hooks(project)
Ryan Cui1562fb82011-05-09 11:01:31 -0700460 error_found = False
Ryan Cuifa55df52011-05-06 11:16:55 -0700461 for commit in commit_list:
Ryan Cui1562fb82011-05-09 11:01:31 -0700462 error_list = []
Ryan Cui9b651632011-05-11 11:38:58 -0700463 for hook in hooks:
Ryan Cui1562fb82011-05-09 11:01:31 -0700464 hook_error = hook(project, commit)
465 if hook_error:
466 error_list.append(hook_error)
467 error_found = True
468 if error_list:
469 PrintErrorsForCommit(project, commit, _get_commit_desc(commit),
470 error_list)
Don Garrettdba548a2011-05-05 15:17:14 -0700471
Ryan Cuiec4d6332011-05-02 14:15:25 -0700472 os.chdir(pwd)
Ryan Cui1562fb82011-05-09 11:01:31 -0700473 return error_found
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700474
475# Main
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -0700476
Ryan Cui1562fb82011-05-09 11:01:31 -0700477
Anush Elangovan63afad72011-03-23 00:41:27 -0700478def main(project_list, **kwargs):
Doug Anderson06456632012-01-05 11:02:14 -0800479 """Main function invoked directly by repo.
480
481 This function will exit directly upon error so that repo doesn't print some
482 obscure error message.
483
484 Args:
485 project_list: List of projects to run on.
486 kwargs: Leave this here for forward-compatibility.
487 """
Ryan Cui1562fb82011-05-09 11:01:31 -0700488 found_error = False
489 for project in project_list:
Ryan Cui9b651632011-05-11 11:38:58 -0700490 if _run_project_hooks(project):
Ryan Cui1562fb82011-05-09 11:01:31 -0700491 found_error = True
492
493 if (found_error):
494 msg = ('Preupload failed due to errors in project(s). HINTS:\n'
Ryan Cui9b651632011-05-11 11:38:58 -0700495 '- To disable some source style checks, and for other hints, see '
496 '<checkout_dir>/src/repohooks/README\n'
497 '- To upload only current project, run \'repo upload .\'')
Ryan Cui1562fb82011-05-09 11:01:31 -0700498 print >> sys.stderr, msg
Don Garrettdba548a2011-05-05 15:17:14 -0700499 sys.exit(1)
Anush Elangovan63afad72011-03-23 00:41:27 -0700500
Ryan Cui1562fb82011-05-09 11:01:31 -0700501
Doug Anderson44a644f2011-11-02 10:37:37 -0700502def _identify_project(path):
503 """Identify the repo project associated with the given path.
504
505 Returns:
506 A string indicating what project is associated with the path passed in or
507 a blank string upon failure.
508 """
509 return _run_command(['repo', 'forall', '.', '-c', 'echo ${REPO_PROJECT}'],
510 stderr=subprocess.PIPE, cwd=path).strip()
511
512
513def direct_main(args, verbose=False):
514 """Run hooks directly (outside of the context of repo).
515
516 # Setup for doctests below.
517 # ...note that some tests assume that running pre-upload on this CWD is fine.
518 # TODO: Use mock and actually mock out _run_project_hooks() for tests.
519 >>> mydir = os.path.dirname(os.path.abspath(__file__))
520 >>> olddir = os.getcwd()
521
522 # OK to run w/ no arugments; will run with CWD.
523 >>> os.chdir(mydir)
524 >>> direct_main(['prog_name'], verbose=True)
525 Running hooks on chromiumos/repohooks
526 0
527 >>> os.chdir(olddir)
528
529 # Run specifying a dir
530 >>> direct_main(['prog_name', '--dir=%s' % mydir], verbose=True)
531 Running hooks on chromiumos/repohooks
532 0
533
534 # Not a problem to use a bogus project; we'll just get default settings.
535 >>> direct_main(['prog_name', '--dir=%s' % mydir, '--project=X'],verbose=True)
536 Running hooks on X
537 0
538
539 # Run with project but no dir
540 >>> os.chdir(mydir)
541 >>> direct_main(['prog_name', '--project=X'], verbose=True)
542 Running hooks on X
543 0
544 >>> os.chdir(olddir)
545
546 # Try with a non-git CWD
547 >>> os.chdir('/tmp')
548 >>> direct_main(['prog_name'])
549 Traceback (most recent call last):
550 ...
551 BadInvocation: The current directory is not part of a git project.
552
553 # Check various bad arguments...
554 >>> direct_main(['prog_name', 'bogus'])
555 Traceback (most recent call last):
556 ...
557 BadInvocation: Unexpected arguments: bogus
558 >>> direct_main(['prog_name', '--project=bogus', '--dir=bogusdir'])
559 Traceback (most recent call last):
560 ...
561 BadInvocation: Invalid dir: bogusdir
562 >>> direct_main(['prog_name', '--project=bogus', '--dir=/tmp'])
563 Traceback (most recent call last):
564 ...
565 BadInvocation: Not a git directory: /tmp
566
567 Args:
568 args: The value of sys.argv
569
570 Returns:
571 0 if no pre-upload failures, 1 if failures.
572
573 Raises:
574 BadInvocation: On some types of invocation errors.
575 """
576 desc = 'Run Chromium OS pre-upload hooks on changes compared to upstream.'
577 parser = optparse.OptionParser(description=desc)
578
579 parser.add_option('--dir', default=None,
580 help='The directory that the project lives in. If not '
581 'specified, use the git project root based on the cwd.')
582 parser.add_option('--project', default=None,
583 help='The project repo path; this can affect how the hooks '
584 'get run, since some hooks are project-specific. For '
585 'chromite this is chromiumos/chromite. If not specified, '
586 'the repo tool will be used to figure this out based on '
587 'the dir.')
588
589 opts, args = parser.parse_args(args[1:])
590
591 if args:
592 raise BadInvocation('Unexpected arguments: %s' % ' '.join(args))
593
594 # Check/normlaize git dir; if unspecified, we'll use the root of the git
595 # project from CWD
596 if opts.dir is None:
597 git_dir = _run_command(['git', 'rev-parse', '--git-dir'],
598 stderr=subprocess.PIPE).strip()
599 if not git_dir:
600 raise BadInvocation('The current directory is not part of a git project.')
601 opts.dir = os.path.dirname(os.path.abspath(git_dir))
602 elif not os.path.isdir(opts.dir):
603 raise BadInvocation('Invalid dir: %s' % opts.dir)
604 elif not os.path.isdir(os.path.join(opts.dir, '.git')):
605 raise BadInvocation('Not a git directory: %s' % opts.dir)
606
607 # Identify the project if it wasn't specified; this _requires_ the repo
608 # tool to be installed and for the project to be part of a repo checkout.
609 if not opts.project:
610 opts.project = _identify_project(opts.dir)
611 if not opts.project:
612 raise BadInvocation("Repo couldn't identify the project of %s" % opts.dir)
613
614 if verbose:
615 print "Running hooks on %s" % (opts.project)
616
617 found_error = _run_project_hooks(opts.project, proj_dir=opts.dir)
618 if found_error:
619 return 1
620 return 0
621
622
623def _test():
624 """Run any built-in tests."""
625 import doctest
626 doctest.testmod()
627
628
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -0700629if __name__ == '__main__':
Doug Anderson44a644f2011-11-02 10:37:37 -0700630 if sys.argv[1:2] == ["--test"]:
631 _test()
632 exit_code = 0
633 else:
634 prog_name = os.path.basename(sys.argv[0])
635 try:
636 exit_code = direct_main(sys.argv)
637 except BadInvocation, e:
638 print >>sys.stderr, "%s: %s" % (prog_name, str(e))
639 exit_code = 1
640 sys.exit(exit_code)