blob: 969d82890cb6053799e8ac6b8dd40e6aad551215 [file] [log] [blame]
Daniel Erat9d203ff2015-02-17 10:12:21 -07001#!/usr/bin/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$",
Ryan Cuiec4d6332011-05-02 14:15:25 -070053]
54
Ryan Cui1562fb82011-05-09 11:01:31 -070055
Ryan Cuiec4d6332011-05-02 14:15:25 -070056COMMON_EXCLUDED_PATHS = [
Daniel Erate3ea3fc2015-02-13 15:27:52 -070057 # Avoid doing source file checks for kernel.
Mike Frysingerae409522014-02-01 03:16:11 -050058 r"/src/third_party/kernel/",
59 r"/src/third_party/kernel-next/",
60 r"/src/third_party/ktop/",
61 r"/src/third_party/punybench/",
62 r".*\bexperimental[\\\/].*",
63 r".*\b[A-Z0-9_]{2,}$",
64 r".*[\\\/]debian[\\\/]rules$",
Daniel Erate3ea3fc2015-02-13 15:27:52 -070065
66 # For ebuild trees, ignore any caches and manifest data.
Mike Frysingerae409522014-02-01 03:16:11 -050067 r".*/Manifest$",
68 r".*/metadata/[^/]*cache[^/]*/[^/]+/[^/]+$",
Doug Anderson5bfb6792011-10-25 16:45:41 -070069
Daniel Erate3ea3fc2015-02-13 15:27:52 -070070 # Ignore profiles data (like overlay-tegra2/profiles).
Mike Frysinger94a670c2014-09-19 12:46:26 -040071 r"(^|.*/)overlay-.*/profiles/.*",
Mike Frysinger98638102014-08-28 00:15:08 -040072 r"^profiles/.*$",
73
Daniel Erate3ea3fc2015-02-13 15:27:52 -070074 # Ignore minified js and jquery.
Mike Frysingerae409522014-02-01 03:16:11 -050075 r".*\.min\.js",
76 r".*jquery.*\.js",
Mike Frysinger33a458d2014-03-03 17:00:51 -050077
78 # Ignore license files as the content is often taken verbatim.
Daniel Erate3ea3fc2015-02-13 15:27:52 -070079 r".*/licenses/.*",
Ryan Cuiec4d6332011-05-02 14:15:25 -070080]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070081
Ryan Cui1562fb82011-05-09 11:01:31 -070082
Ryan Cui9b651632011-05-11 11:38:58 -070083_CONFIG_FILE = 'PRESUBMIT.cfg'
84
85
Daniel Erate3ea3fc2015-02-13 15:27:52 -070086# File containing wildcards, one per line, matching files that should be
87# excluded from presubmit checks. Lines beginning with '#' are ignored.
88_IGNORE_FILE = '.presubmitignore'
89
90
Doug Anderson44a644f2011-11-02 10:37:37 -070091# Exceptions
92
93
94class BadInvocation(Exception):
95 """An Exception indicating a bad invocation of the program."""
96 pass
97
98
Ryan Cui1562fb82011-05-09 11:01:31 -070099# General Helpers
100
Sean Paulba01d402011-05-05 11:36:23 -0400101
Alex Deymo643ac4c2015-09-03 10:40:50 -0700102Project = collections.namedtuple('Project', ['name', 'dir', 'remote'])
103
104
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700105# pylint: disable=redefined-builtin
106def _run_command(cmd, cwd=None, input=None,
107 redirect_stderr=False, combine_stdout_stderr=False):
Doug Anderson44a644f2011-11-02 10:37:37 -0700108 """Executes the passed in command and returns raw stdout output.
109
110 Args:
111 cmd: The command to run; should be a list of strings.
112 cwd: The directory to switch to for running the command.
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700113 input: The data to pipe into this command through stdin. If a file object
114 or file descriptor, stdin will be connected directly to that.
115 redirect_stderr: Redirect stderr away from console.
116 combine_stdout_stderr: Combines stdout and stderr streams into stdout.
Doug Anderson44a644f2011-11-02 10:37:37 -0700117
118 Returns:
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700119 The stdout from the process (discards stderr and returncode).
Doug Anderson44a644f2011-11-02 10:37:37 -0700120 """
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700121 return cros_build_lib.RunCommand(cmd=cmd,
122 cwd=cwd,
123 print_cmd=False,
124 input=input,
125 stdout_to_pipe=True,
126 redirect_stderr=redirect_stderr,
127 combine_stdout_stderr=combine_stdout_stderr,
128 error_code_ok=True).output
129# pylint: enable=redefined-builtin
Ryan Cui72834d12011-05-05 14:51:33 -0700130
Ryan Cui1562fb82011-05-09 11:01:31 -0700131
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700132def _get_hooks_dir():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700133 """Returns the absolute path to the repohooks directory."""
Doug Anderson44a644f2011-11-02 10:37:37 -0700134 if __name__ == '__main__':
135 # Works when file is run on its own (__file__ is defined)...
136 return os.path.abspath(os.path.dirname(__file__))
137 else:
138 # We need to do this when we're run through repo. Since repo executes
139 # us with execfile(), we don't get __file__ defined.
140 cmd = ['repo', 'forall', 'chromiumos/repohooks', '-c', 'pwd']
141 return _run_command(cmd).strip()
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700142
Ryan Cui1562fb82011-05-09 11:01:31 -0700143
Ryan Cuiec4d6332011-05-02 14:15:25 -0700144def _match_regex_list(subject, expressions):
145 """Try to match a list of regular expressions to a string.
146
147 Args:
148 subject: The string to match regexes on
149 expressions: A list of regular expressions to check for matches with.
150
151 Returns:
152 Whether the passed in subject matches any of the passed in regexes.
153 """
154 for expr in expressions:
Mike Frysingerae409522014-02-01 03:16:11 -0500155 if re.search(expr, subject):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700156 return True
157 return False
158
Ryan Cui1562fb82011-05-09 11:01:31 -0700159
Mike Frysingerae409522014-02-01 03:16:11 -0500160def _filter_files(files, include_list, exclude_list=()):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700161 """Filter out files based on the conditions passed in.
162
163 Args:
164 files: list of filepaths to filter
165 include_list: list of regex that when matched with a file path will cause it
166 to be added to the output list unless the file is also matched with a
167 regex in the exclude_list.
168 exclude_list: list of regex that when matched with a file will prevent it
169 from being added to the output list, even if it is also matched with a
170 regex in the include_list.
171
172 Returns:
173 A list of filepaths that contain files matched in the include_list and not
174 in the exclude_list.
175 """
176 filtered = []
177 for f in files:
178 if (_match_regex_list(f, include_list) and
179 not _match_regex_list(f, exclude_list)):
180 filtered.append(f)
181 return filtered
182
Ryan Cuiec4d6332011-05-02 14:15:25 -0700183
184# Git Helpers
Ryan Cui1562fb82011-05-09 11:01:31 -0700185
186
Ryan Cui4725d952011-05-05 15:41:19 -0700187def _get_upstream_branch():
188 """Returns the upstream tracking branch of the current branch.
189
190 Raises:
191 Error if there is no tracking branch
192 """
193 current_branch = _run_command(['git', 'symbolic-ref', 'HEAD']).strip()
194 current_branch = current_branch.replace('refs/heads/', '')
195 if not current_branch:
Ryan Cui1562fb82011-05-09 11:01:31 -0700196 raise VerifyException('Need to be on a tracking branch')
Ryan Cui4725d952011-05-05 15:41:19 -0700197
198 cfg_option = 'branch.' + current_branch + '.%s'
199 full_upstream = _run_command(['git', 'config', cfg_option % 'merge']).strip()
200 remote = _run_command(['git', 'config', cfg_option % 'remote']).strip()
201 if not remote or not full_upstream:
Ryan Cui1562fb82011-05-09 11:01:31 -0700202 raise VerifyException('Need to be on a tracking branch')
Ryan Cui4725d952011-05-05 15:41:19 -0700203
204 return full_upstream.replace('heads', 'remotes/' + remote)
205
Ryan Cui1562fb82011-05-09 11:01:31 -0700206
Che-Liang Chiou5ce2d7b2013-03-22 18:47:55 -0700207def _get_patch(commit):
208 """Returns the patch for this commit."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700209 if commit == PRE_SUBMIT:
210 return _run_command(['git', 'diff', '--cached', 'HEAD'])
211 else:
212 return _run_command(['git', 'format-patch', '--stdout', '-1', commit])
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700213
Ryan Cui1562fb82011-05-09 11:01:31 -0700214
Jon Salz98255932012-08-18 14:48:02 +0800215def _try_utf8_decode(data):
216 """Attempts to decode a string as UTF-8.
217
218 Returns:
219 The decoded Unicode object, or the original string if parsing fails.
220 """
221 try:
222 return unicode(data, 'utf-8', 'strict')
223 except UnicodeDecodeError:
224 return data
225
226
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500227def _get_file_content(path, commit):
228 """Returns the content of a file at a specific commit.
229
230 We can't rely on the file as it exists in the filesystem as people might be
231 uploading a series of changes which modifies the file multiple times.
232
233 Note: The "content" of a symlink is just the target. So if you're expecting
234 a full file, you should check that first. One way to detect is that the
235 content will not have any newlines.
236 """
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700237 if commit == PRE_SUBMIT:
238 return _run_command(['git', 'diff', 'HEAD', path])
239 else:
240 return _run_command(['git', 'show', '%s:%s' % (commit, path)])
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500241
242
Mike Frysingerae409522014-02-01 03:16:11 -0500243def _get_file_diff(path, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700244 """Returns a list of (linenum, lines) tuples that the commit touched."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700245 command = ['git', 'diff', '-p', '--pretty=format:', '--no-ext-diff']
246 if commit == PRE_SUBMIT:
247 command += ['HEAD', path]
248 else:
249 command += [commit, path]
250 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
395# Common Hooks
396
Ryan Cui1562fb82011-05-09 11:01:31 -0700397
Mike Frysingerae409522014-02-01 03:16:11 -0500398def _check_no_long_lines(_project, commit):
Mike Frysinger55f85b52014-12-18 14:45:21 -0500399 """Checks there are no lines longer than MAX_LEN in any of the text files."""
400
Ryan Cuiec4d6332011-05-02 14:15:25 -0700401 MAX_LEN = 80
Jon Salz98255932012-08-18 14:48:02 +0800402 SKIP_REGEXP = re.compile('|'.join([
403 r'https?://',
404 r'^#\s*(define|include|import|pragma|if|endif)\b']))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700405
406 errors = []
407 files = _filter_files(_get_affected_files(commit),
408 COMMON_INCLUDED_PATHS,
409 COMMON_EXCLUDED_PATHS)
410
411 for afile in files:
412 for line_num, line in _get_file_diff(afile, commit):
413 # Allow certain lines to exceed the maxlen rule.
Mike Frysingerae409522014-02-01 03:16:11 -0500414 if len(line) <= MAX_LEN or SKIP_REGEXP.search(line):
Jon Salz98255932012-08-18 14:48:02 +0800415 continue
416
417 errors.append('%s, line %s, %s chars' % (afile, line_num, len(line)))
418 if len(errors) == 5: # Just show the first 5 errors.
419 break
Ryan Cuiec4d6332011-05-02 14:15:25 -0700420
421 if errors:
422 msg = 'Found lines longer than %s characters (first 5 shown):' % MAX_LEN
Ryan Cui1562fb82011-05-09 11:01:31 -0700423 return HookFailure(msg, errors)
424
Ryan Cuiec4d6332011-05-02 14:15:25 -0700425
Mike Frysingerae409522014-02-01 03:16:11 -0500426def _check_no_stray_whitespace(_project, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700427 """Checks that there is no stray whitespace at source lines end."""
428 errors = []
429 files = _filter_files(_get_affected_files(commit),
Mike Frysingerae409522014-02-01 03:16:11 -0500430 COMMON_INCLUDED_PATHS,
431 COMMON_EXCLUDED_PATHS)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700432 for afile in files:
433 for line_num, line in _get_file_diff(afile, commit):
434 if line.rstrip() != line:
435 errors.append('%s, line %s' % (afile, line_num))
436 if errors:
Ryan Cui1562fb82011-05-09 11:01:31 -0700437 return HookFailure('Found line ending with white space in:', errors)
438
Ryan Cuiec4d6332011-05-02 14:15:25 -0700439
Mike Frysingerae409522014-02-01 03:16:11 -0500440def _check_no_tabs(_project, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700441 """Checks there are no unexpanded tabs."""
442 TAB_OK_PATHS = [
Ryan Cui31e0c172011-05-04 21:00:45 -0700443 r"/src/third_party/u-boot/",
Ryan Cuiec4d6332011-05-02 14:15:25 -0700444 r".*\.ebuild$",
445 r".*\.eclass$",
Elly Jones5ab34192011-11-15 14:57:06 -0500446 r".*/[M|m]akefile$",
447 r".*\.mk$"
Ryan Cuiec4d6332011-05-02 14:15:25 -0700448 ]
449
450 errors = []
451 files = _filter_files(_get_affected_files(commit),
452 COMMON_INCLUDED_PATHS,
453 COMMON_EXCLUDED_PATHS + TAB_OK_PATHS)
454
455 for afile in files:
456 for line_num, line in _get_file_diff(afile, commit):
457 if '\t' in line:
Mike Frysingerae409522014-02-01 03:16:11 -0500458 errors.append('%s, line %s' % (afile, line_num))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700459 if errors:
Ryan Cui1562fb82011-05-09 11:01:31 -0700460 return HookFailure('Found a tab character in:', errors)
461
Ryan Cuiec4d6332011-05-02 14:15:25 -0700462
Rahul Chaudhry09f61372015-07-31 17:14:26 -0700463def _check_gofmt(_project, commit):
464 """Checks that Go files are formatted with gofmt."""
465 errors = []
466 files = _filter_files(_get_affected_files(commit, relative=True),
467 [r'\.go$'])
468
469 for gofile in files:
470 contents = _get_file_content(gofile, commit)
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700471 output = _run_command(cmd=['gofmt', '-l'], input=contents,
472 combine_stdout_stderr=True)
Rahul Chaudhry09f61372015-07-31 17:14:26 -0700473 if output:
474 errors.append(gofile)
475 if errors:
476 return HookFailure('Files not formatted with gofmt:', errors)
477
478
Mike Frysingerae409522014-02-01 03:16:11 -0500479def _check_change_has_test_field(_project, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700480 """Check for a non-empty 'TEST=' field in the commit message."""
David McMahon8f6553e2011-06-10 15:46:36 -0700481 TEST_RE = r'\nTEST=\S+'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700482
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700483 if not re.search(TEST_RE, _get_commit_desc(commit)):
Ryan Cui1562fb82011-05-09 11:01:31 -0700484 msg = 'Changelist description needs TEST field (after first line)'
485 return HookFailure(msg)
486
Ryan Cuiec4d6332011-05-02 14:15:25 -0700487
Mike Frysingerae409522014-02-01 03:16:11 -0500488def _check_change_has_valid_cq_depend(_project, commit):
David Jamesc3b68b32013-04-03 09:17:03 -0700489 """Check for a correctly formatted CQ-DEPEND field in the commit message."""
490 msg = 'Changelist has invalid CQ-DEPEND target.'
491 example = 'Example: CQ-DEPEND=CL:1234, CL:2345'
492 try:
493 patch.GetPaladinDeps(_get_commit_desc(commit))
494 except ValueError as ex:
495 return HookFailure(msg, [example, str(ex)])
496
497
Bernie Thompsonf8fea992016-01-14 10:27:18 -0800498def _check_change_is_contribution(_project, commit):
499 """Check that the change is a contribution."""
500 NO_CONTRIB = 'not a contribution'
501 if NO_CONTRIB in _get_commit_desc(commit).lower():
502 msg = ('Changelist is not a contribution, this cannot be accepted.\n'
503 'Please remove the "%s" text from the commit message.') % NO_CONTRIB
504 return HookFailure(msg)
505
506
Alex Deymo643ac4c2015-09-03 10:40:50 -0700507def _check_change_has_bug_field(project, commit):
David McMahon8f6553e2011-06-10 15:46:36 -0700508 """Check for a correctly formatted 'BUG=' field in the commit message."""
David James5c0073d2013-04-03 08:48:52 -0700509 OLD_BUG_RE = r'\nBUG=.*chromium-os'
510 if re.search(OLD_BUG_RE, _get_commit_desc(commit)):
511 msg = ('The chromium-os bug tracker is now deprecated. Please use\n'
512 'the chromium tracker in your BUG= line now.')
513 return HookFailure(msg)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700514
Alex Deymo643ac4c2015-09-03 10:40:50 -0700515 # Android internal and external projects use "Bug: " to track bugs in
516 # buganizer.
517 BUG_COLON_REMOTES = (
518 'aosp',
519 'goog',
520 )
521 if project.remote in BUG_COLON_REMOTES:
522 BUG_RE = r'\nBug: ?([Nn]one|\d+)'
523 if not re.search(BUG_RE, _get_commit_desc(commit)):
524 msg = ('Changelist description needs BUG field (after first line):\n'
525 'Bug: 9999 (for buganizer)\n'
526 'BUG=None')
527 return HookFailure(msg)
528 else:
529 BUG_RE = r'\nBUG=([Nn]one|(chrome-os-partner|chromium|brillo|b):\d+)'
530 if not re.search(BUG_RE, _get_commit_desc(commit)):
531 msg = ('Changelist description needs BUG field (after first line):\n'
532 'BUG=brillo:9999 (for Brillo tracker)\n'
533 'BUG=chromium:9999 (for public tracker)\n'
534 'BUG=chrome-os-partner:9999 (for partner tracker)\n'
535 'BUG=b:9999 (for buganizer)\n'
536 'BUG=None')
537 return HookFailure(msg)
Ryan Cui1562fb82011-05-09 11:01:31 -0700538
Ryan Cuiec4d6332011-05-02 14:15:25 -0700539
Mike Frysinger292b45d2014-11-25 01:17:10 -0500540def _check_for_uprev(project, commit, project_top=None):
Doug Anderson42b8a052013-06-26 10:45:36 -0700541 """Check that we're not missing a revbump of an ebuild in the given commit.
542
543 If the given commit touches files in a directory that has ebuilds somewhere
544 up the directory hierarchy, it's very likely that we need an ebuild revbump
545 in order for those changes to take effect.
546
547 It's not totally trivial to detect a revbump, so at least detect that an
548 ebuild with a revision number in it was touched. This should handle the
549 common case where we use a symlink to do the revbump.
550
551 TODO: it would be nice to enhance this hook to:
552 * Handle cases where people revbump with a slightly different syntax. I see
553 one ebuild (puppy) that revbumps with _pN. This is a false positive.
554 * Catches cases where people aren't using symlinks for revbumps. If they
555 edit a revisioned file directly (and are expected to rename it for revbump)
556 we'll miss that. Perhaps we could detect that the file touched is a
557 symlink?
558
559 If a project doesn't use symlinks we'll potentially miss a revbump, but we're
560 still better off than without this check.
561
562 Args:
Alex Deymo643ac4c2015-09-03 10:40:50 -0700563 project: The Project to look at
Doug Anderson42b8a052013-06-26 10:45:36 -0700564 commit: The commit to look at
Mike Frysinger292b45d2014-11-25 01:17:10 -0500565 project_top: Top dir to process commits in
Doug Anderson42b8a052013-06-26 10:45:36 -0700566
567 Returns:
568 A HookFailure or None.
569 """
Mike Frysinger011af942014-01-17 16:12:22 -0500570 # If this is the portage-stable overlay, then ignore the check. It's rare
571 # that we're doing anything other than importing files from upstream, so
572 # forcing a rev bump makes no sense.
573 whitelist = (
574 'chromiumos/overlays/portage-stable',
575 )
Alex Deymo643ac4c2015-09-03 10:40:50 -0700576 if project.name in whitelist:
Mike Frysinger011af942014-01-17 16:12:22 -0500577 return None
578
Mike Frysinger292b45d2014-11-25 01:17:10 -0500579 def FinalName(obj):
580 # If the file is being deleted, then the dst_file is not set.
581 if obj.dst_file is None:
582 return obj.src_file
583 else:
584 return obj.dst_file
585
586 affected_path_objs = _get_affected_files(
587 commit, include_deletes=True, include_symlinks=True, relative=True,
588 full_details=True)
Doug Anderson42b8a052013-06-26 10:45:36 -0700589
590 # Don't yell about changes to whitelisted files...
Mike Frysinger011af942014-01-17 16:12:22 -0500591 whitelist = ('ChangeLog', 'Manifest', 'metadata.xml')
Mike Frysinger292b45d2014-11-25 01:17:10 -0500592 affected_path_objs = [x for x in affected_path_objs
593 if os.path.basename(FinalName(x)) not in whitelist]
594 if not affected_path_objs:
Doug Anderson42b8a052013-06-26 10:45:36 -0700595 return None
596
597 # If we've touched any file named with a -rN.ebuild then we'll say we're
598 # OK right away. See TODO above about enhancing this.
Mike Frysinger292b45d2014-11-25 01:17:10 -0500599 touched_revved_ebuild = any(re.search(r'-r\d*\.ebuild$', FinalName(x))
600 for x in affected_path_objs)
Doug Anderson42b8a052013-06-26 10:45:36 -0700601 if touched_revved_ebuild:
602 return None
603
Mike Frysinger292b45d2014-11-25 01:17:10 -0500604 # If we're creating new ebuilds from scratch, then we don't need an uprev.
605 # Find all the dirs that new ebuilds and ignore their files/.
606 ebuild_dirs = [os.path.dirname(FinalName(x)) + '/' for x in affected_path_objs
607 if FinalName(x).endswith('.ebuild') and x.status == 'A']
608 affected_path_objs = [obj for obj in affected_path_objs
609 if not any(FinalName(obj).startswith(x)
610 for x in ebuild_dirs)]
611 if not affected_path_objs:
612 return
613
Doug Anderson42b8a052013-06-26 10:45:36 -0700614 # We want to examine the current contents of all directories that are parents
615 # of files that were touched (up to the top of the project).
616 #
617 # ...note: we use the current directory contents even though it may have
618 # changed since the commit we're looking at. This is just a heuristic after
619 # all. Worst case we don't flag a missing revbump.
Mike Frysinger292b45d2014-11-25 01:17:10 -0500620 if project_top is None:
621 project_top = os.getcwd()
Doug Anderson42b8a052013-06-26 10:45:36 -0700622 dirs_to_check = set([project_top])
Mike Frysinger292b45d2014-11-25 01:17:10 -0500623 for obj in affected_path_objs:
624 path = os.path.join(project_top, os.path.dirname(FinalName(obj)))
Doug Anderson42b8a052013-06-26 10:45:36 -0700625 while os.path.exists(path) and not os.path.samefile(path, project_top):
626 dirs_to_check.add(path)
627 path = os.path.dirname(path)
628
629 # Look through each directory. If it's got an ebuild in it then we'll
630 # consider this as a case when we need a revbump.
Gwendal Grignoua3086c32014-12-09 11:17:22 -0800631 affected_paths = set(os.path.join(project_top, FinalName(x))
632 for x in affected_path_objs)
Doug Anderson42b8a052013-06-26 10:45:36 -0700633 for dir_path in dirs_to_check:
634 contents = os.listdir(dir_path)
635 ebuilds = [os.path.join(dir_path, path)
636 for path in contents if path.endswith('.ebuild')]
637 ebuilds_9999 = [path for path in ebuilds if path.endswith('-9999.ebuild')]
638
639 # If the -9999.ebuild file was touched the bot will uprev for us.
640 # ...we'll use a simple intersection here as a heuristic...
Mike Frysinger292b45d2014-11-25 01:17:10 -0500641 if set(ebuilds_9999) & affected_paths:
Doug Anderson42b8a052013-06-26 10:45:36 -0700642 continue
643
644 if ebuilds:
Mike Frysinger292b45d2014-11-25 01:17:10 -0500645 return HookFailure('Changelist probably needs a revbump of an ebuild, '
646 'or a -r1.ebuild symlink if this is a new ebuild:\n'
647 '%s' % dir_path)
Doug Anderson42b8a052013-06-26 10:45:36 -0700648
649 return None
650
651
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500652def _check_ebuild_eapi(project, commit):
653 """Make sure we have people use EAPI=4 or newer with custom ebuilds.
654
655 We want to get away from older EAPI's as it makes life confusing and they
656 have less builtin error checking.
657
658 Args:
Alex Deymo643ac4c2015-09-03 10:40:50 -0700659 project: The Project to look at
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500660 commit: The commit to look at
661
662 Returns:
663 A HookFailure or None.
664 """
665 # If this is the portage-stable overlay, then ignore the check. It's rare
Mike Frysingercd6adfc2014-02-06 01:03:56 -0500666 # that we're doing anything other than importing files from upstream, and
667 # we shouldn't be rewriting things fundamentally anyways.
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500668 whitelist = (
669 'chromiumos/overlays/portage-stable',
670 )
Alex Deymo643ac4c2015-09-03 10:40:50 -0700671 if project.name in whitelist:
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500672 return None
673
674 BAD_EAPIS = ('0', '1', '2', '3')
675
676 get_eapi = re.compile(r'^\s*EAPI=[\'"]?([^\'"]+)')
677
678 ebuilds_re = [r'\.ebuild$']
679 ebuilds = _filter_files(_get_affected_files(commit, relative=True),
680 ebuilds_re)
681 bad_ebuilds = []
682
683 for ebuild in ebuilds:
684 # If the ebuild does not specify an EAPI, it defaults to 0.
685 eapi = '0'
686
687 lines = _get_file_content(ebuild, commit).splitlines()
688 if len(lines) == 1:
689 # This is most likely a symlink, so skip it entirely.
690 continue
691
692 for line in lines:
693 m = get_eapi.match(line)
694 if m:
695 # Once we hit the first EAPI line in this ebuild, stop processing.
696 # The spec requires that there only be one and it be first, so
697 # checking all possible values is pointless. We also assume that
698 # it's "the" EAPI line and not something in the middle of a heredoc.
699 eapi = m.group(1)
700 break
701
702 if eapi in BAD_EAPIS:
703 bad_ebuilds.append((ebuild, eapi))
704
705 if bad_ebuilds:
706 # pylint: disable=C0301
707 url = 'http://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/upgrade-ebuild-eapis'
708 # pylint: enable=C0301
709 return HookFailure(
Mike Frysingercd6adfc2014-02-06 01:03:56 -0500710 'These ebuilds are using old EAPIs. If these are imported from\n'
711 'Gentoo, then you may ignore and upload once with the --no-verify\n'
712 'flag. Otherwise, please update to 4 or newer.\n'
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500713 '\t%s\n'
714 'See this guide for more details:\n%s\n' %
715 ('\n\t'.join(['%s: EAPI=%s' % x for x in bad_ebuilds]), url))
716
717
Mike Frysinger89bdb852014-02-01 05:26:26 -0500718def _check_ebuild_keywords(_project, commit):
Mike Frysingerc51ece72014-01-17 16:23:40 -0500719 """Make sure we use the new style KEYWORDS when possible in ebuilds.
720
721 If an ebuild generally does not care about the arch it is running on, then
722 ebuilds should flag it with one of:
723 KEYWORDS="*" # A stable ebuild.
724 KEYWORDS="~*" # An unstable ebuild.
725 KEYWORDS="-* ..." # Is known to only work on specific arches.
726
727 Args:
Alex Deymo643ac4c2015-09-03 10:40:50 -0700728 project: The Project to look at
Mike Frysingerc51ece72014-01-17 16:23:40 -0500729 commit: The commit to look at
730
731 Returns:
732 A HookFailure or None.
733 """
734 WHITELIST = set(('*', '-*', '~*'))
735
736 get_keywords = re.compile(r'^\s*KEYWORDS="(.*)"')
737
Mike Frysinger89bdb852014-02-01 05:26:26 -0500738 ebuilds_re = [r'\.ebuild$']
739 ebuilds = _filter_files(_get_affected_files(commit, relative=True),
740 ebuilds_re)
741
Mike Frysinger8d42d742014-09-22 15:50:21 -0400742 bad_ebuilds = []
Mike Frysingerc51ece72014-01-17 16:23:40 -0500743 for ebuild in ebuilds:
Mike Frysinger5c9e58d2014-09-09 03:32:50 -0400744 # We get the full content rather than a diff as the latter does not work
745 # on new files (like when adding new ebuilds).
746 lines = _get_file_content(ebuild, commit).splitlines()
747 for line in lines:
Mike Frysingerc51ece72014-01-17 16:23:40 -0500748 m = get_keywords.match(line)
749 if m:
750 keywords = set(m.group(1).split())
751 if not keywords or WHITELIST - keywords != WHITELIST:
752 continue
753
Mike Frysinger8d42d742014-09-22 15:50:21 -0400754 bad_ebuilds.append(ebuild)
755
756 if bad_ebuilds:
757 return HookFailure(
758 '%s\n'
759 'Please update KEYWORDS to use a glob:\n'
760 'If the ebuild should be marked stable (normal for non-9999 ebuilds):\n'
761 ' KEYWORDS="*"\n'
762 'If the ebuild should be marked unstable (normal for '
763 'cros-workon / 9999 ebuilds):\n'
764 ' KEYWORDS="~*"\n'
Mike Frysingerde8efea2015-05-17 03:42:26 -0400765 'If the ebuild needs to be marked for only specific arches, '
Mike Frysinger8d42d742014-09-22 15:50:21 -0400766 'then use -* like so:\n'
767 ' KEYWORDS="-* arm ..."\n' % '\n* '.join(bad_ebuilds))
Mike Frysingerc51ece72014-01-17 16:23:40 -0500768
769
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800770def _check_ebuild_licenses(_project, commit):
771 """Check if the LICENSE field in the ebuild is correct."""
Brian Norris7a610e82016-02-17 12:24:54 -0800772 affected_paths = _get_affected_files(commit, relative=True)
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800773 touched_ebuilds = [x for x in affected_paths if x.endswith('.ebuild')]
774
775 # A list of licenses to ignore for now.
Yu-Ju Hongc0963fa2014-03-03 12:36:52 -0800776 LICENSES_IGNORE = ['||', '(', ')']
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800777
778 for ebuild in touched_ebuilds:
779 # Skip virutal packages.
780 if ebuild.split('/')[-3] == 'virtual':
781 continue
782
783 try:
Brian Norris7a610e82016-02-17 12:24:54 -0800784 ebuild_content = _get_file_content(ebuild, commit)
785 license_types = licenses_lib.GetLicenseTypesFromEbuild(ebuild_content)
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800786 except ValueError as e:
787 return HookFailure(e.message, [ebuild])
788
789 # Also ignore licenses ending with '?'
790 for license_type in [x for x in license_types
791 if x not in LICENSES_IGNORE and not x.endswith('?')]:
792 try:
Mike Frysinger2ec70ed2014-08-17 19:28:34 -0400793 licenses_lib.Licensing.FindLicenseType(license_type)
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800794 except AssertionError as e:
795 return HookFailure(e.message, [ebuild])
796
797
Mike Frysingercd363c82014-02-01 05:20:18 -0500798def _check_ebuild_virtual_pv(project, commit):
799 """Enforce the virtual PV policies."""
800 # If this is the portage-stable overlay, then ignore the check.
801 # We want to import virtuals as-is from upstream Gentoo.
802 whitelist = (
803 'chromiumos/overlays/portage-stable',
804 )
Alex Deymo643ac4c2015-09-03 10:40:50 -0700805 if project.name in whitelist:
Mike Frysingercd363c82014-02-01 05:20:18 -0500806 return None
807
808 # We assume the repo name is the same as the dir name on disk.
809 # It would be dumb to not have them match though.
Alex Deymo643ac4c2015-09-03 10:40:50 -0700810 project_base = os.path.basename(project.name)
Mike Frysingercd363c82014-02-01 05:20:18 -0500811
812 is_variant = lambda x: x.startswith('overlay-variant-')
813 is_board = lambda x: x.startswith('overlay-')
814 is_private = lambda x: x.endswith('-private')
815
816 get_pv = re.compile(r'(.*?)virtual/([^/]+)/\2-([^/]*)\.ebuild$')
817
818 ebuilds_re = [r'\.ebuild$']
819 ebuilds = _filter_files(_get_affected_files(commit, relative=True),
820 ebuilds_re)
821 bad_ebuilds = []
822
823 for ebuild in ebuilds:
824 m = get_pv.match(ebuild)
825 if m:
826 overlay = m.group(1)
827 if not overlay or not is_board(overlay):
Alex Deymo643ac4c2015-09-03 10:40:50 -0700828 overlay = project_base
Mike Frysingercd363c82014-02-01 05:20:18 -0500829
830 pv = m.group(3).split('-', 1)[0]
831
Bernie Thompsone5ee1822016-01-12 14:22:23 -0800832 # Virtual versions >= 4 are special cases used above the standard
833 # versioning structure, e.g. if one has a board inheriting a board.
834 if float(pv) >= 4:
835 want_pv = pv
836 elif is_private(overlay):
Mike Frysingercd363c82014-02-01 05:20:18 -0500837 want_pv = '3.5' if is_variant(overlay) else '3'
838 elif is_board(overlay):
839 want_pv = '2.5' if is_variant(overlay) else '2'
840 else:
841 want_pv = '1'
842
843 if pv != want_pv:
844 bad_ebuilds.append((ebuild, pv, want_pv))
845
846 if bad_ebuilds:
847 # pylint: disable=C0301
848 url = 'http://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/portage-build-faq#TOC-Virtuals-and-central-management'
849 # pylint: enable=C0301
850 return HookFailure(
851 'These virtuals have incorrect package versions (PVs). Please adjust:\n'
852 '\t%s\n'
853 'If this is an upstream Gentoo virtual, then you may ignore this\n'
854 'check (and re-run w/--no-verify). Otherwise, please see this\n'
855 'page for more details:\n%s\n' %
856 ('\n\t'.join(['%s:\n\t\tPV is %s but should be %s' % x
857 for x in bad_ebuilds]), url))
858
859
Daniel Erat9d203ff2015-02-17 10:12:21 -0700860def _check_portage_make_use_var(_project, commit):
861 """Verify that $USE is set correctly in make.conf and make.defaults."""
862 files = _filter_files(_get_affected_files(commit, relative=True),
863 [r'(^|/)make.(conf|defaults)$'])
864
865 errors = []
866 for path in files:
867 basename = os.path.basename(path)
868
869 # Has a USE= line already been encountered in this file?
870 saw_use = False
871
872 for i, line in enumerate(_get_file_content(path, commit).splitlines(), 1):
873 if not line.startswith('USE='):
874 continue
875
876 preserves_use = '${USE}' in line or '$USE' in line
877
878 if (basename == 'make.conf' or
879 (basename == 'make.defaults' and saw_use)) and not preserves_use:
880 errors.append('%s:%d: missing ${USE}' % (path, i))
881 elif basename == 'make.defaults' and not saw_use and preserves_use:
882 errors.append('%s:%d: ${USE} referenced in initial declaration' %
883 (path, i))
884
885 saw_use = True
886
887 if errors:
888 return HookFailure(
889 'One or more Portage make files appear to set USE incorrectly.\n'
890 '\n'
891 'All USE assignments in make.conf and all assignments after the\n'
892 'initial declaration in make.defaults should contain "${USE}" to\n'
893 'preserve previously-set flags.\n'
894 '\n'
895 'The initial USE declaration in make.defaults should not contain\n'
896 '"${USE}".\n',
897 errors)
898
899
Mike Frysingerae409522014-02-01 03:16:11 -0500900def _check_change_has_proper_changeid(_project, commit):
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700901 """Verify that Change-ID is present in last paragraph of commit message."""
Mike Frysinger4a22bf02014-10-31 13:53:35 -0400902 CHANGE_ID_RE = r'\nChange-Id: I[a-f0-9]+\n'
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700903 desc = _get_commit_desc(commit)
Mike Frysinger4a22bf02014-10-31 13:53:35 -0400904 m = re.search(CHANGE_ID_RE, desc)
Mike Frysinger02b88bd2014-11-21 00:29:38 -0500905 if not m:
Ryan Cui1562fb82011-05-09 11:01:31 -0700906 return HookFailure('Change-Id must be in last paragraph of description.')
907
Mike Frysinger02b88bd2014-11-21 00:29:38 -0500908 # Allow s-o-b tags to follow it, but only those.
909 end = desc[m.end():].strip().splitlines()
910 if [x for x in end if not x.startswith('Signed-off-by: ')]:
911 return HookFailure('Only "Signed-off-by:" tags may follow the Change-Id.')
912
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700913
Mike Frysinger36b2ebc2014-10-31 14:02:03 -0400914def _check_commit_message_style(_project, commit):
915 """Verify that the commit message matches our style.
916
917 We do not check for BUG=/TEST=/etc... lines here as that is handled by other
918 commit hooks.
919 """
920 desc = _get_commit_desc(commit)
921
922 # The first line should be by itself.
923 lines = desc.splitlines()
924 if len(lines) > 1 and lines[1]:
925 return HookFailure('The second line of the commit message must be blank.')
926
927 # The first line should be one sentence.
928 if '. ' in lines[0]:
929 return HookFailure('The first line cannot be more than one sentence.')
930
931 # The first line cannot be too long.
932 MAX_FIRST_LINE_LEN = 100
933 if len(lines[0]) > MAX_FIRST_LINE_LEN:
934 return HookFailure('The first line must be less than %i chars.' %
935 MAX_FIRST_LINE_LEN)
936
937
Filipe Brandenburger4b542b12015-10-09 12:46:31 -0700938def _check_cros_license(_project, commit, options=()):
Alex Deymof5792ce2015-08-24 22:50:08 -0700939 """Verifies the Chromium OS license/copyright header.
Ryan Cuiec4d6332011-05-02 14:15:25 -0700940
Mike Frysinger98638102014-08-28 00:15:08 -0400941 Should be following the spec:
942 http://dev.chromium.org/developers/coding-style#TOC-File-headers
943 """
944 # For older years, be a bit more flexible as our policy says leave them be.
945 LICENSE_HEADER = (
946 r'.* Copyright( \(c\))? 20[-0-9]{2,7} The Chromium OS Authors\. '
Mike Frysingerb81102f2014-11-21 00:33:35 -0500947 r'All rights reserved\.' r'\n'
Mike Frysinger98638102014-08-28 00:15:08 -0400948 r'.* Use of this source code is governed by a BSD-style license that can '
Mike Frysingerb81102f2014-11-21 00:33:35 -0500949 r'be\n'
Mike Frysinger98638102014-08-28 00:15:08 -0400950 r'.* found in the LICENSE file\.'
Mike Frysingerb81102f2014-11-21 00:33:35 -0500951 r'\n'
Mike Frysinger98638102014-08-28 00:15:08 -0400952 )
953 license_re = re.compile(LICENSE_HEADER, re.MULTILINE)
954
955 # For newer years, be stricter.
956 COPYRIGHT_LINE = (
957 r'.* Copyright \(c\) 20(1[5-9]|[2-9][0-9]) The Chromium OS Authors\. '
Mike Frysingerb81102f2014-11-21 00:33:35 -0500958 r'All rights reserved\.' r'\n'
Mike Frysinger98638102014-08-28 00:15:08 -0400959 )
960 copyright_re = re.compile(COPYRIGHT_LINE)
961
Filipe Brandenburger4b542b12015-10-09 12:46:31 -0700962 parser = argparse.ArgumentParser()
963 parser.add_argument('--exclude_regex', action='append')
964 parser.add_argument('--include_regex', action='append')
965 opts = parser.parse_args(options)
966 included = opts.include_regex or []
967 excluded = opts.exclude_regex or []
968
Mike Frysinger98638102014-08-28 00:15:08 -0400969 bad_files = []
970 bad_copyright_files = []
971 files = _filter_files(_get_affected_files(commit, relative=True),
Filipe Brandenburger4b542b12015-10-09 12:46:31 -0700972 included + COMMON_INCLUDED_PATHS,
973 excluded + COMMON_EXCLUDED_PATHS)
Mike Frysinger98638102014-08-28 00:15:08 -0400974
975 for f in files:
976 contents = _get_file_content(f, commit)
977 if not contents:
978 # Ignore empty files.
979 continue
980
981 if not license_re.search(contents):
982 bad_files.append(f)
983 elif copyright_re.search(contents):
984 bad_copyright_files.append(f)
985
986 if bad_files:
987 msg = '%s:\n%s\n%s' % (
988 'License must match', license_re.pattern,
989 'Found a bad header in these files:')
990 return HookFailure(msg, bad_files)
991
992 if bad_copyright_files:
993 msg = 'Do not use (c) in copyright headers in new files:'
994 return HookFailure(msg, bad_copyright_files)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700995
996
Alex Deymof5792ce2015-08-24 22:50:08 -0700997def _check_aosp_license(_project, commit):
998 """Verifies the AOSP license/copyright header.
999
1000 AOSP uses the Apache2 License:
1001 https://source.android.com/source/licenses.html
1002 """
1003 LICENSE_HEADER = (
1004 r"""^[#/\*]*
1005[#/\*]* ?Copyright( \([cC]\))? 20[-0-9]{2,7} The Android Open Source Project
1006[#/\*]* ?
1007[#/\*]* ?Licensed under the Apache License, Version 2.0 \(the "License"\);
1008[#/\*]* ?you may not use this file except in compliance with the License\.
1009[#/\*]* ?You may obtain a copy of the License at
1010[#/\*]* ?
1011[#/\*]* ? http://www\.apache\.org/licenses/LICENSE-2\.0
1012[#/\*]* ?
1013[#/\*]* ?Unless required by applicable law or agreed to in writing, software
1014[#/\*]* ?distributed under the License is distributed on an "AS IS" BASIS,
1015[#/\*]* ?WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or """
1016 r"""implied\.
1017[#/\*]* ?See the License for the specific language governing permissions and
1018[#/\*]* ?limitations under the License\.
1019[#/\*]*$
1020"""
1021 )
1022 license_re = re.compile(LICENSE_HEADER, re.MULTILINE)
1023
1024 files = _filter_files(_get_affected_files(commit, relative=True),
1025 COMMON_INCLUDED_PATHS,
1026 COMMON_EXCLUDED_PATHS)
1027
1028 bad_files = []
1029 for f in files:
1030 contents = _get_file_content(f, commit)
1031 if not contents:
1032 # Ignore empty files.
1033 continue
1034
1035 if not license_re.search(contents):
1036 bad_files.append(f)
1037
1038 if bad_files:
1039 msg = ('License must match:\n%s\nFound a bad header in these files:' %
1040 license_re.pattern)
1041 return HookFailure(msg, bad_files)
1042
1043
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001044def _check_layout_conf(_project, commit):
1045 """Verifies the metadata/layout.conf file."""
1046 repo_name = 'profiles/repo_name'
Mike Frysinger94a670c2014-09-19 12:46:26 -04001047 repo_names = []
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001048 layout_path = 'metadata/layout.conf'
Mike Frysinger94a670c2014-09-19 12:46:26 -04001049 layout_paths = []
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001050
Mike Frysinger94a670c2014-09-19 12:46:26 -04001051 # Handle multiple overlays in a single commit (like the public tree).
1052 for f in _get_affected_files(commit, relative=True):
1053 if f.endswith(repo_name):
1054 repo_names.append(f)
1055 elif f.endswith(layout_path):
1056 layout_paths.append(f)
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001057
1058 # Disallow new repos with the repo_name file.
Mike Frysinger94a670c2014-09-19 12:46:26 -04001059 if repo_names:
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001060 return HookFailure('%s: use "repo-name" in %s instead' %
Mike Frysinger94a670c2014-09-19 12:46:26 -04001061 (repo_names, layout_path))
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001062
Mike Frysinger94a670c2014-09-19 12:46:26 -04001063 # Gather all the errors in one pass so we show one full message.
1064 all_errors = {}
1065 for layout_path in layout_paths:
1066 all_errors[layout_path] = errors = []
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001067
Mike Frysinger94a670c2014-09-19 12:46:26 -04001068 # Make sure the config file is sorted.
1069 data = [x for x in _get_file_content(layout_path, commit).splitlines()
1070 if x and x[0] != '#']
1071 if sorted(data) != data:
1072 errors += ['keep lines sorted']
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001073
Mike Frysinger94a670c2014-09-19 12:46:26 -04001074 # Require people to set specific values all the time.
1075 settings = (
1076 # TODO: Enable this for everyone. http://crbug.com/408038
1077 #('fast caching', 'cache-format = md5-dict'),
1078 ('fast manifests', 'thin-manifests = true'),
Mike Frysingerd7734522015-02-26 16:12:43 -05001079 ('extra features', 'profile-formats = portage-2 profile-default-eapi'),
1080 ('newer eapi', 'profile_eapi_when_unspecified = 5-progress'),
Mike Frysinger94a670c2014-09-19 12:46:26 -04001081 )
1082 for reason, line in settings:
1083 if line not in data:
1084 errors += ['enable %s with: %s' % (reason, line)]
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001085
Mike Frysinger94a670c2014-09-19 12:46:26 -04001086 # Require one of these settings.
Mike Frysinger5fae62d2015-11-11 20:12:15 -05001087 if 'use-manifests = strict' not in data:
1088 errors += ['enable file checking with: use-manifests = strict']
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001089
Mike Frysinger94a670c2014-09-19 12:46:26 -04001090 # Require repo-name to be set.
Mike Frysinger324cf682014-09-22 15:52:50 -04001091 for line in data:
1092 if line.startswith('repo-name = '):
1093 break
1094 else:
Mike Frysinger94a670c2014-09-19 12:46:26 -04001095 errors += ['set the board name with: repo-name = $BOARD']
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001096
Mike Frysinger94a670c2014-09-19 12:46:26 -04001097 # Summarize all the errors we saw (if any).
1098 lines = ''
1099 for layout_path, errors in all_errors.items():
1100 if errors:
1101 lines += '\n\t- '.join(['\n* %s:' % layout_path] + errors)
1102 if lines:
1103 lines = 'See the portage(5) man page for layout.conf details' + lines + '\n'
1104 return HookFailure(lines)
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001105
1106
Ryan Cuiec4d6332011-05-02 14:15:25 -07001107# Project-specific hooks
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001108
Ryan Cui1562fb82011-05-09 11:01:31 -07001109
Mike Frysingerae409522014-02-01 03:16:11 -05001110def _run_checkpatch(_project, commit, options=()):
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001111 """Runs checkpatch.pl on the given project"""
1112 hooks_dir = _get_hooks_dir()
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001113 options = list(options)
1114 if commit == PRE_SUBMIT:
1115 # The --ignore option must be present and include 'MISSING_SIGN_OFF' in
1116 # this case.
1117 options.append('--ignore=MISSING_SIGN_OFF')
Filipe Brandenburger28d48d62015-10-07 09:48:54 -07001118 # Always ignore the check for the MAINTAINERS file. We do not track that
1119 # information on that file in our source trees, so let's suppress the
1120 # warning.
1121 options.append('--ignore=FILE_PATH_CHANGES')
Filipe Brandenburgerce978322015-10-09 10:04:15 -07001122 # Do not complain about the Change-Id: fields, since we use Gerrit.
1123 # Upstream does not want those lines (since they do not use Gerrit), but
1124 # we always do, so disable the check globally.
Daisuke Nojiri4844f892015-10-08 09:54:33 -07001125 options.append('--ignore=GERRIT_CHANGE_ID')
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001126 cmd = ['%s/checkpatch.pl' % hooks_dir] + options + ['-']
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001127 cmd_result = cros_build_lib.RunCommand(cmd=cmd,
1128 print_cmd=False,
1129 input=_get_patch(commit),
1130 stdout_to_pipe=True,
1131 combine_stdout_stderr=True,
1132 error_code_ok=True)
1133 if cmd_result.returncode:
1134 return HookFailure('checkpatch.pl errors/warnings\n\n' + cmd_result.output)
Ryan Cuiec4d6332011-05-02 14:15:25 -07001135
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001136
Mike Frysingerae409522014-02-01 03:16:11 -05001137def _kernel_configcheck(_project, commit):
Olof Johanssona96810f2012-09-04 16:20:03 -07001138 """Makes sure kernel config changes are not mixed with code changes"""
1139 files = _get_affected_files(commit)
1140 if not len(_filter_files(files, [r'chromeos/config'])) in [0, len(files)]:
1141 return HookFailure('Changes to chromeos/config/ and regular files must '
1142 'be in separate commits:\n%s' % '\n'.join(files))
Anton Staaf815d6852011-08-22 10:08:45 -07001143
Mike Frysingerae409522014-02-01 03:16:11 -05001144
1145def _run_json_check(_project, commit):
Dale Curtis2975c432011-05-03 17:25:20 -07001146 """Checks that all JSON files are syntactically valid."""
Dale Curtisa039cfd2011-05-04 12:01:05 -07001147 for f in _filter_files(_get_affected_files(commit), [r'.*\.json']):
Dale Curtis2975c432011-05-03 17:25:20 -07001148 try:
1149 json.load(open(f))
1150 except Exception, e:
Ryan Cui1562fb82011-05-09 11:01:31 -07001151 return HookFailure('Invalid JSON in %s: %s' % (f, e))
Dale Curtis2975c432011-05-03 17:25:20 -07001152
1153
Mike Frysingerae409522014-02-01 03:16:11 -05001154def _check_manifests(_project, commit):
Mike Frysinger52b537e2013-08-22 22:59:53 -04001155 """Make sure Manifest files only have DIST lines"""
1156 paths = []
1157
1158 for path in _get_affected_files(commit):
1159 if os.path.basename(path) != 'Manifest':
1160 continue
1161 if not os.path.exists(path):
1162 continue
1163
1164 with open(path, 'r') as f:
1165 for line in f.readlines():
1166 if not line.startswith('DIST '):
1167 paths.append(path)
1168 break
1169
1170 if paths:
1171 return HookFailure('Please remove lines that do not start with DIST:\n%s' %
1172 ('\n'.join(paths),))
1173
1174
Mike Frysingerae409522014-02-01 03:16:11 -05001175def _check_change_has_branch_field(_project, commit):
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001176 """Check for a non-empty 'BRANCH=' field in the commit message."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001177 if commit == PRE_SUBMIT:
1178 return
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001179 BRANCH_RE = r'\nBRANCH=\S+'
1180
1181 if not re.search(BRANCH_RE, _get_commit_desc(commit)):
1182 msg = ('Changelist description needs BRANCH field (after first line)\n'
1183 'E.g. BRANCH=none or BRANCH=link,snow')
1184 return HookFailure(msg)
1185
1186
Mike Frysingerae409522014-02-01 03:16:11 -05001187def _check_change_has_signoff_field(_project, commit):
Shawn Nematbakhsh51e16ac2014-01-28 15:31:07 -08001188 """Check for a non-empty 'Signed-off-by:' field in the commit message."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001189 if commit == PRE_SUBMIT:
1190 return
Shawn Nematbakhsh51e16ac2014-01-28 15:31:07 -08001191 SIGNOFF_RE = r'\nSigned-off-by: \S+'
1192
1193 if not re.search(SIGNOFF_RE, _get_commit_desc(commit)):
1194 msg = ('Changelist description needs Signed-off-by: field\n'
1195 'E.g. Signed-off-by: My Name <me@chromium.org>')
1196 return HookFailure(msg)
1197
1198
Jon Salz3ee59de2012-08-18 13:54:22 +08001199def _run_project_hook_script(script, project, commit):
1200 """Runs a project hook script.
1201
1202 The script is run with the following environment variables set:
1203 PRESUBMIT_PROJECT: The affected project
1204 PRESUBMIT_COMMIT: The affected commit
1205 PRESUBMIT_FILES: A newline-separated list of affected files
1206
1207 The script is considered to fail if the exit code is non-zero. It should
1208 write an error message to stdout.
1209 """
1210 env = dict(os.environ)
Alex Deymo643ac4c2015-09-03 10:40:50 -07001211 env['PRESUBMIT_PROJECT'] = project.name
Jon Salz3ee59de2012-08-18 13:54:22 +08001212 env['PRESUBMIT_COMMIT'] = commit
1213
1214 # Put affected files in an environment variable
1215 files = _get_affected_files(commit)
1216 env['PRESUBMIT_FILES'] = '\n'.join(files)
1217
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001218 cmd_result = cros_build_lib.RunCommand(cmd=script,
1219 env=env,
1220 shell=True,
1221 print_cmd=False,
1222 input=os.devnull,
1223 stdout_to_pipe=True,
1224 combine_stdout_stderr=True,
1225 error_code_ok=True)
1226 if cmd_result.returncode:
1227 stdout = cmd_result.output
Jon Salz7b618af2012-08-31 06:03:16 +08001228 if stdout:
1229 stdout = re.sub('(?m)^', ' ', stdout)
1230 return HookFailure('Hook script "%s" failed with code %d%s' %
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001231 (script, cmd_result.returncode,
Jon Salz3ee59de2012-08-18 13:54:22 +08001232 ':\n' + stdout if stdout else ''))
1233
1234
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001235def _check_project_prefix(_project, commit):
Mike Frysinger55f85b52014-12-18 14:45:21 -05001236 """Require the commit message have a project specific prefix as needed."""
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001237
1238 files = _get_affected_files(commit, relative=True)
1239 prefix = os.path.commonprefix(files)
1240 prefix = os.path.dirname(prefix)
1241
1242 # If there is no common prefix, the CL span multiple projects.
Daniel Erata350fd32014-09-29 14:02:34 -07001243 if not prefix:
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001244 return
1245
1246 project_name = prefix.split('/')[0]
Daniel Erata350fd32014-09-29 14:02:34 -07001247
1248 # The common files may all be within a subdirectory of the main project
1249 # directory, so walk up the tree until we find an alias file.
1250 # _get_affected_files() should return relative paths, but check against '/' to
1251 # ensure that this loop terminates even if it receives an absolute path.
1252 while prefix and prefix != '/':
1253 alias_file = os.path.join(prefix, '.project_alias')
1254
1255 # If an alias exists, use it.
1256 if os.path.isfile(alias_file):
1257 project_name = osutils.ReadFile(alias_file).strip()
1258
1259 prefix = os.path.dirname(prefix)
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001260
1261 if not _get_commit_desc(commit).startswith(project_name + ': '):
1262 return HookFailure('The commit title for changes affecting only %s'
1263 ' should start with \"%s: \"'
1264 % (project_name, project_name))
1265
1266
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001267# Base
1268
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001269# A list of hooks which are not project specific and check patch description
1270# (as opposed to patch body).
1271_PATCH_DESCRIPTION_HOOKS = [
Ryan Cui9b651632011-05-11 11:38:58 -07001272 _check_change_has_bug_field,
David Jamesc3b68b32013-04-03 09:17:03 -07001273 _check_change_has_valid_cq_depend,
Ryan Cui9b651632011-05-11 11:38:58 -07001274 _check_change_has_test_field,
1275 _check_change_has_proper_changeid,
Mike Frysinger36b2ebc2014-10-31 14:02:03 -04001276 _check_commit_message_style,
Bernie Thompsonf8fea992016-01-14 10:27:18 -08001277 _check_change_is_contribution,
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001278]
1279
1280
1281# A list of hooks that are not project-specific
1282_COMMON_HOOKS = [
Mike Frysingerbf8b91c2014-02-01 02:50:27 -05001283 _check_ebuild_eapi,
Mike Frysinger89bdb852014-02-01 05:26:26 -05001284 _check_ebuild_keywords,
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -08001285 _check_ebuild_licenses,
Mike Frysingercd363c82014-02-01 05:20:18 -05001286 _check_ebuild_virtual_pv,
Daniel Erat9d203ff2015-02-17 10:12:21 -07001287 _check_for_uprev,
Rahul Chaudhry09f61372015-07-31 17:14:26 -07001288 _check_gofmt,
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001289 _check_layout_conf,
Alex Deymof5792ce2015-08-24 22:50:08 -07001290 _check_cros_license,
Daniel Erat9d203ff2015-02-17 10:12:21 -07001291 _check_no_long_lines,
1292 _check_no_stray_whitespace,
Ryan Cui9b651632011-05-11 11:38:58 -07001293 _check_no_tabs,
Daniel Erat9d203ff2015-02-17 10:12:21 -07001294 _check_portage_make_use_var,
Ryan Cui9b651632011-05-11 11:38:58 -07001295]
Ryan Cuiec4d6332011-05-02 14:15:25 -07001296
Ryan Cui1562fb82011-05-09 11:01:31 -07001297
Ryan Cui9b651632011-05-11 11:38:58 -07001298# A dictionary of project-specific hooks(callbacks), indexed by project name.
1299# dict[project] = [callback1, callback2]
1300_PROJECT_SPECIFIC_HOOKS = {
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001301 "chromiumos/platform2": [_check_project_prefix],
Mike Frysingeraf891292015-03-25 19:46:53 -04001302 "chromiumos/third_party/kernel": [_kernel_configcheck],
1303 "chromiumos/third_party/kernel-next": [_kernel_configcheck],
Ryan Cui9b651632011-05-11 11:38:58 -07001304}
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001305
Ryan Cui1562fb82011-05-09 11:01:31 -07001306
Ryan Cui9b651632011-05-11 11:38:58 -07001307# A dictionary of flags (keys) that can appear in the config file, and the hook
Mike Frysinger3554bc92015-03-11 04:59:21 -04001308# that the flag controls (value).
1309_HOOK_FLAGS = {
Mike Frysingera7642f52015-03-25 18:31:42 -04001310 'checkpatch_check': _run_checkpatch,
Ryan Cui9b651632011-05-11 11:38:58 -07001311 'stray_whitespace_check': _check_no_stray_whitespace,
Mike Frysingerff6c7d62015-03-24 13:49:46 -04001312 'json_check': _run_json_check,
Ryan Cui9b651632011-05-11 11:38:58 -07001313 'long_line_check': _check_no_long_lines,
Alex Deymof5792ce2015-08-24 22:50:08 -07001314 'cros_license_check': _check_cros_license,
1315 'aosp_license_check': _check_aosp_license,
Ryan Cui9b651632011-05-11 11:38:58 -07001316 'tab_check': _check_no_tabs,
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001317 'branch_check': _check_change_has_branch_field,
Shawn Nematbakhsh51e16ac2014-01-28 15:31:07 -08001318 'signoff_check': _check_change_has_signoff_field,
Josh Triplett0e8fc7f2014-04-23 16:00:00 -07001319 'bug_field_check': _check_change_has_bug_field,
1320 'test_field_check': _check_change_has_test_field,
Steve Fung49ec7e92015-03-23 16:07:12 -07001321 'manifest_check': _check_manifests,
Bernie Thompsonf8fea992016-01-14 10:27:18 -08001322 'contribution_check': _check_change_is_contribution,
Ryan Cui9b651632011-05-11 11:38:58 -07001323}
1324
1325
Mike Frysinger3554bc92015-03-11 04:59:21 -04001326def _get_override_hooks(config):
1327 """Returns a set of hooks controlled by the current project's config file.
Ryan Cui9b651632011-05-11 11:38:58 -07001328
1329 Expects to be called within the project root.
Jon Salz3ee59de2012-08-18 13:54:22 +08001330
1331 Args:
1332 config: A ConfigParser for the project's config file.
Ryan Cui9b651632011-05-11 11:38:58 -07001333 """
1334 SECTION = 'Hook Overrides'
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001335 SECTION_OPTIONS = 'Hook Overrides Options'
Jon Salz3ee59de2012-08-18 13:54:22 +08001336 if not config.has_section(SECTION):
Mike Frysinger3554bc92015-03-11 04:59:21 -04001337 return set(), set()
Ryan Cui9b651632011-05-11 11:38:58 -07001338
Mike Frysinger3554bc92015-03-11 04:59:21 -04001339 valid_keys = set(_HOOK_FLAGS.iterkeys())
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001340 hooks = _HOOK_FLAGS.copy()
Mike Frysinger3554bc92015-03-11 04:59:21 -04001341
1342 enable_flags = []
Ryan Cui9b651632011-05-11 11:38:58 -07001343 disable_flags = []
Jon Salz3ee59de2012-08-18 13:54:22 +08001344 for flag in config.options(SECTION):
Mike Frysinger3554bc92015-03-11 04:59:21 -04001345 if flag not in valid_keys:
1346 raise ValueError('Error: unknown key "%s" in hook section of "%s"' %
1347 (flag, _CONFIG_FILE))
1348
Ryan Cui9b651632011-05-11 11:38:58 -07001349 try:
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001350 enabled = config.getboolean(SECTION, flag)
Ryan Cui9b651632011-05-11 11:38:58 -07001351 except ValueError as e:
Mike Frysinger3554bc92015-03-11 04:59:21 -04001352 raise ValueError('Error: parsing flag "%s" in "%s" failed: %s' %
1353 (flag, _CONFIG_FILE, e))
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001354 if enabled:
1355 enable_flags.append(flag)
1356 else:
1357 disable_flags.append(flag)
Ryan Cui9b651632011-05-11 11:38:58 -07001358
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001359 # See if this hook has custom options.
1360 if enabled:
1361 try:
1362 options = config.get(SECTION_OPTIONS, flag)
1363 hooks[flag] = functools.partial(hooks[flag], options=options.split())
1364 except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
1365 pass
1366
1367 enabled_hooks = set(hooks[x] for x in enable_flags)
1368 disabled_hooks = set(hooks[x] for x in disable_flags)
Mike Frysinger3554bc92015-03-11 04:59:21 -04001369 return enabled_hooks, disabled_hooks
Ryan Cui9b651632011-05-11 11:38:58 -07001370
1371
Jon Salz3ee59de2012-08-18 13:54:22 +08001372def _get_project_hook_scripts(config):
1373 """Returns a list of project-specific hook scripts.
1374
1375 Args:
1376 config: A ConfigParser for the project's config file.
1377 """
1378 SECTION = 'Hook Scripts'
1379 if not config.has_section(SECTION):
1380 return []
1381
1382 hook_names_values = config.items(SECTION)
1383 hook_names_values.sort(key=lambda x: x[0])
1384 return [x[1] for x in hook_names_values]
1385
1386
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001387def _get_project_hooks(project, presubmit):
Ryan Cui9b651632011-05-11 11:38:58 -07001388 """Returns a list of hooks that need to be run for a project.
1389
1390 Expects to be called from within the project root.
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001391
1392 Args:
1393 project: A string, name of the project.
1394 presubmit: A Boolean, True if the check is run as a git pre-submit script.
Ryan Cui9b651632011-05-11 11:38:58 -07001395 """
Jon Salz3ee59de2012-08-18 13:54:22 +08001396 config = ConfigParser.RawConfigParser()
1397 try:
1398 config.read(_CONFIG_FILE)
1399 except ConfigParser.Error:
1400 # Just use an empty config file
1401 config = ConfigParser.RawConfigParser()
1402
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001403 if presubmit:
Filipe Brandenburgerf70d32c2015-10-09 13:35:45 -07001404 hooks = _COMMON_HOOKS
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001405 else:
Filipe Brandenburgerf70d32c2015-10-09 13:35:45 -07001406 hooks = _PATCH_DESCRIPTION_HOOKS + _COMMON_HOOKS
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001407
Mike Frysinger3554bc92015-03-11 04:59:21 -04001408 enabled_hooks, disabled_hooks = _get_override_hooks(config)
Filipe Brandenburgerf70d32c2015-10-09 13:35:45 -07001409 hooks = [hook for hook in hooks if hook not in disabled_hooks]
1410
1411 # If a list is both in _COMMON_HOOKS and also enabled explicitly through an
1412 # override, keep the override only. Note that the override may end up being
1413 # a functools.partial, in which case we need to extract the .func to compare
1414 # it to the common hooks.
1415 unwrapped_hooks = [getattr(hook, 'func', hook) for hook in enabled_hooks]
1416 hooks = [hook for hook in hooks if hook not in unwrapped_hooks]
1417
1418 hooks = list(enabled_hooks) + hooks
Ryan Cui9b651632011-05-11 11:38:58 -07001419
1420 if project in _PROJECT_SPECIFIC_HOOKS:
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001421 hooks.extend(hook for hook in _PROJECT_SPECIFIC_HOOKS[project]
1422 if hook not in disabled_hooks)
Ryan Cui9b651632011-05-11 11:38:58 -07001423
Jon Salz3ee59de2012-08-18 13:54:22 +08001424 for script in _get_project_hook_scripts(config):
1425 hooks.append(functools.partial(_run_project_hook_script, script))
1426
Ryan Cui9b651632011-05-11 11:38:58 -07001427 return hooks
1428
1429
Alex Deymo643ac4c2015-09-03 10:40:50 -07001430def _run_project_hooks(project_name, proj_dir=None,
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001431 commit_list=None, presubmit=False):
Ryan Cui1562fb82011-05-09 11:01:31 -07001432 """For each project run its project specific hook from the hooks dictionary.
1433
1434 Args:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001435 project_name: The name of project to run hooks for.
Doug Anderson44a644f2011-11-02 10:37:37 -07001436 proj_dir: If non-None, this is the directory the project is in. If None,
1437 we'll ask repo.
Doug Anderson14749562013-06-26 13:38:29 -07001438 commit_list: A list of commits to run hooks against. If None or empty list
1439 then we'll automatically get the list of commits that would be uploaded.
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001440 presubmit: A Boolean, True if the check is run as a git pre-submit script.
Ryan Cui1562fb82011-05-09 11:01:31 -07001441
1442 Returns:
1443 Boolean value of whether any errors were ecountered while running the hooks.
1444 """
Doug Anderson44a644f2011-11-02 10:37:37 -07001445 if proj_dir is None:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001446 proj_dirs = _run_command(
1447 ['repo', 'forall', project_name, '-c', 'pwd']).split()
David James2edd9002013-10-11 14:09:19 -07001448 if len(proj_dirs) == 0:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001449 print('%s cannot be found.' % project_name, file=sys.stderr)
David James2edd9002013-10-11 14:09:19 -07001450 print('Please specify a valid project.', file=sys.stderr)
1451 return True
1452 if len(proj_dirs) > 1:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001453 print('%s is associated with multiple directories.' % project_name,
David James2edd9002013-10-11 14:09:19 -07001454 file=sys.stderr)
1455 print('Please specify a directory to help disambiguate.', file=sys.stderr)
1456 return True
1457 proj_dir = proj_dirs[0]
Doug Anderson44a644f2011-11-02 10:37:37 -07001458
Ryan Cuiec4d6332011-05-02 14:15:25 -07001459 pwd = os.getcwd()
1460 # hooks assume they are run from the root of the project
1461 os.chdir(proj_dir)
1462
Alex Deymo643ac4c2015-09-03 10:40:50 -07001463 remote_branch = _run_command(['git', 'rev-parse', '--abbrev-ref',
1464 '--symbolic-full-name', '@{u}']).strip()
1465 if not remote_branch:
1466 print('Your project %s doesn\'t track any remote repo.' % project_name,
1467 file=sys.stderr)
1468 remote = None
1469 else:
1470 remote, _branch = remote_branch.split('/', 1)
1471
1472 project = Project(name=project_name, dir=proj_dir, remote=remote)
1473
Doug Anderson14749562013-06-26 13:38:29 -07001474 if not commit_list:
1475 try:
1476 commit_list = _get_commits()
1477 except VerifyException as e:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001478 PrintErrorForProject(project.name, HookFailure(str(e)))
Doug Anderson14749562013-06-26 13:38:29 -07001479 os.chdir(pwd)
1480 return True
Ryan Cuifa55df52011-05-06 11:16:55 -07001481
Alex Deymo643ac4c2015-09-03 10:40:50 -07001482 hooks = _get_project_hooks(project.name, presubmit)
Ryan Cui1562fb82011-05-09 11:01:31 -07001483 error_found = False
Ryan Cuifa55df52011-05-06 11:16:55 -07001484 for commit in commit_list:
Ryan Cui1562fb82011-05-09 11:01:31 -07001485 error_list = []
Ryan Cui9b651632011-05-11 11:38:58 -07001486 for hook in hooks:
Ryan Cui1562fb82011-05-09 11:01:31 -07001487 hook_error = hook(project, commit)
1488 if hook_error:
1489 error_list.append(hook_error)
1490 error_found = True
1491 if error_list:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001492 PrintErrorsForCommit(project.name, commit, _get_commit_desc(commit),
Ryan Cui1562fb82011-05-09 11:01:31 -07001493 error_list)
Don Garrettdba548a2011-05-05 15:17:14 -07001494
Ryan Cuiec4d6332011-05-02 14:15:25 -07001495 os.chdir(pwd)
Ryan Cui1562fb82011-05-09 11:01:31 -07001496 return error_found
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001497
Mike Frysingerae409522014-02-01 03:16:11 -05001498
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001499# Main
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -07001500
Ryan Cui1562fb82011-05-09 11:01:31 -07001501
Mike Frysingerae409522014-02-01 03:16:11 -05001502def main(project_list, worktree_list=None, **_kwargs):
Doug Anderson06456632012-01-05 11:02:14 -08001503 """Main function invoked directly by repo.
1504
1505 This function will exit directly upon error so that repo doesn't print some
1506 obscure error message.
1507
1508 Args:
1509 project_list: List of projects to run on.
David James2edd9002013-10-11 14:09:19 -07001510 worktree_list: A list of directories. It should be the same length as
1511 project_list, so that each entry in project_list matches with a directory
1512 in worktree_list. If None, we will attempt to calculate the directories
1513 automatically.
Doug Anderson06456632012-01-05 11:02:14 -08001514 kwargs: Leave this here for forward-compatibility.
1515 """
Ryan Cui1562fb82011-05-09 11:01:31 -07001516 found_error = False
David James2edd9002013-10-11 14:09:19 -07001517 if not worktree_list:
1518 worktree_list = [None] * len(project_list)
1519 for project, worktree in zip(project_list, worktree_list):
1520 if _run_project_hooks(project, proj_dir=worktree):
Ryan Cui1562fb82011-05-09 11:01:31 -07001521 found_error = True
1522
Mike Frysingerae409522014-02-01 03:16:11 -05001523 if found_error:
Ryan Cui1562fb82011-05-09 11:01:31 -07001524 msg = ('Preupload failed due to errors in project(s). HINTS:\n'
Ryan Cui9b651632011-05-11 11:38:58 -07001525 '- To disable some source style checks, and for other hints, see '
1526 '<checkout_dir>/src/repohooks/README\n'
1527 '- To upload only current project, run \'repo upload .\'')
Mike Frysinger09d6a3d2013-10-08 22:21:03 -04001528 print(msg, file=sys.stderr)
Don Garrettdba548a2011-05-05 15:17:14 -07001529 sys.exit(1)
Anush Elangovan63afad72011-03-23 00:41:27 -07001530
Ryan Cui1562fb82011-05-09 11:01:31 -07001531
Doug Anderson44a644f2011-11-02 10:37:37 -07001532def _identify_project(path):
1533 """Identify the repo project associated with the given path.
1534
1535 Returns:
1536 A string indicating what project is associated with the path passed in or
1537 a blank string upon failure.
1538 """
1539 return _run_command(['repo', 'forall', '.', '-c', 'echo ${REPO_PROJECT}'],
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001540 redirect_stderr=True, cwd=path).strip()
Doug Anderson44a644f2011-11-02 10:37:37 -07001541
1542
Mike Frysinger55f85b52014-12-18 14:45:21 -05001543def direct_main(argv):
Doug Anderson44a644f2011-11-02 10:37:37 -07001544 """Run hooks directly (outside of the context of repo).
1545
Doug Anderson44a644f2011-11-02 10:37:37 -07001546 Args:
Mike Frysinger55f85b52014-12-18 14:45:21 -05001547 argv: The command line args to process
Doug Anderson44a644f2011-11-02 10:37:37 -07001548
1549 Returns:
1550 0 if no pre-upload failures, 1 if failures.
1551
1552 Raises:
1553 BadInvocation: On some types of invocation errors.
1554 """
Mike Frysinger66142932014-12-18 14:55:57 -05001555 parser = commandline.ArgumentParser(description=__doc__)
1556 parser.add_argument('--dir', default=None,
1557 help='The directory that the project lives in. If not '
1558 'specified, use the git project root based on the cwd.')
1559 parser.add_argument('--project', default=None,
1560 help='The project repo path; this can affect how the '
1561 'hooks get run, since some hooks are project-specific. '
1562 'For chromite this is chromiumos/chromite. If not '
1563 'specified, the repo tool will be used to figure this '
1564 'out based on the dir.')
1565 parser.add_argument('--rerun-since', default=None,
1566 help='Rerun hooks on old commits since the given date. '
1567 'The date should match git log\'s concept of a date. '
1568 'e.g. 2012-06-20. This option is mutually exclusive '
1569 'with --pre-submit.')
1570 parser.add_argument('--pre-submit', action="store_true",
1571 help='Run the check against the pending commit. '
1572 'This option should be used at the \'git commit\' '
1573 'phase as opposed to \'repo upload\'. This option '
1574 'is mutually exclusive with --rerun-since.')
1575 parser.add_argument('commits', nargs='*',
1576 help='Check specific commits')
1577 opts = parser.parse_args(argv)
Doug Anderson44a644f2011-11-02 10:37:37 -07001578
Doug Anderson14749562013-06-26 13:38:29 -07001579 if opts.rerun_since:
Mike Frysinger66142932014-12-18 14:55:57 -05001580 if opts.commits:
Doug Anderson14749562013-06-26 13:38:29 -07001581 raise BadInvocation('Can\'t pass commits and use rerun-since: %s' %
Mike Frysinger66142932014-12-18 14:55:57 -05001582 ' '.join(opts.commits))
Doug Anderson14749562013-06-26 13:38:29 -07001583
1584 cmd = ['git', 'log', '--since="%s"' % opts.rerun_since, '--pretty=%H']
1585 all_commits = _run_command(cmd).splitlines()
1586 bot_commits = _run_command(cmd + ['--author=chrome-bot']).splitlines()
1587
1588 # Eliminate chrome-bot commits but keep ordering the same...
1589 bot_commits = set(bot_commits)
Mike Frysinger66142932014-12-18 14:55:57 -05001590 opts.commits = [c for c in all_commits if c not in bot_commits]
Doug Anderson14749562013-06-26 13:38:29 -07001591
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001592 if opts.pre_submit:
1593 raise BadInvocation('rerun-since and pre-submit can not be '
1594 'used together')
1595 if opts.pre_submit:
Mike Frysinger66142932014-12-18 14:55:57 -05001596 if opts.commits:
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001597 raise BadInvocation('Can\'t pass commits and use pre-submit: %s' %
Mike Frysinger66142932014-12-18 14:55:57 -05001598 ' '.join(opts.commits))
1599 opts.commits = [PRE_SUBMIT,]
Doug Anderson44a644f2011-11-02 10:37:37 -07001600
1601 # Check/normlaize git dir; if unspecified, we'll use the root of the git
1602 # project from CWD
1603 if opts.dir is None:
1604 git_dir = _run_command(['git', 'rev-parse', '--git-dir'],
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001605 redirect_stderr=True).strip()
Doug Anderson44a644f2011-11-02 10:37:37 -07001606 if not git_dir:
1607 raise BadInvocation('The current directory is not part of a git project.')
1608 opts.dir = os.path.dirname(os.path.abspath(git_dir))
1609 elif not os.path.isdir(opts.dir):
1610 raise BadInvocation('Invalid dir: %s' % opts.dir)
1611 elif not os.path.isdir(os.path.join(opts.dir, '.git')):
1612 raise BadInvocation('Not a git directory: %s' % opts.dir)
1613
1614 # Identify the project if it wasn't specified; this _requires_ the repo
1615 # tool to be installed and for the project to be part of a repo checkout.
1616 if not opts.project:
1617 opts.project = _identify_project(opts.dir)
1618 if not opts.project:
1619 raise BadInvocation("Repo couldn't identify the project of %s" % opts.dir)
1620
Doug Anderson14749562013-06-26 13:38:29 -07001621 found_error = _run_project_hooks(opts.project, proj_dir=opts.dir,
Mike Frysinger66142932014-12-18 14:55:57 -05001622 commit_list=opts.commits,
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001623 presubmit=opts.pre_submit)
Doug Anderson44a644f2011-11-02 10:37:37 -07001624 if found_error:
1625 return 1
1626 return 0
1627
1628
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -07001629if __name__ == '__main__':
Mike Frysinger55f85b52014-12-18 14:45:21 -05001630 sys.exit(direct_main(sys.argv[1:]))