blob: 5be3748cbe550d2b3bd742d8842b426dbce623f9 [file] [log] [blame]
Prathmesh Prabhuc5254652016-12-22 12:58:05 -08001#!/usr/bin/env python2
Mike Frysingerb7d552e2017-11-23 11:50:47 -05002# -*- coding: utf-8 -*-
Jon Salz98255932012-08-18 14:48:02 +08003# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07004# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
Mike Frysingerae409522014-02-01 03:16:11 -05007"""Presubmit checks to run when doing `repo upload`.
8
9You can add new checks by adding a functions to the HOOKS constants.
10"""
11
Mike Frysinger09d6a3d2013-10-08 22:21:03 -040012from __future__ import print_function
13
Filipe Brandenburger4b542b12015-10-09 12:46:31 -070014import argparse
Alex Deymo643ac4c2015-09-03 10:40:50 -070015import collections
Ryan Cui9b651632011-05-11 11:38:58 -070016import ConfigParser
Daniel Erate3ea3fc2015-02-13 15:27:52 -070017import fnmatch
Jon Salz3ee59de2012-08-18 13:54:22 +080018import functools
Dale Curtis2975c432011-05-03 17:25:20 -070019import json
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070020import os
Ryan Cuiec4d6332011-05-02 14:15:25 -070021import re
Mandeep Singh Bainesa7ffa4b2011-05-03 11:37:02 -070022import sys
Peter Ammon811f6702014-06-12 15:45:38 -070023import stat
Aviv Keshet5ac59522017-01-31 14:28:27 -080024import StringIO
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070025
Ryan Cui1562fb82011-05-09 11:01:31 -070026from errors import (VerifyException, HookFailure, PrintErrorForProject,
27 PrintErrorsForCommit)
Ryan Cuiec4d6332011-05-02 14:15:25 -070028
David Jamesc3b68b32013-04-03 09:17:03 -070029# If repo imports us, the __name__ will be __builtin__, and the wrapper will
30# be in $CHROMEOS_CHECKOUT/.repo/repo/main.py, so we need to go two directories
31# up. The same logic also happens to work if we're executed directly.
32if __name__ in ('__builtin__', '__main__'):
33 sys.path.insert(0, os.path.join(os.path.dirname(sys.argv[0]), '..', '..'))
34
Mike Frysinger66142932014-12-18 14:55:57 -050035from chromite.lib import commandline
Aviv Keshet5ac59522017-01-31 14:28:27 -080036from chromite.lib import constants
Rahul Chaudhry0e515342015-08-07 12:00:43 -070037from chromite.lib import cros_build_lib
Mike Frysingerd3bd32c2014-11-24 23:34:29 -050038from chromite.lib import git
Daniel Erata350fd32014-09-29 14:02:34 -070039from chromite.lib import osutils
David Jamesc3b68b32013-04-03 09:17:03 -070040from chromite.lib import patch
Mike Frysinger2ec70ed2014-08-17 19:28:34 -040041from chromite.licensing import licenses_lib
David Jamesc3b68b32013-04-03 09:17:03 -070042
Vadim Bendebury2b62d742014-06-22 13:14:51 -070043PRE_SUBMIT = 'pre-submit'
Ryan Cuiec4d6332011-05-02 14:15:25 -070044
45COMMON_INCLUDED_PATHS = [
Mike Frysingerae409522014-02-01 03:16:11 -050046 # C++ and friends
47 r".*\.c$", r".*\.cc$", r".*\.cpp$", r".*\.h$", r".*\.m$", r".*\.mm$",
48 r".*\.inl$", r".*\.asm$", r".*\.hxx$", r".*\.hpp$", r".*\.s$", r".*\.S$",
49 # Scripts
50 r".*\.js$", r".*\.py$", r".*\.sh$", r".*\.rb$", r".*\.pl$", r".*\.pm$",
51 # No extension at all, note that ALL CAPS files are black listed in
52 # COMMON_EXCLUDED_LIST below.
53 r"(^|.*[\\\/])[^.]+$",
54 # Other
55 r".*\.java$", r".*\.mk$", r".*\.am$",
Brian Norrisfdbac8e2016-06-16 11:09:05 -070056 r".*\.policy$", r".*\.conf$",
Ryan Cuiec4d6332011-05-02 14:15:25 -070057]
58
Ryan Cui1562fb82011-05-09 11:01:31 -070059
Ryan Cuiec4d6332011-05-02 14:15:25 -070060COMMON_EXCLUDED_PATHS = [
Daniel Erate3ea3fc2015-02-13 15:27:52 -070061 # For ebuild trees, ignore any caches and manifest data.
Mike Frysingerae409522014-02-01 03:16:11 -050062 r".*/Manifest$",
63 r".*/metadata/[^/]*cache[^/]*/[^/]+/[^/]+$",
Doug Anderson5bfb6792011-10-25 16:45:41 -070064
Daniel Erate3ea3fc2015-02-13 15:27:52 -070065 # Ignore profiles data (like overlay-tegra2/profiles).
Mike Frysinger94a670c2014-09-19 12:46:26 -040066 r"(^|.*/)overlay-.*/profiles/.*",
Mike Frysinger98638102014-08-28 00:15:08 -040067 r"^profiles/.*$",
68
C Shapiro8f90e9b2017-06-28 09:54:50 -060069 # Ignore config files in ebuild setup.
70 r"(^|.*/)overlay-.*/chromeos-base/chromeos-bsp.*/files/.*",
71 r"^chromeos-base/chromeos-bsp.*/files/.*",
72
Daniel Erate3ea3fc2015-02-13 15:27:52 -070073 # Ignore minified js and jquery.
Mike Frysingerae409522014-02-01 03:16:11 -050074 r".*\.min\.js",
75 r".*jquery.*\.js",
Mike Frysinger33a458d2014-03-03 17:00:51 -050076
77 # Ignore license files as the content is often taken verbatim.
Daniel Erate3ea3fc2015-02-13 15:27:52 -070078 r".*/licenses/.*",
Ryan Cuiec4d6332011-05-02 14:15:25 -070079]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070080
Ryan Cui1562fb82011-05-09 11:01:31 -070081
Ryan Cui9b651632011-05-11 11:38:58 -070082_CONFIG_FILE = 'PRESUBMIT.cfg'
83
84
Daniel Erate3ea3fc2015-02-13 15:27:52 -070085# File containing wildcards, one per line, matching files that should be
86# excluded from presubmit checks. Lines beginning with '#' are ignored.
87_IGNORE_FILE = '.presubmitignore'
88
89
Doug Anderson44a644f2011-11-02 10:37:37 -070090# Exceptions
91
92
93class BadInvocation(Exception):
94 """An Exception indicating a bad invocation of the program."""
95 pass
96
97
Ryan Cui1562fb82011-05-09 11:01:31 -070098# General Helpers
99
Sean Paulba01d402011-05-05 11:36:23 -0400100
Alex Deymo643ac4c2015-09-03 10:40:50 -0700101Project = collections.namedtuple('Project', ['name', 'dir', 'remote'])
102
103
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700104# pylint: disable=redefined-builtin
105def _run_command(cmd, cwd=None, input=None,
106 redirect_stderr=False, combine_stdout_stderr=False):
Doug Anderson44a644f2011-11-02 10:37:37 -0700107 """Executes the passed in command and returns raw stdout output.
108
109 Args:
110 cmd: The command to run; should be a list of strings.
111 cwd: The directory to switch to for running the command.
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700112 input: The data to pipe into this command through stdin. If a file object
113 or file descriptor, stdin will be connected directly to that.
114 redirect_stderr: Redirect stderr away from console.
115 combine_stdout_stderr: Combines stdout and stderr streams into stdout.
Doug Anderson44a644f2011-11-02 10:37:37 -0700116
117 Returns:
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700118 The stdout from the process (discards stderr and returncode).
Doug Anderson44a644f2011-11-02 10:37:37 -0700119 """
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700120 return cros_build_lib.RunCommand(cmd=cmd,
121 cwd=cwd,
122 print_cmd=False,
123 input=input,
124 stdout_to_pipe=True,
125 redirect_stderr=redirect_stderr,
126 combine_stdout_stderr=combine_stdout_stderr,
127 error_code_ok=True).output
128# pylint: enable=redefined-builtin
Ryan Cui72834d12011-05-05 14:51:33 -0700129
Ryan Cui1562fb82011-05-09 11:01:31 -0700130
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700131def _get_hooks_dir():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700132 """Returns the absolute path to the repohooks directory."""
Doug Anderson44a644f2011-11-02 10:37:37 -0700133 if __name__ == '__main__':
134 # Works when file is run on its own (__file__ is defined)...
135 return os.path.abspath(os.path.dirname(__file__))
136 else:
137 # We need to do this when we're run through repo. Since repo executes
138 # us with execfile(), we don't get __file__ defined.
139 cmd = ['repo', 'forall', 'chromiumos/repohooks', '-c', 'pwd']
140 return _run_command(cmd).strip()
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700141
Ryan Cui1562fb82011-05-09 11:01:31 -0700142
Ryan Cuiec4d6332011-05-02 14:15:25 -0700143def _match_regex_list(subject, expressions):
144 """Try to match a list of regular expressions to a string.
145
146 Args:
147 subject: The string to match regexes on
148 expressions: A list of regular expressions to check for matches with.
149
150 Returns:
151 Whether the passed in subject matches any of the passed in regexes.
152 """
153 for expr in expressions:
Mike Frysingerae409522014-02-01 03:16:11 -0500154 if re.search(expr, subject):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700155 return True
156 return False
157
Ryan Cui1562fb82011-05-09 11:01:31 -0700158
Mike Frysingerae409522014-02-01 03:16:11 -0500159def _filter_files(files, include_list, exclude_list=()):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700160 """Filter out files based on the conditions passed in.
161
162 Args:
163 files: list of filepaths to filter
164 include_list: list of regex that when matched with a file path will cause it
165 to be added to the output list unless the file is also matched with a
166 regex in the exclude_list.
167 exclude_list: list of regex that when matched with a file will prevent it
168 from being added to the output list, even if it is also matched with a
169 regex in the include_list.
170
171 Returns:
172 A list of filepaths that contain files matched in the include_list and not
173 in the exclude_list.
174 """
175 filtered = []
176 for f in files:
177 if (_match_regex_list(f, include_list) and
178 not _match_regex_list(f, exclude_list)):
179 filtered.append(f)
180 return filtered
181
Ryan Cuiec4d6332011-05-02 14:15:25 -0700182
183# Git Helpers
Ryan Cui1562fb82011-05-09 11:01:31 -0700184
185
Ryan Cui4725d952011-05-05 15:41:19 -0700186def _get_upstream_branch():
187 """Returns the upstream tracking branch of the current branch.
188
189 Raises:
190 Error if there is no tracking branch
191 """
192 current_branch = _run_command(['git', 'symbolic-ref', 'HEAD']).strip()
193 current_branch = current_branch.replace('refs/heads/', '')
194 if not current_branch:
Ryan Cui1562fb82011-05-09 11:01:31 -0700195 raise VerifyException('Need to be on a tracking branch')
Ryan Cui4725d952011-05-05 15:41:19 -0700196
197 cfg_option = 'branch.' + current_branch + '.%s'
198 full_upstream = _run_command(['git', 'config', cfg_option % 'merge']).strip()
199 remote = _run_command(['git', 'config', cfg_option % 'remote']).strip()
200 if not remote or not full_upstream:
Ryan Cui1562fb82011-05-09 11:01:31 -0700201 raise VerifyException('Need to be on a tracking branch')
Ryan Cui4725d952011-05-05 15:41:19 -0700202
203 return full_upstream.replace('heads', 'remotes/' + remote)
204
Ryan Cui1562fb82011-05-09 11:01:31 -0700205
Che-Liang Chiou5ce2d7b2013-03-22 18:47:55 -0700206def _get_patch(commit):
207 """Returns the patch for this commit."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700208 if commit == PRE_SUBMIT:
209 return _run_command(['git', 'diff', '--cached', 'HEAD'])
210 else:
211 return _run_command(['git', 'format-patch', '--stdout', '-1', commit])
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700212
Ryan Cui1562fb82011-05-09 11:01:31 -0700213
Jon Salz98255932012-08-18 14:48:02 +0800214def _try_utf8_decode(data):
215 """Attempts to decode a string as UTF-8.
216
217 Returns:
218 The decoded Unicode object, or the original string if parsing fails.
219 """
220 try:
221 return unicode(data, 'utf-8', 'strict')
222 except UnicodeDecodeError:
223 return data
224
225
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500226def _get_file_content(path, commit):
227 """Returns the content of a file at a specific commit.
228
229 We can't rely on the file as it exists in the filesystem as people might be
230 uploading a series of changes which modifies the file multiple times.
231
232 Note: The "content" of a symlink is just the target. So if you're expecting
233 a full file, you should check that first. One way to detect is that the
234 content will not have any newlines.
235 """
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700236 if commit == PRE_SUBMIT:
237 return _run_command(['git', 'diff', 'HEAD', path])
238 else:
239 return _run_command(['git', 'show', '%s:%s' % (commit, path)])
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500240
241
Mike Frysingerae409522014-02-01 03:16:11 -0500242def _get_file_diff(path, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700243 """Returns a list of (linenum, lines) tuples that the commit touched."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700244 if commit == PRE_SUBMIT:
Prathmesh Prabhua9de1722016-12-22 14:56:40 -0800245 command = ['git', 'diff', '-p', '--pretty=format:', '--no-ext-diff', 'HEAD',
246 path]
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700247 else:
Prathmesh Prabhua9de1722016-12-22 14:56:40 -0800248 command = ['git', 'show', '-p', '--pretty=format:', '--no-ext-diff', commit,
249 path]
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700250 output = _run_command(command)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700251
252 new_lines = []
253 line_num = 0
254 for line in output.splitlines():
255 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
256 if m:
257 line_num = int(m.groups(1)[0])
258 continue
259 if line.startswith('+') and not line.startswith('++'):
Jon Salz98255932012-08-18 14:48:02 +0800260 new_lines.append((line_num, _try_utf8_decode(line[1:])))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700261 if not line.startswith('-'):
262 line_num += 1
263 return new_lines
264
Ryan Cui1562fb82011-05-09 11:01:31 -0700265
Daniel Erate3ea3fc2015-02-13 15:27:52 -0700266def _get_ignore_wildcards(directory, cache):
267 """Get wildcards listed in a directory's _IGNORE_FILE.
268
269 Args:
270 directory: A string containing a directory path.
271 cache: A dictionary (opaque to caller) caching previously-read wildcards.
272
273 Returns:
274 A list of wildcards from _IGNORE_FILE or an empty list if _IGNORE_FILE
275 wasn't present.
276 """
277 # In the cache, keys are directories and values are lists of wildcards from
278 # _IGNORE_FILE within those directories (and empty if no file was present).
279 if directory not in cache:
280 wildcards = []
281 dotfile_path = os.path.join(directory, _IGNORE_FILE)
282 if os.path.exists(dotfile_path):
283 # TODO(derat): Consider using _get_file_content() to get the file as of
284 # this commit instead of the on-disk version. This may have a noticeable
285 # performance impact, as each call to _get_file_content() runs git.
286 with open(dotfile_path, 'r') as dotfile:
287 for line in dotfile.readlines():
288 line = line.strip()
289 if line.startswith('#'):
290 continue
291 if line.endswith('/'):
292 line += '*'
293 wildcards.append(line)
294 cache[directory] = wildcards
295
296 return cache[directory]
297
298
299def _path_is_ignored(path, cache):
300 """Check whether a path is ignored by _IGNORE_FILE.
301
302 Args:
303 path: A string containing a path.
304 cache: A dictionary (opaque to caller) caching previously-read wildcards.
305
306 Returns:
307 True if a file named _IGNORE_FILE in one of the passed-in path's parent
308 directories contains a wildcard matching the path.
309 """
310 # Skip ignore files.
311 if os.path.basename(path) == _IGNORE_FILE:
312 return True
313
314 path = os.path.abspath(path)
315 base = os.getcwd()
316
317 prefix = os.path.dirname(path)
318 while prefix.startswith(base):
319 rel_path = path[len(prefix) + 1:]
320 for wildcard in _get_ignore_wildcards(prefix, cache):
321 if fnmatch.fnmatch(rel_path, wildcard):
322 return True
323 prefix = os.path.dirname(prefix)
324
325 return False
326
327
Mike Frysinger292b45d2014-11-25 01:17:10 -0500328def _get_affected_files(commit, include_deletes=False, relative=False,
329 include_symlinks=False, include_adds=True,
Daniel Erate3ea3fc2015-02-13 15:27:52 -0700330 full_details=False, use_ignore_files=True):
Peter Ammon811f6702014-06-12 15:45:38 -0700331 """Returns list of file paths that were modified/added, excluding symlinks.
332
333 Args:
334 commit: The commit
335 include_deletes: If true, we'll include deleted files in the result
336 relative: Whether to return relative or full paths to files
Mike Frysinger292b45d2014-11-25 01:17:10 -0500337 include_symlinks: If true, we'll include symlinks in the result
338 include_adds: If true, we'll include new files in the result
339 full_details: If False, return filenames, else return structured results.
Daniel Erate3ea3fc2015-02-13 15:27:52 -0700340 use_ignore_files: Whether we ignore files matched by _IGNORE_FILE files.
Peter Ammon811f6702014-06-12 15:45:38 -0700341
342 Returns:
343 A list of modified/added (and perhaps deleted) files
344 """
Mike Frysinger292b45d2014-11-25 01:17:10 -0500345 if not relative and full_details:
346 raise ValueError('full_details only supports relative paths currently')
347
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700348 if commit == PRE_SUBMIT:
349 return _run_command(['git', 'diff-index', '--cached',
350 '--name-only', 'HEAD']).split()
Mike Frysingerd3bd32c2014-11-24 23:34:29 -0500351
352 path = os.getcwd()
353 files = git.RawDiff(path, '%s^!' % commit)
354
355 # Filter out symlinks.
Mike Frysinger292b45d2014-11-25 01:17:10 -0500356 if not include_symlinks:
357 files = [x for x in files if not stat.S_ISLNK(int(x.dst_mode, 8))]
Mike Frysingerd3bd32c2014-11-24 23:34:29 -0500358
359 if not include_deletes:
360 files = [x for x in files if x.status != 'D']
361
Mike Frysinger292b45d2014-11-25 01:17:10 -0500362 if not include_adds:
363 files = [x for x in files if x.status != 'A']
364
Daniel Erate3ea3fc2015-02-13 15:27:52 -0700365 if use_ignore_files:
366 cache = {}
367 is_ignored = lambda x: _path_is_ignored(x.dst_file or x.src_file, cache)
368 files = [x for x in files if not is_ignored(x)]
369
Mike Frysinger292b45d2014-11-25 01:17:10 -0500370 if full_details:
371 # Caller wants the raw objects to parse status/etc... themselves.
Mike Frysingerd3bd32c2014-11-24 23:34:29 -0500372 return files
373 else:
Mike Frysinger292b45d2014-11-25 01:17:10 -0500374 # Caller only cares about filenames.
375 files = [x.dst_file if x.dst_file else x.src_file for x in files]
376 if relative:
377 return files
378 else:
379 return [os.path.join(path, x) for x in files]
Peter Ammon811f6702014-06-12 15:45:38 -0700380
381
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700382def _get_commits():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700383 """Returns a list of commits for this review."""
Ryan Cui4725d952011-05-05 15:41:19 -0700384 cmd = ['git', 'log', '%s..' % _get_upstream_branch(), '--format=%H']
Ryan Cui72834d12011-05-05 14:51:33 -0700385 return _run_command(cmd).split()
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700386
Ryan Cui1562fb82011-05-09 11:01:31 -0700387
Ryan Cuiec4d6332011-05-02 14:15:25 -0700388def _get_commit_desc(commit):
389 """Returns the full commit message of a commit."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700390 if commit == PRE_SUBMIT:
391 return ''
Sean Paul23a2c582011-05-06 13:10:44 -0400392 return _run_command(['git', 'log', '--format=%s%n%n%b', commit + '^!'])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700393
394
Prathmesh Prabhuc5254652016-12-22 12:58:05 -0800395def _check_lines_in_diff(commit, files, check_callable, error_description):
396 """Checks given file for errors via the given check.
397
398 This is a convenience function for common per-line checks. It goes through all
399 files and returns a HookFailure with the error description listing all the
400 failures.
401
402 Args:
403 commit: The commit we're working on.
404 files: The files to check.
405 check_callable: A callable that takes a line and returns True if this line
406 _fails_ the check.
407 error_description: A string describing the error.
408 """
409 errors = []
410 for afile in files:
411 for line_num, line in _get_file_diff(afile, commit):
412 if check_callable(line):
413 errors.append('%s, line %s' % (afile, line_num))
414 if errors:
415 return HookFailure(error_description, errors)
416
417
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900418def _parse_common_inclusion_options(options):
419 """Parses common hook options for including/excluding files.
420
421 Args:
422 options: Option string list.
423
424 Returns:
425 (included, excluded) where each one is a list of regex strings.
426 """
427 parser = argparse.ArgumentParser()
428 parser.add_argument('--exclude_regex', action='append')
429 parser.add_argument('--include_regex', action='append')
430 opts = parser.parse_args(options)
431 included = opts.include_regex or []
432 excluded = opts.exclude_regex or []
433 return included, excluded
434
435
Ryan Cuiec4d6332011-05-02 14:15:25 -0700436# Common Hooks
437
Ryan Cui1562fb82011-05-09 11:01:31 -0700438
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900439def _check_no_long_lines(_project, commit, options=()):
Mike Frysinger55f85b52014-12-18 14:45:21 -0500440 """Checks there are no lines longer than MAX_LEN in any of the text files."""
441
Ryan Cuiec4d6332011-05-02 14:15:25 -0700442 MAX_LEN = 80
Jon Salz98255932012-08-18 14:48:02 +0800443 SKIP_REGEXP = re.compile('|'.join([
444 r'https?://',
445 r'^#\s*(define|include|import|pragma|if|endif)\b']))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700446
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900447 included, excluded = _parse_common_inclusion_options(options)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700448 files = _filter_files(_get_affected_files(commit),
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900449 included + COMMON_INCLUDED_PATHS,
450 excluded + COMMON_EXCLUDED_PATHS)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700451
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900452 errors = []
Ryan Cuiec4d6332011-05-02 14:15:25 -0700453 for afile in files:
454 for line_num, line in _get_file_diff(afile, commit):
455 # Allow certain lines to exceed the maxlen rule.
Mike Frysingerae409522014-02-01 03:16:11 -0500456 if len(line) <= MAX_LEN or SKIP_REGEXP.search(line):
Jon Salz98255932012-08-18 14:48:02 +0800457 continue
458
459 errors.append('%s, line %s, %s chars' % (afile, line_num, len(line)))
460 if len(errors) == 5: # Just show the first 5 errors.
461 break
Ryan Cuiec4d6332011-05-02 14:15:25 -0700462
463 if errors:
464 msg = 'Found lines longer than %s characters (first 5 shown):' % MAX_LEN
Ryan Cui1562fb82011-05-09 11:01:31 -0700465 return HookFailure(msg, errors)
466
Ryan Cuiec4d6332011-05-02 14:15:25 -0700467
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900468def _check_no_stray_whitespace(_project, commit, options=()):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700469 """Checks that there is no stray whitespace at source lines end."""
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900470 included, excluded = _parse_common_inclusion_options(options)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700471 files = _filter_files(_get_affected_files(commit),
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900472 included + COMMON_INCLUDED_PATHS,
473 excluded + COMMON_EXCLUDED_PATHS)
Prathmesh Prabhuc5254652016-12-22 12:58:05 -0800474 return _check_lines_in_diff(commit, files,
475 lambda line: line.rstrip() != line,
476 'Found line ending with white space in:')
Ryan Cui1562fb82011-05-09 11:01:31 -0700477
Ryan Cuiec4d6332011-05-02 14:15:25 -0700478
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900479def _check_no_tabs(_project, commit, options=()):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700480 """Checks there are no unexpanded tabs."""
Mike Frysingercd134512017-10-26 04:36:33 -0400481 # Don't add entire repos here. Update the PRESUBMIT.cfg in each repo instead.
482 # We only whitelist known specific filetypes here that show up in all repos.
Ryan Cuiec4d6332011-05-02 14:15:25 -0700483 TAB_OK_PATHS = [
Ryan Cuiec4d6332011-05-02 14:15:25 -0700484 r".*\.ebuild$",
485 r".*\.eclass$",
Elly Jones5ab34192011-11-15 14:57:06 -0500486 r".*/[M|m]akefile$",
487 r".*\.mk$"
Ryan Cuiec4d6332011-05-02 14:15:25 -0700488 ]
489
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900490 included, excluded = _parse_common_inclusion_options(options)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700491 files = _filter_files(_get_affected_files(commit),
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900492 included + COMMON_INCLUDED_PATHS,
493 excluded + COMMON_EXCLUDED_PATHS + TAB_OK_PATHS)
Prathmesh Prabhuc5254652016-12-22 12:58:05 -0800494 return _check_lines_in_diff(commit, files,
495 lambda line: '\t' in line,
496 'Found a tab character in:')
Ryan Cuiec4d6332011-05-02 14:15:25 -0700497
Prathmesh Prabhuc5254652016-12-22 12:58:05 -0800498
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900499def _check_tabbed_indents(_project, commit, options=()):
Prathmesh Prabhuc5254652016-12-22 12:58:05 -0800500 """Checks that indents use tabs only."""
501 TABS_REQUIRED_PATHS = [
502 r".*\.ebuild$",
503 r".*\.eclass$",
504 ]
505 LEADING_SPACE_RE = re.compile('[\t]* ')
506
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900507 included, excluded = _parse_common_inclusion_options(options)
Prathmesh Prabhuc5254652016-12-22 12:58:05 -0800508 files = _filter_files(_get_affected_files(commit),
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900509 included + TABS_REQUIRED_PATHS,
510 excluded + COMMON_EXCLUDED_PATHS)
Prathmesh Prabhuc5254652016-12-22 12:58:05 -0800511 return _check_lines_in_diff(
512 commit, files,
513 lambda line: LEADING_SPACE_RE.match(line) is not None,
514 'Found a space in indentation (must be all tabs):')
Ryan Cui1562fb82011-05-09 11:01:31 -0700515
Ryan Cuiec4d6332011-05-02 14:15:25 -0700516
Rahul Chaudhry09f61372015-07-31 17:14:26 -0700517def _check_gofmt(_project, commit):
518 """Checks that Go files are formatted with gofmt."""
519 errors = []
520 files = _filter_files(_get_affected_files(commit, relative=True),
521 [r'\.go$'])
522
523 for gofile in files:
524 contents = _get_file_content(gofile, commit)
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700525 output = _run_command(cmd=['gofmt', '-l'], input=contents,
526 combine_stdout_stderr=True)
Rahul Chaudhry09f61372015-07-31 17:14:26 -0700527 if output:
528 errors.append(gofile)
529 if errors:
530 return HookFailure('Files not formatted with gofmt:', errors)
531
532
Mike Frysingerae409522014-02-01 03:16:11 -0500533def _check_change_has_test_field(_project, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700534 """Check for a non-empty 'TEST=' field in the commit message."""
David McMahon8f6553e2011-06-10 15:46:36 -0700535 TEST_RE = r'\nTEST=\S+'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700536
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700537 if not re.search(TEST_RE, _get_commit_desc(commit)):
Ryan Cui1562fb82011-05-09 11:01:31 -0700538 msg = 'Changelist description needs TEST field (after first line)'
539 return HookFailure(msg)
540
Ryan Cuiec4d6332011-05-02 14:15:25 -0700541
Mike Frysingerae409522014-02-01 03:16:11 -0500542def _check_change_has_valid_cq_depend(_project, commit):
David Jamesc3b68b32013-04-03 09:17:03 -0700543 """Check for a correctly formatted CQ-DEPEND field in the commit message."""
544 msg = 'Changelist has invalid CQ-DEPEND target.'
545 example = 'Example: CQ-DEPEND=CL:1234, CL:2345'
546 try:
547 patch.GetPaladinDeps(_get_commit_desc(commit))
548 except ValueError as ex:
549 return HookFailure(msg, [example, str(ex)])
550
551
Bernie Thompsonf8fea992016-01-14 10:27:18 -0800552def _check_change_is_contribution(_project, commit):
553 """Check that the change is a contribution."""
554 NO_CONTRIB = 'not a contribution'
555 if NO_CONTRIB in _get_commit_desc(commit).lower():
556 msg = ('Changelist is not a contribution, this cannot be accepted.\n'
557 'Please remove the "%s" text from the commit message.') % NO_CONTRIB
558 return HookFailure(msg)
559
560
Alex Deymo643ac4c2015-09-03 10:40:50 -0700561def _check_change_has_bug_field(project, commit):
David McMahon8f6553e2011-06-10 15:46:36 -0700562 """Check for a correctly formatted 'BUG=' field in the commit message."""
David James5c0073d2013-04-03 08:48:52 -0700563 OLD_BUG_RE = r'\nBUG=.*chromium-os'
564 if re.search(OLD_BUG_RE, _get_commit_desc(commit)):
565 msg = ('The chromium-os bug tracker is now deprecated. Please use\n'
566 'the chromium tracker in your BUG= line now.')
567 return HookFailure(msg)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700568
Alex Deymo643ac4c2015-09-03 10:40:50 -0700569 # Android internal and external projects use "Bug: " to track bugs in
570 # buganizer.
571 BUG_COLON_REMOTES = (
572 'aosp',
573 'goog',
574 )
575 if project.remote in BUG_COLON_REMOTES:
576 BUG_RE = r'\nBug: ?([Nn]one|\d+)'
577 if not re.search(BUG_RE, _get_commit_desc(commit)):
578 msg = ('Changelist description needs BUG field (after first line):\n'
579 'Bug: 9999 (for buganizer)\n'
580 'BUG=None')
581 return HookFailure(msg)
582 else:
Jorge Lucangeli Obesdce214e2017-10-25 15:04:39 -0400583 BUG_RE = r'\nBUG=([Nn]one|(chromium|b):\d+)'
Alex Deymo643ac4c2015-09-03 10:40:50 -0700584 if not re.search(BUG_RE, _get_commit_desc(commit)):
585 msg = ('Changelist description needs BUG field (after first line):\n'
Alex Deymo643ac4c2015-09-03 10:40:50 -0700586 'BUG=chromium:9999 (for public tracker)\n'
Alex Deymo643ac4c2015-09-03 10:40:50 -0700587 'BUG=b:9999 (for buganizer)\n'
588 'BUG=None')
589 return HookFailure(msg)
Ryan Cui1562fb82011-05-09 11:01:31 -0700590
Ryan Cuiec4d6332011-05-02 14:15:25 -0700591
Mike Frysinger292b45d2014-11-25 01:17:10 -0500592def _check_for_uprev(project, commit, project_top=None):
Doug Anderson42b8a052013-06-26 10:45:36 -0700593 """Check that we're not missing a revbump of an ebuild in the given commit.
594
595 If the given commit touches files in a directory that has ebuilds somewhere
596 up the directory hierarchy, it's very likely that we need an ebuild revbump
597 in order for those changes to take effect.
598
599 It's not totally trivial to detect a revbump, so at least detect that an
600 ebuild with a revision number in it was touched. This should handle the
601 common case where we use a symlink to do the revbump.
602
603 TODO: it would be nice to enhance this hook to:
604 * Handle cases where people revbump with a slightly different syntax. I see
605 one ebuild (puppy) that revbumps with _pN. This is a false positive.
606 * Catches cases where people aren't using symlinks for revbumps. If they
607 edit a revisioned file directly (and are expected to rename it for revbump)
608 we'll miss that. Perhaps we could detect that the file touched is a
609 symlink?
610
611 If a project doesn't use symlinks we'll potentially miss a revbump, but we're
612 still better off than without this check.
613
614 Args:
Alex Deymo643ac4c2015-09-03 10:40:50 -0700615 project: The Project to look at
Doug Anderson42b8a052013-06-26 10:45:36 -0700616 commit: The commit to look at
Mike Frysinger292b45d2014-11-25 01:17:10 -0500617 project_top: Top dir to process commits in
Doug Anderson42b8a052013-06-26 10:45:36 -0700618
619 Returns:
620 A HookFailure or None.
621 """
Mike Frysinger011af942014-01-17 16:12:22 -0500622 # If this is the portage-stable overlay, then ignore the check. It's rare
623 # that we're doing anything other than importing files from upstream, so
624 # forcing a rev bump makes no sense.
625 whitelist = (
626 'chromiumos/overlays/portage-stable',
627 )
Alex Deymo643ac4c2015-09-03 10:40:50 -0700628 if project.name in whitelist:
Mike Frysinger011af942014-01-17 16:12:22 -0500629 return None
630
Mike Frysinger292b45d2014-11-25 01:17:10 -0500631 def FinalName(obj):
632 # If the file is being deleted, then the dst_file is not set.
633 if obj.dst_file is None:
634 return obj.src_file
635 else:
636 return obj.dst_file
637
638 affected_path_objs = _get_affected_files(
639 commit, include_deletes=True, include_symlinks=True, relative=True,
640 full_details=True)
Doug Anderson42b8a052013-06-26 10:45:36 -0700641
642 # Don't yell about changes to whitelisted files...
Aviv Keshet272f2e52016-04-25 14:49:44 -0700643 whitelist = ('ChangeLog', 'Manifest', 'metadata.xml', 'COMMIT-QUEUE.ini')
Mike Frysinger292b45d2014-11-25 01:17:10 -0500644 affected_path_objs = [x for x in affected_path_objs
645 if os.path.basename(FinalName(x)) not in whitelist]
646 if not affected_path_objs:
Doug Anderson42b8a052013-06-26 10:45:36 -0700647 return None
648
649 # If we've touched any file named with a -rN.ebuild then we'll say we're
650 # OK right away. See TODO above about enhancing this.
Mike Frysinger292b45d2014-11-25 01:17:10 -0500651 touched_revved_ebuild = any(re.search(r'-r\d*\.ebuild$', FinalName(x))
652 for x in affected_path_objs)
Doug Anderson42b8a052013-06-26 10:45:36 -0700653 if touched_revved_ebuild:
654 return None
655
Mike Frysinger292b45d2014-11-25 01:17:10 -0500656 # If we're creating new ebuilds from scratch, then we don't need an uprev.
657 # Find all the dirs that new ebuilds and ignore their files/.
658 ebuild_dirs = [os.path.dirname(FinalName(x)) + '/' for x in affected_path_objs
659 if FinalName(x).endswith('.ebuild') and x.status == 'A']
660 affected_path_objs = [obj for obj in affected_path_objs
661 if not any(FinalName(obj).startswith(x)
662 for x in ebuild_dirs)]
663 if not affected_path_objs:
664 return
665
Doug Anderson42b8a052013-06-26 10:45:36 -0700666 # We want to examine the current contents of all directories that are parents
667 # of files that were touched (up to the top of the project).
668 #
669 # ...note: we use the current directory contents even though it may have
670 # changed since the commit we're looking at. This is just a heuristic after
671 # all. Worst case we don't flag a missing revbump.
Mike Frysinger292b45d2014-11-25 01:17:10 -0500672 if project_top is None:
673 project_top = os.getcwd()
Doug Anderson42b8a052013-06-26 10:45:36 -0700674 dirs_to_check = set([project_top])
Mike Frysinger292b45d2014-11-25 01:17:10 -0500675 for obj in affected_path_objs:
676 path = os.path.join(project_top, os.path.dirname(FinalName(obj)))
Doug Anderson42b8a052013-06-26 10:45:36 -0700677 while os.path.exists(path) and not os.path.samefile(path, project_top):
678 dirs_to_check.add(path)
679 path = os.path.dirname(path)
680
681 # Look through each directory. If it's got an ebuild in it then we'll
682 # consider this as a case when we need a revbump.
Gwendal Grignoua3086c32014-12-09 11:17:22 -0800683 affected_paths = set(os.path.join(project_top, FinalName(x))
684 for x in affected_path_objs)
Doug Anderson42b8a052013-06-26 10:45:36 -0700685 for dir_path in dirs_to_check:
686 contents = os.listdir(dir_path)
687 ebuilds = [os.path.join(dir_path, path)
688 for path in contents if path.endswith('.ebuild')]
689 ebuilds_9999 = [path for path in ebuilds if path.endswith('-9999.ebuild')]
690
C Shapiroae157ae2017-09-18 16:24:03 -0600691 affected_paths_under_9999_ebuilds = set()
692 for affected_path in affected_paths:
693 for ebuild_9999 in ebuilds_9999:
694 ebuild_dir = os.path.dirname(ebuild_9999)
695 if affected_path.startswith(ebuild_dir):
696 affected_paths_under_9999_ebuilds.add(affected_path)
697
698 # If every file changed exists under a 9999 ebuild, then skip
699 if len(affected_paths_under_9999_ebuilds) == len(affected_paths):
700 continue
701
Doug Anderson42b8a052013-06-26 10:45:36 -0700702 # If the -9999.ebuild file was touched the bot will uprev for us.
703 # ...we'll use a simple intersection here as a heuristic...
Mike Frysinger292b45d2014-11-25 01:17:10 -0500704 if set(ebuilds_9999) & affected_paths:
Doug Anderson42b8a052013-06-26 10:45:36 -0700705 continue
706
707 if ebuilds:
Mike Frysinger292b45d2014-11-25 01:17:10 -0500708 return HookFailure('Changelist probably needs a revbump of an ebuild, '
709 'or a -r1.ebuild symlink if this is a new ebuild:\n'
710 '%s' % dir_path)
Doug Anderson42b8a052013-06-26 10:45:36 -0700711
712 return None
713
714
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500715def _check_ebuild_eapi(project, commit):
716 """Make sure we have people use EAPI=4 or newer with custom ebuilds.
717
718 We want to get away from older EAPI's as it makes life confusing and they
719 have less builtin error checking.
720
721 Args:
Alex Deymo643ac4c2015-09-03 10:40:50 -0700722 project: The Project to look at
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500723 commit: The commit to look at
724
725 Returns:
726 A HookFailure or None.
727 """
728 # If this is the portage-stable overlay, then ignore the check. It's rare
Mike Frysingercd6adfc2014-02-06 01:03:56 -0500729 # that we're doing anything other than importing files from upstream, and
730 # we shouldn't be rewriting things fundamentally anyways.
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500731 whitelist = (
732 'chromiumos/overlays/portage-stable',
733 )
Alex Deymo643ac4c2015-09-03 10:40:50 -0700734 if project.name in whitelist:
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500735 return None
736
737 BAD_EAPIS = ('0', '1', '2', '3')
738
739 get_eapi = re.compile(r'^\s*EAPI=[\'"]?([^\'"]+)')
740
741 ebuilds_re = [r'\.ebuild$']
742 ebuilds = _filter_files(_get_affected_files(commit, relative=True),
743 ebuilds_re)
744 bad_ebuilds = []
745
746 for ebuild in ebuilds:
747 # If the ebuild does not specify an EAPI, it defaults to 0.
748 eapi = '0'
749
750 lines = _get_file_content(ebuild, commit).splitlines()
751 if len(lines) == 1:
752 # This is most likely a symlink, so skip it entirely.
753 continue
754
755 for line in lines:
756 m = get_eapi.match(line)
757 if m:
758 # Once we hit the first EAPI line in this ebuild, stop processing.
759 # The spec requires that there only be one and it be first, so
760 # checking all possible values is pointless. We also assume that
761 # it's "the" EAPI line and not something in the middle of a heredoc.
762 eapi = m.group(1)
763 break
764
765 if eapi in BAD_EAPIS:
766 bad_ebuilds.append((ebuild, eapi))
767
768 if bad_ebuilds:
769 # pylint: disable=C0301
770 url = 'http://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/upgrade-ebuild-eapis'
771 # pylint: enable=C0301
772 return HookFailure(
Mike Frysingercd6adfc2014-02-06 01:03:56 -0500773 'These ebuilds are using old EAPIs. If these are imported from\n'
774 'Gentoo, then you may ignore and upload once with the --no-verify\n'
775 'flag. Otherwise, please update to 4 or newer.\n'
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500776 '\t%s\n'
777 'See this guide for more details:\n%s\n' %
778 ('\n\t'.join(['%s: EAPI=%s' % x for x in bad_ebuilds]), url))
779
780
Mike Frysinger89bdb852014-02-01 05:26:26 -0500781def _check_ebuild_keywords(_project, commit):
Mike Frysingerc51ece72014-01-17 16:23:40 -0500782 """Make sure we use the new style KEYWORDS when possible in ebuilds.
783
784 If an ebuild generally does not care about the arch it is running on, then
785 ebuilds should flag it with one of:
786 KEYWORDS="*" # A stable ebuild.
787 KEYWORDS="~*" # An unstable ebuild.
788 KEYWORDS="-* ..." # Is known to only work on specific arches.
789
790 Args:
Alex Deymo643ac4c2015-09-03 10:40:50 -0700791 project: The Project to look at
Mike Frysingerc51ece72014-01-17 16:23:40 -0500792 commit: The commit to look at
793
794 Returns:
795 A HookFailure or None.
796 """
797 WHITELIST = set(('*', '-*', '~*'))
798
799 get_keywords = re.compile(r'^\s*KEYWORDS="(.*)"')
800
Mike Frysinger89bdb852014-02-01 05:26:26 -0500801 ebuilds_re = [r'\.ebuild$']
802 ebuilds = _filter_files(_get_affected_files(commit, relative=True),
803 ebuilds_re)
804
Mike Frysinger8d42d742014-09-22 15:50:21 -0400805 bad_ebuilds = []
Mike Frysingerc51ece72014-01-17 16:23:40 -0500806 for ebuild in ebuilds:
Mike Frysinger5c9e58d2014-09-09 03:32:50 -0400807 # We get the full content rather than a diff as the latter does not work
808 # on new files (like when adding new ebuilds).
809 lines = _get_file_content(ebuild, commit).splitlines()
810 for line in lines:
Mike Frysingerc51ece72014-01-17 16:23:40 -0500811 m = get_keywords.match(line)
812 if m:
813 keywords = set(m.group(1).split())
814 if not keywords or WHITELIST - keywords != WHITELIST:
815 continue
816
Mike Frysinger8d42d742014-09-22 15:50:21 -0400817 bad_ebuilds.append(ebuild)
818
819 if bad_ebuilds:
820 return HookFailure(
821 '%s\n'
822 'Please update KEYWORDS to use a glob:\n'
823 'If the ebuild should be marked stable (normal for non-9999 ebuilds):\n'
824 ' KEYWORDS="*"\n'
825 'If the ebuild should be marked unstable (normal for '
826 'cros-workon / 9999 ebuilds):\n'
827 ' KEYWORDS="~*"\n'
Mike Frysingerde8efea2015-05-17 03:42:26 -0400828 'If the ebuild needs to be marked for only specific arches, '
Mike Frysinger8d42d742014-09-22 15:50:21 -0400829 'then use -* like so:\n'
830 ' KEYWORDS="-* arm ..."\n' % '\n* '.join(bad_ebuilds))
Mike Frysingerc51ece72014-01-17 16:23:40 -0500831
832
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800833def _check_ebuild_licenses(_project, commit):
834 """Check if the LICENSE field in the ebuild is correct."""
Brian Norris7a610e82016-02-17 12:24:54 -0800835 affected_paths = _get_affected_files(commit, relative=True)
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800836 touched_ebuilds = [x for x in affected_paths if x.endswith('.ebuild')]
837
838 # A list of licenses to ignore for now.
Yu-Ju Hongc0963fa2014-03-03 12:36:52 -0800839 LICENSES_IGNORE = ['||', '(', ')']
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800840
841 for ebuild in touched_ebuilds:
842 # Skip virutal packages.
843 if ebuild.split('/')[-3] == 'virtual':
844 continue
845
846 try:
Brian Norris7a610e82016-02-17 12:24:54 -0800847 ebuild_content = _get_file_content(ebuild, commit)
848 license_types = licenses_lib.GetLicenseTypesFromEbuild(ebuild_content)
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800849 except ValueError as e:
850 return HookFailure(e.message, [ebuild])
851
852 # Also ignore licenses ending with '?'
853 for license_type in [x for x in license_types
854 if x not in LICENSES_IGNORE and not x.endswith('?')]:
855 try:
Mike Frysinger2ec70ed2014-08-17 19:28:34 -0400856 licenses_lib.Licensing.FindLicenseType(license_type)
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800857 except AssertionError as e:
858 return HookFailure(e.message, [ebuild])
859
860
Mike Frysingercd363c82014-02-01 05:20:18 -0500861def _check_ebuild_virtual_pv(project, commit):
862 """Enforce the virtual PV policies."""
863 # If this is the portage-stable overlay, then ignore the check.
864 # We want to import virtuals as-is from upstream Gentoo.
865 whitelist = (
866 'chromiumos/overlays/portage-stable',
867 )
Alex Deymo643ac4c2015-09-03 10:40:50 -0700868 if project.name in whitelist:
Mike Frysingercd363c82014-02-01 05:20:18 -0500869 return None
870
871 # We assume the repo name is the same as the dir name on disk.
872 # It would be dumb to not have them match though.
Alex Deymo643ac4c2015-09-03 10:40:50 -0700873 project_base = os.path.basename(project.name)
Mike Frysingercd363c82014-02-01 05:20:18 -0500874
875 is_variant = lambda x: x.startswith('overlay-variant-')
876 is_board = lambda x: x.startswith('overlay-')
877 is_private = lambda x: x.endswith('-private')
878
879 get_pv = re.compile(r'(.*?)virtual/([^/]+)/\2-([^/]*)\.ebuild$')
880
881 ebuilds_re = [r'\.ebuild$']
882 ebuilds = _filter_files(_get_affected_files(commit, relative=True),
883 ebuilds_re)
884 bad_ebuilds = []
885
886 for ebuild in ebuilds:
887 m = get_pv.match(ebuild)
888 if m:
889 overlay = m.group(1)
890 if not overlay or not is_board(overlay):
Alex Deymo643ac4c2015-09-03 10:40:50 -0700891 overlay = project_base
Mike Frysingercd363c82014-02-01 05:20:18 -0500892
893 pv = m.group(3).split('-', 1)[0]
894
Bernie Thompsone5ee1822016-01-12 14:22:23 -0800895 # Virtual versions >= 4 are special cases used above the standard
896 # versioning structure, e.g. if one has a board inheriting a board.
897 if float(pv) >= 4:
898 want_pv = pv
899 elif is_private(overlay):
Mike Frysingercd363c82014-02-01 05:20:18 -0500900 want_pv = '3.5' if is_variant(overlay) else '3'
901 elif is_board(overlay):
902 want_pv = '2.5' if is_variant(overlay) else '2'
903 else:
904 want_pv = '1'
905
906 if pv != want_pv:
907 bad_ebuilds.append((ebuild, pv, want_pv))
908
909 if bad_ebuilds:
910 # pylint: disable=C0301
911 url = 'http://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/portage-build-faq#TOC-Virtuals-and-central-management'
912 # pylint: enable=C0301
913 return HookFailure(
914 'These virtuals have incorrect package versions (PVs). Please adjust:\n'
915 '\t%s\n'
916 'If this is an upstream Gentoo virtual, then you may ignore this\n'
917 'check (and re-run w/--no-verify). Otherwise, please see this\n'
918 'page for more details:\n%s\n' %
919 ('\n\t'.join(['%s:\n\t\tPV is %s but should be %s' % x
920 for x in bad_ebuilds]), url))
921
922
Daniel Erat9d203ff2015-02-17 10:12:21 -0700923def _check_portage_make_use_var(_project, commit):
924 """Verify that $USE is set correctly in make.conf and make.defaults."""
925 files = _filter_files(_get_affected_files(commit, relative=True),
926 [r'(^|/)make.(conf|defaults)$'])
927
928 errors = []
929 for path in files:
930 basename = os.path.basename(path)
931
932 # Has a USE= line already been encountered in this file?
933 saw_use = False
934
935 for i, line in enumerate(_get_file_content(path, commit).splitlines(), 1):
936 if not line.startswith('USE='):
937 continue
938
939 preserves_use = '${USE}' in line or '$USE' in line
940
941 if (basename == 'make.conf' or
942 (basename == 'make.defaults' and saw_use)) and not preserves_use:
943 errors.append('%s:%d: missing ${USE}' % (path, i))
944 elif basename == 'make.defaults' and not saw_use and preserves_use:
945 errors.append('%s:%d: ${USE} referenced in initial declaration' %
946 (path, i))
947
948 saw_use = True
949
950 if errors:
951 return HookFailure(
952 'One or more Portage make files appear to set USE incorrectly.\n'
953 '\n'
954 'All USE assignments in make.conf and all assignments after the\n'
955 'initial declaration in make.defaults should contain "${USE}" to\n'
956 'preserve previously-set flags.\n'
957 '\n'
958 'The initial USE declaration in make.defaults should not contain\n'
959 '"${USE}".\n',
960 errors)
961
962
Mike Frysingerae409522014-02-01 03:16:11 -0500963def _check_change_has_proper_changeid(_project, commit):
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700964 """Verify that Change-ID is present in last paragraph of commit message."""
Mike Frysinger4a22bf02014-10-31 13:53:35 -0400965 CHANGE_ID_RE = r'\nChange-Id: I[a-f0-9]+\n'
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700966 desc = _get_commit_desc(commit)
Mike Frysinger4a22bf02014-10-31 13:53:35 -0400967 m = re.search(CHANGE_ID_RE, desc)
Mike Frysinger02b88bd2014-11-21 00:29:38 -0500968 if not m:
Vadim Bendebury20532ba2017-05-23 17:26:15 -0700969 return HookFailure('Last paragraph of description must include Change-Id.')
Ryan Cui1562fb82011-05-09 11:01:31 -0700970
Vadim Bendebury20532ba2017-05-23 17:26:15 -0700971 # S-o-b tags always allowed to follow Change-ID.
972 allowed_tags = ['Signed-off-by']
973
Mike Frysinger02b88bd2014-11-21 00:29:38 -0500974 end = desc[m.end():].strip().splitlines()
Vadim Bendebury6504aea2017-09-13 18:35:49 -0700975 cherry_pick_marker = 'cherry picked from commit'
976
977 if end and cherry_pick_marker in end[-1]:
Vadim Bendebury20532ba2017-05-23 17:26:15 -0700978 # Cherry picked patches allow more tags in the last paragraph.
Vadim Bendebury6504aea2017-09-13 18:35:49 -0700979 allowed_tags += ['Commit-Queue', 'Commit-Ready', 'Reviewed-by',
980 'Reviewed-on', 'Tested-by']
Vadim Bendebury20532ba2017-05-23 17:26:15 -0700981 end = end[:-1]
982
Vadim Bendebury6504aea2017-09-13 18:35:49 -0700983 # Note that descriptions could have multiple cherry pick markers.
984 tag_search = r'^(%s:|\(%s) ' % (':|'.join(allowed_tags), cherry_pick_marker)
Vadim Bendebury20532ba2017-05-23 17:26:15 -0700985
986 if [x for x in end if not re.search(tag_search, x)]:
987 return HookFailure('Only "%s:" tag(s) may follow the Change-Id.' %
988 ':", "'.join(allowed_tags))
Mike Frysinger02b88bd2014-11-21 00:29:38 -0500989
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700990
Mike Frysinger36b2ebc2014-10-31 14:02:03 -0400991def _check_commit_message_style(_project, commit):
992 """Verify that the commit message matches our style.
993
994 We do not check for BUG=/TEST=/etc... lines here as that is handled by other
995 commit hooks.
996 """
997 desc = _get_commit_desc(commit)
998
999 # The first line should be by itself.
1000 lines = desc.splitlines()
1001 if len(lines) > 1 and lines[1]:
1002 return HookFailure('The second line of the commit message must be blank.')
1003
1004 # The first line should be one sentence.
1005 if '. ' in lines[0]:
1006 return HookFailure('The first line cannot be more than one sentence.')
1007
1008 # The first line cannot be too long.
1009 MAX_FIRST_LINE_LEN = 100
1010 if len(lines[0]) > MAX_FIRST_LINE_LEN:
1011 return HookFailure('The first line must be less than %i chars.' %
1012 MAX_FIRST_LINE_LEN)
1013
1014
Filipe Brandenburger4b542b12015-10-09 12:46:31 -07001015def _check_cros_license(_project, commit, options=()):
Alex Deymof5792ce2015-08-24 22:50:08 -07001016 """Verifies the Chromium OS license/copyright header.
Ryan Cuiec4d6332011-05-02 14:15:25 -07001017
Mike Frysinger98638102014-08-28 00:15:08 -04001018 Should be following the spec:
1019 http://dev.chromium.org/developers/coding-style#TOC-File-headers
1020 """
1021 # For older years, be a bit more flexible as our policy says leave them be.
1022 LICENSE_HEADER = (
1023 r'.* Copyright( \(c\))? 20[-0-9]{2,7} The Chromium OS Authors\. '
Mike Frysingerb81102f2014-11-21 00:33:35 -05001024 r'All rights reserved\.' r'\n'
Mike Frysinger98638102014-08-28 00:15:08 -04001025 r'.* Use of this source code is governed by a BSD-style license that can '
Mike Frysingerb81102f2014-11-21 00:33:35 -05001026 r'be\n'
Mike Frysinger98638102014-08-28 00:15:08 -04001027 r'.* found in the LICENSE file\.'
Mike Frysingerb81102f2014-11-21 00:33:35 -05001028 r'\n'
Mike Frysinger98638102014-08-28 00:15:08 -04001029 )
1030 license_re = re.compile(LICENSE_HEADER, re.MULTILINE)
1031
1032 # For newer years, be stricter.
1033 COPYRIGHT_LINE = (
1034 r'.* Copyright \(c\) 20(1[5-9]|[2-9][0-9]) The Chromium OS Authors\. '
Mike Frysingerb81102f2014-11-21 00:33:35 -05001035 r'All rights reserved\.' r'\n'
Mike Frysinger98638102014-08-28 00:15:08 -04001036 )
1037 copyright_re = re.compile(COPYRIGHT_LINE)
1038
Shuhei Takahashiabc20f32017-07-10 19:35:45 +09001039 included, excluded = _parse_common_inclusion_options(options)
Filipe Brandenburger4b542b12015-10-09 12:46:31 -07001040
Mike Frysinger98638102014-08-28 00:15:08 -04001041 bad_files = []
1042 bad_copyright_files = []
1043 files = _filter_files(_get_affected_files(commit, relative=True),
Filipe Brandenburger4b542b12015-10-09 12:46:31 -07001044 included + COMMON_INCLUDED_PATHS,
1045 excluded + COMMON_EXCLUDED_PATHS)
Mike Frysinger98638102014-08-28 00:15:08 -04001046
1047 for f in files:
1048 contents = _get_file_content(f, commit)
1049 if not contents:
1050 # Ignore empty files.
1051 continue
1052
1053 if not license_re.search(contents):
1054 bad_files.append(f)
1055 elif copyright_re.search(contents):
1056 bad_copyright_files.append(f)
1057
1058 if bad_files:
1059 msg = '%s:\n%s\n%s' % (
1060 'License must match', license_re.pattern,
1061 'Found a bad header in these files:')
1062 return HookFailure(msg, bad_files)
1063
1064 if bad_copyright_files:
1065 msg = 'Do not use (c) in copyright headers in new files:'
1066 return HookFailure(msg, bad_copyright_files)
Ryan Cuiec4d6332011-05-02 14:15:25 -07001067
1068
Alex Deymof5792ce2015-08-24 22:50:08 -07001069def _check_aosp_license(_project, commit):
1070 """Verifies the AOSP license/copyright header.
1071
1072 AOSP uses the Apache2 License:
1073 https://source.android.com/source/licenses.html
1074 """
1075 LICENSE_HEADER = (
1076 r"""^[#/\*]*
1077[#/\*]* ?Copyright( \([cC]\))? 20[-0-9]{2,7} The Android Open Source Project
1078[#/\*]* ?
1079[#/\*]* ?Licensed under the Apache License, Version 2.0 \(the "License"\);
1080[#/\*]* ?you may not use this file except in compliance with the License\.
1081[#/\*]* ?You may obtain a copy of the License at
1082[#/\*]* ?
1083[#/\*]* ? http://www\.apache\.org/licenses/LICENSE-2\.0
1084[#/\*]* ?
1085[#/\*]* ?Unless required by applicable law or agreed to in writing, software
1086[#/\*]* ?distributed under the License is distributed on an "AS IS" BASIS,
1087[#/\*]* ?WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or """
1088 r"""implied\.
1089[#/\*]* ?See the License for the specific language governing permissions and
1090[#/\*]* ?limitations under the License\.
1091[#/\*]*$
1092"""
1093 )
1094 license_re = re.compile(LICENSE_HEADER, re.MULTILINE)
1095
1096 files = _filter_files(_get_affected_files(commit, relative=True),
1097 COMMON_INCLUDED_PATHS,
1098 COMMON_EXCLUDED_PATHS)
1099
1100 bad_files = []
1101 for f in files:
1102 contents = _get_file_content(f, commit)
1103 if not contents:
1104 # Ignore empty files.
1105 continue
1106
1107 if not license_re.search(contents):
1108 bad_files.append(f)
1109
1110 if bad_files:
1111 msg = ('License must match:\n%s\nFound a bad header in these files:' %
1112 license_re.pattern)
1113 return HookFailure(msg, bad_files)
1114
1115
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001116def _check_layout_conf(_project, commit):
1117 """Verifies the metadata/layout.conf file."""
1118 repo_name = 'profiles/repo_name'
Mike Frysinger94a670c2014-09-19 12:46:26 -04001119 repo_names = []
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001120 layout_path = 'metadata/layout.conf'
Mike Frysinger94a670c2014-09-19 12:46:26 -04001121 layout_paths = []
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001122
Mike Frysinger94a670c2014-09-19 12:46:26 -04001123 # Handle multiple overlays in a single commit (like the public tree).
1124 for f in _get_affected_files(commit, relative=True):
1125 if f.endswith(repo_name):
1126 repo_names.append(f)
1127 elif f.endswith(layout_path):
1128 layout_paths.append(f)
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001129
1130 # Disallow new repos with the repo_name file.
Mike Frysinger94a670c2014-09-19 12:46:26 -04001131 if repo_names:
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001132 return HookFailure('%s: use "repo-name" in %s instead' %
Mike Frysinger94a670c2014-09-19 12:46:26 -04001133 (repo_names, layout_path))
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001134
Mike Frysinger94a670c2014-09-19 12:46:26 -04001135 # Gather all the errors in one pass so we show one full message.
1136 all_errors = {}
1137 for layout_path in layout_paths:
1138 all_errors[layout_path] = errors = []
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001139
Mike Frysinger94a670c2014-09-19 12:46:26 -04001140 # Make sure the config file is sorted.
1141 data = [x for x in _get_file_content(layout_path, commit).splitlines()
1142 if x and x[0] != '#']
1143 if sorted(data) != data:
1144 errors += ['keep lines sorted']
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001145
Mike Frysinger94a670c2014-09-19 12:46:26 -04001146 # Require people to set specific values all the time.
1147 settings = (
1148 # TODO: Enable this for everyone. http://crbug.com/408038
1149 #('fast caching', 'cache-format = md5-dict'),
1150 ('fast manifests', 'thin-manifests = true'),
Mike Frysingerd7734522015-02-26 16:12:43 -05001151 ('extra features', 'profile-formats = portage-2 profile-default-eapi'),
1152 ('newer eapi', 'profile_eapi_when_unspecified = 5-progress'),
Mike Frysinger94a670c2014-09-19 12:46:26 -04001153 )
1154 for reason, line in settings:
1155 if line not in data:
1156 errors += ['enable %s with: %s' % (reason, line)]
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001157
Mike Frysinger94a670c2014-09-19 12:46:26 -04001158 # Require one of these settings.
Mike Frysinger5fae62d2015-11-11 20:12:15 -05001159 if 'use-manifests = strict' not in data:
1160 errors += ['enable file checking with: use-manifests = strict']
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001161
Mike Frysinger94a670c2014-09-19 12:46:26 -04001162 # Require repo-name to be set.
Mike Frysinger324cf682014-09-22 15:52:50 -04001163 for line in data:
1164 if line.startswith('repo-name = '):
1165 break
1166 else:
Mike Frysinger94a670c2014-09-19 12:46:26 -04001167 errors += ['set the board name with: repo-name = $BOARD']
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001168
Mike Frysinger94a670c2014-09-19 12:46:26 -04001169 # Summarize all the errors we saw (if any).
1170 lines = ''
1171 for layout_path, errors in all_errors.items():
1172 if errors:
1173 lines += '\n\t- '.join(['\n* %s:' % layout_path] + errors)
1174 if lines:
1175 lines = 'See the portage(5) man page for layout.conf details' + lines + '\n'
1176 return HookFailure(lines)
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001177
1178
Ryan Cuiec4d6332011-05-02 14:15:25 -07001179# Project-specific hooks
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001180
Ryan Cui1562fb82011-05-09 11:01:31 -07001181
Luis Hector Chavezb50391d2017-09-26 15:48:15 -07001182def _check_clang_format(_project, commit, options=()):
1183 """Runs clang-format on the given project"""
1184 hooks_dir = _get_hooks_dir()
1185 options = list(options)
1186 if commit == PRE_SUBMIT:
1187 options.append('--commit=HEAD')
1188 else:
1189 options.extend(['--commit', commit])
1190 cmd = ['%s/clang-format.py' % hooks_dir] + options
1191 cmd_result = cros_build_lib.RunCommand(cmd=cmd,
1192 print_cmd=False,
1193 input=_get_patch(commit),
1194 stdout_to_pipe=True,
1195 combine_stdout_stderr=True,
1196 error_code_ok=True)
1197 if cmd_result.returncode:
1198 return HookFailure('clang-format.py errors/warnings\n\n' +
1199 cmd_result.output)
1200
1201
Mike Frysingerae409522014-02-01 03:16:11 -05001202def _run_checkpatch(_project, commit, options=()):
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001203 """Runs checkpatch.pl on the given project"""
1204 hooks_dir = _get_hooks_dir()
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001205 options = list(options)
1206 if commit == PRE_SUBMIT:
1207 # The --ignore option must be present and include 'MISSING_SIGN_OFF' in
1208 # this case.
1209 options.append('--ignore=MISSING_SIGN_OFF')
Filipe Brandenburger28d48d62015-10-07 09:48:54 -07001210 # Always ignore the check for the MAINTAINERS file. We do not track that
1211 # information on that file in our source trees, so let's suppress the
1212 # warning.
1213 options.append('--ignore=FILE_PATH_CHANGES')
Filipe Brandenburgerce978322015-10-09 10:04:15 -07001214 # Do not complain about the Change-Id: fields, since we use Gerrit.
1215 # Upstream does not want those lines (since they do not use Gerrit), but
1216 # we always do, so disable the check globally.
Daisuke Nojiri4844f892015-10-08 09:54:33 -07001217 options.append('--ignore=GERRIT_CHANGE_ID')
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001218 cmd = ['%s/checkpatch.pl' % hooks_dir] + options + ['-']
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001219 cmd_result = cros_build_lib.RunCommand(cmd=cmd,
1220 print_cmd=False,
1221 input=_get_patch(commit),
1222 stdout_to_pipe=True,
1223 combine_stdout_stderr=True,
1224 error_code_ok=True)
1225 if cmd_result.returncode:
1226 return HookFailure('checkpatch.pl errors/warnings\n\n' + cmd_result.output)
Ryan Cuiec4d6332011-05-02 14:15:25 -07001227
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001228
Mike Frysingerae409522014-02-01 03:16:11 -05001229def _kernel_configcheck(_project, commit):
Olof Johanssona96810f2012-09-04 16:20:03 -07001230 """Makes sure kernel config changes are not mixed with code changes"""
1231 files = _get_affected_files(commit)
1232 if not len(_filter_files(files, [r'chromeos/config'])) in [0, len(files)]:
1233 return HookFailure('Changes to chromeos/config/ and regular files must '
1234 'be in separate commits:\n%s' % '\n'.join(files))
Anton Staaf815d6852011-08-22 10:08:45 -07001235
Mike Frysingerae409522014-02-01 03:16:11 -05001236
1237def _run_json_check(_project, commit):
Dale Curtis2975c432011-05-03 17:25:20 -07001238 """Checks that all JSON files are syntactically valid."""
Dale Curtisa039cfd2011-05-04 12:01:05 -07001239 for f in _filter_files(_get_affected_files(commit), [r'.*\.json']):
Dale Curtis2975c432011-05-03 17:25:20 -07001240 try:
1241 json.load(open(f))
1242 except Exception, e:
Ryan Cui1562fb82011-05-09 11:01:31 -07001243 return HookFailure('Invalid JSON in %s: %s' % (f, e))
Dale Curtis2975c432011-05-03 17:25:20 -07001244
1245
Mike Frysingerae409522014-02-01 03:16:11 -05001246def _check_manifests(_project, commit):
Mike Frysinger52b537e2013-08-22 22:59:53 -04001247 """Make sure Manifest files only have DIST lines"""
1248 paths = []
1249
1250 for path in _get_affected_files(commit):
1251 if os.path.basename(path) != 'Manifest':
1252 continue
1253 if not os.path.exists(path):
1254 continue
1255
1256 with open(path, 'r') as f:
1257 for line in f.readlines():
1258 if not line.startswith('DIST '):
1259 paths.append(path)
1260 break
1261
1262 if paths:
1263 return HookFailure('Please remove lines that do not start with DIST:\n%s' %
1264 ('\n'.join(paths),))
1265
1266
Mike Frysingerae409522014-02-01 03:16:11 -05001267def _check_change_has_branch_field(_project, commit):
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001268 """Check for a non-empty 'BRANCH=' field in the commit message."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001269 if commit == PRE_SUBMIT:
1270 return
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001271 BRANCH_RE = r'\nBRANCH=\S+'
1272
1273 if not re.search(BRANCH_RE, _get_commit_desc(commit)):
1274 msg = ('Changelist description needs BRANCH field (after first line)\n'
1275 'E.g. BRANCH=none or BRANCH=link,snow')
1276 return HookFailure(msg)
1277
1278
Mike Frysingerae409522014-02-01 03:16:11 -05001279def _check_change_has_signoff_field(_project, commit):
Shawn Nematbakhsh51e16ac2014-01-28 15:31:07 -08001280 """Check for a non-empty 'Signed-off-by:' field in the commit message."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001281 if commit == PRE_SUBMIT:
1282 return
Shawn Nematbakhsh51e16ac2014-01-28 15:31:07 -08001283 SIGNOFF_RE = r'\nSigned-off-by: \S+'
1284
1285 if not re.search(SIGNOFF_RE, _get_commit_desc(commit)):
1286 msg = ('Changelist description needs Signed-off-by: field\n'
1287 'E.g. Signed-off-by: My Name <me@chromium.org>')
1288 return HookFailure(msg)
1289
1290
Aviv Keshet5ac59522017-01-31 14:28:27 -08001291def _check_cq_ini_well_formed(_project, commit):
1292 """Check that any modified COMMIT-QUEUE.ini files are well formed."""
1293 pattern = '.*' + constants.CQ_CONFIG_FILENAME
1294 files = _filter_files(_get_affected_files(commit), (pattern,))
1295
1296 # TODO(akeshet): Check not only that the file is parseable, but that all the
1297 # pre-cq configs it requests are existing ones.
1298 for f in files:
1299 try:
1300 parser = ConfigParser.SafeConfigParser()
1301 # Prior to python3, ConfigParser has no read_string method, so we must
1302 # pass it either a file path or file like object. And we must use
1303 # _get_file_content to fetch file contents to ensure we are examining the
1304 # commit diff, rather than whatever's on disk.
1305 contents = _get_file_content(f, commit)
1306 parser.readfp(StringIO.StringIO(contents))
1307 except ConfigParser.Error as e:
1308 msg = ('Unable to parse COMMIT-QUEUE.ini file at %s due to %s.' %
1309 (f, e))
1310 return HookFailure(msg)
1311
1312
Jon Salz3ee59de2012-08-18 13:54:22 +08001313def _run_project_hook_script(script, project, commit):
1314 """Runs a project hook script.
1315
1316 The script is run with the following environment variables set:
1317 PRESUBMIT_PROJECT: The affected project
1318 PRESUBMIT_COMMIT: The affected commit
1319 PRESUBMIT_FILES: A newline-separated list of affected files
1320
1321 The script is considered to fail if the exit code is non-zero. It should
1322 write an error message to stdout.
1323 """
1324 env = dict(os.environ)
Alex Deymo643ac4c2015-09-03 10:40:50 -07001325 env['PRESUBMIT_PROJECT'] = project.name
Jon Salz3ee59de2012-08-18 13:54:22 +08001326 env['PRESUBMIT_COMMIT'] = commit
1327
1328 # Put affected files in an environment variable
1329 files = _get_affected_files(commit)
1330 env['PRESUBMIT_FILES'] = '\n'.join(files)
1331
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001332 cmd_result = cros_build_lib.RunCommand(cmd=script,
1333 env=env,
1334 shell=True,
1335 print_cmd=False,
1336 input=os.devnull,
1337 stdout_to_pipe=True,
1338 combine_stdout_stderr=True,
1339 error_code_ok=True)
1340 if cmd_result.returncode:
1341 stdout = cmd_result.output
Jon Salz7b618af2012-08-31 06:03:16 +08001342 if stdout:
1343 stdout = re.sub('(?m)^', ' ', stdout)
1344 return HookFailure('Hook script "%s" failed with code %d%s' %
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001345 (script, cmd_result.returncode,
Jon Salz3ee59de2012-08-18 13:54:22 +08001346 ':\n' + stdout if stdout else ''))
1347
1348
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001349def _check_project_prefix(_project, commit):
Mike Frysinger55f85b52014-12-18 14:45:21 -05001350 """Require the commit message have a project specific prefix as needed."""
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001351
1352 files = _get_affected_files(commit, relative=True)
1353 prefix = os.path.commonprefix(files)
1354 prefix = os.path.dirname(prefix)
1355
1356 # If there is no common prefix, the CL span multiple projects.
Daniel Erata350fd32014-09-29 14:02:34 -07001357 if not prefix:
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001358 return
1359
1360 project_name = prefix.split('/')[0]
Daniel Erata350fd32014-09-29 14:02:34 -07001361
1362 # The common files may all be within a subdirectory of the main project
1363 # directory, so walk up the tree until we find an alias file.
1364 # _get_affected_files() should return relative paths, but check against '/' to
1365 # ensure that this loop terminates even if it receives an absolute path.
1366 while prefix and prefix != '/':
1367 alias_file = os.path.join(prefix, '.project_alias')
1368
1369 # If an alias exists, use it.
1370 if os.path.isfile(alias_file):
1371 project_name = osutils.ReadFile(alias_file).strip()
1372
1373 prefix = os.path.dirname(prefix)
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001374
1375 if not _get_commit_desc(commit).startswith(project_name + ': '):
1376 return HookFailure('The commit title for changes affecting only %s'
1377 ' should start with \"%s: \"'
1378 % (project_name, project_name))
1379
1380
Mike Frysingerf9d41b32017-02-23 15:20:04 -05001381def _check_exec_files(_project, commit):
1382 """Make +x bits on files."""
1383 # List of files that should never be +x.
1384 NO_EXEC = (
1385 'ChangeLog*',
1386 'COPYING',
1387 'make.conf',
1388 'make.defaults',
1389 'Manifest',
1390 'OWNERS',
1391 'package.use',
1392 'package.keywords',
1393 'package.mask',
1394 'parent',
1395 'README',
1396 'TODO',
1397 '.gitignore',
1398 '*.[achly]',
1399 '*.[ch]xx',
1400 '*.boto',
1401 '*.cc',
1402 '*.cfg',
1403 '*.conf',
1404 '*.config',
1405 '*.cpp',
1406 '*.css',
1407 '*.ebuild',
1408 '*.eclass',
1409 '*.gyp',
1410 '*.gypi',
1411 '*.htm',
1412 '*.html',
1413 '*.ini',
1414 '*.js',
1415 '*.json',
1416 '*.md',
1417 '*.mk',
1418 '*.patch',
1419 '*.policy',
1420 '*.proto',
1421 '*.raw',
1422 '*.rules',
1423 '*.service',
1424 '*.target',
1425 '*.txt',
1426 '*.xml',
1427 '*.yaml',
1428 )
1429
1430 def FinalName(obj):
1431 # If the file is being deleted, then the dst_file is not set.
1432 if obj.dst_file is None:
1433 return obj.src_file
1434 else:
1435 return obj.dst_file
1436
1437 bad_files = []
1438 files = _get_affected_files(commit, relative=True, full_details=True)
1439 for f in files:
1440 mode = int(f.dst_mode, 8)
1441 if not mode & 0o111:
1442 continue
1443 name = FinalName(f)
1444 for no_exec in NO_EXEC:
1445 if fnmatch.fnmatch(name, no_exec):
1446 bad_files.append(name)
1447 break
1448
1449 if bad_files:
1450 return HookFailure('These files should not be executable. '
1451 'Please `chmod -x` them.', bad_files)
1452
1453
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001454# Base
1455
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001456# A list of hooks which are not project specific and check patch description
1457# (as opposed to patch body).
1458_PATCH_DESCRIPTION_HOOKS = [
Ryan Cui9b651632011-05-11 11:38:58 -07001459 _check_change_has_bug_field,
David Jamesc3b68b32013-04-03 09:17:03 -07001460 _check_change_has_valid_cq_depend,
Ryan Cui9b651632011-05-11 11:38:58 -07001461 _check_change_has_test_field,
1462 _check_change_has_proper_changeid,
Mike Frysinger36b2ebc2014-10-31 14:02:03 -04001463 _check_commit_message_style,
Bernie Thompsonf8fea992016-01-14 10:27:18 -08001464 _check_change_is_contribution,
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001465]
1466
1467
1468# A list of hooks that are not project-specific
1469_COMMON_HOOKS = [
Aviv Keshet5ac59522017-01-31 14:28:27 -08001470 _check_cq_ini_well_formed,
1471 _check_cros_license,
Mike Frysingerbf8b91c2014-02-01 02:50:27 -05001472 _check_ebuild_eapi,
Mike Frysinger89bdb852014-02-01 05:26:26 -05001473 _check_ebuild_keywords,
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -08001474 _check_ebuild_licenses,
Mike Frysingercd363c82014-02-01 05:20:18 -05001475 _check_ebuild_virtual_pv,
Mike Frysingerf9d41b32017-02-23 15:20:04 -05001476 _check_exec_files,
Daniel Erat9d203ff2015-02-17 10:12:21 -07001477 _check_for_uprev,
Rahul Chaudhry09f61372015-07-31 17:14:26 -07001478 _check_gofmt,
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001479 _check_layout_conf,
Daniel Erat9d203ff2015-02-17 10:12:21 -07001480 _check_no_long_lines,
1481 _check_no_stray_whitespace,
Ryan Cui9b651632011-05-11 11:38:58 -07001482 _check_no_tabs,
Daniel Erat9d203ff2015-02-17 10:12:21 -07001483 _check_portage_make_use_var,
Aviv Keshet5ac59522017-01-31 14:28:27 -08001484 _check_tabbed_indents,
Ryan Cui9b651632011-05-11 11:38:58 -07001485]
Ryan Cuiec4d6332011-05-02 14:15:25 -07001486
Ryan Cui1562fb82011-05-09 11:01:31 -07001487
Ryan Cui9b651632011-05-11 11:38:58 -07001488# A dictionary of project-specific hooks(callbacks), indexed by project name.
1489# dict[project] = [callback1, callback2]
1490_PROJECT_SPECIFIC_HOOKS = {
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001491 "chromiumos/platform2": [_check_project_prefix],
Mike Frysingeraf891292015-03-25 19:46:53 -04001492 "chromiumos/third_party/kernel": [_kernel_configcheck],
1493 "chromiumos/third_party/kernel-next": [_kernel_configcheck],
Ryan Cui9b651632011-05-11 11:38:58 -07001494}
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001495
Ryan Cui1562fb82011-05-09 11:01:31 -07001496
Ryan Cui9b651632011-05-11 11:38:58 -07001497# A dictionary of flags (keys) that can appear in the config file, and the hook
Mike Frysinger3554bc92015-03-11 04:59:21 -04001498# that the flag controls (value).
1499_HOOK_FLAGS = {
Luis Hector Chavezb50391d2017-09-26 15:48:15 -07001500 'clang_format_check': _check_clang_format,
Mike Frysingera7642f52015-03-25 18:31:42 -04001501 'checkpatch_check': _run_checkpatch,
Ryan Cui9b651632011-05-11 11:38:58 -07001502 'stray_whitespace_check': _check_no_stray_whitespace,
Mike Frysingerff6c7d62015-03-24 13:49:46 -04001503 'json_check': _run_json_check,
Ryan Cui9b651632011-05-11 11:38:58 -07001504 'long_line_check': _check_no_long_lines,
Alex Deymof5792ce2015-08-24 22:50:08 -07001505 'cros_license_check': _check_cros_license,
1506 'aosp_license_check': _check_aosp_license,
Ryan Cui9b651632011-05-11 11:38:58 -07001507 'tab_check': _check_no_tabs,
Prathmesh Prabhuc5254652016-12-22 12:58:05 -08001508 'tabbed_indent_required_check': _check_tabbed_indents,
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001509 'branch_check': _check_change_has_branch_field,
Shawn Nematbakhsh51e16ac2014-01-28 15:31:07 -08001510 'signoff_check': _check_change_has_signoff_field,
Josh Triplett0e8fc7f2014-04-23 16:00:00 -07001511 'bug_field_check': _check_change_has_bug_field,
1512 'test_field_check': _check_change_has_test_field,
Steve Fung49ec7e92015-03-23 16:07:12 -07001513 'manifest_check': _check_manifests,
Bernie Thompsonf8fea992016-01-14 10:27:18 -08001514 'contribution_check': _check_change_is_contribution,
Ryan Cui9b651632011-05-11 11:38:58 -07001515}
1516
1517
Mike Frysinger3554bc92015-03-11 04:59:21 -04001518def _get_override_hooks(config):
1519 """Returns a set of hooks controlled by the current project's config file.
Ryan Cui9b651632011-05-11 11:38:58 -07001520
1521 Expects to be called within the project root.
Jon Salz3ee59de2012-08-18 13:54:22 +08001522
1523 Args:
1524 config: A ConfigParser for the project's config file.
Ryan Cui9b651632011-05-11 11:38:58 -07001525 """
1526 SECTION = 'Hook Overrides'
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001527 SECTION_OPTIONS = 'Hook Overrides Options'
Jon Salz3ee59de2012-08-18 13:54:22 +08001528 if not config.has_section(SECTION):
Mike Frysinger3554bc92015-03-11 04:59:21 -04001529 return set(), set()
Ryan Cui9b651632011-05-11 11:38:58 -07001530
Mike Frysinger3554bc92015-03-11 04:59:21 -04001531 valid_keys = set(_HOOK_FLAGS.iterkeys())
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001532 hooks = _HOOK_FLAGS.copy()
Mike Frysinger3554bc92015-03-11 04:59:21 -04001533
1534 enable_flags = []
Ryan Cui9b651632011-05-11 11:38:58 -07001535 disable_flags = []
Jon Salz3ee59de2012-08-18 13:54:22 +08001536 for flag in config.options(SECTION):
Mike Frysinger3554bc92015-03-11 04:59:21 -04001537 if flag not in valid_keys:
1538 raise ValueError('Error: unknown key "%s" in hook section of "%s"' %
1539 (flag, _CONFIG_FILE))
1540
Ryan Cui9b651632011-05-11 11:38:58 -07001541 try:
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001542 enabled = config.getboolean(SECTION, flag)
Ryan Cui9b651632011-05-11 11:38:58 -07001543 except ValueError as e:
Mike Frysinger3554bc92015-03-11 04:59:21 -04001544 raise ValueError('Error: parsing flag "%s" in "%s" failed: %s' %
1545 (flag, _CONFIG_FILE, e))
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001546 if enabled:
1547 enable_flags.append(flag)
1548 else:
1549 disable_flags.append(flag)
Ryan Cui9b651632011-05-11 11:38:58 -07001550
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001551 # See if this hook has custom options.
1552 if enabled:
1553 try:
1554 options = config.get(SECTION_OPTIONS, flag)
1555 hooks[flag] = functools.partial(hooks[flag], options=options.split())
Mike Frysingerb7d552e2017-11-23 11:50:47 -05001556 hooks[flag].__name__ = flag
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001557 except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
1558 pass
1559
1560 enabled_hooks = set(hooks[x] for x in enable_flags)
1561 disabled_hooks = set(hooks[x] for x in disable_flags)
Mike Frysinger3554bc92015-03-11 04:59:21 -04001562 return enabled_hooks, disabled_hooks
Ryan Cui9b651632011-05-11 11:38:58 -07001563
1564
Jon Salz3ee59de2012-08-18 13:54:22 +08001565def _get_project_hook_scripts(config):
1566 """Returns a list of project-specific hook scripts.
1567
1568 Args:
1569 config: A ConfigParser for the project's config file.
1570 """
1571 SECTION = 'Hook Scripts'
1572 if not config.has_section(SECTION):
1573 return []
1574
Mike Frysingerb7d552e2017-11-23 11:50:47 -05001575 return config.items(SECTION)
Jon Salz3ee59de2012-08-18 13:54:22 +08001576
1577
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001578def _get_project_hooks(project, presubmit):
Ryan Cui9b651632011-05-11 11:38:58 -07001579 """Returns a list of hooks that need to be run for a project.
1580
1581 Expects to be called from within the project root.
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001582
1583 Args:
1584 project: A string, name of the project.
1585 presubmit: A Boolean, True if the check is run as a git pre-submit script.
Ryan Cui9b651632011-05-11 11:38:58 -07001586 """
Jon Salz3ee59de2012-08-18 13:54:22 +08001587 config = ConfigParser.RawConfigParser()
1588 try:
1589 config.read(_CONFIG_FILE)
1590 except ConfigParser.Error:
1591 # Just use an empty config file
1592 config = ConfigParser.RawConfigParser()
1593
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001594 if presubmit:
Filipe Brandenburgerf70d32c2015-10-09 13:35:45 -07001595 hooks = _COMMON_HOOKS
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001596 else:
Filipe Brandenburgerf70d32c2015-10-09 13:35:45 -07001597 hooks = _PATCH_DESCRIPTION_HOOKS + _COMMON_HOOKS
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001598
Mike Frysinger3554bc92015-03-11 04:59:21 -04001599 enabled_hooks, disabled_hooks = _get_override_hooks(config)
Filipe Brandenburgerf70d32c2015-10-09 13:35:45 -07001600 hooks = [hook for hook in hooks if hook not in disabled_hooks]
1601
1602 # If a list is both in _COMMON_HOOKS and also enabled explicitly through an
1603 # override, keep the override only. Note that the override may end up being
1604 # a functools.partial, in which case we need to extract the .func to compare
1605 # it to the common hooks.
1606 unwrapped_hooks = [getattr(hook, 'func', hook) for hook in enabled_hooks]
1607 hooks = [hook for hook in hooks if hook not in unwrapped_hooks]
1608
1609 hooks = list(enabled_hooks) + hooks
Ryan Cui9b651632011-05-11 11:38:58 -07001610
1611 if project in _PROJECT_SPECIFIC_HOOKS:
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001612 hooks.extend(hook for hook in _PROJECT_SPECIFIC_HOOKS[project]
1613 if hook not in disabled_hooks)
Ryan Cui9b651632011-05-11 11:38:58 -07001614
Mike Frysingerb7d552e2017-11-23 11:50:47 -05001615 for name, script in _get_project_hook_scripts(config):
1616 func = functools.partial(_run_project_hook_script, script)
1617 func.__name__ = name
1618 hooks.append(func)
Jon Salz3ee59de2012-08-18 13:54:22 +08001619
Ryan Cui9b651632011-05-11 11:38:58 -07001620 return hooks
1621
1622
Alex Deymo643ac4c2015-09-03 10:40:50 -07001623def _run_project_hooks(project_name, proj_dir=None,
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001624 commit_list=None, presubmit=False):
Ryan Cui1562fb82011-05-09 11:01:31 -07001625 """For each project run its project specific hook from the hooks dictionary.
1626
1627 Args:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001628 project_name: The name of project to run hooks for.
Doug Anderson44a644f2011-11-02 10:37:37 -07001629 proj_dir: If non-None, this is the directory the project is in. If None,
1630 we'll ask repo.
Doug Anderson14749562013-06-26 13:38:29 -07001631 commit_list: A list of commits to run hooks against. If None or empty list
1632 then we'll automatically get the list of commits that would be uploaded.
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001633 presubmit: A Boolean, True if the check is run as a git pre-submit script.
Ryan Cui1562fb82011-05-09 11:01:31 -07001634
1635 Returns:
1636 Boolean value of whether any errors were ecountered while running the hooks.
1637 """
Doug Anderson44a644f2011-11-02 10:37:37 -07001638 if proj_dir is None:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001639 proj_dirs = _run_command(
1640 ['repo', 'forall', project_name, '-c', 'pwd']).split()
David James2edd9002013-10-11 14:09:19 -07001641 if len(proj_dirs) == 0:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001642 print('%s cannot be found.' % project_name, file=sys.stderr)
David James2edd9002013-10-11 14:09:19 -07001643 print('Please specify a valid project.', file=sys.stderr)
1644 return True
1645 if len(proj_dirs) > 1:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001646 print('%s is associated with multiple directories.' % project_name,
David James2edd9002013-10-11 14:09:19 -07001647 file=sys.stderr)
1648 print('Please specify a directory to help disambiguate.', file=sys.stderr)
1649 return True
1650 proj_dir = proj_dirs[0]
Doug Anderson44a644f2011-11-02 10:37:37 -07001651
Ryan Cuiec4d6332011-05-02 14:15:25 -07001652 pwd = os.getcwd()
1653 # hooks assume they are run from the root of the project
1654 os.chdir(proj_dir)
1655
Alex Deymo643ac4c2015-09-03 10:40:50 -07001656 remote_branch = _run_command(['git', 'rev-parse', '--abbrev-ref',
1657 '--symbolic-full-name', '@{u}']).strip()
1658 if not remote_branch:
1659 print('Your project %s doesn\'t track any remote repo.' % project_name,
1660 file=sys.stderr)
1661 remote = None
1662 else:
1663 remote, _branch = remote_branch.split('/', 1)
1664
1665 project = Project(name=project_name, dir=proj_dir, remote=remote)
1666
Doug Anderson14749562013-06-26 13:38:29 -07001667 if not commit_list:
1668 try:
1669 commit_list = _get_commits()
1670 except VerifyException as e:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001671 PrintErrorForProject(project.name, HookFailure(str(e)))
Doug Anderson14749562013-06-26 13:38:29 -07001672 os.chdir(pwd)
1673 return True
Ryan Cuifa55df52011-05-06 11:16:55 -07001674
Alex Deymo643ac4c2015-09-03 10:40:50 -07001675 hooks = _get_project_hooks(project.name, presubmit)
Ryan Cui1562fb82011-05-09 11:01:31 -07001676 error_found = False
Mike Frysingerb7d552e2017-11-23 11:50:47 -05001677 commit_count = len(commit_list)
1678 for i, commit in enumerate(commit_list):
Ryan Cui1562fb82011-05-09 11:01:31 -07001679 error_list = []
Ryan Cui9b651632011-05-11 11:38:58 -07001680 for hook in hooks:
Mike Frysingerb7d552e2017-11-23 11:50:47 -05001681 output = ('PRESUBMIT.cfg: [%i/%i]: %s: Running %s' %
1682 (i + 1, commit_count, commit, hook.__name__))
1683 print(output, end='\r')
1684 sys.stdout.flush()
Ryan Cui1562fb82011-05-09 11:01:31 -07001685 hook_error = hook(project, commit)
Mike Frysingerb7d552e2017-11-23 11:50:47 -05001686 print(' ' * len(output), end='\r')
1687 sys.stdout.flush()
Ryan Cui1562fb82011-05-09 11:01:31 -07001688 if hook_error:
1689 error_list.append(hook_error)
1690 error_found = True
1691 if error_list:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001692 PrintErrorsForCommit(project.name, commit, _get_commit_desc(commit),
Ryan Cui1562fb82011-05-09 11:01:31 -07001693 error_list)
Don Garrettdba548a2011-05-05 15:17:14 -07001694
Ryan Cuiec4d6332011-05-02 14:15:25 -07001695 os.chdir(pwd)
Ryan Cui1562fb82011-05-09 11:01:31 -07001696 return error_found
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001697
Mike Frysingerae409522014-02-01 03:16:11 -05001698
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001699# Main
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -07001700
Ryan Cui1562fb82011-05-09 11:01:31 -07001701
Mike Frysingerae409522014-02-01 03:16:11 -05001702def main(project_list, worktree_list=None, **_kwargs):
Doug Anderson06456632012-01-05 11:02:14 -08001703 """Main function invoked directly by repo.
1704
1705 This function will exit directly upon error so that repo doesn't print some
1706 obscure error message.
1707
1708 Args:
1709 project_list: List of projects to run on.
David James2edd9002013-10-11 14:09:19 -07001710 worktree_list: A list of directories. It should be the same length as
1711 project_list, so that each entry in project_list matches with a directory
1712 in worktree_list. If None, we will attempt to calculate the directories
1713 automatically.
Doug Anderson06456632012-01-05 11:02:14 -08001714 kwargs: Leave this here for forward-compatibility.
1715 """
Ryan Cui1562fb82011-05-09 11:01:31 -07001716 found_error = False
David James2edd9002013-10-11 14:09:19 -07001717 if not worktree_list:
1718 worktree_list = [None] * len(project_list)
1719 for project, worktree in zip(project_list, worktree_list):
1720 if _run_project_hooks(project, proj_dir=worktree):
Ryan Cui1562fb82011-05-09 11:01:31 -07001721 found_error = True
1722
Mike Frysingerae409522014-02-01 03:16:11 -05001723 if found_error:
Ryan Cui1562fb82011-05-09 11:01:31 -07001724 msg = ('Preupload failed due to errors in project(s). HINTS:\n'
Ryan Cui9b651632011-05-11 11:38:58 -07001725 '- To disable some source style checks, and for other hints, see '
1726 '<checkout_dir>/src/repohooks/README\n'
1727 '- To upload only current project, run \'repo upload .\'')
Mike Frysinger09d6a3d2013-10-08 22:21:03 -04001728 print(msg, file=sys.stderr)
Don Garrettdba548a2011-05-05 15:17:14 -07001729 sys.exit(1)
Anush Elangovan63afad72011-03-23 00:41:27 -07001730
Ryan Cui1562fb82011-05-09 11:01:31 -07001731
Doug Anderson44a644f2011-11-02 10:37:37 -07001732def _identify_project(path):
1733 """Identify the repo project associated with the given path.
1734
1735 Returns:
1736 A string indicating what project is associated with the path passed in or
1737 a blank string upon failure.
1738 """
1739 return _run_command(['repo', 'forall', '.', '-c', 'echo ${REPO_PROJECT}'],
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001740 redirect_stderr=True, cwd=path).strip()
Doug Anderson44a644f2011-11-02 10:37:37 -07001741
1742
Mike Frysinger55f85b52014-12-18 14:45:21 -05001743def direct_main(argv):
Doug Anderson44a644f2011-11-02 10:37:37 -07001744 """Run hooks directly (outside of the context of repo).
1745
Doug Anderson44a644f2011-11-02 10:37:37 -07001746 Args:
Mike Frysinger55f85b52014-12-18 14:45:21 -05001747 argv: The command line args to process
Doug Anderson44a644f2011-11-02 10:37:37 -07001748
1749 Returns:
1750 0 if no pre-upload failures, 1 if failures.
1751
1752 Raises:
1753 BadInvocation: On some types of invocation errors.
1754 """
Mike Frysinger66142932014-12-18 14:55:57 -05001755 parser = commandline.ArgumentParser(description=__doc__)
1756 parser.add_argument('--dir', default=None,
1757 help='The directory that the project lives in. If not '
1758 'specified, use the git project root based on the cwd.')
1759 parser.add_argument('--project', default=None,
1760 help='The project repo path; this can affect how the '
1761 'hooks get run, since some hooks are project-specific. '
1762 'For chromite this is chromiumos/chromite. If not '
1763 'specified, the repo tool will be used to figure this '
1764 'out based on the dir.')
1765 parser.add_argument('--rerun-since', default=None,
1766 help='Rerun hooks on old commits since the given date. '
1767 'The date should match git log\'s concept of a date. '
1768 'e.g. 2012-06-20. This option is mutually exclusive '
1769 'with --pre-submit.')
1770 parser.add_argument('--pre-submit', action="store_true",
1771 help='Run the check against the pending commit. '
1772 'This option should be used at the \'git commit\' '
1773 'phase as opposed to \'repo upload\'. This option '
1774 'is mutually exclusive with --rerun-since.')
1775 parser.add_argument('commits', nargs='*',
1776 help='Check specific commits')
1777 opts = parser.parse_args(argv)
Doug Anderson44a644f2011-11-02 10:37:37 -07001778
Doug Anderson14749562013-06-26 13:38:29 -07001779 if opts.rerun_since:
Mike Frysinger66142932014-12-18 14:55:57 -05001780 if opts.commits:
Doug Anderson14749562013-06-26 13:38:29 -07001781 raise BadInvocation('Can\'t pass commits and use rerun-since: %s' %
Mike Frysinger66142932014-12-18 14:55:57 -05001782 ' '.join(opts.commits))
Doug Anderson14749562013-06-26 13:38:29 -07001783
1784 cmd = ['git', 'log', '--since="%s"' % opts.rerun_since, '--pretty=%H']
1785 all_commits = _run_command(cmd).splitlines()
1786 bot_commits = _run_command(cmd + ['--author=chrome-bot']).splitlines()
1787
1788 # Eliminate chrome-bot commits but keep ordering the same...
1789 bot_commits = set(bot_commits)
Mike Frysinger66142932014-12-18 14:55:57 -05001790 opts.commits = [c for c in all_commits if c not in bot_commits]
Doug Anderson14749562013-06-26 13:38:29 -07001791
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001792 if opts.pre_submit:
1793 raise BadInvocation('rerun-since and pre-submit can not be '
1794 'used together')
1795 if opts.pre_submit:
Mike Frysinger66142932014-12-18 14:55:57 -05001796 if opts.commits:
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001797 raise BadInvocation('Can\'t pass commits and use pre-submit: %s' %
Mike Frysinger66142932014-12-18 14:55:57 -05001798 ' '.join(opts.commits))
1799 opts.commits = [PRE_SUBMIT,]
Doug Anderson44a644f2011-11-02 10:37:37 -07001800
1801 # Check/normlaize git dir; if unspecified, we'll use the root of the git
1802 # project from CWD
1803 if opts.dir is None:
1804 git_dir = _run_command(['git', 'rev-parse', '--git-dir'],
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001805 redirect_stderr=True).strip()
Doug Anderson44a644f2011-11-02 10:37:37 -07001806 if not git_dir:
1807 raise BadInvocation('The current directory is not part of a git project.')
1808 opts.dir = os.path.dirname(os.path.abspath(git_dir))
1809 elif not os.path.isdir(opts.dir):
1810 raise BadInvocation('Invalid dir: %s' % opts.dir)
1811 elif not os.path.isdir(os.path.join(opts.dir, '.git')):
1812 raise BadInvocation('Not a git directory: %s' % opts.dir)
1813
1814 # Identify the project if it wasn't specified; this _requires_ the repo
1815 # tool to be installed and for the project to be part of a repo checkout.
1816 if not opts.project:
1817 opts.project = _identify_project(opts.dir)
1818 if not opts.project:
1819 raise BadInvocation("Repo couldn't identify the project of %s" % opts.dir)
1820
Doug Anderson14749562013-06-26 13:38:29 -07001821 found_error = _run_project_hooks(opts.project, proj_dir=opts.dir,
Mike Frysinger66142932014-12-18 14:55:57 -05001822 commit_list=opts.commits,
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001823 presubmit=opts.pre_submit)
Doug Anderson44a644f2011-11-02 10:37:37 -07001824 if found_error:
1825 return 1
1826 return 0
1827
1828
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -07001829if __name__ == '__main__':
Mike Frysinger55f85b52014-12-18 14:45:21 -05001830 sys.exit(direct_main(sys.argv[1:]))