blob: 7677605cdb3174138d90908f0eadf10ec68c9ea8 [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$",
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
397# Common Hooks
398
Ryan Cui1562fb82011-05-09 11:01:31 -0700399
Mike Frysingerae409522014-02-01 03:16:11 -0500400def _check_no_long_lines(_project, commit):
Mike Frysinger55f85b52014-12-18 14:45:21 -0500401 """Checks there are no lines longer than MAX_LEN in any of the text files."""
402
Ryan Cuiec4d6332011-05-02 14:15:25 -0700403 MAX_LEN = 80
Jon Salz98255932012-08-18 14:48:02 +0800404 SKIP_REGEXP = re.compile('|'.join([
405 r'https?://',
406 r'^#\s*(define|include|import|pragma|if|endif)\b']))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700407
408 errors = []
409 files = _filter_files(_get_affected_files(commit),
410 COMMON_INCLUDED_PATHS,
411 COMMON_EXCLUDED_PATHS)
412
413 for afile in files:
414 for line_num, line in _get_file_diff(afile, commit):
415 # Allow certain lines to exceed the maxlen rule.
Mike Frysingerae409522014-02-01 03:16:11 -0500416 if len(line) <= MAX_LEN or SKIP_REGEXP.search(line):
Jon Salz98255932012-08-18 14:48:02 +0800417 continue
418
419 errors.append('%s, line %s, %s chars' % (afile, line_num, len(line)))
420 if len(errors) == 5: # Just show the first 5 errors.
421 break
Ryan Cuiec4d6332011-05-02 14:15:25 -0700422
423 if errors:
424 msg = 'Found lines longer than %s characters (first 5 shown):' % MAX_LEN
Ryan Cui1562fb82011-05-09 11:01:31 -0700425 return HookFailure(msg, errors)
426
Ryan Cuiec4d6332011-05-02 14:15:25 -0700427
Mike Frysingerae409522014-02-01 03:16:11 -0500428def _check_no_stray_whitespace(_project, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700429 """Checks that there is no stray whitespace at source lines end."""
430 errors = []
431 files = _filter_files(_get_affected_files(commit),
Mike Frysingerae409522014-02-01 03:16:11 -0500432 COMMON_INCLUDED_PATHS,
433 COMMON_EXCLUDED_PATHS)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700434 for afile in files:
435 for line_num, line in _get_file_diff(afile, commit):
436 if line.rstrip() != line:
437 errors.append('%s, line %s' % (afile, line_num))
438 if errors:
Ryan Cui1562fb82011-05-09 11:01:31 -0700439 return HookFailure('Found line ending with white space in:', errors)
440
Ryan Cuiec4d6332011-05-02 14:15:25 -0700441
Mike Frysingerae409522014-02-01 03:16:11 -0500442def _check_no_tabs(_project, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700443 """Checks there are no unexpanded tabs."""
444 TAB_OK_PATHS = [
Ryan Cui31e0c172011-05-04 21:00:45 -0700445 r"/src/third_party/u-boot/",
Ryan Cuiec4d6332011-05-02 14:15:25 -0700446 r".*\.ebuild$",
447 r".*\.eclass$",
Elly Jones5ab34192011-11-15 14:57:06 -0500448 r".*/[M|m]akefile$",
449 r".*\.mk$"
Ryan Cuiec4d6332011-05-02 14:15:25 -0700450 ]
451
452 errors = []
453 files = _filter_files(_get_affected_files(commit),
454 COMMON_INCLUDED_PATHS,
455 COMMON_EXCLUDED_PATHS + TAB_OK_PATHS)
456
457 for afile in files:
458 for line_num, line in _get_file_diff(afile, commit):
459 if '\t' in line:
Mike Frysingerae409522014-02-01 03:16:11 -0500460 errors.append('%s, line %s' % (afile, line_num))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700461 if errors:
Ryan Cui1562fb82011-05-09 11:01:31 -0700462 return HookFailure('Found a tab character in:', errors)
463
Ryan Cuiec4d6332011-05-02 14:15:25 -0700464
Rahul Chaudhry09f61372015-07-31 17:14:26 -0700465def _check_gofmt(_project, commit):
466 """Checks that Go files are formatted with gofmt."""
467 errors = []
468 files = _filter_files(_get_affected_files(commit, relative=True),
469 [r'\.go$'])
470
471 for gofile in files:
472 contents = _get_file_content(gofile, commit)
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700473 output = _run_command(cmd=['gofmt', '-l'], input=contents,
474 combine_stdout_stderr=True)
Rahul Chaudhry09f61372015-07-31 17:14:26 -0700475 if output:
476 errors.append(gofile)
477 if errors:
478 return HookFailure('Files not formatted with gofmt:', errors)
479
480
Mike Frysingerae409522014-02-01 03:16:11 -0500481def _check_change_has_test_field(_project, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700482 """Check for a non-empty 'TEST=' field in the commit message."""
David McMahon8f6553e2011-06-10 15:46:36 -0700483 TEST_RE = r'\nTEST=\S+'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700484
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700485 if not re.search(TEST_RE, _get_commit_desc(commit)):
Ryan Cui1562fb82011-05-09 11:01:31 -0700486 msg = 'Changelist description needs TEST field (after first line)'
487 return HookFailure(msg)
488
Ryan Cuiec4d6332011-05-02 14:15:25 -0700489
Mike Frysingerae409522014-02-01 03:16:11 -0500490def _check_change_has_valid_cq_depend(_project, commit):
David Jamesc3b68b32013-04-03 09:17:03 -0700491 """Check for a correctly formatted CQ-DEPEND field in the commit message."""
492 msg = 'Changelist has invalid CQ-DEPEND target.'
493 example = 'Example: CQ-DEPEND=CL:1234, CL:2345'
494 try:
495 patch.GetPaladinDeps(_get_commit_desc(commit))
496 except ValueError as ex:
497 return HookFailure(msg, [example, str(ex)])
498
499
Bernie Thompsonf8fea992016-01-14 10:27:18 -0800500def _check_change_is_contribution(_project, commit):
501 """Check that the change is a contribution."""
502 NO_CONTRIB = 'not a contribution'
503 if NO_CONTRIB in _get_commit_desc(commit).lower():
504 msg = ('Changelist is not a contribution, this cannot be accepted.\n'
505 'Please remove the "%s" text from the commit message.') % NO_CONTRIB
506 return HookFailure(msg)
507
508
Alex Deymo643ac4c2015-09-03 10:40:50 -0700509def _check_change_has_bug_field(project, commit):
David McMahon8f6553e2011-06-10 15:46:36 -0700510 """Check for a correctly formatted 'BUG=' field in the commit message."""
David James5c0073d2013-04-03 08:48:52 -0700511 OLD_BUG_RE = r'\nBUG=.*chromium-os'
512 if re.search(OLD_BUG_RE, _get_commit_desc(commit)):
513 msg = ('The chromium-os bug tracker is now deprecated. Please use\n'
514 'the chromium tracker in your BUG= line now.')
515 return HookFailure(msg)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700516
Alex Deymo643ac4c2015-09-03 10:40:50 -0700517 # Android internal and external projects use "Bug: " to track bugs in
518 # buganizer.
519 BUG_COLON_REMOTES = (
520 'aosp',
521 'goog',
522 )
523 if project.remote in BUG_COLON_REMOTES:
524 BUG_RE = r'\nBug: ?([Nn]one|\d+)'
525 if not re.search(BUG_RE, _get_commit_desc(commit)):
526 msg = ('Changelist description needs BUG field (after first line):\n'
527 'Bug: 9999 (for buganizer)\n'
528 'BUG=None')
529 return HookFailure(msg)
530 else:
531 BUG_RE = r'\nBUG=([Nn]one|(chrome-os-partner|chromium|brillo|b):\d+)'
532 if not re.search(BUG_RE, _get_commit_desc(commit)):
533 msg = ('Changelist description needs BUG field (after first line):\n'
534 'BUG=brillo:9999 (for Brillo tracker)\n'
535 'BUG=chromium:9999 (for public tracker)\n'
536 'BUG=chrome-os-partner:9999 (for partner tracker)\n'
537 'BUG=b:9999 (for buganizer)\n'
538 'BUG=None')
539 return HookFailure(msg)
Ryan Cui1562fb82011-05-09 11:01:31 -0700540
Ryan Cuiec4d6332011-05-02 14:15:25 -0700541
Mike Frysinger292b45d2014-11-25 01:17:10 -0500542def _check_for_uprev(project, commit, project_top=None):
Doug Anderson42b8a052013-06-26 10:45:36 -0700543 """Check that we're not missing a revbump of an ebuild in the given commit.
544
545 If the given commit touches files in a directory that has ebuilds somewhere
546 up the directory hierarchy, it's very likely that we need an ebuild revbump
547 in order for those changes to take effect.
548
549 It's not totally trivial to detect a revbump, so at least detect that an
550 ebuild with a revision number in it was touched. This should handle the
551 common case where we use a symlink to do the revbump.
552
553 TODO: it would be nice to enhance this hook to:
554 * Handle cases where people revbump with a slightly different syntax. I see
555 one ebuild (puppy) that revbumps with _pN. This is a false positive.
556 * Catches cases where people aren't using symlinks for revbumps. If they
557 edit a revisioned file directly (and are expected to rename it for revbump)
558 we'll miss that. Perhaps we could detect that the file touched is a
559 symlink?
560
561 If a project doesn't use symlinks we'll potentially miss a revbump, but we're
562 still better off than without this check.
563
564 Args:
Alex Deymo643ac4c2015-09-03 10:40:50 -0700565 project: The Project to look at
Doug Anderson42b8a052013-06-26 10:45:36 -0700566 commit: The commit to look at
Mike Frysinger292b45d2014-11-25 01:17:10 -0500567 project_top: Top dir to process commits in
Doug Anderson42b8a052013-06-26 10:45:36 -0700568
569 Returns:
570 A HookFailure or None.
571 """
Mike Frysinger011af942014-01-17 16:12:22 -0500572 # If this is the portage-stable overlay, then ignore the check. It's rare
573 # that we're doing anything other than importing files from upstream, so
574 # forcing a rev bump makes no sense.
575 whitelist = (
576 'chromiumos/overlays/portage-stable',
577 )
Alex Deymo643ac4c2015-09-03 10:40:50 -0700578 if project.name in whitelist:
Mike Frysinger011af942014-01-17 16:12:22 -0500579 return None
580
Mike Frysinger292b45d2014-11-25 01:17:10 -0500581 def FinalName(obj):
582 # If the file is being deleted, then the dst_file is not set.
583 if obj.dst_file is None:
584 return obj.src_file
585 else:
586 return obj.dst_file
587
588 affected_path_objs = _get_affected_files(
589 commit, include_deletes=True, include_symlinks=True, relative=True,
590 full_details=True)
Doug Anderson42b8a052013-06-26 10:45:36 -0700591
592 # Don't yell about changes to whitelisted files...
Aviv Keshet272f2e52016-04-25 14:49:44 -0700593 whitelist = ('ChangeLog', 'Manifest', 'metadata.xml', 'COMMIT-QUEUE.ini')
Mike Frysinger292b45d2014-11-25 01:17:10 -0500594 affected_path_objs = [x for x in affected_path_objs
595 if os.path.basename(FinalName(x)) not in whitelist]
596 if not affected_path_objs:
Doug Anderson42b8a052013-06-26 10:45:36 -0700597 return None
598
599 # If we've touched any file named with a -rN.ebuild then we'll say we're
600 # OK right away. See TODO above about enhancing this.
Mike Frysinger292b45d2014-11-25 01:17:10 -0500601 touched_revved_ebuild = any(re.search(r'-r\d*\.ebuild$', FinalName(x))
602 for x in affected_path_objs)
Doug Anderson42b8a052013-06-26 10:45:36 -0700603 if touched_revved_ebuild:
604 return None
605
Mike Frysinger292b45d2014-11-25 01:17:10 -0500606 # If we're creating new ebuilds from scratch, then we don't need an uprev.
607 # Find all the dirs that new ebuilds and ignore their files/.
608 ebuild_dirs = [os.path.dirname(FinalName(x)) + '/' for x in affected_path_objs
609 if FinalName(x).endswith('.ebuild') and x.status == 'A']
610 affected_path_objs = [obj for obj in affected_path_objs
611 if not any(FinalName(obj).startswith(x)
612 for x in ebuild_dirs)]
613 if not affected_path_objs:
614 return
615
Doug Anderson42b8a052013-06-26 10:45:36 -0700616 # We want to examine the current contents of all directories that are parents
617 # of files that were touched (up to the top of the project).
618 #
619 # ...note: we use the current directory contents even though it may have
620 # changed since the commit we're looking at. This is just a heuristic after
621 # all. Worst case we don't flag a missing revbump.
Mike Frysinger292b45d2014-11-25 01:17:10 -0500622 if project_top is None:
623 project_top = os.getcwd()
Doug Anderson42b8a052013-06-26 10:45:36 -0700624 dirs_to_check = set([project_top])
Mike Frysinger292b45d2014-11-25 01:17:10 -0500625 for obj in affected_path_objs:
626 path = os.path.join(project_top, os.path.dirname(FinalName(obj)))
Doug Anderson42b8a052013-06-26 10:45:36 -0700627 while os.path.exists(path) and not os.path.samefile(path, project_top):
628 dirs_to_check.add(path)
629 path = os.path.dirname(path)
630
631 # Look through each directory. If it's got an ebuild in it then we'll
632 # consider this as a case when we need a revbump.
Gwendal Grignoua3086c32014-12-09 11:17:22 -0800633 affected_paths = set(os.path.join(project_top, FinalName(x))
634 for x in affected_path_objs)
Doug Anderson42b8a052013-06-26 10:45:36 -0700635 for dir_path in dirs_to_check:
636 contents = os.listdir(dir_path)
637 ebuilds = [os.path.join(dir_path, path)
638 for path in contents if path.endswith('.ebuild')]
639 ebuilds_9999 = [path for path in ebuilds if path.endswith('-9999.ebuild')]
640
641 # If the -9999.ebuild file was touched the bot will uprev for us.
642 # ...we'll use a simple intersection here as a heuristic...
Mike Frysinger292b45d2014-11-25 01:17:10 -0500643 if set(ebuilds_9999) & affected_paths:
Doug Anderson42b8a052013-06-26 10:45:36 -0700644 continue
645
646 if ebuilds:
Mike Frysinger292b45d2014-11-25 01:17:10 -0500647 return HookFailure('Changelist probably needs a revbump of an ebuild, '
648 'or a -r1.ebuild symlink if this is a new ebuild:\n'
649 '%s' % dir_path)
Doug Anderson42b8a052013-06-26 10:45:36 -0700650
651 return None
652
653
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500654def _check_ebuild_eapi(project, commit):
655 """Make sure we have people use EAPI=4 or newer with custom ebuilds.
656
657 We want to get away from older EAPI's as it makes life confusing and they
658 have less builtin error checking.
659
660 Args:
Alex Deymo643ac4c2015-09-03 10:40:50 -0700661 project: The Project to look at
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500662 commit: The commit to look at
663
664 Returns:
665 A HookFailure or None.
666 """
667 # If this is the portage-stable overlay, then ignore the check. It's rare
Mike Frysingercd6adfc2014-02-06 01:03:56 -0500668 # that we're doing anything other than importing files from upstream, and
669 # we shouldn't be rewriting things fundamentally anyways.
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500670 whitelist = (
671 'chromiumos/overlays/portage-stable',
672 )
Alex Deymo643ac4c2015-09-03 10:40:50 -0700673 if project.name in whitelist:
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500674 return None
675
676 BAD_EAPIS = ('0', '1', '2', '3')
677
678 get_eapi = re.compile(r'^\s*EAPI=[\'"]?([^\'"]+)')
679
680 ebuilds_re = [r'\.ebuild$']
681 ebuilds = _filter_files(_get_affected_files(commit, relative=True),
682 ebuilds_re)
683 bad_ebuilds = []
684
685 for ebuild in ebuilds:
686 # If the ebuild does not specify an EAPI, it defaults to 0.
687 eapi = '0'
688
689 lines = _get_file_content(ebuild, commit).splitlines()
690 if len(lines) == 1:
691 # This is most likely a symlink, so skip it entirely.
692 continue
693
694 for line in lines:
695 m = get_eapi.match(line)
696 if m:
697 # Once we hit the first EAPI line in this ebuild, stop processing.
698 # The spec requires that there only be one and it be first, so
699 # checking all possible values is pointless. We also assume that
700 # it's "the" EAPI line and not something in the middle of a heredoc.
701 eapi = m.group(1)
702 break
703
704 if eapi in BAD_EAPIS:
705 bad_ebuilds.append((ebuild, eapi))
706
707 if bad_ebuilds:
708 # pylint: disable=C0301
709 url = 'http://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/upgrade-ebuild-eapis'
710 # pylint: enable=C0301
711 return HookFailure(
Mike Frysingercd6adfc2014-02-06 01:03:56 -0500712 'These ebuilds are using old EAPIs. If these are imported from\n'
713 'Gentoo, then you may ignore and upload once with the --no-verify\n'
714 'flag. Otherwise, please update to 4 or newer.\n'
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500715 '\t%s\n'
716 'See this guide for more details:\n%s\n' %
717 ('\n\t'.join(['%s: EAPI=%s' % x for x in bad_ebuilds]), url))
718
719
Mike Frysinger89bdb852014-02-01 05:26:26 -0500720def _check_ebuild_keywords(_project, commit):
Mike Frysingerc51ece72014-01-17 16:23:40 -0500721 """Make sure we use the new style KEYWORDS when possible in ebuilds.
722
723 If an ebuild generally does not care about the arch it is running on, then
724 ebuilds should flag it with one of:
725 KEYWORDS="*" # A stable ebuild.
726 KEYWORDS="~*" # An unstable ebuild.
727 KEYWORDS="-* ..." # Is known to only work on specific arches.
728
729 Args:
Alex Deymo643ac4c2015-09-03 10:40:50 -0700730 project: The Project to look at
Mike Frysingerc51ece72014-01-17 16:23:40 -0500731 commit: The commit to look at
732
733 Returns:
734 A HookFailure or None.
735 """
736 WHITELIST = set(('*', '-*', '~*'))
737
738 get_keywords = re.compile(r'^\s*KEYWORDS="(.*)"')
739
Mike Frysinger89bdb852014-02-01 05:26:26 -0500740 ebuilds_re = [r'\.ebuild$']
741 ebuilds = _filter_files(_get_affected_files(commit, relative=True),
742 ebuilds_re)
743
Mike Frysinger8d42d742014-09-22 15:50:21 -0400744 bad_ebuilds = []
Mike Frysingerc51ece72014-01-17 16:23:40 -0500745 for ebuild in ebuilds:
Mike Frysinger5c9e58d2014-09-09 03:32:50 -0400746 # We get the full content rather than a diff as the latter does not work
747 # on new files (like when adding new ebuilds).
748 lines = _get_file_content(ebuild, commit).splitlines()
749 for line in lines:
Mike Frysingerc51ece72014-01-17 16:23:40 -0500750 m = get_keywords.match(line)
751 if m:
752 keywords = set(m.group(1).split())
753 if not keywords or WHITELIST - keywords != WHITELIST:
754 continue
755
Mike Frysinger8d42d742014-09-22 15:50:21 -0400756 bad_ebuilds.append(ebuild)
757
758 if bad_ebuilds:
759 return HookFailure(
760 '%s\n'
761 'Please update KEYWORDS to use a glob:\n'
762 'If the ebuild should be marked stable (normal for non-9999 ebuilds):\n'
763 ' KEYWORDS="*"\n'
764 'If the ebuild should be marked unstable (normal for '
765 'cros-workon / 9999 ebuilds):\n'
766 ' KEYWORDS="~*"\n'
Mike Frysingerde8efea2015-05-17 03:42:26 -0400767 'If the ebuild needs to be marked for only specific arches, '
Mike Frysinger8d42d742014-09-22 15:50:21 -0400768 'then use -* like so:\n'
769 ' KEYWORDS="-* arm ..."\n' % '\n* '.join(bad_ebuilds))
Mike Frysingerc51ece72014-01-17 16:23:40 -0500770
771
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800772def _check_ebuild_licenses(_project, commit):
773 """Check if the LICENSE field in the ebuild is correct."""
Brian Norris7a610e82016-02-17 12:24:54 -0800774 affected_paths = _get_affected_files(commit, relative=True)
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800775 touched_ebuilds = [x for x in affected_paths if x.endswith('.ebuild')]
776
777 # A list of licenses to ignore for now.
Yu-Ju Hongc0963fa2014-03-03 12:36:52 -0800778 LICENSES_IGNORE = ['||', '(', ')']
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800779
780 for ebuild in touched_ebuilds:
781 # Skip virutal packages.
782 if ebuild.split('/')[-3] == 'virtual':
783 continue
784
785 try:
Brian Norris7a610e82016-02-17 12:24:54 -0800786 ebuild_content = _get_file_content(ebuild, commit)
787 license_types = licenses_lib.GetLicenseTypesFromEbuild(ebuild_content)
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800788 except ValueError as e:
789 return HookFailure(e.message, [ebuild])
790
791 # Also ignore licenses ending with '?'
792 for license_type in [x for x in license_types
793 if x not in LICENSES_IGNORE and not x.endswith('?')]:
794 try:
Mike Frysinger2ec70ed2014-08-17 19:28:34 -0400795 licenses_lib.Licensing.FindLicenseType(license_type)
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800796 except AssertionError as e:
797 return HookFailure(e.message, [ebuild])
798
799
Mike Frysingercd363c82014-02-01 05:20:18 -0500800def _check_ebuild_virtual_pv(project, commit):
801 """Enforce the virtual PV policies."""
802 # If this is the portage-stable overlay, then ignore the check.
803 # We want to import virtuals as-is from upstream Gentoo.
804 whitelist = (
805 'chromiumos/overlays/portage-stable',
806 )
Alex Deymo643ac4c2015-09-03 10:40:50 -0700807 if project.name in whitelist:
Mike Frysingercd363c82014-02-01 05:20:18 -0500808 return None
809
810 # We assume the repo name is the same as the dir name on disk.
811 # It would be dumb to not have them match though.
Alex Deymo643ac4c2015-09-03 10:40:50 -0700812 project_base = os.path.basename(project.name)
Mike Frysingercd363c82014-02-01 05:20:18 -0500813
814 is_variant = lambda x: x.startswith('overlay-variant-')
815 is_board = lambda x: x.startswith('overlay-')
816 is_private = lambda x: x.endswith('-private')
817
818 get_pv = re.compile(r'(.*?)virtual/([^/]+)/\2-([^/]*)\.ebuild$')
819
820 ebuilds_re = [r'\.ebuild$']
821 ebuilds = _filter_files(_get_affected_files(commit, relative=True),
822 ebuilds_re)
823 bad_ebuilds = []
824
825 for ebuild in ebuilds:
826 m = get_pv.match(ebuild)
827 if m:
828 overlay = m.group(1)
829 if not overlay or not is_board(overlay):
Alex Deymo643ac4c2015-09-03 10:40:50 -0700830 overlay = project_base
Mike Frysingercd363c82014-02-01 05:20:18 -0500831
832 pv = m.group(3).split('-', 1)[0]
833
Bernie Thompsone5ee1822016-01-12 14:22:23 -0800834 # Virtual versions >= 4 are special cases used above the standard
835 # versioning structure, e.g. if one has a board inheriting a board.
836 if float(pv) >= 4:
837 want_pv = pv
838 elif is_private(overlay):
Mike Frysingercd363c82014-02-01 05:20:18 -0500839 want_pv = '3.5' if is_variant(overlay) else '3'
840 elif is_board(overlay):
841 want_pv = '2.5' if is_variant(overlay) else '2'
842 else:
843 want_pv = '1'
844
845 if pv != want_pv:
846 bad_ebuilds.append((ebuild, pv, want_pv))
847
848 if bad_ebuilds:
849 # pylint: disable=C0301
850 url = 'http://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/portage-build-faq#TOC-Virtuals-and-central-management'
851 # pylint: enable=C0301
852 return HookFailure(
853 'These virtuals have incorrect package versions (PVs). Please adjust:\n'
854 '\t%s\n'
855 'If this is an upstream Gentoo virtual, then you may ignore this\n'
856 'check (and re-run w/--no-verify). Otherwise, please see this\n'
857 'page for more details:\n%s\n' %
858 ('\n\t'.join(['%s:\n\t\tPV is %s but should be %s' % x
859 for x in bad_ebuilds]), url))
860
861
Daniel Erat9d203ff2015-02-17 10:12:21 -0700862def _check_portage_make_use_var(_project, commit):
863 """Verify that $USE is set correctly in make.conf and make.defaults."""
864 files = _filter_files(_get_affected_files(commit, relative=True),
865 [r'(^|/)make.(conf|defaults)$'])
866
867 errors = []
868 for path in files:
869 basename = os.path.basename(path)
870
871 # Has a USE= line already been encountered in this file?
872 saw_use = False
873
874 for i, line in enumerate(_get_file_content(path, commit).splitlines(), 1):
875 if not line.startswith('USE='):
876 continue
877
878 preserves_use = '${USE}' in line or '$USE' in line
879
880 if (basename == 'make.conf' or
881 (basename == 'make.defaults' and saw_use)) and not preserves_use:
882 errors.append('%s:%d: missing ${USE}' % (path, i))
883 elif basename == 'make.defaults' and not saw_use and preserves_use:
884 errors.append('%s:%d: ${USE} referenced in initial declaration' %
885 (path, i))
886
887 saw_use = True
888
889 if errors:
890 return HookFailure(
891 'One or more Portage make files appear to set USE incorrectly.\n'
892 '\n'
893 'All USE assignments in make.conf and all assignments after the\n'
894 'initial declaration in make.defaults should contain "${USE}" to\n'
895 'preserve previously-set flags.\n'
896 '\n'
897 'The initial USE declaration in make.defaults should not contain\n'
898 '"${USE}".\n',
899 errors)
900
901
Mike Frysingerae409522014-02-01 03:16:11 -0500902def _check_change_has_proper_changeid(_project, commit):
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700903 """Verify that Change-ID is present in last paragraph of commit message."""
Mike Frysinger4a22bf02014-10-31 13:53:35 -0400904 CHANGE_ID_RE = r'\nChange-Id: I[a-f0-9]+\n'
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700905 desc = _get_commit_desc(commit)
Mike Frysinger4a22bf02014-10-31 13:53:35 -0400906 m = re.search(CHANGE_ID_RE, desc)
Mike Frysinger02b88bd2014-11-21 00:29:38 -0500907 if not m:
Ryan Cui1562fb82011-05-09 11:01:31 -0700908 return HookFailure('Change-Id must be in last paragraph of description.')
909
Mike Frysinger02b88bd2014-11-21 00:29:38 -0500910 # Allow s-o-b tags to follow it, but only those.
911 end = desc[m.end():].strip().splitlines()
912 if [x for x in end if not x.startswith('Signed-off-by: ')]:
913 return HookFailure('Only "Signed-off-by:" tags may follow the Change-Id.')
914
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700915
Mike Frysinger36b2ebc2014-10-31 14:02:03 -0400916def _check_commit_message_style(_project, commit):
917 """Verify that the commit message matches our style.
918
919 We do not check for BUG=/TEST=/etc... lines here as that is handled by other
920 commit hooks.
921 """
922 desc = _get_commit_desc(commit)
923
924 # The first line should be by itself.
925 lines = desc.splitlines()
926 if len(lines) > 1 and lines[1]:
927 return HookFailure('The second line of the commit message must be blank.')
928
929 # The first line should be one sentence.
930 if '. ' in lines[0]:
931 return HookFailure('The first line cannot be more than one sentence.')
932
933 # The first line cannot be too long.
934 MAX_FIRST_LINE_LEN = 100
935 if len(lines[0]) > MAX_FIRST_LINE_LEN:
936 return HookFailure('The first line must be less than %i chars.' %
937 MAX_FIRST_LINE_LEN)
938
939
Filipe Brandenburger4b542b12015-10-09 12:46:31 -0700940def _check_cros_license(_project, commit, options=()):
Alex Deymof5792ce2015-08-24 22:50:08 -0700941 """Verifies the Chromium OS license/copyright header.
Ryan Cuiec4d6332011-05-02 14:15:25 -0700942
Mike Frysinger98638102014-08-28 00:15:08 -0400943 Should be following the spec:
944 http://dev.chromium.org/developers/coding-style#TOC-File-headers
945 """
946 # For older years, be a bit more flexible as our policy says leave them be.
947 LICENSE_HEADER = (
948 r'.* Copyright( \(c\))? 20[-0-9]{2,7} The Chromium OS Authors\. '
Mike Frysingerb81102f2014-11-21 00:33:35 -0500949 r'All rights reserved\.' r'\n'
Mike Frysinger98638102014-08-28 00:15:08 -0400950 r'.* Use of this source code is governed by a BSD-style license that can '
Mike Frysingerb81102f2014-11-21 00:33:35 -0500951 r'be\n'
Mike Frysinger98638102014-08-28 00:15:08 -0400952 r'.* found in the LICENSE file\.'
Mike Frysingerb81102f2014-11-21 00:33:35 -0500953 r'\n'
Mike Frysinger98638102014-08-28 00:15:08 -0400954 )
955 license_re = re.compile(LICENSE_HEADER, re.MULTILINE)
956
957 # For newer years, be stricter.
958 COPYRIGHT_LINE = (
959 r'.* Copyright \(c\) 20(1[5-9]|[2-9][0-9]) The Chromium OS Authors\. '
Mike Frysingerb81102f2014-11-21 00:33:35 -0500960 r'All rights reserved\.' r'\n'
Mike Frysinger98638102014-08-28 00:15:08 -0400961 )
962 copyright_re = re.compile(COPYRIGHT_LINE)
963
Filipe Brandenburger4b542b12015-10-09 12:46:31 -0700964 parser = argparse.ArgumentParser()
965 parser.add_argument('--exclude_regex', action='append')
966 parser.add_argument('--include_regex', action='append')
967 opts = parser.parse_args(options)
968 included = opts.include_regex or []
969 excluded = opts.exclude_regex or []
970
Mike Frysinger98638102014-08-28 00:15:08 -0400971 bad_files = []
972 bad_copyright_files = []
973 files = _filter_files(_get_affected_files(commit, relative=True),
Filipe Brandenburger4b542b12015-10-09 12:46:31 -0700974 included + COMMON_INCLUDED_PATHS,
975 excluded + COMMON_EXCLUDED_PATHS)
Mike Frysinger98638102014-08-28 00:15:08 -0400976
977 for f in files:
978 contents = _get_file_content(f, commit)
979 if not contents:
980 # Ignore empty files.
981 continue
982
983 if not license_re.search(contents):
984 bad_files.append(f)
985 elif copyright_re.search(contents):
986 bad_copyright_files.append(f)
987
988 if bad_files:
989 msg = '%s:\n%s\n%s' % (
990 'License must match', license_re.pattern,
991 'Found a bad header in these files:')
992 return HookFailure(msg, bad_files)
993
994 if bad_copyright_files:
995 msg = 'Do not use (c) in copyright headers in new files:'
996 return HookFailure(msg, bad_copyright_files)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700997
998
Alex Deymof5792ce2015-08-24 22:50:08 -0700999def _check_aosp_license(_project, commit):
1000 """Verifies the AOSP license/copyright header.
1001
1002 AOSP uses the Apache2 License:
1003 https://source.android.com/source/licenses.html
1004 """
1005 LICENSE_HEADER = (
1006 r"""^[#/\*]*
1007[#/\*]* ?Copyright( \([cC]\))? 20[-0-9]{2,7} The Android Open Source Project
1008[#/\*]* ?
1009[#/\*]* ?Licensed under the Apache License, Version 2.0 \(the "License"\);
1010[#/\*]* ?you may not use this file except in compliance with the License\.
1011[#/\*]* ?You may obtain a copy of the License at
1012[#/\*]* ?
1013[#/\*]* ? http://www\.apache\.org/licenses/LICENSE-2\.0
1014[#/\*]* ?
1015[#/\*]* ?Unless required by applicable law or agreed to in writing, software
1016[#/\*]* ?distributed under the License is distributed on an "AS IS" BASIS,
1017[#/\*]* ?WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or """
1018 r"""implied\.
1019[#/\*]* ?See the License for the specific language governing permissions and
1020[#/\*]* ?limitations under the License\.
1021[#/\*]*$
1022"""
1023 )
1024 license_re = re.compile(LICENSE_HEADER, re.MULTILINE)
1025
1026 files = _filter_files(_get_affected_files(commit, relative=True),
1027 COMMON_INCLUDED_PATHS,
1028 COMMON_EXCLUDED_PATHS)
1029
1030 bad_files = []
1031 for f in files:
1032 contents = _get_file_content(f, commit)
1033 if not contents:
1034 # Ignore empty files.
1035 continue
1036
1037 if not license_re.search(contents):
1038 bad_files.append(f)
1039
1040 if bad_files:
1041 msg = ('License must match:\n%s\nFound a bad header in these files:' %
1042 license_re.pattern)
1043 return HookFailure(msg, bad_files)
1044
1045
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001046def _check_layout_conf(_project, commit):
1047 """Verifies the metadata/layout.conf file."""
1048 repo_name = 'profiles/repo_name'
Mike Frysinger94a670c2014-09-19 12:46:26 -04001049 repo_names = []
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001050 layout_path = 'metadata/layout.conf'
Mike Frysinger94a670c2014-09-19 12:46:26 -04001051 layout_paths = []
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001052
Mike Frysinger94a670c2014-09-19 12:46:26 -04001053 # Handle multiple overlays in a single commit (like the public tree).
1054 for f in _get_affected_files(commit, relative=True):
1055 if f.endswith(repo_name):
1056 repo_names.append(f)
1057 elif f.endswith(layout_path):
1058 layout_paths.append(f)
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001059
1060 # Disallow new repos with the repo_name file.
Mike Frysinger94a670c2014-09-19 12:46:26 -04001061 if repo_names:
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001062 return HookFailure('%s: use "repo-name" in %s instead' %
Mike Frysinger94a670c2014-09-19 12:46:26 -04001063 (repo_names, layout_path))
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001064
Mike Frysinger94a670c2014-09-19 12:46:26 -04001065 # Gather all the errors in one pass so we show one full message.
1066 all_errors = {}
1067 for layout_path in layout_paths:
1068 all_errors[layout_path] = errors = []
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001069
Mike Frysinger94a670c2014-09-19 12:46:26 -04001070 # Make sure the config file is sorted.
1071 data = [x for x in _get_file_content(layout_path, commit).splitlines()
1072 if x and x[0] != '#']
1073 if sorted(data) != data:
1074 errors += ['keep lines sorted']
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001075
Mike Frysinger94a670c2014-09-19 12:46:26 -04001076 # Require people to set specific values all the time.
1077 settings = (
1078 # TODO: Enable this for everyone. http://crbug.com/408038
1079 #('fast caching', 'cache-format = md5-dict'),
1080 ('fast manifests', 'thin-manifests = true'),
Mike Frysingerd7734522015-02-26 16:12:43 -05001081 ('extra features', 'profile-formats = portage-2 profile-default-eapi'),
1082 ('newer eapi', 'profile_eapi_when_unspecified = 5-progress'),
Mike Frysinger94a670c2014-09-19 12:46:26 -04001083 )
1084 for reason, line in settings:
1085 if line not in data:
1086 errors += ['enable %s with: %s' % (reason, line)]
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001087
Mike Frysinger94a670c2014-09-19 12:46:26 -04001088 # Require one of these settings.
Mike Frysinger5fae62d2015-11-11 20:12:15 -05001089 if 'use-manifests = strict' not in data:
1090 errors += ['enable file checking with: use-manifests = strict']
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001091
Mike Frysinger94a670c2014-09-19 12:46:26 -04001092 # Require repo-name to be set.
Mike Frysinger324cf682014-09-22 15:52:50 -04001093 for line in data:
1094 if line.startswith('repo-name = '):
1095 break
1096 else:
Mike Frysinger94a670c2014-09-19 12:46:26 -04001097 errors += ['set the board name with: repo-name = $BOARD']
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001098
Mike Frysinger94a670c2014-09-19 12:46:26 -04001099 # Summarize all the errors we saw (if any).
1100 lines = ''
1101 for layout_path, errors in all_errors.items():
1102 if errors:
1103 lines += '\n\t- '.join(['\n* %s:' % layout_path] + errors)
1104 if lines:
1105 lines = 'See the portage(5) man page for layout.conf details' + lines + '\n'
1106 return HookFailure(lines)
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001107
1108
Ryan Cuiec4d6332011-05-02 14:15:25 -07001109# Project-specific hooks
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001110
Ryan Cui1562fb82011-05-09 11:01:31 -07001111
Mike Frysingerae409522014-02-01 03:16:11 -05001112def _run_checkpatch(_project, commit, options=()):
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001113 """Runs checkpatch.pl on the given project"""
1114 hooks_dir = _get_hooks_dir()
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001115 options = list(options)
1116 if commit == PRE_SUBMIT:
1117 # The --ignore option must be present and include 'MISSING_SIGN_OFF' in
1118 # this case.
1119 options.append('--ignore=MISSING_SIGN_OFF')
Filipe Brandenburger28d48d62015-10-07 09:48:54 -07001120 # Always ignore the check for the MAINTAINERS file. We do not track that
1121 # information on that file in our source trees, so let's suppress the
1122 # warning.
1123 options.append('--ignore=FILE_PATH_CHANGES')
Filipe Brandenburgerce978322015-10-09 10:04:15 -07001124 # Do not complain about the Change-Id: fields, since we use Gerrit.
1125 # Upstream does not want those lines (since they do not use Gerrit), but
1126 # we always do, so disable the check globally.
Daisuke Nojiri4844f892015-10-08 09:54:33 -07001127 options.append('--ignore=GERRIT_CHANGE_ID')
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001128 cmd = ['%s/checkpatch.pl' % hooks_dir] + options + ['-']
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001129 cmd_result = cros_build_lib.RunCommand(cmd=cmd,
1130 print_cmd=False,
1131 input=_get_patch(commit),
1132 stdout_to_pipe=True,
1133 combine_stdout_stderr=True,
1134 error_code_ok=True)
1135 if cmd_result.returncode:
1136 return HookFailure('checkpatch.pl errors/warnings\n\n' + cmd_result.output)
Ryan Cuiec4d6332011-05-02 14:15:25 -07001137
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001138
Mike Frysingerae409522014-02-01 03:16:11 -05001139def _kernel_configcheck(_project, commit):
Olof Johanssona96810f2012-09-04 16:20:03 -07001140 """Makes sure kernel config changes are not mixed with code changes"""
1141 files = _get_affected_files(commit)
1142 if not len(_filter_files(files, [r'chromeos/config'])) in [0, len(files)]:
1143 return HookFailure('Changes to chromeos/config/ and regular files must '
1144 'be in separate commits:\n%s' % '\n'.join(files))
Anton Staaf815d6852011-08-22 10:08:45 -07001145
Mike Frysingerae409522014-02-01 03:16:11 -05001146
1147def _run_json_check(_project, commit):
Dale Curtis2975c432011-05-03 17:25:20 -07001148 """Checks that all JSON files are syntactically valid."""
Dale Curtisa039cfd2011-05-04 12:01:05 -07001149 for f in _filter_files(_get_affected_files(commit), [r'.*\.json']):
Dale Curtis2975c432011-05-03 17:25:20 -07001150 try:
1151 json.load(open(f))
1152 except Exception, e:
Ryan Cui1562fb82011-05-09 11:01:31 -07001153 return HookFailure('Invalid JSON in %s: %s' % (f, e))
Dale Curtis2975c432011-05-03 17:25:20 -07001154
1155
Mike Frysingerae409522014-02-01 03:16:11 -05001156def _check_manifests(_project, commit):
Mike Frysinger52b537e2013-08-22 22:59:53 -04001157 """Make sure Manifest files only have DIST lines"""
1158 paths = []
1159
1160 for path in _get_affected_files(commit):
1161 if os.path.basename(path) != 'Manifest':
1162 continue
1163 if not os.path.exists(path):
1164 continue
1165
1166 with open(path, 'r') as f:
1167 for line in f.readlines():
1168 if not line.startswith('DIST '):
1169 paths.append(path)
1170 break
1171
1172 if paths:
1173 return HookFailure('Please remove lines that do not start with DIST:\n%s' %
1174 ('\n'.join(paths),))
1175
1176
Mike Frysingerae409522014-02-01 03:16:11 -05001177def _check_change_has_branch_field(_project, commit):
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001178 """Check for a non-empty 'BRANCH=' field in the commit message."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001179 if commit == PRE_SUBMIT:
1180 return
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001181 BRANCH_RE = r'\nBRANCH=\S+'
1182
1183 if not re.search(BRANCH_RE, _get_commit_desc(commit)):
1184 msg = ('Changelist description needs BRANCH field (after first line)\n'
1185 'E.g. BRANCH=none or BRANCH=link,snow')
1186 return HookFailure(msg)
1187
1188
Mike Frysingerae409522014-02-01 03:16:11 -05001189def _check_change_has_signoff_field(_project, commit):
Shawn Nematbakhsh51e16ac2014-01-28 15:31:07 -08001190 """Check for a non-empty 'Signed-off-by:' field in the commit message."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001191 if commit == PRE_SUBMIT:
1192 return
Shawn Nematbakhsh51e16ac2014-01-28 15:31:07 -08001193 SIGNOFF_RE = r'\nSigned-off-by: \S+'
1194
1195 if not re.search(SIGNOFF_RE, _get_commit_desc(commit)):
1196 msg = ('Changelist description needs Signed-off-by: field\n'
1197 'E.g. Signed-off-by: My Name <me@chromium.org>')
1198 return HookFailure(msg)
1199
1200
Jon Salz3ee59de2012-08-18 13:54:22 +08001201def _run_project_hook_script(script, project, commit):
1202 """Runs a project hook script.
1203
1204 The script is run with the following environment variables set:
1205 PRESUBMIT_PROJECT: The affected project
1206 PRESUBMIT_COMMIT: The affected commit
1207 PRESUBMIT_FILES: A newline-separated list of affected files
1208
1209 The script is considered to fail if the exit code is non-zero. It should
1210 write an error message to stdout.
1211 """
1212 env = dict(os.environ)
Alex Deymo643ac4c2015-09-03 10:40:50 -07001213 env['PRESUBMIT_PROJECT'] = project.name
Jon Salz3ee59de2012-08-18 13:54:22 +08001214 env['PRESUBMIT_COMMIT'] = commit
1215
1216 # Put affected files in an environment variable
1217 files = _get_affected_files(commit)
1218 env['PRESUBMIT_FILES'] = '\n'.join(files)
1219
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001220 cmd_result = cros_build_lib.RunCommand(cmd=script,
1221 env=env,
1222 shell=True,
1223 print_cmd=False,
1224 input=os.devnull,
1225 stdout_to_pipe=True,
1226 combine_stdout_stderr=True,
1227 error_code_ok=True)
1228 if cmd_result.returncode:
1229 stdout = cmd_result.output
Jon Salz7b618af2012-08-31 06:03:16 +08001230 if stdout:
1231 stdout = re.sub('(?m)^', ' ', stdout)
1232 return HookFailure('Hook script "%s" failed with code %d%s' %
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001233 (script, cmd_result.returncode,
Jon Salz3ee59de2012-08-18 13:54:22 +08001234 ':\n' + stdout if stdout else ''))
1235
1236
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001237def _check_project_prefix(_project, commit):
Mike Frysinger55f85b52014-12-18 14:45:21 -05001238 """Require the commit message have a project specific prefix as needed."""
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001239
1240 files = _get_affected_files(commit, relative=True)
1241 prefix = os.path.commonprefix(files)
1242 prefix = os.path.dirname(prefix)
1243
1244 # If there is no common prefix, the CL span multiple projects.
Daniel Erata350fd32014-09-29 14:02:34 -07001245 if not prefix:
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001246 return
1247
1248 project_name = prefix.split('/')[0]
Daniel Erata350fd32014-09-29 14:02:34 -07001249
1250 # The common files may all be within a subdirectory of the main project
1251 # directory, so walk up the tree until we find an alias file.
1252 # _get_affected_files() should return relative paths, but check against '/' to
1253 # ensure that this loop terminates even if it receives an absolute path.
1254 while prefix and prefix != '/':
1255 alias_file = os.path.join(prefix, '.project_alias')
1256
1257 # If an alias exists, use it.
1258 if os.path.isfile(alias_file):
1259 project_name = osutils.ReadFile(alias_file).strip()
1260
1261 prefix = os.path.dirname(prefix)
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001262
1263 if not _get_commit_desc(commit).startswith(project_name + ': '):
1264 return HookFailure('The commit title for changes affecting only %s'
1265 ' should start with \"%s: \"'
1266 % (project_name, project_name))
1267
1268
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001269# Base
1270
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001271# A list of hooks which are not project specific and check patch description
1272# (as opposed to patch body).
1273_PATCH_DESCRIPTION_HOOKS = [
Ryan Cui9b651632011-05-11 11:38:58 -07001274 _check_change_has_bug_field,
David Jamesc3b68b32013-04-03 09:17:03 -07001275 _check_change_has_valid_cq_depend,
Ryan Cui9b651632011-05-11 11:38:58 -07001276 _check_change_has_test_field,
1277 _check_change_has_proper_changeid,
Mike Frysinger36b2ebc2014-10-31 14:02:03 -04001278 _check_commit_message_style,
Bernie Thompsonf8fea992016-01-14 10:27:18 -08001279 _check_change_is_contribution,
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001280]
1281
1282
1283# A list of hooks that are not project-specific
1284_COMMON_HOOKS = [
Mike Frysingerbf8b91c2014-02-01 02:50:27 -05001285 _check_ebuild_eapi,
Mike Frysinger89bdb852014-02-01 05:26:26 -05001286 _check_ebuild_keywords,
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -08001287 _check_ebuild_licenses,
Mike Frysingercd363c82014-02-01 05:20:18 -05001288 _check_ebuild_virtual_pv,
Daniel Erat9d203ff2015-02-17 10:12:21 -07001289 _check_for_uprev,
Rahul Chaudhry09f61372015-07-31 17:14:26 -07001290 _check_gofmt,
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001291 _check_layout_conf,
Alex Deymof5792ce2015-08-24 22:50:08 -07001292 _check_cros_license,
Daniel Erat9d203ff2015-02-17 10:12:21 -07001293 _check_no_long_lines,
1294 _check_no_stray_whitespace,
Ryan Cui9b651632011-05-11 11:38:58 -07001295 _check_no_tabs,
Daniel Erat9d203ff2015-02-17 10:12:21 -07001296 _check_portage_make_use_var,
Ryan Cui9b651632011-05-11 11:38:58 -07001297]
Ryan Cuiec4d6332011-05-02 14:15:25 -07001298
Ryan Cui1562fb82011-05-09 11:01:31 -07001299
Ryan Cui9b651632011-05-11 11:38:58 -07001300# A dictionary of project-specific hooks(callbacks), indexed by project name.
1301# dict[project] = [callback1, callback2]
1302_PROJECT_SPECIFIC_HOOKS = {
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001303 "chromiumos/platform2": [_check_project_prefix],
Mike Frysingeraf891292015-03-25 19:46:53 -04001304 "chromiumos/third_party/kernel": [_kernel_configcheck],
1305 "chromiumos/third_party/kernel-next": [_kernel_configcheck],
Ryan Cui9b651632011-05-11 11:38:58 -07001306}
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001307
Ryan Cui1562fb82011-05-09 11:01:31 -07001308
Ryan Cui9b651632011-05-11 11:38:58 -07001309# A dictionary of flags (keys) that can appear in the config file, and the hook
Mike Frysinger3554bc92015-03-11 04:59:21 -04001310# that the flag controls (value).
1311_HOOK_FLAGS = {
Mike Frysingera7642f52015-03-25 18:31:42 -04001312 'checkpatch_check': _run_checkpatch,
Ryan Cui9b651632011-05-11 11:38:58 -07001313 'stray_whitespace_check': _check_no_stray_whitespace,
Mike Frysingerff6c7d62015-03-24 13:49:46 -04001314 'json_check': _run_json_check,
Ryan Cui9b651632011-05-11 11:38:58 -07001315 'long_line_check': _check_no_long_lines,
Alex Deymof5792ce2015-08-24 22:50:08 -07001316 'cros_license_check': _check_cros_license,
1317 'aosp_license_check': _check_aosp_license,
Ryan Cui9b651632011-05-11 11:38:58 -07001318 'tab_check': _check_no_tabs,
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001319 'branch_check': _check_change_has_branch_field,
Shawn Nematbakhsh51e16ac2014-01-28 15:31:07 -08001320 'signoff_check': _check_change_has_signoff_field,
Josh Triplett0e8fc7f2014-04-23 16:00:00 -07001321 'bug_field_check': _check_change_has_bug_field,
1322 'test_field_check': _check_change_has_test_field,
Steve Fung49ec7e92015-03-23 16:07:12 -07001323 'manifest_check': _check_manifests,
Bernie Thompsonf8fea992016-01-14 10:27:18 -08001324 'contribution_check': _check_change_is_contribution,
Ryan Cui9b651632011-05-11 11:38:58 -07001325}
1326
1327
Mike Frysinger3554bc92015-03-11 04:59:21 -04001328def _get_override_hooks(config):
1329 """Returns a set of hooks controlled by the current project's config file.
Ryan Cui9b651632011-05-11 11:38:58 -07001330
1331 Expects to be called within the project root.
Jon Salz3ee59de2012-08-18 13:54:22 +08001332
1333 Args:
1334 config: A ConfigParser for the project's config file.
Ryan Cui9b651632011-05-11 11:38:58 -07001335 """
1336 SECTION = 'Hook Overrides'
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001337 SECTION_OPTIONS = 'Hook Overrides Options'
Jon Salz3ee59de2012-08-18 13:54:22 +08001338 if not config.has_section(SECTION):
Mike Frysinger3554bc92015-03-11 04:59:21 -04001339 return set(), set()
Ryan Cui9b651632011-05-11 11:38:58 -07001340
Mike Frysinger3554bc92015-03-11 04:59:21 -04001341 valid_keys = set(_HOOK_FLAGS.iterkeys())
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001342 hooks = _HOOK_FLAGS.copy()
Mike Frysinger3554bc92015-03-11 04:59:21 -04001343
1344 enable_flags = []
Ryan Cui9b651632011-05-11 11:38:58 -07001345 disable_flags = []
Jon Salz3ee59de2012-08-18 13:54:22 +08001346 for flag in config.options(SECTION):
Mike Frysinger3554bc92015-03-11 04:59:21 -04001347 if flag not in valid_keys:
1348 raise ValueError('Error: unknown key "%s" in hook section of "%s"' %
1349 (flag, _CONFIG_FILE))
1350
Ryan Cui9b651632011-05-11 11:38:58 -07001351 try:
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001352 enabled = config.getboolean(SECTION, flag)
Ryan Cui9b651632011-05-11 11:38:58 -07001353 except ValueError as e:
Mike Frysinger3554bc92015-03-11 04:59:21 -04001354 raise ValueError('Error: parsing flag "%s" in "%s" failed: %s' %
1355 (flag, _CONFIG_FILE, e))
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001356 if enabled:
1357 enable_flags.append(flag)
1358 else:
1359 disable_flags.append(flag)
Ryan Cui9b651632011-05-11 11:38:58 -07001360
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001361 # See if this hook has custom options.
1362 if enabled:
1363 try:
1364 options = config.get(SECTION_OPTIONS, flag)
1365 hooks[flag] = functools.partial(hooks[flag], options=options.split())
1366 except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
1367 pass
1368
1369 enabled_hooks = set(hooks[x] for x in enable_flags)
1370 disabled_hooks = set(hooks[x] for x in disable_flags)
Mike Frysinger3554bc92015-03-11 04:59:21 -04001371 return enabled_hooks, disabled_hooks
Ryan Cui9b651632011-05-11 11:38:58 -07001372
1373
Jon Salz3ee59de2012-08-18 13:54:22 +08001374def _get_project_hook_scripts(config):
1375 """Returns a list of project-specific hook scripts.
1376
1377 Args:
1378 config: A ConfigParser for the project's config file.
1379 """
1380 SECTION = 'Hook Scripts'
1381 if not config.has_section(SECTION):
1382 return []
1383
1384 hook_names_values = config.items(SECTION)
1385 hook_names_values.sort(key=lambda x: x[0])
1386 return [x[1] for x in hook_names_values]
1387
1388
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001389def _get_project_hooks(project, presubmit):
Ryan Cui9b651632011-05-11 11:38:58 -07001390 """Returns a list of hooks that need to be run for a project.
1391
1392 Expects to be called from within the project root.
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001393
1394 Args:
1395 project: A string, name of the project.
1396 presubmit: A Boolean, True if the check is run as a git pre-submit script.
Ryan Cui9b651632011-05-11 11:38:58 -07001397 """
Jon Salz3ee59de2012-08-18 13:54:22 +08001398 config = ConfigParser.RawConfigParser()
1399 try:
1400 config.read(_CONFIG_FILE)
1401 except ConfigParser.Error:
1402 # Just use an empty config file
1403 config = ConfigParser.RawConfigParser()
1404
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001405 if presubmit:
Filipe Brandenburgerf70d32c2015-10-09 13:35:45 -07001406 hooks = _COMMON_HOOKS
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001407 else:
Filipe Brandenburgerf70d32c2015-10-09 13:35:45 -07001408 hooks = _PATCH_DESCRIPTION_HOOKS + _COMMON_HOOKS
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001409
Mike Frysinger3554bc92015-03-11 04:59:21 -04001410 enabled_hooks, disabled_hooks = _get_override_hooks(config)
Filipe Brandenburgerf70d32c2015-10-09 13:35:45 -07001411 hooks = [hook for hook in hooks if hook not in disabled_hooks]
1412
1413 # If a list is both in _COMMON_HOOKS and also enabled explicitly through an
1414 # override, keep the override only. Note that the override may end up being
1415 # a functools.partial, in which case we need to extract the .func to compare
1416 # it to the common hooks.
1417 unwrapped_hooks = [getattr(hook, 'func', hook) for hook in enabled_hooks]
1418 hooks = [hook for hook in hooks if hook not in unwrapped_hooks]
1419
1420 hooks = list(enabled_hooks) + hooks
Ryan Cui9b651632011-05-11 11:38:58 -07001421
1422 if project in _PROJECT_SPECIFIC_HOOKS:
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001423 hooks.extend(hook for hook in _PROJECT_SPECIFIC_HOOKS[project]
1424 if hook not in disabled_hooks)
Ryan Cui9b651632011-05-11 11:38:58 -07001425
Jon Salz3ee59de2012-08-18 13:54:22 +08001426 for script in _get_project_hook_scripts(config):
1427 hooks.append(functools.partial(_run_project_hook_script, script))
1428
Ryan Cui9b651632011-05-11 11:38:58 -07001429 return hooks
1430
1431
Alex Deymo643ac4c2015-09-03 10:40:50 -07001432def _run_project_hooks(project_name, proj_dir=None,
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001433 commit_list=None, presubmit=False):
Ryan Cui1562fb82011-05-09 11:01:31 -07001434 """For each project run its project specific hook from the hooks dictionary.
1435
1436 Args:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001437 project_name: The name of project to run hooks for.
Doug Anderson44a644f2011-11-02 10:37:37 -07001438 proj_dir: If non-None, this is the directory the project is in. If None,
1439 we'll ask repo.
Doug Anderson14749562013-06-26 13:38:29 -07001440 commit_list: A list of commits to run hooks against. If None or empty list
1441 then we'll automatically get the list of commits that would be uploaded.
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001442 presubmit: A Boolean, True if the check is run as a git pre-submit script.
Ryan Cui1562fb82011-05-09 11:01:31 -07001443
1444 Returns:
1445 Boolean value of whether any errors were ecountered while running the hooks.
1446 """
Doug Anderson44a644f2011-11-02 10:37:37 -07001447 if proj_dir is None:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001448 proj_dirs = _run_command(
1449 ['repo', 'forall', project_name, '-c', 'pwd']).split()
David James2edd9002013-10-11 14:09:19 -07001450 if len(proj_dirs) == 0:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001451 print('%s cannot be found.' % project_name, file=sys.stderr)
David James2edd9002013-10-11 14:09:19 -07001452 print('Please specify a valid project.', file=sys.stderr)
1453 return True
1454 if len(proj_dirs) > 1:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001455 print('%s is associated with multiple directories.' % project_name,
David James2edd9002013-10-11 14:09:19 -07001456 file=sys.stderr)
1457 print('Please specify a directory to help disambiguate.', file=sys.stderr)
1458 return True
1459 proj_dir = proj_dirs[0]
Doug Anderson44a644f2011-11-02 10:37:37 -07001460
Ryan Cuiec4d6332011-05-02 14:15:25 -07001461 pwd = os.getcwd()
1462 # hooks assume they are run from the root of the project
1463 os.chdir(proj_dir)
1464
Alex Deymo643ac4c2015-09-03 10:40:50 -07001465 remote_branch = _run_command(['git', 'rev-parse', '--abbrev-ref',
1466 '--symbolic-full-name', '@{u}']).strip()
1467 if not remote_branch:
1468 print('Your project %s doesn\'t track any remote repo.' % project_name,
1469 file=sys.stderr)
1470 remote = None
1471 else:
1472 remote, _branch = remote_branch.split('/', 1)
1473
1474 project = Project(name=project_name, dir=proj_dir, remote=remote)
1475
Doug Anderson14749562013-06-26 13:38:29 -07001476 if not commit_list:
1477 try:
1478 commit_list = _get_commits()
1479 except VerifyException as e:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001480 PrintErrorForProject(project.name, HookFailure(str(e)))
Doug Anderson14749562013-06-26 13:38:29 -07001481 os.chdir(pwd)
1482 return True
Ryan Cuifa55df52011-05-06 11:16:55 -07001483
Alex Deymo643ac4c2015-09-03 10:40:50 -07001484 hooks = _get_project_hooks(project.name, presubmit)
Ryan Cui1562fb82011-05-09 11:01:31 -07001485 error_found = False
Ryan Cuifa55df52011-05-06 11:16:55 -07001486 for commit in commit_list:
Ryan Cui1562fb82011-05-09 11:01:31 -07001487 error_list = []
Ryan Cui9b651632011-05-11 11:38:58 -07001488 for hook in hooks:
Ryan Cui1562fb82011-05-09 11:01:31 -07001489 hook_error = hook(project, commit)
1490 if hook_error:
1491 error_list.append(hook_error)
1492 error_found = True
1493 if error_list:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001494 PrintErrorsForCommit(project.name, commit, _get_commit_desc(commit),
Ryan Cui1562fb82011-05-09 11:01:31 -07001495 error_list)
Don Garrettdba548a2011-05-05 15:17:14 -07001496
Ryan Cuiec4d6332011-05-02 14:15:25 -07001497 os.chdir(pwd)
Ryan Cui1562fb82011-05-09 11:01:31 -07001498 return error_found
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001499
Mike Frysingerae409522014-02-01 03:16:11 -05001500
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001501# Main
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -07001502
Ryan Cui1562fb82011-05-09 11:01:31 -07001503
Mike Frysingerae409522014-02-01 03:16:11 -05001504def main(project_list, worktree_list=None, **_kwargs):
Doug Anderson06456632012-01-05 11:02:14 -08001505 """Main function invoked directly by repo.
1506
1507 This function will exit directly upon error so that repo doesn't print some
1508 obscure error message.
1509
1510 Args:
1511 project_list: List of projects to run on.
David James2edd9002013-10-11 14:09:19 -07001512 worktree_list: A list of directories. It should be the same length as
1513 project_list, so that each entry in project_list matches with a directory
1514 in worktree_list. If None, we will attempt to calculate the directories
1515 automatically.
Doug Anderson06456632012-01-05 11:02:14 -08001516 kwargs: Leave this here for forward-compatibility.
1517 """
Ryan Cui1562fb82011-05-09 11:01:31 -07001518 found_error = False
David James2edd9002013-10-11 14:09:19 -07001519 if not worktree_list:
1520 worktree_list = [None] * len(project_list)
1521 for project, worktree in zip(project_list, worktree_list):
1522 if _run_project_hooks(project, proj_dir=worktree):
Ryan Cui1562fb82011-05-09 11:01:31 -07001523 found_error = True
1524
Mike Frysingerae409522014-02-01 03:16:11 -05001525 if found_error:
Ryan Cui1562fb82011-05-09 11:01:31 -07001526 msg = ('Preupload failed due to errors in project(s). HINTS:\n'
Ryan Cui9b651632011-05-11 11:38:58 -07001527 '- To disable some source style checks, and for other hints, see '
1528 '<checkout_dir>/src/repohooks/README\n'
1529 '- To upload only current project, run \'repo upload .\'')
Mike Frysinger09d6a3d2013-10-08 22:21:03 -04001530 print(msg, file=sys.stderr)
Don Garrettdba548a2011-05-05 15:17:14 -07001531 sys.exit(1)
Anush Elangovan63afad72011-03-23 00:41:27 -07001532
Ryan Cui1562fb82011-05-09 11:01:31 -07001533
Doug Anderson44a644f2011-11-02 10:37:37 -07001534def _identify_project(path):
1535 """Identify the repo project associated with the given path.
1536
1537 Returns:
1538 A string indicating what project is associated with the path passed in or
1539 a blank string upon failure.
1540 """
1541 return _run_command(['repo', 'forall', '.', '-c', 'echo ${REPO_PROJECT}'],
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001542 redirect_stderr=True, cwd=path).strip()
Doug Anderson44a644f2011-11-02 10:37:37 -07001543
1544
Mike Frysinger55f85b52014-12-18 14:45:21 -05001545def direct_main(argv):
Doug Anderson44a644f2011-11-02 10:37:37 -07001546 """Run hooks directly (outside of the context of repo).
1547
Doug Anderson44a644f2011-11-02 10:37:37 -07001548 Args:
Mike Frysinger55f85b52014-12-18 14:45:21 -05001549 argv: The command line args to process
Doug Anderson44a644f2011-11-02 10:37:37 -07001550
1551 Returns:
1552 0 if no pre-upload failures, 1 if failures.
1553
1554 Raises:
1555 BadInvocation: On some types of invocation errors.
1556 """
Mike Frysinger66142932014-12-18 14:55:57 -05001557 parser = commandline.ArgumentParser(description=__doc__)
1558 parser.add_argument('--dir', default=None,
1559 help='The directory that the project lives in. If not '
1560 'specified, use the git project root based on the cwd.')
1561 parser.add_argument('--project', default=None,
1562 help='The project repo path; this can affect how the '
1563 'hooks get run, since some hooks are project-specific. '
1564 'For chromite this is chromiumos/chromite. If not '
1565 'specified, the repo tool will be used to figure this '
1566 'out based on the dir.')
1567 parser.add_argument('--rerun-since', default=None,
1568 help='Rerun hooks on old commits since the given date. '
1569 'The date should match git log\'s concept of a date. '
1570 'e.g. 2012-06-20. This option is mutually exclusive '
1571 'with --pre-submit.')
1572 parser.add_argument('--pre-submit', action="store_true",
1573 help='Run the check against the pending commit. '
1574 'This option should be used at the \'git commit\' '
1575 'phase as opposed to \'repo upload\'. This option '
1576 'is mutually exclusive with --rerun-since.')
1577 parser.add_argument('commits', nargs='*',
1578 help='Check specific commits')
1579 opts = parser.parse_args(argv)
Doug Anderson44a644f2011-11-02 10:37:37 -07001580
Doug Anderson14749562013-06-26 13:38:29 -07001581 if opts.rerun_since:
Mike Frysinger66142932014-12-18 14:55:57 -05001582 if opts.commits:
Doug Anderson14749562013-06-26 13:38:29 -07001583 raise BadInvocation('Can\'t pass commits and use rerun-since: %s' %
Mike Frysinger66142932014-12-18 14:55:57 -05001584 ' '.join(opts.commits))
Doug Anderson14749562013-06-26 13:38:29 -07001585
1586 cmd = ['git', 'log', '--since="%s"' % opts.rerun_since, '--pretty=%H']
1587 all_commits = _run_command(cmd).splitlines()
1588 bot_commits = _run_command(cmd + ['--author=chrome-bot']).splitlines()
1589
1590 # Eliminate chrome-bot commits but keep ordering the same...
1591 bot_commits = set(bot_commits)
Mike Frysinger66142932014-12-18 14:55:57 -05001592 opts.commits = [c for c in all_commits if c not in bot_commits]
Doug Anderson14749562013-06-26 13:38:29 -07001593
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001594 if opts.pre_submit:
1595 raise BadInvocation('rerun-since and pre-submit can not be '
1596 'used together')
1597 if opts.pre_submit:
Mike Frysinger66142932014-12-18 14:55:57 -05001598 if opts.commits:
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001599 raise BadInvocation('Can\'t pass commits and use pre-submit: %s' %
Mike Frysinger66142932014-12-18 14:55:57 -05001600 ' '.join(opts.commits))
1601 opts.commits = [PRE_SUBMIT,]
Doug Anderson44a644f2011-11-02 10:37:37 -07001602
1603 # Check/normlaize git dir; if unspecified, we'll use the root of the git
1604 # project from CWD
1605 if opts.dir is None:
1606 git_dir = _run_command(['git', 'rev-parse', '--git-dir'],
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001607 redirect_stderr=True).strip()
Doug Anderson44a644f2011-11-02 10:37:37 -07001608 if not git_dir:
1609 raise BadInvocation('The current directory is not part of a git project.')
1610 opts.dir = os.path.dirname(os.path.abspath(git_dir))
1611 elif not os.path.isdir(opts.dir):
1612 raise BadInvocation('Invalid dir: %s' % opts.dir)
1613 elif not os.path.isdir(os.path.join(opts.dir, '.git')):
1614 raise BadInvocation('Not a git directory: %s' % opts.dir)
1615
1616 # Identify the project if it wasn't specified; this _requires_ the repo
1617 # tool to be installed and for the project to be part of a repo checkout.
1618 if not opts.project:
1619 opts.project = _identify_project(opts.dir)
1620 if not opts.project:
1621 raise BadInvocation("Repo couldn't identify the project of %s" % opts.dir)
1622
Doug Anderson14749562013-06-26 13:38:29 -07001623 found_error = _run_project_hooks(opts.project, proj_dir=opts.dir,
Mike Frysinger66142932014-12-18 14:55:57 -05001624 commit_list=opts.commits,
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001625 presubmit=opts.pre_submit)
Doug Anderson44a644f2011-11-02 10:37:37 -07001626 if found_error:
1627 return 1
1628 return 0
1629
1630
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -07001631if __name__ == '__main__':
Mike Frysinger55f85b52014-12-18 14:45:21 -05001632 sys.exit(direct_main(sys.argv[1:]))