blob: 1ca755c1ef23497091dc08576573f1f1b69f85c7 [file] [log] [blame]
Doug Anderson44a644f2011-11-02 10:37:37 -07001#!/usr/bin/env python
Jon Salz98255932012-08-18 14:48:02 +08002# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07003# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
Ryan Cui9b651632011-05-11 11:38:58 -07006import ConfigParser
Jon Salz3ee59de2012-08-18 13:54:22 +08007import functools
Dale Curtis2975c432011-05-03 17:25:20 -07008import json
Doug Anderson44a644f2011-11-02 10:37:37 -07009import optparse
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070010import os
Ryan Cuiec4d6332011-05-02 14:15:25 -070011import re
Mandeep Singh Bainesa7ffa4b2011-05-03 11:37:02 -070012import sys
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070013import subprocess
14
Ryan Cui1562fb82011-05-09 11:01:31 -070015from errors import (VerifyException, HookFailure, PrintErrorForProject,
16 PrintErrorsForCommit)
Ryan Cuiec4d6332011-05-02 14:15:25 -070017
Ryan Cuiec4d6332011-05-02 14:15:25 -070018
19COMMON_INCLUDED_PATHS = [
20 # C++ and friends
21 r".*\.c$", r".*\.cc$", r".*\.cpp$", r".*\.h$", r".*\.m$", r".*\.mm$",
22 r".*\.inl$", r".*\.asm$", r".*\.hxx$", r".*\.hpp$", r".*\.s$", r".*\.S$",
23 # Scripts
24 r".*\.js$", r".*\.py$", r".*\.sh$", r".*\.rb$", r".*\.pl$", r".*\.pm$",
25 # No extension at all, note that ALL CAPS files are black listed in
26 # COMMON_EXCLUDED_LIST below.
27 r"(^|.*?[\\\/])[^.]+$",
28 # Other
29 r".*\.java$", r".*\.mk$", r".*\.am$",
30]
31
Ryan Cui1562fb82011-05-09 11:01:31 -070032
Ryan Cuiec4d6332011-05-02 14:15:25 -070033COMMON_EXCLUDED_PATHS = [
Ryan Cui31e0c172011-05-04 21:00:45 -070034 # avoid doing source file checks for kernel
35 r"/src/third_party/kernel/",
36 r"/src/third_party/kernel-next/",
Paul Taysomf8b6e012011-05-09 14:32:42 -070037 r"/src/third_party/ktop/",
38 r"/src/third_party/punybench/",
Ryan Cuiec4d6332011-05-02 14:15:25 -070039 r".*\bexperimental[\\\/].*",
40 r".*\b[A-Z0-9_]{2,}$",
41 r".*[\\\/]debian[\\\/]rules$",
Brian Harringd780d602011-10-18 16:48:08 -070042 # for ebuild trees, ignore any caches and manifest data
43 r".*/Manifest$",
44 r".*/metadata/[^/]*cache[^/]*/[^/]+/[^/]+$",
Doug Anderson5bfb6792011-10-25 16:45:41 -070045
46 # ignore profiles data (like overlay-tegra2/profiles)
47 r".*/overlay-.*/profiles/.*",
Andrew de los Reyes0e679922012-05-02 11:42:54 -070048 # ignore minified js and jquery
49 r".*\.min\.js",
50 r".*jquery.*\.js",
Ryan Cuiec4d6332011-05-02 14:15:25 -070051]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070052
Ryan Cui1562fb82011-05-09 11:01:31 -070053
Ryan Cui9b651632011-05-11 11:38:58 -070054_CONFIG_FILE = 'PRESUBMIT.cfg'
55
56
Doug Anderson44a644f2011-11-02 10:37:37 -070057# Exceptions
58
59
60class BadInvocation(Exception):
61 """An Exception indicating a bad invocation of the program."""
62 pass
63
64
Ryan Cui1562fb82011-05-09 11:01:31 -070065# General Helpers
66
Sean Paulba01d402011-05-05 11:36:23 -040067
Doug Anderson44a644f2011-11-02 10:37:37 -070068def _run_command(cmd, cwd=None, stderr=None):
69 """Executes the passed in command and returns raw stdout output.
70
71 Args:
72 cmd: The command to run; should be a list of strings.
73 cwd: The directory to switch to for running the command.
74 stderr: Can be one of None (print stderr to console), subprocess.STDOUT
75 (combine stderr with stdout), or subprocess.PIPE (ignore stderr).
76
77 Returns:
78 The standard out from the process.
79 """
80 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=stderr, cwd=cwd)
81 return p.communicate()[0]
Ryan Cui72834d12011-05-05 14:51:33 -070082
Ryan Cui1562fb82011-05-09 11:01:31 -070083
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070084def _get_hooks_dir():
Ryan Cuiec4d6332011-05-02 14:15:25 -070085 """Returns the absolute path to the repohooks directory."""
Doug Anderson44a644f2011-11-02 10:37:37 -070086 if __name__ == '__main__':
87 # Works when file is run on its own (__file__ is defined)...
88 return os.path.abspath(os.path.dirname(__file__))
89 else:
90 # We need to do this when we're run through repo. Since repo executes
91 # us with execfile(), we don't get __file__ defined.
92 cmd = ['repo', 'forall', 'chromiumos/repohooks', '-c', 'pwd']
93 return _run_command(cmd).strip()
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070094
Ryan Cui1562fb82011-05-09 11:01:31 -070095
Ryan Cuiec4d6332011-05-02 14:15:25 -070096def _match_regex_list(subject, expressions):
97 """Try to match a list of regular expressions to a string.
98
99 Args:
100 subject: The string to match regexes on
101 expressions: A list of regular expressions to check for matches with.
102
103 Returns:
104 Whether the passed in subject matches any of the passed in regexes.
105 """
106 for expr in expressions:
107 if (re.search(expr, subject)):
108 return True
109 return False
110
Ryan Cui1562fb82011-05-09 11:01:31 -0700111
Ryan Cuiec4d6332011-05-02 14:15:25 -0700112def _filter_files(files, include_list, exclude_list=[]):
113 """Filter out files based on the conditions passed in.
114
115 Args:
116 files: list of filepaths to filter
117 include_list: list of regex that when matched with a file path will cause it
118 to be added to the output list unless the file is also matched with a
119 regex in the exclude_list.
120 exclude_list: list of regex that when matched with a file will prevent it
121 from being added to the output list, even if it is also matched with a
122 regex in the include_list.
123
124 Returns:
125 A list of filepaths that contain files matched in the include_list and not
126 in the exclude_list.
127 """
128 filtered = []
129 for f in files:
130 if (_match_regex_list(f, include_list) and
131 not _match_regex_list(f, exclude_list)):
132 filtered.append(f)
133 return filtered
134
Ryan Cuiec4d6332011-05-02 14:15:25 -0700135
David Hendricks35030d02013-02-04 17:49:16 -0800136def _verify_header_content(commit, content, fail_msg):
137 """Verify that file headers contain specified content.
138
139 Args:
140 commit: the affected commit.
141 content: the content of the header to be verified.
142 fail_msg: the first message to display in case of failure.
143
144 Returns:
145 The return value of HookFailure().
146 """
147 license_re = re.compile(content, re.MULTILINE)
148 bad_files = []
149 files = _filter_files(_get_affected_files(commit),
150 COMMON_INCLUDED_PATHS,
151 COMMON_EXCLUDED_PATHS)
152
153 for f in files:
154 contents = open(f).read()
155 if len(contents) == 0: continue # Ignore empty files
156 if not license_re.search(contents):
157 bad_files.append(f)
158 if bad_files:
159 msg = "%s:\n%s\n%s" % (fail_msg, license_re.pattern,
160 "Found a bad header in these files:")
161 return HookFailure(msg, bad_files)
162
163
Ryan Cuiec4d6332011-05-02 14:15:25 -0700164# Git Helpers
Ryan Cui1562fb82011-05-09 11:01:31 -0700165
166
Ryan Cui4725d952011-05-05 15:41:19 -0700167def _get_upstream_branch():
168 """Returns the upstream tracking branch of the current branch.
169
170 Raises:
171 Error if there is no tracking branch
172 """
173 current_branch = _run_command(['git', 'symbolic-ref', 'HEAD']).strip()
174 current_branch = current_branch.replace('refs/heads/', '')
175 if not current_branch:
Ryan Cui1562fb82011-05-09 11:01:31 -0700176 raise VerifyException('Need to be on a tracking branch')
Ryan Cui4725d952011-05-05 15:41:19 -0700177
178 cfg_option = 'branch.' + current_branch + '.%s'
179 full_upstream = _run_command(['git', 'config', cfg_option % 'merge']).strip()
180 remote = _run_command(['git', 'config', cfg_option % 'remote']).strip()
181 if not remote or not full_upstream:
Ryan Cui1562fb82011-05-09 11:01:31 -0700182 raise VerifyException('Need to be on a tracking branch')
Ryan Cui4725d952011-05-05 15:41:19 -0700183
184 return full_upstream.replace('heads', 'remotes/' + remote)
185
Ryan Cui1562fb82011-05-09 11:01:31 -0700186
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700187def _get_diff(commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700188 """Returns the diff for this commit."""
Ryan Cui72834d12011-05-05 14:51:33 -0700189 return _run_command(['git', 'show', commit])
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700190
Ryan Cui1562fb82011-05-09 11:01:31 -0700191
Jon Salz98255932012-08-18 14:48:02 +0800192def _try_utf8_decode(data):
193 """Attempts to decode a string as UTF-8.
194
195 Returns:
196 The decoded Unicode object, or the original string if parsing fails.
197 """
198 try:
199 return unicode(data, 'utf-8', 'strict')
200 except UnicodeDecodeError:
201 return data
202
203
Ryan Cuiec4d6332011-05-02 14:15:25 -0700204def _get_file_diff(file, commit):
205 """Returns a list of (linenum, lines) tuples that the commit touched."""
Ryan Cui72834d12011-05-05 14:51:33 -0700206 output = _run_command(['git', 'show', '-p', '--no-ext-diff', commit, file])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700207
208 new_lines = []
209 line_num = 0
210 for line in output.splitlines():
211 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
212 if m:
213 line_num = int(m.groups(1)[0])
214 continue
215 if line.startswith('+') and not line.startswith('++'):
Jon Salz98255932012-08-18 14:48:02 +0800216 new_lines.append((line_num, _try_utf8_decode(line[1:])))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700217 if not line.startswith('-'):
218 line_num += 1
219 return new_lines
220
Ryan Cui1562fb82011-05-09 11:01:31 -0700221
Ryan Cuiec4d6332011-05-02 14:15:25 -0700222def _get_affected_files(commit):
223 """Returns list of absolute filepaths that were modified/added."""
Ryan Cui72834d12011-05-05 14:51:33 -0700224 output = _run_command(['git', 'diff', '--name-status', commit + '^!'])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700225 files = []
226 for statusline in output.splitlines():
227 m = re.match('^(\w)+\t(.+)$', statusline.rstrip())
228 # Ignore deleted files, and return absolute paths of files
229 if (m.group(1)[0] != 'D'):
230 pwd = os.getcwd()
231 files.append(os.path.join(pwd, m.group(2)))
232 return files
233
Ryan Cui1562fb82011-05-09 11:01:31 -0700234
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700235def _get_commits():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700236 """Returns a list of commits for this review."""
Ryan Cui4725d952011-05-05 15:41:19 -0700237 cmd = ['git', 'log', '%s..' % _get_upstream_branch(), '--format=%H']
Ryan Cui72834d12011-05-05 14:51:33 -0700238 return _run_command(cmd).split()
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700239
Ryan Cui1562fb82011-05-09 11:01:31 -0700240
Ryan Cuiec4d6332011-05-02 14:15:25 -0700241def _get_commit_desc(commit):
242 """Returns the full commit message of a commit."""
Sean Paul23a2c582011-05-06 13:10:44 -0400243 return _run_command(['git', 'log', '--format=%s%n%n%b', commit + '^!'])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700244
245
246# Common Hooks
247
Ryan Cui1562fb82011-05-09 11:01:31 -0700248
Ryan Cuiec4d6332011-05-02 14:15:25 -0700249def _check_no_long_lines(project, commit):
250 """Checks that there aren't any lines longer than maxlen characters in any of
251 the text files to be submitted.
252 """
253 MAX_LEN = 80
Jon Salz98255932012-08-18 14:48:02 +0800254 SKIP_REGEXP = re.compile('|'.join([
255 r'https?://',
256 r'^#\s*(define|include|import|pragma|if|endif)\b']))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700257
258 errors = []
259 files = _filter_files(_get_affected_files(commit),
260 COMMON_INCLUDED_PATHS,
261 COMMON_EXCLUDED_PATHS)
262
263 for afile in files:
264 for line_num, line in _get_file_diff(afile, commit):
265 # Allow certain lines to exceed the maxlen rule.
Jon Salz98255932012-08-18 14:48:02 +0800266 if (len(line) <= MAX_LEN or SKIP_REGEXP.search(line)):
267 continue
268
269 errors.append('%s, line %s, %s chars' % (afile, line_num, len(line)))
270 if len(errors) == 5: # Just show the first 5 errors.
271 break
Ryan Cuiec4d6332011-05-02 14:15:25 -0700272
273 if errors:
274 msg = 'Found lines longer than %s characters (first 5 shown):' % MAX_LEN
Ryan Cui1562fb82011-05-09 11:01:31 -0700275 return HookFailure(msg, errors)
276
Ryan Cuiec4d6332011-05-02 14:15:25 -0700277
278def _check_no_stray_whitespace(project, commit):
279 """Checks that there is no stray whitespace at source lines end."""
280 errors = []
281 files = _filter_files(_get_affected_files(commit),
282 COMMON_INCLUDED_PATHS,
283 COMMON_EXCLUDED_PATHS)
284
285 for afile in files:
286 for line_num, line in _get_file_diff(afile, commit):
287 if line.rstrip() != line:
288 errors.append('%s, line %s' % (afile, line_num))
289 if errors:
Ryan Cui1562fb82011-05-09 11:01:31 -0700290 return HookFailure('Found line ending with white space in:', errors)
291
Ryan Cuiec4d6332011-05-02 14:15:25 -0700292
293def _check_no_tabs(project, commit):
294 """Checks there are no unexpanded tabs."""
295 TAB_OK_PATHS = [
Ryan Cui31e0c172011-05-04 21:00:45 -0700296 r"/src/third_party/u-boot/",
Ryan Cuiec4d6332011-05-02 14:15:25 -0700297 r".*\.ebuild$",
298 r".*\.eclass$",
Elly Jones5ab34192011-11-15 14:57:06 -0500299 r".*/[M|m]akefile$",
300 r".*\.mk$"
Ryan Cuiec4d6332011-05-02 14:15:25 -0700301 ]
302
303 errors = []
304 files = _filter_files(_get_affected_files(commit),
305 COMMON_INCLUDED_PATHS,
306 COMMON_EXCLUDED_PATHS + TAB_OK_PATHS)
307
308 for afile in files:
309 for line_num, line in _get_file_diff(afile, commit):
310 if '\t' in line:
311 errors.append('%s, line %s' % (afile, line_num))
312 if errors:
Ryan Cui1562fb82011-05-09 11:01:31 -0700313 return HookFailure('Found a tab character in:', errors)
314
Ryan Cuiec4d6332011-05-02 14:15:25 -0700315
316def _check_change_has_test_field(project, commit):
317 """Check for a non-empty 'TEST=' field in the commit message."""
David McMahon8f6553e2011-06-10 15:46:36 -0700318 TEST_RE = r'\nTEST=\S+'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700319
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700320 if not re.search(TEST_RE, _get_commit_desc(commit)):
Ryan Cui1562fb82011-05-09 11:01:31 -0700321 msg = 'Changelist description needs TEST field (after first line)'
322 return HookFailure(msg)
323
Ryan Cuiec4d6332011-05-02 14:15:25 -0700324
325def _check_change_has_bug_field(project, commit):
David McMahon8f6553e2011-06-10 15:46:36 -0700326 """Check for a correctly formatted 'BUG=' field in the commit message."""
Daniel Erat1f064642012-01-10 09:48:20 -0800327 BUG_RE = r'\nBUG=([Nn]one|(chrome-os-partner|chromium|chromium-os):\d+)'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700328
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700329 if not re.search(BUG_RE, _get_commit_desc(commit)):
David McMahon8f6553e2011-06-10 15:46:36 -0700330 msg = ('Changelist description needs BUG field (after first line):\n'
Daniel Erat1f064642012-01-10 09:48:20 -0800331 'BUG=chromium-os:9999 (for public tracker)\n'
David McMahon8f6553e2011-06-10 15:46:36 -0700332 'BUG=chrome-os-partner:9999 (for partner tracker)\n'
Daniel Erat1f064642012-01-10 09:48:20 -0800333 'BUG=chromium:9999 (for browser tracker)\n'
David McMahon8f6553e2011-06-10 15:46:36 -0700334 'BUG=None')
Ryan Cui1562fb82011-05-09 11:01:31 -0700335 return HookFailure(msg)
336
Ryan Cuiec4d6332011-05-02 14:15:25 -0700337
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700338def _check_change_has_proper_changeid(project, commit):
339 """Verify that Change-ID is present in last paragraph of commit message."""
340 desc = _get_commit_desc(commit)
341 loc = desc.rfind('\nChange-Id:')
342 if loc == -1 or re.search('\n\s*\n\s*\S+', desc[loc:]):
Ryan Cui1562fb82011-05-09 11:01:31 -0700343 return HookFailure('Change-Id must be in last paragraph of description.')
344
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700345
Ryan Cuiec4d6332011-05-02 14:15:25 -0700346def _check_license(project, commit):
347 """Verifies the license header."""
348 LICENSE_HEADER = (
David James28766e62012-08-06 17:30:15 -0700349 r".*? Copyright \(c\) 20[-0-9]{2,7} The Chromium OS Authors\. All rights "
Ryan Cuiec4d6332011-05-02 14:15:25 -0700350 r"reserved\." "\n"
351 r".*? Use of this source code is governed by a BSD-style license that can "
352 "be\n"
353 r".*? found in the LICENSE file\."
354 "\n"
355 )
David Hendricks35030d02013-02-04 17:49:16 -0800356 FAIL_MSG = "License must match"
Ryan Cuiec4d6332011-05-02 14:15:25 -0700357
David Hendricks35030d02013-02-04 17:49:16 -0800358 return _verify_header_content(commit, LICENSE_HEADER, FAIL_MSG)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700359
360
361# Project-specific hooks
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700362
Ryan Cui1562fb82011-05-09 11:01:31 -0700363
Anton Staaf815d6852011-08-22 10:08:45 -0700364def _run_checkpatch(project, commit, options=[]):
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700365 """Runs checkpatch.pl on the given project"""
366 hooks_dir = _get_hooks_dir()
Anton Staaf815d6852011-08-22 10:08:45 -0700367 cmd = ['%s/checkpatch.pl' % hooks_dir] + options + ['-']
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700368 p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700369 output = p.communicate(_get_diff(commit))[0]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700370 if p.returncode:
Ryan Cui1562fb82011-05-09 11:01:31 -0700371 return HookFailure('checkpatch.pl errors/warnings\n\n' + output)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700372
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700373
Anton Staaf815d6852011-08-22 10:08:45 -0700374def _run_checkpatch_no_tree(project, commit):
375 return _run_checkpatch(project, commit, ['--no-tree'])
376
Olof Johanssona96810f2012-09-04 16:20:03 -0700377def _kernel_configcheck(project, commit):
378 """Makes sure kernel config changes are not mixed with code changes"""
379 files = _get_affected_files(commit)
380 if not len(_filter_files(files, [r'chromeos/config'])) in [0, len(files)]:
381 return HookFailure('Changes to chromeos/config/ and regular files must '
382 'be in separate commits:\n%s' % '\n'.join(files))
Anton Staaf815d6852011-08-22 10:08:45 -0700383
Dale Curtis2975c432011-05-03 17:25:20 -0700384def _run_json_check(project, commit):
385 """Checks that all JSON files are syntactically valid."""
Dale Curtisa039cfd2011-05-04 12:01:05 -0700386 for f in _filter_files(_get_affected_files(commit), [r'.*\.json']):
Dale Curtis2975c432011-05-03 17:25:20 -0700387 try:
388 json.load(open(f))
389 except Exception, e:
Ryan Cui1562fb82011-05-09 11:01:31 -0700390 return HookFailure('Invalid JSON in %s: %s' % (f, e))
Dale Curtis2975c432011-05-03 17:25:20 -0700391
392
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700393def _check_change_has_branch_field(project, commit):
394 """Check for a non-empty 'BRANCH=' field in the commit message."""
395 BRANCH_RE = r'\nBRANCH=\S+'
396
397 if not re.search(BRANCH_RE, _get_commit_desc(commit)):
398 msg = ('Changelist description needs BRANCH field (after first line)\n'
399 'E.g. BRANCH=none or BRANCH=link,snow')
400 return HookFailure(msg)
401
402
Jon Salz3ee59de2012-08-18 13:54:22 +0800403def _run_project_hook_script(script, project, commit):
404 """Runs a project hook script.
405
406 The script is run with the following environment variables set:
407 PRESUBMIT_PROJECT: The affected project
408 PRESUBMIT_COMMIT: The affected commit
409 PRESUBMIT_FILES: A newline-separated list of affected files
410
411 The script is considered to fail if the exit code is non-zero. It should
412 write an error message to stdout.
413 """
414 env = dict(os.environ)
415 env['PRESUBMIT_PROJECT'] = project
416 env['PRESUBMIT_COMMIT'] = commit
417
418 # Put affected files in an environment variable
419 files = _get_affected_files(commit)
420 env['PRESUBMIT_FILES'] = '\n'.join(files)
421
422 process = subprocess.Popen(script, env=env, shell=True,
423 stdin=open(os.devnull),
Jon Salz7b618af2012-08-31 06:03:16 +0800424 stdout=subprocess.PIPE,
425 stderr=subprocess.STDOUT)
Jon Salz3ee59de2012-08-18 13:54:22 +0800426 stdout, _ = process.communicate()
427 if process.wait():
Jon Salz7b618af2012-08-31 06:03:16 +0800428 if stdout:
429 stdout = re.sub('(?m)^', ' ', stdout)
430 return HookFailure('Hook script "%s" failed with code %d%s' %
Jon Salz3ee59de2012-08-18 13:54:22 +0800431 (script, process.returncode,
432 ':\n' + stdout if stdout else ''))
433
434
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700435# Base
436
Ryan Cui1562fb82011-05-09 11:01:31 -0700437
Ryan Cui9b651632011-05-11 11:38:58 -0700438# A list of hooks that are not project-specific
439_COMMON_HOOKS = [
440 _check_change_has_bug_field,
441 _check_change_has_test_field,
442 _check_change_has_proper_changeid,
443 _check_no_stray_whitespace,
444 _check_no_long_lines,
445 _check_license,
446 _check_no_tabs,
447]
Ryan Cuiec4d6332011-05-02 14:15:25 -0700448
Ryan Cui1562fb82011-05-09 11:01:31 -0700449
Ryan Cui9b651632011-05-11 11:38:58 -0700450# A dictionary of project-specific hooks(callbacks), indexed by project name.
451# dict[project] = [callback1, callback2]
452_PROJECT_SPECIFIC_HOOKS = {
Olof Johanssona96810f2012-09-04 16:20:03 -0700453 "chromiumos/third_party/kernel": [_run_checkpatch, _kernel_configcheck],
454 "chromiumos/third_party/kernel-next": [_run_checkpatch,
455 _kernel_configcheck],
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700456 "chromiumos/third_party/u-boot": [_run_checkpatch_no_tree,
457 _check_change_has_branch_field],
458 "chromiumos/platform/ec": [_run_checkpatch_no_tree,
459 _check_change_has_branch_field],
460 "chromeos/platform/ec-private": [_run_checkpatch_no_tree,
461 _check_change_has_branch_field],
462 "chromeos/third_party/coreboot": [_check_change_has_branch_field],
Puneet Kumar57b9c092012-08-14 18:58:29 -0700463 "chromeos/third_party/intel-framework": [_check_change_has_branch_field],
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700464 "chromiumos/platform/vboot_reference": [_check_change_has_branch_field],
465 "chromiumos/platform/mosys": [_check_change_has_branch_field],
466 "chromiumos/third_party/flashrom": [_check_change_has_branch_field],
Dale Curtis2975c432011-05-03 17:25:20 -0700467 "chromeos/autotest-tools": [_run_json_check],
Ryan Cui9b651632011-05-11 11:38:58 -0700468}
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700469
Ryan Cui1562fb82011-05-09 11:01:31 -0700470
Ryan Cui9b651632011-05-11 11:38:58 -0700471# A dictionary of flags (keys) that can appear in the config file, and the hook
472# that the flag disables (value)
473_DISABLE_FLAGS = {
474 'stray_whitespace_check': _check_no_stray_whitespace,
475 'long_line_check': _check_no_long_lines,
476 'cros_license_check': _check_license,
477 'tab_check': _check_no_tabs,
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700478 'branch_check': _check_change_has_branch_field,
Ryan Cui9b651632011-05-11 11:38:58 -0700479}
480
481
Jon Salz3ee59de2012-08-18 13:54:22 +0800482def _get_disabled_hooks(config):
Ryan Cui9b651632011-05-11 11:38:58 -0700483 """Returns a set of hooks disabled by the current project's config file.
484
485 Expects to be called within the project root.
Jon Salz3ee59de2012-08-18 13:54:22 +0800486
487 Args:
488 config: A ConfigParser for the project's config file.
Ryan Cui9b651632011-05-11 11:38:58 -0700489 """
490 SECTION = 'Hook Overrides'
Jon Salz3ee59de2012-08-18 13:54:22 +0800491 if not config.has_section(SECTION):
492 return set()
Ryan Cui9b651632011-05-11 11:38:58 -0700493
494 disable_flags = []
Jon Salz3ee59de2012-08-18 13:54:22 +0800495 for flag in config.options(SECTION):
Ryan Cui9b651632011-05-11 11:38:58 -0700496 try:
497 if not config.getboolean(SECTION, flag): disable_flags.append(flag)
498 except ValueError as e:
499 msg = "Error parsing flag \'%s\' in %s file - " % (flag, _CONFIG_FILE)
500 print msg + str(e)
501
502 disabled_keys = set(_DISABLE_FLAGS.iterkeys()).intersection(disable_flags)
503 return set([_DISABLE_FLAGS[key] for key in disabled_keys])
504
505
Jon Salz3ee59de2012-08-18 13:54:22 +0800506def _get_project_hook_scripts(config):
507 """Returns a list of project-specific hook scripts.
508
509 Args:
510 config: A ConfigParser for the project's config file.
511 """
512 SECTION = 'Hook Scripts'
513 if not config.has_section(SECTION):
514 return []
515
516 hook_names_values = config.items(SECTION)
517 hook_names_values.sort(key=lambda x: x[0])
518 return [x[1] for x in hook_names_values]
519
520
Ryan Cui9b651632011-05-11 11:38:58 -0700521def _get_project_hooks(project):
522 """Returns a list of hooks that need to be run for a project.
523
524 Expects to be called from within the project root.
525 """
Jon Salz3ee59de2012-08-18 13:54:22 +0800526 config = ConfigParser.RawConfigParser()
527 try:
528 config.read(_CONFIG_FILE)
529 except ConfigParser.Error:
530 # Just use an empty config file
531 config = ConfigParser.RawConfigParser()
532
533 disabled_hooks = _get_disabled_hooks(config)
Ryan Cui9b651632011-05-11 11:38:58 -0700534 hooks = [hook for hook in _COMMON_HOOKS if hook not in disabled_hooks]
535
536 if project in _PROJECT_SPECIFIC_HOOKS:
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700537 hooks.extend(hook for hook in _PROJECT_SPECIFIC_HOOKS[project]
538 if hook not in disabled_hooks)
Ryan Cui9b651632011-05-11 11:38:58 -0700539
Jon Salz3ee59de2012-08-18 13:54:22 +0800540 for script in _get_project_hook_scripts(config):
541 hooks.append(functools.partial(_run_project_hook_script, script))
542
Ryan Cui9b651632011-05-11 11:38:58 -0700543 return hooks
544
545
Doug Anderson44a644f2011-11-02 10:37:37 -0700546def _run_project_hooks(project, proj_dir=None):
Ryan Cui1562fb82011-05-09 11:01:31 -0700547 """For each project run its project specific hook from the hooks dictionary.
548
549 Args:
Doug Anderson44a644f2011-11-02 10:37:37 -0700550 project: The name of project to run hooks for.
551 proj_dir: If non-None, this is the directory the project is in. If None,
552 we'll ask repo.
Ryan Cui1562fb82011-05-09 11:01:31 -0700553
554 Returns:
555 Boolean value of whether any errors were ecountered while running the hooks.
556 """
Doug Anderson44a644f2011-11-02 10:37:37 -0700557 if proj_dir is None:
558 proj_dir = _run_command(['repo', 'forall', project, '-c', 'pwd']).strip()
559
Ryan Cuiec4d6332011-05-02 14:15:25 -0700560 pwd = os.getcwd()
561 # hooks assume they are run from the root of the project
562 os.chdir(proj_dir)
563
Ryan Cuifa55df52011-05-06 11:16:55 -0700564 try:
565 commit_list = _get_commits()
Don Garrettdba548a2011-05-05 15:17:14 -0700566 except VerifyException as e:
Ryan Cui1562fb82011-05-09 11:01:31 -0700567 PrintErrorForProject(project, HookFailure(str(e)))
568 os.chdir(pwd)
569 return True
Ryan Cuifa55df52011-05-06 11:16:55 -0700570
Ryan Cui9b651632011-05-11 11:38:58 -0700571 hooks = _get_project_hooks(project)
Ryan Cui1562fb82011-05-09 11:01:31 -0700572 error_found = False
Ryan Cuifa55df52011-05-06 11:16:55 -0700573 for commit in commit_list:
Ryan Cui1562fb82011-05-09 11:01:31 -0700574 error_list = []
Ryan Cui9b651632011-05-11 11:38:58 -0700575 for hook in hooks:
Ryan Cui1562fb82011-05-09 11:01:31 -0700576 hook_error = hook(project, commit)
577 if hook_error:
578 error_list.append(hook_error)
579 error_found = True
580 if error_list:
581 PrintErrorsForCommit(project, commit, _get_commit_desc(commit),
582 error_list)
Don Garrettdba548a2011-05-05 15:17:14 -0700583
Ryan Cuiec4d6332011-05-02 14:15:25 -0700584 os.chdir(pwd)
Ryan Cui1562fb82011-05-09 11:01:31 -0700585 return error_found
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700586
587# Main
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -0700588
Ryan Cui1562fb82011-05-09 11:01:31 -0700589
Anush Elangovan63afad72011-03-23 00:41:27 -0700590def main(project_list, **kwargs):
Doug Anderson06456632012-01-05 11:02:14 -0800591 """Main function invoked directly by repo.
592
593 This function will exit directly upon error so that repo doesn't print some
594 obscure error message.
595
596 Args:
597 project_list: List of projects to run on.
598 kwargs: Leave this here for forward-compatibility.
599 """
Ryan Cui1562fb82011-05-09 11:01:31 -0700600 found_error = False
601 for project in project_list:
Ryan Cui9b651632011-05-11 11:38:58 -0700602 if _run_project_hooks(project):
Ryan Cui1562fb82011-05-09 11:01:31 -0700603 found_error = True
604
605 if (found_error):
606 msg = ('Preupload failed due to errors in project(s). HINTS:\n'
Ryan Cui9b651632011-05-11 11:38:58 -0700607 '- To disable some source style checks, and for other hints, see '
608 '<checkout_dir>/src/repohooks/README\n'
609 '- To upload only current project, run \'repo upload .\'')
Ryan Cui1562fb82011-05-09 11:01:31 -0700610 print >> sys.stderr, msg
Don Garrettdba548a2011-05-05 15:17:14 -0700611 sys.exit(1)
Anush Elangovan63afad72011-03-23 00:41:27 -0700612
Ryan Cui1562fb82011-05-09 11:01:31 -0700613
Doug Anderson44a644f2011-11-02 10:37:37 -0700614def _identify_project(path):
615 """Identify the repo project associated with the given path.
616
617 Returns:
618 A string indicating what project is associated with the path passed in or
619 a blank string upon failure.
620 """
621 return _run_command(['repo', 'forall', '.', '-c', 'echo ${REPO_PROJECT}'],
622 stderr=subprocess.PIPE, cwd=path).strip()
623
624
625def direct_main(args, verbose=False):
626 """Run hooks directly (outside of the context of repo).
627
628 # Setup for doctests below.
629 # ...note that some tests assume that running pre-upload on this CWD is fine.
630 # TODO: Use mock and actually mock out _run_project_hooks() for tests.
631 >>> mydir = os.path.dirname(os.path.abspath(__file__))
632 >>> olddir = os.getcwd()
633
634 # OK to run w/ no arugments; will run with CWD.
635 >>> os.chdir(mydir)
636 >>> direct_main(['prog_name'], verbose=True)
637 Running hooks on chromiumos/repohooks
638 0
639 >>> os.chdir(olddir)
640
641 # Run specifying a dir
642 >>> direct_main(['prog_name', '--dir=%s' % mydir], verbose=True)
643 Running hooks on chromiumos/repohooks
644 0
645
646 # Not a problem to use a bogus project; we'll just get default settings.
647 >>> direct_main(['prog_name', '--dir=%s' % mydir, '--project=X'],verbose=True)
648 Running hooks on X
649 0
650
651 # Run with project but no dir
652 >>> os.chdir(mydir)
653 >>> direct_main(['prog_name', '--project=X'], verbose=True)
654 Running hooks on X
655 0
656 >>> os.chdir(olddir)
657
658 # Try with a non-git CWD
659 >>> os.chdir('/tmp')
660 >>> direct_main(['prog_name'])
661 Traceback (most recent call last):
662 ...
663 BadInvocation: The current directory is not part of a git project.
664
665 # Check various bad arguments...
666 >>> direct_main(['prog_name', 'bogus'])
667 Traceback (most recent call last):
668 ...
669 BadInvocation: Unexpected arguments: bogus
670 >>> direct_main(['prog_name', '--project=bogus', '--dir=bogusdir'])
671 Traceback (most recent call last):
672 ...
673 BadInvocation: Invalid dir: bogusdir
674 >>> direct_main(['prog_name', '--project=bogus', '--dir=/tmp'])
675 Traceback (most recent call last):
676 ...
677 BadInvocation: Not a git directory: /tmp
678
679 Args:
680 args: The value of sys.argv
681
682 Returns:
683 0 if no pre-upload failures, 1 if failures.
684
685 Raises:
686 BadInvocation: On some types of invocation errors.
687 """
688 desc = 'Run Chromium OS pre-upload hooks on changes compared to upstream.'
689 parser = optparse.OptionParser(description=desc)
690
691 parser.add_option('--dir', default=None,
692 help='The directory that the project lives in. If not '
693 'specified, use the git project root based on the cwd.')
694 parser.add_option('--project', default=None,
695 help='The project repo path; this can affect how the hooks '
696 'get run, since some hooks are project-specific. For '
697 'chromite this is chromiumos/chromite. If not specified, '
698 'the repo tool will be used to figure this out based on '
699 'the dir.')
700
701 opts, args = parser.parse_args(args[1:])
702
703 if args:
704 raise BadInvocation('Unexpected arguments: %s' % ' '.join(args))
705
706 # Check/normlaize git dir; if unspecified, we'll use the root of the git
707 # project from CWD
708 if opts.dir is None:
709 git_dir = _run_command(['git', 'rev-parse', '--git-dir'],
710 stderr=subprocess.PIPE).strip()
711 if not git_dir:
712 raise BadInvocation('The current directory is not part of a git project.')
713 opts.dir = os.path.dirname(os.path.abspath(git_dir))
714 elif not os.path.isdir(opts.dir):
715 raise BadInvocation('Invalid dir: %s' % opts.dir)
716 elif not os.path.isdir(os.path.join(opts.dir, '.git')):
717 raise BadInvocation('Not a git directory: %s' % opts.dir)
718
719 # Identify the project if it wasn't specified; this _requires_ the repo
720 # tool to be installed and for the project to be part of a repo checkout.
721 if not opts.project:
722 opts.project = _identify_project(opts.dir)
723 if not opts.project:
724 raise BadInvocation("Repo couldn't identify the project of %s" % opts.dir)
725
726 if verbose:
727 print "Running hooks on %s" % (opts.project)
728
729 found_error = _run_project_hooks(opts.project, proj_dir=opts.dir)
730 if found_error:
731 return 1
732 return 0
733
734
735def _test():
736 """Run any built-in tests."""
737 import doctest
738 doctest.testmod()
739
740
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -0700741if __name__ == '__main__':
Doug Anderson44a644f2011-11-02 10:37:37 -0700742 if sys.argv[1:2] == ["--test"]:
743 _test()
744 exit_code = 0
745 else:
746 prog_name = os.path.basename(sys.argv[0])
747 try:
748 exit_code = direct_main(sys.argv)
749 except BadInvocation, e:
750 print >>sys.stderr, "%s: %s" % (prog_name, str(e))
751 exit_code = 1
752 sys.exit(exit_code)