blob: 43789d996cad468f44417f0e6470aeee6bb9abd4 [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
C Shapiro8f90e9b2017-06-28 09:54:50 -060077 # Ignore config files in ebuild setup.
78 r"(^|.*/)overlay-.*/chromeos-base/chromeos-bsp.*/files/.*",
79 r"^chromeos-base/chromeos-bsp.*/files/.*",
80
Daniel Erate3ea3fc2015-02-13 15:27:52 -070081 # Ignore minified js and jquery.
Mike Frysingerae409522014-02-01 03:16:11 -050082 r".*\.min\.js",
83 r".*jquery.*\.js",
Mike Frysinger33a458d2014-03-03 17:00:51 -050084
85 # Ignore license files as the content is often taken verbatim.
Daniel Erate3ea3fc2015-02-13 15:27:52 -070086 r".*/licenses/.*",
Ryan Cuiec4d6332011-05-02 14:15:25 -070087]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070088
Ryan Cui1562fb82011-05-09 11:01:31 -070089
Ryan Cui9b651632011-05-11 11:38:58 -070090_CONFIG_FILE = 'PRESUBMIT.cfg'
91
92
Daniel Erate3ea3fc2015-02-13 15:27:52 -070093# File containing wildcards, one per line, matching files that should be
94# excluded from presubmit checks. Lines beginning with '#' are ignored.
95_IGNORE_FILE = '.presubmitignore'
96
97
Doug Anderson44a644f2011-11-02 10:37:37 -070098# Exceptions
99
100
101class BadInvocation(Exception):
102 """An Exception indicating a bad invocation of the program."""
103 pass
104
105
Ryan Cui1562fb82011-05-09 11:01:31 -0700106# General Helpers
107
Sean Paulba01d402011-05-05 11:36:23 -0400108
Alex Deymo643ac4c2015-09-03 10:40:50 -0700109Project = collections.namedtuple('Project', ['name', 'dir', 'remote'])
110
111
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700112# pylint: disable=redefined-builtin
113def _run_command(cmd, cwd=None, input=None,
114 redirect_stderr=False, combine_stdout_stderr=False):
Doug Anderson44a644f2011-11-02 10:37:37 -0700115 """Executes the passed in command and returns raw stdout output.
116
117 Args:
118 cmd: The command to run; should be a list of strings.
119 cwd: The directory to switch to for running the command.
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700120 input: The data to pipe into this command through stdin. If a file object
121 or file descriptor, stdin will be connected directly to that.
122 redirect_stderr: Redirect stderr away from console.
123 combine_stdout_stderr: Combines stdout and stderr streams into stdout.
Doug Anderson44a644f2011-11-02 10:37:37 -0700124
125 Returns:
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700126 The stdout from the process (discards stderr and returncode).
Doug Anderson44a644f2011-11-02 10:37:37 -0700127 """
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700128 return cros_build_lib.RunCommand(cmd=cmd,
129 cwd=cwd,
130 print_cmd=False,
131 input=input,
132 stdout_to_pipe=True,
133 redirect_stderr=redirect_stderr,
134 combine_stdout_stderr=combine_stdout_stderr,
135 error_code_ok=True).output
136# pylint: enable=redefined-builtin
Ryan Cui72834d12011-05-05 14:51:33 -0700137
Ryan Cui1562fb82011-05-09 11:01:31 -0700138
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700139def _get_hooks_dir():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700140 """Returns the absolute path to the repohooks directory."""
Doug Anderson44a644f2011-11-02 10:37:37 -0700141 if __name__ == '__main__':
142 # Works when file is run on its own (__file__ is defined)...
143 return os.path.abspath(os.path.dirname(__file__))
144 else:
145 # We need to do this when we're run through repo. Since repo executes
146 # us with execfile(), we don't get __file__ defined.
147 cmd = ['repo', 'forall', 'chromiumos/repohooks', '-c', 'pwd']
148 return _run_command(cmd).strip()
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700149
Ryan Cui1562fb82011-05-09 11:01:31 -0700150
Ryan Cuiec4d6332011-05-02 14:15:25 -0700151def _match_regex_list(subject, expressions):
152 """Try to match a list of regular expressions to a string.
153
154 Args:
155 subject: The string to match regexes on
156 expressions: A list of regular expressions to check for matches with.
157
158 Returns:
159 Whether the passed in subject matches any of the passed in regexes.
160 """
161 for expr in expressions:
Mike Frysingerae409522014-02-01 03:16:11 -0500162 if re.search(expr, subject):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700163 return True
164 return False
165
Ryan Cui1562fb82011-05-09 11:01:31 -0700166
Mike Frysingerae409522014-02-01 03:16:11 -0500167def _filter_files(files, include_list, exclude_list=()):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700168 """Filter out files based on the conditions passed in.
169
170 Args:
171 files: list of filepaths to filter
172 include_list: list of regex that when matched with a file path will cause it
173 to be added to the output list unless the file is also matched with a
174 regex in the exclude_list.
175 exclude_list: list of regex that when matched with a file will prevent it
176 from being added to the output list, even if it is also matched with a
177 regex in the include_list.
178
179 Returns:
180 A list of filepaths that contain files matched in the include_list and not
181 in the exclude_list.
182 """
183 filtered = []
184 for f in files:
185 if (_match_regex_list(f, include_list) and
186 not _match_regex_list(f, exclude_list)):
187 filtered.append(f)
188 return filtered
189
Ryan Cuiec4d6332011-05-02 14:15:25 -0700190
191# Git Helpers
Ryan Cui1562fb82011-05-09 11:01:31 -0700192
193
Ryan Cui4725d952011-05-05 15:41:19 -0700194def _get_upstream_branch():
195 """Returns the upstream tracking branch of the current branch.
196
197 Raises:
198 Error if there is no tracking branch
199 """
200 current_branch = _run_command(['git', 'symbolic-ref', 'HEAD']).strip()
201 current_branch = current_branch.replace('refs/heads/', '')
202 if not current_branch:
Ryan Cui1562fb82011-05-09 11:01:31 -0700203 raise VerifyException('Need to be on a tracking branch')
Ryan Cui4725d952011-05-05 15:41:19 -0700204
205 cfg_option = 'branch.' + current_branch + '.%s'
206 full_upstream = _run_command(['git', 'config', cfg_option % 'merge']).strip()
207 remote = _run_command(['git', 'config', cfg_option % 'remote']).strip()
208 if not remote or not full_upstream:
Ryan Cui1562fb82011-05-09 11:01:31 -0700209 raise VerifyException('Need to be on a tracking branch')
Ryan Cui4725d952011-05-05 15:41:19 -0700210
211 return full_upstream.replace('heads', 'remotes/' + remote)
212
Ryan Cui1562fb82011-05-09 11:01:31 -0700213
Che-Liang Chiou5ce2d7b2013-03-22 18:47:55 -0700214def _get_patch(commit):
215 """Returns the patch for this commit."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700216 if commit == PRE_SUBMIT:
217 return _run_command(['git', 'diff', '--cached', 'HEAD'])
218 else:
219 return _run_command(['git', 'format-patch', '--stdout', '-1', commit])
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700220
Ryan Cui1562fb82011-05-09 11:01:31 -0700221
Jon Salz98255932012-08-18 14:48:02 +0800222def _try_utf8_decode(data):
223 """Attempts to decode a string as UTF-8.
224
225 Returns:
226 The decoded Unicode object, or the original string if parsing fails.
227 """
228 try:
229 return unicode(data, 'utf-8', 'strict')
230 except UnicodeDecodeError:
231 return data
232
233
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500234def _get_file_content(path, commit):
235 """Returns the content of a file at a specific commit.
236
237 We can't rely on the file as it exists in the filesystem as people might be
238 uploading a series of changes which modifies the file multiple times.
239
240 Note: The "content" of a symlink is just the target. So if you're expecting
241 a full file, you should check that first. One way to detect is that the
242 content will not have any newlines.
243 """
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700244 if commit == PRE_SUBMIT:
245 return _run_command(['git', 'diff', 'HEAD', path])
246 else:
247 return _run_command(['git', 'show', '%s:%s' % (commit, path)])
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500248
249
Mike Frysingerae409522014-02-01 03:16:11 -0500250def _get_file_diff(path, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700251 """Returns a list of (linenum, lines) tuples that the commit touched."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700252 if commit == PRE_SUBMIT:
Prathmesh Prabhua9de1722016-12-22 14:56:40 -0800253 command = ['git', 'diff', '-p', '--pretty=format:', '--no-ext-diff', 'HEAD',
254 path]
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700255 else:
Prathmesh Prabhua9de1722016-12-22 14:56:40 -0800256 command = ['git', 'show', '-p', '--pretty=format:', '--no-ext-diff', commit,
257 path]
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700258 output = _run_command(command)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700259
260 new_lines = []
261 line_num = 0
262 for line in output.splitlines():
263 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
264 if m:
265 line_num = int(m.groups(1)[0])
266 continue
267 if line.startswith('+') and not line.startswith('++'):
Jon Salz98255932012-08-18 14:48:02 +0800268 new_lines.append((line_num, _try_utf8_decode(line[1:])))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700269 if not line.startswith('-'):
270 line_num += 1
271 return new_lines
272
Ryan Cui1562fb82011-05-09 11:01:31 -0700273
Daniel Erate3ea3fc2015-02-13 15:27:52 -0700274def _get_ignore_wildcards(directory, cache):
275 """Get wildcards listed in a directory's _IGNORE_FILE.
276
277 Args:
278 directory: A string containing a directory path.
279 cache: A dictionary (opaque to caller) caching previously-read wildcards.
280
281 Returns:
282 A list of wildcards from _IGNORE_FILE or an empty list if _IGNORE_FILE
283 wasn't present.
284 """
285 # In the cache, keys are directories and values are lists of wildcards from
286 # _IGNORE_FILE within those directories (and empty if no file was present).
287 if directory not in cache:
288 wildcards = []
289 dotfile_path = os.path.join(directory, _IGNORE_FILE)
290 if os.path.exists(dotfile_path):
291 # TODO(derat): Consider using _get_file_content() to get the file as of
292 # this commit instead of the on-disk version. This may have a noticeable
293 # performance impact, as each call to _get_file_content() runs git.
294 with open(dotfile_path, 'r') as dotfile:
295 for line in dotfile.readlines():
296 line = line.strip()
297 if line.startswith('#'):
298 continue
299 if line.endswith('/'):
300 line += '*'
301 wildcards.append(line)
302 cache[directory] = wildcards
303
304 return cache[directory]
305
306
307def _path_is_ignored(path, cache):
308 """Check whether a path is ignored by _IGNORE_FILE.
309
310 Args:
311 path: A string containing a path.
312 cache: A dictionary (opaque to caller) caching previously-read wildcards.
313
314 Returns:
315 True if a file named _IGNORE_FILE in one of the passed-in path's parent
316 directories contains a wildcard matching the path.
317 """
318 # Skip ignore files.
319 if os.path.basename(path) == _IGNORE_FILE:
320 return True
321
322 path = os.path.abspath(path)
323 base = os.getcwd()
324
325 prefix = os.path.dirname(path)
326 while prefix.startswith(base):
327 rel_path = path[len(prefix) + 1:]
328 for wildcard in _get_ignore_wildcards(prefix, cache):
329 if fnmatch.fnmatch(rel_path, wildcard):
330 return True
331 prefix = os.path.dirname(prefix)
332
333 return False
334
335
Mike Frysinger292b45d2014-11-25 01:17:10 -0500336def _get_affected_files(commit, include_deletes=False, relative=False,
337 include_symlinks=False, include_adds=True,
Daniel Erate3ea3fc2015-02-13 15:27:52 -0700338 full_details=False, use_ignore_files=True):
Peter Ammon811f6702014-06-12 15:45:38 -0700339 """Returns list of file paths that were modified/added, excluding symlinks.
340
341 Args:
342 commit: The commit
343 include_deletes: If true, we'll include deleted files in the result
344 relative: Whether to return relative or full paths to files
Mike Frysinger292b45d2014-11-25 01:17:10 -0500345 include_symlinks: If true, we'll include symlinks in the result
346 include_adds: If true, we'll include new files in the result
347 full_details: If False, return filenames, else return structured results.
Daniel Erate3ea3fc2015-02-13 15:27:52 -0700348 use_ignore_files: Whether we ignore files matched by _IGNORE_FILE files.
Peter Ammon811f6702014-06-12 15:45:38 -0700349
350 Returns:
351 A list of modified/added (and perhaps deleted) files
352 """
Mike Frysinger292b45d2014-11-25 01:17:10 -0500353 if not relative and full_details:
354 raise ValueError('full_details only supports relative paths currently')
355
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700356 if commit == PRE_SUBMIT:
357 return _run_command(['git', 'diff-index', '--cached',
358 '--name-only', 'HEAD']).split()
Mike Frysingerd3bd32c2014-11-24 23:34:29 -0500359
360 path = os.getcwd()
361 files = git.RawDiff(path, '%s^!' % commit)
362
363 # Filter out symlinks.
Mike Frysinger292b45d2014-11-25 01:17:10 -0500364 if not include_symlinks:
365 files = [x for x in files if not stat.S_ISLNK(int(x.dst_mode, 8))]
Mike Frysingerd3bd32c2014-11-24 23:34:29 -0500366
367 if not include_deletes:
368 files = [x for x in files if x.status != 'D']
369
Mike Frysinger292b45d2014-11-25 01:17:10 -0500370 if not include_adds:
371 files = [x for x in files if x.status != 'A']
372
Daniel Erate3ea3fc2015-02-13 15:27:52 -0700373 if use_ignore_files:
374 cache = {}
375 is_ignored = lambda x: _path_is_ignored(x.dst_file or x.src_file, cache)
376 files = [x for x in files if not is_ignored(x)]
377
Mike Frysinger292b45d2014-11-25 01:17:10 -0500378 if full_details:
379 # Caller wants the raw objects to parse status/etc... themselves.
Mike Frysingerd3bd32c2014-11-24 23:34:29 -0500380 return files
381 else:
Mike Frysinger292b45d2014-11-25 01:17:10 -0500382 # Caller only cares about filenames.
383 files = [x.dst_file if x.dst_file else x.src_file for x in files]
384 if relative:
385 return files
386 else:
387 return [os.path.join(path, x) for x in files]
Peter Ammon811f6702014-06-12 15:45:38 -0700388
389
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700390def _get_commits():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700391 """Returns a list of commits for this review."""
Ryan Cui4725d952011-05-05 15:41:19 -0700392 cmd = ['git', 'log', '%s..' % _get_upstream_branch(), '--format=%H']
Ryan Cui72834d12011-05-05 14:51:33 -0700393 return _run_command(cmd).split()
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700394
Ryan Cui1562fb82011-05-09 11:01:31 -0700395
Ryan Cuiec4d6332011-05-02 14:15:25 -0700396def _get_commit_desc(commit):
397 """Returns the full commit message of a commit."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700398 if commit == PRE_SUBMIT:
399 return ''
Sean Paul23a2c582011-05-06 13:10:44 -0400400 return _run_command(['git', 'log', '--format=%s%n%n%b', commit + '^!'])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700401
402
Prathmesh Prabhuc5254652016-12-22 12:58:05 -0800403def _check_lines_in_diff(commit, files, check_callable, error_description):
404 """Checks given file for errors via the given check.
405
406 This is a convenience function for common per-line checks. It goes through all
407 files and returns a HookFailure with the error description listing all the
408 failures.
409
410 Args:
411 commit: The commit we're working on.
412 files: The files to check.
413 check_callable: A callable that takes a line and returns True if this line
414 _fails_ the check.
415 error_description: A string describing the error.
416 """
417 errors = []
418 for afile in files:
419 for line_num, line in _get_file_diff(afile, commit):
420 if check_callable(line):
421 errors.append('%s, line %s' % (afile, line_num))
422 if errors:
423 return HookFailure(error_description, errors)
424
425
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900426def _parse_common_inclusion_options(options):
427 """Parses common hook options for including/excluding files.
428
429 Args:
430 options: Option string list.
431
432 Returns:
433 (included, excluded) where each one is a list of regex strings.
434 """
435 parser = argparse.ArgumentParser()
436 parser.add_argument('--exclude_regex', action='append')
437 parser.add_argument('--include_regex', action='append')
438 opts = parser.parse_args(options)
439 included = opts.include_regex or []
440 excluded = opts.exclude_regex or []
441 return included, excluded
442
443
Ryan Cuiec4d6332011-05-02 14:15:25 -0700444# Common Hooks
445
Ryan Cui1562fb82011-05-09 11:01:31 -0700446
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900447def _check_no_long_lines(_project, commit, options=()):
Mike Frysinger55f85b52014-12-18 14:45:21 -0500448 """Checks there are no lines longer than MAX_LEN in any of the text files."""
449
Ryan Cuiec4d6332011-05-02 14:15:25 -0700450 MAX_LEN = 80
Jon Salz98255932012-08-18 14:48:02 +0800451 SKIP_REGEXP = re.compile('|'.join([
452 r'https?://',
453 r'^#\s*(define|include|import|pragma|if|endif)\b']))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700454
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900455 included, excluded = _parse_common_inclusion_options(options)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700456 files = _filter_files(_get_affected_files(commit),
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900457 included + COMMON_INCLUDED_PATHS,
458 excluded + COMMON_EXCLUDED_PATHS)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700459
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900460 errors = []
Ryan Cuiec4d6332011-05-02 14:15:25 -0700461 for afile in files:
462 for line_num, line in _get_file_diff(afile, commit):
463 # Allow certain lines to exceed the maxlen rule.
Mike Frysingerae409522014-02-01 03:16:11 -0500464 if len(line) <= MAX_LEN or SKIP_REGEXP.search(line):
Jon Salz98255932012-08-18 14:48:02 +0800465 continue
466
467 errors.append('%s, line %s, %s chars' % (afile, line_num, len(line)))
468 if len(errors) == 5: # Just show the first 5 errors.
469 break
Ryan Cuiec4d6332011-05-02 14:15:25 -0700470
471 if errors:
472 msg = 'Found lines longer than %s characters (first 5 shown):' % MAX_LEN
Ryan Cui1562fb82011-05-09 11:01:31 -0700473 return HookFailure(msg, errors)
474
Ryan Cuiec4d6332011-05-02 14:15:25 -0700475
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900476def _check_no_stray_whitespace(_project, commit, options=()):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700477 """Checks that there is no stray whitespace at source lines end."""
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900478 included, excluded = _parse_common_inclusion_options(options)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700479 files = _filter_files(_get_affected_files(commit),
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900480 included + COMMON_INCLUDED_PATHS,
481 excluded + COMMON_EXCLUDED_PATHS)
Prathmesh Prabhuc5254652016-12-22 12:58:05 -0800482 return _check_lines_in_diff(commit, files,
483 lambda line: line.rstrip() != line,
484 'Found line ending with white space in:')
Ryan Cui1562fb82011-05-09 11:01:31 -0700485
Ryan Cuiec4d6332011-05-02 14:15:25 -0700486
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900487def _check_no_tabs(_project, commit, options=()):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700488 """Checks there are no unexpanded tabs."""
489 TAB_OK_PATHS = [
Ryan Cui31e0c172011-05-04 21:00:45 -0700490 r"/src/third_party/u-boot/",
Ryan Cuiec4d6332011-05-02 14:15:25 -0700491 r".*\.ebuild$",
492 r".*\.eclass$",
Elly Jones5ab34192011-11-15 14:57:06 -0500493 r".*/[M|m]akefile$",
494 r".*\.mk$"
Ryan Cuiec4d6332011-05-02 14:15:25 -0700495 ]
496
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900497 included, excluded = _parse_common_inclusion_options(options)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700498 files = _filter_files(_get_affected_files(commit),
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900499 included + COMMON_INCLUDED_PATHS,
500 excluded + COMMON_EXCLUDED_PATHS + TAB_OK_PATHS)
Prathmesh Prabhuc5254652016-12-22 12:58:05 -0800501 return _check_lines_in_diff(commit, files,
502 lambda line: '\t' in line,
503 'Found a tab character in:')
Ryan Cuiec4d6332011-05-02 14:15:25 -0700504
Prathmesh Prabhuc5254652016-12-22 12:58:05 -0800505
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900506def _check_tabbed_indents(_project, commit, options=()):
Prathmesh Prabhuc5254652016-12-22 12:58:05 -0800507 """Checks that indents use tabs only."""
508 TABS_REQUIRED_PATHS = [
509 r".*\.ebuild$",
510 r".*\.eclass$",
511 ]
512 LEADING_SPACE_RE = re.compile('[\t]* ')
513
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900514 included, excluded = _parse_common_inclusion_options(options)
Prathmesh Prabhuc5254652016-12-22 12:58:05 -0800515 files = _filter_files(_get_affected_files(commit),
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900516 included + TABS_REQUIRED_PATHS,
517 excluded + COMMON_EXCLUDED_PATHS)
Prathmesh Prabhuc5254652016-12-22 12:58:05 -0800518 return _check_lines_in_diff(
519 commit, files,
520 lambda line: LEADING_SPACE_RE.match(line) is not None,
521 'Found a space in indentation (must be all tabs):')
Ryan Cui1562fb82011-05-09 11:01:31 -0700522
Ryan Cuiec4d6332011-05-02 14:15:25 -0700523
Rahul Chaudhry09f61372015-07-31 17:14:26 -0700524def _check_gofmt(_project, commit):
525 """Checks that Go files are formatted with gofmt."""
526 errors = []
527 files = _filter_files(_get_affected_files(commit, relative=True),
528 [r'\.go$'])
529
530 for gofile in files:
531 contents = _get_file_content(gofile, commit)
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700532 output = _run_command(cmd=['gofmt', '-l'], input=contents,
533 combine_stdout_stderr=True)
Rahul Chaudhry09f61372015-07-31 17:14:26 -0700534 if output:
535 errors.append(gofile)
536 if errors:
537 return HookFailure('Files not formatted with gofmt:', errors)
538
539
Mike Frysingerae409522014-02-01 03:16:11 -0500540def _check_change_has_test_field(_project, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700541 """Check for a non-empty 'TEST=' field in the commit message."""
David McMahon8f6553e2011-06-10 15:46:36 -0700542 TEST_RE = r'\nTEST=\S+'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700543
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700544 if not re.search(TEST_RE, _get_commit_desc(commit)):
Ryan Cui1562fb82011-05-09 11:01:31 -0700545 msg = 'Changelist description needs TEST field (after first line)'
546 return HookFailure(msg)
547
Ryan Cuiec4d6332011-05-02 14:15:25 -0700548
Mike Frysingerae409522014-02-01 03:16:11 -0500549def _check_change_has_valid_cq_depend(_project, commit):
David Jamesc3b68b32013-04-03 09:17:03 -0700550 """Check for a correctly formatted CQ-DEPEND field in the commit message."""
551 msg = 'Changelist has invalid CQ-DEPEND target.'
552 example = 'Example: CQ-DEPEND=CL:1234, CL:2345'
553 try:
554 patch.GetPaladinDeps(_get_commit_desc(commit))
555 except ValueError as ex:
556 return HookFailure(msg, [example, str(ex)])
557
558
Bernie Thompsonf8fea992016-01-14 10:27:18 -0800559def _check_change_is_contribution(_project, commit):
560 """Check that the change is a contribution."""
561 NO_CONTRIB = 'not a contribution'
562 if NO_CONTRIB in _get_commit_desc(commit).lower():
563 msg = ('Changelist is not a contribution, this cannot be accepted.\n'
564 'Please remove the "%s" text from the commit message.') % NO_CONTRIB
565 return HookFailure(msg)
566
567
Alex Deymo643ac4c2015-09-03 10:40:50 -0700568def _check_change_has_bug_field(project, commit):
David McMahon8f6553e2011-06-10 15:46:36 -0700569 """Check for a correctly formatted 'BUG=' field in the commit message."""
David James5c0073d2013-04-03 08:48:52 -0700570 OLD_BUG_RE = r'\nBUG=.*chromium-os'
571 if re.search(OLD_BUG_RE, _get_commit_desc(commit)):
572 msg = ('The chromium-os bug tracker is now deprecated. Please use\n'
573 'the chromium tracker in your BUG= line now.')
574 return HookFailure(msg)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700575
Alex Deymo643ac4c2015-09-03 10:40:50 -0700576 # Android internal and external projects use "Bug: " to track bugs in
577 # buganizer.
578 BUG_COLON_REMOTES = (
579 'aosp',
580 'goog',
581 )
582 if project.remote in BUG_COLON_REMOTES:
583 BUG_RE = r'\nBug: ?([Nn]one|\d+)'
584 if not re.search(BUG_RE, _get_commit_desc(commit)):
585 msg = ('Changelist description needs BUG field (after first line):\n'
586 'Bug: 9999 (for buganizer)\n'
587 'BUG=None')
588 return HookFailure(msg)
589 else:
Jorge Lucangeli Obesdce214e2017-10-25 15:04:39 -0400590 BUG_RE = r'\nBUG=([Nn]one|(chromium|b):\d+)'
Alex Deymo643ac4c2015-09-03 10:40:50 -0700591 if not re.search(BUG_RE, _get_commit_desc(commit)):
592 msg = ('Changelist description needs BUG field (after first line):\n'
Alex Deymo643ac4c2015-09-03 10:40:50 -0700593 'BUG=chromium:9999 (for public tracker)\n'
Alex Deymo643ac4c2015-09-03 10:40:50 -0700594 'BUG=b:9999 (for buganizer)\n'
595 'BUG=None')
596 return HookFailure(msg)
Ryan Cui1562fb82011-05-09 11:01:31 -0700597
Ryan Cuiec4d6332011-05-02 14:15:25 -0700598
Mike Frysinger292b45d2014-11-25 01:17:10 -0500599def _check_for_uprev(project, commit, project_top=None):
Doug Anderson42b8a052013-06-26 10:45:36 -0700600 """Check that we're not missing a revbump of an ebuild in the given commit.
601
602 If the given commit touches files in a directory that has ebuilds somewhere
603 up the directory hierarchy, it's very likely that we need an ebuild revbump
604 in order for those changes to take effect.
605
606 It's not totally trivial to detect a revbump, so at least detect that an
607 ebuild with a revision number in it was touched. This should handle the
608 common case where we use a symlink to do the revbump.
609
610 TODO: it would be nice to enhance this hook to:
611 * Handle cases where people revbump with a slightly different syntax. I see
612 one ebuild (puppy) that revbumps with _pN. This is a false positive.
613 * Catches cases where people aren't using symlinks for revbumps. If they
614 edit a revisioned file directly (and are expected to rename it for revbump)
615 we'll miss that. Perhaps we could detect that the file touched is a
616 symlink?
617
618 If a project doesn't use symlinks we'll potentially miss a revbump, but we're
619 still better off than without this check.
620
621 Args:
Alex Deymo643ac4c2015-09-03 10:40:50 -0700622 project: The Project to look at
Doug Anderson42b8a052013-06-26 10:45:36 -0700623 commit: The commit to look at
Mike Frysinger292b45d2014-11-25 01:17:10 -0500624 project_top: Top dir to process commits in
Doug Anderson42b8a052013-06-26 10:45:36 -0700625
626 Returns:
627 A HookFailure or None.
628 """
Mike Frysinger011af942014-01-17 16:12:22 -0500629 # If this is the portage-stable overlay, then ignore the check. It's rare
630 # that we're doing anything other than importing files from upstream, so
631 # forcing a rev bump makes no sense.
632 whitelist = (
633 'chromiumos/overlays/portage-stable',
634 )
Alex Deymo643ac4c2015-09-03 10:40:50 -0700635 if project.name in whitelist:
Mike Frysinger011af942014-01-17 16:12:22 -0500636 return None
637
Mike Frysinger292b45d2014-11-25 01:17:10 -0500638 def FinalName(obj):
639 # If the file is being deleted, then the dst_file is not set.
640 if obj.dst_file is None:
641 return obj.src_file
642 else:
643 return obj.dst_file
644
645 affected_path_objs = _get_affected_files(
646 commit, include_deletes=True, include_symlinks=True, relative=True,
647 full_details=True)
Doug Anderson42b8a052013-06-26 10:45:36 -0700648
649 # Don't yell about changes to whitelisted files...
Aviv Keshet272f2e52016-04-25 14:49:44 -0700650 whitelist = ('ChangeLog', 'Manifest', 'metadata.xml', 'COMMIT-QUEUE.ini')
Mike Frysinger292b45d2014-11-25 01:17:10 -0500651 affected_path_objs = [x for x in affected_path_objs
652 if os.path.basename(FinalName(x)) not in whitelist]
653 if not affected_path_objs:
Doug Anderson42b8a052013-06-26 10:45:36 -0700654 return None
655
656 # If we've touched any file named with a -rN.ebuild then we'll say we're
657 # OK right away. See TODO above about enhancing this.
Mike Frysinger292b45d2014-11-25 01:17:10 -0500658 touched_revved_ebuild = any(re.search(r'-r\d*\.ebuild$', FinalName(x))
659 for x in affected_path_objs)
Doug Anderson42b8a052013-06-26 10:45:36 -0700660 if touched_revved_ebuild:
661 return None
662
Mike Frysinger292b45d2014-11-25 01:17:10 -0500663 # If we're creating new ebuilds from scratch, then we don't need an uprev.
664 # Find all the dirs that new ebuilds and ignore their files/.
665 ebuild_dirs = [os.path.dirname(FinalName(x)) + '/' for x in affected_path_objs
666 if FinalName(x).endswith('.ebuild') and x.status == 'A']
667 affected_path_objs = [obj for obj in affected_path_objs
668 if not any(FinalName(obj).startswith(x)
669 for x in ebuild_dirs)]
670 if not affected_path_objs:
671 return
672
Doug Anderson42b8a052013-06-26 10:45:36 -0700673 # We want to examine the current contents of all directories that are parents
674 # of files that were touched (up to the top of the project).
675 #
676 # ...note: we use the current directory contents even though it may have
677 # changed since the commit we're looking at. This is just a heuristic after
678 # all. Worst case we don't flag a missing revbump.
Mike Frysinger292b45d2014-11-25 01:17:10 -0500679 if project_top is None:
680 project_top = os.getcwd()
Doug Anderson42b8a052013-06-26 10:45:36 -0700681 dirs_to_check = set([project_top])
Mike Frysinger292b45d2014-11-25 01:17:10 -0500682 for obj in affected_path_objs:
683 path = os.path.join(project_top, os.path.dirname(FinalName(obj)))
Doug Anderson42b8a052013-06-26 10:45:36 -0700684 while os.path.exists(path) and not os.path.samefile(path, project_top):
685 dirs_to_check.add(path)
686 path = os.path.dirname(path)
687
688 # Look through each directory. If it's got an ebuild in it then we'll
689 # consider this as a case when we need a revbump.
Gwendal Grignoua3086c32014-12-09 11:17:22 -0800690 affected_paths = set(os.path.join(project_top, FinalName(x))
691 for x in affected_path_objs)
Doug Anderson42b8a052013-06-26 10:45:36 -0700692 for dir_path in dirs_to_check:
693 contents = os.listdir(dir_path)
694 ebuilds = [os.path.join(dir_path, path)
695 for path in contents if path.endswith('.ebuild')]
696 ebuilds_9999 = [path for path in ebuilds if path.endswith('-9999.ebuild')]
697
C Shapiroae157ae2017-09-18 16:24:03 -0600698 affected_paths_under_9999_ebuilds = set()
699 for affected_path in affected_paths:
700 for ebuild_9999 in ebuilds_9999:
701 ebuild_dir = os.path.dirname(ebuild_9999)
702 if affected_path.startswith(ebuild_dir):
703 affected_paths_under_9999_ebuilds.add(affected_path)
704
705 # If every file changed exists under a 9999 ebuild, then skip
706 if len(affected_paths_under_9999_ebuilds) == len(affected_paths):
707 continue
708
Doug Anderson42b8a052013-06-26 10:45:36 -0700709 # If the -9999.ebuild file was touched the bot will uprev for us.
710 # ...we'll use a simple intersection here as a heuristic...
Mike Frysinger292b45d2014-11-25 01:17:10 -0500711 if set(ebuilds_9999) & affected_paths:
Doug Anderson42b8a052013-06-26 10:45:36 -0700712 continue
713
714 if ebuilds:
Mike Frysinger292b45d2014-11-25 01:17:10 -0500715 return HookFailure('Changelist probably needs a revbump of an ebuild, '
716 'or a -r1.ebuild symlink if this is a new ebuild:\n'
717 '%s' % dir_path)
Doug Anderson42b8a052013-06-26 10:45:36 -0700718
719 return None
720
721
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500722def _check_ebuild_eapi(project, commit):
723 """Make sure we have people use EAPI=4 or newer with custom ebuilds.
724
725 We want to get away from older EAPI's as it makes life confusing and they
726 have less builtin error checking.
727
728 Args:
Alex Deymo643ac4c2015-09-03 10:40:50 -0700729 project: The Project to look at
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500730 commit: The commit to look at
731
732 Returns:
733 A HookFailure or None.
734 """
735 # If this is the portage-stable overlay, then ignore the check. It's rare
Mike Frysingercd6adfc2014-02-06 01:03:56 -0500736 # that we're doing anything other than importing files from upstream, and
737 # we shouldn't be rewriting things fundamentally anyways.
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500738 whitelist = (
739 'chromiumos/overlays/portage-stable',
740 )
Alex Deymo643ac4c2015-09-03 10:40:50 -0700741 if project.name in whitelist:
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500742 return None
743
744 BAD_EAPIS = ('0', '1', '2', '3')
745
746 get_eapi = re.compile(r'^\s*EAPI=[\'"]?([^\'"]+)')
747
748 ebuilds_re = [r'\.ebuild$']
749 ebuilds = _filter_files(_get_affected_files(commit, relative=True),
750 ebuilds_re)
751 bad_ebuilds = []
752
753 for ebuild in ebuilds:
754 # If the ebuild does not specify an EAPI, it defaults to 0.
755 eapi = '0'
756
757 lines = _get_file_content(ebuild, commit).splitlines()
758 if len(lines) == 1:
759 # This is most likely a symlink, so skip it entirely.
760 continue
761
762 for line in lines:
763 m = get_eapi.match(line)
764 if m:
765 # Once we hit the first EAPI line in this ebuild, stop processing.
766 # The spec requires that there only be one and it be first, so
767 # checking all possible values is pointless. We also assume that
768 # it's "the" EAPI line and not something in the middle of a heredoc.
769 eapi = m.group(1)
770 break
771
772 if eapi in BAD_EAPIS:
773 bad_ebuilds.append((ebuild, eapi))
774
775 if bad_ebuilds:
776 # pylint: disable=C0301
777 url = 'http://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/upgrade-ebuild-eapis'
778 # pylint: enable=C0301
779 return HookFailure(
Mike Frysingercd6adfc2014-02-06 01:03:56 -0500780 'These ebuilds are using old EAPIs. If these are imported from\n'
781 'Gentoo, then you may ignore and upload once with the --no-verify\n'
782 'flag. Otherwise, please update to 4 or newer.\n'
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500783 '\t%s\n'
784 'See this guide for more details:\n%s\n' %
785 ('\n\t'.join(['%s: EAPI=%s' % x for x in bad_ebuilds]), url))
786
787
Mike Frysinger89bdb852014-02-01 05:26:26 -0500788def _check_ebuild_keywords(_project, commit):
Mike Frysingerc51ece72014-01-17 16:23:40 -0500789 """Make sure we use the new style KEYWORDS when possible in ebuilds.
790
791 If an ebuild generally does not care about the arch it is running on, then
792 ebuilds should flag it with one of:
793 KEYWORDS="*" # A stable ebuild.
794 KEYWORDS="~*" # An unstable ebuild.
795 KEYWORDS="-* ..." # Is known to only work on specific arches.
796
797 Args:
Alex Deymo643ac4c2015-09-03 10:40:50 -0700798 project: The Project to look at
Mike Frysingerc51ece72014-01-17 16:23:40 -0500799 commit: The commit to look at
800
801 Returns:
802 A HookFailure or None.
803 """
804 WHITELIST = set(('*', '-*', '~*'))
805
806 get_keywords = re.compile(r'^\s*KEYWORDS="(.*)"')
807
Mike Frysinger89bdb852014-02-01 05:26:26 -0500808 ebuilds_re = [r'\.ebuild$']
809 ebuilds = _filter_files(_get_affected_files(commit, relative=True),
810 ebuilds_re)
811
Mike Frysinger8d42d742014-09-22 15:50:21 -0400812 bad_ebuilds = []
Mike Frysingerc51ece72014-01-17 16:23:40 -0500813 for ebuild in ebuilds:
Mike Frysinger5c9e58d2014-09-09 03:32:50 -0400814 # We get the full content rather than a diff as the latter does not work
815 # on new files (like when adding new ebuilds).
816 lines = _get_file_content(ebuild, commit).splitlines()
817 for line in lines:
Mike Frysingerc51ece72014-01-17 16:23:40 -0500818 m = get_keywords.match(line)
819 if m:
820 keywords = set(m.group(1).split())
821 if not keywords or WHITELIST - keywords != WHITELIST:
822 continue
823
Mike Frysinger8d42d742014-09-22 15:50:21 -0400824 bad_ebuilds.append(ebuild)
825
826 if bad_ebuilds:
827 return HookFailure(
828 '%s\n'
829 'Please update KEYWORDS to use a glob:\n'
830 'If the ebuild should be marked stable (normal for non-9999 ebuilds):\n'
831 ' KEYWORDS="*"\n'
832 'If the ebuild should be marked unstable (normal for '
833 'cros-workon / 9999 ebuilds):\n'
834 ' KEYWORDS="~*"\n'
Mike Frysingerde8efea2015-05-17 03:42:26 -0400835 'If the ebuild needs to be marked for only specific arches, '
Mike Frysinger8d42d742014-09-22 15:50:21 -0400836 'then use -* like so:\n'
837 ' KEYWORDS="-* arm ..."\n' % '\n* '.join(bad_ebuilds))
Mike Frysingerc51ece72014-01-17 16:23:40 -0500838
839
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800840def _check_ebuild_licenses(_project, commit):
841 """Check if the LICENSE field in the ebuild is correct."""
Brian Norris7a610e82016-02-17 12:24:54 -0800842 affected_paths = _get_affected_files(commit, relative=True)
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800843 touched_ebuilds = [x for x in affected_paths if x.endswith('.ebuild')]
844
845 # A list of licenses to ignore for now.
Yu-Ju Hongc0963fa2014-03-03 12:36:52 -0800846 LICENSES_IGNORE = ['||', '(', ')']
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800847
848 for ebuild in touched_ebuilds:
849 # Skip virutal packages.
850 if ebuild.split('/')[-3] == 'virtual':
851 continue
852
853 try:
Brian Norris7a610e82016-02-17 12:24:54 -0800854 ebuild_content = _get_file_content(ebuild, commit)
855 license_types = licenses_lib.GetLicenseTypesFromEbuild(ebuild_content)
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800856 except ValueError as e:
857 return HookFailure(e.message, [ebuild])
858
859 # Also ignore licenses ending with '?'
860 for license_type in [x for x in license_types
861 if x not in LICENSES_IGNORE and not x.endswith('?')]:
862 try:
Mike Frysinger2ec70ed2014-08-17 19:28:34 -0400863 licenses_lib.Licensing.FindLicenseType(license_type)
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800864 except AssertionError as e:
865 return HookFailure(e.message, [ebuild])
866
867
Mike Frysingercd363c82014-02-01 05:20:18 -0500868def _check_ebuild_virtual_pv(project, commit):
869 """Enforce the virtual PV policies."""
870 # If this is the portage-stable overlay, then ignore the check.
871 # We want to import virtuals as-is from upstream Gentoo.
872 whitelist = (
873 'chromiumos/overlays/portage-stable',
874 )
Alex Deymo643ac4c2015-09-03 10:40:50 -0700875 if project.name in whitelist:
Mike Frysingercd363c82014-02-01 05:20:18 -0500876 return None
877
878 # We assume the repo name is the same as the dir name on disk.
879 # It would be dumb to not have them match though.
Alex Deymo643ac4c2015-09-03 10:40:50 -0700880 project_base = os.path.basename(project.name)
Mike Frysingercd363c82014-02-01 05:20:18 -0500881
882 is_variant = lambda x: x.startswith('overlay-variant-')
883 is_board = lambda x: x.startswith('overlay-')
884 is_private = lambda x: x.endswith('-private')
885
886 get_pv = re.compile(r'(.*?)virtual/([^/]+)/\2-([^/]*)\.ebuild$')
887
888 ebuilds_re = [r'\.ebuild$']
889 ebuilds = _filter_files(_get_affected_files(commit, relative=True),
890 ebuilds_re)
891 bad_ebuilds = []
892
893 for ebuild in ebuilds:
894 m = get_pv.match(ebuild)
895 if m:
896 overlay = m.group(1)
897 if not overlay or not is_board(overlay):
Alex Deymo643ac4c2015-09-03 10:40:50 -0700898 overlay = project_base
Mike Frysingercd363c82014-02-01 05:20:18 -0500899
900 pv = m.group(3).split('-', 1)[0]
901
Bernie Thompsone5ee1822016-01-12 14:22:23 -0800902 # Virtual versions >= 4 are special cases used above the standard
903 # versioning structure, e.g. if one has a board inheriting a board.
904 if float(pv) >= 4:
905 want_pv = pv
906 elif is_private(overlay):
Mike Frysingercd363c82014-02-01 05:20:18 -0500907 want_pv = '3.5' if is_variant(overlay) else '3'
908 elif is_board(overlay):
909 want_pv = '2.5' if is_variant(overlay) else '2'
910 else:
911 want_pv = '1'
912
913 if pv != want_pv:
914 bad_ebuilds.append((ebuild, pv, want_pv))
915
916 if bad_ebuilds:
917 # pylint: disable=C0301
918 url = 'http://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/portage-build-faq#TOC-Virtuals-and-central-management'
919 # pylint: enable=C0301
920 return HookFailure(
921 'These virtuals have incorrect package versions (PVs). Please adjust:\n'
922 '\t%s\n'
923 'If this is an upstream Gentoo virtual, then you may ignore this\n'
924 'check (and re-run w/--no-verify). Otherwise, please see this\n'
925 'page for more details:\n%s\n' %
926 ('\n\t'.join(['%s:\n\t\tPV is %s but should be %s' % x
927 for x in bad_ebuilds]), url))
928
929
Daniel Erat9d203ff2015-02-17 10:12:21 -0700930def _check_portage_make_use_var(_project, commit):
931 """Verify that $USE is set correctly in make.conf and make.defaults."""
932 files = _filter_files(_get_affected_files(commit, relative=True),
933 [r'(^|/)make.(conf|defaults)$'])
934
935 errors = []
936 for path in files:
937 basename = os.path.basename(path)
938
939 # Has a USE= line already been encountered in this file?
940 saw_use = False
941
942 for i, line in enumerate(_get_file_content(path, commit).splitlines(), 1):
943 if not line.startswith('USE='):
944 continue
945
946 preserves_use = '${USE}' in line or '$USE' in line
947
948 if (basename == 'make.conf' or
949 (basename == 'make.defaults' and saw_use)) and not preserves_use:
950 errors.append('%s:%d: missing ${USE}' % (path, i))
951 elif basename == 'make.defaults' and not saw_use and preserves_use:
952 errors.append('%s:%d: ${USE} referenced in initial declaration' %
953 (path, i))
954
955 saw_use = True
956
957 if errors:
958 return HookFailure(
959 'One or more Portage make files appear to set USE incorrectly.\n'
960 '\n'
961 'All USE assignments in make.conf and all assignments after the\n'
962 'initial declaration in make.defaults should contain "${USE}" to\n'
963 'preserve previously-set flags.\n'
964 '\n'
965 'The initial USE declaration in make.defaults should not contain\n'
966 '"${USE}".\n',
967 errors)
968
969
Mike Frysingerae409522014-02-01 03:16:11 -0500970def _check_change_has_proper_changeid(_project, commit):
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700971 """Verify that Change-ID is present in last paragraph of commit message."""
Mike Frysinger4a22bf02014-10-31 13:53:35 -0400972 CHANGE_ID_RE = r'\nChange-Id: I[a-f0-9]+\n'
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700973 desc = _get_commit_desc(commit)
Mike Frysinger4a22bf02014-10-31 13:53:35 -0400974 m = re.search(CHANGE_ID_RE, desc)
Mike Frysinger02b88bd2014-11-21 00:29:38 -0500975 if not m:
Vadim Bendebury20532ba2017-05-23 17:26:15 -0700976 return HookFailure('Last paragraph of description must include Change-Id.')
Ryan Cui1562fb82011-05-09 11:01:31 -0700977
Vadim Bendebury20532ba2017-05-23 17:26:15 -0700978 # S-o-b tags always allowed to follow Change-ID.
979 allowed_tags = ['Signed-off-by']
980
Mike Frysinger02b88bd2014-11-21 00:29:38 -0500981 end = desc[m.end():].strip().splitlines()
Vadim Bendebury6504aea2017-09-13 18:35:49 -0700982 cherry_pick_marker = 'cherry picked from commit'
983
984 if end and cherry_pick_marker in end[-1]:
Vadim Bendebury20532ba2017-05-23 17:26:15 -0700985 # Cherry picked patches allow more tags in the last paragraph.
Vadim Bendebury6504aea2017-09-13 18:35:49 -0700986 allowed_tags += ['Commit-Queue', 'Commit-Ready', 'Reviewed-by',
987 'Reviewed-on', 'Tested-by']
Vadim Bendebury20532ba2017-05-23 17:26:15 -0700988 end = end[:-1]
989
Vadim Bendebury6504aea2017-09-13 18:35:49 -0700990 # Note that descriptions could have multiple cherry pick markers.
991 tag_search = r'^(%s:|\(%s) ' % (':|'.join(allowed_tags), cherry_pick_marker)
Vadim Bendebury20532ba2017-05-23 17:26:15 -0700992
993 if [x for x in end if not re.search(tag_search, x)]:
994 return HookFailure('Only "%s:" tag(s) may follow the Change-Id.' %
995 ':", "'.join(allowed_tags))
Mike Frysinger02b88bd2014-11-21 00:29:38 -0500996
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700997
Mike Frysinger36b2ebc2014-10-31 14:02:03 -0400998def _check_commit_message_style(_project, commit):
999 """Verify that the commit message matches our style.
1000
1001 We do not check for BUG=/TEST=/etc... lines here as that is handled by other
1002 commit hooks.
1003 """
1004 desc = _get_commit_desc(commit)
1005
1006 # The first line should be by itself.
1007 lines = desc.splitlines()
1008 if len(lines) > 1 and lines[1]:
1009 return HookFailure('The second line of the commit message must be blank.')
1010
1011 # The first line should be one sentence.
1012 if '. ' in lines[0]:
1013 return HookFailure('The first line cannot be more than one sentence.')
1014
1015 # The first line cannot be too long.
1016 MAX_FIRST_LINE_LEN = 100
1017 if len(lines[0]) > MAX_FIRST_LINE_LEN:
1018 return HookFailure('The first line must be less than %i chars.' %
1019 MAX_FIRST_LINE_LEN)
1020
1021
Filipe Brandenburger4b542b12015-10-09 12:46:31 -07001022def _check_cros_license(_project, commit, options=()):
Alex Deymof5792ce2015-08-24 22:50:08 -07001023 """Verifies the Chromium OS license/copyright header.
Ryan Cuiec4d6332011-05-02 14:15:25 -07001024
Mike Frysinger98638102014-08-28 00:15:08 -04001025 Should be following the spec:
1026 http://dev.chromium.org/developers/coding-style#TOC-File-headers
1027 """
1028 # For older years, be a bit more flexible as our policy says leave them be.
1029 LICENSE_HEADER = (
1030 r'.* Copyright( \(c\))? 20[-0-9]{2,7} The Chromium OS Authors\. '
Mike Frysingerb81102f2014-11-21 00:33:35 -05001031 r'All rights reserved\.' r'\n'
Mike Frysinger98638102014-08-28 00:15:08 -04001032 r'.* Use of this source code is governed by a BSD-style license that can '
Mike Frysingerb81102f2014-11-21 00:33:35 -05001033 r'be\n'
Mike Frysinger98638102014-08-28 00:15:08 -04001034 r'.* found in the LICENSE file\.'
Mike Frysingerb81102f2014-11-21 00:33:35 -05001035 r'\n'
Mike Frysinger98638102014-08-28 00:15:08 -04001036 )
1037 license_re = re.compile(LICENSE_HEADER, re.MULTILINE)
1038
1039 # For newer years, be stricter.
1040 COPYRIGHT_LINE = (
1041 r'.* Copyright \(c\) 20(1[5-9]|[2-9][0-9]) The Chromium OS Authors\. '
Mike Frysingerb81102f2014-11-21 00:33:35 -05001042 r'All rights reserved\.' r'\n'
Mike Frysinger98638102014-08-28 00:15:08 -04001043 )
1044 copyright_re = re.compile(COPYRIGHT_LINE)
1045
Shuhei Takahashiabc20f32017-07-10 19:35:45 +09001046 included, excluded = _parse_common_inclusion_options(options)
Filipe Brandenburger4b542b12015-10-09 12:46:31 -07001047
Mike Frysinger98638102014-08-28 00:15:08 -04001048 bad_files = []
1049 bad_copyright_files = []
1050 files = _filter_files(_get_affected_files(commit, relative=True),
Filipe Brandenburger4b542b12015-10-09 12:46:31 -07001051 included + COMMON_INCLUDED_PATHS,
1052 excluded + COMMON_EXCLUDED_PATHS)
Mike Frysinger98638102014-08-28 00:15:08 -04001053
1054 for f in files:
1055 contents = _get_file_content(f, commit)
1056 if not contents:
1057 # Ignore empty files.
1058 continue
1059
1060 if not license_re.search(contents):
1061 bad_files.append(f)
1062 elif copyright_re.search(contents):
1063 bad_copyright_files.append(f)
1064
1065 if bad_files:
1066 msg = '%s:\n%s\n%s' % (
1067 'License must match', license_re.pattern,
1068 'Found a bad header in these files:')
1069 return HookFailure(msg, bad_files)
1070
1071 if bad_copyright_files:
1072 msg = 'Do not use (c) in copyright headers in new files:'
1073 return HookFailure(msg, bad_copyright_files)
Ryan Cuiec4d6332011-05-02 14:15:25 -07001074
1075
Alex Deymof5792ce2015-08-24 22:50:08 -07001076def _check_aosp_license(_project, commit):
1077 """Verifies the AOSP license/copyright header.
1078
1079 AOSP uses the Apache2 License:
1080 https://source.android.com/source/licenses.html
1081 """
1082 LICENSE_HEADER = (
1083 r"""^[#/\*]*
1084[#/\*]* ?Copyright( \([cC]\))? 20[-0-9]{2,7} The Android Open Source Project
1085[#/\*]* ?
1086[#/\*]* ?Licensed under the Apache License, Version 2.0 \(the "License"\);
1087[#/\*]* ?you may not use this file except in compliance with the License\.
1088[#/\*]* ?You may obtain a copy of the License at
1089[#/\*]* ?
1090[#/\*]* ? http://www\.apache\.org/licenses/LICENSE-2\.0
1091[#/\*]* ?
1092[#/\*]* ?Unless required by applicable law or agreed to in writing, software
1093[#/\*]* ?distributed under the License is distributed on an "AS IS" BASIS,
1094[#/\*]* ?WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or """
1095 r"""implied\.
1096[#/\*]* ?See the License for the specific language governing permissions and
1097[#/\*]* ?limitations under the License\.
1098[#/\*]*$
1099"""
1100 )
1101 license_re = re.compile(LICENSE_HEADER, re.MULTILINE)
1102
1103 files = _filter_files(_get_affected_files(commit, relative=True),
1104 COMMON_INCLUDED_PATHS,
1105 COMMON_EXCLUDED_PATHS)
1106
1107 bad_files = []
1108 for f in files:
1109 contents = _get_file_content(f, commit)
1110 if not contents:
1111 # Ignore empty files.
1112 continue
1113
1114 if not license_re.search(contents):
1115 bad_files.append(f)
1116
1117 if bad_files:
1118 msg = ('License must match:\n%s\nFound a bad header in these files:' %
1119 license_re.pattern)
1120 return HookFailure(msg, bad_files)
1121
1122
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001123def _check_layout_conf(_project, commit):
1124 """Verifies the metadata/layout.conf file."""
1125 repo_name = 'profiles/repo_name'
Mike Frysinger94a670c2014-09-19 12:46:26 -04001126 repo_names = []
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001127 layout_path = 'metadata/layout.conf'
Mike Frysinger94a670c2014-09-19 12:46:26 -04001128 layout_paths = []
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001129
Mike Frysinger94a670c2014-09-19 12:46:26 -04001130 # Handle multiple overlays in a single commit (like the public tree).
1131 for f in _get_affected_files(commit, relative=True):
1132 if f.endswith(repo_name):
1133 repo_names.append(f)
1134 elif f.endswith(layout_path):
1135 layout_paths.append(f)
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001136
1137 # Disallow new repos with the repo_name file.
Mike Frysinger94a670c2014-09-19 12:46:26 -04001138 if repo_names:
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001139 return HookFailure('%s: use "repo-name" in %s instead' %
Mike Frysinger94a670c2014-09-19 12:46:26 -04001140 (repo_names, layout_path))
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001141
Mike Frysinger94a670c2014-09-19 12:46:26 -04001142 # Gather all the errors in one pass so we show one full message.
1143 all_errors = {}
1144 for layout_path in layout_paths:
1145 all_errors[layout_path] = errors = []
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001146
Mike Frysinger94a670c2014-09-19 12:46:26 -04001147 # Make sure the config file is sorted.
1148 data = [x for x in _get_file_content(layout_path, commit).splitlines()
1149 if x and x[0] != '#']
1150 if sorted(data) != data:
1151 errors += ['keep lines sorted']
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001152
Mike Frysinger94a670c2014-09-19 12:46:26 -04001153 # Require people to set specific values all the time.
1154 settings = (
1155 # TODO: Enable this for everyone. http://crbug.com/408038
1156 #('fast caching', 'cache-format = md5-dict'),
1157 ('fast manifests', 'thin-manifests = true'),
Mike Frysingerd7734522015-02-26 16:12:43 -05001158 ('extra features', 'profile-formats = portage-2 profile-default-eapi'),
1159 ('newer eapi', 'profile_eapi_when_unspecified = 5-progress'),
Mike Frysinger94a670c2014-09-19 12:46:26 -04001160 )
1161 for reason, line in settings:
1162 if line not in data:
1163 errors += ['enable %s with: %s' % (reason, line)]
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001164
Mike Frysinger94a670c2014-09-19 12:46:26 -04001165 # Require one of these settings.
Mike Frysinger5fae62d2015-11-11 20:12:15 -05001166 if 'use-manifests = strict' not in data:
1167 errors += ['enable file checking with: use-manifests = strict']
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001168
Mike Frysinger94a670c2014-09-19 12:46:26 -04001169 # Require repo-name to be set.
Mike Frysinger324cf682014-09-22 15:52:50 -04001170 for line in data:
1171 if line.startswith('repo-name = '):
1172 break
1173 else:
Mike Frysinger94a670c2014-09-19 12:46:26 -04001174 errors += ['set the board name with: repo-name = $BOARD']
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001175
Mike Frysinger94a670c2014-09-19 12:46:26 -04001176 # Summarize all the errors we saw (if any).
1177 lines = ''
1178 for layout_path, errors in all_errors.items():
1179 if errors:
1180 lines += '\n\t- '.join(['\n* %s:' % layout_path] + errors)
1181 if lines:
1182 lines = 'See the portage(5) man page for layout.conf details' + lines + '\n'
1183 return HookFailure(lines)
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001184
1185
Ryan Cuiec4d6332011-05-02 14:15:25 -07001186# Project-specific hooks
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001187
Ryan Cui1562fb82011-05-09 11:01:31 -07001188
Luis Hector Chavezb50391d2017-09-26 15:48:15 -07001189def _check_clang_format(_project, commit, options=()):
1190 """Runs clang-format on the given project"""
1191 hooks_dir = _get_hooks_dir()
1192 options = list(options)
1193 if commit == PRE_SUBMIT:
1194 options.append('--commit=HEAD')
1195 else:
1196 options.extend(['--commit', commit])
1197 cmd = ['%s/clang-format.py' % hooks_dir] + options
1198 cmd_result = cros_build_lib.RunCommand(cmd=cmd,
1199 print_cmd=False,
1200 input=_get_patch(commit),
1201 stdout_to_pipe=True,
1202 combine_stdout_stderr=True,
1203 error_code_ok=True)
1204 if cmd_result.returncode:
1205 return HookFailure('clang-format.py errors/warnings\n\n' +
1206 cmd_result.output)
1207
1208
Mike Frysingerae409522014-02-01 03:16:11 -05001209def _run_checkpatch(_project, commit, options=()):
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001210 """Runs checkpatch.pl on the given project"""
1211 hooks_dir = _get_hooks_dir()
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001212 options = list(options)
1213 if commit == PRE_SUBMIT:
1214 # The --ignore option must be present and include 'MISSING_SIGN_OFF' in
1215 # this case.
1216 options.append('--ignore=MISSING_SIGN_OFF')
Filipe Brandenburger28d48d62015-10-07 09:48:54 -07001217 # Always ignore the check for the MAINTAINERS file. We do not track that
1218 # information on that file in our source trees, so let's suppress the
1219 # warning.
1220 options.append('--ignore=FILE_PATH_CHANGES')
Filipe Brandenburgerce978322015-10-09 10:04:15 -07001221 # Do not complain about the Change-Id: fields, since we use Gerrit.
1222 # Upstream does not want those lines (since they do not use Gerrit), but
1223 # we always do, so disable the check globally.
Daisuke Nojiri4844f892015-10-08 09:54:33 -07001224 options.append('--ignore=GERRIT_CHANGE_ID')
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001225 cmd = ['%s/checkpatch.pl' % hooks_dir] + options + ['-']
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001226 cmd_result = cros_build_lib.RunCommand(cmd=cmd,
1227 print_cmd=False,
1228 input=_get_patch(commit),
1229 stdout_to_pipe=True,
1230 combine_stdout_stderr=True,
1231 error_code_ok=True)
1232 if cmd_result.returncode:
1233 return HookFailure('checkpatch.pl errors/warnings\n\n' + cmd_result.output)
Ryan Cuiec4d6332011-05-02 14:15:25 -07001234
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001235
Mike Frysingerae409522014-02-01 03:16:11 -05001236def _kernel_configcheck(_project, commit):
Olof Johanssona96810f2012-09-04 16:20:03 -07001237 """Makes sure kernel config changes are not mixed with code changes"""
1238 files = _get_affected_files(commit)
1239 if not len(_filter_files(files, [r'chromeos/config'])) in [0, len(files)]:
1240 return HookFailure('Changes to chromeos/config/ and regular files must '
1241 'be in separate commits:\n%s' % '\n'.join(files))
Anton Staaf815d6852011-08-22 10:08:45 -07001242
Mike Frysingerae409522014-02-01 03:16:11 -05001243
1244def _run_json_check(_project, commit):
Dale Curtis2975c432011-05-03 17:25:20 -07001245 """Checks that all JSON files are syntactically valid."""
Dale Curtisa039cfd2011-05-04 12:01:05 -07001246 for f in _filter_files(_get_affected_files(commit), [r'.*\.json']):
Dale Curtis2975c432011-05-03 17:25:20 -07001247 try:
1248 json.load(open(f))
1249 except Exception, e:
Ryan Cui1562fb82011-05-09 11:01:31 -07001250 return HookFailure('Invalid JSON in %s: %s' % (f, e))
Dale Curtis2975c432011-05-03 17:25:20 -07001251
1252
Mike Frysingerae409522014-02-01 03:16:11 -05001253def _check_manifests(_project, commit):
Mike Frysinger52b537e2013-08-22 22:59:53 -04001254 """Make sure Manifest files only have DIST lines"""
1255 paths = []
1256
1257 for path in _get_affected_files(commit):
1258 if os.path.basename(path) != 'Manifest':
1259 continue
1260 if not os.path.exists(path):
1261 continue
1262
1263 with open(path, 'r') as f:
1264 for line in f.readlines():
1265 if not line.startswith('DIST '):
1266 paths.append(path)
1267 break
1268
1269 if paths:
1270 return HookFailure('Please remove lines that do not start with DIST:\n%s' %
1271 ('\n'.join(paths),))
1272
1273
Mike Frysingerae409522014-02-01 03:16:11 -05001274def _check_change_has_branch_field(_project, commit):
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001275 """Check for a non-empty 'BRANCH=' field in the commit message."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001276 if commit == PRE_SUBMIT:
1277 return
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001278 BRANCH_RE = r'\nBRANCH=\S+'
1279
1280 if not re.search(BRANCH_RE, _get_commit_desc(commit)):
1281 msg = ('Changelist description needs BRANCH field (after first line)\n'
1282 'E.g. BRANCH=none or BRANCH=link,snow')
1283 return HookFailure(msg)
1284
1285
Mike Frysingerae409522014-02-01 03:16:11 -05001286def _check_change_has_signoff_field(_project, commit):
Shawn Nematbakhsh51e16ac2014-01-28 15:31:07 -08001287 """Check for a non-empty 'Signed-off-by:' field in the commit message."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001288 if commit == PRE_SUBMIT:
1289 return
Shawn Nematbakhsh51e16ac2014-01-28 15:31:07 -08001290 SIGNOFF_RE = r'\nSigned-off-by: \S+'
1291
1292 if not re.search(SIGNOFF_RE, _get_commit_desc(commit)):
1293 msg = ('Changelist description needs Signed-off-by: field\n'
1294 'E.g. Signed-off-by: My Name <me@chromium.org>')
1295 return HookFailure(msg)
1296
1297
Aviv Keshet5ac59522017-01-31 14:28:27 -08001298def _check_cq_ini_well_formed(_project, commit):
1299 """Check that any modified COMMIT-QUEUE.ini files are well formed."""
1300 pattern = '.*' + constants.CQ_CONFIG_FILENAME
1301 files = _filter_files(_get_affected_files(commit), (pattern,))
1302
1303 # TODO(akeshet): Check not only that the file is parseable, but that all the
1304 # pre-cq configs it requests are existing ones.
1305 for f in files:
1306 try:
1307 parser = ConfigParser.SafeConfigParser()
1308 # Prior to python3, ConfigParser has no read_string method, so we must
1309 # pass it either a file path or file like object. And we must use
1310 # _get_file_content to fetch file contents to ensure we are examining the
1311 # commit diff, rather than whatever's on disk.
1312 contents = _get_file_content(f, commit)
1313 parser.readfp(StringIO.StringIO(contents))
1314 except ConfigParser.Error as e:
1315 msg = ('Unable to parse COMMIT-QUEUE.ini file at %s due to %s.' %
1316 (f, e))
1317 return HookFailure(msg)
1318
1319
Jon Salz3ee59de2012-08-18 13:54:22 +08001320def _run_project_hook_script(script, project, commit):
1321 """Runs a project hook script.
1322
1323 The script is run with the following environment variables set:
1324 PRESUBMIT_PROJECT: The affected project
1325 PRESUBMIT_COMMIT: The affected commit
1326 PRESUBMIT_FILES: A newline-separated list of affected files
1327
1328 The script is considered to fail if the exit code is non-zero. It should
1329 write an error message to stdout.
1330 """
1331 env = dict(os.environ)
Alex Deymo643ac4c2015-09-03 10:40:50 -07001332 env['PRESUBMIT_PROJECT'] = project.name
Jon Salz3ee59de2012-08-18 13:54:22 +08001333 env['PRESUBMIT_COMMIT'] = commit
1334
1335 # Put affected files in an environment variable
1336 files = _get_affected_files(commit)
1337 env['PRESUBMIT_FILES'] = '\n'.join(files)
1338
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001339 cmd_result = cros_build_lib.RunCommand(cmd=script,
1340 env=env,
1341 shell=True,
1342 print_cmd=False,
1343 input=os.devnull,
1344 stdout_to_pipe=True,
1345 combine_stdout_stderr=True,
1346 error_code_ok=True)
1347 if cmd_result.returncode:
1348 stdout = cmd_result.output
Jon Salz7b618af2012-08-31 06:03:16 +08001349 if stdout:
1350 stdout = re.sub('(?m)^', ' ', stdout)
1351 return HookFailure('Hook script "%s" failed with code %d%s' %
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001352 (script, cmd_result.returncode,
Jon Salz3ee59de2012-08-18 13:54:22 +08001353 ':\n' + stdout if stdout else ''))
1354
1355
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001356def _check_project_prefix(_project, commit):
Mike Frysinger55f85b52014-12-18 14:45:21 -05001357 """Require the commit message have a project specific prefix as needed."""
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001358
1359 files = _get_affected_files(commit, relative=True)
1360 prefix = os.path.commonprefix(files)
1361 prefix = os.path.dirname(prefix)
1362
1363 # If there is no common prefix, the CL span multiple projects.
Daniel Erata350fd32014-09-29 14:02:34 -07001364 if not prefix:
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001365 return
1366
1367 project_name = prefix.split('/')[0]
Daniel Erata350fd32014-09-29 14:02:34 -07001368
1369 # The common files may all be within a subdirectory of the main project
1370 # directory, so walk up the tree until we find an alias file.
1371 # _get_affected_files() should return relative paths, but check against '/' to
1372 # ensure that this loop terminates even if it receives an absolute path.
1373 while prefix and prefix != '/':
1374 alias_file = os.path.join(prefix, '.project_alias')
1375
1376 # If an alias exists, use it.
1377 if os.path.isfile(alias_file):
1378 project_name = osutils.ReadFile(alias_file).strip()
1379
1380 prefix = os.path.dirname(prefix)
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001381
1382 if not _get_commit_desc(commit).startswith(project_name + ': '):
1383 return HookFailure('The commit title for changes affecting only %s'
1384 ' should start with \"%s: \"'
1385 % (project_name, project_name))
1386
1387
Mike Frysingerf9d41b32017-02-23 15:20:04 -05001388def _check_exec_files(_project, commit):
1389 """Make +x bits on files."""
1390 # List of files that should never be +x.
1391 NO_EXEC = (
1392 'ChangeLog*',
1393 'COPYING',
1394 'make.conf',
1395 'make.defaults',
1396 'Manifest',
1397 'OWNERS',
1398 'package.use',
1399 'package.keywords',
1400 'package.mask',
1401 'parent',
1402 'README',
1403 'TODO',
1404 '.gitignore',
1405 '*.[achly]',
1406 '*.[ch]xx',
1407 '*.boto',
1408 '*.cc',
1409 '*.cfg',
1410 '*.conf',
1411 '*.config',
1412 '*.cpp',
1413 '*.css',
1414 '*.ebuild',
1415 '*.eclass',
1416 '*.gyp',
1417 '*.gypi',
1418 '*.htm',
1419 '*.html',
1420 '*.ini',
1421 '*.js',
1422 '*.json',
1423 '*.md',
1424 '*.mk',
1425 '*.patch',
1426 '*.policy',
1427 '*.proto',
1428 '*.raw',
1429 '*.rules',
1430 '*.service',
1431 '*.target',
1432 '*.txt',
1433 '*.xml',
1434 '*.yaml',
1435 )
1436
1437 def FinalName(obj):
1438 # If the file is being deleted, then the dst_file is not set.
1439 if obj.dst_file is None:
1440 return obj.src_file
1441 else:
1442 return obj.dst_file
1443
1444 bad_files = []
1445 files = _get_affected_files(commit, relative=True, full_details=True)
1446 for f in files:
1447 mode = int(f.dst_mode, 8)
1448 if not mode & 0o111:
1449 continue
1450 name = FinalName(f)
1451 for no_exec in NO_EXEC:
1452 if fnmatch.fnmatch(name, no_exec):
1453 bad_files.append(name)
1454 break
1455
1456 if bad_files:
1457 return HookFailure('These files should not be executable. '
1458 'Please `chmod -x` them.', bad_files)
1459
1460
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001461# Base
1462
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001463# A list of hooks which are not project specific and check patch description
1464# (as opposed to patch body).
1465_PATCH_DESCRIPTION_HOOKS = [
Ryan Cui9b651632011-05-11 11:38:58 -07001466 _check_change_has_bug_field,
David Jamesc3b68b32013-04-03 09:17:03 -07001467 _check_change_has_valid_cq_depend,
Ryan Cui9b651632011-05-11 11:38:58 -07001468 _check_change_has_test_field,
1469 _check_change_has_proper_changeid,
Mike Frysinger36b2ebc2014-10-31 14:02:03 -04001470 _check_commit_message_style,
Bernie Thompsonf8fea992016-01-14 10:27:18 -08001471 _check_change_is_contribution,
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001472]
1473
1474
1475# A list of hooks that are not project-specific
1476_COMMON_HOOKS = [
Aviv Keshet5ac59522017-01-31 14:28:27 -08001477 _check_cq_ini_well_formed,
1478 _check_cros_license,
Mike Frysingerbf8b91c2014-02-01 02:50:27 -05001479 _check_ebuild_eapi,
Mike Frysinger89bdb852014-02-01 05:26:26 -05001480 _check_ebuild_keywords,
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -08001481 _check_ebuild_licenses,
Mike Frysingercd363c82014-02-01 05:20:18 -05001482 _check_ebuild_virtual_pv,
Mike Frysingerf9d41b32017-02-23 15:20:04 -05001483 _check_exec_files,
Daniel Erat9d203ff2015-02-17 10:12:21 -07001484 _check_for_uprev,
Rahul Chaudhry09f61372015-07-31 17:14:26 -07001485 _check_gofmt,
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001486 _check_layout_conf,
Daniel Erat9d203ff2015-02-17 10:12:21 -07001487 _check_no_long_lines,
1488 _check_no_stray_whitespace,
Ryan Cui9b651632011-05-11 11:38:58 -07001489 _check_no_tabs,
Daniel Erat9d203ff2015-02-17 10:12:21 -07001490 _check_portage_make_use_var,
Aviv Keshet5ac59522017-01-31 14:28:27 -08001491 _check_tabbed_indents,
Ryan Cui9b651632011-05-11 11:38:58 -07001492]
Ryan Cuiec4d6332011-05-02 14:15:25 -07001493
Ryan Cui1562fb82011-05-09 11:01:31 -07001494
Ryan Cui9b651632011-05-11 11:38:58 -07001495# A dictionary of project-specific hooks(callbacks), indexed by project name.
1496# dict[project] = [callback1, callback2]
1497_PROJECT_SPECIFIC_HOOKS = {
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001498 "chromiumos/platform2": [_check_project_prefix],
Mike Frysingeraf891292015-03-25 19:46:53 -04001499 "chromiumos/third_party/kernel": [_kernel_configcheck],
1500 "chromiumos/third_party/kernel-next": [_kernel_configcheck],
Ryan Cui9b651632011-05-11 11:38:58 -07001501}
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001502
Ryan Cui1562fb82011-05-09 11:01:31 -07001503
Ryan Cui9b651632011-05-11 11:38:58 -07001504# A dictionary of flags (keys) that can appear in the config file, and the hook
Mike Frysinger3554bc92015-03-11 04:59:21 -04001505# that the flag controls (value).
1506_HOOK_FLAGS = {
Luis Hector Chavezb50391d2017-09-26 15:48:15 -07001507 'clang_format_check': _check_clang_format,
Mike Frysingera7642f52015-03-25 18:31:42 -04001508 'checkpatch_check': _run_checkpatch,
Ryan Cui9b651632011-05-11 11:38:58 -07001509 'stray_whitespace_check': _check_no_stray_whitespace,
Mike Frysingerff6c7d62015-03-24 13:49:46 -04001510 'json_check': _run_json_check,
Ryan Cui9b651632011-05-11 11:38:58 -07001511 'long_line_check': _check_no_long_lines,
Alex Deymof5792ce2015-08-24 22:50:08 -07001512 'cros_license_check': _check_cros_license,
1513 'aosp_license_check': _check_aosp_license,
Ryan Cui9b651632011-05-11 11:38:58 -07001514 'tab_check': _check_no_tabs,
Prathmesh Prabhuc5254652016-12-22 12:58:05 -08001515 'tabbed_indent_required_check': _check_tabbed_indents,
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001516 'branch_check': _check_change_has_branch_field,
Shawn Nematbakhsh51e16ac2014-01-28 15:31:07 -08001517 'signoff_check': _check_change_has_signoff_field,
Josh Triplett0e8fc7f2014-04-23 16:00:00 -07001518 'bug_field_check': _check_change_has_bug_field,
1519 'test_field_check': _check_change_has_test_field,
Steve Fung49ec7e92015-03-23 16:07:12 -07001520 'manifest_check': _check_manifests,
Bernie Thompsonf8fea992016-01-14 10:27:18 -08001521 'contribution_check': _check_change_is_contribution,
Ryan Cui9b651632011-05-11 11:38:58 -07001522}
1523
1524
Mike Frysinger3554bc92015-03-11 04:59:21 -04001525def _get_override_hooks(config):
1526 """Returns a set of hooks controlled by the current project's config file.
Ryan Cui9b651632011-05-11 11:38:58 -07001527
1528 Expects to be called within the project root.
Jon Salz3ee59de2012-08-18 13:54:22 +08001529
1530 Args:
1531 config: A ConfigParser for the project's config file.
Ryan Cui9b651632011-05-11 11:38:58 -07001532 """
1533 SECTION = 'Hook Overrides'
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001534 SECTION_OPTIONS = 'Hook Overrides Options'
Jon Salz3ee59de2012-08-18 13:54:22 +08001535 if not config.has_section(SECTION):
Mike Frysinger3554bc92015-03-11 04:59:21 -04001536 return set(), set()
Ryan Cui9b651632011-05-11 11:38:58 -07001537
Mike Frysinger3554bc92015-03-11 04:59:21 -04001538 valid_keys = set(_HOOK_FLAGS.iterkeys())
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001539 hooks = _HOOK_FLAGS.copy()
Mike Frysinger3554bc92015-03-11 04:59:21 -04001540
1541 enable_flags = []
Ryan Cui9b651632011-05-11 11:38:58 -07001542 disable_flags = []
Jon Salz3ee59de2012-08-18 13:54:22 +08001543 for flag in config.options(SECTION):
Mike Frysinger3554bc92015-03-11 04:59:21 -04001544 if flag not in valid_keys:
1545 raise ValueError('Error: unknown key "%s" in hook section of "%s"' %
1546 (flag, _CONFIG_FILE))
1547
Ryan Cui9b651632011-05-11 11:38:58 -07001548 try:
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001549 enabled = config.getboolean(SECTION, flag)
Ryan Cui9b651632011-05-11 11:38:58 -07001550 except ValueError as e:
Mike Frysinger3554bc92015-03-11 04:59:21 -04001551 raise ValueError('Error: parsing flag "%s" in "%s" failed: %s' %
1552 (flag, _CONFIG_FILE, e))
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001553 if enabled:
1554 enable_flags.append(flag)
1555 else:
1556 disable_flags.append(flag)
Ryan Cui9b651632011-05-11 11:38:58 -07001557
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001558 # See if this hook has custom options.
1559 if enabled:
1560 try:
1561 options = config.get(SECTION_OPTIONS, flag)
1562 hooks[flag] = functools.partial(hooks[flag], options=options.split())
1563 except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
1564 pass
1565
1566 enabled_hooks = set(hooks[x] for x in enable_flags)
1567 disabled_hooks = set(hooks[x] for x in disable_flags)
Mike Frysinger3554bc92015-03-11 04:59:21 -04001568 return enabled_hooks, disabled_hooks
Ryan Cui9b651632011-05-11 11:38:58 -07001569
1570
Jon Salz3ee59de2012-08-18 13:54:22 +08001571def _get_project_hook_scripts(config):
1572 """Returns a list of project-specific hook scripts.
1573
1574 Args:
1575 config: A ConfigParser for the project's config file.
1576 """
1577 SECTION = 'Hook Scripts'
1578 if not config.has_section(SECTION):
1579 return []
1580
1581 hook_names_values = config.items(SECTION)
1582 hook_names_values.sort(key=lambda x: x[0])
1583 return [x[1] for x in hook_names_values]
1584
1585
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001586def _get_project_hooks(project, presubmit):
Ryan Cui9b651632011-05-11 11:38:58 -07001587 """Returns a list of hooks that need to be run for a project.
1588
1589 Expects to be called from within the project root.
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001590
1591 Args:
1592 project: A string, name of the project.
1593 presubmit: A Boolean, True if the check is run as a git pre-submit script.
Ryan Cui9b651632011-05-11 11:38:58 -07001594 """
Jon Salz3ee59de2012-08-18 13:54:22 +08001595 config = ConfigParser.RawConfigParser()
1596 try:
1597 config.read(_CONFIG_FILE)
1598 except ConfigParser.Error:
1599 # Just use an empty config file
1600 config = ConfigParser.RawConfigParser()
1601
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001602 if presubmit:
Filipe Brandenburgerf70d32c2015-10-09 13:35:45 -07001603 hooks = _COMMON_HOOKS
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001604 else:
Filipe Brandenburgerf70d32c2015-10-09 13:35:45 -07001605 hooks = _PATCH_DESCRIPTION_HOOKS + _COMMON_HOOKS
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001606
Mike Frysinger3554bc92015-03-11 04:59:21 -04001607 enabled_hooks, disabled_hooks = _get_override_hooks(config)
Filipe Brandenburgerf70d32c2015-10-09 13:35:45 -07001608 hooks = [hook for hook in hooks if hook not in disabled_hooks]
1609
1610 # If a list is both in _COMMON_HOOKS and also enabled explicitly through an
1611 # override, keep the override only. Note that the override may end up being
1612 # a functools.partial, in which case we need to extract the .func to compare
1613 # it to the common hooks.
1614 unwrapped_hooks = [getattr(hook, 'func', hook) for hook in enabled_hooks]
1615 hooks = [hook for hook in hooks if hook not in unwrapped_hooks]
1616
1617 hooks = list(enabled_hooks) + hooks
Ryan Cui9b651632011-05-11 11:38:58 -07001618
1619 if project in _PROJECT_SPECIFIC_HOOKS:
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001620 hooks.extend(hook for hook in _PROJECT_SPECIFIC_HOOKS[project]
1621 if hook not in disabled_hooks)
Ryan Cui9b651632011-05-11 11:38:58 -07001622
Jon Salz3ee59de2012-08-18 13:54:22 +08001623 for script in _get_project_hook_scripts(config):
1624 hooks.append(functools.partial(_run_project_hook_script, script))
1625
Ryan Cui9b651632011-05-11 11:38:58 -07001626 return hooks
1627
1628
Alex Deymo643ac4c2015-09-03 10:40:50 -07001629def _run_project_hooks(project_name, proj_dir=None,
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001630 commit_list=None, presubmit=False):
Ryan Cui1562fb82011-05-09 11:01:31 -07001631 """For each project run its project specific hook from the hooks dictionary.
1632
1633 Args:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001634 project_name: The name of project to run hooks for.
Doug Anderson44a644f2011-11-02 10:37:37 -07001635 proj_dir: If non-None, this is the directory the project is in. If None,
1636 we'll ask repo.
Doug Anderson14749562013-06-26 13:38:29 -07001637 commit_list: A list of commits to run hooks against. If None or empty list
1638 then we'll automatically get the list of commits that would be uploaded.
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001639 presubmit: A Boolean, True if the check is run as a git pre-submit script.
Ryan Cui1562fb82011-05-09 11:01:31 -07001640
1641 Returns:
1642 Boolean value of whether any errors were ecountered while running the hooks.
1643 """
Doug Anderson44a644f2011-11-02 10:37:37 -07001644 if proj_dir is None:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001645 proj_dirs = _run_command(
1646 ['repo', 'forall', project_name, '-c', 'pwd']).split()
David James2edd9002013-10-11 14:09:19 -07001647 if len(proj_dirs) == 0:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001648 print('%s cannot be found.' % project_name, file=sys.stderr)
David James2edd9002013-10-11 14:09:19 -07001649 print('Please specify a valid project.', file=sys.stderr)
1650 return True
1651 if len(proj_dirs) > 1:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001652 print('%s is associated with multiple directories.' % project_name,
David James2edd9002013-10-11 14:09:19 -07001653 file=sys.stderr)
1654 print('Please specify a directory to help disambiguate.', file=sys.stderr)
1655 return True
1656 proj_dir = proj_dirs[0]
Doug Anderson44a644f2011-11-02 10:37:37 -07001657
Ryan Cuiec4d6332011-05-02 14:15:25 -07001658 pwd = os.getcwd()
1659 # hooks assume they are run from the root of the project
1660 os.chdir(proj_dir)
1661
Alex Deymo643ac4c2015-09-03 10:40:50 -07001662 remote_branch = _run_command(['git', 'rev-parse', '--abbrev-ref',
1663 '--symbolic-full-name', '@{u}']).strip()
1664 if not remote_branch:
1665 print('Your project %s doesn\'t track any remote repo.' % project_name,
1666 file=sys.stderr)
1667 remote = None
1668 else:
1669 remote, _branch = remote_branch.split('/', 1)
1670
1671 project = Project(name=project_name, dir=proj_dir, remote=remote)
1672
Doug Anderson14749562013-06-26 13:38:29 -07001673 if not commit_list:
1674 try:
1675 commit_list = _get_commits()
1676 except VerifyException as e:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001677 PrintErrorForProject(project.name, HookFailure(str(e)))
Doug Anderson14749562013-06-26 13:38:29 -07001678 os.chdir(pwd)
1679 return True
Ryan Cuifa55df52011-05-06 11:16:55 -07001680
Alex Deymo643ac4c2015-09-03 10:40:50 -07001681 hooks = _get_project_hooks(project.name, presubmit)
Ryan Cui1562fb82011-05-09 11:01:31 -07001682 error_found = False
Ryan Cuifa55df52011-05-06 11:16:55 -07001683 for commit in commit_list:
Ryan Cui1562fb82011-05-09 11:01:31 -07001684 error_list = []
Ryan Cui9b651632011-05-11 11:38:58 -07001685 for hook in hooks:
Ryan Cui1562fb82011-05-09 11:01:31 -07001686 hook_error = hook(project, commit)
1687 if hook_error:
1688 error_list.append(hook_error)
1689 error_found = True
1690 if error_list:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001691 PrintErrorsForCommit(project.name, commit, _get_commit_desc(commit),
Ryan Cui1562fb82011-05-09 11:01:31 -07001692 error_list)
Don Garrettdba548a2011-05-05 15:17:14 -07001693
Ryan Cuiec4d6332011-05-02 14:15:25 -07001694 os.chdir(pwd)
Ryan Cui1562fb82011-05-09 11:01:31 -07001695 return error_found
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001696
Mike Frysingerae409522014-02-01 03:16:11 -05001697
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001698# Main
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -07001699
Ryan Cui1562fb82011-05-09 11:01:31 -07001700
Mike Frysingerae409522014-02-01 03:16:11 -05001701def main(project_list, worktree_list=None, **_kwargs):
Doug Anderson06456632012-01-05 11:02:14 -08001702 """Main function invoked directly by repo.
1703
1704 This function will exit directly upon error so that repo doesn't print some
1705 obscure error message.
1706
1707 Args:
1708 project_list: List of projects to run on.
David James2edd9002013-10-11 14:09:19 -07001709 worktree_list: A list of directories. It should be the same length as
1710 project_list, so that each entry in project_list matches with a directory
1711 in worktree_list. If None, we will attempt to calculate the directories
1712 automatically.
Doug Anderson06456632012-01-05 11:02:14 -08001713 kwargs: Leave this here for forward-compatibility.
1714 """
Ryan Cui1562fb82011-05-09 11:01:31 -07001715 found_error = False
David James2edd9002013-10-11 14:09:19 -07001716 if not worktree_list:
1717 worktree_list = [None] * len(project_list)
1718 for project, worktree in zip(project_list, worktree_list):
1719 if _run_project_hooks(project, proj_dir=worktree):
Ryan Cui1562fb82011-05-09 11:01:31 -07001720 found_error = True
1721
Mike Frysingerae409522014-02-01 03:16:11 -05001722 if found_error:
Ryan Cui1562fb82011-05-09 11:01:31 -07001723 msg = ('Preupload failed due to errors in project(s). HINTS:\n'
Ryan Cui9b651632011-05-11 11:38:58 -07001724 '- To disable some source style checks, and for other hints, see '
1725 '<checkout_dir>/src/repohooks/README\n'
1726 '- To upload only current project, run \'repo upload .\'')
Mike Frysinger09d6a3d2013-10-08 22:21:03 -04001727 print(msg, file=sys.stderr)
Don Garrettdba548a2011-05-05 15:17:14 -07001728 sys.exit(1)
Anush Elangovan63afad72011-03-23 00:41:27 -07001729
Ryan Cui1562fb82011-05-09 11:01:31 -07001730
Doug Anderson44a644f2011-11-02 10:37:37 -07001731def _identify_project(path):
1732 """Identify the repo project associated with the given path.
1733
1734 Returns:
1735 A string indicating what project is associated with the path passed in or
1736 a blank string upon failure.
1737 """
1738 return _run_command(['repo', 'forall', '.', '-c', 'echo ${REPO_PROJECT}'],
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001739 redirect_stderr=True, cwd=path).strip()
Doug Anderson44a644f2011-11-02 10:37:37 -07001740
1741
Mike Frysinger55f85b52014-12-18 14:45:21 -05001742def direct_main(argv):
Doug Anderson44a644f2011-11-02 10:37:37 -07001743 """Run hooks directly (outside of the context of repo).
1744
Doug Anderson44a644f2011-11-02 10:37:37 -07001745 Args:
Mike Frysinger55f85b52014-12-18 14:45:21 -05001746 argv: The command line args to process
Doug Anderson44a644f2011-11-02 10:37:37 -07001747
1748 Returns:
1749 0 if no pre-upload failures, 1 if failures.
1750
1751 Raises:
1752 BadInvocation: On some types of invocation errors.
1753 """
Mike Frysinger66142932014-12-18 14:55:57 -05001754 parser = commandline.ArgumentParser(description=__doc__)
1755 parser.add_argument('--dir', default=None,
1756 help='The directory that the project lives in. If not '
1757 'specified, use the git project root based on the cwd.')
1758 parser.add_argument('--project', default=None,
1759 help='The project repo path; this can affect how the '
1760 'hooks get run, since some hooks are project-specific. '
1761 'For chromite this is chromiumos/chromite. If not '
1762 'specified, the repo tool will be used to figure this '
1763 'out based on the dir.')
1764 parser.add_argument('--rerun-since', default=None,
1765 help='Rerun hooks on old commits since the given date. '
1766 'The date should match git log\'s concept of a date. '
1767 'e.g. 2012-06-20. This option is mutually exclusive '
1768 'with --pre-submit.')
1769 parser.add_argument('--pre-submit', action="store_true",
1770 help='Run the check against the pending commit. '
1771 'This option should be used at the \'git commit\' '
1772 'phase as opposed to \'repo upload\'. This option '
1773 'is mutually exclusive with --rerun-since.')
1774 parser.add_argument('commits', nargs='*',
1775 help='Check specific commits')
1776 opts = parser.parse_args(argv)
Doug Anderson44a644f2011-11-02 10:37:37 -07001777
Doug Anderson14749562013-06-26 13:38:29 -07001778 if opts.rerun_since:
Mike Frysinger66142932014-12-18 14:55:57 -05001779 if opts.commits:
Doug Anderson14749562013-06-26 13:38:29 -07001780 raise BadInvocation('Can\'t pass commits and use rerun-since: %s' %
Mike Frysinger66142932014-12-18 14:55:57 -05001781 ' '.join(opts.commits))
Doug Anderson14749562013-06-26 13:38:29 -07001782
1783 cmd = ['git', 'log', '--since="%s"' % opts.rerun_since, '--pretty=%H']
1784 all_commits = _run_command(cmd).splitlines()
1785 bot_commits = _run_command(cmd + ['--author=chrome-bot']).splitlines()
1786
1787 # Eliminate chrome-bot commits but keep ordering the same...
1788 bot_commits = set(bot_commits)
Mike Frysinger66142932014-12-18 14:55:57 -05001789 opts.commits = [c for c in all_commits if c not in bot_commits]
Doug Anderson14749562013-06-26 13:38:29 -07001790
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001791 if opts.pre_submit:
1792 raise BadInvocation('rerun-since and pre-submit can not be '
1793 'used together')
1794 if opts.pre_submit:
Mike Frysinger66142932014-12-18 14:55:57 -05001795 if opts.commits:
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001796 raise BadInvocation('Can\'t pass commits and use pre-submit: %s' %
Mike Frysinger66142932014-12-18 14:55:57 -05001797 ' '.join(opts.commits))
1798 opts.commits = [PRE_SUBMIT,]
Doug Anderson44a644f2011-11-02 10:37:37 -07001799
1800 # Check/normlaize git dir; if unspecified, we'll use the root of the git
1801 # project from CWD
1802 if opts.dir is None:
1803 git_dir = _run_command(['git', 'rev-parse', '--git-dir'],
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001804 redirect_stderr=True).strip()
Doug Anderson44a644f2011-11-02 10:37:37 -07001805 if not git_dir:
1806 raise BadInvocation('The current directory is not part of a git project.')
1807 opts.dir = os.path.dirname(os.path.abspath(git_dir))
1808 elif not os.path.isdir(opts.dir):
1809 raise BadInvocation('Invalid dir: %s' % opts.dir)
1810 elif not os.path.isdir(os.path.join(opts.dir, '.git')):
1811 raise BadInvocation('Not a git directory: %s' % opts.dir)
1812
1813 # Identify the project if it wasn't specified; this _requires_ the repo
1814 # tool to be installed and for the project to be part of a repo checkout.
1815 if not opts.project:
1816 opts.project = _identify_project(opts.dir)
1817 if not opts.project:
1818 raise BadInvocation("Repo couldn't identify the project of %s" % opts.dir)
1819
Doug Anderson14749562013-06-26 13:38:29 -07001820 found_error = _run_project_hooks(opts.project, proj_dir=opts.dir,
Mike Frysinger66142932014-12-18 14:55:57 -05001821 commit_list=opts.commits,
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001822 presubmit=opts.pre_submit)
Doug Anderson44a644f2011-11-02 10:37:37 -07001823 if found_error:
1824 return 1
1825 return 0
1826
1827
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -07001828if __name__ == '__main__':
Mike Frysinger55f85b52014-12-18 14:45:21 -05001829 sys.exit(direct_main(sys.argv[1:]))