blob: b4f00f7b8ab38e6fb90c9b245d4d02e74f4b1921 [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
Ryan Cuiec4d6332011-05-02 14:15:25 -070019
20COMMON_INCLUDED_PATHS = [
21 # C++ and friends
22 r".*\.c$", r".*\.cc$", r".*\.cpp$", r".*\.h$", r".*\.m$", r".*\.mm$",
23 r".*\.inl$", r".*\.asm$", r".*\.hxx$", r".*\.hpp$", r".*\.s$", r".*\.S$",
24 # Scripts
25 r".*\.js$", r".*\.py$", r".*\.sh$", r".*\.rb$", r".*\.pl$", r".*\.pm$",
26 # No extension at all, note that ALL CAPS files are black listed in
27 # COMMON_EXCLUDED_LIST below.
David Hendricks0af30eb2013-02-05 11:35:56 -080028 r"(^|.*[\\\/])[^.]+$",
Ryan Cuiec4d6332011-05-02 14:15:25 -070029 # Other
30 r".*\.java$", r".*\.mk$", r".*\.am$",
31]
32
Ryan Cui1562fb82011-05-09 11:01:31 -070033
Ryan Cuiec4d6332011-05-02 14:15:25 -070034COMMON_EXCLUDED_PATHS = [
Ryan Cui31e0c172011-05-04 21:00:45 -070035 # avoid doing source file checks for kernel
36 r"/src/third_party/kernel/",
37 r"/src/third_party/kernel-next/",
Paul Taysomf8b6e012011-05-09 14:32:42 -070038 r"/src/third_party/ktop/",
39 r"/src/third_party/punybench/",
Ryan Cuiec4d6332011-05-02 14:15:25 -070040 r".*\bexperimental[\\\/].*",
41 r".*\b[A-Z0-9_]{2,}$",
42 r".*[\\\/]debian[\\\/]rules$",
Brian Harringd780d602011-10-18 16:48:08 -070043 # for ebuild trees, ignore any caches and manifest data
44 r".*/Manifest$",
45 r".*/metadata/[^/]*cache[^/]*/[^/]+/[^/]+$",
Doug Anderson5bfb6792011-10-25 16:45:41 -070046
47 # ignore profiles data (like overlay-tegra2/profiles)
48 r".*/overlay-.*/profiles/.*",
Andrew de los Reyes0e679922012-05-02 11:42:54 -070049 # ignore minified js and jquery
50 r".*\.min\.js",
51 r".*jquery.*\.js",
Ryan Cuiec4d6332011-05-02 14:15:25 -070052]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070053
Ryan Cui1562fb82011-05-09 11:01:31 -070054
Ryan Cui9b651632011-05-11 11:38:58 -070055_CONFIG_FILE = 'PRESUBMIT.cfg'
56
57
Doug Anderson44a644f2011-11-02 10:37:37 -070058# Exceptions
59
60
61class BadInvocation(Exception):
62 """An Exception indicating a bad invocation of the program."""
63 pass
64
65
Ryan Cui1562fb82011-05-09 11:01:31 -070066# General Helpers
67
Sean Paulba01d402011-05-05 11:36:23 -040068
Doug Anderson44a644f2011-11-02 10:37:37 -070069def _run_command(cmd, cwd=None, stderr=None):
70 """Executes the passed in command and returns raw stdout output.
71
72 Args:
73 cmd: The command to run; should be a list of strings.
74 cwd: The directory to switch to for running the command.
75 stderr: Can be one of None (print stderr to console), subprocess.STDOUT
76 (combine stderr with stdout), or subprocess.PIPE (ignore stderr).
77
78 Returns:
79 The standard out from the process.
80 """
81 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=stderr, cwd=cwd)
82 return p.communicate()[0]
Ryan Cui72834d12011-05-05 14:51:33 -070083
Ryan Cui1562fb82011-05-09 11:01:31 -070084
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070085def _get_hooks_dir():
Ryan Cuiec4d6332011-05-02 14:15:25 -070086 """Returns the absolute path to the repohooks directory."""
Doug Anderson44a644f2011-11-02 10:37:37 -070087 if __name__ == '__main__':
88 # Works when file is run on its own (__file__ is defined)...
89 return os.path.abspath(os.path.dirname(__file__))
90 else:
91 # We need to do this when we're run through repo. Since repo executes
92 # us with execfile(), we don't get __file__ defined.
93 cmd = ['repo', 'forall', 'chromiumos/repohooks', '-c', 'pwd']
94 return _run_command(cmd).strip()
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070095
Ryan Cui1562fb82011-05-09 11:01:31 -070096
Ryan Cuiec4d6332011-05-02 14:15:25 -070097def _match_regex_list(subject, expressions):
98 """Try to match a list of regular expressions to a string.
99
100 Args:
101 subject: The string to match regexes on
102 expressions: A list of regular expressions to check for matches with.
103
104 Returns:
105 Whether the passed in subject matches any of the passed in regexes.
106 """
107 for expr in expressions:
108 if (re.search(expr, subject)):
109 return True
110 return False
111
Ryan Cui1562fb82011-05-09 11:01:31 -0700112
Ryan Cuiec4d6332011-05-02 14:15:25 -0700113def _filter_files(files, include_list, exclude_list=[]):
114 """Filter out files based on the conditions passed in.
115
116 Args:
117 files: list of filepaths to filter
118 include_list: list of regex that when matched with a file path will cause it
119 to be added to the output list unless the file is also matched with a
120 regex in the exclude_list.
121 exclude_list: list of regex that when matched with a file will prevent it
122 from being added to the output list, even if it is also matched with a
123 regex in the include_list.
124
125 Returns:
126 A list of filepaths that contain files matched in the include_list and not
127 in the exclude_list.
128 """
129 filtered = []
130 for f in files:
131 if (_match_regex_list(f, include_list) and
132 not _match_regex_list(f, exclude_list)):
133 filtered.append(f)
134 return filtered
135
Ryan Cuiec4d6332011-05-02 14:15:25 -0700136
David Hendricks35030d02013-02-04 17:49:16 -0800137def _verify_header_content(commit, content, fail_msg):
138 """Verify that file headers contain specified content.
139
140 Args:
141 commit: the affected commit.
142 content: the content of the header to be verified.
143 fail_msg: the first message to display in case of failure.
144
145 Returns:
146 The return value of HookFailure().
147 """
148 license_re = re.compile(content, re.MULTILINE)
149 bad_files = []
150 files = _filter_files(_get_affected_files(commit),
151 COMMON_INCLUDED_PATHS,
152 COMMON_EXCLUDED_PATHS)
153
154 for f in files:
Gabe Blackcf3c32c2013-02-27 00:26:13 -0800155 if os.path.exists(f): # Ignore non-existant files
156 contents = open(f).read()
157 if len(contents) == 0: continue # Ignore empty files
158 if not license_re.search(contents):
159 bad_files.append(f)
David Hendricks35030d02013-02-04 17:49:16 -0800160 if bad_files:
161 msg = "%s:\n%s\n%s" % (fail_msg, license_re.pattern,
162 "Found a bad header in these files:")
163 return HookFailure(msg, bad_files)
164
165
Ryan Cuiec4d6332011-05-02 14:15:25 -0700166# Git Helpers
Ryan Cui1562fb82011-05-09 11:01:31 -0700167
168
Ryan Cui4725d952011-05-05 15:41:19 -0700169def _get_upstream_branch():
170 """Returns the upstream tracking branch of the current branch.
171
172 Raises:
173 Error if there is no tracking branch
174 """
175 current_branch = _run_command(['git', 'symbolic-ref', 'HEAD']).strip()
176 current_branch = current_branch.replace('refs/heads/', '')
177 if not current_branch:
Ryan Cui1562fb82011-05-09 11:01:31 -0700178 raise VerifyException('Need to be on a tracking branch')
Ryan Cui4725d952011-05-05 15:41:19 -0700179
180 cfg_option = 'branch.' + current_branch + '.%s'
181 full_upstream = _run_command(['git', 'config', cfg_option % 'merge']).strip()
182 remote = _run_command(['git', 'config', cfg_option % 'remote']).strip()
183 if not remote or not full_upstream:
Ryan Cui1562fb82011-05-09 11:01:31 -0700184 raise VerifyException('Need to be on a tracking branch')
Ryan Cui4725d952011-05-05 15:41:19 -0700185
186 return full_upstream.replace('heads', 'remotes/' + remote)
187
Ryan Cui1562fb82011-05-09 11:01:31 -0700188
Che-Liang Chiou5ce2d7b2013-03-22 18:47:55 -0700189def _get_patch(commit):
190 """Returns the patch for this commit."""
191 return _run_command(['git', 'format-patch', '--stdout', '-1', commit])
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700192
Ryan Cui1562fb82011-05-09 11:01:31 -0700193
Jon Salz98255932012-08-18 14:48:02 +0800194def _try_utf8_decode(data):
195 """Attempts to decode a string as UTF-8.
196
197 Returns:
198 The decoded Unicode object, or the original string if parsing fails.
199 """
200 try:
201 return unicode(data, 'utf-8', 'strict')
202 except UnicodeDecodeError:
203 return data
204
205
Ryan Cuiec4d6332011-05-02 14:15:25 -0700206def _get_file_diff(file, commit):
207 """Returns a list of (linenum, lines) tuples that the commit touched."""
Ryan Cui72834d12011-05-05 14:51:33 -0700208 output = _run_command(['git', 'show', '-p', '--no-ext-diff', commit, file])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700209
210 new_lines = []
211 line_num = 0
212 for line in output.splitlines():
213 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
214 if m:
215 line_num = int(m.groups(1)[0])
216 continue
217 if line.startswith('+') and not line.startswith('++'):
Jon Salz98255932012-08-18 14:48:02 +0800218 new_lines.append((line_num, _try_utf8_decode(line[1:])))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700219 if not line.startswith('-'):
220 line_num += 1
221 return new_lines
222
Ryan Cui1562fb82011-05-09 11:01:31 -0700223
Ryan Cuiec4d6332011-05-02 14:15:25 -0700224def _get_affected_files(commit):
225 """Returns list of absolute filepaths that were modified/added."""
Ryan Cui72834d12011-05-05 14:51:33 -0700226 output = _run_command(['git', 'diff', '--name-status', commit + '^!'])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700227 files = []
228 for statusline in output.splitlines():
229 m = re.match('^(\w)+\t(.+)$', statusline.rstrip())
230 # Ignore deleted files, and return absolute paths of files
231 if (m.group(1)[0] != 'D'):
232 pwd = os.getcwd()
233 files.append(os.path.join(pwd, m.group(2)))
234 return files
235
Ryan Cui1562fb82011-05-09 11:01:31 -0700236
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700237def _get_commits():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700238 """Returns a list of commits for this review."""
Ryan Cui4725d952011-05-05 15:41:19 -0700239 cmd = ['git', 'log', '%s..' % _get_upstream_branch(), '--format=%H']
Ryan Cui72834d12011-05-05 14:51:33 -0700240 return _run_command(cmd).split()
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700241
Ryan Cui1562fb82011-05-09 11:01:31 -0700242
Ryan Cuiec4d6332011-05-02 14:15:25 -0700243def _get_commit_desc(commit):
244 """Returns the full commit message of a commit."""
Sean Paul23a2c582011-05-06 13:10:44 -0400245 return _run_command(['git', 'log', '--format=%s%n%n%b', commit + '^!'])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700246
247
248# Common Hooks
249
Ryan Cui1562fb82011-05-09 11:01:31 -0700250
Ryan Cuiec4d6332011-05-02 14:15:25 -0700251def _check_no_long_lines(project, commit):
252 """Checks that there aren't any lines longer than maxlen characters in any of
253 the text files to be submitted.
254 """
255 MAX_LEN = 80
Jon Salz98255932012-08-18 14:48:02 +0800256 SKIP_REGEXP = re.compile('|'.join([
257 r'https?://',
258 r'^#\s*(define|include|import|pragma|if|endif)\b']))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700259
260 errors = []
261 files = _filter_files(_get_affected_files(commit),
262 COMMON_INCLUDED_PATHS,
263 COMMON_EXCLUDED_PATHS)
264
265 for afile in files:
266 for line_num, line in _get_file_diff(afile, commit):
267 # Allow certain lines to exceed the maxlen rule.
Jon Salz98255932012-08-18 14:48:02 +0800268 if (len(line) <= MAX_LEN or SKIP_REGEXP.search(line)):
269 continue
270
271 errors.append('%s, line %s, %s chars' % (afile, line_num, len(line)))
272 if len(errors) == 5: # Just show the first 5 errors.
273 break
Ryan Cuiec4d6332011-05-02 14:15:25 -0700274
275 if errors:
276 msg = 'Found lines longer than %s characters (first 5 shown):' % MAX_LEN
Ryan Cui1562fb82011-05-09 11:01:31 -0700277 return HookFailure(msg, errors)
278
Ryan Cuiec4d6332011-05-02 14:15:25 -0700279
280def _check_no_stray_whitespace(project, commit):
281 """Checks that there is no stray whitespace at source lines end."""
282 errors = []
283 files = _filter_files(_get_affected_files(commit),
284 COMMON_INCLUDED_PATHS,
285 COMMON_EXCLUDED_PATHS)
286
287 for afile in files:
288 for line_num, line in _get_file_diff(afile, commit):
289 if line.rstrip() != line:
290 errors.append('%s, line %s' % (afile, line_num))
291 if errors:
Ryan Cui1562fb82011-05-09 11:01:31 -0700292 return HookFailure('Found line ending with white space in:', errors)
293
Ryan Cuiec4d6332011-05-02 14:15:25 -0700294
295def _check_no_tabs(project, commit):
296 """Checks there are no unexpanded tabs."""
297 TAB_OK_PATHS = [
Ryan Cui31e0c172011-05-04 21:00:45 -0700298 r"/src/third_party/u-boot/",
Ryan Cuiec4d6332011-05-02 14:15:25 -0700299 r".*\.ebuild$",
300 r".*\.eclass$",
Elly Jones5ab34192011-11-15 14:57:06 -0500301 r".*/[M|m]akefile$",
302 r".*\.mk$"
Ryan Cuiec4d6332011-05-02 14:15:25 -0700303 ]
304
305 errors = []
306 files = _filter_files(_get_affected_files(commit),
307 COMMON_INCLUDED_PATHS,
308 COMMON_EXCLUDED_PATHS + TAB_OK_PATHS)
309
310 for afile in files:
311 for line_num, line in _get_file_diff(afile, commit):
312 if '\t' in line:
313 errors.append('%s, line %s' % (afile, line_num))
314 if errors:
Ryan Cui1562fb82011-05-09 11:01:31 -0700315 return HookFailure('Found a tab character in:', errors)
316
Ryan Cuiec4d6332011-05-02 14:15:25 -0700317
318def _check_change_has_test_field(project, commit):
319 """Check for a non-empty 'TEST=' field in the commit message."""
David McMahon8f6553e2011-06-10 15:46:36 -0700320 TEST_RE = r'\nTEST=\S+'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700321
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700322 if not re.search(TEST_RE, _get_commit_desc(commit)):
Ryan Cui1562fb82011-05-09 11:01:31 -0700323 msg = 'Changelist description needs TEST field (after first line)'
324 return HookFailure(msg)
325
Ryan Cuiec4d6332011-05-02 14:15:25 -0700326
327def _check_change_has_bug_field(project, commit):
David McMahon8f6553e2011-06-10 15:46:36 -0700328 """Check for a correctly formatted 'BUG=' field in the commit message."""
David James5c0073d2013-04-03 08:48:52 -0700329 OLD_BUG_RE = r'\nBUG=.*chromium-os'
330 if re.search(OLD_BUG_RE, _get_commit_desc(commit)):
331 msg = ('The chromium-os bug tracker is now deprecated. Please use\n'
332 'the chromium tracker in your BUG= line now.')
333 return HookFailure(msg)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700334
David James5c0073d2013-04-03 08:48:52 -0700335 BUG_RE = r'\nBUG=([Nn]one|(chrome-os-partner|chromium):\d+)'
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700336 if not re.search(BUG_RE, _get_commit_desc(commit)):
David McMahon8f6553e2011-06-10 15:46:36 -0700337 msg = ('Changelist description needs BUG field (after first line):\n'
David James5c0073d2013-04-03 08:48:52 -0700338 'BUG=chromium:9999 (for public tracker)\n'
David McMahon8f6553e2011-06-10 15:46:36 -0700339 'BUG=chrome-os-partner:9999 (for partner tracker)\n'
340 'BUG=None')
Ryan Cui1562fb82011-05-09 11:01:31 -0700341 return HookFailure(msg)
342
Ryan Cuiec4d6332011-05-02 14:15:25 -0700343
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700344def _check_change_has_proper_changeid(project, commit):
345 """Verify that Change-ID is present in last paragraph of commit message."""
346 desc = _get_commit_desc(commit)
347 loc = desc.rfind('\nChange-Id:')
348 if loc == -1 or re.search('\n\s*\n\s*\S+', desc[loc:]):
Ryan Cui1562fb82011-05-09 11:01:31 -0700349 return HookFailure('Change-Id must be in last paragraph of description.')
350
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700351
Ryan Cuiec4d6332011-05-02 14:15:25 -0700352def _check_license(project, commit):
353 """Verifies the license header."""
354 LICENSE_HEADER = (
David Hendricks0af30eb2013-02-05 11:35:56 -0800355 r".* Copyright \(c\) 20[-0-9]{2,7} The Chromium OS Authors\. All rights "
Ryan Cuiec4d6332011-05-02 14:15:25 -0700356 r"reserved\." "\n"
David Hendricks0af30eb2013-02-05 11:35:56 -0800357 r".* Use of this source code is governed by a BSD-style license that can "
Ryan Cuiec4d6332011-05-02 14:15:25 -0700358 "be\n"
David Hendricks0af30eb2013-02-05 11:35:56 -0800359 r".* found in the LICENSE file\."
Ryan Cuiec4d6332011-05-02 14:15:25 -0700360 "\n"
361 )
David Hendricks35030d02013-02-04 17:49:16 -0800362 FAIL_MSG = "License must match"
Ryan Cuiec4d6332011-05-02 14:15:25 -0700363
David Hendricks35030d02013-02-04 17:49:16 -0800364 return _verify_header_content(commit, LICENSE_HEADER, FAIL_MSG)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700365
366
David Hendricksa0e310d2013-02-04 17:51:55 -0800367def _check_google_copyright(project, commit):
368 """Verifies Google Inc. as copyright holder."""
369 LICENSE_HEADER = (
370 r".* Copyright 20[-0-9]{2,7} Google Inc\."
371 )
372 FAIL_MSG = "Copyright must match"
373
David Hendricks4c018e72013-02-06 13:46:38 -0800374 # Avoid blocking partners and external contributors.
375 fqdn = socket.getfqdn()
376 if not fqdn.endswith(".corp.google.com"):
377 return None
378
David Hendricksa0e310d2013-02-04 17:51:55 -0800379 return _verify_header_content(commit, LICENSE_HEADER, FAIL_MSG)
380
381
Ryan Cuiec4d6332011-05-02 14:15:25 -0700382# Project-specific hooks
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700383
Ryan Cui1562fb82011-05-09 11:01:31 -0700384
Anton Staaf815d6852011-08-22 10:08:45 -0700385def _run_checkpatch(project, commit, options=[]):
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700386 """Runs checkpatch.pl on the given project"""
387 hooks_dir = _get_hooks_dir()
Anton Staaf815d6852011-08-22 10:08:45 -0700388 cmd = ['%s/checkpatch.pl' % hooks_dir] + options + ['-']
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700389 p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Che-Liang Chiou5ce2d7b2013-03-22 18:47:55 -0700390 output = p.communicate(_get_patch(commit))[0]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700391 if p.returncode:
Ryan Cui1562fb82011-05-09 11:01:31 -0700392 return HookFailure('checkpatch.pl errors/warnings\n\n' + output)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700393
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700394
Anton Staaf815d6852011-08-22 10:08:45 -0700395def _run_checkpatch_no_tree(project, commit):
396 return _run_checkpatch(project, commit, ['--no-tree'])
397
Olof Johanssona96810f2012-09-04 16:20:03 -0700398def _kernel_configcheck(project, commit):
399 """Makes sure kernel config changes are not mixed with code changes"""
400 files = _get_affected_files(commit)
401 if not len(_filter_files(files, [r'chromeos/config'])) in [0, len(files)]:
402 return HookFailure('Changes to chromeos/config/ and regular files must '
403 'be in separate commits:\n%s' % '\n'.join(files))
Anton Staaf815d6852011-08-22 10:08:45 -0700404
Dale Curtis2975c432011-05-03 17:25:20 -0700405def _run_json_check(project, commit):
406 """Checks that all JSON files are syntactically valid."""
Dale Curtisa039cfd2011-05-04 12:01:05 -0700407 for f in _filter_files(_get_affected_files(commit), [r'.*\.json']):
Dale Curtis2975c432011-05-03 17:25:20 -0700408 try:
409 json.load(open(f))
410 except Exception, e:
Ryan Cui1562fb82011-05-09 11:01:31 -0700411 return HookFailure('Invalid JSON in %s: %s' % (f, e))
Dale Curtis2975c432011-05-03 17:25:20 -0700412
413
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700414def _check_change_has_branch_field(project, commit):
415 """Check for a non-empty 'BRANCH=' field in the commit message."""
416 BRANCH_RE = r'\nBRANCH=\S+'
417
418 if not re.search(BRANCH_RE, _get_commit_desc(commit)):
419 msg = ('Changelist description needs BRANCH field (after first line)\n'
420 'E.g. BRANCH=none or BRANCH=link,snow')
421 return HookFailure(msg)
422
423
Jon Salz3ee59de2012-08-18 13:54:22 +0800424def _run_project_hook_script(script, project, commit):
425 """Runs a project hook script.
426
427 The script is run with the following environment variables set:
428 PRESUBMIT_PROJECT: The affected project
429 PRESUBMIT_COMMIT: The affected commit
430 PRESUBMIT_FILES: A newline-separated list of affected files
431
432 The script is considered to fail if the exit code is non-zero. It should
433 write an error message to stdout.
434 """
435 env = dict(os.environ)
436 env['PRESUBMIT_PROJECT'] = project
437 env['PRESUBMIT_COMMIT'] = commit
438
439 # Put affected files in an environment variable
440 files = _get_affected_files(commit)
441 env['PRESUBMIT_FILES'] = '\n'.join(files)
442
443 process = subprocess.Popen(script, env=env, shell=True,
444 stdin=open(os.devnull),
Jon Salz7b618af2012-08-31 06:03:16 +0800445 stdout=subprocess.PIPE,
446 stderr=subprocess.STDOUT)
Jon Salz3ee59de2012-08-18 13:54:22 +0800447 stdout, _ = process.communicate()
448 if process.wait():
Jon Salz7b618af2012-08-31 06:03:16 +0800449 if stdout:
450 stdout = re.sub('(?m)^', ' ', stdout)
451 return HookFailure('Hook script "%s" failed with code %d%s' %
Jon Salz3ee59de2012-08-18 13:54:22 +0800452 (script, process.returncode,
453 ':\n' + stdout if stdout else ''))
454
455
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700456# Base
457
Ryan Cui1562fb82011-05-09 11:01:31 -0700458
Ryan Cui9b651632011-05-11 11:38:58 -0700459# A list of hooks that are not project-specific
460_COMMON_HOOKS = [
461 _check_change_has_bug_field,
462 _check_change_has_test_field,
463 _check_change_has_proper_changeid,
464 _check_no_stray_whitespace,
465 _check_no_long_lines,
466 _check_license,
467 _check_no_tabs,
468]
Ryan Cuiec4d6332011-05-02 14:15:25 -0700469
Ryan Cui1562fb82011-05-09 11:01:31 -0700470
Ryan Cui9b651632011-05-11 11:38:58 -0700471# A dictionary of project-specific hooks(callbacks), indexed by project name.
472# dict[project] = [callback1, callback2]
473_PROJECT_SPECIFIC_HOOKS = {
Olof Johanssona96810f2012-09-04 16:20:03 -0700474 "chromiumos/third_party/kernel": [_run_checkpatch, _kernel_configcheck],
475 "chromiumos/third_party/kernel-next": [_run_checkpatch,
476 _kernel_configcheck],
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700477 "chromiumos/third_party/u-boot": [_run_checkpatch_no_tree,
478 _check_change_has_branch_field],
479 "chromiumos/platform/ec": [_run_checkpatch_no_tree,
480 _check_change_has_branch_field],
481 "chromeos/platform/ec-private": [_run_checkpatch_no_tree,
482 _check_change_has_branch_field],
David Hendricks33f77d52013-02-04 17:53:02 -0800483 "chromeos/third_party/coreboot": [_check_change_has_branch_field,
484 _check_google_copyright],
Puneet Kumar57b9c092012-08-14 18:58:29 -0700485 "chromeos/third_party/intel-framework": [_check_change_has_branch_field],
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700486 "chromiumos/platform/vboot_reference": [_check_change_has_branch_field],
487 "chromiumos/platform/mosys": [_check_change_has_branch_field],
488 "chromiumos/third_party/flashrom": [_check_change_has_branch_field],
Dale Curtis2975c432011-05-03 17:25:20 -0700489 "chromeos/autotest-tools": [_run_json_check],
Ryan Cui9b651632011-05-11 11:38:58 -0700490}
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700491
Ryan Cui1562fb82011-05-09 11:01:31 -0700492
Ryan Cui9b651632011-05-11 11:38:58 -0700493# A dictionary of flags (keys) that can appear in the config file, and the hook
494# that the flag disables (value)
495_DISABLE_FLAGS = {
496 'stray_whitespace_check': _check_no_stray_whitespace,
497 'long_line_check': _check_no_long_lines,
498 'cros_license_check': _check_license,
499 'tab_check': _check_no_tabs,
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700500 'branch_check': _check_change_has_branch_field,
Ryan Cui9b651632011-05-11 11:38:58 -0700501}
502
503
Jon Salz3ee59de2012-08-18 13:54:22 +0800504def _get_disabled_hooks(config):
Ryan Cui9b651632011-05-11 11:38:58 -0700505 """Returns a set of hooks disabled by the current project's config file.
506
507 Expects to be called within the project root.
Jon Salz3ee59de2012-08-18 13:54:22 +0800508
509 Args:
510 config: A ConfigParser for the project's config file.
Ryan Cui9b651632011-05-11 11:38:58 -0700511 """
512 SECTION = 'Hook Overrides'
Jon Salz3ee59de2012-08-18 13:54:22 +0800513 if not config.has_section(SECTION):
514 return set()
Ryan Cui9b651632011-05-11 11:38:58 -0700515
516 disable_flags = []
Jon Salz3ee59de2012-08-18 13:54:22 +0800517 for flag in config.options(SECTION):
Ryan Cui9b651632011-05-11 11:38:58 -0700518 try:
519 if not config.getboolean(SECTION, flag): disable_flags.append(flag)
520 except ValueError as e:
521 msg = "Error parsing flag \'%s\' in %s file - " % (flag, _CONFIG_FILE)
522 print msg + str(e)
523
524 disabled_keys = set(_DISABLE_FLAGS.iterkeys()).intersection(disable_flags)
525 return set([_DISABLE_FLAGS[key] for key in disabled_keys])
526
527
Jon Salz3ee59de2012-08-18 13:54:22 +0800528def _get_project_hook_scripts(config):
529 """Returns a list of project-specific hook scripts.
530
531 Args:
532 config: A ConfigParser for the project's config file.
533 """
534 SECTION = 'Hook Scripts'
535 if not config.has_section(SECTION):
536 return []
537
538 hook_names_values = config.items(SECTION)
539 hook_names_values.sort(key=lambda x: x[0])
540 return [x[1] for x in hook_names_values]
541
542
Ryan Cui9b651632011-05-11 11:38:58 -0700543def _get_project_hooks(project):
544 """Returns a list of hooks that need to be run for a project.
545
546 Expects to be called from within the project root.
547 """
Jon Salz3ee59de2012-08-18 13:54:22 +0800548 config = ConfigParser.RawConfigParser()
549 try:
550 config.read(_CONFIG_FILE)
551 except ConfigParser.Error:
552 # Just use an empty config file
553 config = ConfigParser.RawConfigParser()
554
555 disabled_hooks = _get_disabled_hooks(config)
Ryan Cui9b651632011-05-11 11:38:58 -0700556 hooks = [hook for hook in _COMMON_HOOKS if hook not in disabled_hooks]
557
558 if project in _PROJECT_SPECIFIC_HOOKS:
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700559 hooks.extend(hook for hook in _PROJECT_SPECIFIC_HOOKS[project]
560 if hook not in disabled_hooks)
Ryan Cui9b651632011-05-11 11:38:58 -0700561
Jon Salz3ee59de2012-08-18 13:54:22 +0800562 for script in _get_project_hook_scripts(config):
563 hooks.append(functools.partial(_run_project_hook_script, script))
564
Ryan Cui9b651632011-05-11 11:38:58 -0700565 return hooks
566
567
Doug Anderson44a644f2011-11-02 10:37:37 -0700568def _run_project_hooks(project, proj_dir=None):
Ryan Cui1562fb82011-05-09 11:01:31 -0700569 """For each project run its project specific hook from the hooks dictionary.
570
571 Args:
Doug Anderson44a644f2011-11-02 10:37:37 -0700572 project: The name of project to run hooks for.
573 proj_dir: If non-None, this is the directory the project is in. If None,
574 we'll ask repo.
Ryan Cui1562fb82011-05-09 11:01:31 -0700575
576 Returns:
577 Boolean value of whether any errors were ecountered while running the hooks.
578 """
Doug Anderson44a644f2011-11-02 10:37:37 -0700579 if proj_dir is None:
580 proj_dir = _run_command(['repo', 'forall', project, '-c', 'pwd']).strip()
581
Ryan Cuiec4d6332011-05-02 14:15:25 -0700582 pwd = os.getcwd()
583 # hooks assume they are run from the root of the project
584 os.chdir(proj_dir)
585
Ryan Cuifa55df52011-05-06 11:16:55 -0700586 try:
587 commit_list = _get_commits()
Don Garrettdba548a2011-05-05 15:17:14 -0700588 except VerifyException as e:
Ryan Cui1562fb82011-05-09 11:01:31 -0700589 PrintErrorForProject(project, HookFailure(str(e)))
590 os.chdir(pwd)
591 return True
Ryan Cuifa55df52011-05-06 11:16:55 -0700592
Ryan Cui9b651632011-05-11 11:38:58 -0700593 hooks = _get_project_hooks(project)
Ryan Cui1562fb82011-05-09 11:01:31 -0700594 error_found = False
Ryan Cuifa55df52011-05-06 11:16:55 -0700595 for commit in commit_list:
Ryan Cui1562fb82011-05-09 11:01:31 -0700596 error_list = []
Ryan Cui9b651632011-05-11 11:38:58 -0700597 for hook in hooks:
Ryan Cui1562fb82011-05-09 11:01:31 -0700598 hook_error = hook(project, commit)
599 if hook_error:
600 error_list.append(hook_error)
601 error_found = True
602 if error_list:
603 PrintErrorsForCommit(project, commit, _get_commit_desc(commit),
604 error_list)
Don Garrettdba548a2011-05-05 15:17:14 -0700605
Ryan Cuiec4d6332011-05-02 14:15:25 -0700606 os.chdir(pwd)
Ryan Cui1562fb82011-05-09 11:01:31 -0700607 return error_found
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700608
609# Main
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -0700610
Ryan Cui1562fb82011-05-09 11:01:31 -0700611
Anush Elangovan63afad72011-03-23 00:41:27 -0700612def main(project_list, **kwargs):
Doug Anderson06456632012-01-05 11:02:14 -0800613 """Main function invoked directly by repo.
614
615 This function will exit directly upon error so that repo doesn't print some
616 obscure error message.
617
618 Args:
619 project_list: List of projects to run on.
620 kwargs: Leave this here for forward-compatibility.
621 """
Ryan Cui1562fb82011-05-09 11:01:31 -0700622 found_error = False
623 for project in project_list:
Ryan Cui9b651632011-05-11 11:38:58 -0700624 if _run_project_hooks(project):
Ryan Cui1562fb82011-05-09 11:01:31 -0700625 found_error = True
626
627 if (found_error):
628 msg = ('Preupload failed due to errors in project(s). HINTS:\n'
Ryan Cui9b651632011-05-11 11:38:58 -0700629 '- To disable some source style checks, and for other hints, see '
630 '<checkout_dir>/src/repohooks/README\n'
631 '- To upload only current project, run \'repo upload .\'')
Ryan Cui1562fb82011-05-09 11:01:31 -0700632 print >> sys.stderr, msg
Don Garrettdba548a2011-05-05 15:17:14 -0700633 sys.exit(1)
Anush Elangovan63afad72011-03-23 00:41:27 -0700634
Ryan Cui1562fb82011-05-09 11:01:31 -0700635
Doug Anderson44a644f2011-11-02 10:37:37 -0700636def _identify_project(path):
637 """Identify the repo project associated with the given path.
638
639 Returns:
640 A string indicating what project is associated with the path passed in or
641 a blank string upon failure.
642 """
643 return _run_command(['repo', 'forall', '.', '-c', 'echo ${REPO_PROJECT}'],
644 stderr=subprocess.PIPE, cwd=path).strip()
645
646
647def direct_main(args, verbose=False):
648 """Run hooks directly (outside of the context of repo).
649
650 # Setup for doctests below.
651 # ...note that some tests assume that running pre-upload on this CWD is fine.
652 # TODO: Use mock and actually mock out _run_project_hooks() for tests.
653 >>> mydir = os.path.dirname(os.path.abspath(__file__))
654 >>> olddir = os.getcwd()
655
656 # OK to run w/ no arugments; will run with CWD.
657 >>> os.chdir(mydir)
658 >>> direct_main(['prog_name'], verbose=True)
659 Running hooks on chromiumos/repohooks
660 0
661 >>> os.chdir(olddir)
662
663 # Run specifying a dir
664 >>> direct_main(['prog_name', '--dir=%s' % mydir], verbose=True)
665 Running hooks on chromiumos/repohooks
666 0
667
668 # Not a problem to use a bogus project; we'll just get default settings.
669 >>> direct_main(['prog_name', '--dir=%s' % mydir, '--project=X'],verbose=True)
670 Running hooks on X
671 0
672
673 # Run with project but no dir
674 >>> os.chdir(mydir)
675 >>> direct_main(['prog_name', '--project=X'], verbose=True)
676 Running hooks on X
677 0
678 >>> os.chdir(olddir)
679
680 # Try with a non-git CWD
681 >>> os.chdir('/tmp')
682 >>> direct_main(['prog_name'])
683 Traceback (most recent call last):
684 ...
685 BadInvocation: The current directory is not part of a git project.
686
687 # Check various bad arguments...
688 >>> direct_main(['prog_name', 'bogus'])
689 Traceback (most recent call last):
690 ...
691 BadInvocation: Unexpected arguments: bogus
692 >>> direct_main(['prog_name', '--project=bogus', '--dir=bogusdir'])
693 Traceback (most recent call last):
694 ...
695 BadInvocation: Invalid dir: bogusdir
696 >>> direct_main(['prog_name', '--project=bogus', '--dir=/tmp'])
697 Traceback (most recent call last):
698 ...
699 BadInvocation: Not a git directory: /tmp
700
701 Args:
702 args: The value of sys.argv
703
704 Returns:
705 0 if no pre-upload failures, 1 if failures.
706
707 Raises:
708 BadInvocation: On some types of invocation errors.
709 """
710 desc = 'Run Chromium OS pre-upload hooks on changes compared to upstream.'
711 parser = optparse.OptionParser(description=desc)
712
713 parser.add_option('--dir', default=None,
714 help='The directory that the project lives in. If not '
715 'specified, use the git project root based on the cwd.')
716 parser.add_option('--project', default=None,
717 help='The project repo path; this can affect how the hooks '
718 'get run, since some hooks are project-specific. For '
719 'chromite this is chromiumos/chromite. If not specified, '
720 'the repo tool will be used to figure this out based on '
721 'the dir.')
722
723 opts, args = parser.parse_args(args[1:])
724
725 if args:
726 raise BadInvocation('Unexpected arguments: %s' % ' '.join(args))
727
728 # Check/normlaize git dir; if unspecified, we'll use the root of the git
729 # project from CWD
730 if opts.dir is None:
731 git_dir = _run_command(['git', 'rev-parse', '--git-dir'],
732 stderr=subprocess.PIPE).strip()
733 if not git_dir:
734 raise BadInvocation('The current directory is not part of a git project.')
735 opts.dir = os.path.dirname(os.path.abspath(git_dir))
736 elif not os.path.isdir(opts.dir):
737 raise BadInvocation('Invalid dir: %s' % opts.dir)
738 elif not os.path.isdir(os.path.join(opts.dir, '.git')):
739 raise BadInvocation('Not a git directory: %s' % opts.dir)
740
741 # Identify the project if it wasn't specified; this _requires_ the repo
742 # tool to be installed and for the project to be part of a repo checkout.
743 if not opts.project:
744 opts.project = _identify_project(opts.dir)
745 if not opts.project:
746 raise BadInvocation("Repo couldn't identify the project of %s" % opts.dir)
747
748 if verbose:
749 print "Running hooks on %s" % (opts.project)
750
751 found_error = _run_project_hooks(opts.project, proj_dir=opts.dir)
752 if found_error:
753 return 1
754 return 0
755
756
757def _test():
758 """Run any built-in tests."""
759 import doctest
760 doctest.testmod()
761
762
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -0700763if __name__ == '__main__':
Doug Anderson44a644f2011-11-02 10:37:37 -0700764 if sys.argv[1:2] == ["--test"]:
765 _test()
766 exit_code = 0
767 else:
768 prog_name = os.path.basename(sys.argv[0])
769 try:
770 exit_code = direct_main(sys.argv)
771 except BadInvocation, e:
772 print >>sys.stderr, "%s: %s" % (prog_name, str(e))
773 exit_code = 1
774 sys.exit(exit_code)