blob: d4176a12a3ddb99cf28583dd73d99af85a122d75 [file] [log] [blame]
Prathmesh Prabhuc5254652016-12-22 12:58:05 -08001#!/usr/bin/env python2
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 Frysingerae409522014-02-01 03:16:11 -05006"""Presubmit checks to run when doing `repo upload`.
7
8You can add new checks by adding a functions to the HOOKS constants.
9"""
10
Mike Frysinger09d6a3d2013-10-08 22:21:03 -040011from __future__ import print_function
12
Filipe Brandenburger4b542b12015-10-09 12:46:31 -070013import argparse
Alex Deymo643ac4c2015-09-03 10:40:50 -070014import collections
Ryan Cui9b651632011-05-11 11:38:58 -070015import ConfigParser
Daniel Erate3ea3fc2015-02-13 15:27:52 -070016import fnmatch
Jon Salz3ee59de2012-08-18 13:54:22 +080017import functools
Dale Curtis2975c432011-05-03 17:25:20 -070018import json
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070019import os
Ryan Cuiec4d6332011-05-02 14:15:25 -070020import re
Mandeep Singh Bainesa7ffa4b2011-05-03 11:37:02 -070021import sys
Peter Ammon811f6702014-06-12 15:45:38 -070022import stat
Aviv Keshet5ac59522017-01-31 14:28:27 -080023import StringIO
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070024
Ryan Cui1562fb82011-05-09 11:01:31 -070025from errors import (VerifyException, HookFailure, PrintErrorForProject,
26 PrintErrorsForCommit)
Ryan Cuiec4d6332011-05-02 14:15:25 -070027
David Jamesc3b68b32013-04-03 09:17:03 -070028# If repo imports us, the __name__ will be __builtin__, and the wrapper will
29# be in $CHROMEOS_CHECKOUT/.repo/repo/main.py, so we need to go two directories
30# up. The same logic also happens to work if we're executed directly.
31if __name__ in ('__builtin__', '__main__'):
32 sys.path.insert(0, os.path.join(os.path.dirname(sys.argv[0]), '..', '..'))
33
Mike Frysinger66142932014-12-18 14:55:57 -050034from chromite.lib import commandline
Aviv Keshet5ac59522017-01-31 14:28:27 -080035from chromite.lib import constants
Rahul Chaudhry0e515342015-08-07 12:00:43 -070036from chromite.lib import cros_build_lib
Mike Frysingerd3bd32c2014-11-24 23:34:29 -050037from chromite.lib import git
Daniel Erata350fd32014-09-29 14:02:34 -070038from chromite.lib import osutils
David Jamesc3b68b32013-04-03 09:17:03 -070039from chromite.lib import patch
Mike Frysinger2ec70ed2014-08-17 19:28:34 -040040from chromite.licensing import licenses_lib
David Jamesc3b68b32013-04-03 09:17:03 -070041
Vadim Bendebury2b62d742014-06-22 13:14:51 -070042PRE_SUBMIT = 'pre-submit'
Ryan Cuiec4d6332011-05-02 14:15:25 -070043
44COMMON_INCLUDED_PATHS = [
Mike Frysingerae409522014-02-01 03:16:11 -050045 # C++ and friends
46 r".*\.c$", r".*\.cc$", r".*\.cpp$", r".*\.h$", r".*\.m$", r".*\.mm$",
47 r".*\.inl$", r".*\.asm$", r".*\.hxx$", r".*\.hpp$", r".*\.s$", r".*\.S$",
48 # Scripts
49 r".*\.js$", r".*\.py$", r".*\.sh$", r".*\.rb$", r".*\.pl$", r".*\.pm$",
50 # No extension at all, note that ALL CAPS files are black listed in
51 # COMMON_EXCLUDED_LIST below.
52 r"(^|.*[\\\/])[^.]+$",
53 # Other
54 r".*\.java$", r".*\.mk$", r".*\.am$",
Brian Norrisfdbac8e2016-06-16 11:09:05 -070055 r".*\.policy$", r".*\.conf$",
Ryan Cuiec4d6332011-05-02 14:15:25 -070056]
57
Ryan Cui1562fb82011-05-09 11:01:31 -070058
Ryan Cuiec4d6332011-05-02 14:15:25 -070059COMMON_EXCLUDED_PATHS = [
Daniel Erate3ea3fc2015-02-13 15:27:52 -070060 # Avoid doing source file checks for kernel.
Mike Frysingerae409522014-02-01 03:16:11 -050061 r"/src/third_party/kernel/",
62 r"/src/third_party/kernel-next/",
63 r"/src/third_party/ktop/",
64 r"/src/third_party/punybench/",
65 r".*\bexperimental[\\\/].*",
66 r".*\b[A-Z0-9_]{2,}$",
67 r".*[\\\/]debian[\\\/]rules$",
Daniel Erate3ea3fc2015-02-13 15:27:52 -070068
69 # For ebuild trees, ignore any caches and manifest data.
Mike Frysingerae409522014-02-01 03:16:11 -050070 r".*/Manifest$",
71 r".*/metadata/[^/]*cache[^/]*/[^/]+/[^/]+$",
Doug Anderson5bfb6792011-10-25 16:45:41 -070072
Daniel Erate3ea3fc2015-02-13 15:27:52 -070073 # Ignore profiles data (like overlay-tegra2/profiles).
Mike Frysinger94a670c2014-09-19 12:46:26 -040074 r"(^|.*/)overlay-.*/profiles/.*",
Mike Frysinger98638102014-08-28 00:15:08 -040075 r"^profiles/.*$",
76
Daniel Erate3ea3fc2015-02-13 15:27:52 -070077 # Ignore minified js and jquery.
Mike Frysingerae409522014-02-01 03:16:11 -050078 r".*\.min\.js",
79 r".*jquery.*\.js",
Mike Frysinger33a458d2014-03-03 17:00:51 -050080
81 # Ignore license files as the content is often taken verbatim.
Daniel Erate3ea3fc2015-02-13 15:27:52 -070082 r".*/licenses/.*",
Ryan Cuiec4d6332011-05-02 14:15:25 -070083]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070084
Ryan Cui1562fb82011-05-09 11:01:31 -070085
Ryan Cui9b651632011-05-11 11:38:58 -070086_CONFIG_FILE = 'PRESUBMIT.cfg'
87
88
Daniel Erate3ea3fc2015-02-13 15:27:52 -070089# File containing wildcards, one per line, matching files that should be
90# excluded from presubmit checks. Lines beginning with '#' are ignored.
91_IGNORE_FILE = '.presubmitignore'
92
93
Doug Anderson44a644f2011-11-02 10:37:37 -070094# Exceptions
95
96
97class BadInvocation(Exception):
98 """An Exception indicating a bad invocation of the program."""
99 pass
100
101
Ryan Cui1562fb82011-05-09 11:01:31 -0700102# General Helpers
103
Sean Paulba01d402011-05-05 11:36:23 -0400104
Alex Deymo643ac4c2015-09-03 10:40:50 -0700105Project = collections.namedtuple('Project', ['name', 'dir', 'remote'])
106
107
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700108# pylint: disable=redefined-builtin
109def _run_command(cmd, cwd=None, input=None,
110 redirect_stderr=False, combine_stdout_stderr=False):
Doug Anderson44a644f2011-11-02 10:37:37 -0700111 """Executes the passed in command and returns raw stdout output.
112
113 Args:
114 cmd: The command to run; should be a list of strings.
115 cwd: The directory to switch to for running the command.
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700116 input: The data to pipe into this command through stdin. If a file object
117 or file descriptor, stdin will be connected directly to that.
118 redirect_stderr: Redirect stderr away from console.
119 combine_stdout_stderr: Combines stdout and stderr streams into stdout.
Doug Anderson44a644f2011-11-02 10:37:37 -0700120
121 Returns:
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700122 The stdout from the process (discards stderr and returncode).
Doug Anderson44a644f2011-11-02 10:37:37 -0700123 """
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700124 return cros_build_lib.RunCommand(cmd=cmd,
125 cwd=cwd,
126 print_cmd=False,
127 input=input,
128 stdout_to_pipe=True,
129 redirect_stderr=redirect_stderr,
130 combine_stdout_stderr=combine_stdout_stderr,
131 error_code_ok=True).output
132# pylint: enable=redefined-builtin
Ryan Cui72834d12011-05-05 14:51:33 -0700133
Ryan Cui1562fb82011-05-09 11:01:31 -0700134
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700135def _get_hooks_dir():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700136 """Returns the absolute path to the repohooks directory."""
Doug Anderson44a644f2011-11-02 10:37:37 -0700137 if __name__ == '__main__':
138 # Works when file is run on its own (__file__ is defined)...
139 return os.path.abspath(os.path.dirname(__file__))
140 else:
141 # We need to do this when we're run through repo. Since repo executes
142 # us with execfile(), we don't get __file__ defined.
143 cmd = ['repo', 'forall', 'chromiumos/repohooks', '-c', 'pwd']
144 return _run_command(cmd).strip()
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700145
Ryan Cui1562fb82011-05-09 11:01:31 -0700146
Ryan Cuiec4d6332011-05-02 14:15:25 -0700147def _match_regex_list(subject, expressions):
148 """Try to match a list of regular expressions to a string.
149
150 Args:
151 subject: The string to match regexes on
152 expressions: A list of regular expressions to check for matches with.
153
154 Returns:
155 Whether the passed in subject matches any of the passed in regexes.
156 """
157 for expr in expressions:
Mike Frysingerae409522014-02-01 03:16:11 -0500158 if re.search(expr, subject):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700159 return True
160 return False
161
Ryan Cui1562fb82011-05-09 11:01:31 -0700162
Mike Frysingerae409522014-02-01 03:16:11 -0500163def _filter_files(files, include_list, exclude_list=()):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700164 """Filter out files based on the conditions passed in.
165
166 Args:
167 files: list of filepaths to filter
168 include_list: list of regex that when matched with a file path will cause it
169 to be added to the output list unless the file is also matched with a
170 regex in the exclude_list.
171 exclude_list: list of regex that when matched with a file will prevent it
172 from being added to the output list, even if it is also matched with a
173 regex in the include_list.
174
175 Returns:
176 A list of filepaths that contain files matched in the include_list and not
177 in the exclude_list.
178 """
179 filtered = []
180 for f in files:
181 if (_match_regex_list(f, include_list) and
182 not _match_regex_list(f, exclude_list)):
183 filtered.append(f)
184 return filtered
185
Ryan Cuiec4d6332011-05-02 14:15:25 -0700186
187# Git Helpers
Ryan Cui1562fb82011-05-09 11:01:31 -0700188
189
Ryan Cui4725d952011-05-05 15:41:19 -0700190def _get_upstream_branch():
191 """Returns the upstream tracking branch of the current branch.
192
193 Raises:
194 Error if there is no tracking branch
195 """
196 current_branch = _run_command(['git', 'symbolic-ref', 'HEAD']).strip()
197 current_branch = current_branch.replace('refs/heads/', '')
198 if not current_branch:
Ryan Cui1562fb82011-05-09 11:01:31 -0700199 raise VerifyException('Need to be on a tracking branch')
Ryan Cui4725d952011-05-05 15:41:19 -0700200
201 cfg_option = 'branch.' + current_branch + '.%s'
202 full_upstream = _run_command(['git', 'config', cfg_option % 'merge']).strip()
203 remote = _run_command(['git', 'config', cfg_option % 'remote']).strip()
204 if not remote or not full_upstream:
Ryan Cui1562fb82011-05-09 11:01:31 -0700205 raise VerifyException('Need to be on a tracking branch')
Ryan Cui4725d952011-05-05 15:41:19 -0700206
207 return full_upstream.replace('heads', 'remotes/' + remote)
208
Ryan Cui1562fb82011-05-09 11:01:31 -0700209
Che-Liang Chiou5ce2d7b2013-03-22 18:47:55 -0700210def _get_patch(commit):
211 """Returns the patch for this commit."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700212 if commit == PRE_SUBMIT:
213 return _run_command(['git', 'diff', '--cached', 'HEAD'])
214 else:
215 return _run_command(['git', 'format-patch', '--stdout', '-1', commit])
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700216
Ryan Cui1562fb82011-05-09 11:01:31 -0700217
Jon Salz98255932012-08-18 14:48:02 +0800218def _try_utf8_decode(data):
219 """Attempts to decode a string as UTF-8.
220
221 Returns:
222 The decoded Unicode object, or the original string if parsing fails.
223 """
224 try:
225 return unicode(data, 'utf-8', 'strict')
226 except UnicodeDecodeError:
227 return data
228
229
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500230def _get_file_content(path, commit):
231 """Returns the content of a file at a specific commit.
232
233 We can't rely on the file as it exists in the filesystem as people might be
234 uploading a series of changes which modifies the file multiple times.
235
236 Note: The "content" of a symlink is just the target. So if you're expecting
237 a full file, you should check that first. One way to detect is that the
238 content will not have any newlines.
239 """
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700240 if commit == PRE_SUBMIT:
241 return _run_command(['git', 'diff', 'HEAD', path])
242 else:
243 return _run_command(['git', 'show', '%s:%s' % (commit, path)])
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500244
245
Mike Frysingerae409522014-02-01 03:16:11 -0500246def _get_file_diff(path, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700247 """Returns a list of (linenum, lines) tuples that the commit touched."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700248 if commit == PRE_SUBMIT:
Prathmesh Prabhua9de1722016-12-22 14:56:40 -0800249 command = ['git', 'diff', '-p', '--pretty=format:', '--no-ext-diff', 'HEAD',
250 path]
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700251 else:
Prathmesh Prabhua9de1722016-12-22 14:56:40 -0800252 command = ['git', 'show', '-p', '--pretty=format:', '--no-ext-diff', commit,
253 path]
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700254 output = _run_command(command)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700255
256 new_lines = []
257 line_num = 0
258 for line in output.splitlines():
259 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
260 if m:
261 line_num = int(m.groups(1)[0])
262 continue
263 if line.startswith('+') and not line.startswith('++'):
Jon Salz98255932012-08-18 14:48:02 +0800264 new_lines.append((line_num, _try_utf8_decode(line[1:])))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700265 if not line.startswith('-'):
266 line_num += 1
267 return new_lines
268
Ryan Cui1562fb82011-05-09 11:01:31 -0700269
Daniel Erate3ea3fc2015-02-13 15:27:52 -0700270def _get_ignore_wildcards(directory, cache):
271 """Get wildcards listed in a directory's _IGNORE_FILE.
272
273 Args:
274 directory: A string containing a directory path.
275 cache: A dictionary (opaque to caller) caching previously-read wildcards.
276
277 Returns:
278 A list of wildcards from _IGNORE_FILE or an empty list if _IGNORE_FILE
279 wasn't present.
280 """
281 # In the cache, keys are directories and values are lists of wildcards from
282 # _IGNORE_FILE within those directories (and empty if no file was present).
283 if directory not in cache:
284 wildcards = []
285 dotfile_path = os.path.join(directory, _IGNORE_FILE)
286 if os.path.exists(dotfile_path):
287 # TODO(derat): Consider using _get_file_content() to get the file as of
288 # this commit instead of the on-disk version. This may have a noticeable
289 # performance impact, as each call to _get_file_content() runs git.
290 with open(dotfile_path, 'r') as dotfile:
291 for line in dotfile.readlines():
292 line = line.strip()
293 if line.startswith('#'):
294 continue
295 if line.endswith('/'):
296 line += '*'
297 wildcards.append(line)
298 cache[directory] = wildcards
299
300 return cache[directory]
301
302
303def _path_is_ignored(path, cache):
304 """Check whether a path is ignored by _IGNORE_FILE.
305
306 Args:
307 path: A string containing a path.
308 cache: A dictionary (opaque to caller) caching previously-read wildcards.
309
310 Returns:
311 True if a file named _IGNORE_FILE in one of the passed-in path's parent
312 directories contains a wildcard matching the path.
313 """
314 # Skip ignore files.
315 if os.path.basename(path) == _IGNORE_FILE:
316 return True
317
318 path = os.path.abspath(path)
319 base = os.getcwd()
320
321 prefix = os.path.dirname(path)
322 while prefix.startswith(base):
323 rel_path = path[len(prefix) + 1:]
324 for wildcard in _get_ignore_wildcards(prefix, cache):
325 if fnmatch.fnmatch(rel_path, wildcard):
326 return True
327 prefix = os.path.dirname(prefix)
328
329 return False
330
331
Mike Frysinger292b45d2014-11-25 01:17:10 -0500332def _get_affected_files(commit, include_deletes=False, relative=False,
333 include_symlinks=False, include_adds=True,
Daniel Erate3ea3fc2015-02-13 15:27:52 -0700334 full_details=False, use_ignore_files=True):
Peter Ammon811f6702014-06-12 15:45:38 -0700335 """Returns list of file paths that were modified/added, excluding symlinks.
336
337 Args:
338 commit: The commit
339 include_deletes: If true, we'll include deleted files in the result
340 relative: Whether to return relative or full paths to files
Mike Frysinger292b45d2014-11-25 01:17:10 -0500341 include_symlinks: If true, we'll include symlinks in the result
342 include_adds: If true, we'll include new files in the result
343 full_details: If False, return filenames, else return structured results.
Daniel Erate3ea3fc2015-02-13 15:27:52 -0700344 use_ignore_files: Whether we ignore files matched by _IGNORE_FILE files.
Peter Ammon811f6702014-06-12 15:45:38 -0700345
346 Returns:
347 A list of modified/added (and perhaps deleted) files
348 """
Mike Frysinger292b45d2014-11-25 01:17:10 -0500349 if not relative and full_details:
350 raise ValueError('full_details only supports relative paths currently')
351
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700352 if commit == PRE_SUBMIT:
353 return _run_command(['git', 'diff-index', '--cached',
354 '--name-only', 'HEAD']).split()
Mike Frysingerd3bd32c2014-11-24 23:34:29 -0500355
356 path = os.getcwd()
357 files = git.RawDiff(path, '%s^!' % commit)
358
359 # Filter out symlinks.
Mike Frysinger292b45d2014-11-25 01:17:10 -0500360 if not include_symlinks:
361 files = [x for x in files if not stat.S_ISLNK(int(x.dst_mode, 8))]
Mike Frysingerd3bd32c2014-11-24 23:34:29 -0500362
363 if not include_deletes:
364 files = [x for x in files if x.status != 'D']
365
Mike Frysinger292b45d2014-11-25 01:17:10 -0500366 if not include_adds:
367 files = [x for x in files if x.status != 'A']
368
Daniel Erate3ea3fc2015-02-13 15:27:52 -0700369 if use_ignore_files:
370 cache = {}
371 is_ignored = lambda x: _path_is_ignored(x.dst_file or x.src_file, cache)
372 files = [x for x in files if not is_ignored(x)]
373
Mike Frysinger292b45d2014-11-25 01:17:10 -0500374 if full_details:
375 # Caller wants the raw objects to parse status/etc... themselves.
Mike Frysingerd3bd32c2014-11-24 23:34:29 -0500376 return files
377 else:
Mike Frysinger292b45d2014-11-25 01:17:10 -0500378 # Caller only cares about filenames.
379 files = [x.dst_file if x.dst_file else x.src_file for x in files]
380 if relative:
381 return files
382 else:
383 return [os.path.join(path, x) for x in files]
Peter Ammon811f6702014-06-12 15:45:38 -0700384
385
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700386def _get_commits():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700387 """Returns a list of commits for this review."""
Ryan Cui4725d952011-05-05 15:41:19 -0700388 cmd = ['git', 'log', '%s..' % _get_upstream_branch(), '--format=%H']
Ryan Cui72834d12011-05-05 14:51:33 -0700389 return _run_command(cmd).split()
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700390
Ryan Cui1562fb82011-05-09 11:01:31 -0700391
Ryan Cuiec4d6332011-05-02 14:15:25 -0700392def _get_commit_desc(commit):
393 """Returns the full commit message of a commit."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700394 if commit == PRE_SUBMIT:
395 return ''
Sean Paul23a2c582011-05-06 13:10:44 -0400396 return _run_command(['git', 'log', '--format=%s%n%n%b', commit + '^!'])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700397
398
Prathmesh Prabhuc5254652016-12-22 12:58:05 -0800399def _check_lines_in_diff(commit, files, check_callable, error_description):
400 """Checks given file for errors via the given check.
401
402 This is a convenience function for common per-line checks. It goes through all
403 files and returns a HookFailure with the error description listing all the
404 failures.
405
406 Args:
407 commit: The commit we're working on.
408 files: The files to check.
409 check_callable: A callable that takes a line and returns True if this line
410 _fails_ the check.
411 error_description: A string describing the error.
412 """
413 errors = []
414 for afile in files:
415 for line_num, line in _get_file_diff(afile, commit):
416 if check_callable(line):
417 errors.append('%s, line %s' % (afile, line_num))
418 if errors:
419 return HookFailure(error_description, errors)
420
421
Ryan Cuiec4d6332011-05-02 14:15:25 -0700422# Common Hooks
423
Ryan Cui1562fb82011-05-09 11:01:31 -0700424
Mike Frysingerae409522014-02-01 03:16:11 -0500425def _check_no_long_lines(_project, commit):
Mike Frysinger55f85b52014-12-18 14:45:21 -0500426 """Checks there are no lines longer than MAX_LEN in any of the text files."""
427
Ryan Cuiec4d6332011-05-02 14:15:25 -0700428 MAX_LEN = 80
Jon Salz98255932012-08-18 14:48:02 +0800429 SKIP_REGEXP = re.compile('|'.join([
430 r'https?://',
431 r'^#\s*(define|include|import|pragma|if|endif)\b']))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700432
433 errors = []
434 files = _filter_files(_get_affected_files(commit),
435 COMMON_INCLUDED_PATHS,
436 COMMON_EXCLUDED_PATHS)
437
438 for afile in files:
439 for line_num, line in _get_file_diff(afile, commit):
440 # Allow certain lines to exceed the maxlen rule.
Mike Frysingerae409522014-02-01 03:16:11 -0500441 if len(line) <= MAX_LEN or SKIP_REGEXP.search(line):
Jon Salz98255932012-08-18 14:48:02 +0800442 continue
443
444 errors.append('%s, line %s, %s chars' % (afile, line_num, len(line)))
445 if len(errors) == 5: # Just show the first 5 errors.
446 break
Ryan Cuiec4d6332011-05-02 14:15:25 -0700447
448 if errors:
449 msg = 'Found lines longer than %s characters (first 5 shown):' % MAX_LEN
Ryan Cui1562fb82011-05-09 11:01:31 -0700450 return HookFailure(msg, errors)
451
Ryan Cuiec4d6332011-05-02 14:15:25 -0700452
Mike Frysingerae409522014-02-01 03:16:11 -0500453def _check_no_stray_whitespace(_project, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700454 """Checks that there is no stray whitespace at source lines end."""
Ryan Cuiec4d6332011-05-02 14:15:25 -0700455 files = _filter_files(_get_affected_files(commit),
Mike Frysingerae409522014-02-01 03:16:11 -0500456 COMMON_INCLUDED_PATHS,
457 COMMON_EXCLUDED_PATHS)
Prathmesh Prabhuc5254652016-12-22 12:58:05 -0800458 return _check_lines_in_diff(commit, files,
459 lambda line: line.rstrip() != line,
460 'Found line ending with white space in:')
Ryan Cui1562fb82011-05-09 11:01:31 -0700461
Ryan Cuiec4d6332011-05-02 14:15:25 -0700462
Mike Frysingerae409522014-02-01 03:16:11 -0500463def _check_no_tabs(_project, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700464 """Checks there are no unexpanded tabs."""
465 TAB_OK_PATHS = [
Ryan Cui31e0c172011-05-04 21:00:45 -0700466 r"/src/third_party/u-boot/",
Ryan Cuiec4d6332011-05-02 14:15:25 -0700467 r".*\.ebuild$",
468 r".*\.eclass$",
Elly Jones5ab34192011-11-15 14:57:06 -0500469 r".*/[M|m]akefile$",
470 r".*\.mk$"
Ryan Cuiec4d6332011-05-02 14:15:25 -0700471 ]
472
Ryan Cuiec4d6332011-05-02 14:15:25 -0700473 files = _filter_files(_get_affected_files(commit),
474 COMMON_INCLUDED_PATHS,
475 COMMON_EXCLUDED_PATHS + TAB_OK_PATHS)
Prathmesh Prabhuc5254652016-12-22 12:58:05 -0800476 return _check_lines_in_diff(commit, files,
477 lambda line: '\t' in line,
478 'Found a tab character in:')
Ryan Cuiec4d6332011-05-02 14:15:25 -0700479
Prathmesh Prabhuc5254652016-12-22 12:58:05 -0800480
481def _check_tabbed_indents(_project, commit):
482 """Checks that indents use tabs only."""
483 TABS_REQUIRED_PATHS = [
484 r".*\.ebuild$",
485 r".*\.eclass$",
486 ]
487 LEADING_SPACE_RE = re.compile('[\t]* ')
488
489 files = _filter_files(_get_affected_files(commit),
490 TABS_REQUIRED_PATHS,
491 COMMON_EXCLUDED_PATHS)
492 return _check_lines_in_diff(
493 commit, files,
494 lambda line: LEADING_SPACE_RE.match(line) is not None,
495 'Found a space in indentation (must be all tabs):')
Ryan Cui1562fb82011-05-09 11:01:31 -0700496
Ryan Cuiec4d6332011-05-02 14:15:25 -0700497
Rahul Chaudhry09f61372015-07-31 17:14:26 -0700498def _check_gofmt(_project, commit):
499 """Checks that Go files are formatted with gofmt."""
500 errors = []
501 files = _filter_files(_get_affected_files(commit, relative=True),
502 [r'\.go$'])
503
504 for gofile in files:
505 contents = _get_file_content(gofile, commit)
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700506 output = _run_command(cmd=['gofmt', '-l'], input=contents,
507 combine_stdout_stderr=True)
Rahul Chaudhry09f61372015-07-31 17:14:26 -0700508 if output:
509 errors.append(gofile)
510 if errors:
511 return HookFailure('Files not formatted with gofmt:', errors)
512
513
Mike Frysingerae409522014-02-01 03:16:11 -0500514def _check_change_has_test_field(_project, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700515 """Check for a non-empty 'TEST=' field in the commit message."""
David McMahon8f6553e2011-06-10 15:46:36 -0700516 TEST_RE = r'\nTEST=\S+'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700517
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700518 if not re.search(TEST_RE, _get_commit_desc(commit)):
Ryan Cui1562fb82011-05-09 11:01:31 -0700519 msg = 'Changelist description needs TEST field (after first line)'
520 return HookFailure(msg)
521
Ryan Cuiec4d6332011-05-02 14:15:25 -0700522
Mike Frysingerae409522014-02-01 03:16:11 -0500523def _check_change_has_valid_cq_depend(_project, commit):
David Jamesc3b68b32013-04-03 09:17:03 -0700524 """Check for a correctly formatted CQ-DEPEND field in the commit message."""
525 msg = 'Changelist has invalid CQ-DEPEND target.'
526 example = 'Example: CQ-DEPEND=CL:1234, CL:2345'
527 try:
528 patch.GetPaladinDeps(_get_commit_desc(commit))
529 except ValueError as ex:
530 return HookFailure(msg, [example, str(ex)])
531
532
Bernie Thompsonf8fea992016-01-14 10:27:18 -0800533def _check_change_is_contribution(_project, commit):
534 """Check that the change is a contribution."""
535 NO_CONTRIB = 'not a contribution'
536 if NO_CONTRIB in _get_commit_desc(commit).lower():
537 msg = ('Changelist is not a contribution, this cannot be accepted.\n'
538 'Please remove the "%s" text from the commit message.') % NO_CONTRIB
539 return HookFailure(msg)
540
541
Alex Deymo643ac4c2015-09-03 10:40:50 -0700542def _check_change_has_bug_field(project, commit):
David McMahon8f6553e2011-06-10 15:46:36 -0700543 """Check for a correctly formatted 'BUG=' field in the commit message."""
David James5c0073d2013-04-03 08:48:52 -0700544 OLD_BUG_RE = r'\nBUG=.*chromium-os'
545 if re.search(OLD_BUG_RE, _get_commit_desc(commit)):
546 msg = ('The chromium-os bug tracker is now deprecated. Please use\n'
547 'the chromium tracker in your BUG= line now.')
548 return HookFailure(msg)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700549
Alex Deymo643ac4c2015-09-03 10:40:50 -0700550 # Android internal and external projects use "Bug: " to track bugs in
551 # buganizer.
552 BUG_COLON_REMOTES = (
553 'aosp',
554 'goog',
555 )
556 if project.remote in BUG_COLON_REMOTES:
557 BUG_RE = r'\nBug: ?([Nn]one|\d+)'
558 if not re.search(BUG_RE, _get_commit_desc(commit)):
559 msg = ('Changelist description needs BUG field (after first line):\n'
560 'Bug: 9999 (for buganizer)\n'
561 'BUG=None')
562 return HookFailure(msg)
563 else:
564 BUG_RE = r'\nBUG=([Nn]one|(chrome-os-partner|chromium|brillo|b):\d+)'
565 if not re.search(BUG_RE, _get_commit_desc(commit)):
566 msg = ('Changelist description needs BUG field (after first line):\n'
567 'BUG=brillo:9999 (for Brillo tracker)\n'
568 'BUG=chromium:9999 (for public tracker)\n'
569 'BUG=chrome-os-partner:9999 (for partner tracker)\n'
570 'BUG=b:9999 (for buganizer)\n'
571 'BUG=None')
572 return HookFailure(msg)
Ryan Cui1562fb82011-05-09 11:01:31 -0700573
Ryan Cuiec4d6332011-05-02 14:15:25 -0700574
Mike Frysinger292b45d2014-11-25 01:17:10 -0500575def _check_for_uprev(project, commit, project_top=None):
Doug Anderson42b8a052013-06-26 10:45:36 -0700576 """Check that we're not missing a revbump of an ebuild in the given commit.
577
578 If the given commit touches files in a directory that has ebuilds somewhere
579 up the directory hierarchy, it's very likely that we need an ebuild revbump
580 in order for those changes to take effect.
581
582 It's not totally trivial to detect a revbump, so at least detect that an
583 ebuild with a revision number in it was touched. This should handle the
584 common case where we use a symlink to do the revbump.
585
586 TODO: it would be nice to enhance this hook to:
587 * Handle cases where people revbump with a slightly different syntax. I see
588 one ebuild (puppy) that revbumps with _pN. This is a false positive.
589 * Catches cases where people aren't using symlinks for revbumps. If they
590 edit a revisioned file directly (and are expected to rename it for revbump)
591 we'll miss that. Perhaps we could detect that the file touched is a
592 symlink?
593
594 If a project doesn't use symlinks we'll potentially miss a revbump, but we're
595 still better off than without this check.
596
597 Args:
Alex Deymo643ac4c2015-09-03 10:40:50 -0700598 project: The Project to look at
Doug Anderson42b8a052013-06-26 10:45:36 -0700599 commit: The commit to look at
Mike Frysinger292b45d2014-11-25 01:17:10 -0500600 project_top: Top dir to process commits in
Doug Anderson42b8a052013-06-26 10:45:36 -0700601
602 Returns:
603 A HookFailure or None.
604 """
Mike Frysinger011af942014-01-17 16:12:22 -0500605 # If this is the portage-stable overlay, then ignore the check. It's rare
606 # that we're doing anything other than importing files from upstream, so
607 # forcing a rev bump makes no sense.
608 whitelist = (
609 'chromiumos/overlays/portage-stable',
610 )
Alex Deymo643ac4c2015-09-03 10:40:50 -0700611 if project.name in whitelist:
Mike Frysinger011af942014-01-17 16:12:22 -0500612 return None
613
Mike Frysinger292b45d2014-11-25 01:17:10 -0500614 def FinalName(obj):
615 # If the file is being deleted, then the dst_file is not set.
616 if obj.dst_file is None:
617 return obj.src_file
618 else:
619 return obj.dst_file
620
621 affected_path_objs = _get_affected_files(
622 commit, include_deletes=True, include_symlinks=True, relative=True,
623 full_details=True)
Doug Anderson42b8a052013-06-26 10:45:36 -0700624
625 # Don't yell about changes to whitelisted files...
Aviv Keshet272f2e52016-04-25 14:49:44 -0700626 whitelist = ('ChangeLog', 'Manifest', 'metadata.xml', 'COMMIT-QUEUE.ini')
Mike Frysinger292b45d2014-11-25 01:17:10 -0500627 affected_path_objs = [x for x in affected_path_objs
628 if os.path.basename(FinalName(x)) not in whitelist]
629 if not affected_path_objs:
Doug Anderson42b8a052013-06-26 10:45:36 -0700630 return None
631
632 # If we've touched any file named with a -rN.ebuild then we'll say we're
633 # OK right away. See TODO above about enhancing this.
Mike Frysinger292b45d2014-11-25 01:17:10 -0500634 touched_revved_ebuild = any(re.search(r'-r\d*\.ebuild$', FinalName(x))
635 for x in affected_path_objs)
Doug Anderson42b8a052013-06-26 10:45:36 -0700636 if touched_revved_ebuild:
637 return None
638
Mike Frysinger292b45d2014-11-25 01:17:10 -0500639 # If we're creating new ebuilds from scratch, then we don't need an uprev.
640 # Find all the dirs that new ebuilds and ignore their files/.
641 ebuild_dirs = [os.path.dirname(FinalName(x)) + '/' for x in affected_path_objs
642 if FinalName(x).endswith('.ebuild') and x.status == 'A']
643 affected_path_objs = [obj for obj in affected_path_objs
644 if not any(FinalName(obj).startswith(x)
645 for x in ebuild_dirs)]
646 if not affected_path_objs:
647 return
648
Doug Anderson42b8a052013-06-26 10:45:36 -0700649 # We want to examine the current contents of all directories that are parents
650 # of files that were touched (up to the top of the project).
651 #
652 # ...note: we use the current directory contents even though it may have
653 # changed since the commit we're looking at. This is just a heuristic after
654 # all. Worst case we don't flag a missing revbump.
Mike Frysinger292b45d2014-11-25 01:17:10 -0500655 if project_top is None:
656 project_top = os.getcwd()
Doug Anderson42b8a052013-06-26 10:45:36 -0700657 dirs_to_check = set([project_top])
Mike Frysinger292b45d2014-11-25 01:17:10 -0500658 for obj in affected_path_objs:
659 path = os.path.join(project_top, os.path.dirname(FinalName(obj)))
Doug Anderson42b8a052013-06-26 10:45:36 -0700660 while os.path.exists(path) and not os.path.samefile(path, project_top):
661 dirs_to_check.add(path)
662 path = os.path.dirname(path)
663
664 # Look through each directory. If it's got an ebuild in it then we'll
665 # consider this as a case when we need a revbump.
Gwendal Grignoua3086c32014-12-09 11:17:22 -0800666 affected_paths = set(os.path.join(project_top, FinalName(x))
667 for x in affected_path_objs)
Doug Anderson42b8a052013-06-26 10:45:36 -0700668 for dir_path in dirs_to_check:
669 contents = os.listdir(dir_path)
670 ebuilds = [os.path.join(dir_path, path)
671 for path in contents if path.endswith('.ebuild')]
672 ebuilds_9999 = [path for path in ebuilds if path.endswith('-9999.ebuild')]
673
674 # If the -9999.ebuild file was touched the bot will uprev for us.
675 # ...we'll use a simple intersection here as a heuristic...
Mike Frysinger292b45d2014-11-25 01:17:10 -0500676 if set(ebuilds_9999) & affected_paths:
Doug Anderson42b8a052013-06-26 10:45:36 -0700677 continue
678
679 if ebuilds:
Mike Frysinger292b45d2014-11-25 01:17:10 -0500680 return HookFailure('Changelist probably needs a revbump of an ebuild, '
681 'or a -r1.ebuild symlink if this is a new ebuild:\n'
682 '%s' % dir_path)
Doug Anderson42b8a052013-06-26 10:45:36 -0700683
684 return None
685
686
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500687def _check_ebuild_eapi(project, commit):
688 """Make sure we have people use EAPI=4 or newer with custom ebuilds.
689
690 We want to get away from older EAPI's as it makes life confusing and they
691 have less builtin error checking.
692
693 Args:
Alex Deymo643ac4c2015-09-03 10:40:50 -0700694 project: The Project to look at
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500695 commit: The commit to look at
696
697 Returns:
698 A HookFailure or None.
699 """
700 # If this is the portage-stable overlay, then ignore the check. It's rare
Mike Frysingercd6adfc2014-02-06 01:03:56 -0500701 # that we're doing anything other than importing files from upstream, and
702 # we shouldn't be rewriting things fundamentally anyways.
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500703 whitelist = (
704 'chromiumos/overlays/portage-stable',
705 )
Alex Deymo643ac4c2015-09-03 10:40:50 -0700706 if project.name in whitelist:
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500707 return None
708
709 BAD_EAPIS = ('0', '1', '2', '3')
710
711 get_eapi = re.compile(r'^\s*EAPI=[\'"]?([^\'"]+)')
712
713 ebuilds_re = [r'\.ebuild$']
714 ebuilds = _filter_files(_get_affected_files(commit, relative=True),
715 ebuilds_re)
716 bad_ebuilds = []
717
718 for ebuild in ebuilds:
719 # If the ebuild does not specify an EAPI, it defaults to 0.
720 eapi = '0'
721
722 lines = _get_file_content(ebuild, commit).splitlines()
723 if len(lines) == 1:
724 # This is most likely a symlink, so skip it entirely.
725 continue
726
727 for line in lines:
728 m = get_eapi.match(line)
729 if m:
730 # Once we hit the first EAPI line in this ebuild, stop processing.
731 # The spec requires that there only be one and it be first, so
732 # checking all possible values is pointless. We also assume that
733 # it's "the" EAPI line and not something in the middle of a heredoc.
734 eapi = m.group(1)
735 break
736
737 if eapi in BAD_EAPIS:
738 bad_ebuilds.append((ebuild, eapi))
739
740 if bad_ebuilds:
741 # pylint: disable=C0301
742 url = 'http://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/upgrade-ebuild-eapis'
743 # pylint: enable=C0301
744 return HookFailure(
Mike Frysingercd6adfc2014-02-06 01:03:56 -0500745 'These ebuilds are using old EAPIs. If these are imported from\n'
746 'Gentoo, then you may ignore and upload once with the --no-verify\n'
747 'flag. Otherwise, please update to 4 or newer.\n'
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500748 '\t%s\n'
749 'See this guide for more details:\n%s\n' %
750 ('\n\t'.join(['%s: EAPI=%s' % x for x in bad_ebuilds]), url))
751
752
Mike Frysinger89bdb852014-02-01 05:26:26 -0500753def _check_ebuild_keywords(_project, commit):
Mike Frysingerc51ece72014-01-17 16:23:40 -0500754 """Make sure we use the new style KEYWORDS when possible in ebuilds.
755
756 If an ebuild generally does not care about the arch it is running on, then
757 ebuilds should flag it with one of:
758 KEYWORDS="*" # A stable ebuild.
759 KEYWORDS="~*" # An unstable ebuild.
760 KEYWORDS="-* ..." # Is known to only work on specific arches.
761
762 Args:
Alex Deymo643ac4c2015-09-03 10:40:50 -0700763 project: The Project to look at
Mike Frysingerc51ece72014-01-17 16:23:40 -0500764 commit: The commit to look at
765
766 Returns:
767 A HookFailure or None.
768 """
769 WHITELIST = set(('*', '-*', '~*'))
770
771 get_keywords = re.compile(r'^\s*KEYWORDS="(.*)"')
772
Mike Frysinger89bdb852014-02-01 05:26:26 -0500773 ebuilds_re = [r'\.ebuild$']
774 ebuilds = _filter_files(_get_affected_files(commit, relative=True),
775 ebuilds_re)
776
Mike Frysinger8d42d742014-09-22 15:50:21 -0400777 bad_ebuilds = []
Mike Frysingerc51ece72014-01-17 16:23:40 -0500778 for ebuild in ebuilds:
Mike Frysinger5c9e58d2014-09-09 03:32:50 -0400779 # We get the full content rather than a diff as the latter does not work
780 # on new files (like when adding new ebuilds).
781 lines = _get_file_content(ebuild, commit).splitlines()
782 for line in lines:
Mike Frysingerc51ece72014-01-17 16:23:40 -0500783 m = get_keywords.match(line)
784 if m:
785 keywords = set(m.group(1).split())
786 if not keywords or WHITELIST - keywords != WHITELIST:
787 continue
788
Mike Frysinger8d42d742014-09-22 15:50:21 -0400789 bad_ebuilds.append(ebuild)
790
791 if bad_ebuilds:
792 return HookFailure(
793 '%s\n'
794 'Please update KEYWORDS to use a glob:\n'
795 'If the ebuild should be marked stable (normal for non-9999 ebuilds):\n'
796 ' KEYWORDS="*"\n'
797 'If the ebuild should be marked unstable (normal for '
798 'cros-workon / 9999 ebuilds):\n'
799 ' KEYWORDS="~*"\n'
Mike Frysingerde8efea2015-05-17 03:42:26 -0400800 'If the ebuild needs to be marked for only specific arches, '
Mike Frysinger8d42d742014-09-22 15:50:21 -0400801 'then use -* like so:\n'
802 ' KEYWORDS="-* arm ..."\n' % '\n* '.join(bad_ebuilds))
Mike Frysingerc51ece72014-01-17 16:23:40 -0500803
804
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800805def _check_ebuild_licenses(_project, commit):
806 """Check if the LICENSE field in the ebuild is correct."""
Brian Norris7a610e82016-02-17 12:24:54 -0800807 affected_paths = _get_affected_files(commit, relative=True)
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800808 touched_ebuilds = [x for x in affected_paths if x.endswith('.ebuild')]
809
810 # A list of licenses to ignore for now.
Yu-Ju Hongc0963fa2014-03-03 12:36:52 -0800811 LICENSES_IGNORE = ['||', '(', ')']
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800812
813 for ebuild in touched_ebuilds:
814 # Skip virutal packages.
815 if ebuild.split('/')[-3] == 'virtual':
816 continue
817
818 try:
Brian Norris7a610e82016-02-17 12:24:54 -0800819 ebuild_content = _get_file_content(ebuild, commit)
820 license_types = licenses_lib.GetLicenseTypesFromEbuild(ebuild_content)
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800821 except ValueError as e:
822 return HookFailure(e.message, [ebuild])
823
824 # Also ignore licenses ending with '?'
825 for license_type in [x for x in license_types
826 if x not in LICENSES_IGNORE and not x.endswith('?')]:
827 try:
Mike Frysinger2ec70ed2014-08-17 19:28:34 -0400828 licenses_lib.Licensing.FindLicenseType(license_type)
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800829 except AssertionError as e:
830 return HookFailure(e.message, [ebuild])
831
832
Mike Frysingercd363c82014-02-01 05:20:18 -0500833def _check_ebuild_virtual_pv(project, commit):
834 """Enforce the virtual PV policies."""
835 # If this is the portage-stable overlay, then ignore the check.
836 # We want to import virtuals as-is from upstream Gentoo.
837 whitelist = (
838 'chromiumos/overlays/portage-stable',
839 )
Alex Deymo643ac4c2015-09-03 10:40:50 -0700840 if project.name in whitelist:
Mike Frysingercd363c82014-02-01 05:20:18 -0500841 return None
842
843 # We assume the repo name is the same as the dir name on disk.
844 # It would be dumb to not have them match though.
Alex Deymo643ac4c2015-09-03 10:40:50 -0700845 project_base = os.path.basename(project.name)
Mike Frysingercd363c82014-02-01 05:20:18 -0500846
847 is_variant = lambda x: x.startswith('overlay-variant-')
848 is_board = lambda x: x.startswith('overlay-')
849 is_private = lambda x: x.endswith('-private')
850
851 get_pv = re.compile(r'(.*?)virtual/([^/]+)/\2-([^/]*)\.ebuild$')
852
853 ebuilds_re = [r'\.ebuild$']
854 ebuilds = _filter_files(_get_affected_files(commit, relative=True),
855 ebuilds_re)
856 bad_ebuilds = []
857
858 for ebuild in ebuilds:
859 m = get_pv.match(ebuild)
860 if m:
861 overlay = m.group(1)
862 if not overlay or not is_board(overlay):
Alex Deymo643ac4c2015-09-03 10:40:50 -0700863 overlay = project_base
Mike Frysingercd363c82014-02-01 05:20:18 -0500864
865 pv = m.group(3).split('-', 1)[0]
866
Bernie Thompsone5ee1822016-01-12 14:22:23 -0800867 # Virtual versions >= 4 are special cases used above the standard
868 # versioning structure, e.g. if one has a board inheriting a board.
869 if float(pv) >= 4:
870 want_pv = pv
871 elif is_private(overlay):
Mike Frysingercd363c82014-02-01 05:20:18 -0500872 want_pv = '3.5' if is_variant(overlay) else '3'
873 elif is_board(overlay):
874 want_pv = '2.5' if is_variant(overlay) else '2'
875 else:
876 want_pv = '1'
877
878 if pv != want_pv:
879 bad_ebuilds.append((ebuild, pv, want_pv))
880
881 if bad_ebuilds:
882 # pylint: disable=C0301
883 url = 'http://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/portage-build-faq#TOC-Virtuals-and-central-management'
884 # pylint: enable=C0301
885 return HookFailure(
886 'These virtuals have incorrect package versions (PVs). Please adjust:\n'
887 '\t%s\n'
888 'If this is an upstream Gentoo virtual, then you may ignore this\n'
889 'check (and re-run w/--no-verify). Otherwise, please see this\n'
890 'page for more details:\n%s\n' %
891 ('\n\t'.join(['%s:\n\t\tPV is %s but should be %s' % x
892 for x in bad_ebuilds]), url))
893
894
Daniel Erat9d203ff2015-02-17 10:12:21 -0700895def _check_portage_make_use_var(_project, commit):
896 """Verify that $USE is set correctly in make.conf and make.defaults."""
897 files = _filter_files(_get_affected_files(commit, relative=True),
898 [r'(^|/)make.(conf|defaults)$'])
899
900 errors = []
901 for path in files:
902 basename = os.path.basename(path)
903
904 # Has a USE= line already been encountered in this file?
905 saw_use = False
906
907 for i, line in enumerate(_get_file_content(path, commit).splitlines(), 1):
908 if not line.startswith('USE='):
909 continue
910
911 preserves_use = '${USE}' in line or '$USE' in line
912
913 if (basename == 'make.conf' or
914 (basename == 'make.defaults' and saw_use)) and not preserves_use:
915 errors.append('%s:%d: missing ${USE}' % (path, i))
916 elif basename == 'make.defaults' and not saw_use and preserves_use:
917 errors.append('%s:%d: ${USE} referenced in initial declaration' %
918 (path, i))
919
920 saw_use = True
921
922 if errors:
923 return HookFailure(
924 'One or more Portage make files appear to set USE incorrectly.\n'
925 '\n'
926 'All USE assignments in make.conf and all assignments after the\n'
927 'initial declaration in make.defaults should contain "${USE}" to\n'
928 'preserve previously-set flags.\n'
929 '\n'
930 'The initial USE declaration in make.defaults should not contain\n'
931 '"${USE}".\n',
932 errors)
933
934
Mike Frysingerae409522014-02-01 03:16:11 -0500935def _check_change_has_proper_changeid(_project, commit):
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700936 """Verify that Change-ID is present in last paragraph of commit message."""
Mike Frysinger4a22bf02014-10-31 13:53:35 -0400937 CHANGE_ID_RE = r'\nChange-Id: I[a-f0-9]+\n'
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700938 desc = _get_commit_desc(commit)
Mike Frysinger4a22bf02014-10-31 13:53:35 -0400939 m = re.search(CHANGE_ID_RE, desc)
Mike Frysinger02b88bd2014-11-21 00:29:38 -0500940 if not m:
Vadim Bendebury20532ba2017-05-23 17:26:15 -0700941 return HookFailure('Last paragraph of description must include Change-Id.')
Ryan Cui1562fb82011-05-09 11:01:31 -0700942
Vadim Bendebury20532ba2017-05-23 17:26:15 -0700943 # S-o-b tags always allowed to follow Change-ID.
944 allowed_tags = ['Signed-off-by']
945
Mike Frysinger02b88bd2014-11-21 00:29:38 -0500946 end = desc[m.end():].strip().splitlines()
Vadim Bendebury20532ba2017-05-23 17:26:15 -0700947 if end and end[-1].startswith('(cherry picked from commit'):
948 # Cherry picked patches allow more tags in the last paragraph.
949 allowed_tags += ['Reviewed-on', 'Reviewed-by', 'Commit-Ready', 'Tested-by']
950 end = end[:-1]
951
952 tag_search = '^(%s): ' % '|'.join(allowed_tags)
953
954 if [x for x in end if not re.search(tag_search, x)]:
955 return HookFailure('Only "%s:" tag(s) may follow the Change-Id.' %
956 ':", "'.join(allowed_tags))
Mike Frysinger02b88bd2014-11-21 00:29:38 -0500957
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700958
Mike Frysinger36b2ebc2014-10-31 14:02:03 -0400959def _check_commit_message_style(_project, commit):
960 """Verify that the commit message matches our style.
961
962 We do not check for BUG=/TEST=/etc... lines here as that is handled by other
963 commit hooks.
964 """
965 desc = _get_commit_desc(commit)
966
967 # The first line should be by itself.
968 lines = desc.splitlines()
969 if len(lines) > 1 and lines[1]:
970 return HookFailure('The second line of the commit message must be blank.')
971
972 # The first line should be one sentence.
973 if '. ' in lines[0]:
974 return HookFailure('The first line cannot be more than one sentence.')
975
976 # The first line cannot be too long.
977 MAX_FIRST_LINE_LEN = 100
978 if len(lines[0]) > MAX_FIRST_LINE_LEN:
979 return HookFailure('The first line must be less than %i chars.' %
980 MAX_FIRST_LINE_LEN)
981
982
Filipe Brandenburger4b542b12015-10-09 12:46:31 -0700983def _check_cros_license(_project, commit, options=()):
Alex Deymof5792ce2015-08-24 22:50:08 -0700984 """Verifies the Chromium OS license/copyright header.
Ryan Cuiec4d6332011-05-02 14:15:25 -0700985
Mike Frysinger98638102014-08-28 00:15:08 -0400986 Should be following the spec:
987 http://dev.chromium.org/developers/coding-style#TOC-File-headers
988 """
989 # For older years, be a bit more flexible as our policy says leave them be.
990 LICENSE_HEADER = (
991 r'.* Copyright( \(c\))? 20[-0-9]{2,7} The Chromium OS Authors\. '
Mike Frysingerb81102f2014-11-21 00:33:35 -0500992 r'All rights reserved\.' r'\n'
Mike Frysinger98638102014-08-28 00:15:08 -0400993 r'.* Use of this source code is governed by a BSD-style license that can '
Mike Frysingerb81102f2014-11-21 00:33:35 -0500994 r'be\n'
Mike Frysinger98638102014-08-28 00:15:08 -0400995 r'.* found in the LICENSE file\.'
Mike Frysingerb81102f2014-11-21 00:33:35 -0500996 r'\n'
Mike Frysinger98638102014-08-28 00:15:08 -0400997 )
998 license_re = re.compile(LICENSE_HEADER, re.MULTILINE)
999
1000 # For newer years, be stricter.
1001 COPYRIGHT_LINE = (
1002 r'.* Copyright \(c\) 20(1[5-9]|[2-9][0-9]) The Chromium OS Authors\. '
Mike Frysingerb81102f2014-11-21 00:33:35 -05001003 r'All rights reserved\.' r'\n'
Mike Frysinger98638102014-08-28 00:15:08 -04001004 )
1005 copyright_re = re.compile(COPYRIGHT_LINE)
1006
Filipe Brandenburger4b542b12015-10-09 12:46:31 -07001007 parser = argparse.ArgumentParser()
1008 parser.add_argument('--exclude_regex', action='append')
1009 parser.add_argument('--include_regex', action='append')
1010 opts = parser.parse_args(options)
1011 included = opts.include_regex or []
1012 excluded = opts.exclude_regex or []
1013
Mike Frysinger98638102014-08-28 00:15:08 -04001014 bad_files = []
1015 bad_copyright_files = []
1016 files = _filter_files(_get_affected_files(commit, relative=True),
Filipe Brandenburger4b542b12015-10-09 12:46:31 -07001017 included + COMMON_INCLUDED_PATHS,
1018 excluded + COMMON_EXCLUDED_PATHS)
Mike Frysinger98638102014-08-28 00:15:08 -04001019
1020 for f in files:
1021 contents = _get_file_content(f, commit)
1022 if not contents:
1023 # Ignore empty files.
1024 continue
1025
1026 if not license_re.search(contents):
1027 bad_files.append(f)
1028 elif copyright_re.search(contents):
1029 bad_copyright_files.append(f)
1030
1031 if bad_files:
1032 msg = '%s:\n%s\n%s' % (
1033 'License must match', license_re.pattern,
1034 'Found a bad header in these files:')
1035 return HookFailure(msg, bad_files)
1036
1037 if bad_copyright_files:
1038 msg = 'Do not use (c) in copyright headers in new files:'
1039 return HookFailure(msg, bad_copyright_files)
Ryan Cuiec4d6332011-05-02 14:15:25 -07001040
1041
Alex Deymof5792ce2015-08-24 22:50:08 -07001042def _check_aosp_license(_project, commit):
1043 """Verifies the AOSP license/copyright header.
1044
1045 AOSP uses the Apache2 License:
1046 https://source.android.com/source/licenses.html
1047 """
1048 LICENSE_HEADER = (
1049 r"""^[#/\*]*
1050[#/\*]* ?Copyright( \([cC]\))? 20[-0-9]{2,7} The Android Open Source Project
1051[#/\*]* ?
1052[#/\*]* ?Licensed under the Apache License, Version 2.0 \(the "License"\);
1053[#/\*]* ?you may not use this file except in compliance with the License\.
1054[#/\*]* ?You may obtain a copy of the License at
1055[#/\*]* ?
1056[#/\*]* ? http://www\.apache\.org/licenses/LICENSE-2\.0
1057[#/\*]* ?
1058[#/\*]* ?Unless required by applicable law or agreed to in writing, software
1059[#/\*]* ?distributed under the License is distributed on an "AS IS" BASIS,
1060[#/\*]* ?WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or """
1061 r"""implied\.
1062[#/\*]* ?See the License for the specific language governing permissions and
1063[#/\*]* ?limitations under the License\.
1064[#/\*]*$
1065"""
1066 )
1067 license_re = re.compile(LICENSE_HEADER, re.MULTILINE)
1068
1069 files = _filter_files(_get_affected_files(commit, relative=True),
1070 COMMON_INCLUDED_PATHS,
1071 COMMON_EXCLUDED_PATHS)
1072
1073 bad_files = []
1074 for f in files:
1075 contents = _get_file_content(f, commit)
1076 if not contents:
1077 # Ignore empty files.
1078 continue
1079
1080 if not license_re.search(contents):
1081 bad_files.append(f)
1082
1083 if bad_files:
1084 msg = ('License must match:\n%s\nFound a bad header in these files:' %
1085 license_re.pattern)
1086 return HookFailure(msg, bad_files)
1087
1088
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001089def _check_layout_conf(_project, commit):
1090 """Verifies the metadata/layout.conf file."""
1091 repo_name = 'profiles/repo_name'
Mike Frysinger94a670c2014-09-19 12:46:26 -04001092 repo_names = []
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001093 layout_path = 'metadata/layout.conf'
Mike Frysinger94a670c2014-09-19 12:46:26 -04001094 layout_paths = []
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001095
Mike Frysinger94a670c2014-09-19 12:46:26 -04001096 # Handle multiple overlays in a single commit (like the public tree).
1097 for f in _get_affected_files(commit, relative=True):
1098 if f.endswith(repo_name):
1099 repo_names.append(f)
1100 elif f.endswith(layout_path):
1101 layout_paths.append(f)
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001102
1103 # Disallow new repos with the repo_name file.
Mike Frysinger94a670c2014-09-19 12:46:26 -04001104 if repo_names:
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001105 return HookFailure('%s: use "repo-name" in %s instead' %
Mike Frysinger94a670c2014-09-19 12:46:26 -04001106 (repo_names, layout_path))
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001107
Mike Frysinger94a670c2014-09-19 12:46:26 -04001108 # Gather all the errors in one pass so we show one full message.
1109 all_errors = {}
1110 for layout_path in layout_paths:
1111 all_errors[layout_path] = errors = []
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001112
Mike Frysinger94a670c2014-09-19 12:46:26 -04001113 # Make sure the config file is sorted.
1114 data = [x for x in _get_file_content(layout_path, commit).splitlines()
1115 if x and x[0] != '#']
1116 if sorted(data) != data:
1117 errors += ['keep lines sorted']
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001118
Mike Frysinger94a670c2014-09-19 12:46:26 -04001119 # Require people to set specific values all the time.
1120 settings = (
1121 # TODO: Enable this for everyone. http://crbug.com/408038
1122 #('fast caching', 'cache-format = md5-dict'),
1123 ('fast manifests', 'thin-manifests = true'),
Mike Frysingerd7734522015-02-26 16:12:43 -05001124 ('extra features', 'profile-formats = portage-2 profile-default-eapi'),
1125 ('newer eapi', 'profile_eapi_when_unspecified = 5-progress'),
Mike Frysinger94a670c2014-09-19 12:46:26 -04001126 )
1127 for reason, line in settings:
1128 if line not in data:
1129 errors += ['enable %s with: %s' % (reason, line)]
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001130
Mike Frysinger94a670c2014-09-19 12:46:26 -04001131 # Require one of these settings.
Mike Frysinger5fae62d2015-11-11 20:12:15 -05001132 if 'use-manifests = strict' not in data:
1133 errors += ['enable file checking with: use-manifests = strict']
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001134
Mike Frysinger94a670c2014-09-19 12:46:26 -04001135 # Require repo-name to be set.
Mike Frysinger324cf682014-09-22 15:52:50 -04001136 for line in data:
1137 if line.startswith('repo-name = '):
1138 break
1139 else:
Mike Frysinger94a670c2014-09-19 12:46:26 -04001140 errors += ['set the board name with: repo-name = $BOARD']
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001141
Mike Frysinger94a670c2014-09-19 12:46:26 -04001142 # Summarize all the errors we saw (if any).
1143 lines = ''
1144 for layout_path, errors in all_errors.items():
1145 if errors:
1146 lines += '\n\t- '.join(['\n* %s:' % layout_path] + errors)
1147 if lines:
1148 lines = 'See the portage(5) man page for layout.conf details' + lines + '\n'
1149 return HookFailure(lines)
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001150
1151
Ryan Cuiec4d6332011-05-02 14:15:25 -07001152# Project-specific hooks
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001153
Ryan Cui1562fb82011-05-09 11:01:31 -07001154
Mike Frysingerae409522014-02-01 03:16:11 -05001155def _run_checkpatch(_project, commit, options=()):
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001156 """Runs checkpatch.pl on the given project"""
1157 hooks_dir = _get_hooks_dir()
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001158 options = list(options)
1159 if commit == PRE_SUBMIT:
1160 # The --ignore option must be present and include 'MISSING_SIGN_OFF' in
1161 # this case.
1162 options.append('--ignore=MISSING_SIGN_OFF')
Filipe Brandenburger28d48d62015-10-07 09:48:54 -07001163 # Always ignore the check for the MAINTAINERS file. We do not track that
1164 # information on that file in our source trees, so let's suppress the
1165 # warning.
1166 options.append('--ignore=FILE_PATH_CHANGES')
Filipe Brandenburgerce978322015-10-09 10:04:15 -07001167 # Do not complain about the Change-Id: fields, since we use Gerrit.
1168 # Upstream does not want those lines (since they do not use Gerrit), but
1169 # we always do, so disable the check globally.
Daisuke Nojiri4844f892015-10-08 09:54:33 -07001170 options.append('--ignore=GERRIT_CHANGE_ID')
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001171 cmd = ['%s/checkpatch.pl' % hooks_dir] + options + ['-']
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001172 cmd_result = cros_build_lib.RunCommand(cmd=cmd,
1173 print_cmd=False,
1174 input=_get_patch(commit),
1175 stdout_to_pipe=True,
1176 combine_stdout_stderr=True,
1177 error_code_ok=True)
1178 if cmd_result.returncode:
1179 return HookFailure('checkpatch.pl errors/warnings\n\n' + cmd_result.output)
Ryan Cuiec4d6332011-05-02 14:15:25 -07001180
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001181
Mike Frysingerae409522014-02-01 03:16:11 -05001182def _kernel_configcheck(_project, commit):
Olof Johanssona96810f2012-09-04 16:20:03 -07001183 """Makes sure kernel config changes are not mixed with code changes"""
1184 files = _get_affected_files(commit)
1185 if not len(_filter_files(files, [r'chromeos/config'])) in [0, len(files)]:
1186 return HookFailure('Changes to chromeos/config/ and regular files must '
1187 'be in separate commits:\n%s' % '\n'.join(files))
Anton Staaf815d6852011-08-22 10:08:45 -07001188
Mike Frysingerae409522014-02-01 03:16:11 -05001189
1190def _run_json_check(_project, commit):
Dale Curtis2975c432011-05-03 17:25:20 -07001191 """Checks that all JSON files are syntactically valid."""
Dale Curtisa039cfd2011-05-04 12:01:05 -07001192 for f in _filter_files(_get_affected_files(commit), [r'.*\.json']):
Dale Curtis2975c432011-05-03 17:25:20 -07001193 try:
1194 json.load(open(f))
1195 except Exception, e:
Ryan Cui1562fb82011-05-09 11:01:31 -07001196 return HookFailure('Invalid JSON in %s: %s' % (f, e))
Dale Curtis2975c432011-05-03 17:25:20 -07001197
1198
Mike Frysingerae409522014-02-01 03:16:11 -05001199def _check_manifests(_project, commit):
Mike Frysinger52b537e2013-08-22 22:59:53 -04001200 """Make sure Manifest files only have DIST lines"""
1201 paths = []
1202
1203 for path in _get_affected_files(commit):
1204 if os.path.basename(path) != 'Manifest':
1205 continue
1206 if not os.path.exists(path):
1207 continue
1208
1209 with open(path, 'r') as f:
1210 for line in f.readlines():
1211 if not line.startswith('DIST '):
1212 paths.append(path)
1213 break
1214
1215 if paths:
1216 return HookFailure('Please remove lines that do not start with DIST:\n%s' %
1217 ('\n'.join(paths),))
1218
1219
Mike Frysingerae409522014-02-01 03:16:11 -05001220def _check_change_has_branch_field(_project, commit):
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001221 """Check for a non-empty 'BRANCH=' field in the commit message."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001222 if commit == PRE_SUBMIT:
1223 return
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001224 BRANCH_RE = r'\nBRANCH=\S+'
1225
1226 if not re.search(BRANCH_RE, _get_commit_desc(commit)):
1227 msg = ('Changelist description needs BRANCH field (after first line)\n'
1228 'E.g. BRANCH=none or BRANCH=link,snow')
1229 return HookFailure(msg)
1230
1231
Mike Frysingerae409522014-02-01 03:16:11 -05001232def _check_change_has_signoff_field(_project, commit):
Shawn Nematbakhsh51e16ac2014-01-28 15:31:07 -08001233 """Check for a non-empty 'Signed-off-by:' field in the commit message."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001234 if commit == PRE_SUBMIT:
1235 return
Shawn Nematbakhsh51e16ac2014-01-28 15:31:07 -08001236 SIGNOFF_RE = r'\nSigned-off-by: \S+'
1237
1238 if not re.search(SIGNOFF_RE, _get_commit_desc(commit)):
1239 msg = ('Changelist description needs Signed-off-by: field\n'
1240 'E.g. Signed-off-by: My Name <me@chromium.org>')
1241 return HookFailure(msg)
1242
1243
Aviv Keshet5ac59522017-01-31 14:28:27 -08001244def _check_cq_ini_well_formed(_project, commit):
1245 """Check that any modified COMMIT-QUEUE.ini files are well formed."""
1246 pattern = '.*' + constants.CQ_CONFIG_FILENAME
1247 files = _filter_files(_get_affected_files(commit), (pattern,))
1248
1249 # TODO(akeshet): Check not only that the file is parseable, but that all the
1250 # pre-cq configs it requests are existing ones.
1251 for f in files:
1252 try:
1253 parser = ConfigParser.SafeConfigParser()
1254 # Prior to python3, ConfigParser has no read_string method, so we must
1255 # pass it either a file path or file like object. And we must use
1256 # _get_file_content to fetch file contents to ensure we are examining the
1257 # commit diff, rather than whatever's on disk.
1258 contents = _get_file_content(f, commit)
1259 parser.readfp(StringIO.StringIO(contents))
1260 except ConfigParser.Error as e:
1261 msg = ('Unable to parse COMMIT-QUEUE.ini file at %s due to %s.' %
1262 (f, e))
1263 return HookFailure(msg)
1264
1265
Jon Salz3ee59de2012-08-18 13:54:22 +08001266def _run_project_hook_script(script, project, commit):
1267 """Runs a project hook script.
1268
1269 The script is run with the following environment variables set:
1270 PRESUBMIT_PROJECT: The affected project
1271 PRESUBMIT_COMMIT: The affected commit
1272 PRESUBMIT_FILES: A newline-separated list of affected files
1273
1274 The script is considered to fail if the exit code is non-zero. It should
1275 write an error message to stdout.
1276 """
1277 env = dict(os.environ)
Alex Deymo643ac4c2015-09-03 10:40:50 -07001278 env['PRESUBMIT_PROJECT'] = project.name
Jon Salz3ee59de2012-08-18 13:54:22 +08001279 env['PRESUBMIT_COMMIT'] = commit
1280
1281 # Put affected files in an environment variable
1282 files = _get_affected_files(commit)
1283 env['PRESUBMIT_FILES'] = '\n'.join(files)
1284
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001285 cmd_result = cros_build_lib.RunCommand(cmd=script,
1286 env=env,
1287 shell=True,
1288 print_cmd=False,
1289 input=os.devnull,
1290 stdout_to_pipe=True,
1291 combine_stdout_stderr=True,
1292 error_code_ok=True)
1293 if cmd_result.returncode:
1294 stdout = cmd_result.output
Jon Salz7b618af2012-08-31 06:03:16 +08001295 if stdout:
1296 stdout = re.sub('(?m)^', ' ', stdout)
1297 return HookFailure('Hook script "%s" failed with code %d%s' %
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001298 (script, cmd_result.returncode,
Jon Salz3ee59de2012-08-18 13:54:22 +08001299 ':\n' + stdout if stdout else ''))
1300
1301
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001302def _check_project_prefix(_project, commit):
Mike Frysinger55f85b52014-12-18 14:45:21 -05001303 """Require the commit message have a project specific prefix as needed."""
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001304
1305 files = _get_affected_files(commit, relative=True)
1306 prefix = os.path.commonprefix(files)
1307 prefix = os.path.dirname(prefix)
1308
1309 # If there is no common prefix, the CL span multiple projects.
Daniel Erata350fd32014-09-29 14:02:34 -07001310 if not prefix:
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001311 return
1312
1313 project_name = prefix.split('/')[0]
Daniel Erata350fd32014-09-29 14:02:34 -07001314
1315 # The common files may all be within a subdirectory of the main project
1316 # directory, so walk up the tree until we find an alias file.
1317 # _get_affected_files() should return relative paths, but check against '/' to
1318 # ensure that this loop terminates even if it receives an absolute path.
1319 while prefix and prefix != '/':
1320 alias_file = os.path.join(prefix, '.project_alias')
1321
1322 # If an alias exists, use it.
1323 if os.path.isfile(alias_file):
1324 project_name = osutils.ReadFile(alias_file).strip()
1325
1326 prefix = os.path.dirname(prefix)
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001327
1328 if not _get_commit_desc(commit).startswith(project_name + ': '):
1329 return HookFailure('The commit title for changes affecting only %s'
1330 ' should start with \"%s: \"'
1331 % (project_name, project_name))
1332
1333
Mike Frysingerf9d41b32017-02-23 15:20:04 -05001334def _check_exec_files(_project, commit):
1335 """Make +x bits on files."""
1336 # List of files that should never be +x.
1337 NO_EXEC = (
1338 'ChangeLog*',
1339 'COPYING',
1340 'make.conf',
1341 'make.defaults',
1342 'Manifest',
1343 'OWNERS',
1344 'package.use',
1345 'package.keywords',
1346 'package.mask',
1347 'parent',
1348 'README',
1349 'TODO',
1350 '.gitignore',
1351 '*.[achly]',
1352 '*.[ch]xx',
1353 '*.boto',
1354 '*.cc',
1355 '*.cfg',
1356 '*.conf',
1357 '*.config',
1358 '*.cpp',
1359 '*.css',
1360 '*.ebuild',
1361 '*.eclass',
1362 '*.gyp',
1363 '*.gypi',
1364 '*.htm',
1365 '*.html',
1366 '*.ini',
1367 '*.js',
1368 '*.json',
1369 '*.md',
1370 '*.mk',
1371 '*.patch',
1372 '*.policy',
1373 '*.proto',
1374 '*.raw',
1375 '*.rules',
1376 '*.service',
1377 '*.target',
1378 '*.txt',
1379 '*.xml',
1380 '*.yaml',
1381 )
1382
1383 def FinalName(obj):
1384 # If the file is being deleted, then the dst_file is not set.
1385 if obj.dst_file is None:
1386 return obj.src_file
1387 else:
1388 return obj.dst_file
1389
1390 bad_files = []
1391 files = _get_affected_files(commit, relative=True, full_details=True)
1392 for f in files:
1393 mode = int(f.dst_mode, 8)
1394 if not mode & 0o111:
1395 continue
1396 name = FinalName(f)
1397 for no_exec in NO_EXEC:
1398 if fnmatch.fnmatch(name, no_exec):
1399 bad_files.append(name)
1400 break
1401
1402 if bad_files:
1403 return HookFailure('These files should not be executable. '
1404 'Please `chmod -x` them.', bad_files)
1405
1406
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001407# Base
1408
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001409# A list of hooks which are not project specific and check patch description
1410# (as opposed to patch body).
1411_PATCH_DESCRIPTION_HOOKS = [
Ryan Cui9b651632011-05-11 11:38:58 -07001412 _check_change_has_bug_field,
David Jamesc3b68b32013-04-03 09:17:03 -07001413 _check_change_has_valid_cq_depend,
Ryan Cui9b651632011-05-11 11:38:58 -07001414 _check_change_has_test_field,
1415 _check_change_has_proper_changeid,
Mike Frysinger36b2ebc2014-10-31 14:02:03 -04001416 _check_commit_message_style,
Bernie Thompsonf8fea992016-01-14 10:27:18 -08001417 _check_change_is_contribution,
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001418]
1419
1420
1421# A list of hooks that are not project-specific
1422_COMMON_HOOKS = [
Aviv Keshet5ac59522017-01-31 14:28:27 -08001423 _check_cq_ini_well_formed,
1424 _check_cros_license,
Mike Frysingerbf8b91c2014-02-01 02:50:27 -05001425 _check_ebuild_eapi,
Mike Frysinger89bdb852014-02-01 05:26:26 -05001426 _check_ebuild_keywords,
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -08001427 _check_ebuild_licenses,
Mike Frysingercd363c82014-02-01 05:20:18 -05001428 _check_ebuild_virtual_pv,
Mike Frysingerf9d41b32017-02-23 15:20:04 -05001429 _check_exec_files,
Daniel Erat9d203ff2015-02-17 10:12:21 -07001430 _check_for_uprev,
Rahul Chaudhry09f61372015-07-31 17:14:26 -07001431 _check_gofmt,
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001432 _check_layout_conf,
Daniel Erat9d203ff2015-02-17 10:12:21 -07001433 _check_no_long_lines,
1434 _check_no_stray_whitespace,
Ryan Cui9b651632011-05-11 11:38:58 -07001435 _check_no_tabs,
Daniel Erat9d203ff2015-02-17 10:12:21 -07001436 _check_portage_make_use_var,
Aviv Keshet5ac59522017-01-31 14:28:27 -08001437 _check_tabbed_indents,
Ryan Cui9b651632011-05-11 11:38:58 -07001438]
Ryan Cuiec4d6332011-05-02 14:15:25 -07001439
Ryan Cui1562fb82011-05-09 11:01:31 -07001440
Ryan Cui9b651632011-05-11 11:38:58 -07001441# A dictionary of project-specific hooks(callbacks), indexed by project name.
1442# dict[project] = [callback1, callback2]
1443_PROJECT_SPECIFIC_HOOKS = {
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001444 "chromiumos/platform2": [_check_project_prefix],
Mike Frysingeraf891292015-03-25 19:46:53 -04001445 "chromiumos/third_party/kernel": [_kernel_configcheck],
1446 "chromiumos/third_party/kernel-next": [_kernel_configcheck],
Ryan Cui9b651632011-05-11 11:38:58 -07001447}
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001448
Ryan Cui1562fb82011-05-09 11:01:31 -07001449
Ryan Cui9b651632011-05-11 11:38:58 -07001450# A dictionary of flags (keys) that can appear in the config file, and the hook
Mike Frysinger3554bc92015-03-11 04:59:21 -04001451# that the flag controls (value).
1452_HOOK_FLAGS = {
Mike Frysingera7642f52015-03-25 18:31:42 -04001453 'checkpatch_check': _run_checkpatch,
Ryan Cui9b651632011-05-11 11:38:58 -07001454 'stray_whitespace_check': _check_no_stray_whitespace,
Mike Frysingerff6c7d62015-03-24 13:49:46 -04001455 'json_check': _run_json_check,
Ryan Cui9b651632011-05-11 11:38:58 -07001456 'long_line_check': _check_no_long_lines,
Alex Deymof5792ce2015-08-24 22:50:08 -07001457 'cros_license_check': _check_cros_license,
1458 'aosp_license_check': _check_aosp_license,
Ryan Cui9b651632011-05-11 11:38:58 -07001459 'tab_check': _check_no_tabs,
Prathmesh Prabhuc5254652016-12-22 12:58:05 -08001460 'tabbed_indent_required_check': _check_tabbed_indents,
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001461 'branch_check': _check_change_has_branch_field,
Shawn Nematbakhsh51e16ac2014-01-28 15:31:07 -08001462 'signoff_check': _check_change_has_signoff_field,
Josh Triplett0e8fc7f2014-04-23 16:00:00 -07001463 'bug_field_check': _check_change_has_bug_field,
1464 'test_field_check': _check_change_has_test_field,
Steve Fung49ec7e92015-03-23 16:07:12 -07001465 'manifest_check': _check_manifests,
Bernie Thompsonf8fea992016-01-14 10:27:18 -08001466 'contribution_check': _check_change_is_contribution,
Ryan Cui9b651632011-05-11 11:38:58 -07001467}
1468
1469
Mike Frysinger3554bc92015-03-11 04:59:21 -04001470def _get_override_hooks(config):
1471 """Returns a set of hooks controlled by the current project's config file.
Ryan Cui9b651632011-05-11 11:38:58 -07001472
1473 Expects to be called within the project root.
Jon Salz3ee59de2012-08-18 13:54:22 +08001474
1475 Args:
1476 config: A ConfigParser for the project's config file.
Ryan Cui9b651632011-05-11 11:38:58 -07001477 """
1478 SECTION = 'Hook Overrides'
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001479 SECTION_OPTIONS = 'Hook Overrides Options'
Jon Salz3ee59de2012-08-18 13:54:22 +08001480 if not config.has_section(SECTION):
Mike Frysinger3554bc92015-03-11 04:59:21 -04001481 return set(), set()
Ryan Cui9b651632011-05-11 11:38:58 -07001482
Mike Frysinger3554bc92015-03-11 04:59:21 -04001483 valid_keys = set(_HOOK_FLAGS.iterkeys())
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001484 hooks = _HOOK_FLAGS.copy()
Mike Frysinger3554bc92015-03-11 04:59:21 -04001485
1486 enable_flags = []
Ryan Cui9b651632011-05-11 11:38:58 -07001487 disable_flags = []
Jon Salz3ee59de2012-08-18 13:54:22 +08001488 for flag in config.options(SECTION):
Mike Frysinger3554bc92015-03-11 04:59:21 -04001489 if flag not in valid_keys:
1490 raise ValueError('Error: unknown key "%s" in hook section of "%s"' %
1491 (flag, _CONFIG_FILE))
1492
Ryan Cui9b651632011-05-11 11:38:58 -07001493 try:
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001494 enabled = config.getboolean(SECTION, flag)
Ryan Cui9b651632011-05-11 11:38:58 -07001495 except ValueError as e:
Mike Frysinger3554bc92015-03-11 04:59:21 -04001496 raise ValueError('Error: parsing flag "%s" in "%s" failed: %s' %
1497 (flag, _CONFIG_FILE, e))
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001498 if enabled:
1499 enable_flags.append(flag)
1500 else:
1501 disable_flags.append(flag)
Ryan Cui9b651632011-05-11 11:38:58 -07001502
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001503 # See if this hook has custom options.
1504 if enabled:
1505 try:
1506 options = config.get(SECTION_OPTIONS, flag)
1507 hooks[flag] = functools.partial(hooks[flag], options=options.split())
1508 except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
1509 pass
1510
1511 enabled_hooks = set(hooks[x] for x in enable_flags)
1512 disabled_hooks = set(hooks[x] for x in disable_flags)
Mike Frysinger3554bc92015-03-11 04:59:21 -04001513 return enabled_hooks, disabled_hooks
Ryan Cui9b651632011-05-11 11:38:58 -07001514
1515
Jon Salz3ee59de2012-08-18 13:54:22 +08001516def _get_project_hook_scripts(config):
1517 """Returns a list of project-specific hook scripts.
1518
1519 Args:
1520 config: A ConfigParser for the project's config file.
1521 """
1522 SECTION = 'Hook Scripts'
1523 if not config.has_section(SECTION):
1524 return []
1525
1526 hook_names_values = config.items(SECTION)
1527 hook_names_values.sort(key=lambda x: x[0])
1528 return [x[1] for x in hook_names_values]
1529
1530
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001531def _get_project_hooks(project, presubmit):
Ryan Cui9b651632011-05-11 11:38:58 -07001532 """Returns a list of hooks that need to be run for a project.
1533
1534 Expects to be called from within the project root.
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001535
1536 Args:
1537 project: A string, name of the project.
1538 presubmit: A Boolean, True if the check is run as a git pre-submit script.
Ryan Cui9b651632011-05-11 11:38:58 -07001539 """
Jon Salz3ee59de2012-08-18 13:54:22 +08001540 config = ConfigParser.RawConfigParser()
1541 try:
1542 config.read(_CONFIG_FILE)
1543 except ConfigParser.Error:
1544 # Just use an empty config file
1545 config = ConfigParser.RawConfigParser()
1546
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001547 if presubmit:
Filipe Brandenburgerf70d32c2015-10-09 13:35:45 -07001548 hooks = _COMMON_HOOKS
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001549 else:
Filipe Brandenburgerf70d32c2015-10-09 13:35:45 -07001550 hooks = _PATCH_DESCRIPTION_HOOKS + _COMMON_HOOKS
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001551
Mike Frysinger3554bc92015-03-11 04:59:21 -04001552 enabled_hooks, disabled_hooks = _get_override_hooks(config)
Filipe Brandenburgerf70d32c2015-10-09 13:35:45 -07001553 hooks = [hook for hook in hooks if hook not in disabled_hooks]
1554
1555 # If a list is both in _COMMON_HOOKS and also enabled explicitly through an
1556 # override, keep the override only. Note that the override may end up being
1557 # a functools.partial, in which case we need to extract the .func to compare
1558 # it to the common hooks.
1559 unwrapped_hooks = [getattr(hook, 'func', hook) for hook in enabled_hooks]
1560 hooks = [hook for hook in hooks if hook not in unwrapped_hooks]
1561
1562 hooks = list(enabled_hooks) + hooks
Ryan Cui9b651632011-05-11 11:38:58 -07001563
1564 if project in _PROJECT_SPECIFIC_HOOKS:
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001565 hooks.extend(hook for hook in _PROJECT_SPECIFIC_HOOKS[project]
1566 if hook not in disabled_hooks)
Ryan Cui9b651632011-05-11 11:38:58 -07001567
Jon Salz3ee59de2012-08-18 13:54:22 +08001568 for script in _get_project_hook_scripts(config):
1569 hooks.append(functools.partial(_run_project_hook_script, script))
1570
Ryan Cui9b651632011-05-11 11:38:58 -07001571 return hooks
1572
1573
Alex Deymo643ac4c2015-09-03 10:40:50 -07001574def _run_project_hooks(project_name, proj_dir=None,
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001575 commit_list=None, presubmit=False):
Ryan Cui1562fb82011-05-09 11:01:31 -07001576 """For each project run its project specific hook from the hooks dictionary.
1577
1578 Args:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001579 project_name: The name of project to run hooks for.
Doug Anderson44a644f2011-11-02 10:37:37 -07001580 proj_dir: If non-None, this is the directory the project is in. If None,
1581 we'll ask repo.
Doug Anderson14749562013-06-26 13:38:29 -07001582 commit_list: A list of commits to run hooks against. If None or empty list
1583 then we'll automatically get the list of commits that would be uploaded.
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001584 presubmit: A Boolean, True if the check is run as a git pre-submit script.
Ryan Cui1562fb82011-05-09 11:01:31 -07001585
1586 Returns:
1587 Boolean value of whether any errors were ecountered while running the hooks.
1588 """
Doug Anderson44a644f2011-11-02 10:37:37 -07001589 if proj_dir is None:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001590 proj_dirs = _run_command(
1591 ['repo', 'forall', project_name, '-c', 'pwd']).split()
David James2edd9002013-10-11 14:09:19 -07001592 if len(proj_dirs) == 0:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001593 print('%s cannot be found.' % project_name, file=sys.stderr)
David James2edd9002013-10-11 14:09:19 -07001594 print('Please specify a valid project.', file=sys.stderr)
1595 return True
1596 if len(proj_dirs) > 1:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001597 print('%s is associated with multiple directories.' % project_name,
David James2edd9002013-10-11 14:09:19 -07001598 file=sys.stderr)
1599 print('Please specify a directory to help disambiguate.', file=sys.stderr)
1600 return True
1601 proj_dir = proj_dirs[0]
Doug Anderson44a644f2011-11-02 10:37:37 -07001602
Ryan Cuiec4d6332011-05-02 14:15:25 -07001603 pwd = os.getcwd()
1604 # hooks assume they are run from the root of the project
1605 os.chdir(proj_dir)
1606
Alex Deymo643ac4c2015-09-03 10:40:50 -07001607 remote_branch = _run_command(['git', 'rev-parse', '--abbrev-ref',
1608 '--symbolic-full-name', '@{u}']).strip()
1609 if not remote_branch:
1610 print('Your project %s doesn\'t track any remote repo.' % project_name,
1611 file=sys.stderr)
1612 remote = None
1613 else:
1614 remote, _branch = remote_branch.split('/', 1)
1615
1616 project = Project(name=project_name, dir=proj_dir, remote=remote)
1617
Doug Anderson14749562013-06-26 13:38:29 -07001618 if not commit_list:
1619 try:
1620 commit_list = _get_commits()
1621 except VerifyException as e:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001622 PrintErrorForProject(project.name, HookFailure(str(e)))
Doug Anderson14749562013-06-26 13:38:29 -07001623 os.chdir(pwd)
1624 return True
Ryan Cuifa55df52011-05-06 11:16:55 -07001625
Alex Deymo643ac4c2015-09-03 10:40:50 -07001626 hooks = _get_project_hooks(project.name, presubmit)
Ryan Cui1562fb82011-05-09 11:01:31 -07001627 error_found = False
Ryan Cuifa55df52011-05-06 11:16:55 -07001628 for commit in commit_list:
Ryan Cui1562fb82011-05-09 11:01:31 -07001629 error_list = []
Ryan Cui9b651632011-05-11 11:38:58 -07001630 for hook in hooks:
Ryan Cui1562fb82011-05-09 11:01:31 -07001631 hook_error = hook(project, commit)
1632 if hook_error:
1633 error_list.append(hook_error)
1634 error_found = True
1635 if error_list:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001636 PrintErrorsForCommit(project.name, commit, _get_commit_desc(commit),
Ryan Cui1562fb82011-05-09 11:01:31 -07001637 error_list)
Don Garrettdba548a2011-05-05 15:17:14 -07001638
Ryan Cuiec4d6332011-05-02 14:15:25 -07001639 os.chdir(pwd)
Ryan Cui1562fb82011-05-09 11:01:31 -07001640 return error_found
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001641
Mike Frysingerae409522014-02-01 03:16:11 -05001642
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001643# Main
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -07001644
Ryan Cui1562fb82011-05-09 11:01:31 -07001645
Mike Frysingerae409522014-02-01 03:16:11 -05001646def main(project_list, worktree_list=None, **_kwargs):
Doug Anderson06456632012-01-05 11:02:14 -08001647 """Main function invoked directly by repo.
1648
1649 This function will exit directly upon error so that repo doesn't print some
1650 obscure error message.
1651
1652 Args:
1653 project_list: List of projects to run on.
David James2edd9002013-10-11 14:09:19 -07001654 worktree_list: A list of directories. It should be the same length as
1655 project_list, so that each entry in project_list matches with a directory
1656 in worktree_list. If None, we will attempt to calculate the directories
1657 automatically.
Doug Anderson06456632012-01-05 11:02:14 -08001658 kwargs: Leave this here for forward-compatibility.
1659 """
Ryan Cui1562fb82011-05-09 11:01:31 -07001660 found_error = False
David James2edd9002013-10-11 14:09:19 -07001661 if not worktree_list:
1662 worktree_list = [None] * len(project_list)
1663 for project, worktree in zip(project_list, worktree_list):
1664 if _run_project_hooks(project, proj_dir=worktree):
Ryan Cui1562fb82011-05-09 11:01:31 -07001665 found_error = True
1666
Mike Frysingerae409522014-02-01 03:16:11 -05001667 if found_error:
Ryan Cui1562fb82011-05-09 11:01:31 -07001668 msg = ('Preupload failed due to errors in project(s). HINTS:\n'
Ryan Cui9b651632011-05-11 11:38:58 -07001669 '- To disable some source style checks, and for other hints, see '
1670 '<checkout_dir>/src/repohooks/README\n'
1671 '- To upload only current project, run \'repo upload .\'')
Mike Frysinger09d6a3d2013-10-08 22:21:03 -04001672 print(msg, file=sys.stderr)
Don Garrettdba548a2011-05-05 15:17:14 -07001673 sys.exit(1)
Anush Elangovan63afad72011-03-23 00:41:27 -07001674
Ryan Cui1562fb82011-05-09 11:01:31 -07001675
Doug Anderson44a644f2011-11-02 10:37:37 -07001676def _identify_project(path):
1677 """Identify the repo project associated with the given path.
1678
1679 Returns:
1680 A string indicating what project is associated with the path passed in or
1681 a blank string upon failure.
1682 """
1683 return _run_command(['repo', 'forall', '.', '-c', 'echo ${REPO_PROJECT}'],
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001684 redirect_stderr=True, cwd=path).strip()
Doug Anderson44a644f2011-11-02 10:37:37 -07001685
1686
Mike Frysinger55f85b52014-12-18 14:45:21 -05001687def direct_main(argv):
Doug Anderson44a644f2011-11-02 10:37:37 -07001688 """Run hooks directly (outside of the context of repo).
1689
Doug Anderson44a644f2011-11-02 10:37:37 -07001690 Args:
Mike Frysinger55f85b52014-12-18 14:45:21 -05001691 argv: The command line args to process
Doug Anderson44a644f2011-11-02 10:37:37 -07001692
1693 Returns:
1694 0 if no pre-upload failures, 1 if failures.
1695
1696 Raises:
1697 BadInvocation: On some types of invocation errors.
1698 """
Mike Frysinger66142932014-12-18 14:55:57 -05001699 parser = commandline.ArgumentParser(description=__doc__)
1700 parser.add_argument('--dir', default=None,
1701 help='The directory that the project lives in. If not '
1702 'specified, use the git project root based on the cwd.')
1703 parser.add_argument('--project', default=None,
1704 help='The project repo path; this can affect how the '
1705 'hooks get run, since some hooks are project-specific. '
1706 'For chromite this is chromiumos/chromite. If not '
1707 'specified, the repo tool will be used to figure this '
1708 'out based on the dir.')
1709 parser.add_argument('--rerun-since', default=None,
1710 help='Rerun hooks on old commits since the given date. '
1711 'The date should match git log\'s concept of a date. '
1712 'e.g. 2012-06-20. This option is mutually exclusive '
1713 'with --pre-submit.')
1714 parser.add_argument('--pre-submit', action="store_true",
1715 help='Run the check against the pending commit. '
1716 'This option should be used at the \'git commit\' '
1717 'phase as opposed to \'repo upload\'. This option '
1718 'is mutually exclusive with --rerun-since.')
1719 parser.add_argument('commits', nargs='*',
1720 help='Check specific commits')
1721 opts = parser.parse_args(argv)
Doug Anderson44a644f2011-11-02 10:37:37 -07001722
Doug Anderson14749562013-06-26 13:38:29 -07001723 if opts.rerun_since:
Mike Frysinger66142932014-12-18 14:55:57 -05001724 if opts.commits:
Doug Anderson14749562013-06-26 13:38:29 -07001725 raise BadInvocation('Can\'t pass commits and use rerun-since: %s' %
Mike Frysinger66142932014-12-18 14:55:57 -05001726 ' '.join(opts.commits))
Doug Anderson14749562013-06-26 13:38:29 -07001727
1728 cmd = ['git', 'log', '--since="%s"' % opts.rerun_since, '--pretty=%H']
1729 all_commits = _run_command(cmd).splitlines()
1730 bot_commits = _run_command(cmd + ['--author=chrome-bot']).splitlines()
1731
1732 # Eliminate chrome-bot commits but keep ordering the same...
1733 bot_commits = set(bot_commits)
Mike Frysinger66142932014-12-18 14:55:57 -05001734 opts.commits = [c for c in all_commits if c not in bot_commits]
Doug Anderson14749562013-06-26 13:38:29 -07001735
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001736 if opts.pre_submit:
1737 raise BadInvocation('rerun-since and pre-submit can not be '
1738 'used together')
1739 if opts.pre_submit:
Mike Frysinger66142932014-12-18 14:55:57 -05001740 if opts.commits:
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001741 raise BadInvocation('Can\'t pass commits and use pre-submit: %s' %
Mike Frysinger66142932014-12-18 14:55:57 -05001742 ' '.join(opts.commits))
1743 opts.commits = [PRE_SUBMIT,]
Doug Anderson44a644f2011-11-02 10:37:37 -07001744
1745 # Check/normlaize git dir; if unspecified, we'll use the root of the git
1746 # project from CWD
1747 if opts.dir is None:
1748 git_dir = _run_command(['git', 'rev-parse', '--git-dir'],
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001749 redirect_stderr=True).strip()
Doug Anderson44a644f2011-11-02 10:37:37 -07001750 if not git_dir:
1751 raise BadInvocation('The current directory is not part of a git project.')
1752 opts.dir = os.path.dirname(os.path.abspath(git_dir))
1753 elif not os.path.isdir(opts.dir):
1754 raise BadInvocation('Invalid dir: %s' % opts.dir)
1755 elif not os.path.isdir(os.path.join(opts.dir, '.git')):
1756 raise BadInvocation('Not a git directory: %s' % opts.dir)
1757
1758 # Identify the project if it wasn't specified; this _requires_ the repo
1759 # tool to be installed and for the project to be part of a repo checkout.
1760 if not opts.project:
1761 opts.project = _identify_project(opts.dir)
1762 if not opts.project:
1763 raise BadInvocation("Repo couldn't identify the project of %s" % opts.dir)
1764
Doug Anderson14749562013-06-26 13:38:29 -07001765 found_error = _run_project_hooks(opts.project, proj_dir=opts.dir,
Mike Frysinger66142932014-12-18 14:55:57 -05001766 commit_list=opts.commits,
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001767 presubmit=opts.pre_submit)
Doug Anderson44a644f2011-11-02 10:37:37 -07001768 if found_error:
1769 return 1
1770 return 0
1771
1772
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -07001773if __name__ == '__main__':
Mike Frysinger55f85b52014-12-18 14:45:21 -05001774 sys.exit(direct_main(sys.argv[1:]))