blob: 53205777521ad24afa10746905cf094a84ee1083 [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
Mike Frysinger09d6a3d2013-10-08 22:21:03 -04006from __future__ import print_function
7
Ryan Cui9b651632011-05-11 11:38:58 -07008import ConfigParser
Jon Salz3ee59de2012-08-18 13:54:22 +08009import functools
Dale Curtis2975c432011-05-03 17:25:20 -070010import json
Doug Anderson44a644f2011-11-02 10:37:37 -070011import optparse
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070012import os
Ryan Cuiec4d6332011-05-02 14:15:25 -070013import re
David Hendricks4c018e72013-02-06 13:46:38 -080014import socket
Mandeep Singh Bainesa7ffa4b2011-05-03 11:37:02 -070015import sys
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070016import subprocess
17
Ryan Cui1562fb82011-05-09 11:01:31 -070018from errors import (VerifyException, HookFailure, PrintErrorForProject,
19 PrintErrorsForCommit)
Ryan Cuiec4d6332011-05-02 14:15:25 -070020
David Jamesc3b68b32013-04-03 09:17:03 -070021# If repo imports us, the __name__ will be __builtin__, and the wrapper will
22# be in $CHROMEOS_CHECKOUT/.repo/repo/main.py, so we need to go two directories
23# up. The same logic also happens to work if we're executed directly.
24if __name__ in ('__builtin__', '__main__'):
25 sys.path.insert(0, os.path.join(os.path.dirname(sys.argv[0]), '..', '..'))
26
27from chromite.lib import patch
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -080028from chromite.licensing import licenses
David Jamesc3b68b32013-04-03 09:17:03 -070029
Ryan Cuiec4d6332011-05-02 14:15:25 -070030
31COMMON_INCLUDED_PATHS = [
32 # C++ and friends
33 r".*\.c$", r".*\.cc$", r".*\.cpp$", r".*\.h$", r".*\.m$", r".*\.mm$",
34 r".*\.inl$", r".*\.asm$", r".*\.hxx$", r".*\.hpp$", r".*\.s$", r".*\.S$",
35 # Scripts
36 r".*\.js$", r".*\.py$", r".*\.sh$", r".*\.rb$", r".*\.pl$", r".*\.pm$",
37 # No extension at all, note that ALL CAPS files are black listed in
38 # COMMON_EXCLUDED_LIST below.
David Hendricks0af30eb2013-02-05 11:35:56 -080039 r"(^|.*[\\\/])[^.]+$",
Ryan Cuiec4d6332011-05-02 14:15:25 -070040 # Other
41 r".*\.java$", r".*\.mk$", r".*\.am$",
42]
43
Ryan Cui1562fb82011-05-09 11:01:31 -070044
Ryan Cuiec4d6332011-05-02 14:15:25 -070045COMMON_EXCLUDED_PATHS = [
Ryan Cui31e0c172011-05-04 21:00:45 -070046 # avoid doing source file checks for kernel
47 r"/src/third_party/kernel/",
48 r"/src/third_party/kernel-next/",
Paul Taysomf8b6e012011-05-09 14:32:42 -070049 r"/src/third_party/ktop/",
50 r"/src/third_party/punybench/",
Ryan Cuiec4d6332011-05-02 14:15:25 -070051 r".*\bexperimental[\\\/].*",
52 r".*\b[A-Z0-9_]{2,}$",
53 r".*[\\\/]debian[\\\/]rules$",
Brian Harringd780d602011-10-18 16:48:08 -070054 # for ebuild trees, ignore any caches and manifest data
55 r".*/Manifest$",
56 r".*/metadata/[^/]*cache[^/]*/[^/]+/[^/]+$",
Doug Anderson5bfb6792011-10-25 16:45:41 -070057
58 # ignore profiles data (like overlay-tegra2/profiles)
59 r".*/overlay-.*/profiles/.*",
Andrew de los Reyes0e679922012-05-02 11:42:54 -070060 # ignore minified js and jquery
61 r".*\.min\.js",
62 r".*jquery.*\.js",
Ryan Cuiec4d6332011-05-02 14:15:25 -070063]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070064
Ryan Cui1562fb82011-05-09 11:01:31 -070065
Ryan Cui9b651632011-05-11 11:38:58 -070066_CONFIG_FILE = 'PRESUBMIT.cfg'
67
68
Doug Anderson44a644f2011-11-02 10:37:37 -070069# Exceptions
70
71
72class BadInvocation(Exception):
73 """An Exception indicating a bad invocation of the program."""
74 pass
75
76
Ryan Cui1562fb82011-05-09 11:01:31 -070077# General Helpers
78
Sean Paulba01d402011-05-05 11:36:23 -040079
Doug Anderson44a644f2011-11-02 10:37:37 -070080def _run_command(cmd, cwd=None, stderr=None):
81 """Executes the passed in command and returns raw stdout output.
82
83 Args:
84 cmd: The command to run; should be a list of strings.
85 cwd: The directory to switch to for running the command.
86 stderr: Can be one of None (print stderr to console), subprocess.STDOUT
87 (combine stderr with stdout), or subprocess.PIPE (ignore stderr).
88
89 Returns:
90 The standard out from the process.
91 """
92 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=stderr, cwd=cwd)
93 return p.communicate()[0]
Ryan Cui72834d12011-05-05 14:51:33 -070094
Ryan Cui1562fb82011-05-09 11:01:31 -070095
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070096def _get_hooks_dir():
Ryan Cuiec4d6332011-05-02 14:15:25 -070097 """Returns the absolute path to the repohooks directory."""
Doug Anderson44a644f2011-11-02 10:37:37 -070098 if __name__ == '__main__':
99 # Works when file is run on its own (__file__ is defined)...
100 return os.path.abspath(os.path.dirname(__file__))
101 else:
102 # We need to do this when we're run through repo. Since repo executes
103 # us with execfile(), we don't get __file__ defined.
104 cmd = ['repo', 'forall', 'chromiumos/repohooks', '-c', 'pwd']
105 return _run_command(cmd).strip()
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700106
Ryan Cui1562fb82011-05-09 11:01:31 -0700107
Ryan Cuiec4d6332011-05-02 14:15:25 -0700108def _match_regex_list(subject, expressions):
109 """Try to match a list of regular expressions to a string.
110
111 Args:
112 subject: The string to match regexes on
113 expressions: A list of regular expressions to check for matches with.
114
115 Returns:
116 Whether the passed in subject matches any of the passed in regexes.
117 """
118 for expr in expressions:
119 if (re.search(expr, subject)):
120 return True
121 return False
122
Ryan Cui1562fb82011-05-09 11:01:31 -0700123
Ryan Cuiec4d6332011-05-02 14:15:25 -0700124def _filter_files(files, include_list, exclude_list=[]):
125 """Filter out files based on the conditions passed in.
126
127 Args:
128 files: list of filepaths to filter
129 include_list: list of regex that when matched with a file path will cause it
130 to be added to the output list unless the file is also matched with a
131 regex in the exclude_list.
132 exclude_list: list of regex that when matched with a file will prevent it
133 from being added to the output list, even if it is also matched with a
134 regex in the include_list.
135
136 Returns:
137 A list of filepaths that contain files matched in the include_list and not
138 in the exclude_list.
139 """
140 filtered = []
141 for f in files:
142 if (_match_regex_list(f, include_list) and
143 not _match_regex_list(f, exclude_list)):
144 filtered.append(f)
145 return filtered
146
Ryan Cuiec4d6332011-05-02 14:15:25 -0700147
David Hendricks35030d02013-02-04 17:49:16 -0800148def _verify_header_content(commit, content, fail_msg):
149 """Verify that file headers contain specified content.
150
151 Args:
152 commit: the affected commit.
153 content: the content of the header to be verified.
154 fail_msg: the first message to display in case of failure.
155
156 Returns:
157 The return value of HookFailure().
158 """
159 license_re = re.compile(content, re.MULTILINE)
160 bad_files = []
161 files = _filter_files(_get_affected_files(commit),
162 COMMON_INCLUDED_PATHS,
163 COMMON_EXCLUDED_PATHS)
164
165 for f in files:
Gabe Blackcf3c32c2013-02-27 00:26:13 -0800166 if os.path.exists(f): # Ignore non-existant files
167 contents = open(f).read()
168 if len(contents) == 0: continue # Ignore empty files
169 if not license_re.search(contents):
170 bad_files.append(f)
David Hendricks35030d02013-02-04 17:49:16 -0800171 if bad_files:
172 msg = "%s:\n%s\n%s" % (fail_msg, license_re.pattern,
173 "Found a bad header in these files:")
174 return HookFailure(msg, bad_files)
175
176
Ryan Cuiec4d6332011-05-02 14:15:25 -0700177# Git Helpers
Ryan Cui1562fb82011-05-09 11:01:31 -0700178
179
Ryan Cui4725d952011-05-05 15:41:19 -0700180def _get_upstream_branch():
181 """Returns the upstream tracking branch of the current branch.
182
183 Raises:
184 Error if there is no tracking branch
185 """
186 current_branch = _run_command(['git', 'symbolic-ref', 'HEAD']).strip()
187 current_branch = current_branch.replace('refs/heads/', '')
188 if not current_branch:
Ryan Cui1562fb82011-05-09 11:01:31 -0700189 raise VerifyException('Need to be on a tracking branch')
Ryan Cui4725d952011-05-05 15:41:19 -0700190
191 cfg_option = 'branch.' + current_branch + '.%s'
192 full_upstream = _run_command(['git', 'config', cfg_option % 'merge']).strip()
193 remote = _run_command(['git', 'config', cfg_option % 'remote']).strip()
194 if not remote or not full_upstream:
Ryan Cui1562fb82011-05-09 11:01:31 -0700195 raise VerifyException('Need to be on a tracking branch')
Ryan Cui4725d952011-05-05 15:41:19 -0700196
197 return full_upstream.replace('heads', 'remotes/' + remote)
198
Ryan Cui1562fb82011-05-09 11:01:31 -0700199
Che-Liang Chiou5ce2d7b2013-03-22 18:47:55 -0700200def _get_patch(commit):
201 """Returns the patch for this commit."""
202 return _run_command(['git', 'format-patch', '--stdout', '-1', commit])
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700203
Ryan Cui1562fb82011-05-09 11:01:31 -0700204
Jon Salz98255932012-08-18 14:48:02 +0800205def _try_utf8_decode(data):
206 """Attempts to decode a string as UTF-8.
207
208 Returns:
209 The decoded Unicode object, or the original string if parsing fails.
210 """
211 try:
212 return unicode(data, 'utf-8', 'strict')
213 except UnicodeDecodeError:
214 return data
215
216
Ryan Cuiec4d6332011-05-02 14:15:25 -0700217def _get_file_diff(file, commit):
218 """Returns a list of (linenum, lines) tuples that the commit touched."""
Ryan Cui72834d12011-05-05 14:51:33 -0700219 output = _run_command(['git', 'show', '-p', '--no-ext-diff', commit, file])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700220
221 new_lines = []
222 line_num = 0
223 for line in output.splitlines():
224 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
225 if m:
226 line_num = int(m.groups(1)[0])
227 continue
228 if line.startswith('+') and not line.startswith('++'):
Jon Salz98255932012-08-18 14:48:02 +0800229 new_lines.append((line_num, _try_utf8_decode(line[1:])))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700230 if not line.startswith('-'):
231 line_num += 1
232 return new_lines
233
Ryan Cui1562fb82011-05-09 11:01:31 -0700234
Doug Anderson42b8a052013-06-26 10:45:36 -0700235def _get_affected_files(commit, include_deletes=False):
236 """Returns list of absolute filepaths that were modified/added.
237
238 Args:
239 commit: The commit
240 include_deletes: If true we'll include delete in the list.
241
242 Returns:
243 A list of modified/added (and perhaps deleted) files
244 """
Ryan Cui72834d12011-05-05 14:51:33 -0700245 output = _run_command(['git', 'diff', '--name-status', commit + '^!'])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700246 files = []
247 for statusline in output.splitlines():
248 m = re.match('^(\w)+\t(.+)$', statusline.rstrip())
249 # Ignore deleted files, and return absolute paths of files
Doug Anderson42b8a052013-06-26 10:45:36 -0700250 if (include_deletes or m.group(1)[0] != 'D'):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700251 pwd = os.getcwd()
252 files.append(os.path.join(pwd, m.group(2)))
253 return files
254
Ryan Cui1562fb82011-05-09 11:01:31 -0700255
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700256def _get_commits():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700257 """Returns a list of commits for this review."""
Ryan Cui4725d952011-05-05 15:41:19 -0700258 cmd = ['git', 'log', '%s..' % _get_upstream_branch(), '--format=%H']
Ryan Cui72834d12011-05-05 14:51:33 -0700259 return _run_command(cmd).split()
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700260
Ryan Cui1562fb82011-05-09 11:01:31 -0700261
Ryan Cuiec4d6332011-05-02 14:15:25 -0700262def _get_commit_desc(commit):
263 """Returns the full commit message of a commit."""
Sean Paul23a2c582011-05-06 13:10:44 -0400264 return _run_command(['git', 'log', '--format=%s%n%n%b', commit + '^!'])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700265
266
267# Common Hooks
268
Ryan Cui1562fb82011-05-09 11:01:31 -0700269
Ryan Cuiec4d6332011-05-02 14:15:25 -0700270def _check_no_long_lines(project, commit):
271 """Checks that there aren't any lines longer than maxlen characters in any of
272 the text files to be submitted.
273 """
274 MAX_LEN = 80
Jon Salz98255932012-08-18 14:48:02 +0800275 SKIP_REGEXP = re.compile('|'.join([
276 r'https?://',
277 r'^#\s*(define|include|import|pragma|if|endif)\b']))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700278
279 errors = []
280 files = _filter_files(_get_affected_files(commit),
281 COMMON_INCLUDED_PATHS,
282 COMMON_EXCLUDED_PATHS)
283
284 for afile in files:
285 for line_num, line in _get_file_diff(afile, commit):
286 # Allow certain lines to exceed the maxlen rule.
Jon Salz98255932012-08-18 14:48:02 +0800287 if (len(line) <= MAX_LEN or SKIP_REGEXP.search(line)):
288 continue
289
290 errors.append('%s, line %s, %s chars' % (afile, line_num, len(line)))
291 if len(errors) == 5: # Just show the first 5 errors.
292 break
Ryan Cuiec4d6332011-05-02 14:15:25 -0700293
294 if errors:
295 msg = 'Found lines longer than %s characters (first 5 shown):' % MAX_LEN
Ryan Cui1562fb82011-05-09 11:01:31 -0700296 return HookFailure(msg, errors)
297
Ryan Cuiec4d6332011-05-02 14:15:25 -0700298
299def _check_no_stray_whitespace(project, commit):
300 """Checks that there is no stray whitespace at source lines end."""
301 errors = []
302 files = _filter_files(_get_affected_files(commit),
303 COMMON_INCLUDED_PATHS,
304 COMMON_EXCLUDED_PATHS)
305
306 for afile in files:
307 for line_num, line in _get_file_diff(afile, commit):
308 if line.rstrip() != line:
309 errors.append('%s, line %s' % (afile, line_num))
310 if errors:
Ryan Cui1562fb82011-05-09 11:01:31 -0700311 return HookFailure('Found line ending with white space in:', errors)
312
Ryan Cuiec4d6332011-05-02 14:15:25 -0700313
314def _check_no_tabs(project, commit):
315 """Checks there are no unexpanded tabs."""
316 TAB_OK_PATHS = [
Ryan Cui31e0c172011-05-04 21:00:45 -0700317 r"/src/third_party/u-boot/",
Ryan Cuiec4d6332011-05-02 14:15:25 -0700318 r".*\.ebuild$",
319 r".*\.eclass$",
Elly Jones5ab34192011-11-15 14:57:06 -0500320 r".*/[M|m]akefile$",
321 r".*\.mk$"
Ryan Cuiec4d6332011-05-02 14:15:25 -0700322 ]
323
324 errors = []
325 files = _filter_files(_get_affected_files(commit),
326 COMMON_INCLUDED_PATHS,
327 COMMON_EXCLUDED_PATHS + TAB_OK_PATHS)
328
329 for afile in files:
330 for line_num, line in _get_file_diff(afile, commit):
331 if '\t' in line:
332 errors.append('%s, line %s' % (afile, line_num))
333 if errors:
Ryan Cui1562fb82011-05-09 11:01:31 -0700334 return HookFailure('Found a tab character in:', errors)
335
Ryan Cuiec4d6332011-05-02 14:15:25 -0700336
337def _check_change_has_test_field(project, commit):
338 """Check for a non-empty 'TEST=' field in the commit message."""
David McMahon8f6553e2011-06-10 15:46:36 -0700339 TEST_RE = r'\nTEST=\S+'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700340
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700341 if not re.search(TEST_RE, _get_commit_desc(commit)):
Ryan Cui1562fb82011-05-09 11:01:31 -0700342 msg = 'Changelist description needs TEST field (after first line)'
343 return HookFailure(msg)
344
Ryan Cuiec4d6332011-05-02 14:15:25 -0700345
David Jamesc3b68b32013-04-03 09:17:03 -0700346def _check_change_has_valid_cq_depend(project, commit):
347 """Check for a correctly formatted CQ-DEPEND field in the commit message."""
348 msg = 'Changelist has invalid CQ-DEPEND target.'
349 example = 'Example: CQ-DEPEND=CL:1234, CL:2345'
350 try:
351 patch.GetPaladinDeps(_get_commit_desc(commit))
352 except ValueError as ex:
353 return HookFailure(msg, [example, str(ex)])
354
355
Ryan Cuiec4d6332011-05-02 14:15:25 -0700356def _check_change_has_bug_field(project, commit):
David McMahon8f6553e2011-06-10 15:46:36 -0700357 """Check for a correctly formatted 'BUG=' field in the commit message."""
David James5c0073d2013-04-03 08:48:52 -0700358 OLD_BUG_RE = r'\nBUG=.*chromium-os'
359 if re.search(OLD_BUG_RE, _get_commit_desc(commit)):
360 msg = ('The chromium-os bug tracker is now deprecated. Please use\n'
361 'the chromium tracker in your BUG= line now.')
362 return HookFailure(msg)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700363
David James5c0073d2013-04-03 08:48:52 -0700364 BUG_RE = r'\nBUG=([Nn]one|(chrome-os-partner|chromium):\d+)'
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700365 if not re.search(BUG_RE, _get_commit_desc(commit)):
David McMahon8f6553e2011-06-10 15:46:36 -0700366 msg = ('Changelist description needs BUG field (after first line):\n'
David James5c0073d2013-04-03 08:48:52 -0700367 'BUG=chromium:9999 (for public tracker)\n'
David McMahon8f6553e2011-06-10 15:46:36 -0700368 'BUG=chrome-os-partner:9999 (for partner tracker)\n'
369 'BUG=None')
Ryan Cui1562fb82011-05-09 11:01:31 -0700370 return HookFailure(msg)
371
Ryan Cuiec4d6332011-05-02 14:15:25 -0700372
Doug Anderson42b8a052013-06-26 10:45:36 -0700373def _check_for_uprev(project, commit):
374 """Check that we're not missing a revbump of an ebuild in the given commit.
375
376 If the given commit touches files in a directory that has ebuilds somewhere
377 up the directory hierarchy, it's very likely that we need an ebuild revbump
378 in order for those changes to take effect.
379
380 It's not totally trivial to detect a revbump, so at least detect that an
381 ebuild with a revision number in it was touched. This should handle the
382 common case where we use a symlink to do the revbump.
383
384 TODO: it would be nice to enhance this hook to:
385 * Handle cases where people revbump with a slightly different syntax. I see
386 one ebuild (puppy) that revbumps with _pN. This is a false positive.
387 * Catches cases where people aren't using symlinks for revbumps. If they
388 edit a revisioned file directly (and are expected to rename it for revbump)
389 we'll miss that. Perhaps we could detect that the file touched is a
390 symlink?
391
392 If a project doesn't use symlinks we'll potentially miss a revbump, but we're
393 still better off than without this check.
394
395 Args:
396 project: The project to look at
397 commit: The commit to look at
398
399 Returns:
400 A HookFailure or None.
401 """
402 affected_paths = _get_affected_files(commit, include_deletes=True)
403
404 # Don't yell about changes to whitelisted files...
405 whitelist = ['Manifest', 'metadata.xml']
406 affected_paths = [path for path in affected_paths
407 if os.path.basename(path) not in whitelist]
408 if not affected_paths:
409 return None
410
411 # If we've touched any file named with a -rN.ebuild then we'll say we're
412 # OK right away. See TODO above about enhancing this.
413 touched_revved_ebuild = any(re.search(r'-r\d*\.ebuild$', path)
414 for path in affected_paths)
415 if touched_revved_ebuild:
416 return None
417
418 # We want to examine the current contents of all directories that are parents
419 # of files that were touched (up to the top of the project).
420 #
421 # ...note: we use the current directory contents even though it may have
422 # changed since the commit we're looking at. This is just a heuristic after
423 # all. Worst case we don't flag a missing revbump.
424 project_top = os.getcwd()
425 dirs_to_check = set([project_top])
426 for path in affected_paths:
427 path = os.path.dirname(path)
428 while os.path.exists(path) and not os.path.samefile(path, project_top):
429 dirs_to_check.add(path)
430 path = os.path.dirname(path)
431
432 # Look through each directory. If it's got an ebuild in it then we'll
433 # consider this as a case when we need a revbump.
434 for dir_path in dirs_to_check:
435 contents = os.listdir(dir_path)
436 ebuilds = [os.path.join(dir_path, path)
437 for path in contents if path.endswith('.ebuild')]
438 ebuilds_9999 = [path for path in ebuilds if path.endswith('-9999.ebuild')]
439
440 # If the -9999.ebuild file was touched the bot will uprev for us.
441 # ...we'll use a simple intersection here as a heuristic...
442 if set(ebuilds_9999) & set(affected_paths):
443 continue
444
445 if ebuilds:
446 return HookFailure('Changelist probably needs a revbump of an ebuild\n'
447 'or a -r1.ebuild symlink if this is a new ebuild')
448
449 return None
450
451
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800452def _check_ebuild_licenses(_project, commit):
453 """Check if the LICENSE field in the ebuild is correct."""
454 affected_paths = _get_affected_files(commit)
455 touched_ebuilds = [x for x in affected_paths if x.endswith('.ebuild')]
456
457 # A list of licenses to ignore for now.
458 LICENSES_IGNORE = ['||', '(', ')', 'Proprietary', 'as-is']
459
460 for ebuild in touched_ebuilds:
461 # Skip virutal packages.
462 if ebuild.split('/')[-3] == 'virtual':
463 continue
464
465 try:
466 license_types = licenses.GetLicenseTypesFromEbuild(ebuild)
467 except ValueError as e:
468 return HookFailure(e.message, [ebuild])
469
470 # Also ignore licenses ending with '?'
471 for license_type in [x for x in license_types
472 if x not in LICENSES_IGNORE and not x.endswith('?')]:
473 try:
474 licenses.Licensing.FindLicenseType(license_type)
475 except AssertionError as e:
476 return HookFailure(e.message, [ebuild])
477
478
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700479def _check_change_has_proper_changeid(project, commit):
480 """Verify that Change-ID is present in last paragraph of commit message."""
481 desc = _get_commit_desc(commit)
482 loc = desc.rfind('\nChange-Id:')
483 if loc == -1 or re.search('\n\s*\n\s*\S+', desc[loc:]):
Ryan Cui1562fb82011-05-09 11:01:31 -0700484 return HookFailure('Change-Id must be in last paragraph of description.')
485
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700486
Ryan Cuiec4d6332011-05-02 14:15:25 -0700487def _check_license(project, commit):
488 """Verifies the license header."""
489 LICENSE_HEADER = (
David Hendricks0af30eb2013-02-05 11:35:56 -0800490 r".* Copyright \(c\) 20[-0-9]{2,7} The Chromium OS Authors\. All rights "
Ryan Cuiec4d6332011-05-02 14:15:25 -0700491 r"reserved\." "\n"
David Hendricks0af30eb2013-02-05 11:35:56 -0800492 r".* Use of this source code is governed by a BSD-style license that can "
Ryan Cuiec4d6332011-05-02 14:15:25 -0700493 "be\n"
David Hendricks0af30eb2013-02-05 11:35:56 -0800494 r".* found in the LICENSE file\."
Ryan Cuiec4d6332011-05-02 14:15:25 -0700495 "\n"
496 )
David Hendricks35030d02013-02-04 17:49:16 -0800497 FAIL_MSG = "License must match"
Ryan Cuiec4d6332011-05-02 14:15:25 -0700498
David Hendricks35030d02013-02-04 17:49:16 -0800499 return _verify_header_content(commit, LICENSE_HEADER, FAIL_MSG)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700500
501
David Hendricksa0e310d2013-02-04 17:51:55 -0800502def _check_google_copyright(project, commit):
503 """Verifies Google Inc. as copyright holder."""
504 LICENSE_HEADER = (
505 r".* Copyright 20[-0-9]{2,7} Google Inc\."
506 )
507 FAIL_MSG = "Copyright must match"
508
David Hendricks4c018e72013-02-06 13:46:38 -0800509 # Avoid blocking partners and external contributors.
510 fqdn = socket.getfqdn()
511 if not fqdn.endswith(".corp.google.com"):
512 return None
513
David Hendricksa0e310d2013-02-04 17:51:55 -0800514 return _verify_header_content(commit, LICENSE_HEADER, FAIL_MSG)
515
516
Ryan Cuiec4d6332011-05-02 14:15:25 -0700517# Project-specific hooks
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700518
Ryan Cui1562fb82011-05-09 11:01:31 -0700519
Anton Staaf815d6852011-08-22 10:08:45 -0700520def _run_checkpatch(project, commit, options=[]):
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700521 """Runs checkpatch.pl on the given project"""
522 hooks_dir = _get_hooks_dir()
Anton Staaf815d6852011-08-22 10:08:45 -0700523 cmd = ['%s/checkpatch.pl' % hooks_dir] + options + ['-']
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700524 p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Che-Liang Chiou5ce2d7b2013-03-22 18:47:55 -0700525 output = p.communicate(_get_patch(commit))[0]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700526 if p.returncode:
Ryan Cui1562fb82011-05-09 11:01:31 -0700527 return HookFailure('checkpatch.pl errors/warnings\n\n' + output)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700528
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700529
Anton Staaf815d6852011-08-22 10:08:45 -0700530def _run_checkpatch_no_tree(project, commit):
531 return _run_checkpatch(project, commit, ['--no-tree'])
532
Randall Spangler7318fd62013-11-21 12:16:58 -0800533def _run_checkpatch_ec(project, commit):
534 """Runs checkpatch with options for Chromium EC projects."""
535 return _run_checkpatch(project, commit, ['--no-tree',
536 '--ignore=MSLEEP,VOLATILE'])
537
Olof Johanssona96810f2012-09-04 16:20:03 -0700538def _kernel_configcheck(project, commit):
539 """Makes sure kernel config changes are not mixed with code changes"""
540 files = _get_affected_files(commit)
541 if not len(_filter_files(files, [r'chromeos/config'])) in [0, len(files)]:
542 return HookFailure('Changes to chromeos/config/ and regular files must '
543 'be in separate commits:\n%s' % '\n'.join(files))
Anton Staaf815d6852011-08-22 10:08:45 -0700544
Dale Curtis2975c432011-05-03 17:25:20 -0700545def _run_json_check(project, commit):
546 """Checks that all JSON files are syntactically valid."""
Dale Curtisa039cfd2011-05-04 12:01:05 -0700547 for f in _filter_files(_get_affected_files(commit), [r'.*\.json']):
Dale Curtis2975c432011-05-03 17:25:20 -0700548 try:
549 json.load(open(f))
550 except Exception, e:
Ryan Cui1562fb82011-05-09 11:01:31 -0700551 return HookFailure('Invalid JSON in %s: %s' % (f, e))
Dale Curtis2975c432011-05-03 17:25:20 -0700552
553
Mike Frysinger52b537e2013-08-22 22:59:53 -0400554def _check_manifests(project, commit):
555 """Make sure Manifest files only have DIST lines"""
556 paths = []
557
558 for path in _get_affected_files(commit):
559 if os.path.basename(path) != 'Manifest':
560 continue
561 if not os.path.exists(path):
562 continue
563
564 with open(path, 'r') as f:
565 for line in f.readlines():
566 if not line.startswith('DIST '):
567 paths.append(path)
568 break
569
570 if paths:
571 return HookFailure('Please remove lines that do not start with DIST:\n%s' %
572 ('\n'.join(paths),))
573
574
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700575def _check_change_has_branch_field(project, commit):
576 """Check for a non-empty 'BRANCH=' field in the commit message."""
577 BRANCH_RE = r'\nBRANCH=\S+'
578
579 if not re.search(BRANCH_RE, _get_commit_desc(commit)):
580 msg = ('Changelist description needs BRANCH field (after first line)\n'
581 'E.g. BRANCH=none or BRANCH=link,snow')
582 return HookFailure(msg)
583
584
Jon Salz3ee59de2012-08-18 13:54:22 +0800585def _run_project_hook_script(script, project, commit):
586 """Runs a project hook script.
587
588 The script is run with the following environment variables set:
589 PRESUBMIT_PROJECT: The affected project
590 PRESUBMIT_COMMIT: The affected commit
591 PRESUBMIT_FILES: A newline-separated list of affected files
592
593 The script is considered to fail if the exit code is non-zero. It should
594 write an error message to stdout.
595 """
596 env = dict(os.environ)
597 env['PRESUBMIT_PROJECT'] = project
598 env['PRESUBMIT_COMMIT'] = commit
599
600 # Put affected files in an environment variable
601 files = _get_affected_files(commit)
602 env['PRESUBMIT_FILES'] = '\n'.join(files)
603
604 process = subprocess.Popen(script, env=env, shell=True,
605 stdin=open(os.devnull),
Jon Salz7b618af2012-08-31 06:03:16 +0800606 stdout=subprocess.PIPE,
607 stderr=subprocess.STDOUT)
Jon Salz3ee59de2012-08-18 13:54:22 +0800608 stdout, _ = process.communicate()
609 if process.wait():
Jon Salz7b618af2012-08-31 06:03:16 +0800610 if stdout:
611 stdout = re.sub('(?m)^', ' ', stdout)
612 return HookFailure('Hook script "%s" failed with code %d%s' %
Jon Salz3ee59de2012-08-18 13:54:22 +0800613 (script, process.returncode,
614 ':\n' + stdout if stdout else ''))
615
616
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700617# Base
618
Ryan Cui1562fb82011-05-09 11:01:31 -0700619
Ryan Cui9b651632011-05-11 11:38:58 -0700620# A list of hooks that are not project-specific
621_COMMON_HOOKS = [
622 _check_change_has_bug_field,
David Jamesc3b68b32013-04-03 09:17:03 -0700623 _check_change_has_valid_cq_depend,
Ryan Cui9b651632011-05-11 11:38:58 -0700624 _check_change_has_test_field,
625 _check_change_has_proper_changeid,
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800626 _check_ebuild_licenses,
Ryan Cui9b651632011-05-11 11:38:58 -0700627 _check_no_stray_whitespace,
628 _check_no_long_lines,
629 _check_license,
630 _check_no_tabs,
Doug Anderson42b8a052013-06-26 10:45:36 -0700631 _check_for_uprev,
Ryan Cui9b651632011-05-11 11:38:58 -0700632]
Ryan Cuiec4d6332011-05-02 14:15:25 -0700633
Ryan Cui1562fb82011-05-09 11:01:31 -0700634
Ryan Cui9b651632011-05-11 11:38:58 -0700635# A dictionary of project-specific hooks(callbacks), indexed by project name.
636# dict[project] = [callback1, callback2]
637_PROJECT_SPECIFIC_HOOKS = {
Mike Frysingerdf980702013-08-22 22:25:22 -0400638 "chromeos/autotest-tools": [_run_json_check],
Mike Frysinger52b537e2013-08-22 22:59:53 -0400639 "chromeos/overlays/chromeos-overlay": [_check_manifests],
640 "chromeos/overlays/chromeos-partner-overlay": [_check_manifests],
Randall Spangler7318fd62013-11-21 12:16:58 -0800641 "chromeos/platform/ec-private": [_run_checkpatch_ec,
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700642 _check_change_has_branch_field],
David Hendricks33f77d52013-02-04 17:53:02 -0800643 "chromeos/third_party/coreboot": [_check_change_has_branch_field,
644 _check_google_copyright],
Puneet Kumar57b9c092012-08-14 18:58:29 -0700645 "chromeos/third_party/intel-framework": [_check_change_has_branch_field],
Mike Frysingerdf980702013-08-22 22:25:22 -0400646 "chromeos/vendor/kernel-exynos-staging": [_run_checkpatch,
647 _kernel_configcheck],
648 "chromeos/vendor/u-boot-exynos": [_run_checkpatch_no_tree],
Mike Frysinger52b537e2013-08-22 22:59:53 -0400649 "chromiumos/overlays/board-overlays": [_check_manifests],
650 "chromiumos/overlays/chromiumos-overlay": [_check_manifests],
651 "chromiumos/overlays/portage-stable": [_check_manifests],
Randall Spangler7318fd62013-11-21 12:16:58 -0800652 "chromiumos/platform/ec": [_run_checkpatch_ec,
Mike Frysingerdf980702013-08-22 22:25:22 -0400653 _check_change_has_branch_field],
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700654 "chromiumos/platform/mosys": [_check_change_has_branch_field],
Mike Frysingerdf980702013-08-22 22:25:22 -0400655 "chromiumos/platform/vboot_reference": [_check_change_has_branch_field],
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700656 "chromiumos/third_party/flashrom": [_check_change_has_branch_field],
Mike Frysingerdf980702013-08-22 22:25:22 -0400657 "chromiumos/third_party/kernel": [_run_checkpatch, _kernel_configcheck],
658 "chromiumos/third_party/kernel-next": [_run_checkpatch,
659 _kernel_configcheck],
660 "chromiumos/third_party/u-boot": [_run_checkpatch_no_tree,
661 _check_change_has_branch_field],
Ryan Cui9b651632011-05-11 11:38:58 -0700662}
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700663
Ryan Cui1562fb82011-05-09 11:01:31 -0700664
Ryan Cui9b651632011-05-11 11:38:58 -0700665# A dictionary of flags (keys) that can appear in the config file, and the hook
666# that the flag disables (value)
667_DISABLE_FLAGS = {
668 'stray_whitespace_check': _check_no_stray_whitespace,
669 'long_line_check': _check_no_long_lines,
670 'cros_license_check': _check_license,
671 'tab_check': _check_no_tabs,
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700672 'branch_check': _check_change_has_branch_field,
Ryan Cui9b651632011-05-11 11:38:58 -0700673}
674
675
Jon Salz3ee59de2012-08-18 13:54:22 +0800676def _get_disabled_hooks(config):
Ryan Cui9b651632011-05-11 11:38:58 -0700677 """Returns a set of hooks disabled by the current project's config file.
678
679 Expects to be called within the project root.
Jon Salz3ee59de2012-08-18 13:54:22 +0800680
681 Args:
682 config: A ConfigParser for the project's config file.
Ryan Cui9b651632011-05-11 11:38:58 -0700683 """
684 SECTION = 'Hook Overrides'
Jon Salz3ee59de2012-08-18 13:54:22 +0800685 if not config.has_section(SECTION):
686 return set()
Ryan Cui9b651632011-05-11 11:38:58 -0700687
688 disable_flags = []
Jon Salz3ee59de2012-08-18 13:54:22 +0800689 for flag in config.options(SECTION):
Ryan Cui9b651632011-05-11 11:38:58 -0700690 try:
691 if not config.getboolean(SECTION, flag): disable_flags.append(flag)
692 except ValueError as e:
693 msg = "Error parsing flag \'%s\' in %s file - " % (flag, _CONFIG_FILE)
Mike Frysinger09d6a3d2013-10-08 22:21:03 -0400694 print(msg + str(e))
Ryan Cui9b651632011-05-11 11:38:58 -0700695
696 disabled_keys = set(_DISABLE_FLAGS.iterkeys()).intersection(disable_flags)
697 return set([_DISABLE_FLAGS[key] for key in disabled_keys])
698
699
Jon Salz3ee59de2012-08-18 13:54:22 +0800700def _get_project_hook_scripts(config):
701 """Returns a list of project-specific hook scripts.
702
703 Args:
704 config: A ConfigParser for the project's config file.
705 """
706 SECTION = 'Hook Scripts'
707 if not config.has_section(SECTION):
708 return []
709
710 hook_names_values = config.items(SECTION)
711 hook_names_values.sort(key=lambda x: x[0])
712 return [x[1] for x in hook_names_values]
713
714
Ryan Cui9b651632011-05-11 11:38:58 -0700715def _get_project_hooks(project):
716 """Returns a list of hooks that need to be run for a project.
717
718 Expects to be called from within the project root.
719 """
Jon Salz3ee59de2012-08-18 13:54:22 +0800720 config = ConfigParser.RawConfigParser()
721 try:
722 config.read(_CONFIG_FILE)
723 except ConfigParser.Error:
724 # Just use an empty config file
725 config = ConfigParser.RawConfigParser()
726
727 disabled_hooks = _get_disabled_hooks(config)
Ryan Cui9b651632011-05-11 11:38:58 -0700728 hooks = [hook for hook in _COMMON_HOOKS if hook not in disabled_hooks]
729
730 if project in _PROJECT_SPECIFIC_HOOKS:
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700731 hooks.extend(hook for hook in _PROJECT_SPECIFIC_HOOKS[project]
732 if hook not in disabled_hooks)
Ryan Cui9b651632011-05-11 11:38:58 -0700733
Jon Salz3ee59de2012-08-18 13:54:22 +0800734 for script in _get_project_hook_scripts(config):
735 hooks.append(functools.partial(_run_project_hook_script, script))
736
Ryan Cui9b651632011-05-11 11:38:58 -0700737 return hooks
738
739
Doug Anderson14749562013-06-26 13:38:29 -0700740def _run_project_hooks(project, proj_dir=None, commit_list=None):
Ryan Cui1562fb82011-05-09 11:01:31 -0700741 """For each project run its project specific hook from the hooks dictionary.
742
743 Args:
Doug Anderson44a644f2011-11-02 10:37:37 -0700744 project: The name of project to run hooks for.
745 proj_dir: If non-None, this is the directory the project is in. If None,
746 we'll ask repo.
Doug Anderson14749562013-06-26 13:38:29 -0700747 commit_list: A list of commits to run hooks against. If None or empty list
748 then we'll automatically get the list of commits that would be uploaded.
Ryan Cui1562fb82011-05-09 11:01:31 -0700749
750 Returns:
751 Boolean value of whether any errors were ecountered while running the hooks.
752 """
Doug Anderson44a644f2011-11-02 10:37:37 -0700753 if proj_dir is None:
David James2edd9002013-10-11 14:09:19 -0700754 proj_dirs = _run_command(['repo', 'forall', project, '-c', 'pwd']).split()
755 if len(proj_dirs) == 0:
756 print('%s cannot be found.' % project, file=sys.stderr)
757 print('Please specify a valid project.', file=sys.stderr)
758 return True
759 if len(proj_dirs) > 1:
760 print('%s is associated with multiple directories.' % project,
761 file=sys.stderr)
762 print('Please specify a directory to help disambiguate.', file=sys.stderr)
763 return True
764 proj_dir = proj_dirs[0]
Doug Anderson44a644f2011-11-02 10:37:37 -0700765
Ryan Cuiec4d6332011-05-02 14:15:25 -0700766 pwd = os.getcwd()
767 # hooks assume they are run from the root of the project
768 os.chdir(proj_dir)
769
Doug Anderson14749562013-06-26 13:38:29 -0700770 if not commit_list:
771 try:
772 commit_list = _get_commits()
773 except VerifyException as e:
774 PrintErrorForProject(project, HookFailure(str(e)))
775 os.chdir(pwd)
776 return True
Ryan Cuifa55df52011-05-06 11:16:55 -0700777
Ryan Cui9b651632011-05-11 11:38:58 -0700778 hooks = _get_project_hooks(project)
Ryan Cui1562fb82011-05-09 11:01:31 -0700779 error_found = False
Ryan Cuifa55df52011-05-06 11:16:55 -0700780 for commit in commit_list:
Ryan Cui1562fb82011-05-09 11:01:31 -0700781 error_list = []
Ryan Cui9b651632011-05-11 11:38:58 -0700782 for hook in hooks:
Ryan Cui1562fb82011-05-09 11:01:31 -0700783 hook_error = hook(project, commit)
784 if hook_error:
785 error_list.append(hook_error)
786 error_found = True
787 if error_list:
788 PrintErrorsForCommit(project, commit, _get_commit_desc(commit),
789 error_list)
Don Garrettdba548a2011-05-05 15:17:14 -0700790
Ryan Cuiec4d6332011-05-02 14:15:25 -0700791 os.chdir(pwd)
Ryan Cui1562fb82011-05-09 11:01:31 -0700792 return error_found
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700793
794# Main
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -0700795
Ryan Cui1562fb82011-05-09 11:01:31 -0700796
David James2edd9002013-10-11 14:09:19 -0700797def main(project_list, worktree_list=None, **kwargs):
Doug Anderson06456632012-01-05 11:02:14 -0800798 """Main function invoked directly by repo.
799
800 This function will exit directly upon error so that repo doesn't print some
801 obscure error message.
802
803 Args:
804 project_list: List of projects to run on.
David James2edd9002013-10-11 14:09:19 -0700805 worktree_list: A list of directories. It should be the same length as
806 project_list, so that each entry in project_list matches with a directory
807 in worktree_list. If None, we will attempt to calculate the directories
808 automatically.
Doug Anderson06456632012-01-05 11:02:14 -0800809 kwargs: Leave this here for forward-compatibility.
810 """
Ryan Cui1562fb82011-05-09 11:01:31 -0700811 found_error = False
David James2edd9002013-10-11 14:09:19 -0700812 if not worktree_list:
813 worktree_list = [None] * len(project_list)
814 for project, worktree in zip(project_list, worktree_list):
815 if _run_project_hooks(project, proj_dir=worktree):
Ryan Cui1562fb82011-05-09 11:01:31 -0700816 found_error = True
817
818 if (found_error):
819 msg = ('Preupload failed due to errors in project(s). HINTS:\n'
Ryan Cui9b651632011-05-11 11:38:58 -0700820 '- To disable some source style checks, and for other hints, see '
821 '<checkout_dir>/src/repohooks/README\n'
822 '- To upload only current project, run \'repo upload .\'')
Mike Frysinger09d6a3d2013-10-08 22:21:03 -0400823 print(msg, file=sys.stderr)
Don Garrettdba548a2011-05-05 15:17:14 -0700824 sys.exit(1)
Anush Elangovan63afad72011-03-23 00:41:27 -0700825
Ryan Cui1562fb82011-05-09 11:01:31 -0700826
Doug Anderson44a644f2011-11-02 10:37:37 -0700827def _identify_project(path):
828 """Identify the repo project associated with the given path.
829
830 Returns:
831 A string indicating what project is associated with the path passed in or
832 a blank string upon failure.
833 """
834 return _run_command(['repo', 'forall', '.', '-c', 'echo ${REPO_PROJECT}'],
835 stderr=subprocess.PIPE, cwd=path).strip()
836
837
838def direct_main(args, verbose=False):
839 """Run hooks directly (outside of the context of repo).
840
841 # Setup for doctests below.
842 # ...note that some tests assume that running pre-upload on this CWD is fine.
843 # TODO: Use mock and actually mock out _run_project_hooks() for tests.
844 >>> mydir = os.path.dirname(os.path.abspath(__file__))
845 >>> olddir = os.getcwd()
846
847 # OK to run w/ no arugments; will run with CWD.
848 >>> os.chdir(mydir)
849 >>> direct_main(['prog_name'], verbose=True)
850 Running hooks on chromiumos/repohooks
851 0
852 >>> os.chdir(olddir)
853
854 # Run specifying a dir
855 >>> direct_main(['prog_name', '--dir=%s' % mydir], verbose=True)
856 Running hooks on chromiumos/repohooks
857 0
858
859 # Not a problem to use a bogus project; we'll just get default settings.
860 >>> direct_main(['prog_name', '--dir=%s' % mydir, '--project=X'],verbose=True)
861 Running hooks on X
862 0
863
864 # Run with project but no dir
865 >>> os.chdir(mydir)
866 >>> direct_main(['prog_name', '--project=X'], verbose=True)
867 Running hooks on X
868 0
869 >>> os.chdir(olddir)
870
871 # Try with a non-git CWD
872 >>> os.chdir('/tmp')
873 >>> direct_main(['prog_name'])
874 Traceback (most recent call last):
875 ...
876 BadInvocation: The current directory is not part of a git project.
877
878 # Check various bad arguments...
879 >>> direct_main(['prog_name', 'bogus'])
880 Traceback (most recent call last):
881 ...
882 BadInvocation: Unexpected arguments: bogus
883 >>> direct_main(['prog_name', '--project=bogus', '--dir=bogusdir'])
884 Traceback (most recent call last):
885 ...
886 BadInvocation: Invalid dir: bogusdir
887 >>> direct_main(['prog_name', '--project=bogus', '--dir=/tmp'])
888 Traceback (most recent call last):
889 ...
890 BadInvocation: Not a git directory: /tmp
891
892 Args:
893 args: The value of sys.argv
894
895 Returns:
896 0 if no pre-upload failures, 1 if failures.
897
898 Raises:
899 BadInvocation: On some types of invocation errors.
900 """
901 desc = 'Run Chromium OS pre-upload hooks on changes compared to upstream.'
902 parser = optparse.OptionParser(description=desc)
903
904 parser.add_option('--dir', default=None,
905 help='The directory that the project lives in. If not '
906 'specified, use the git project root based on the cwd.')
907 parser.add_option('--project', default=None,
908 help='The project repo path; this can affect how the hooks '
909 'get run, since some hooks are project-specific. For '
910 'chromite this is chromiumos/chromite. If not specified, '
911 'the repo tool will be used to figure this out based on '
912 'the dir.')
Doug Anderson14749562013-06-26 13:38:29 -0700913 parser.add_option('--rerun-since', default=None,
914 help='Rerun hooks on old commits since the given date. '
915 'The date should match git log\'s concept of a date. '
916 'e.g. 2012-06-20')
917
918 parser.usage = "pre-upload.py [options] [commits]"
Doug Anderson44a644f2011-11-02 10:37:37 -0700919
920 opts, args = parser.parse_args(args[1:])
921
Doug Anderson14749562013-06-26 13:38:29 -0700922 if opts.rerun_since:
923 if args:
924 raise BadInvocation('Can\'t pass commits and use rerun-since: %s' %
925 ' '.join(args))
926
927 cmd = ['git', 'log', '--since="%s"' % opts.rerun_since, '--pretty=%H']
928 all_commits = _run_command(cmd).splitlines()
929 bot_commits = _run_command(cmd + ['--author=chrome-bot']).splitlines()
930
931 # Eliminate chrome-bot commits but keep ordering the same...
932 bot_commits = set(bot_commits)
933 args = [c for c in all_commits if c not in bot_commits]
934
Doug Anderson44a644f2011-11-02 10:37:37 -0700935
936 # Check/normlaize git dir; if unspecified, we'll use the root of the git
937 # project from CWD
938 if opts.dir is None:
939 git_dir = _run_command(['git', 'rev-parse', '--git-dir'],
940 stderr=subprocess.PIPE).strip()
941 if not git_dir:
942 raise BadInvocation('The current directory is not part of a git project.')
943 opts.dir = os.path.dirname(os.path.abspath(git_dir))
944 elif not os.path.isdir(opts.dir):
945 raise BadInvocation('Invalid dir: %s' % opts.dir)
946 elif not os.path.isdir(os.path.join(opts.dir, '.git')):
947 raise BadInvocation('Not a git directory: %s' % opts.dir)
948
949 # Identify the project if it wasn't specified; this _requires_ the repo
950 # tool to be installed and for the project to be part of a repo checkout.
951 if not opts.project:
952 opts.project = _identify_project(opts.dir)
953 if not opts.project:
954 raise BadInvocation("Repo couldn't identify the project of %s" % opts.dir)
955
956 if verbose:
Mike Frysinger09d6a3d2013-10-08 22:21:03 -0400957 print("Running hooks on %s" % (opts.project))
Doug Anderson44a644f2011-11-02 10:37:37 -0700958
Doug Anderson14749562013-06-26 13:38:29 -0700959 found_error = _run_project_hooks(opts.project, proj_dir=opts.dir,
960 commit_list=args)
Doug Anderson44a644f2011-11-02 10:37:37 -0700961 if found_error:
962 return 1
963 return 0
964
965
966def _test():
967 """Run any built-in tests."""
968 import doctest
969 doctest.testmod()
970
971
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -0700972if __name__ == '__main__':
Doug Anderson44a644f2011-11-02 10:37:37 -0700973 if sys.argv[1:2] == ["--test"]:
974 _test()
975 exit_code = 0
976 else:
977 prog_name = os.path.basename(sys.argv[0])
978 try:
979 exit_code = direct_main(sys.argv)
980 except BadInvocation, e:
Mike Frysinger09d6a3d2013-10-08 22:21:03 -0400981 print("%s: %s" % (prog_name, str(e)), file=sys.stderr)
Doug Anderson44a644f2011-11-02 10:37:37 -0700982 exit_code = 1
983 sys.exit(exit_code)