blob: be40f96823a473e11e2071cd1ef7585975d06632 [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
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070023
Ryan Cui1562fb82011-05-09 11:01:31 -070024from errors import (VerifyException, HookFailure, PrintErrorForProject,
25 PrintErrorsForCommit)
Ryan Cuiec4d6332011-05-02 14:15:25 -070026
David Jamesc3b68b32013-04-03 09:17:03 -070027# If repo imports us, the __name__ will be __builtin__, and the wrapper will
28# be in $CHROMEOS_CHECKOUT/.repo/repo/main.py, so we need to go two directories
29# up. The same logic also happens to work if we're executed directly.
30if __name__ in ('__builtin__', '__main__'):
31 sys.path.insert(0, os.path.join(os.path.dirname(sys.argv[0]), '..', '..'))
32
Mike Frysinger66142932014-12-18 14:55:57 -050033from chromite.lib import commandline
Rahul Chaudhry0e515342015-08-07 12:00:43 -070034from chromite.lib import cros_build_lib
Mike Frysingerd3bd32c2014-11-24 23:34:29 -050035from chromite.lib import git
Daniel Erata350fd32014-09-29 14:02:34 -070036from chromite.lib import osutils
David Jamesc3b68b32013-04-03 09:17:03 -070037from chromite.lib import patch
Mike Frysinger2ec70ed2014-08-17 19:28:34 -040038from chromite.licensing import licenses_lib
David Jamesc3b68b32013-04-03 09:17:03 -070039
Vadim Bendebury2b62d742014-06-22 13:14:51 -070040PRE_SUBMIT = 'pre-submit'
Ryan Cuiec4d6332011-05-02 14:15:25 -070041
42COMMON_INCLUDED_PATHS = [
Mike Frysingerae409522014-02-01 03:16:11 -050043 # C++ and friends
44 r".*\.c$", r".*\.cc$", r".*\.cpp$", r".*\.h$", r".*\.m$", r".*\.mm$",
45 r".*\.inl$", r".*\.asm$", r".*\.hxx$", r".*\.hpp$", r".*\.s$", r".*\.S$",
46 # Scripts
47 r".*\.js$", r".*\.py$", r".*\.sh$", r".*\.rb$", r".*\.pl$", r".*\.pm$",
48 # No extension at all, note that ALL CAPS files are black listed in
49 # COMMON_EXCLUDED_LIST below.
50 r"(^|.*[\\\/])[^.]+$",
51 # Other
52 r".*\.java$", r".*\.mk$", r".*\.am$",
Brian Norrisfdbac8e2016-06-16 11:09:05 -070053 r".*\.policy$", r".*\.conf$",
Ryan Cuiec4d6332011-05-02 14:15:25 -070054]
55
Ryan Cui1562fb82011-05-09 11:01:31 -070056
Ryan Cuiec4d6332011-05-02 14:15:25 -070057COMMON_EXCLUDED_PATHS = [
Daniel Erate3ea3fc2015-02-13 15:27:52 -070058 # Avoid doing source file checks for kernel.
Mike Frysingerae409522014-02-01 03:16:11 -050059 r"/src/third_party/kernel/",
60 r"/src/third_party/kernel-next/",
61 r"/src/third_party/ktop/",
62 r"/src/third_party/punybench/",
63 r".*\bexperimental[\\\/].*",
64 r".*\b[A-Z0-9_]{2,}$",
65 r".*[\\\/]debian[\\\/]rules$",
Daniel Erate3ea3fc2015-02-13 15:27:52 -070066
67 # For ebuild trees, ignore any caches and manifest data.
Mike Frysingerae409522014-02-01 03:16:11 -050068 r".*/Manifest$",
69 r".*/metadata/[^/]*cache[^/]*/[^/]+/[^/]+$",
Doug Anderson5bfb6792011-10-25 16:45:41 -070070
Daniel Erate3ea3fc2015-02-13 15:27:52 -070071 # Ignore profiles data (like overlay-tegra2/profiles).
Mike Frysinger94a670c2014-09-19 12:46:26 -040072 r"(^|.*/)overlay-.*/profiles/.*",
Mike Frysinger98638102014-08-28 00:15:08 -040073 r"^profiles/.*$",
74
Daniel Erate3ea3fc2015-02-13 15:27:52 -070075 # Ignore minified js and jquery.
Mike Frysingerae409522014-02-01 03:16:11 -050076 r".*\.min\.js",
77 r".*jquery.*\.js",
Mike Frysinger33a458d2014-03-03 17:00:51 -050078
79 # Ignore license files as the content is often taken verbatim.
Daniel Erate3ea3fc2015-02-13 15:27:52 -070080 r".*/licenses/.*",
Ryan Cuiec4d6332011-05-02 14:15:25 -070081]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070082
Ryan Cui1562fb82011-05-09 11:01:31 -070083
Ryan Cui9b651632011-05-11 11:38:58 -070084_CONFIG_FILE = 'PRESUBMIT.cfg'
85
86
Daniel Erate3ea3fc2015-02-13 15:27:52 -070087# File containing wildcards, one per line, matching files that should be
88# excluded from presubmit checks. Lines beginning with '#' are ignored.
89_IGNORE_FILE = '.presubmitignore'
90
91
Doug Anderson44a644f2011-11-02 10:37:37 -070092# Exceptions
93
94
95class BadInvocation(Exception):
96 """An Exception indicating a bad invocation of the program."""
97 pass
98
99
Ryan Cui1562fb82011-05-09 11:01:31 -0700100# General Helpers
101
Sean Paulba01d402011-05-05 11:36:23 -0400102
Alex Deymo643ac4c2015-09-03 10:40:50 -0700103Project = collections.namedtuple('Project', ['name', 'dir', 'remote'])
104
105
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700106# pylint: disable=redefined-builtin
107def _run_command(cmd, cwd=None, input=None,
108 redirect_stderr=False, combine_stdout_stderr=False):
Doug Anderson44a644f2011-11-02 10:37:37 -0700109 """Executes the passed in command and returns raw stdout output.
110
111 Args:
112 cmd: The command to run; should be a list of strings.
113 cwd: The directory to switch to for running the command.
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700114 input: The data to pipe into this command through stdin. If a file object
115 or file descriptor, stdin will be connected directly to that.
116 redirect_stderr: Redirect stderr away from console.
117 combine_stdout_stderr: Combines stdout and stderr streams into stdout.
Doug Anderson44a644f2011-11-02 10:37:37 -0700118
119 Returns:
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700120 The stdout from the process (discards stderr and returncode).
Doug Anderson44a644f2011-11-02 10:37:37 -0700121 """
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700122 return cros_build_lib.RunCommand(cmd=cmd,
123 cwd=cwd,
124 print_cmd=False,
125 input=input,
126 stdout_to_pipe=True,
127 redirect_stderr=redirect_stderr,
128 combine_stdout_stderr=combine_stdout_stderr,
129 error_code_ok=True).output
130# pylint: enable=redefined-builtin
Ryan Cui72834d12011-05-05 14:51:33 -0700131
Ryan Cui1562fb82011-05-09 11:01:31 -0700132
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700133def _get_hooks_dir():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700134 """Returns the absolute path to the repohooks directory."""
Doug Anderson44a644f2011-11-02 10:37:37 -0700135 if __name__ == '__main__':
136 # Works when file is run on its own (__file__ is defined)...
137 return os.path.abspath(os.path.dirname(__file__))
138 else:
139 # We need to do this when we're run through repo. Since repo executes
140 # us with execfile(), we don't get __file__ defined.
141 cmd = ['repo', 'forall', 'chromiumos/repohooks', '-c', 'pwd']
142 return _run_command(cmd).strip()
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700143
Ryan Cui1562fb82011-05-09 11:01:31 -0700144
Ryan Cuiec4d6332011-05-02 14:15:25 -0700145def _match_regex_list(subject, expressions):
146 """Try to match a list of regular expressions to a string.
147
148 Args:
149 subject: The string to match regexes on
150 expressions: A list of regular expressions to check for matches with.
151
152 Returns:
153 Whether the passed in subject matches any of the passed in regexes.
154 """
155 for expr in expressions:
Mike Frysingerae409522014-02-01 03:16:11 -0500156 if re.search(expr, subject):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700157 return True
158 return False
159
Ryan Cui1562fb82011-05-09 11:01:31 -0700160
Mike Frysingerae409522014-02-01 03:16:11 -0500161def _filter_files(files, include_list, exclude_list=()):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700162 """Filter out files based on the conditions passed in.
163
164 Args:
165 files: list of filepaths to filter
166 include_list: list of regex that when matched with a file path will cause it
167 to be added to the output list unless the file is also matched with a
168 regex in the exclude_list.
169 exclude_list: list of regex that when matched with a file will prevent it
170 from being added to the output list, even if it is also matched with a
171 regex in the include_list.
172
173 Returns:
174 A list of filepaths that contain files matched in the include_list and not
175 in the exclude_list.
176 """
177 filtered = []
178 for f in files:
179 if (_match_regex_list(f, include_list) and
180 not _match_regex_list(f, exclude_list)):
181 filtered.append(f)
182 return filtered
183
Ryan Cuiec4d6332011-05-02 14:15:25 -0700184
185# Git Helpers
Ryan Cui1562fb82011-05-09 11:01:31 -0700186
187
Ryan Cui4725d952011-05-05 15:41:19 -0700188def _get_upstream_branch():
189 """Returns the upstream tracking branch of the current branch.
190
191 Raises:
192 Error if there is no tracking branch
193 """
194 current_branch = _run_command(['git', 'symbolic-ref', 'HEAD']).strip()
195 current_branch = current_branch.replace('refs/heads/', '')
196 if not current_branch:
Ryan Cui1562fb82011-05-09 11:01:31 -0700197 raise VerifyException('Need to be on a tracking branch')
Ryan Cui4725d952011-05-05 15:41:19 -0700198
199 cfg_option = 'branch.' + current_branch + '.%s'
200 full_upstream = _run_command(['git', 'config', cfg_option % 'merge']).strip()
201 remote = _run_command(['git', 'config', cfg_option % 'remote']).strip()
202 if not remote or not full_upstream:
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 return full_upstream.replace('heads', 'remotes/' + remote)
206
Ryan Cui1562fb82011-05-09 11:01:31 -0700207
Che-Liang Chiou5ce2d7b2013-03-22 18:47:55 -0700208def _get_patch(commit):
209 """Returns the patch for this commit."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700210 if commit == PRE_SUBMIT:
211 return _run_command(['git', 'diff', '--cached', 'HEAD'])
212 else:
213 return _run_command(['git', 'format-patch', '--stdout', '-1', commit])
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700214
Ryan Cui1562fb82011-05-09 11:01:31 -0700215
Jon Salz98255932012-08-18 14:48:02 +0800216def _try_utf8_decode(data):
217 """Attempts to decode a string as UTF-8.
218
219 Returns:
220 The decoded Unicode object, or the original string if parsing fails.
221 """
222 try:
223 return unicode(data, 'utf-8', 'strict')
224 except UnicodeDecodeError:
225 return data
226
227
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500228def _get_file_content(path, commit):
229 """Returns the content of a file at a specific commit.
230
231 We can't rely on the file as it exists in the filesystem as people might be
232 uploading a series of changes which modifies the file multiple times.
233
234 Note: The "content" of a symlink is just the target. So if you're expecting
235 a full file, you should check that first. One way to detect is that the
236 content will not have any newlines.
237 """
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700238 if commit == PRE_SUBMIT:
239 return _run_command(['git', 'diff', 'HEAD', path])
240 else:
241 return _run_command(['git', 'show', '%s:%s' % (commit, path)])
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500242
243
Mike Frysingerae409522014-02-01 03:16:11 -0500244def _get_file_diff(path, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700245 """Returns a list of (linenum, lines) tuples that the commit touched."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700246 if commit == PRE_SUBMIT:
Prathmesh Prabhua9de1722016-12-22 14:56:40 -0800247 command = ['git', 'diff', '-p', '--pretty=format:', '--no-ext-diff', 'HEAD',
248 path]
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700249 else:
Prathmesh Prabhua9de1722016-12-22 14:56:40 -0800250 command = ['git', 'show', '-p', '--pretty=format:', '--no-ext-diff', commit,
251 path]
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700252 output = _run_command(command)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700253
254 new_lines = []
255 line_num = 0
256 for line in output.splitlines():
257 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
258 if m:
259 line_num = int(m.groups(1)[0])
260 continue
261 if line.startswith('+') and not line.startswith('++'):
Jon Salz98255932012-08-18 14:48:02 +0800262 new_lines.append((line_num, _try_utf8_decode(line[1:])))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700263 if not line.startswith('-'):
264 line_num += 1
265 return new_lines
266
Ryan Cui1562fb82011-05-09 11:01:31 -0700267
Daniel Erate3ea3fc2015-02-13 15:27:52 -0700268def _get_ignore_wildcards(directory, cache):
269 """Get wildcards listed in a directory's _IGNORE_FILE.
270
271 Args:
272 directory: A string containing a directory path.
273 cache: A dictionary (opaque to caller) caching previously-read wildcards.
274
275 Returns:
276 A list of wildcards from _IGNORE_FILE or an empty list if _IGNORE_FILE
277 wasn't present.
278 """
279 # In the cache, keys are directories and values are lists of wildcards from
280 # _IGNORE_FILE within those directories (and empty if no file was present).
281 if directory not in cache:
282 wildcards = []
283 dotfile_path = os.path.join(directory, _IGNORE_FILE)
284 if os.path.exists(dotfile_path):
285 # TODO(derat): Consider using _get_file_content() to get the file as of
286 # this commit instead of the on-disk version. This may have a noticeable
287 # performance impact, as each call to _get_file_content() runs git.
288 with open(dotfile_path, 'r') as dotfile:
289 for line in dotfile.readlines():
290 line = line.strip()
291 if line.startswith('#'):
292 continue
293 if line.endswith('/'):
294 line += '*'
295 wildcards.append(line)
296 cache[directory] = wildcards
297
298 return cache[directory]
299
300
301def _path_is_ignored(path, cache):
302 """Check whether a path is ignored by _IGNORE_FILE.
303
304 Args:
305 path: A string containing a path.
306 cache: A dictionary (opaque to caller) caching previously-read wildcards.
307
308 Returns:
309 True if a file named _IGNORE_FILE in one of the passed-in path's parent
310 directories contains a wildcard matching the path.
311 """
312 # Skip ignore files.
313 if os.path.basename(path) == _IGNORE_FILE:
314 return True
315
316 path = os.path.abspath(path)
317 base = os.getcwd()
318
319 prefix = os.path.dirname(path)
320 while prefix.startswith(base):
321 rel_path = path[len(prefix) + 1:]
322 for wildcard in _get_ignore_wildcards(prefix, cache):
323 if fnmatch.fnmatch(rel_path, wildcard):
324 return True
325 prefix = os.path.dirname(prefix)
326
327 return False
328
329
Mike Frysinger292b45d2014-11-25 01:17:10 -0500330def _get_affected_files(commit, include_deletes=False, relative=False,
331 include_symlinks=False, include_adds=True,
Daniel Erate3ea3fc2015-02-13 15:27:52 -0700332 full_details=False, use_ignore_files=True):
Peter Ammon811f6702014-06-12 15:45:38 -0700333 """Returns list of file paths that were modified/added, excluding symlinks.
334
335 Args:
336 commit: The commit
337 include_deletes: If true, we'll include deleted files in the result
338 relative: Whether to return relative or full paths to files
Mike Frysinger292b45d2014-11-25 01:17:10 -0500339 include_symlinks: If true, we'll include symlinks in the result
340 include_adds: If true, we'll include new files in the result
341 full_details: If False, return filenames, else return structured results.
Daniel Erate3ea3fc2015-02-13 15:27:52 -0700342 use_ignore_files: Whether we ignore files matched by _IGNORE_FILE files.
Peter Ammon811f6702014-06-12 15:45:38 -0700343
344 Returns:
345 A list of modified/added (and perhaps deleted) files
346 """
Mike Frysinger292b45d2014-11-25 01:17:10 -0500347 if not relative and full_details:
348 raise ValueError('full_details only supports relative paths currently')
349
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700350 if commit == PRE_SUBMIT:
351 return _run_command(['git', 'diff-index', '--cached',
352 '--name-only', 'HEAD']).split()
Mike Frysingerd3bd32c2014-11-24 23:34:29 -0500353
354 path = os.getcwd()
355 files = git.RawDiff(path, '%s^!' % commit)
356
357 # Filter out symlinks.
Mike Frysinger292b45d2014-11-25 01:17:10 -0500358 if not include_symlinks:
359 files = [x for x in files if not stat.S_ISLNK(int(x.dst_mode, 8))]
Mike Frysingerd3bd32c2014-11-24 23:34:29 -0500360
361 if not include_deletes:
362 files = [x for x in files if x.status != 'D']
363
Mike Frysinger292b45d2014-11-25 01:17:10 -0500364 if not include_adds:
365 files = [x for x in files if x.status != 'A']
366
Daniel Erate3ea3fc2015-02-13 15:27:52 -0700367 if use_ignore_files:
368 cache = {}
369 is_ignored = lambda x: _path_is_ignored(x.dst_file or x.src_file, cache)
370 files = [x for x in files if not is_ignored(x)]
371
Mike Frysinger292b45d2014-11-25 01:17:10 -0500372 if full_details:
373 # Caller wants the raw objects to parse status/etc... themselves.
Mike Frysingerd3bd32c2014-11-24 23:34:29 -0500374 return files
375 else:
Mike Frysinger292b45d2014-11-25 01:17:10 -0500376 # Caller only cares about filenames.
377 files = [x.dst_file if x.dst_file else x.src_file for x in files]
378 if relative:
379 return files
380 else:
381 return [os.path.join(path, x) for x in files]
Peter Ammon811f6702014-06-12 15:45:38 -0700382
383
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700384def _get_commits():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700385 """Returns a list of commits for this review."""
Ryan Cui4725d952011-05-05 15:41:19 -0700386 cmd = ['git', 'log', '%s..' % _get_upstream_branch(), '--format=%H']
Ryan Cui72834d12011-05-05 14:51:33 -0700387 return _run_command(cmd).split()
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700388
Ryan Cui1562fb82011-05-09 11:01:31 -0700389
Ryan Cuiec4d6332011-05-02 14:15:25 -0700390def _get_commit_desc(commit):
391 """Returns the full commit message of a commit."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700392 if commit == PRE_SUBMIT:
393 return ''
Sean Paul23a2c582011-05-06 13:10:44 -0400394 return _run_command(['git', 'log', '--format=%s%n%n%b', commit + '^!'])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700395
396
Prathmesh Prabhuc5254652016-12-22 12:58:05 -0800397def _check_lines_in_diff(commit, files, check_callable, error_description):
398 """Checks given file for errors via the given check.
399
400 This is a convenience function for common per-line checks. It goes through all
401 files and returns a HookFailure with the error description listing all the
402 failures.
403
404 Args:
405 commit: The commit we're working on.
406 files: The files to check.
407 check_callable: A callable that takes a line and returns True if this line
408 _fails_ the check.
409 error_description: A string describing the error.
410 """
411 errors = []
412 for afile in files:
413 for line_num, line in _get_file_diff(afile, commit):
414 if check_callable(line):
415 errors.append('%s, line %s' % (afile, line_num))
416 if errors:
417 return HookFailure(error_description, errors)
418
419
Ryan Cuiec4d6332011-05-02 14:15:25 -0700420# Common Hooks
421
Ryan Cui1562fb82011-05-09 11:01:31 -0700422
Mike Frysingerae409522014-02-01 03:16:11 -0500423def _check_no_long_lines(_project, commit):
Mike Frysinger55f85b52014-12-18 14:45:21 -0500424 """Checks there are no lines longer than MAX_LEN in any of the text files."""
425
Ryan Cuiec4d6332011-05-02 14:15:25 -0700426 MAX_LEN = 80
Jon Salz98255932012-08-18 14:48:02 +0800427 SKIP_REGEXP = re.compile('|'.join([
428 r'https?://',
429 r'^#\s*(define|include|import|pragma|if|endif)\b']))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700430
431 errors = []
432 files = _filter_files(_get_affected_files(commit),
433 COMMON_INCLUDED_PATHS,
434 COMMON_EXCLUDED_PATHS)
435
436 for afile in files:
437 for line_num, line in _get_file_diff(afile, commit):
438 # Allow certain lines to exceed the maxlen rule.
Mike Frysingerae409522014-02-01 03:16:11 -0500439 if len(line) <= MAX_LEN or SKIP_REGEXP.search(line):
Jon Salz98255932012-08-18 14:48:02 +0800440 continue
441
442 errors.append('%s, line %s, %s chars' % (afile, line_num, len(line)))
443 if len(errors) == 5: # Just show the first 5 errors.
444 break
Ryan Cuiec4d6332011-05-02 14:15:25 -0700445
446 if errors:
447 msg = 'Found lines longer than %s characters (first 5 shown):' % MAX_LEN
Ryan Cui1562fb82011-05-09 11:01:31 -0700448 return HookFailure(msg, errors)
449
Ryan Cuiec4d6332011-05-02 14:15:25 -0700450
Mike Frysingerae409522014-02-01 03:16:11 -0500451def _check_no_stray_whitespace(_project, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700452 """Checks that there is no stray whitespace at source lines end."""
Ryan Cuiec4d6332011-05-02 14:15:25 -0700453 files = _filter_files(_get_affected_files(commit),
Mike Frysingerae409522014-02-01 03:16:11 -0500454 COMMON_INCLUDED_PATHS,
455 COMMON_EXCLUDED_PATHS)
Prathmesh Prabhuc5254652016-12-22 12:58:05 -0800456 return _check_lines_in_diff(commit, files,
457 lambda line: line.rstrip() != line,
458 'Found line ending with white space in:')
Ryan Cui1562fb82011-05-09 11:01:31 -0700459
Ryan Cuiec4d6332011-05-02 14:15:25 -0700460
Mike Frysingerae409522014-02-01 03:16:11 -0500461def _check_no_tabs(_project, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700462 """Checks there are no unexpanded tabs."""
463 TAB_OK_PATHS = [
Ryan Cui31e0c172011-05-04 21:00:45 -0700464 r"/src/third_party/u-boot/",
Ryan Cuiec4d6332011-05-02 14:15:25 -0700465 r".*\.ebuild$",
466 r".*\.eclass$",
Elly Jones5ab34192011-11-15 14:57:06 -0500467 r".*/[M|m]akefile$",
468 r".*\.mk$"
Ryan Cuiec4d6332011-05-02 14:15:25 -0700469 ]
470
Ryan Cuiec4d6332011-05-02 14:15:25 -0700471 files = _filter_files(_get_affected_files(commit),
472 COMMON_INCLUDED_PATHS,
473 COMMON_EXCLUDED_PATHS + TAB_OK_PATHS)
Prathmesh Prabhuc5254652016-12-22 12:58:05 -0800474 return _check_lines_in_diff(commit, files,
475 lambda line: '\t' in line,
476 'Found a tab character in:')
Ryan Cuiec4d6332011-05-02 14:15:25 -0700477
Prathmesh Prabhuc5254652016-12-22 12:58:05 -0800478
479def _check_tabbed_indents(_project, commit):
480 """Checks that indents use tabs only."""
481 TABS_REQUIRED_PATHS = [
482 r".*\.ebuild$",
483 r".*\.eclass$",
484 ]
485 LEADING_SPACE_RE = re.compile('[\t]* ')
486
487 files = _filter_files(_get_affected_files(commit),
488 TABS_REQUIRED_PATHS,
489 COMMON_EXCLUDED_PATHS)
490 return _check_lines_in_diff(
491 commit, files,
492 lambda line: LEADING_SPACE_RE.match(line) is not None,
493 'Found a space in indentation (must be all tabs):')
Ryan Cui1562fb82011-05-09 11:01:31 -0700494
Ryan Cuiec4d6332011-05-02 14:15:25 -0700495
Rahul Chaudhry09f61372015-07-31 17:14:26 -0700496def _check_gofmt(_project, commit):
497 """Checks that Go files are formatted with gofmt."""
498 errors = []
499 files = _filter_files(_get_affected_files(commit, relative=True),
500 [r'\.go$'])
501
502 for gofile in files:
503 contents = _get_file_content(gofile, commit)
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700504 output = _run_command(cmd=['gofmt', '-l'], input=contents,
505 combine_stdout_stderr=True)
Rahul Chaudhry09f61372015-07-31 17:14:26 -0700506 if output:
507 errors.append(gofile)
508 if errors:
509 return HookFailure('Files not formatted with gofmt:', errors)
510
511
Mike Frysingerae409522014-02-01 03:16:11 -0500512def _check_change_has_test_field(_project, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700513 """Check for a non-empty 'TEST=' field in the commit message."""
David McMahon8f6553e2011-06-10 15:46:36 -0700514 TEST_RE = r'\nTEST=\S+'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700515
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700516 if not re.search(TEST_RE, _get_commit_desc(commit)):
Ryan Cui1562fb82011-05-09 11:01:31 -0700517 msg = 'Changelist description needs TEST field (after first line)'
518 return HookFailure(msg)
519
Ryan Cuiec4d6332011-05-02 14:15:25 -0700520
Mike Frysingerae409522014-02-01 03:16:11 -0500521def _check_change_has_valid_cq_depend(_project, commit):
David Jamesc3b68b32013-04-03 09:17:03 -0700522 """Check for a correctly formatted CQ-DEPEND field in the commit message."""
523 msg = 'Changelist has invalid CQ-DEPEND target.'
524 example = 'Example: CQ-DEPEND=CL:1234, CL:2345'
525 try:
526 patch.GetPaladinDeps(_get_commit_desc(commit))
527 except ValueError as ex:
528 return HookFailure(msg, [example, str(ex)])
529
530
Bernie Thompsonf8fea992016-01-14 10:27:18 -0800531def _check_change_is_contribution(_project, commit):
532 """Check that the change is a contribution."""
533 NO_CONTRIB = 'not a contribution'
534 if NO_CONTRIB in _get_commit_desc(commit).lower():
535 msg = ('Changelist is not a contribution, this cannot be accepted.\n'
536 'Please remove the "%s" text from the commit message.') % NO_CONTRIB
537 return HookFailure(msg)
538
539
Alex Deymo643ac4c2015-09-03 10:40:50 -0700540def _check_change_has_bug_field(project, commit):
David McMahon8f6553e2011-06-10 15:46:36 -0700541 """Check for a correctly formatted 'BUG=' field in the commit message."""
David James5c0073d2013-04-03 08:48:52 -0700542 OLD_BUG_RE = r'\nBUG=.*chromium-os'
543 if re.search(OLD_BUG_RE, _get_commit_desc(commit)):
544 msg = ('The chromium-os bug tracker is now deprecated. Please use\n'
545 'the chromium tracker in your BUG= line now.')
546 return HookFailure(msg)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700547
Alex Deymo643ac4c2015-09-03 10:40:50 -0700548 # Android internal and external projects use "Bug: " to track bugs in
549 # buganizer.
550 BUG_COLON_REMOTES = (
551 'aosp',
552 'goog',
553 )
554 if project.remote in BUG_COLON_REMOTES:
555 BUG_RE = r'\nBug: ?([Nn]one|\d+)'
556 if not re.search(BUG_RE, _get_commit_desc(commit)):
557 msg = ('Changelist description needs BUG field (after first line):\n'
558 'Bug: 9999 (for buganizer)\n'
559 'BUG=None')
560 return HookFailure(msg)
561 else:
562 BUG_RE = r'\nBUG=([Nn]one|(chrome-os-partner|chromium|brillo|b):\d+)'
563 if not re.search(BUG_RE, _get_commit_desc(commit)):
564 msg = ('Changelist description needs BUG field (after first line):\n'
565 'BUG=brillo:9999 (for Brillo tracker)\n'
566 'BUG=chromium:9999 (for public tracker)\n'
567 'BUG=chrome-os-partner:9999 (for partner tracker)\n'
568 'BUG=b:9999 (for buganizer)\n'
569 'BUG=None')
570 return HookFailure(msg)
Ryan Cui1562fb82011-05-09 11:01:31 -0700571
Ryan Cuiec4d6332011-05-02 14:15:25 -0700572
Mike Frysinger292b45d2014-11-25 01:17:10 -0500573def _check_for_uprev(project, commit, project_top=None):
Doug Anderson42b8a052013-06-26 10:45:36 -0700574 """Check that we're not missing a revbump of an ebuild in the given commit.
575
576 If the given commit touches files in a directory that has ebuilds somewhere
577 up the directory hierarchy, it's very likely that we need an ebuild revbump
578 in order for those changes to take effect.
579
580 It's not totally trivial to detect a revbump, so at least detect that an
581 ebuild with a revision number in it was touched. This should handle the
582 common case where we use a symlink to do the revbump.
583
584 TODO: it would be nice to enhance this hook to:
585 * Handle cases where people revbump with a slightly different syntax. I see
586 one ebuild (puppy) that revbumps with _pN. This is a false positive.
587 * Catches cases where people aren't using symlinks for revbumps. If they
588 edit a revisioned file directly (and are expected to rename it for revbump)
589 we'll miss that. Perhaps we could detect that the file touched is a
590 symlink?
591
592 If a project doesn't use symlinks we'll potentially miss a revbump, but we're
593 still better off than without this check.
594
595 Args:
Alex Deymo643ac4c2015-09-03 10:40:50 -0700596 project: The Project to look at
Doug Anderson42b8a052013-06-26 10:45:36 -0700597 commit: The commit to look at
Mike Frysinger292b45d2014-11-25 01:17:10 -0500598 project_top: Top dir to process commits in
Doug Anderson42b8a052013-06-26 10:45:36 -0700599
600 Returns:
601 A HookFailure or None.
602 """
Mike Frysinger011af942014-01-17 16:12:22 -0500603 # If this is the portage-stable overlay, then ignore the check. It's rare
604 # that we're doing anything other than importing files from upstream, so
605 # forcing a rev bump makes no sense.
606 whitelist = (
607 'chromiumos/overlays/portage-stable',
608 )
Alex Deymo643ac4c2015-09-03 10:40:50 -0700609 if project.name in whitelist:
Mike Frysinger011af942014-01-17 16:12:22 -0500610 return None
611
Mike Frysinger292b45d2014-11-25 01:17:10 -0500612 def FinalName(obj):
613 # If the file is being deleted, then the dst_file is not set.
614 if obj.dst_file is None:
615 return obj.src_file
616 else:
617 return obj.dst_file
618
619 affected_path_objs = _get_affected_files(
620 commit, include_deletes=True, include_symlinks=True, relative=True,
621 full_details=True)
Doug Anderson42b8a052013-06-26 10:45:36 -0700622
623 # Don't yell about changes to whitelisted files...
Aviv Keshet272f2e52016-04-25 14:49:44 -0700624 whitelist = ('ChangeLog', 'Manifest', 'metadata.xml', 'COMMIT-QUEUE.ini')
Mike Frysinger292b45d2014-11-25 01:17:10 -0500625 affected_path_objs = [x for x in affected_path_objs
626 if os.path.basename(FinalName(x)) not in whitelist]
627 if not affected_path_objs:
Doug Anderson42b8a052013-06-26 10:45:36 -0700628 return None
629
630 # If we've touched any file named with a -rN.ebuild then we'll say we're
631 # OK right away. See TODO above about enhancing this.
Mike Frysinger292b45d2014-11-25 01:17:10 -0500632 touched_revved_ebuild = any(re.search(r'-r\d*\.ebuild$', FinalName(x))
633 for x in affected_path_objs)
Doug Anderson42b8a052013-06-26 10:45:36 -0700634 if touched_revved_ebuild:
635 return None
636
Mike Frysinger292b45d2014-11-25 01:17:10 -0500637 # If we're creating new ebuilds from scratch, then we don't need an uprev.
638 # Find all the dirs that new ebuilds and ignore their files/.
639 ebuild_dirs = [os.path.dirname(FinalName(x)) + '/' for x in affected_path_objs
640 if FinalName(x).endswith('.ebuild') and x.status == 'A']
641 affected_path_objs = [obj for obj in affected_path_objs
642 if not any(FinalName(obj).startswith(x)
643 for x in ebuild_dirs)]
644 if not affected_path_objs:
645 return
646
Doug Anderson42b8a052013-06-26 10:45:36 -0700647 # We want to examine the current contents of all directories that are parents
648 # of files that were touched (up to the top of the project).
649 #
650 # ...note: we use the current directory contents even though it may have
651 # changed since the commit we're looking at. This is just a heuristic after
652 # all. Worst case we don't flag a missing revbump.
Mike Frysinger292b45d2014-11-25 01:17:10 -0500653 if project_top is None:
654 project_top = os.getcwd()
Doug Anderson42b8a052013-06-26 10:45:36 -0700655 dirs_to_check = set([project_top])
Mike Frysinger292b45d2014-11-25 01:17:10 -0500656 for obj in affected_path_objs:
657 path = os.path.join(project_top, os.path.dirname(FinalName(obj)))
Doug Anderson42b8a052013-06-26 10:45:36 -0700658 while os.path.exists(path) and not os.path.samefile(path, project_top):
659 dirs_to_check.add(path)
660 path = os.path.dirname(path)
661
662 # Look through each directory. If it's got an ebuild in it then we'll
663 # consider this as a case when we need a revbump.
Gwendal Grignoua3086c32014-12-09 11:17:22 -0800664 affected_paths = set(os.path.join(project_top, FinalName(x))
665 for x in affected_path_objs)
Doug Anderson42b8a052013-06-26 10:45:36 -0700666 for dir_path in dirs_to_check:
667 contents = os.listdir(dir_path)
668 ebuilds = [os.path.join(dir_path, path)
669 for path in contents if path.endswith('.ebuild')]
670 ebuilds_9999 = [path for path in ebuilds if path.endswith('-9999.ebuild')]
671
672 # If the -9999.ebuild file was touched the bot will uprev for us.
673 # ...we'll use a simple intersection here as a heuristic...
Mike Frysinger292b45d2014-11-25 01:17:10 -0500674 if set(ebuilds_9999) & affected_paths:
Doug Anderson42b8a052013-06-26 10:45:36 -0700675 continue
676
677 if ebuilds:
Mike Frysinger292b45d2014-11-25 01:17:10 -0500678 return HookFailure('Changelist probably needs a revbump of an ebuild, '
679 'or a -r1.ebuild symlink if this is a new ebuild:\n'
680 '%s' % dir_path)
Doug Anderson42b8a052013-06-26 10:45:36 -0700681
682 return None
683
684
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500685def _check_ebuild_eapi(project, commit):
686 """Make sure we have people use EAPI=4 or newer with custom ebuilds.
687
688 We want to get away from older EAPI's as it makes life confusing and they
689 have less builtin error checking.
690
691 Args:
Alex Deymo643ac4c2015-09-03 10:40:50 -0700692 project: The Project to look at
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500693 commit: The commit to look at
694
695 Returns:
696 A HookFailure or None.
697 """
698 # If this is the portage-stable overlay, then ignore the check. It's rare
Mike Frysingercd6adfc2014-02-06 01:03:56 -0500699 # that we're doing anything other than importing files from upstream, and
700 # we shouldn't be rewriting things fundamentally anyways.
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500701 whitelist = (
702 'chromiumos/overlays/portage-stable',
703 )
Alex Deymo643ac4c2015-09-03 10:40:50 -0700704 if project.name in whitelist:
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500705 return None
706
707 BAD_EAPIS = ('0', '1', '2', '3')
708
709 get_eapi = re.compile(r'^\s*EAPI=[\'"]?([^\'"]+)')
710
711 ebuilds_re = [r'\.ebuild$']
712 ebuilds = _filter_files(_get_affected_files(commit, relative=True),
713 ebuilds_re)
714 bad_ebuilds = []
715
716 for ebuild in ebuilds:
717 # If the ebuild does not specify an EAPI, it defaults to 0.
718 eapi = '0'
719
720 lines = _get_file_content(ebuild, commit).splitlines()
721 if len(lines) == 1:
722 # This is most likely a symlink, so skip it entirely.
723 continue
724
725 for line in lines:
726 m = get_eapi.match(line)
727 if m:
728 # Once we hit the first EAPI line in this ebuild, stop processing.
729 # The spec requires that there only be one and it be first, so
730 # checking all possible values is pointless. We also assume that
731 # it's "the" EAPI line and not something in the middle of a heredoc.
732 eapi = m.group(1)
733 break
734
735 if eapi in BAD_EAPIS:
736 bad_ebuilds.append((ebuild, eapi))
737
738 if bad_ebuilds:
739 # pylint: disable=C0301
740 url = 'http://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/upgrade-ebuild-eapis'
741 # pylint: enable=C0301
742 return HookFailure(
Mike Frysingercd6adfc2014-02-06 01:03:56 -0500743 'These ebuilds are using old EAPIs. If these are imported from\n'
744 'Gentoo, then you may ignore and upload once with the --no-verify\n'
745 'flag. Otherwise, please update to 4 or newer.\n'
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500746 '\t%s\n'
747 'See this guide for more details:\n%s\n' %
748 ('\n\t'.join(['%s: EAPI=%s' % x for x in bad_ebuilds]), url))
749
750
Mike Frysinger89bdb852014-02-01 05:26:26 -0500751def _check_ebuild_keywords(_project, commit):
Mike Frysingerc51ece72014-01-17 16:23:40 -0500752 """Make sure we use the new style KEYWORDS when possible in ebuilds.
753
754 If an ebuild generally does not care about the arch it is running on, then
755 ebuilds should flag it with one of:
756 KEYWORDS="*" # A stable ebuild.
757 KEYWORDS="~*" # An unstable ebuild.
758 KEYWORDS="-* ..." # Is known to only work on specific arches.
759
760 Args:
Alex Deymo643ac4c2015-09-03 10:40:50 -0700761 project: The Project to look at
Mike Frysingerc51ece72014-01-17 16:23:40 -0500762 commit: The commit to look at
763
764 Returns:
765 A HookFailure or None.
766 """
767 WHITELIST = set(('*', '-*', '~*'))
768
769 get_keywords = re.compile(r'^\s*KEYWORDS="(.*)"')
770
Mike Frysinger89bdb852014-02-01 05:26:26 -0500771 ebuilds_re = [r'\.ebuild$']
772 ebuilds = _filter_files(_get_affected_files(commit, relative=True),
773 ebuilds_re)
774
Mike Frysinger8d42d742014-09-22 15:50:21 -0400775 bad_ebuilds = []
Mike Frysingerc51ece72014-01-17 16:23:40 -0500776 for ebuild in ebuilds:
Mike Frysinger5c9e58d2014-09-09 03:32:50 -0400777 # We get the full content rather than a diff as the latter does not work
778 # on new files (like when adding new ebuilds).
779 lines = _get_file_content(ebuild, commit).splitlines()
780 for line in lines:
Mike Frysingerc51ece72014-01-17 16:23:40 -0500781 m = get_keywords.match(line)
782 if m:
783 keywords = set(m.group(1).split())
784 if not keywords or WHITELIST - keywords != WHITELIST:
785 continue
786
Mike Frysinger8d42d742014-09-22 15:50:21 -0400787 bad_ebuilds.append(ebuild)
788
789 if bad_ebuilds:
790 return HookFailure(
791 '%s\n'
792 'Please update KEYWORDS to use a glob:\n'
793 'If the ebuild should be marked stable (normal for non-9999 ebuilds):\n'
794 ' KEYWORDS="*"\n'
795 'If the ebuild should be marked unstable (normal for '
796 'cros-workon / 9999 ebuilds):\n'
797 ' KEYWORDS="~*"\n'
Mike Frysingerde8efea2015-05-17 03:42:26 -0400798 'If the ebuild needs to be marked for only specific arches, '
Mike Frysinger8d42d742014-09-22 15:50:21 -0400799 'then use -* like so:\n'
800 ' KEYWORDS="-* arm ..."\n' % '\n* '.join(bad_ebuilds))
Mike Frysingerc51ece72014-01-17 16:23:40 -0500801
802
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800803def _check_ebuild_licenses(_project, commit):
804 """Check if the LICENSE field in the ebuild is correct."""
Brian Norris7a610e82016-02-17 12:24:54 -0800805 affected_paths = _get_affected_files(commit, relative=True)
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800806 touched_ebuilds = [x for x in affected_paths if x.endswith('.ebuild')]
807
808 # A list of licenses to ignore for now.
Yu-Ju Hongc0963fa2014-03-03 12:36:52 -0800809 LICENSES_IGNORE = ['||', '(', ')']
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800810
811 for ebuild in touched_ebuilds:
812 # Skip virutal packages.
813 if ebuild.split('/')[-3] == 'virtual':
814 continue
815
816 try:
Brian Norris7a610e82016-02-17 12:24:54 -0800817 ebuild_content = _get_file_content(ebuild, commit)
818 license_types = licenses_lib.GetLicenseTypesFromEbuild(ebuild_content)
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800819 except ValueError as e:
820 return HookFailure(e.message, [ebuild])
821
822 # Also ignore licenses ending with '?'
823 for license_type in [x for x in license_types
824 if x not in LICENSES_IGNORE and not x.endswith('?')]:
825 try:
Mike Frysinger2ec70ed2014-08-17 19:28:34 -0400826 licenses_lib.Licensing.FindLicenseType(license_type)
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800827 except AssertionError as e:
828 return HookFailure(e.message, [ebuild])
829
830
Mike Frysingercd363c82014-02-01 05:20:18 -0500831def _check_ebuild_virtual_pv(project, commit):
832 """Enforce the virtual PV policies."""
833 # If this is the portage-stable overlay, then ignore the check.
834 # We want to import virtuals as-is from upstream Gentoo.
835 whitelist = (
836 'chromiumos/overlays/portage-stable',
837 )
Alex Deymo643ac4c2015-09-03 10:40:50 -0700838 if project.name in whitelist:
Mike Frysingercd363c82014-02-01 05:20:18 -0500839 return None
840
841 # We assume the repo name is the same as the dir name on disk.
842 # It would be dumb to not have them match though.
Alex Deymo643ac4c2015-09-03 10:40:50 -0700843 project_base = os.path.basename(project.name)
Mike Frysingercd363c82014-02-01 05:20:18 -0500844
845 is_variant = lambda x: x.startswith('overlay-variant-')
846 is_board = lambda x: x.startswith('overlay-')
847 is_private = lambda x: x.endswith('-private')
848
849 get_pv = re.compile(r'(.*?)virtual/([^/]+)/\2-([^/]*)\.ebuild$')
850
851 ebuilds_re = [r'\.ebuild$']
852 ebuilds = _filter_files(_get_affected_files(commit, relative=True),
853 ebuilds_re)
854 bad_ebuilds = []
855
856 for ebuild in ebuilds:
857 m = get_pv.match(ebuild)
858 if m:
859 overlay = m.group(1)
860 if not overlay or not is_board(overlay):
Alex Deymo643ac4c2015-09-03 10:40:50 -0700861 overlay = project_base
Mike Frysingercd363c82014-02-01 05:20:18 -0500862
863 pv = m.group(3).split('-', 1)[0]
864
Bernie Thompsone5ee1822016-01-12 14:22:23 -0800865 # Virtual versions >= 4 are special cases used above the standard
866 # versioning structure, e.g. if one has a board inheriting a board.
867 if float(pv) >= 4:
868 want_pv = pv
869 elif is_private(overlay):
Mike Frysingercd363c82014-02-01 05:20:18 -0500870 want_pv = '3.5' if is_variant(overlay) else '3'
871 elif is_board(overlay):
872 want_pv = '2.5' if is_variant(overlay) else '2'
873 else:
874 want_pv = '1'
875
876 if pv != want_pv:
877 bad_ebuilds.append((ebuild, pv, want_pv))
878
879 if bad_ebuilds:
880 # pylint: disable=C0301
881 url = 'http://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/portage-build-faq#TOC-Virtuals-and-central-management'
882 # pylint: enable=C0301
883 return HookFailure(
884 'These virtuals have incorrect package versions (PVs). Please adjust:\n'
885 '\t%s\n'
886 'If this is an upstream Gentoo virtual, then you may ignore this\n'
887 'check (and re-run w/--no-verify). Otherwise, please see this\n'
888 'page for more details:\n%s\n' %
889 ('\n\t'.join(['%s:\n\t\tPV is %s but should be %s' % x
890 for x in bad_ebuilds]), url))
891
892
Daniel Erat9d203ff2015-02-17 10:12:21 -0700893def _check_portage_make_use_var(_project, commit):
894 """Verify that $USE is set correctly in make.conf and make.defaults."""
895 files = _filter_files(_get_affected_files(commit, relative=True),
896 [r'(^|/)make.(conf|defaults)$'])
897
898 errors = []
899 for path in files:
900 basename = os.path.basename(path)
901
902 # Has a USE= line already been encountered in this file?
903 saw_use = False
904
905 for i, line in enumerate(_get_file_content(path, commit).splitlines(), 1):
906 if not line.startswith('USE='):
907 continue
908
909 preserves_use = '${USE}' in line or '$USE' in line
910
911 if (basename == 'make.conf' or
912 (basename == 'make.defaults' and saw_use)) and not preserves_use:
913 errors.append('%s:%d: missing ${USE}' % (path, i))
914 elif basename == 'make.defaults' and not saw_use and preserves_use:
915 errors.append('%s:%d: ${USE} referenced in initial declaration' %
916 (path, i))
917
918 saw_use = True
919
920 if errors:
921 return HookFailure(
922 'One or more Portage make files appear to set USE incorrectly.\n'
923 '\n'
924 'All USE assignments in make.conf and all assignments after the\n'
925 'initial declaration in make.defaults should contain "${USE}" to\n'
926 'preserve previously-set flags.\n'
927 '\n'
928 'The initial USE declaration in make.defaults should not contain\n'
929 '"${USE}".\n',
930 errors)
931
932
Mike Frysingerae409522014-02-01 03:16:11 -0500933def _check_change_has_proper_changeid(_project, commit):
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700934 """Verify that Change-ID is present in last paragraph of commit message."""
Mike Frysinger4a22bf02014-10-31 13:53:35 -0400935 CHANGE_ID_RE = r'\nChange-Id: I[a-f0-9]+\n'
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700936 desc = _get_commit_desc(commit)
Mike Frysinger4a22bf02014-10-31 13:53:35 -0400937 m = re.search(CHANGE_ID_RE, desc)
Mike Frysinger02b88bd2014-11-21 00:29:38 -0500938 if not m:
Ryan Cui1562fb82011-05-09 11:01:31 -0700939 return HookFailure('Change-Id must be in last paragraph of description.')
940
Mike Frysinger02b88bd2014-11-21 00:29:38 -0500941 # Allow s-o-b tags to follow it, but only those.
942 end = desc[m.end():].strip().splitlines()
943 if [x for x in end if not x.startswith('Signed-off-by: ')]:
944 return HookFailure('Only "Signed-off-by:" tags may follow the Change-Id.')
945
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700946
Mike Frysinger36b2ebc2014-10-31 14:02:03 -0400947def _check_commit_message_style(_project, commit):
948 """Verify that the commit message matches our style.
949
950 We do not check for BUG=/TEST=/etc... lines here as that is handled by other
951 commit hooks.
952 """
953 desc = _get_commit_desc(commit)
954
955 # The first line should be by itself.
956 lines = desc.splitlines()
957 if len(lines) > 1 and lines[1]:
958 return HookFailure('The second line of the commit message must be blank.')
959
960 # The first line should be one sentence.
961 if '. ' in lines[0]:
962 return HookFailure('The first line cannot be more than one sentence.')
963
964 # The first line cannot be too long.
965 MAX_FIRST_LINE_LEN = 100
966 if len(lines[0]) > MAX_FIRST_LINE_LEN:
967 return HookFailure('The first line must be less than %i chars.' %
968 MAX_FIRST_LINE_LEN)
969
970
Filipe Brandenburger4b542b12015-10-09 12:46:31 -0700971def _check_cros_license(_project, commit, options=()):
Alex Deymof5792ce2015-08-24 22:50:08 -0700972 """Verifies the Chromium OS license/copyright header.
Ryan Cuiec4d6332011-05-02 14:15:25 -0700973
Mike Frysinger98638102014-08-28 00:15:08 -0400974 Should be following the spec:
975 http://dev.chromium.org/developers/coding-style#TOC-File-headers
976 """
977 # For older years, be a bit more flexible as our policy says leave them be.
978 LICENSE_HEADER = (
979 r'.* Copyright( \(c\))? 20[-0-9]{2,7} The Chromium OS Authors\. '
Mike Frysingerb81102f2014-11-21 00:33:35 -0500980 r'All rights reserved\.' r'\n'
Mike Frysinger98638102014-08-28 00:15:08 -0400981 r'.* Use of this source code is governed by a BSD-style license that can '
Mike Frysingerb81102f2014-11-21 00:33:35 -0500982 r'be\n'
Mike Frysinger98638102014-08-28 00:15:08 -0400983 r'.* found in the LICENSE file\.'
Mike Frysingerb81102f2014-11-21 00:33:35 -0500984 r'\n'
Mike Frysinger98638102014-08-28 00:15:08 -0400985 )
986 license_re = re.compile(LICENSE_HEADER, re.MULTILINE)
987
988 # For newer years, be stricter.
989 COPYRIGHT_LINE = (
990 r'.* Copyright \(c\) 20(1[5-9]|[2-9][0-9]) The Chromium OS Authors\. '
Mike Frysingerb81102f2014-11-21 00:33:35 -0500991 r'All rights reserved\.' r'\n'
Mike Frysinger98638102014-08-28 00:15:08 -0400992 )
993 copyright_re = re.compile(COPYRIGHT_LINE)
994
Filipe Brandenburger4b542b12015-10-09 12:46:31 -0700995 parser = argparse.ArgumentParser()
996 parser.add_argument('--exclude_regex', action='append')
997 parser.add_argument('--include_regex', action='append')
998 opts = parser.parse_args(options)
999 included = opts.include_regex or []
1000 excluded = opts.exclude_regex or []
1001
Mike Frysinger98638102014-08-28 00:15:08 -04001002 bad_files = []
1003 bad_copyright_files = []
1004 files = _filter_files(_get_affected_files(commit, relative=True),
Filipe Brandenburger4b542b12015-10-09 12:46:31 -07001005 included + COMMON_INCLUDED_PATHS,
1006 excluded + COMMON_EXCLUDED_PATHS)
Mike Frysinger98638102014-08-28 00:15:08 -04001007
1008 for f in files:
1009 contents = _get_file_content(f, commit)
1010 if not contents:
1011 # Ignore empty files.
1012 continue
1013
1014 if not license_re.search(contents):
1015 bad_files.append(f)
1016 elif copyright_re.search(contents):
1017 bad_copyright_files.append(f)
1018
1019 if bad_files:
1020 msg = '%s:\n%s\n%s' % (
1021 'License must match', license_re.pattern,
1022 'Found a bad header in these files:')
1023 return HookFailure(msg, bad_files)
1024
1025 if bad_copyright_files:
1026 msg = 'Do not use (c) in copyright headers in new files:'
1027 return HookFailure(msg, bad_copyright_files)
Ryan Cuiec4d6332011-05-02 14:15:25 -07001028
1029
Alex Deymof5792ce2015-08-24 22:50:08 -07001030def _check_aosp_license(_project, commit):
1031 """Verifies the AOSP license/copyright header.
1032
1033 AOSP uses the Apache2 License:
1034 https://source.android.com/source/licenses.html
1035 """
1036 LICENSE_HEADER = (
1037 r"""^[#/\*]*
1038[#/\*]* ?Copyright( \([cC]\))? 20[-0-9]{2,7} The Android Open Source Project
1039[#/\*]* ?
1040[#/\*]* ?Licensed under the Apache License, Version 2.0 \(the "License"\);
1041[#/\*]* ?you may not use this file except in compliance with the License\.
1042[#/\*]* ?You may obtain a copy of the License at
1043[#/\*]* ?
1044[#/\*]* ? http://www\.apache\.org/licenses/LICENSE-2\.0
1045[#/\*]* ?
1046[#/\*]* ?Unless required by applicable law or agreed to in writing, software
1047[#/\*]* ?distributed under the License is distributed on an "AS IS" BASIS,
1048[#/\*]* ?WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or """
1049 r"""implied\.
1050[#/\*]* ?See the License for the specific language governing permissions and
1051[#/\*]* ?limitations under the License\.
1052[#/\*]*$
1053"""
1054 )
1055 license_re = re.compile(LICENSE_HEADER, re.MULTILINE)
1056
1057 files = _filter_files(_get_affected_files(commit, relative=True),
1058 COMMON_INCLUDED_PATHS,
1059 COMMON_EXCLUDED_PATHS)
1060
1061 bad_files = []
1062 for f in files:
1063 contents = _get_file_content(f, commit)
1064 if not contents:
1065 # Ignore empty files.
1066 continue
1067
1068 if not license_re.search(contents):
1069 bad_files.append(f)
1070
1071 if bad_files:
1072 msg = ('License must match:\n%s\nFound a bad header in these files:' %
1073 license_re.pattern)
1074 return HookFailure(msg, bad_files)
1075
1076
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001077def _check_layout_conf(_project, commit):
1078 """Verifies the metadata/layout.conf file."""
1079 repo_name = 'profiles/repo_name'
Mike Frysinger94a670c2014-09-19 12:46:26 -04001080 repo_names = []
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001081 layout_path = 'metadata/layout.conf'
Mike Frysinger94a670c2014-09-19 12:46:26 -04001082 layout_paths = []
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001083
Mike Frysinger94a670c2014-09-19 12:46:26 -04001084 # Handle multiple overlays in a single commit (like the public tree).
1085 for f in _get_affected_files(commit, relative=True):
1086 if f.endswith(repo_name):
1087 repo_names.append(f)
1088 elif f.endswith(layout_path):
1089 layout_paths.append(f)
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001090
1091 # Disallow new repos with the repo_name file.
Mike Frysinger94a670c2014-09-19 12:46:26 -04001092 if repo_names:
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001093 return HookFailure('%s: use "repo-name" in %s instead' %
Mike Frysinger94a670c2014-09-19 12:46:26 -04001094 (repo_names, layout_path))
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001095
Mike Frysinger94a670c2014-09-19 12:46:26 -04001096 # Gather all the errors in one pass so we show one full message.
1097 all_errors = {}
1098 for layout_path in layout_paths:
1099 all_errors[layout_path] = errors = []
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001100
Mike Frysinger94a670c2014-09-19 12:46:26 -04001101 # Make sure the config file is sorted.
1102 data = [x for x in _get_file_content(layout_path, commit).splitlines()
1103 if x and x[0] != '#']
1104 if sorted(data) != data:
1105 errors += ['keep lines sorted']
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001106
Mike Frysinger94a670c2014-09-19 12:46:26 -04001107 # Require people to set specific values all the time.
1108 settings = (
1109 # TODO: Enable this for everyone. http://crbug.com/408038
1110 #('fast caching', 'cache-format = md5-dict'),
1111 ('fast manifests', 'thin-manifests = true'),
Mike Frysingerd7734522015-02-26 16:12:43 -05001112 ('extra features', 'profile-formats = portage-2 profile-default-eapi'),
1113 ('newer eapi', 'profile_eapi_when_unspecified = 5-progress'),
Mike Frysinger94a670c2014-09-19 12:46:26 -04001114 )
1115 for reason, line in settings:
1116 if line not in data:
1117 errors += ['enable %s with: %s' % (reason, line)]
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001118
Mike Frysinger94a670c2014-09-19 12:46:26 -04001119 # Require one of these settings.
Mike Frysinger5fae62d2015-11-11 20:12:15 -05001120 if 'use-manifests = strict' not in data:
1121 errors += ['enable file checking with: use-manifests = strict']
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001122
Mike Frysinger94a670c2014-09-19 12:46:26 -04001123 # Require repo-name to be set.
Mike Frysinger324cf682014-09-22 15:52:50 -04001124 for line in data:
1125 if line.startswith('repo-name = '):
1126 break
1127 else:
Mike Frysinger94a670c2014-09-19 12:46:26 -04001128 errors += ['set the board name with: repo-name = $BOARD']
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001129
Mike Frysinger94a670c2014-09-19 12:46:26 -04001130 # Summarize all the errors we saw (if any).
1131 lines = ''
1132 for layout_path, errors in all_errors.items():
1133 if errors:
1134 lines += '\n\t- '.join(['\n* %s:' % layout_path] + errors)
1135 if lines:
1136 lines = 'See the portage(5) man page for layout.conf details' + lines + '\n'
1137 return HookFailure(lines)
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001138
1139
Ryan Cuiec4d6332011-05-02 14:15:25 -07001140# Project-specific hooks
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001141
Ryan Cui1562fb82011-05-09 11:01:31 -07001142
Mike Frysingerae409522014-02-01 03:16:11 -05001143def _run_checkpatch(_project, commit, options=()):
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001144 """Runs checkpatch.pl on the given project"""
1145 hooks_dir = _get_hooks_dir()
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001146 options = list(options)
1147 if commit == PRE_SUBMIT:
1148 # The --ignore option must be present and include 'MISSING_SIGN_OFF' in
1149 # this case.
1150 options.append('--ignore=MISSING_SIGN_OFF')
Filipe Brandenburger28d48d62015-10-07 09:48:54 -07001151 # Always ignore the check for the MAINTAINERS file. We do not track that
1152 # information on that file in our source trees, so let's suppress the
1153 # warning.
1154 options.append('--ignore=FILE_PATH_CHANGES')
Filipe Brandenburgerce978322015-10-09 10:04:15 -07001155 # Do not complain about the Change-Id: fields, since we use Gerrit.
1156 # Upstream does not want those lines (since they do not use Gerrit), but
1157 # we always do, so disable the check globally.
Daisuke Nojiri4844f892015-10-08 09:54:33 -07001158 options.append('--ignore=GERRIT_CHANGE_ID')
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001159 cmd = ['%s/checkpatch.pl' % hooks_dir] + options + ['-']
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001160 cmd_result = cros_build_lib.RunCommand(cmd=cmd,
1161 print_cmd=False,
1162 input=_get_patch(commit),
1163 stdout_to_pipe=True,
1164 combine_stdout_stderr=True,
1165 error_code_ok=True)
1166 if cmd_result.returncode:
1167 return HookFailure('checkpatch.pl errors/warnings\n\n' + cmd_result.output)
Ryan Cuiec4d6332011-05-02 14:15:25 -07001168
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001169
Mike Frysingerae409522014-02-01 03:16:11 -05001170def _kernel_configcheck(_project, commit):
Olof Johanssona96810f2012-09-04 16:20:03 -07001171 """Makes sure kernel config changes are not mixed with code changes"""
1172 files = _get_affected_files(commit)
1173 if not len(_filter_files(files, [r'chromeos/config'])) in [0, len(files)]:
1174 return HookFailure('Changes to chromeos/config/ and regular files must '
1175 'be in separate commits:\n%s' % '\n'.join(files))
Anton Staaf815d6852011-08-22 10:08:45 -07001176
Mike Frysingerae409522014-02-01 03:16:11 -05001177
1178def _run_json_check(_project, commit):
Dale Curtis2975c432011-05-03 17:25:20 -07001179 """Checks that all JSON files are syntactically valid."""
Dale Curtisa039cfd2011-05-04 12:01:05 -07001180 for f in _filter_files(_get_affected_files(commit), [r'.*\.json']):
Dale Curtis2975c432011-05-03 17:25:20 -07001181 try:
1182 json.load(open(f))
1183 except Exception, e:
Ryan Cui1562fb82011-05-09 11:01:31 -07001184 return HookFailure('Invalid JSON in %s: %s' % (f, e))
Dale Curtis2975c432011-05-03 17:25:20 -07001185
1186
Mike Frysingerae409522014-02-01 03:16:11 -05001187def _check_manifests(_project, commit):
Mike Frysinger52b537e2013-08-22 22:59:53 -04001188 """Make sure Manifest files only have DIST lines"""
1189 paths = []
1190
1191 for path in _get_affected_files(commit):
1192 if os.path.basename(path) != 'Manifest':
1193 continue
1194 if not os.path.exists(path):
1195 continue
1196
1197 with open(path, 'r') as f:
1198 for line in f.readlines():
1199 if not line.startswith('DIST '):
1200 paths.append(path)
1201 break
1202
1203 if paths:
1204 return HookFailure('Please remove lines that do not start with DIST:\n%s' %
1205 ('\n'.join(paths),))
1206
1207
Mike Frysingerae409522014-02-01 03:16:11 -05001208def _check_change_has_branch_field(_project, commit):
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001209 """Check for a non-empty 'BRANCH=' field in the commit message."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001210 if commit == PRE_SUBMIT:
1211 return
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001212 BRANCH_RE = r'\nBRANCH=\S+'
1213
1214 if not re.search(BRANCH_RE, _get_commit_desc(commit)):
1215 msg = ('Changelist description needs BRANCH field (after first line)\n'
1216 'E.g. BRANCH=none or BRANCH=link,snow')
1217 return HookFailure(msg)
1218
1219
Mike Frysingerae409522014-02-01 03:16:11 -05001220def _check_change_has_signoff_field(_project, commit):
Shawn Nematbakhsh51e16ac2014-01-28 15:31:07 -08001221 """Check for a non-empty 'Signed-off-by:' field in the commit message."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001222 if commit == PRE_SUBMIT:
1223 return
Shawn Nematbakhsh51e16ac2014-01-28 15:31:07 -08001224 SIGNOFF_RE = r'\nSigned-off-by: \S+'
1225
1226 if not re.search(SIGNOFF_RE, _get_commit_desc(commit)):
1227 msg = ('Changelist description needs Signed-off-by: field\n'
1228 'E.g. Signed-off-by: My Name <me@chromium.org>')
1229 return HookFailure(msg)
1230
1231
Jon Salz3ee59de2012-08-18 13:54:22 +08001232def _run_project_hook_script(script, project, commit):
1233 """Runs a project hook script.
1234
1235 The script is run with the following environment variables set:
1236 PRESUBMIT_PROJECT: The affected project
1237 PRESUBMIT_COMMIT: The affected commit
1238 PRESUBMIT_FILES: A newline-separated list of affected files
1239
1240 The script is considered to fail if the exit code is non-zero. It should
1241 write an error message to stdout.
1242 """
1243 env = dict(os.environ)
Alex Deymo643ac4c2015-09-03 10:40:50 -07001244 env['PRESUBMIT_PROJECT'] = project.name
Jon Salz3ee59de2012-08-18 13:54:22 +08001245 env['PRESUBMIT_COMMIT'] = commit
1246
1247 # Put affected files in an environment variable
1248 files = _get_affected_files(commit)
1249 env['PRESUBMIT_FILES'] = '\n'.join(files)
1250
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001251 cmd_result = cros_build_lib.RunCommand(cmd=script,
1252 env=env,
1253 shell=True,
1254 print_cmd=False,
1255 input=os.devnull,
1256 stdout_to_pipe=True,
1257 combine_stdout_stderr=True,
1258 error_code_ok=True)
1259 if cmd_result.returncode:
1260 stdout = cmd_result.output
Jon Salz7b618af2012-08-31 06:03:16 +08001261 if stdout:
1262 stdout = re.sub('(?m)^', ' ', stdout)
1263 return HookFailure('Hook script "%s" failed with code %d%s' %
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001264 (script, cmd_result.returncode,
Jon Salz3ee59de2012-08-18 13:54:22 +08001265 ':\n' + stdout if stdout else ''))
1266
1267
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001268def _check_project_prefix(_project, commit):
Mike Frysinger55f85b52014-12-18 14:45:21 -05001269 """Require the commit message have a project specific prefix as needed."""
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001270
1271 files = _get_affected_files(commit, relative=True)
1272 prefix = os.path.commonprefix(files)
1273 prefix = os.path.dirname(prefix)
1274
1275 # If there is no common prefix, the CL span multiple projects.
Daniel Erata350fd32014-09-29 14:02:34 -07001276 if not prefix:
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001277 return
1278
1279 project_name = prefix.split('/')[0]
Daniel Erata350fd32014-09-29 14:02:34 -07001280
1281 # The common files may all be within a subdirectory of the main project
1282 # directory, so walk up the tree until we find an alias file.
1283 # _get_affected_files() should return relative paths, but check against '/' to
1284 # ensure that this loop terminates even if it receives an absolute path.
1285 while prefix and prefix != '/':
1286 alias_file = os.path.join(prefix, '.project_alias')
1287
1288 # If an alias exists, use it.
1289 if os.path.isfile(alias_file):
1290 project_name = osutils.ReadFile(alias_file).strip()
1291
1292 prefix = os.path.dirname(prefix)
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001293
1294 if not _get_commit_desc(commit).startswith(project_name + ': '):
1295 return HookFailure('The commit title for changes affecting only %s'
1296 ' should start with \"%s: \"'
1297 % (project_name, project_name))
1298
1299
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001300# Base
1301
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001302# A list of hooks which are not project specific and check patch description
1303# (as opposed to patch body).
1304_PATCH_DESCRIPTION_HOOKS = [
Ryan Cui9b651632011-05-11 11:38:58 -07001305 _check_change_has_bug_field,
David Jamesc3b68b32013-04-03 09:17:03 -07001306 _check_change_has_valid_cq_depend,
Ryan Cui9b651632011-05-11 11:38:58 -07001307 _check_change_has_test_field,
1308 _check_change_has_proper_changeid,
Mike Frysinger36b2ebc2014-10-31 14:02:03 -04001309 _check_commit_message_style,
Bernie Thompsonf8fea992016-01-14 10:27:18 -08001310 _check_change_is_contribution,
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001311]
1312
1313
1314# A list of hooks that are not project-specific
1315_COMMON_HOOKS = [
Mike Frysingerbf8b91c2014-02-01 02:50:27 -05001316 _check_ebuild_eapi,
Mike Frysinger89bdb852014-02-01 05:26:26 -05001317 _check_ebuild_keywords,
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -08001318 _check_ebuild_licenses,
Mike Frysingercd363c82014-02-01 05:20:18 -05001319 _check_ebuild_virtual_pv,
Daniel Erat9d203ff2015-02-17 10:12:21 -07001320 _check_for_uprev,
Rahul Chaudhry09f61372015-07-31 17:14:26 -07001321 _check_gofmt,
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001322 _check_layout_conf,
Alex Deymof5792ce2015-08-24 22:50:08 -07001323 _check_cros_license,
Daniel Erat9d203ff2015-02-17 10:12:21 -07001324 _check_no_long_lines,
1325 _check_no_stray_whitespace,
Ryan Cui9b651632011-05-11 11:38:58 -07001326 _check_no_tabs,
Prathmesh Prabhuc5254652016-12-22 12:58:05 -08001327 _check_tabbed_indents,
Daniel Erat9d203ff2015-02-17 10:12:21 -07001328 _check_portage_make_use_var,
Ryan Cui9b651632011-05-11 11:38:58 -07001329]
Ryan Cuiec4d6332011-05-02 14:15:25 -07001330
Ryan Cui1562fb82011-05-09 11:01:31 -07001331
Ryan Cui9b651632011-05-11 11:38:58 -07001332# A dictionary of project-specific hooks(callbacks), indexed by project name.
1333# dict[project] = [callback1, callback2]
1334_PROJECT_SPECIFIC_HOOKS = {
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001335 "chromiumos/platform2": [_check_project_prefix],
Mike Frysingeraf891292015-03-25 19:46:53 -04001336 "chromiumos/third_party/kernel": [_kernel_configcheck],
1337 "chromiumos/third_party/kernel-next": [_kernel_configcheck],
Ryan Cui9b651632011-05-11 11:38:58 -07001338}
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001339
Ryan Cui1562fb82011-05-09 11:01:31 -07001340
Ryan Cui9b651632011-05-11 11:38:58 -07001341# A dictionary of flags (keys) that can appear in the config file, and the hook
Mike Frysinger3554bc92015-03-11 04:59:21 -04001342# that the flag controls (value).
1343_HOOK_FLAGS = {
Mike Frysingera7642f52015-03-25 18:31:42 -04001344 'checkpatch_check': _run_checkpatch,
Ryan Cui9b651632011-05-11 11:38:58 -07001345 'stray_whitespace_check': _check_no_stray_whitespace,
Mike Frysingerff6c7d62015-03-24 13:49:46 -04001346 'json_check': _run_json_check,
Ryan Cui9b651632011-05-11 11:38:58 -07001347 'long_line_check': _check_no_long_lines,
Alex Deymof5792ce2015-08-24 22:50:08 -07001348 'cros_license_check': _check_cros_license,
1349 'aosp_license_check': _check_aosp_license,
Ryan Cui9b651632011-05-11 11:38:58 -07001350 'tab_check': _check_no_tabs,
Prathmesh Prabhuc5254652016-12-22 12:58:05 -08001351 'tabbed_indent_required_check': _check_tabbed_indents,
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001352 'branch_check': _check_change_has_branch_field,
Shawn Nematbakhsh51e16ac2014-01-28 15:31:07 -08001353 'signoff_check': _check_change_has_signoff_field,
Josh Triplett0e8fc7f2014-04-23 16:00:00 -07001354 'bug_field_check': _check_change_has_bug_field,
1355 'test_field_check': _check_change_has_test_field,
Steve Fung49ec7e92015-03-23 16:07:12 -07001356 'manifest_check': _check_manifests,
Bernie Thompsonf8fea992016-01-14 10:27:18 -08001357 'contribution_check': _check_change_is_contribution,
Ryan Cui9b651632011-05-11 11:38:58 -07001358}
1359
1360
Mike Frysinger3554bc92015-03-11 04:59:21 -04001361def _get_override_hooks(config):
1362 """Returns a set of hooks controlled by the current project's config file.
Ryan Cui9b651632011-05-11 11:38:58 -07001363
1364 Expects to be called within the project root.
Jon Salz3ee59de2012-08-18 13:54:22 +08001365
1366 Args:
1367 config: A ConfigParser for the project's config file.
Ryan Cui9b651632011-05-11 11:38:58 -07001368 """
1369 SECTION = 'Hook Overrides'
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001370 SECTION_OPTIONS = 'Hook Overrides Options'
Jon Salz3ee59de2012-08-18 13:54:22 +08001371 if not config.has_section(SECTION):
Mike Frysinger3554bc92015-03-11 04:59:21 -04001372 return set(), set()
Ryan Cui9b651632011-05-11 11:38:58 -07001373
Mike Frysinger3554bc92015-03-11 04:59:21 -04001374 valid_keys = set(_HOOK_FLAGS.iterkeys())
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001375 hooks = _HOOK_FLAGS.copy()
Mike Frysinger3554bc92015-03-11 04:59:21 -04001376
1377 enable_flags = []
Ryan Cui9b651632011-05-11 11:38:58 -07001378 disable_flags = []
Jon Salz3ee59de2012-08-18 13:54:22 +08001379 for flag in config.options(SECTION):
Mike Frysinger3554bc92015-03-11 04:59:21 -04001380 if flag not in valid_keys:
1381 raise ValueError('Error: unknown key "%s" in hook section of "%s"' %
1382 (flag, _CONFIG_FILE))
1383
Ryan Cui9b651632011-05-11 11:38:58 -07001384 try:
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001385 enabled = config.getboolean(SECTION, flag)
Ryan Cui9b651632011-05-11 11:38:58 -07001386 except ValueError as e:
Mike Frysinger3554bc92015-03-11 04:59:21 -04001387 raise ValueError('Error: parsing flag "%s" in "%s" failed: %s' %
1388 (flag, _CONFIG_FILE, e))
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001389 if enabled:
1390 enable_flags.append(flag)
1391 else:
1392 disable_flags.append(flag)
Ryan Cui9b651632011-05-11 11:38:58 -07001393
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001394 # See if this hook has custom options.
1395 if enabled:
1396 try:
1397 options = config.get(SECTION_OPTIONS, flag)
1398 hooks[flag] = functools.partial(hooks[flag], options=options.split())
1399 except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
1400 pass
1401
1402 enabled_hooks = set(hooks[x] for x in enable_flags)
1403 disabled_hooks = set(hooks[x] for x in disable_flags)
Mike Frysinger3554bc92015-03-11 04:59:21 -04001404 return enabled_hooks, disabled_hooks
Ryan Cui9b651632011-05-11 11:38:58 -07001405
1406
Jon Salz3ee59de2012-08-18 13:54:22 +08001407def _get_project_hook_scripts(config):
1408 """Returns a list of project-specific hook scripts.
1409
1410 Args:
1411 config: A ConfigParser for the project's config file.
1412 """
1413 SECTION = 'Hook Scripts'
1414 if not config.has_section(SECTION):
1415 return []
1416
1417 hook_names_values = config.items(SECTION)
1418 hook_names_values.sort(key=lambda x: x[0])
1419 return [x[1] for x in hook_names_values]
1420
1421
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001422def _get_project_hooks(project, presubmit):
Ryan Cui9b651632011-05-11 11:38:58 -07001423 """Returns a list of hooks that need to be run for a project.
1424
1425 Expects to be called from within the project root.
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001426
1427 Args:
1428 project: A string, name of the project.
1429 presubmit: A Boolean, True if the check is run as a git pre-submit script.
Ryan Cui9b651632011-05-11 11:38:58 -07001430 """
Jon Salz3ee59de2012-08-18 13:54:22 +08001431 config = ConfigParser.RawConfigParser()
1432 try:
1433 config.read(_CONFIG_FILE)
1434 except ConfigParser.Error:
1435 # Just use an empty config file
1436 config = ConfigParser.RawConfigParser()
1437
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001438 if presubmit:
Filipe Brandenburgerf70d32c2015-10-09 13:35:45 -07001439 hooks = _COMMON_HOOKS
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001440 else:
Filipe Brandenburgerf70d32c2015-10-09 13:35:45 -07001441 hooks = _PATCH_DESCRIPTION_HOOKS + _COMMON_HOOKS
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001442
Mike Frysinger3554bc92015-03-11 04:59:21 -04001443 enabled_hooks, disabled_hooks = _get_override_hooks(config)
Filipe Brandenburgerf70d32c2015-10-09 13:35:45 -07001444 hooks = [hook for hook in hooks if hook not in disabled_hooks]
1445
1446 # If a list is both in _COMMON_HOOKS and also enabled explicitly through an
1447 # override, keep the override only. Note that the override may end up being
1448 # a functools.partial, in which case we need to extract the .func to compare
1449 # it to the common hooks.
1450 unwrapped_hooks = [getattr(hook, 'func', hook) for hook in enabled_hooks]
1451 hooks = [hook for hook in hooks if hook not in unwrapped_hooks]
1452
1453 hooks = list(enabled_hooks) + hooks
Ryan Cui9b651632011-05-11 11:38:58 -07001454
1455 if project in _PROJECT_SPECIFIC_HOOKS:
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001456 hooks.extend(hook for hook in _PROJECT_SPECIFIC_HOOKS[project]
1457 if hook not in disabled_hooks)
Ryan Cui9b651632011-05-11 11:38:58 -07001458
Jon Salz3ee59de2012-08-18 13:54:22 +08001459 for script in _get_project_hook_scripts(config):
1460 hooks.append(functools.partial(_run_project_hook_script, script))
1461
Ryan Cui9b651632011-05-11 11:38:58 -07001462 return hooks
1463
1464
Alex Deymo643ac4c2015-09-03 10:40:50 -07001465def _run_project_hooks(project_name, proj_dir=None,
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001466 commit_list=None, presubmit=False):
Ryan Cui1562fb82011-05-09 11:01:31 -07001467 """For each project run its project specific hook from the hooks dictionary.
1468
1469 Args:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001470 project_name: The name of project to run hooks for.
Doug Anderson44a644f2011-11-02 10:37:37 -07001471 proj_dir: If non-None, this is the directory the project is in. If None,
1472 we'll ask repo.
Doug Anderson14749562013-06-26 13:38:29 -07001473 commit_list: A list of commits to run hooks against. If None or empty list
1474 then we'll automatically get the list of commits that would be uploaded.
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001475 presubmit: A Boolean, True if the check is run as a git pre-submit script.
Ryan Cui1562fb82011-05-09 11:01:31 -07001476
1477 Returns:
1478 Boolean value of whether any errors were ecountered while running the hooks.
1479 """
Doug Anderson44a644f2011-11-02 10:37:37 -07001480 if proj_dir is None:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001481 proj_dirs = _run_command(
1482 ['repo', 'forall', project_name, '-c', 'pwd']).split()
David James2edd9002013-10-11 14:09:19 -07001483 if len(proj_dirs) == 0:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001484 print('%s cannot be found.' % project_name, file=sys.stderr)
David James2edd9002013-10-11 14:09:19 -07001485 print('Please specify a valid project.', file=sys.stderr)
1486 return True
1487 if len(proj_dirs) > 1:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001488 print('%s is associated with multiple directories.' % project_name,
David James2edd9002013-10-11 14:09:19 -07001489 file=sys.stderr)
1490 print('Please specify a directory to help disambiguate.', file=sys.stderr)
1491 return True
1492 proj_dir = proj_dirs[0]
Doug Anderson44a644f2011-11-02 10:37:37 -07001493
Ryan Cuiec4d6332011-05-02 14:15:25 -07001494 pwd = os.getcwd()
1495 # hooks assume they are run from the root of the project
1496 os.chdir(proj_dir)
1497
Alex Deymo643ac4c2015-09-03 10:40:50 -07001498 remote_branch = _run_command(['git', 'rev-parse', '--abbrev-ref',
1499 '--symbolic-full-name', '@{u}']).strip()
1500 if not remote_branch:
1501 print('Your project %s doesn\'t track any remote repo.' % project_name,
1502 file=sys.stderr)
1503 remote = None
1504 else:
1505 remote, _branch = remote_branch.split('/', 1)
1506
1507 project = Project(name=project_name, dir=proj_dir, remote=remote)
1508
Doug Anderson14749562013-06-26 13:38:29 -07001509 if not commit_list:
1510 try:
1511 commit_list = _get_commits()
1512 except VerifyException as e:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001513 PrintErrorForProject(project.name, HookFailure(str(e)))
Doug Anderson14749562013-06-26 13:38:29 -07001514 os.chdir(pwd)
1515 return True
Ryan Cuifa55df52011-05-06 11:16:55 -07001516
Alex Deymo643ac4c2015-09-03 10:40:50 -07001517 hooks = _get_project_hooks(project.name, presubmit)
Ryan Cui1562fb82011-05-09 11:01:31 -07001518 error_found = False
Ryan Cuifa55df52011-05-06 11:16:55 -07001519 for commit in commit_list:
Ryan Cui1562fb82011-05-09 11:01:31 -07001520 error_list = []
Ryan Cui9b651632011-05-11 11:38:58 -07001521 for hook in hooks:
Ryan Cui1562fb82011-05-09 11:01:31 -07001522 hook_error = hook(project, commit)
1523 if hook_error:
1524 error_list.append(hook_error)
1525 error_found = True
1526 if error_list:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001527 PrintErrorsForCommit(project.name, commit, _get_commit_desc(commit),
Ryan Cui1562fb82011-05-09 11:01:31 -07001528 error_list)
Don Garrettdba548a2011-05-05 15:17:14 -07001529
Ryan Cuiec4d6332011-05-02 14:15:25 -07001530 os.chdir(pwd)
Ryan Cui1562fb82011-05-09 11:01:31 -07001531 return error_found
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001532
Mike Frysingerae409522014-02-01 03:16:11 -05001533
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001534# Main
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -07001535
Ryan Cui1562fb82011-05-09 11:01:31 -07001536
Mike Frysingerae409522014-02-01 03:16:11 -05001537def main(project_list, worktree_list=None, **_kwargs):
Doug Anderson06456632012-01-05 11:02:14 -08001538 """Main function invoked directly by repo.
1539
1540 This function will exit directly upon error so that repo doesn't print some
1541 obscure error message.
1542
1543 Args:
1544 project_list: List of projects to run on.
David James2edd9002013-10-11 14:09:19 -07001545 worktree_list: A list of directories. It should be the same length as
1546 project_list, so that each entry in project_list matches with a directory
1547 in worktree_list. If None, we will attempt to calculate the directories
1548 automatically.
Doug Anderson06456632012-01-05 11:02:14 -08001549 kwargs: Leave this here for forward-compatibility.
1550 """
Ryan Cui1562fb82011-05-09 11:01:31 -07001551 found_error = False
David James2edd9002013-10-11 14:09:19 -07001552 if not worktree_list:
1553 worktree_list = [None] * len(project_list)
1554 for project, worktree in zip(project_list, worktree_list):
1555 if _run_project_hooks(project, proj_dir=worktree):
Ryan Cui1562fb82011-05-09 11:01:31 -07001556 found_error = True
1557
Mike Frysingerae409522014-02-01 03:16:11 -05001558 if found_error:
Ryan Cui1562fb82011-05-09 11:01:31 -07001559 msg = ('Preupload failed due to errors in project(s). HINTS:\n'
Ryan Cui9b651632011-05-11 11:38:58 -07001560 '- To disable some source style checks, and for other hints, see '
1561 '<checkout_dir>/src/repohooks/README\n'
1562 '- To upload only current project, run \'repo upload .\'')
Mike Frysinger09d6a3d2013-10-08 22:21:03 -04001563 print(msg, file=sys.stderr)
Don Garrettdba548a2011-05-05 15:17:14 -07001564 sys.exit(1)
Anush Elangovan63afad72011-03-23 00:41:27 -07001565
Ryan Cui1562fb82011-05-09 11:01:31 -07001566
Doug Anderson44a644f2011-11-02 10:37:37 -07001567def _identify_project(path):
1568 """Identify the repo project associated with the given path.
1569
1570 Returns:
1571 A string indicating what project is associated with the path passed in or
1572 a blank string upon failure.
1573 """
1574 return _run_command(['repo', 'forall', '.', '-c', 'echo ${REPO_PROJECT}'],
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001575 redirect_stderr=True, cwd=path).strip()
Doug Anderson44a644f2011-11-02 10:37:37 -07001576
1577
Mike Frysinger55f85b52014-12-18 14:45:21 -05001578def direct_main(argv):
Doug Anderson44a644f2011-11-02 10:37:37 -07001579 """Run hooks directly (outside of the context of repo).
1580
Doug Anderson44a644f2011-11-02 10:37:37 -07001581 Args:
Mike Frysinger55f85b52014-12-18 14:45:21 -05001582 argv: The command line args to process
Doug Anderson44a644f2011-11-02 10:37:37 -07001583
1584 Returns:
1585 0 if no pre-upload failures, 1 if failures.
1586
1587 Raises:
1588 BadInvocation: On some types of invocation errors.
1589 """
Mike Frysinger66142932014-12-18 14:55:57 -05001590 parser = commandline.ArgumentParser(description=__doc__)
1591 parser.add_argument('--dir', default=None,
1592 help='The directory that the project lives in. If not '
1593 'specified, use the git project root based on the cwd.')
1594 parser.add_argument('--project', default=None,
1595 help='The project repo path; this can affect how the '
1596 'hooks get run, since some hooks are project-specific. '
1597 'For chromite this is chromiumos/chromite. If not '
1598 'specified, the repo tool will be used to figure this '
1599 'out based on the dir.')
1600 parser.add_argument('--rerun-since', default=None,
1601 help='Rerun hooks on old commits since the given date. '
1602 'The date should match git log\'s concept of a date. '
1603 'e.g. 2012-06-20. This option is mutually exclusive '
1604 'with --pre-submit.')
1605 parser.add_argument('--pre-submit', action="store_true",
1606 help='Run the check against the pending commit. '
1607 'This option should be used at the \'git commit\' '
1608 'phase as opposed to \'repo upload\'. This option '
1609 'is mutually exclusive with --rerun-since.')
1610 parser.add_argument('commits', nargs='*',
1611 help='Check specific commits')
1612 opts = parser.parse_args(argv)
Doug Anderson44a644f2011-11-02 10:37:37 -07001613
Doug Anderson14749562013-06-26 13:38:29 -07001614 if opts.rerun_since:
Mike Frysinger66142932014-12-18 14:55:57 -05001615 if opts.commits:
Doug Anderson14749562013-06-26 13:38:29 -07001616 raise BadInvocation('Can\'t pass commits and use rerun-since: %s' %
Mike Frysinger66142932014-12-18 14:55:57 -05001617 ' '.join(opts.commits))
Doug Anderson14749562013-06-26 13:38:29 -07001618
1619 cmd = ['git', 'log', '--since="%s"' % opts.rerun_since, '--pretty=%H']
1620 all_commits = _run_command(cmd).splitlines()
1621 bot_commits = _run_command(cmd + ['--author=chrome-bot']).splitlines()
1622
1623 # Eliminate chrome-bot commits but keep ordering the same...
1624 bot_commits = set(bot_commits)
Mike Frysinger66142932014-12-18 14:55:57 -05001625 opts.commits = [c for c in all_commits if c not in bot_commits]
Doug Anderson14749562013-06-26 13:38:29 -07001626
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001627 if opts.pre_submit:
1628 raise BadInvocation('rerun-since and pre-submit can not be '
1629 'used together')
1630 if opts.pre_submit:
Mike Frysinger66142932014-12-18 14:55:57 -05001631 if opts.commits:
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001632 raise BadInvocation('Can\'t pass commits and use pre-submit: %s' %
Mike Frysinger66142932014-12-18 14:55:57 -05001633 ' '.join(opts.commits))
1634 opts.commits = [PRE_SUBMIT,]
Doug Anderson44a644f2011-11-02 10:37:37 -07001635
1636 # Check/normlaize git dir; if unspecified, we'll use the root of the git
1637 # project from CWD
1638 if opts.dir is None:
1639 git_dir = _run_command(['git', 'rev-parse', '--git-dir'],
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001640 redirect_stderr=True).strip()
Doug Anderson44a644f2011-11-02 10:37:37 -07001641 if not git_dir:
1642 raise BadInvocation('The current directory is not part of a git project.')
1643 opts.dir = os.path.dirname(os.path.abspath(git_dir))
1644 elif not os.path.isdir(opts.dir):
1645 raise BadInvocation('Invalid dir: %s' % opts.dir)
1646 elif not os.path.isdir(os.path.join(opts.dir, '.git')):
1647 raise BadInvocation('Not a git directory: %s' % opts.dir)
1648
1649 # Identify the project if it wasn't specified; this _requires_ the repo
1650 # tool to be installed and for the project to be part of a repo checkout.
1651 if not opts.project:
1652 opts.project = _identify_project(opts.dir)
1653 if not opts.project:
1654 raise BadInvocation("Repo couldn't identify the project of %s" % opts.dir)
1655
Doug Anderson14749562013-06-26 13:38:29 -07001656 found_error = _run_project_hooks(opts.project, proj_dir=opts.dir,
Mike Frysinger66142932014-12-18 14:55:57 -05001657 commit_list=opts.commits,
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001658 presubmit=opts.pre_submit)
Doug Anderson44a644f2011-11-02 10:37:37 -07001659 if found_error:
1660 return 1
1661 return 0
1662
1663
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -07001664if __name__ == '__main__':
Mike Frysinger55f85b52014-12-18 14:45:21 -05001665 sys.exit(direct_main(sys.argv[1:]))