blob: 6e993c5b785f79f6a118891ebbadcea32200cac0 [file] [log] [blame]
Doug Anderson44a644f2011-11-02 10:37:37 -07001#!/usr/bin/env python
Gilad Arnoldaae49e82012-07-20 11:53:53 -07002# 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
Gilad Arnoldaae49e82012-07-20 11:53:53 -07007import datetime
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
Ryan Cuiec4d6332011-05-02 14:15:25 -0700164def _get_file_diff(file, commit):
165 """Returns a list of (linenum, lines) tuples that the commit touched."""
Ryan Cui72834d12011-05-05 14:51:33 -0700166 output = _run_command(['git', 'show', '-p', '--no-ext-diff', commit, file])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700167
168 new_lines = []
169 line_num = 0
170 for line in output.splitlines():
171 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
172 if m:
173 line_num = int(m.groups(1)[0])
174 continue
175 if line.startswith('+') and not line.startswith('++'):
176 new_lines.append((line_num, line[1:]))
177 if not line.startswith('-'):
178 line_num += 1
179 return new_lines
180
Ryan Cui1562fb82011-05-09 11:01:31 -0700181
Ryan Cuiec4d6332011-05-02 14:15:25 -0700182def _get_affected_files(commit):
183 """Returns list of absolute filepaths that were modified/added."""
Ryan Cui72834d12011-05-05 14:51:33 -0700184 output = _run_command(['git', 'diff', '--name-status', commit + '^!'])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700185 files = []
186 for statusline in output.splitlines():
187 m = re.match('^(\w)+\t(.+)$', statusline.rstrip())
188 # Ignore deleted files, and return absolute paths of files
189 if (m.group(1)[0] != 'D'):
190 pwd = os.getcwd()
191 files.append(os.path.join(pwd, m.group(2)))
192 return files
193
Ryan Cui1562fb82011-05-09 11:01:31 -0700194
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700195def _get_commits():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700196 """Returns a list of commits for this review."""
Ryan Cui4725d952011-05-05 15:41:19 -0700197 cmd = ['git', 'log', '%s..' % _get_upstream_branch(), '--format=%H']
Ryan Cui72834d12011-05-05 14:51:33 -0700198 return _run_command(cmd).split()
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700199
Ryan Cui1562fb82011-05-09 11:01:31 -0700200
Ryan Cuiec4d6332011-05-02 14:15:25 -0700201def _get_commit_desc(commit):
202 """Returns the full commit message of a commit."""
Sean Paul23a2c582011-05-06 13:10:44 -0400203 return _run_command(['git', 'log', '--format=%s%n%n%b', commit + '^!'])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700204
205
206# Common Hooks
207
Ryan Cui1562fb82011-05-09 11:01:31 -0700208
Ryan Cuiec4d6332011-05-02 14:15:25 -0700209def _check_no_long_lines(project, commit):
210 """Checks that there aren't any lines longer than maxlen characters in any of
211 the text files to be submitted.
212 """
213 MAX_LEN = 80
214
215 errors = []
216 files = _filter_files(_get_affected_files(commit),
217 COMMON_INCLUDED_PATHS,
218 COMMON_EXCLUDED_PATHS)
219
220 for afile in files:
221 for line_num, line in _get_file_diff(afile, commit):
222 # Allow certain lines to exceed the maxlen rule.
223 if (len(line) > MAX_LEN and
224 not 'http://' in line and
225 not 'https://' in line and
226 not line.startswith('#define') and
227 not line.startswith('#include') and
228 not line.startswith('#import') and
229 not line.startswith('#pragma') and
230 not line.startswith('#if') and
231 not line.startswith('#endif')):
232 errors.append('%s, line %s, %s chars' % (afile, line_num, len(line)))
233 if len(errors) == 5: # Just show the first 5 errors.
234 break
235
236 if errors:
237 msg = 'Found lines longer than %s characters (first 5 shown):' % MAX_LEN
Ryan Cui1562fb82011-05-09 11:01:31 -0700238 return HookFailure(msg, errors)
239
Ryan Cuiec4d6332011-05-02 14:15:25 -0700240
241def _check_no_stray_whitespace(project, commit):
242 """Checks that there is no stray whitespace at source lines end."""
243 errors = []
244 files = _filter_files(_get_affected_files(commit),
245 COMMON_INCLUDED_PATHS,
246 COMMON_EXCLUDED_PATHS)
247
248 for afile in files:
249 for line_num, line in _get_file_diff(afile, commit):
250 if line.rstrip() != line:
251 errors.append('%s, line %s' % (afile, line_num))
252 if errors:
Ryan Cui1562fb82011-05-09 11:01:31 -0700253 return HookFailure('Found line ending with white space in:', errors)
254
Ryan Cuiec4d6332011-05-02 14:15:25 -0700255
256def _check_no_tabs(project, commit):
257 """Checks there are no unexpanded tabs."""
258 TAB_OK_PATHS = [
Ryan Cui31e0c172011-05-04 21:00:45 -0700259 r"/src/third_party/u-boot/",
Ryan Cuiec4d6332011-05-02 14:15:25 -0700260 r".*\.ebuild$",
261 r".*\.eclass$",
Elly Jones5ab34192011-11-15 14:57:06 -0500262 r".*/[M|m]akefile$",
263 r".*\.mk$"
Ryan Cuiec4d6332011-05-02 14:15:25 -0700264 ]
265
266 errors = []
267 files = _filter_files(_get_affected_files(commit),
268 COMMON_INCLUDED_PATHS,
269 COMMON_EXCLUDED_PATHS + TAB_OK_PATHS)
270
271 for afile in files:
272 for line_num, line in _get_file_diff(afile, commit):
273 if '\t' in line:
274 errors.append('%s, line %s' % (afile, line_num))
275 if errors:
Ryan Cui1562fb82011-05-09 11:01:31 -0700276 return HookFailure('Found a tab character in:', errors)
277
Ryan Cuiec4d6332011-05-02 14:15:25 -0700278
279def _check_change_has_test_field(project, commit):
280 """Check for a non-empty 'TEST=' field in the commit message."""
David McMahon8f6553e2011-06-10 15:46:36 -0700281 TEST_RE = r'\nTEST=\S+'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700282
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700283 if not re.search(TEST_RE, _get_commit_desc(commit)):
Ryan Cui1562fb82011-05-09 11:01:31 -0700284 msg = 'Changelist description needs TEST field (after first line)'
285 return HookFailure(msg)
286
Ryan Cuiec4d6332011-05-02 14:15:25 -0700287
288def _check_change_has_bug_field(project, commit):
David McMahon8f6553e2011-06-10 15:46:36 -0700289 """Check for a correctly formatted 'BUG=' field in the commit message."""
Daniel Erat1f064642012-01-10 09:48:20 -0800290 BUG_RE = r'\nBUG=([Nn]one|(chrome-os-partner|chromium|chromium-os):\d+)'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700291
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700292 if not re.search(BUG_RE, _get_commit_desc(commit)):
David McMahon8f6553e2011-06-10 15:46:36 -0700293 msg = ('Changelist description needs BUG field (after first line):\n'
Daniel Erat1f064642012-01-10 09:48:20 -0800294 'BUG=chromium-os:9999 (for public tracker)\n'
David McMahon8f6553e2011-06-10 15:46:36 -0700295 'BUG=chrome-os-partner:9999 (for partner tracker)\n'
Daniel Erat1f064642012-01-10 09:48:20 -0800296 'BUG=chromium:9999 (for browser tracker)\n'
David McMahon8f6553e2011-06-10 15:46:36 -0700297 'BUG=None')
Ryan Cui1562fb82011-05-09 11:01:31 -0700298 return HookFailure(msg)
299
Ryan Cuiec4d6332011-05-02 14:15:25 -0700300
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700301def _check_change_has_proper_changeid(project, commit):
302 """Verify that Change-ID is present in last paragraph of commit message."""
303 desc = _get_commit_desc(commit)
304 loc = desc.rfind('\nChange-Id:')
305 if loc == -1 or re.search('\n\s*\n\s*\S+', desc[loc:]):
Ryan Cui1562fb82011-05-09 11:01:31 -0700306 return HookFailure('Change-Id must be in last paragraph of description.')
307
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700308
Ryan Cuiec4d6332011-05-02 14:15:25 -0700309def _check_license(project, commit):
310 """Verifies the license header."""
Gilad Arnoldaae49e82012-07-20 11:53:53 -0700311 year = str(datetime.datetime.now().year)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700312 LICENSE_HEADER = (
Gilad Arnoldaae49e82012-07-20 11:53:53 -0700313 r".*? Copyright \(c\) " + year + " The Chromium OS Authors\. All rights "
Ryan Cuiec4d6332011-05-02 14:15:25 -0700314 r"reserved\." "\n"
315 r".*? Use of this source code is governed by a BSD-style license that can "
316 "be\n"
317 r".*? found in the LICENSE file\."
318 "\n"
319 )
320
321 license_re = re.compile(LICENSE_HEADER, re.MULTILINE)
322 bad_files = []
323 files = _filter_files(_get_affected_files(commit),
324 COMMON_INCLUDED_PATHS,
325 COMMON_EXCLUDED_PATHS)
326
327 for f in files:
328 contents = open(f).read()
329 if len(contents) == 0: continue # Ignore empty files
330 if not license_re.search(contents):
331 bad_files.append(f)
332 if bad_files:
Ryan Cui1562fb82011-05-09 11:01:31 -0700333 return HookFailure('License must match:\n%s\n' % license_re.pattern +
334 'Found a bad license header in these files:',
335 bad_files)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700336
337
338# Project-specific hooks
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700339
Ryan Cui1562fb82011-05-09 11:01:31 -0700340
Anton Staaf815d6852011-08-22 10:08:45 -0700341def _run_checkpatch(project, commit, options=[]):
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700342 """Runs checkpatch.pl on the given project"""
343 hooks_dir = _get_hooks_dir()
Anton Staaf815d6852011-08-22 10:08:45 -0700344 cmd = ['%s/checkpatch.pl' % hooks_dir] + options + ['-']
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700345 p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700346 output = p.communicate(_get_diff(commit))[0]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700347 if p.returncode:
Ryan Cui1562fb82011-05-09 11:01:31 -0700348 return HookFailure('checkpatch.pl errors/warnings\n\n' + output)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700349
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700350
Anton Staaf815d6852011-08-22 10:08:45 -0700351def _run_checkpatch_no_tree(project, commit):
352 return _run_checkpatch(project, commit, ['--no-tree'])
353
354
Dale Curtis2975c432011-05-03 17:25:20 -0700355def _run_json_check(project, commit):
356 """Checks that all JSON files are syntactically valid."""
Dale Curtisa039cfd2011-05-04 12:01:05 -0700357 for f in _filter_files(_get_affected_files(commit), [r'.*\.json']):
Dale Curtis2975c432011-05-03 17:25:20 -0700358 try:
359 json.load(open(f))
360 except Exception, e:
Ryan Cui1562fb82011-05-09 11:01:31 -0700361 return HookFailure('Invalid JSON in %s: %s' % (f, e))
Dale Curtis2975c432011-05-03 17:25:20 -0700362
363
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700364# Base
365
Ryan Cui1562fb82011-05-09 11:01:31 -0700366
Ryan Cui9b651632011-05-11 11:38:58 -0700367# A list of hooks that are not project-specific
368_COMMON_HOOKS = [
369 _check_change_has_bug_field,
370 _check_change_has_test_field,
371 _check_change_has_proper_changeid,
372 _check_no_stray_whitespace,
373 _check_no_long_lines,
374 _check_license,
375 _check_no_tabs,
376]
Ryan Cuiec4d6332011-05-02 14:15:25 -0700377
Ryan Cui1562fb82011-05-09 11:01:31 -0700378
Ryan Cui9b651632011-05-11 11:38:58 -0700379# A dictionary of project-specific hooks(callbacks), indexed by project name.
380# dict[project] = [callback1, callback2]
381_PROJECT_SPECIFIC_HOOKS = {
Doug Anderson830216f2011-05-02 10:08:37 -0700382 "chromiumos/third_party/kernel": [_run_checkpatch],
383 "chromiumos/third_party/kernel-next": [_run_checkpatch],
Anton Staaf815d6852011-08-22 10:08:45 -0700384 "chromiumos/third_party/u-boot": [_run_checkpatch_no_tree],
Che-Liang Chiou1eb0ab62011-10-20 16:14:38 +0800385 "chromiumos/platform/u-boot-vboot-integration": [_run_checkpatch_no_tree],
Vincent Palatin11ecc742012-02-28 13:06:59 -0800386 "chromiumos/platform/ec": [_run_checkpatch_no_tree],
387 "chromeos/platform/ec-private": [_run_checkpatch_no_tree],
Dale Curtis2975c432011-05-03 17:25:20 -0700388 "chromeos/autotest-tools": [_run_json_check],
Ryan Cui9b651632011-05-11 11:38:58 -0700389}
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700390
Ryan Cui1562fb82011-05-09 11:01:31 -0700391
Ryan Cui9b651632011-05-11 11:38:58 -0700392# A dictionary of flags (keys) that can appear in the config file, and the hook
393# that the flag disables (value)
394_DISABLE_FLAGS = {
395 'stray_whitespace_check': _check_no_stray_whitespace,
396 'long_line_check': _check_no_long_lines,
397 'cros_license_check': _check_license,
398 'tab_check': _check_no_tabs,
399}
400
401
402def _get_disabled_hooks():
403 """Returns a set of hooks disabled by the current project's config file.
404
405 Expects to be called within the project root.
406 """
407 SECTION = 'Hook Overrides'
408 config = ConfigParser.RawConfigParser()
409 try:
410 config.read(_CONFIG_FILE)
411 flags = config.options(SECTION)
412 except ConfigParser.Error:
413 return set([])
414
415 disable_flags = []
416 for flag in flags:
417 try:
418 if not config.getboolean(SECTION, flag): disable_flags.append(flag)
419 except ValueError as e:
420 msg = "Error parsing flag \'%s\' in %s file - " % (flag, _CONFIG_FILE)
421 print msg + str(e)
422
423 disabled_keys = set(_DISABLE_FLAGS.iterkeys()).intersection(disable_flags)
424 return set([_DISABLE_FLAGS[key] for key in disabled_keys])
425
426
427def _get_project_hooks(project):
428 """Returns a list of hooks that need to be run for a project.
429
430 Expects to be called from within the project root.
431 """
432 disabled_hooks = _get_disabled_hooks()
433 hooks = [hook for hook in _COMMON_HOOKS if hook not in disabled_hooks]
434
435 if project in _PROJECT_SPECIFIC_HOOKS:
436 hooks.extend(_PROJECT_SPECIFIC_HOOKS[project])
437
438 return hooks
439
440
Doug Anderson44a644f2011-11-02 10:37:37 -0700441def _run_project_hooks(project, proj_dir=None):
Ryan Cui1562fb82011-05-09 11:01:31 -0700442 """For each project run its project specific hook from the hooks dictionary.
443
444 Args:
Doug Anderson44a644f2011-11-02 10:37:37 -0700445 project: The name of project to run hooks for.
446 proj_dir: If non-None, this is the directory the project is in. If None,
447 we'll ask repo.
Ryan Cui1562fb82011-05-09 11:01:31 -0700448
449 Returns:
450 Boolean value of whether any errors were ecountered while running the hooks.
451 """
Doug Anderson44a644f2011-11-02 10:37:37 -0700452 if proj_dir is None:
453 proj_dir = _run_command(['repo', 'forall', project, '-c', 'pwd']).strip()
454
Ryan Cuiec4d6332011-05-02 14:15:25 -0700455 pwd = os.getcwd()
456 # hooks assume they are run from the root of the project
457 os.chdir(proj_dir)
458
Ryan Cuifa55df52011-05-06 11:16:55 -0700459 try:
460 commit_list = _get_commits()
Don Garrettdba548a2011-05-05 15:17:14 -0700461 except VerifyException as e:
Ryan Cui1562fb82011-05-09 11:01:31 -0700462 PrintErrorForProject(project, HookFailure(str(e)))
463 os.chdir(pwd)
464 return True
Ryan Cuifa55df52011-05-06 11:16:55 -0700465
Ryan Cui9b651632011-05-11 11:38:58 -0700466 hooks = _get_project_hooks(project)
Ryan Cui1562fb82011-05-09 11:01:31 -0700467 error_found = False
Ryan Cuifa55df52011-05-06 11:16:55 -0700468 for commit in commit_list:
Ryan Cui1562fb82011-05-09 11:01:31 -0700469 error_list = []
Ryan Cui9b651632011-05-11 11:38:58 -0700470 for hook in hooks:
Ryan Cui1562fb82011-05-09 11:01:31 -0700471 hook_error = hook(project, commit)
472 if hook_error:
473 error_list.append(hook_error)
474 error_found = True
475 if error_list:
476 PrintErrorsForCommit(project, commit, _get_commit_desc(commit),
477 error_list)
Don Garrettdba548a2011-05-05 15:17:14 -0700478
Ryan Cuiec4d6332011-05-02 14:15:25 -0700479 os.chdir(pwd)
Ryan Cui1562fb82011-05-09 11:01:31 -0700480 return error_found
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700481
482# Main
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -0700483
Ryan Cui1562fb82011-05-09 11:01:31 -0700484
Anush Elangovan63afad72011-03-23 00:41:27 -0700485def main(project_list, **kwargs):
Doug Anderson06456632012-01-05 11:02:14 -0800486 """Main function invoked directly by repo.
487
488 This function will exit directly upon error so that repo doesn't print some
489 obscure error message.
490
491 Args:
492 project_list: List of projects to run on.
493 kwargs: Leave this here for forward-compatibility.
494 """
Ryan Cui1562fb82011-05-09 11:01:31 -0700495 found_error = False
496 for project in project_list:
Ryan Cui9b651632011-05-11 11:38:58 -0700497 if _run_project_hooks(project):
Ryan Cui1562fb82011-05-09 11:01:31 -0700498 found_error = True
499
500 if (found_error):
501 msg = ('Preupload failed due to errors in project(s). HINTS:\n'
Ryan Cui9b651632011-05-11 11:38:58 -0700502 '- To disable some source style checks, and for other hints, see '
503 '<checkout_dir>/src/repohooks/README\n'
504 '- To upload only current project, run \'repo upload .\'')
Ryan Cui1562fb82011-05-09 11:01:31 -0700505 print >> sys.stderr, msg
Don Garrettdba548a2011-05-05 15:17:14 -0700506 sys.exit(1)
Anush Elangovan63afad72011-03-23 00:41:27 -0700507
Ryan Cui1562fb82011-05-09 11:01:31 -0700508
Doug Anderson44a644f2011-11-02 10:37:37 -0700509def _identify_project(path):
510 """Identify the repo project associated with the given path.
511
512 Returns:
513 A string indicating what project is associated with the path passed in or
514 a blank string upon failure.
515 """
516 return _run_command(['repo', 'forall', '.', '-c', 'echo ${REPO_PROJECT}'],
517 stderr=subprocess.PIPE, cwd=path).strip()
518
519
520def direct_main(args, verbose=False):
521 """Run hooks directly (outside of the context of repo).
522
523 # Setup for doctests below.
524 # ...note that some tests assume that running pre-upload on this CWD is fine.
525 # TODO: Use mock and actually mock out _run_project_hooks() for tests.
526 >>> mydir = os.path.dirname(os.path.abspath(__file__))
527 >>> olddir = os.getcwd()
528
529 # OK to run w/ no arugments; will run with CWD.
530 >>> os.chdir(mydir)
531 >>> direct_main(['prog_name'], verbose=True)
532 Running hooks on chromiumos/repohooks
533 0
534 >>> os.chdir(olddir)
535
536 # Run specifying a dir
537 >>> direct_main(['prog_name', '--dir=%s' % mydir], verbose=True)
538 Running hooks on chromiumos/repohooks
539 0
540
541 # Not a problem to use a bogus project; we'll just get default settings.
542 >>> direct_main(['prog_name', '--dir=%s' % mydir, '--project=X'],verbose=True)
543 Running hooks on X
544 0
545
546 # Run with project but no dir
547 >>> os.chdir(mydir)
548 >>> direct_main(['prog_name', '--project=X'], verbose=True)
549 Running hooks on X
550 0
551 >>> os.chdir(olddir)
552
553 # Try with a non-git CWD
554 >>> os.chdir('/tmp')
555 >>> direct_main(['prog_name'])
556 Traceback (most recent call last):
557 ...
558 BadInvocation: The current directory is not part of a git project.
559
560 # Check various bad arguments...
561 >>> direct_main(['prog_name', 'bogus'])
562 Traceback (most recent call last):
563 ...
564 BadInvocation: Unexpected arguments: bogus
565 >>> direct_main(['prog_name', '--project=bogus', '--dir=bogusdir'])
566 Traceback (most recent call last):
567 ...
568 BadInvocation: Invalid dir: bogusdir
569 >>> direct_main(['prog_name', '--project=bogus', '--dir=/tmp'])
570 Traceback (most recent call last):
571 ...
572 BadInvocation: Not a git directory: /tmp
573
574 Args:
575 args: The value of sys.argv
576
577 Returns:
578 0 if no pre-upload failures, 1 if failures.
579
580 Raises:
581 BadInvocation: On some types of invocation errors.
582 """
583 desc = 'Run Chromium OS pre-upload hooks on changes compared to upstream.'
584 parser = optparse.OptionParser(description=desc)
585
586 parser.add_option('--dir', default=None,
587 help='The directory that the project lives in. If not '
588 'specified, use the git project root based on the cwd.')
589 parser.add_option('--project', default=None,
590 help='The project repo path; this can affect how the hooks '
591 'get run, since some hooks are project-specific. For '
592 'chromite this is chromiumos/chromite. If not specified, '
593 'the repo tool will be used to figure this out based on '
594 'the dir.')
595
596 opts, args = parser.parse_args(args[1:])
597
598 if args:
599 raise BadInvocation('Unexpected arguments: %s' % ' '.join(args))
600
601 # Check/normlaize git dir; if unspecified, we'll use the root of the git
602 # project from CWD
603 if opts.dir is None:
604 git_dir = _run_command(['git', 'rev-parse', '--git-dir'],
605 stderr=subprocess.PIPE).strip()
606 if not git_dir:
607 raise BadInvocation('The current directory is not part of a git project.')
608 opts.dir = os.path.dirname(os.path.abspath(git_dir))
609 elif not os.path.isdir(opts.dir):
610 raise BadInvocation('Invalid dir: %s' % opts.dir)
611 elif not os.path.isdir(os.path.join(opts.dir, '.git')):
612 raise BadInvocation('Not a git directory: %s' % opts.dir)
613
614 # Identify the project if it wasn't specified; this _requires_ the repo
615 # tool to be installed and for the project to be part of a repo checkout.
616 if not opts.project:
617 opts.project = _identify_project(opts.dir)
618 if not opts.project:
619 raise BadInvocation("Repo couldn't identify the project of %s" % opts.dir)
620
621 if verbose:
622 print "Running hooks on %s" % (opts.project)
623
624 found_error = _run_project_hooks(opts.project, proj_dir=opts.dir)
625 if found_error:
626 return 1
627 return 0
628
629
630def _test():
631 """Run any built-in tests."""
632 import doctest
633 doctest.testmod()
634
635
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -0700636if __name__ == '__main__':
Doug Anderson44a644f2011-11-02 10:37:37 -0700637 if sys.argv[1:2] == ["--test"]:
638 _test()
639 exit_code = 0
640 else:
641 prog_name = os.path.basename(sys.argv[0])
642 try:
643 exit_code = direct_main(sys.argv)
644 except BadInvocation, e:
645 print >>sys.stderr, "%s: %s" % (prog_name, str(e))
646 exit_code = 1
647 sys.exit(exit_code)