blob: b96ca55ecab22a4fcca0259b9982c391837992df [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 """
Mike Frysinger011af942014-01-17 16:12:22 -0500402 # If this is the portage-stable overlay, then ignore the check. It's rare
403 # that we're doing anything other than importing files from upstream, so
404 # forcing a rev bump makes no sense.
405 whitelist = (
406 'chromiumos/overlays/portage-stable',
407 )
408 if project in whitelist:
409 return None
410
Doug Anderson42b8a052013-06-26 10:45:36 -0700411 affected_paths = _get_affected_files(commit, include_deletes=True)
412
413 # Don't yell about changes to whitelisted files...
Mike Frysinger011af942014-01-17 16:12:22 -0500414 whitelist = ('ChangeLog', 'Manifest', 'metadata.xml')
Doug Anderson42b8a052013-06-26 10:45:36 -0700415 affected_paths = [path for path in affected_paths
416 if os.path.basename(path) not in whitelist]
417 if not affected_paths:
418 return None
419
420 # If we've touched any file named with a -rN.ebuild then we'll say we're
421 # OK right away. See TODO above about enhancing this.
422 touched_revved_ebuild = any(re.search(r'-r\d*\.ebuild$', path)
423 for path in affected_paths)
424 if touched_revved_ebuild:
425 return None
426
427 # We want to examine the current contents of all directories that are parents
428 # of files that were touched (up to the top of the project).
429 #
430 # ...note: we use the current directory contents even though it may have
431 # changed since the commit we're looking at. This is just a heuristic after
432 # all. Worst case we don't flag a missing revbump.
433 project_top = os.getcwd()
434 dirs_to_check = set([project_top])
435 for path in affected_paths:
436 path = os.path.dirname(path)
437 while os.path.exists(path) and not os.path.samefile(path, project_top):
438 dirs_to_check.add(path)
439 path = os.path.dirname(path)
440
441 # Look through each directory. If it's got an ebuild in it then we'll
442 # consider this as a case when we need a revbump.
443 for dir_path in dirs_to_check:
444 contents = os.listdir(dir_path)
445 ebuilds = [os.path.join(dir_path, path)
446 for path in contents if path.endswith('.ebuild')]
447 ebuilds_9999 = [path for path in ebuilds if path.endswith('-9999.ebuild')]
448
449 # If the -9999.ebuild file was touched the bot will uprev for us.
450 # ...we'll use a simple intersection here as a heuristic...
451 if set(ebuilds_9999) & set(affected_paths):
452 continue
453
454 if ebuilds:
455 return HookFailure('Changelist probably needs a revbump of an ebuild\n'
456 'or a -r1.ebuild symlink if this is a new ebuild')
457
458 return None
459
460
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800461def _check_ebuild_licenses(_project, commit):
462 """Check if the LICENSE field in the ebuild is correct."""
463 affected_paths = _get_affected_files(commit)
464 touched_ebuilds = [x for x in affected_paths if x.endswith('.ebuild')]
465
466 # A list of licenses to ignore for now.
467 LICENSES_IGNORE = ['||', '(', ')', 'Proprietary', 'as-is']
468
469 for ebuild in touched_ebuilds:
470 # Skip virutal packages.
471 if ebuild.split('/')[-3] == 'virtual':
472 continue
473
474 try:
475 license_types = licenses.GetLicenseTypesFromEbuild(ebuild)
476 except ValueError as e:
477 return HookFailure(e.message, [ebuild])
478
479 # Also ignore licenses ending with '?'
480 for license_type in [x for x in license_types
481 if x not in LICENSES_IGNORE and not x.endswith('?')]:
482 try:
483 licenses.Licensing.FindLicenseType(license_type)
484 except AssertionError as e:
485 return HookFailure(e.message, [ebuild])
486
487
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700488def _check_change_has_proper_changeid(project, commit):
489 """Verify that Change-ID is present in last paragraph of commit message."""
490 desc = _get_commit_desc(commit)
491 loc = desc.rfind('\nChange-Id:')
492 if loc == -1 or re.search('\n\s*\n\s*\S+', desc[loc:]):
Ryan Cui1562fb82011-05-09 11:01:31 -0700493 return HookFailure('Change-Id must be in last paragraph of description.')
494
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700495
Ryan Cuiec4d6332011-05-02 14:15:25 -0700496def _check_license(project, commit):
497 """Verifies the license header."""
498 LICENSE_HEADER = (
David Hendricks0af30eb2013-02-05 11:35:56 -0800499 r".* Copyright \(c\) 20[-0-9]{2,7} The Chromium OS Authors\. All rights "
Ryan Cuiec4d6332011-05-02 14:15:25 -0700500 r"reserved\." "\n"
David Hendricks0af30eb2013-02-05 11:35:56 -0800501 r".* Use of this source code is governed by a BSD-style license that can "
Ryan Cuiec4d6332011-05-02 14:15:25 -0700502 "be\n"
David Hendricks0af30eb2013-02-05 11:35:56 -0800503 r".* found in the LICENSE file\."
Ryan Cuiec4d6332011-05-02 14:15:25 -0700504 "\n"
505 )
David Hendricks35030d02013-02-04 17:49:16 -0800506 FAIL_MSG = "License must match"
Ryan Cuiec4d6332011-05-02 14:15:25 -0700507
David Hendricks35030d02013-02-04 17:49:16 -0800508 return _verify_header_content(commit, LICENSE_HEADER, FAIL_MSG)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700509
510
David Hendricksa0e310d2013-02-04 17:51:55 -0800511def _check_google_copyright(project, commit):
512 """Verifies Google Inc. as copyright holder."""
513 LICENSE_HEADER = (
514 r".* Copyright 20[-0-9]{2,7} Google Inc\."
515 )
516 FAIL_MSG = "Copyright must match"
517
David Hendricks4c018e72013-02-06 13:46:38 -0800518 # Avoid blocking partners and external contributors.
519 fqdn = socket.getfqdn()
520 if not fqdn.endswith(".corp.google.com"):
521 return None
522
David Hendricksa0e310d2013-02-04 17:51:55 -0800523 return _verify_header_content(commit, LICENSE_HEADER, FAIL_MSG)
524
525
Ryan Cuiec4d6332011-05-02 14:15:25 -0700526# Project-specific hooks
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700527
Ryan Cui1562fb82011-05-09 11:01:31 -0700528
Anton Staaf815d6852011-08-22 10:08:45 -0700529def _run_checkpatch(project, commit, options=[]):
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700530 """Runs checkpatch.pl on the given project"""
531 hooks_dir = _get_hooks_dir()
Anton Staaf815d6852011-08-22 10:08:45 -0700532 cmd = ['%s/checkpatch.pl' % hooks_dir] + options + ['-']
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700533 p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Che-Liang Chiou5ce2d7b2013-03-22 18:47:55 -0700534 output = p.communicate(_get_patch(commit))[0]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700535 if p.returncode:
Ryan Cui1562fb82011-05-09 11:01:31 -0700536 return HookFailure('checkpatch.pl errors/warnings\n\n' + output)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700537
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700538
Anton Staaf815d6852011-08-22 10:08:45 -0700539def _run_checkpatch_no_tree(project, commit):
540 return _run_checkpatch(project, commit, ['--no-tree'])
541
Randall Spangler7318fd62013-11-21 12:16:58 -0800542def _run_checkpatch_ec(project, commit):
543 """Runs checkpatch with options for Chromium EC projects."""
544 return _run_checkpatch(project, commit, ['--no-tree',
545 '--ignore=MSLEEP,VOLATILE'])
546
Olof Johanssona96810f2012-09-04 16:20:03 -0700547def _kernel_configcheck(project, commit):
548 """Makes sure kernel config changes are not mixed with code changes"""
549 files = _get_affected_files(commit)
550 if not len(_filter_files(files, [r'chromeos/config'])) in [0, len(files)]:
551 return HookFailure('Changes to chromeos/config/ and regular files must '
552 'be in separate commits:\n%s' % '\n'.join(files))
Anton Staaf815d6852011-08-22 10:08:45 -0700553
Dale Curtis2975c432011-05-03 17:25:20 -0700554def _run_json_check(project, commit):
555 """Checks that all JSON files are syntactically valid."""
Dale Curtisa039cfd2011-05-04 12:01:05 -0700556 for f in _filter_files(_get_affected_files(commit), [r'.*\.json']):
Dale Curtis2975c432011-05-03 17:25:20 -0700557 try:
558 json.load(open(f))
559 except Exception, e:
Ryan Cui1562fb82011-05-09 11:01:31 -0700560 return HookFailure('Invalid JSON in %s: %s' % (f, e))
Dale Curtis2975c432011-05-03 17:25:20 -0700561
562
Mike Frysinger52b537e2013-08-22 22:59:53 -0400563def _check_manifests(project, commit):
564 """Make sure Manifest files only have DIST lines"""
565 paths = []
566
567 for path in _get_affected_files(commit):
568 if os.path.basename(path) != 'Manifest':
569 continue
570 if not os.path.exists(path):
571 continue
572
573 with open(path, 'r') as f:
574 for line in f.readlines():
575 if not line.startswith('DIST '):
576 paths.append(path)
577 break
578
579 if paths:
580 return HookFailure('Please remove lines that do not start with DIST:\n%s' %
581 ('\n'.join(paths),))
582
583
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700584def _check_change_has_branch_field(project, commit):
585 """Check for a non-empty 'BRANCH=' field in the commit message."""
586 BRANCH_RE = r'\nBRANCH=\S+'
587
588 if not re.search(BRANCH_RE, _get_commit_desc(commit)):
589 msg = ('Changelist description needs BRANCH field (after first line)\n'
590 'E.g. BRANCH=none or BRANCH=link,snow')
591 return HookFailure(msg)
592
593
Jon Salz3ee59de2012-08-18 13:54:22 +0800594def _run_project_hook_script(script, project, commit):
595 """Runs a project hook script.
596
597 The script is run with the following environment variables set:
598 PRESUBMIT_PROJECT: The affected project
599 PRESUBMIT_COMMIT: The affected commit
600 PRESUBMIT_FILES: A newline-separated list of affected files
601
602 The script is considered to fail if the exit code is non-zero. It should
603 write an error message to stdout.
604 """
605 env = dict(os.environ)
606 env['PRESUBMIT_PROJECT'] = project
607 env['PRESUBMIT_COMMIT'] = commit
608
609 # Put affected files in an environment variable
610 files = _get_affected_files(commit)
611 env['PRESUBMIT_FILES'] = '\n'.join(files)
612
613 process = subprocess.Popen(script, env=env, shell=True,
614 stdin=open(os.devnull),
Jon Salz7b618af2012-08-31 06:03:16 +0800615 stdout=subprocess.PIPE,
616 stderr=subprocess.STDOUT)
Jon Salz3ee59de2012-08-18 13:54:22 +0800617 stdout, _ = process.communicate()
618 if process.wait():
Jon Salz7b618af2012-08-31 06:03:16 +0800619 if stdout:
620 stdout = re.sub('(?m)^', ' ', stdout)
621 return HookFailure('Hook script "%s" failed with code %d%s' %
Jon Salz3ee59de2012-08-18 13:54:22 +0800622 (script, process.returncode,
623 ':\n' + stdout if stdout else ''))
624
625
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700626# Base
627
Ryan Cui1562fb82011-05-09 11:01:31 -0700628
Ryan Cui9b651632011-05-11 11:38:58 -0700629# A list of hooks that are not project-specific
630_COMMON_HOOKS = [
631 _check_change_has_bug_field,
David Jamesc3b68b32013-04-03 09:17:03 -0700632 _check_change_has_valid_cq_depend,
Ryan Cui9b651632011-05-11 11:38:58 -0700633 _check_change_has_test_field,
634 _check_change_has_proper_changeid,
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800635 _check_ebuild_licenses,
Ryan Cui9b651632011-05-11 11:38:58 -0700636 _check_no_stray_whitespace,
637 _check_no_long_lines,
638 _check_license,
639 _check_no_tabs,
Doug Anderson42b8a052013-06-26 10:45:36 -0700640 _check_for_uprev,
Ryan Cui9b651632011-05-11 11:38:58 -0700641]
Ryan Cuiec4d6332011-05-02 14:15:25 -0700642
Ryan Cui1562fb82011-05-09 11:01:31 -0700643
Ryan Cui9b651632011-05-11 11:38:58 -0700644# A dictionary of project-specific hooks(callbacks), indexed by project name.
645# dict[project] = [callback1, callback2]
646_PROJECT_SPECIFIC_HOOKS = {
Mike Frysingerdf980702013-08-22 22:25:22 -0400647 "chromeos/autotest-tools": [_run_json_check],
Mike Frysinger52b537e2013-08-22 22:59:53 -0400648 "chromeos/overlays/chromeos-overlay": [_check_manifests],
649 "chromeos/overlays/chromeos-partner-overlay": [_check_manifests],
Randall Spangler7318fd62013-11-21 12:16:58 -0800650 "chromeos/platform/ec-private": [_run_checkpatch_ec,
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700651 _check_change_has_branch_field],
David Hendricks33f77d52013-02-04 17:53:02 -0800652 "chromeos/third_party/coreboot": [_check_change_has_branch_field,
653 _check_google_copyright],
Puneet Kumar57b9c092012-08-14 18:58:29 -0700654 "chromeos/third_party/intel-framework": [_check_change_has_branch_field],
Mike Frysingerdf980702013-08-22 22:25:22 -0400655 "chromeos/vendor/kernel-exynos-staging": [_run_checkpatch,
656 _kernel_configcheck],
657 "chromeos/vendor/u-boot-exynos": [_run_checkpatch_no_tree],
Mike Frysinger52b537e2013-08-22 22:59:53 -0400658 "chromiumos/overlays/board-overlays": [_check_manifests],
659 "chromiumos/overlays/chromiumos-overlay": [_check_manifests],
660 "chromiumos/overlays/portage-stable": [_check_manifests],
Randall Spangler7318fd62013-11-21 12:16:58 -0800661 "chromiumos/platform/ec": [_run_checkpatch_ec,
Mike Frysingerdf980702013-08-22 22:25:22 -0400662 _check_change_has_branch_field],
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700663 "chromiumos/platform/mosys": [_check_change_has_branch_field],
Mike Frysingerdf980702013-08-22 22:25:22 -0400664 "chromiumos/platform/vboot_reference": [_check_change_has_branch_field],
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700665 "chromiumos/third_party/flashrom": [_check_change_has_branch_field],
Mike Frysingerdf980702013-08-22 22:25:22 -0400666 "chromiumos/third_party/kernel": [_run_checkpatch, _kernel_configcheck],
667 "chromiumos/third_party/kernel-next": [_run_checkpatch,
668 _kernel_configcheck],
669 "chromiumos/third_party/u-boot": [_run_checkpatch_no_tree,
670 _check_change_has_branch_field],
Ryan Cui9b651632011-05-11 11:38:58 -0700671}
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700672
Ryan Cui1562fb82011-05-09 11:01:31 -0700673
Ryan Cui9b651632011-05-11 11:38:58 -0700674# A dictionary of flags (keys) that can appear in the config file, and the hook
675# that the flag disables (value)
676_DISABLE_FLAGS = {
677 'stray_whitespace_check': _check_no_stray_whitespace,
678 'long_line_check': _check_no_long_lines,
679 'cros_license_check': _check_license,
680 'tab_check': _check_no_tabs,
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700681 'branch_check': _check_change_has_branch_field,
Ryan Cui9b651632011-05-11 11:38:58 -0700682}
683
684
Jon Salz3ee59de2012-08-18 13:54:22 +0800685def _get_disabled_hooks(config):
Ryan Cui9b651632011-05-11 11:38:58 -0700686 """Returns a set of hooks disabled by the current project's config file.
687
688 Expects to be called within the project root.
Jon Salz3ee59de2012-08-18 13:54:22 +0800689
690 Args:
691 config: A ConfigParser for the project's config file.
Ryan Cui9b651632011-05-11 11:38:58 -0700692 """
693 SECTION = 'Hook Overrides'
Jon Salz3ee59de2012-08-18 13:54:22 +0800694 if not config.has_section(SECTION):
695 return set()
Ryan Cui9b651632011-05-11 11:38:58 -0700696
697 disable_flags = []
Jon Salz3ee59de2012-08-18 13:54:22 +0800698 for flag in config.options(SECTION):
Ryan Cui9b651632011-05-11 11:38:58 -0700699 try:
700 if not config.getboolean(SECTION, flag): disable_flags.append(flag)
701 except ValueError as e:
702 msg = "Error parsing flag \'%s\' in %s file - " % (flag, _CONFIG_FILE)
Mike Frysinger09d6a3d2013-10-08 22:21:03 -0400703 print(msg + str(e))
Ryan Cui9b651632011-05-11 11:38:58 -0700704
705 disabled_keys = set(_DISABLE_FLAGS.iterkeys()).intersection(disable_flags)
706 return set([_DISABLE_FLAGS[key] for key in disabled_keys])
707
708
Jon Salz3ee59de2012-08-18 13:54:22 +0800709def _get_project_hook_scripts(config):
710 """Returns a list of project-specific hook scripts.
711
712 Args:
713 config: A ConfigParser for the project's config file.
714 """
715 SECTION = 'Hook Scripts'
716 if not config.has_section(SECTION):
717 return []
718
719 hook_names_values = config.items(SECTION)
720 hook_names_values.sort(key=lambda x: x[0])
721 return [x[1] for x in hook_names_values]
722
723
Ryan Cui9b651632011-05-11 11:38:58 -0700724def _get_project_hooks(project):
725 """Returns a list of hooks that need to be run for a project.
726
727 Expects to be called from within the project root.
728 """
Jon Salz3ee59de2012-08-18 13:54:22 +0800729 config = ConfigParser.RawConfigParser()
730 try:
731 config.read(_CONFIG_FILE)
732 except ConfigParser.Error:
733 # Just use an empty config file
734 config = ConfigParser.RawConfigParser()
735
736 disabled_hooks = _get_disabled_hooks(config)
Ryan Cui9b651632011-05-11 11:38:58 -0700737 hooks = [hook for hook in _COMMON_HOOKS if hook not in disabled_hooks]
738
739 if project in _PROJECT_SPECIFIC_HOOKS:
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700740 hooks.extend(hook for hook in _PROJECT_SPECIFIC_HOOKS[project]
741 if hook not in disabled_hooks)
Ryan Cui9b651632011-05-11 11:38:58 -0700742
Jon Salz3ee59de2012-08-18 13:54:22 +0800743 for script in _get_project_hook_scripts(config):
744 hooks.append(functools.partial(_run_project_hook_script, script))
745
Ryan Cui9b651632011-05-11 11:38:58 -0700746 return hooks
747
748
Doug Anderson14749562013-06-26 13:38:29 -0700749def _run_project_hooks(project, proj_dir=None, commit_list=None):
Ryan Cui1562fb82011-05-09 11:01:31 -0700750 """For each project run its project specific hook from the hooks dictionary.
751
752 Args:
Doug Anderson44a644f2011-11-02 10:37:37 -0700753 project: The name of project to run hooks for.
754 proj_dir: If non-None, this is the directory the project is in. If None,
755 we'll ask repo.
Doug Anderson14749562013-06-26 13:38:29 -0700756 commit_list: A list of commits to run hooks against. If None or empty list
757 then we'll automatically get the list of commits that would be uploaded.
Ryan Cui1562fb82011-05-09 11:01:31 -0700758
759 Returns:
760 Boolean value of whether any errors were ecountered while running the hooks.
761 """
Doug Anderson44a644f2011-11-02 10:37:37 -0700762 if proj_dir is None:
David James2edd9002013-10-11 14:09:19 -0700763 proj_dirs = _run_command(['repo', 'forall', project, '-c', 'pwd']).split()
764 if len(proj_dirs) == 0:
765 print('%s cannot be found.' % project, file=sys.stderr)
766 print('Please specify a valid project.', file=sys.stderr)
767 return True
768 if len(proj_dirs) > 1:
769 print('%s is associated with multiple directories.' % project,
770 file=sys.stderr)
771 print('Please specify a directory to help disambiguate.', file=sys.stderr)
772 return True
773 proj_dir = proj_dirs[0]
Doug Anderson44a644f2011-11-02 10:37:37 -0700774
Ryan Cuiec4d6332011-05-02 14:15:25 -0700775 pwd = os.getcwd()
776 # hooks assume they are run from the root of the project
777 os.chdir(proj_dir)
778
Doug Anderson14749562013-06-26 13:38:29 -0700779 if not commit_list:
780 try:
781 commit_list = _get_commits()
782 except VerifyException as e:
783 PrintErrorForProject(project, HookFailure(str(e)))
784 os.chdir(pwd)
785 return True
Ryan Cuifa55df52011-05-06 11:16:55 -0700786
Ryan Cui9b651632011-05-11 11:38:58 -0700787 hooks = _get_project_hooks(project)
Ryan Cui1562fb82011-05-09 11:01:31 -0700788 error_found = False
Ryan Cuifa55df52011-05-06 11:16:55 -0700789 for commit in commit_list:
Ryan Cui1562fb82011-05-09 11:01:31 -0700790 error_list = []
Ryan Cui9b651632011-05-11 11:38:58 -0700791 for hook in hooks:
Ryan Cui1562fb82011-05-09 11:01:31 -0700792 hook_error = hook(project, commit)
793 if hook_error:
794 error_list.append(hook_error)
795 error_found = True
796 if error_list:
797 PrintErrorsForCommit(project, commit, _get_commit_desc(commit),
798 error_list)
Don Garrettdba548a2011-05-05 15:17:14 -0700799
Ryan Cuiec4d6332011-05-02 14:15:25 -0700800 os.chdir(pwd)
Ryan Cui1562fb82011-05-09 11:01:31 -0700801 return error_found
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700802
803# Main
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -0700804
Ryan Cui1562fb82011-05-09 11:01:31 -0700805
David James2edd9002013-10-11 14:09:19 -0700806def main(project_list, worktree_list=None, **kwargs):
Doug Anderson06456632012-01-05 11:02:14 -0800807 """Main function invoked directly by repo.
808
809 This function will exit directly upon error so that repo doesn't print some
810 obscure error message.
811
812 Args:
813 project_list: List of projects to run on.
David James2edd9002013-10-11 14:09:19 -0700814 worktree_list: A list of directories. It should be the same length as
815 project_list, so that each entry in project_list matches with a directory
816 in worktree_list. If None, we will attempt to calculate the directories
817 automatically.
Doug Anderson06456632012-01-05 11:02:14 -0800818 kwargs: Leave this here for forward-compatibility.
819 """
Ryan Cui1562fb82011-05-09 11:01:31 -0700820 found_error = False
David James2edd9002013-10-11 14:09:19 -0700821 if not worktree_list:
822 worktree_list = [None] * len(project_list)
823 for project, worktree in zip(project_list, worktree_list):
824 if _run_project_hooks(project, proj_dir=worktree):
Ryan Cui1562fb82011-05-09 11:01:31 -0700825 found_error = True
826
827 if (found_error):
828 msg = ('Preupload failed due to errors in project(s). HINTS:\n'
Ryan Cui9b651632011-05-11 11:38:58 -0700829 '- To disable some source style checks, and for other hints, see '
830 '<checkout_dir>/src/repohooks/README\n'
831 '- To upload only current project, run \'repo upload .\'')
Mike Frysinger09d6a3d2013-10-08 22:21:03 -0400832 print(msg, file=sys.stderr)
Don Garrettdba548a2011-05-05 15:17:14 -0700833 sys.exit(1)
Anush Elangovan63afad72011-03-23 00:41:27 -0700834
Ryan Cui1562fb82011-05-09 11:01:31 -0700835
Doug Anderson44a644f2011-11-02 10:37:37 -0700836def _identify_project(path):
837 """Identify the repo project associated with the given path.
838
839 Returns:
840 A string indicating what project is associated with the path passed in or
841 a blank string upon failure.
842 """
843 return _run_command(['repo', 'forall', '.', '-c', 'echo ${REPO_PROJECT}'],
844 stderr=subprocess.PIPE, cwd=path).strip()
845
846
847def direct_main(args, verbose=False):
848 """Run hooks directly (outside of the context of repo).
849
850 # Setup for doctests below.
851 # ...note that some tests assume that running pre-upload on this CWD is fine.
852 # TODO: Use mock and actually mock out _run_project_hooks() for tests.
853 >>> mydir = os.path.dirname(os.path.abspath(__file__))
854 >>> olddir = os.getcwd()
855
856 # OK to run w/ no arugments; will run with CWD.
857 >>> os.chdir(mydir)
858 >>> direct_main(['prog_name'], verbose=True)
859 Running hooks on chromiumos/repohooks
860 0
861 >>> os.chdir(olddir)
862
863 # Run specifying a dir
864 >>> direct_main(['prog_name', '--dir=%s' % mydir], verbose=True)
865 Running hooks on chromiumos/repohooks
866 0
867
868 # Not a problem to use a bogus project; we'll just get default settings.
869 >>> direct_main(['prog_name', '--dir=%s' % mydir, '--project=X'],verbose=True)
870 Running hooks on X
871 0
872
873 # Run with project but no dir
874 >>> os.chdir(mydir)
875 >>> direct_main(['prog_name', '--project=X'], verbose=True)
876 Running hooks on X
877 0
878 >>> os.chdir(olddir)
879
880 # Try with a non-git CWD
881 >>> os.chdir('/tmp')
882 >>> direct_main(['prog_name'])
883 Traceback (most recent call last):
884 ...
885 BadInvocation: The current directory is not part of a git project.
886
887 # Check various bad arguments...
888 >>> direct_main(['prog_name', 'bogus'])
889 Traceback (most recent call last):
890 ...
891 BadInvocation: Unexpected arguments: bogus
892 >>> direct_main(['prog_name', '--project=bogus', '--dir=bogusdir'])
893 Traceback (most recent call last):
894 ...
895 BadInvocation: Invalid dir: bogusdir
896 >>> direct_main(['prog_name', '--project=bogus', '--dir=/tmp'])
897 Traceback (most recent call last):
898 ...
899 BadInvocation: Not a git directory: /tmp
900
901 Args:
902 args: The value of sys.argv
903
904 Returns:
905 0 if no pre-upload failures, 1 if failures.
906
907 Raises:
908 BadInvocation: On some types of invocation errors.
909 """
910 desc = 'Run Chromium OS pre-upload hooks on changes compared to upstream.'
911 parser = optparse.OptionParser(description=desc)
912
913 parser.add_option('--dir', default=None,
914 help='The directory that the project lives in. If not '
915 'specified, use the git project root based on the cwd.')
916 parser.add_option('--project', default=None,
917 help='The project repo path; this can affect how the hooks '
918 'get run, since some hooks are project-specific. For '
919 'chromite this is chromiumos/chromite. If not specified, '
920 'the repo tool will be used to figure this out based on '
921 'the dir.')
Doug Anderson14749562013-06-26 13:38:29 -0700922 parser.add_option('--rerun-since', default=None,
923 help='Rerun hooks on old commits since the given date. '
924 'The date should match git log\'s concept of a date. '
925 'e.g. 2012-06-20')
926
927 parser.usage = "pre-upload.py [options] [commits]"
Doug Anderson44a644f2011-11-02 10:37:37 -0700928
929 opts, args = parser.parse_args(args[1:])
930
Doug Anderson14749562013-06-26 13:38:29 -0700931 if opts.rerun_since:
932 if args:
933 raise BadInvocation('Can\'t pass commits and use rerun-since: %s' %
934 ' '.join(args))
935
936 cmd = ['git', 'log', '--since="%s"' % opts.rerun_since, '--pretty=%H']
937 all_commits = _run_command(cmd).splitlines()
938 bot_commits = _run_command(cmd + ['--author=chrome-bot']).splitlines()
939
940 # Eliminate chrome-bot commits but keep ordering the same...
941 bot_commits = set(bot_commits)
942 args = [c for c in all_commits if c not in bot_commits]
943
Doug Anderson44a644f2011-11-02 10:37:37 -0700944
945 # Check/normlaize git dir; if unspecified, we'll use the root of the git
946 # project from CWD
947 if opts.dir is None:
948 git_dir = _run_command(['git', 'rev-parse', '--git-dir'],
949 stderr=subprocess.PIPE).strip()
950 if not git_dir:
951 raise BadInvocation('The current directory is not part of a git project.')
952 opts.dir = os.path.dirname(os.path.abspath(git_dir))
953 elif not os.path.isdir(opts.dir):
954 raise BadInvocation('Invalid dir: %s' % opts.dir)
955 elif not os.path.isdir(os.path.join(opts.dir, '.git')):
956 raise BadInvocation('Not a git directory: %s' % opts.dir)
957
958 # Identify the project if it wasn't specified; this _requires_ the repo
959 # tool to be installed and for the project to be part of a repo checkout.
960 if not opts.project:
961 opts.project = _identify_project(opts.dir)
962 if not opts.project:
963 raise BadInvocation("Repo couldn't identify the project of %s" % opts.dir)
964
965 if verbose:
Mike Frysinger09d6a3d2013-10-08 22:21:03 -0400966 print("Running hooks on %s" % (opts.project))
Doug Anderson44a644f2011-11-02 10:37:37 -0700967
Doug Anderson14749562013-06-26 13:38:29 -0700968 found_error = _run_project_hooks(opts.project, proj_dir=opts.dir,
969 commit_list=args)
Doug Anderson44a644f2011-11-02 10:37:37 -0700970 if found_error:
971 return 1
972 return 0
973
974
975def _test():
976 """Run any built-in tests."""
977 import doctest
978 doctest.testmod()
979
980
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -0700981if __name__ == '__main__':
Doug Anderson44a644f2011-11-02 10:37:37 -0700982 if sys.argv[1:2] == ["--test"]:
983 _test()
984 exit_code = 0
985 else:
986 prog_name = os.path.basename(sys.argv[0])
987 try:
988 exit_code = direct_main(sys.argv)
989 except BadInvocation, e:
Mike Frysinger09d6a3d2013-10-08 22:21:03 -0400990 print("%s: %s" % (prog_name, str(e)), file=sys.stderr)
Doug Anderson44a644f2011-11-02 10:37:37 -0700991 exit_code = 1
992 sys.exit(exit_code)