blob: c2b2a7fdd819dccbd3ff9b610b209cb1ad656a0b [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
David Hendricks4c018e72013-02-06 13:46:38 -080012import socket
Mandeep Singh Bainesa7ffa4b2011-05-03 11:37:02 -070013import sys
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070014import subprocess
15
Ryan Cui1562fb82011-05-09 11:01:31 -070016from errors import (VerifyException, HookFailure, PrintErrorForProject,
17 PrintErrorsForCommit)
Ryan Cuiec4d6332011-05-02 14:15:25 -070018
David Jamesc3b68b32013-04-03 09:17:03 -070019# If repo imports us, the __name__ will be __builtin__, and the wrapper will
20# be in $CHROMEOS_CHECKOUT/.repo/repo/main.py, so we need to go two directories
21# up. The same logic also happens to work if we're executed directly.
22if __name__ in ('__builtin__', '__main__'):
23 sys.path.insert(0, os.path.join(os.path.dirname(sys.argv[0]), '..', '..'))
24
25from chromite.lib import patch
26
Ryan Cuiec4d6332011-05-02 14:15:25 -070027
28COMMON_INCLUDED_PATHS = [
29 # C++ and friends
30 r".*\.c$", r".*\.cc$", r".*\.cpp$", r".*\.h$", r".*\.m$", r".*\.mm$",
31 r".*\.inl$", r".*\.asm$", r".*\.hxx$", r".*\.hpp$", r".*\.s$", r".*\.S$",
32 # Scripts
33 r".*\.js$", r".*\.py$", r".*\.sh$", r".*\.rb$", r".*\.pl$", r".*\.pm$",
34 # No extension at all, note that ALL CAPS files are black listed in
35 # COMMON_EXCLUDED_LIST below.
David Hendricks0af30eb2013-02-05 11:35:56 -080036 r"(^|.*[\\\/])[^.]+$",
Ryan Cuiec4d6332011-05-02 14:15:25 -070037 # Other
38 r".*\.java$", r".*\.mk$", r".*\.am$",
39]
40
Ryan Cui1562fb82011-05-09 11:01:31 -070041
Ryan Cuiec4d6332011-05-02 14:15:25 -070042COMMON_EXCLUDED_PATHS = [
Ryan Cui31e0c172011-05-04 21:00:45 -070043 # avoid doing source file checks for kernel
44 r"/src/third_party/kernel/",
45 r"/src/third_party/kernel-next/",
Paul Taysomf8b6e012011-05-09 14:32:42 -070046 r"/src/third_party/ktop/",
47 r"/src/third_party/punybench/",
Ryan Cuiec4d6332011-05-02 14:15:25 -070048 r".*\bexperimental[\\\/].*",
49 r".*\b[A-Z0-9_]{2,}$",
50 r".*[\\\/]debian[\\\/]rules$",
Brian Harringd780d602011-10-18 16:48:08 -070051 # for ebuild trees, ignore any caches and manifest data
52 r".*/Manifest$",
53 r".*/metadata/[^/]*cache[^/]*/[^/]+/[^/]+$",
Doug Anderson5bfb6792011-10-25 16:45:41 -070054
55 # ignore profiles data (like overlay-tegra2/profiles)
56 r".*/overlay-.*/profiles/.*",
Andrew de los Reyes0e679922012-05-02 11:42:54 -070057 # ignore minified js and jquery
58 r".*\.min\.js",
59 r".*jquery.*\.js",
Ryan Cuiec4d6332011-05-02 14:15:25 -070060]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070061
Ryan Cui1562fb82011-05-09 11:01:31 -070062
Ryan Cui9b651632011-05-11 11:38:58 -070063_CONFIG_FILE = 'PRESUBMIT.cfg'
64
65
Doug Anderson44a644f2011-11-02 10:37:37 -070066# Exceptions
67
68
69class BadInvocation(Exception):
70 """An Exception indicating a bad invocation of the program."""
71 pass
72
73
Ryan Cui1562fb82011-05-09 11:01:31 -070074# General Helpers
75
Sean Paulba01d402011-05-05 11:36:23 -040076
Doug Anderson44a644f2011-11-02 10:37:37 -070077def _run_command(cmd, cwd=None, stderr=None):
78 """Executes the passed in command and returns raw stdout output.
79
80 Args:
81 cmd: The command to run; should be a list of strings.
82 cwd: The directory to switch to for running the command.
83 stderr: Can be one of None (print stderr to console), subprocess.STDOUT
84 (combine stderr with stdout), or subprocess.PIPE (ignore stderr).
85
86 Returns:
87 The standard out from the process.
88 """
89 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=stderr, cwd=cwd)
90 return p.communicate()[0]
Ryan Cui72834d12011-05-05 14:51:33 -070091
Ryan Cui1562fb82011-05-09 11:01:31 -070092
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070093def _get_hooks_dir():
Ryan Cuiec4d6332011-05-02 14:15:25 -070094 """Returns the absolute path to the repohooks directory."""
Doug Anderson44a644f2011-11-02 10:37:37 -070095 if __name__ == '__main__':
96 # Works when file is run on its own (__file__ is defined)...
97 return os.path.abspath(os.path.dirname(__file__))
98 else:
99 # We need to do this when we're run through repo. Since repo executes
100 # us with execfile(), we don't get __file__ defined.
101 cmd = ['repo', 'forall', 'chromiumos/repohooks', '-c', 'pwd']
102 return _run_command(cmd).strip()
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700103
Ryan Cui1562fb82011-05-09 11:01:31 -0700104
Ryan Cuiec4d6332011-05-02 14:15:25 -0700105def _match_regex_list(subject, expressions):
106 """Try to match a list of regular expressions to a string.
107
108 Args:
109 subject: The string to match regexes on
110 expressions: A list of regular expressions to check for matches with.
111
112 Returns:
113 Whether the passed in subject matches any of the passed in regexes.
114 """
115 for expr in expressions:
116 if (re.search(expr, subject)):
117 return True
118 return False
119
Ryan Cui1562fb82011-05-09 11:01:31 -0700120
Ryan Cuiec4d6332011-05-02 14:15:25 -0700121def _filter_files(files, include_list, exclude_list=[]):
122 """Filter out files based on the conditions passed in.
123
124 Args:
125 files: list of filepaths to filter
126 include_list: list of regex that when matched with a file path will cause it
127 to be added to the output list unless the file is also matched with a
128 regex in the exclude_list.
129 exclude_list: list of regex that when matched with a file will prevent it
130 from being added to the output list, even if it is also matched with a
131 regex in the include_list.
132
133 Returns:
134 A list of filepaths that contain files matched in the include_list and not
135 in the exclude_list.
136 """
137 filtered = []
138 for f in files:
139 if (_match_regex_list(f, include_list) and
140 not _match_regex_list(f, exclude_list)):
141 filtered.append(f)
142 return filtered
143
Ryan Cuiec4d6332011-05-02 14:15:25 -0700144
David Hendricks35030d02013-02-04 17:49:16 -0800145def _verify_header_content(commit, content, fail_msg):
146 """Verify that file headers contain specified content.
147
148 Args:
149 commit: the affected commit.
150 content: the content of the header to be verified.
151 fail_msg: the first message to display in case of failure.
152
153 Returns:
154 The return value of HookFailure().
155 """
156 license_re = re.compile(content, re.MULTILINE)
157 bad_files = []
158 files = _filter_files(_get_affected_files(commit),
159 COMMON_INCLUDED_PATHS,
160 COMMON_EXCLUDED_PATHS)
161
162 for f in files:
Gabe Blackcf3c32c2013-02-27 00:26:13 -0800163 if os.path.exists(f): # Ignore non-existant files
164 contents = open(f).read()
165 if len(contents) == 0: continue # Ignore empty files
166 if not license_re.search(contents):
167 bad_files.append(f)
David Hendricks35030d02013-02-04 17:49:16 -0800168 if bad_files:
169 msg = "%s:\n%s\n%s" % (fail_msg, license_re.pattern,
170 "Found a bad header in these files:")
171 return HookFailure(msg, bad_files)
172
173
Ryan Cuiec4d6332011-05-02 14:15:25 -0700174# Git Helpers
Ryan Cui1562fb82011-05-09 11:01:31 -0700175
176
Ryan Cui4725d952011-05-05 15:41:19 -0700177def _get_upstream_branch():
178 """Returns the upstream tracking branch of the current branch.
179
180 Raises:
181 Error if there is no tracking branch
182 """
183 current_branch = _run_command(['git', 'symbolic-ref', 'HEAD']).strip()
184 current_branch = current_branch.replace('refs/heads/', '')
185 if not current_branch:
Ryan Cui1562fb82011-05-09 11:01:31 -0700186 raise VerifyException('Need to be on a tracking branch')
Ryan Cui4725d952011-05-05 15:41:19 -0700187
188 cfg_option = 'branch.' + current_branch + '.%s'
189 full_upstream = _run_command(['git', 'config', cfg_option % 'merge']).strip()
190 remote = _run_command(['git', 'config', cfg_option % 'remote']).strip()
191 if not remote or not full_upstream:
Ryan Cui1562fb82011-05-09 11:01:31 -0700192 raise VerifyException('Need to be on a tracking branch')
Ryan Cui4725d952011-05-05 15:41:19 -0700193
194 return full_upstream.replace('heads', 'remotes/' + remote)
195
Ryan Cui1562fb82011-05-09 11:01:31 -0700196
Che-Liang Chiou5ce2d7b2013-03-22 18:47:55 -0700197def _get_patch(commit):
198 """Returns the patch for this commit."""
199 return _run_command(['git', 'format-patch', '--stdout', '-1', commit])
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700200
Ryan Cui1562fb82011-05-09 11:01:31 -0700201
Jon Salz98255932012-08-18 14:48:02 +0800202def _try_utf8_decode(data):
203 """Attempts to decode a string as UTF-8.
204
205 Returns:
206 The decoded Unicode object, or the original string if parsing fails.
207 """
208 try:
209 return unicode(data, 'utf-8', 'strict')
210 except UnicodeDecodeError:
211 return data
212
213
Ryan Cuiec4d6332011-05-02 14:15:25 -0700214def _get_file_diff(file, commit):
215 """Returns a list of (linenum, lines) tuples that the commit touched."""
Ryan Cui72834d12011-05-05 14:51:33 -0700216 output = _run_command(['git', 'show', '-p', '--no-ext-diff', commit, file])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700217
218 new_lines = []
219 line_num = 0
220 for line in output.splitlines():
221 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
222 if m:
223 line_num = int(m.groups(1)[0])
224 continue
225 if line.startswith('+') and not line.startswith('++'):
Jon Salz98255932012-08-18 14:48:02 +0800226 new_lines.append((line_num, _try_utf8_decode(line[1:])))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700227 if not line.startswith('-'):
228 line_num += 1
229 return new_lines
230
Ryan Cui1562fb82011-05-09 11:01:31 -0700231
Ryan Cuiec4d6332011-05-02 14:15:25 -0700232def _get_affected_files(commit):
233 """Returns list of absolute filepaths that were modified/added."""
Ryan Cui72834d12011-05-05 14:51:33 -0700234 output = _run_command(['git', 'diff', '--name-status', commit + '^!'])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700235 files = []
236 for statusline in output.splitlines():
237 m = re.match('^(\w)+\t(.+)$', statusline.rstrip())
238 # Ignore deleted files, and return absolute paths of files
239 if (m.group(1)[0] != 'D'):
240 pwd = os.getcwd()
241 files.append(os.path.join(pwd, m.group(2)))
242 return files
243
Ryan Cui1562fb82011-05-09 11:01:31 -0700244
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700245def _get_commits():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700246 """Returns a list of commits for this review."""
Ryan Cui4725d952011-05-05 15:41:19 -0700247 cmd = ['git', 'log', '%s..' % _get_upstream_branch(), '--format=%H']
Ryan Cui72834d12011-05-05 14:51:33 -0700248 return _run_command(cmd).split()
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700249
Ryan Cui1562fb82011-05-09 11:01:31 -0700250
Ryan Cuiec4d6332011-05-02 14:15:25 -0700251def _get_commit_desc(commit):
252 """Returns the full commit message of a commit."""
Sean Paul23a2c582011-05-06 13:10:44 -0400253 return _run_command(['git', 'log', '--format=%s%n%n%b', commit + '^!'])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700254
255
256# Common Hooks
257
Ryan Cui1562fb82011-05-09 11:01:31 -0700258
Ryan Cuiec4d6332011-05-02 14:15:25 -0700259def _check_no_long_lines(project, commit):
260 """Checks that there aren't any lines longer than maxlen characters in any of
261 the text files to be submitted.
262 """
263 MAX_LEN = 80
Jon Salz98255932012-08-18 14:48:02 +0800264 SKIP_REGEXP = re.compile('|'.join([
265 r'https?://',
266 r'^#\s*(define|include|import|pragma|if|endif)\b']))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700267
268 errors = []
269 files = _filter_files(_get_affected_files(commit),
270 COMMON_INCLUDED_PATHS,
271 COMMON_EXCLUDED_PATHS)
272
273 for afile in files:
274 for line_num, line in _get_file_diff(afile, commit):
275 # Allow certain lines to exceed the maxlen rule.
Jon Salz98255932012-08-18 14:48:02 +0800276 if (len(line) <= MAX_LEN or SKIP_REGEXP.search(line)):
277 continue
278
279 errors.append('%s, line %s, %s chars' % (afile, line_num, len(line)))
280 if len(errors) == 5: # Just show the first 5 errors.
281 break
Ryan Cuiec4d6332011-05-02 14:15:25 -0700282
283 if errors:
284 msg = 'Found lines longer than %s characters (first 5 shown):' % MAX_LEN
Ryan Cui1562fb82011-05-09 11:01:31 -0700285 return HookFailure(msg, errors)
286
Ryan Cuiec4d6332011-05-02 14:15:25 -0700287
288def _check_no_stray_whitespace(project, commit):
289 """Checks that there is no stray whitespace at source lines end."""
290 errors = []
291 files = _filter_files(_get_affected_files(commit),
292 COMMON_INCLUDED_PATHS,
293 COMMON_EXCLUDED_PATHS)
294
295 for afile in files:
296 for line_num, line in _get_file_diff(afile, commit):
297 if line.rstrip() != line:
298 errors.append('%s, line %s' % (afile, line_num))
299 if errors:
Ryan Cui1562fb82011-05-09 11:01:31 -0700300 return HookFailure('Found line ending with white space in:', errors)
301
Ryan Cuiec4d6332011-05-02 14:15:25 -0700302
303def _check_no_tabs(project, commit):
304 """Checks there are no unexpanded tabs."""
305 TAB_OK_PATHS = [
Ryan Cui31e0c172011-05-04 21:00:45 -0700306 r"/src/third_party/u-boot/",
Ryan Cuiec4d6332011-05-02 14:15:25 -0700307 r".*\.ebuild$",
308 r".*\.eclass$",
Elly Jones5ab34192011-11-15 14:57:06 -0500309 r".*/[M|m]akefile$",
310 r".*\.mk$"
Ryan Cuiec4d6332011-05-02 14:15:25 -0700311 ]
312
313 errors = []
314 files = _filter_files(_get_affected_files(commit),
315 COMMON_INCLUDED_PATHS,
316 COMMON_EXCLUDED_PATHS + TAB_OK_PATHS)
317
318 for afile in files:
319 for line_num, line in _get_file_diff(afile, commit):
320 if '\t' in line:
321 errors.append('%s, line %s' % (afile, line_num))
322 if errors:
Ryan Cui1562fb82011-05-09 11:01:31 -0700323 return HookFailure('Found a tab character in:', errors)
324
Ryan Cuiec4d6332011-05-02 14:15:25 -0700325
326def _check_change_has_test_field(project, commit):
327 """Check for a non-empty 'TEST=' field in the commit message."""
David McMahon8f6553e2011-06-10 15:46:36 -0700328 TEST_RE = r'\nTEST=\S+'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700329
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700330 if not re.search(TEST_RE, _get_commit_desc(commit)):
Ryan Cui1562fb82011-05-09 11:01:31 -0700331 msg = 'Changelist description needs TEST field (after first line)'
332 return HookFailure(msg)
333
Ryan Cuiec4d6332011-05-02 14:15:25 -0700334
David Jamesc3b68b32013-04-03 09:17:03 -0700335def _check_change_has_valid_cq_depend(project, commit):
336 """Check for a correctly formatted CQ-DEPEND field in the commit message."""
337 msg = 'Changelist has invalid CQ-DEPEND target.'
338 example = 'Example: CQ-DEPEND=CL:1234, CL:2345'
339 try:
340 patch.GetPaladinDeps(_get_commit_desc(commit))
341 except ValueError as ex:
342 return HookFailure(msg, [example, str(ex)])
343
344
Ryan Cuiec4d6332011-05-02 14:15:25 -0700345def _check_change_has_bug_field(project, commit):
David McMahon8f6553e2011-06-10 15:46:36 -0700346 """Check for a correctly formatted 'BUG=' field in the commit message."""
David James5c0073d2013-04-03 08:48:52 -0700347 OLD_BUG_RE = r'\nBUG=.*chromium-os'
348 if re.search(OLD_BUG_RE, _get_commit_desc(commit)):
349 msg = ('The chromium-os bug tracker is now deprecated. Please use\n'
350 'the chromium tracker in your BUG= line now.')
351 return HookFailure(msg)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700352
David James5c0073d2013-04-03 08:48:52 -0700353 BUG_RE = r'\nBUG=([Nn]one|(chrome-os-partner|chromium):\d+)'
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700354 if not re.search(BUG_RE, _get_commit_desc(commit)):
David McMahon8f6553e2011-06-10 15:46:36 -0700355 msg = ('Changelist description needs BUG field (after first line):\n'
David James5c0073d2013-04-03 08:48:52 -0700356 'BUG=chromium:9999 (for public tracker)\n'
David McMahon8f6553e2011-06-10 15:46:36 -0700357 'BUG=chrome-os-partner:9999 (for partner tracker)\n'
358 'BUG=None')
Ryan Cui1562fb82011-05-09 11:01:31 -0700359 return HookFailure(msg)
360
Ryan Cuiec4d6332011-05-02 14:15:25 -0700361
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700362def _check_change_has_proper_changeid(project, commit):
363 """Verify that Change-ID is present in last paragraph of commit message."""
364 desc = _get_commit_desc(commit)
365 loc = desc.rfind('\nChange-Id:')
366 if loc == -1 or re.search('\n\s*\n\s*\S+', desc[loc:]):
Ryan Cui1562fb82011-05-09 11:01:31 -0700367 return HookFailure('Change-Id must be in last paragraph of description.')
368
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700369
Ryan Cuiec4d6332011-05-02 14:15:25 -0700370def _check_license(project, commit):
371 """Verifies the license header."""
372 LICENSE_HEADER = (
David Hendricks0af30eb2013-02-05 11:35:56 -0800373 r".* Copyright \(c\) 20[-0-9]{2,7} The Chromium OS Authors\. All rights "
Ryan Cuiec4d6332011-05-02 14:15:25 -0700374 r"reserved\." "\n"
David Hendricks0af30eb2013-02-05 11:35:56 -0800375 r".* Use of this source code is governed by a BSD-style license that can "
Ryan Cuiec4d6332011-05-02 14:15:25 -0700376 "be\n"
David Hendricks0af30eb2013-02-05 11:35:56 -0800377 r".* found in the LICENSE file\."
Ryan Cuiec4d6332011-05-02 14:15:25 -0700378 "\n"
379 )
David Hendricks35030d02013-02-04 17:49:16 -0800380 FAIL_MSG = "License must match"
Ryan Cuiec4d6332011-05-02 14:15:25 -0700381
David Hendricks35030d02013-02-04 17:49:16 -0800382 return _verify_header_content(commit, LICENSE_HEADER, FAIL_MSG)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700383
384
David Hendricksa0e310d2013-02-04 17:51:55 -0800385def _check_google_copyright(project, commit):
386 """Verifies Google Inc. as copyright holder."""
387 LICENSE_HEADER = (
388 r".* Copyright 20[-0-9]{2,7} Google Inc\."
389 )
390 FAIL_MSG = "Copyright must match"
391
David Hendricks4c018e72013-02-06 13:46:38 -0800392 # Avoid blocking partners and external contributors.
393 fqdn = socket.getfqdn()
394 if not fqdn.endswith(".corp.google.com"):
395 return None
396
David Hendricksa0e310d2013-02-04 17:51:55 -0800397 return _verify_header_content(commit, LICENSE_HEADER, FAIL_MSG)
398
399
Ryan Cuiec4d6332011-05-02 14:15:25 -0700400# Project-specific hooks
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700401
Ryan Cui1562fb82011-05-09 11:01:31 -0700402
Anton Staaf815d6852011-08-22 10:08:45 -0700403def _run_checkpatch(project, commit, options=[]):
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700404 """Runs checkpatch.pl on the given project"""
405 hooks_dir = _get_hooks_dir()
Anton Staaf815d6852011-08-22 10:08:45 -0700406 cmd = ['%s/checkpatch.pl' % hooks_dir] + options + ['-']
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700407 p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Che-Liang Chiou5ce2d7b2013-03-22 18:47:55 -0700408 output = p.communicate(_get_patch(commit))[0]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700409 if p.returncode:
Ryan Cui1562fb82011-05-09 11:01:31 -0700410 return HookFailure('checkpatch.pl errors/warnings\n\n' + output)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700411
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700412
Anton Staaf815d6852011-08-22 10:08:45 -0700413def _run_checkpatch_no_tree(project, commit):
414 return _run_checkpatch(project, commit, ['--no-tree'])
415
Olof Johanssona96810f2012-09-04 16:20:03 -0700416def _kernel_configcheck(project, commit):
417 """Makes sure kernel config changes are not mixed with code changes"""
418 files = _get_affected_files(commit)
419 if not len(_filter_files(files, [r'chromeos/config'])) in [0, len(files)]:
420 return HookFailure('Changes to chromeos/config/ and regular files must '
421 'be in separate commits:\n%s' % '\n'.join(files))
Anton Staaf815d6852011-08-22 10:08:45 -0700422
Dale Curtis2975c432011-05-03 17:25:20 -0700423def _run_json_check(project, commit):
424 """Checks that all JSON files are syntactically valid."""
Dale Curtisa039cfd2011-05-04 12:01:05 -0700425 for f in _filter_files(_get_affected_files(commit), [r'.*\.json']):
Dale Curtis2975c432011-05-03 17:25:20 -0700426 try:
427 json.load(open(f))
428 except Exception, e:
Ryan Cui1562fb82011-05-09 11:01:31 -0700429 return HookFailure('Invalid JSON in %s: %s' % (f, e))
Dale Curtis2975c432011-05-03 17:25:20 -0700430
431
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700432def _check_change_has_branch_field(project, commit):
433 """Check for a non-empty 'BRANCH=' field in the commit message."""
434 BRANCH_RE = r'\nBRANCH=\S+'
435
436 if not re.search(BRANCH_RE, _get_commit_desc(commit)):
437 msg = ('Changelist description needs BRANCH field (after first line)\n'
438 'E.g. BRANCH=none or BRANCH=link,snow')
439 return HookFailure(msg)
440
441
Jon Salz3ee59de2012-08-18 13:54:22 +0800442def _run_project_hook_script(script, project, commit):
443 """Runs a project hook script.
444
445 The script is run with the following environment variables set:
446 PRESUBMIT_PROJECT: The affected project
447 PRESUBMIT_COMMIT: The affected commit
448 PRESUBMIT_FILES: A newline-separated list of affected files
449
450 The script is considered to fail if the exit code is non-zero. It should
451 write an error message to stdout.
452 """
453 env = dict(os.environ)
454 env['PRESUBMIT_PROJECT'] = project
455 env['PRESUBMIT_COMMIT'] = commit
456
457 # Put affected files in an environment variable
458 files = _get_affected_files(commit)
459 env['PRESUBMIT_FILES'] = '\n'.join(files)
460
461 process = subprocess.Popen(script, env=env, shell=True,
462 stdin=open(os.devnull),
Jon Salz7b618af2012-08-31 06:03:16 +0800463 stdout=subprocess.PIPE,
464 stderr=subprocess.STDOUT)
Jon Salz3ee59de2012-08-18 13:54:22 +0800465 stdout, _ = process.communicate()
466 if process.wait():
Jon Salz7b618af2012-08-31 06:03:16 +0800467 if stdout:
468 stdout = re.sub('(?m)^', ' ', stdout)
469 return HookFailure('Hook script "%s" failed with code %d%s' %
Jon Salz3ee59de2012-08-18 13:54:22 +0800470 (script, process.returncode,
471 ':\n' + stdout if stdout else ''))
472
473
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700474# Base
475
Ryan Cui1562fb82011-05-09 11:01:31 -0700476
Ryan Cui9b651632011-05-11 11:38:58 -0700477# A list of hooks that are not project-specific
478_COMMON_HOOKS = [
479 _check_change_has_bug_field,
David Jamesc3b68b32013-04-03 09:17:03 -0700480 _check_change_has_valid_cq_depend,
Ryan Cui9b651632011-05-11 11:38:58 -0700481 _check_change_has_test_field,
482 _check_change_has_proper_changeid,
483 _check_no_stray_whitespace,
484 _check_no_long_lines,
485 _check_license,
486 _check_no_tabs,
487]
Ryan Cuiec4d6332011-05-02 14:15:25 -0700488
Ryan Cui1562fb82011-05-09 11:01:31 -0700489
Ryan Cui9b651632011-05-11 11:38:58 -0700490# A dictionary of project-specific hooks(callbacks), indexed by project name.
491# dict[project] = [callback1, callback2]
492_PROJECT_SPECIFIC_HOOKS = {
Olof Johanssona96810f2012-09-04 16:20:03 -0700493 "chromiumos/third_party/kernel": [_run_checkpatch, _kernel_configcheck],
494 "chromiumos/third_party/kernel-next": [_run_checkpatch,
495 _kernel_configcheck],
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700496 "chromiumos/third_party/u-boot": [_run_checkpatch_no_tree,
497 _check_change_has_branch_field],
498 "chromiumos/platform/ec": [_run_checkpatch_no_tree,
499 _check_change_has_branch_field],
500 "chromeos/platform/ec-private": [_run_checkpatch_no_tree,
501 _check_change_has_branch_field],
David Hendricks33f77d52013-02-04 17:53:02 -0800502 "chromeos/third_party/coreboot": [_check_change_has_branch_field,
503 _check_google_copyright],
Puneet Kumar57b9c092012-08-14 18:58:29 -0700504 "chromeos/third_party/intel-framework": [_check_change_has_branch_field],
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700505 "chromiumos/platform/vboot_reference": [_check_change_has_branch_field],
506 "chromiumos/platform/mosys": [_check_change_has_branch_field],
507 "chromiumos/third_party/flashrom": [_check_change_has_branch_field],
Dale Curtis2975c432011-05-03 17:25:20 -0700508 "chromeos/autotest-tools": [_run_json_check],
Ryan Cui9b651632011-05-11 11:38:58 -0700509}
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700510
Ryan Cui1562fb82011-05-09 11:01:31 -0700511
Ryan Cui9b651632011-05-11 11:38:58 -0700512# A dictionary of flags (keys) that can appear in the config file, and the hook
513# that the flag disables (value)
514_DISABLE_FLAGS = {
515 'stray_whitespace_check': _check_no_stray_whitespace,
516 'long_line_check': _check_no_long_lines,
517 'cros_license_check': _check_license,
518 'tab_check': _check_no_tabs,
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700519 'branch_check': _check_change_has_branch_field,
Ryan Cui9b651632011-05-11 11:38:58 -0700520}
521
522
Jon Salz3ee59de2012-08-18 13:54:22 +0800523def _get_disabled_hooks(config):
Ryan Cui9b651632011-05-11 11:38:58 -0700524 """Returns a set of hooks disabled by the current project's config file.
525
526 Expects to be called within the project root.
Jon Salz3ee59de2012-08-18 13:54:22 +0800527
528 Args:
529 config: A ConfigParser for the project's config file.
Ryan Cui9b651632011-05-11 11:38:58 -0700530 """
531 SECTION = 'Hook Overrides'
Jon Salz3ee59de2012-08-18 13:54:22 +0800532 if not config.has_section(SECTION):
533 return set()
Ryan Cui9b651632011-05-11 11:38:58 -0700534
535 disable_flags = []
Jon Salz3ee59de2012-08-18 13:54:22 +0800536 for flag in config.options(SECTION):
Ryan Cui9b651632011-05-11 11:38:58 -0700537 try:
538 if not config.getboolean(SECTION, flag): disable_flags.append(flag)
539 except ValueError as e:
540 msg = "Error parsing flag \'%s\' in %s file - " % (flag, _CONFIG_FILE)
541 print msg + str(e)
542
543 disabled_keys = set(_DISABLE_FLAGS.iterkeys()).intersection(disable_flags)
544 return set([_DISABLE_FLAGS[key] for key in disabled_keys])
545
546
Jon Salz3ee59de2012-08-18 13:54:22 +0800547def _get_project_hook_scripts(config):
548 """Returns a list of project-specific hook scripts.
549
550 Args:
551 config: A ConfigParser for the project's config file.
552 """
553 SECTION = 'Hook Scripts'
554 if not config.has_section(SECTION):
555 return []
556
557 hook_names_values = config.items(SECTION)
558 hook_names_values.sort(key=lambda x: x[0])
559 return [x[1] for x in hook_names_values]
560
561
Ryan Cui9b651632011-05-11 11:38:58 -0700562def _get_project_hooks(project):
563 """Returns a list of hooks that need to be run for a project.
564
565 Expects to be called from within the project root.
566 """
Jon Salz3ee59de2012-08-18 13:54:22 +0800567 config = ConfigParser.RawConfigParser()
568 try:
569 config.read(_CONFIG_FILE)
570 except ConfigParser.Error:
571 # Just use an empty config file
572 config = ConfigParser.RawConfigParser()
573
574 disabled_hooks = _get_disabled_hooks(config)
Ryan Cui9b651632011-05-11 11:38:58 -0700575 hooks = [hook for hook in _COMMON_HOOKS if hook not in disabled_hooks]
576
577 if project in _PROJECT_SPECIFIC_HOOKS:
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700578 hooks.extend(hook for hook in _PROJECT_SPECIFIC_HOOKS[project]
579 if hook not in disabled_hooks)
Ryan Cui9b651632011-05-11 11:38:58 -0700580
Jon Salz3ee59de2012-08-18 13:54:22 +0800581 for script in _get_project_hook_scripts(config):
582 hooks.append(functools.partial(_run_project_hook_script, script))
583
Ryan Cui9b651632011-05-11 11:38:58 -0700584 return hooks
585
586
Doug Anderson44a644f2011-11-02 10:37:37 -0700587def _run_project_hooks(project, proj_dir=None):
Ryan Cui1562fb82011-05-09 11:01:31 -0700588 """For each project run its project specific hook from the hooks dictionary.
589
590 Args:
Doug Anderson44a644f2011-11-02 10:37:37 -0700591 project: The name of project to run hooks for.
592 proj_dir: If non-None, this is the directory the project is in. If None,
593 we'll ask repo.
Ryan Cui1562fb82011-05-09 11:01:31 -0700594
595 Returns:
596 Boolean value of whether any errors were ecountered while running the hooks.
597 """
Doug Anderson44a644f2011-11-02 10:37:37 -0700598 if proj_dir is None:
599 proj_dir = _run_command(['repo', 'forall', project, '-c', 'pwd']).strip()
600
Ryan Cuiec4d6332011-05-02 14:15:25 -0700601 pwd = os.getcwd()
602 # hooks assume they are run from the root of the project
603 os.chdir(proj_dir)
604
Ryan Cuifa55df52011-05-06 11:16:55 -0700605 try:
606 commit_list = _get_commits()
Don Garrettdba548a2011-05-05 15:17:14 -0700607 except VerifyException as e:
Ryan Cui1562fb82011-05-09 11:01:31 -0700608 PrintErrorForProject(project, HookFailure(str(e)))
609 os.chdir(pwd)
610 return True
Ryan Cuifa55df52011-05-06 11:16:55 -0700611
Ryan Cui9b651632011-05-11 11:38:58 -0700612 hooks = _get_project_hooks(project)
Ryan Cui1562fb82011-05-09 11:01:31 -0700613 error_found = False
Ryan Cuifa55df52011-05-06 11:16:55 -0700614 for commit in commit_list:
Ryan Cui1562fb82011-05-09 11:01:31 -0700615 error_list = []
Ryan Cui9b651632011-05-11 11:38:58 -0700616 for hook in hooks:
Ryan Cui1562fb82011-05-09 11:01:31 -0700617 hook_error = hook(project, commit)
618 if hook_error:
619 error_list.append(hook_error)
620 error_found = True
621 if error_list:
622 PrintErrorsForCommit(project, commit, _get_commit_desc(commit),
623 error_list)
Don Garrettdba548a2011-05-05 15:17:14 -0700624
Ryan Cuiec4d6332011-05-02 14:15:25 -0700625 os.chdir(pwd)
Ryan Cui1562fb82011-05-09 11:01:31 -0700626 return error_found
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700627
628# Main
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -0700629
Ryan Cui1562fb82011-05-09 11:01:31 -0700630
Anush Elangovan63afad72011-03-23 00:41:27 -0700631def main(project_list, **kwargs):
Doug Anderson06456632012-01-05 11:02:14 -0800632 """Main function invoked directly by repo.
633
634 This function will exit directly upon error so that repo doesn't print some
635 obscure error message.
636
637 Args:
638 project_list: List of projects to run on.
639 kwargs: Leave this here for forward-compatibility.
640 """
Ryan Cui1562fb82011-05-09 11:01:31 -0700641 found_error = False
642 for project in project_list:
Ryan Cui9b651632011-05-11 11:38:58 -0700643 if _run_project_hooks(project):
Ryan Cui1562fb82011-05-09 11:01:31 -0700644 found_error = True
645
646 if (found_error):
647 msg = ('Preupload failed due to errors in project(s). HINTS:\n'
Ryan Cui9b651632011-05-11 11:38:58 -0700648 '- To disable some source style checks, and for other hints, see '
649 '<checkout_dir>/src/repohooks/README\n'
650 '- To upload only current project, run \'repo upload .\'')
Ryan Cui1562fb82011-05-09 11:01:31 -0700651 print >> sys.stderr, msg
Don Garrettdba548a2011-05-05 15:17:14 -0700652 sys.exit(1)
Anush Elangovan63afad72011-03-23 00:41:27 -0700653
Ryan Cui1562fb82011-05-09 11:01:31 -0700654
Doug Anderson44a644f2011-11-02 10:37:37 -0700655def _identify_project(path):
656 """Identify the repo project associated with the given path.
657
658 Returns:
659 A string indicating what project is associated with the path passed in or
660 a blank string upon failure.
661 """
662 return _run_command(['repo', 'forall', '.', '-c', 'echo ${REPO_PROJECT}'],
663 stderr=subprocess.PIPE, cwd=path).strip()
664
665
666def direct_main(args, verbose=False):
667 """Run hooks directly (outside of the context of repo).
668
669 # Setup for doctests below.
670 # ...note that some tests assume that running pre-upload on this CWD is fine.
671 # TODO: Use mock and actually mock out _run_project_hooks() for tests.
672 >>> mydir = os.path.dirname(os.path.abspath(__file__))
673 >>> olddir = os.getcwd()
674
675 # OK to run w/ no arugments; will run with CWD.
676 >>> os.chdir(mydir)
677 >>> direct_main(['prog_name'], verbose=True)
678 Running hooks on chromiumos/repohooks
679 0
680 >>> os.chdir(olddir)
681
682 # Run specifying a dir
683 >>> direct_main(['prog_name', '--dir=%s' % mydir], verbose=True)
684 Running hooks on chromiumos/repohooks
685 0
686
687 # Not a problem to use a bogus project; we'll just get default settings.
688 >>> direct_main(['prog_name', '--dir=%s' % mydir, '--project=X'],verbose=True)
689 Running hooks on X
690 0
691
692 # Run with project but no dir
693 >>> os.chdir(mydir)
694 >>> direct_main(['prog_name', '--project=X'], verbose=True)
695 Running hooks on X
696 0
697 >>> os.chdir(olddir)
698
699 # Try with a non-git CWD
700 >>> os.chdir('/tmp')
701 >>> direct_main(['prog_name'])
702 Traceback (most recent call last):
703 ...
704 BadInvocation: The current directory is not part of a git project.
705
706 # Check various bad arguments...
707 >>> direct_main(['prog_name', 'bogus'])
708 Traceback (most recent call last):
709 ...
710 BadInvocation: Unexpected arguments: bogus
711 >>> direct_main(['prog_name', '--project=bogus', '--dir=bogusdir'])
712 Traceback (most recent call last):
713 ...
714 BadInvocation: Invalid dir: bogusdir
715 >>> direct_main(['prog_name', '--project=bogus', '--dir=/tmp'])
716 Traceback (most recent call last):
717 ...
718 BadInvocation: Not a git directory: /tmp
719
720 Args:
721 args: The value of sys.argv
722
723 Returns:
724 0 if no pre-upload failures, 1 if failures.
725
726 Raises:
727 BadInvocation: On some types of invocation errors.
728 """
729 desc = 'Run Chromium OS pre-upload hooks on changes compared to upstream.'
730 parser = optparse.OptionParser(description=desc)
731
732 parser.add_option('--dir', default=None,
733 help='The directory that the project lives in. If not '
734 'specified, use the git project root based on the cwd.')
735 parser.add_option('--project', default=None,
736 help='The project repo path; this can affect how the hooks '
737 'get run, since some hooks are project-specific. For '
738 'chromite this is chromiumos/chromite. If not specified, '
739 'the repo tool will be used to figure this out based on '
740 'the dir.')
741
742 opts, args = parser.parse_args(args[1:])
743
744 if args:
745 raise BadInvocation('Unexpected arguments: %s' % ' '.join(args))
746
747 # Check/normlaize git dir; if unspecified, we'll use the root of the git
748 # project from CWD
749 if opts.dir is None:
750 git_dir = _run_command(['git', 'rev-parse', '--git-dir'],
751 stderr=subprocess.PIPE).strip()
752 if not git_dir:
753 raise BadInvocation('The current directory is not part of a git project.')
754 opts.dir = os.path.dirname(os.path.abspath(git_dir))
755 elif not os.path.isdir(opts.dir):
756 raise BadInvocation('Invalid dir: %s' % opts.dir)
757 elif not os.path.isdir(os.path.join(opts.dir, '.git')):
758 raise BadInvocation('Not a git directory: %s' % opts.dir)
759
760 # Identify the project if it wasn't specified; this _requires_ the repo
761 # tool to be installed and for the project to be part of a repo checkout.
762 if not opts.project:
763 opts.project = _identify_project(opts.dir)
764 if not opts.project:
765 raise BadInvocation("Repo couldn't identify the project of %s" % opts.dir)
766
767 if verbose:
768 print "Running hooks on %s" % (opts.project)
769
770 found_error = _run_project_hooks(opts.project, proj_dir=opts.dir)
771 if found_error:
772 return 1
773 return 0
774
775
776def _test():
777 """Run any built-in tests."""
778 import doctest
779 doctest.testmod()
780
781
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -0700782if __name__ == '__main__':
Doug Anderson44a644f2011-11-02 10:37:37 -0700783 if sys.argv[1:2] == ["--test"]:
784 _test()
785 exit_code = 0
786 else:
787 prog_name = os.path.basename(sys.argv[0])
788 try:
789 exit_code = direct_main(sys.argv)
790 except BadInvocation, e:
791 print >>sys.stderr, "%s: %s" % (prog_name, str(e))
792 exit_code = 1
793 sys.exit(exit_code)