blob: 011457f8aacbeecc84773532aa0e94322c3d226b [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
Alex Deymo643ac4c2015-09-03 10:40:50 -070013import collections
Ryan Cui9b651632011-05-11 11:38:58 -070014import ConfigParser
Daniel Erate3ea3fc2015-02-13 15:27:52 -070015import fnmatch
Jon Salz3ee59de2012-08-18 13:54:22 +080016import functools
Dale Curtis2975c432011-05-03 17:25:20 -070017import json
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070018import os
Ryan Cuiec4d6332011-05-02 14:15:25 -070019import re
Mandeep Singh Bainesa7ffa4b2011-05-03 11:37:02 -070020import sys
Peter Ammon811f6702014-06-12 15:45:38 -070021import stat
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070022
Ryan Cui1562fb82011-05-09 11:01:31 -070023from errors import (VerifyException, HookFailure, PrintErrorForProject,
24 PrintErrorsForCommit)
Ryan Cuiec4d6332011-05-02 14:15:25 -070025
David Jamesc3b68b32013-04-03 09:17:03 -070026# If repo imports us, the __name__ will be __builtin__, and the wrapper will
27# be in $CHROMEOS_CHECKOUT/.repo/repo/main.py, so we need to go two directories
28# up. The same logic also happens to work if we're executed directly.
29if __name__ in ('__builtin__', '__main__'):
30 sys.path.insert(0, os.path.join(os.path.dirname(sys.argv[0]), '..', '..'))
31
Mike Frysinger66142932014-12-18 14:55:57 -050032from chromite.lib import commandline
Rahul Chaudhry0e515342015-08-07 12:00:43 -070033from chromite.lib import cros_build_lib
Mike Frysingerd3bd32c2014-11-24 23:34:29 -050034from chromite.lib import git
Daniel Erata350fd32014-09-29 14:02:34 -070035from chromite.lib import osutils
David Jamesc3b68b32013-04-03 09:17:03 -070036from chromite.lib import patch
Mike Frysinger2ec70ed2014-08-17 19:28:34 -040037from chromite.licensing import licenses_lib
David Jamesc3b68b32013-04-03 09:17:03 -070038
Vadim Bendebury2b62d742014-06-22 13:14:51 -070039PRE_SUBMIT = 'pre-submit'
Ryan Cuiec4d6332011-05-02 14:15:25 -070040
41COMMON_INCLUDED_PATHS = [
Mike Frysingerae409522014-02-01 03:16:11 -050042 # C++ and friends
43 r".*\.c$", r".*\.cc$", r".*\.cpp$", r".*\.h$", r".*\.m$", r".*\.mm$",
44 r".*\.inl$", r".*\.asm$", r".*\.hxx$", r".*\.hpp$", r".*\.s$", r".*\.S$",
45 # Scripts
46 r".*\.js$", r".*\.py$", r".*\.sh$", r".*\.rb$", r".*\.pl$", r".*\.pm$",
47 # No extension at all, note that ALL CAPS files are black listed in
48 # COMMON_EXCLUDED_LIST below.
49 r"(^|.*[\\\/])[^.]+$",
50 # Other
51 r".*\.java$", r".*\.mk$", r".*\.am$",
Ryan Cuiec4d6332011-05-02 14:15:25 -070052]
53
Ryan Cui1562fb82011-05-09 11:01:31 -070054
Ryan Cuiec4d6332011-05-02 14:15:25 -070055COMMON_EXCLUDED_PATHS = [
Daniel Erate3ea3fc2015-02-13 15:27:52 -070056 # Avoid doing source file checks for kernel.
Mike Frysingerae409522014-02-01 03:16:11 -050057 r"/src/third_party/kernel/",
58 r"/src/third_party/kernel-next/",
59 r"/src/third_party/ktop/",
60 r"/src/third_party/punybench/",
61 r".*\bexperimental[\\\/].*",
62 r".*\b[A-Z0-9_]{2,}$",
63 r".*[\\\/]debian[\\\/]rules$",
Daniel Erate3ea3fc2015-02-13 15:27:52 -070064
65 # For ebuild trees, ignore any caches and manifest data.
Mike Frysingerae409522014-02-01 03:16:11 -050066 r".*/Manifest$",
67 r".*/metadata/[^/]*cache[^/]*/[^/]+/[^/]+$",
Doug Anderson5bfb6792011-10-25 16:45:41 -070068
Daniel Erate3ea3fc2015-02-13 15:27:52 -070069 # Ignore profiles data (like overlay-tegra2/profiles).
Mike Frysinger94a670c2014-09-19 12:46:26 -040070 r"(^|.*/)overlay-.*/profiles/.*",
Mike Frysinger98638102014-08-28 00:15:08 -040071 r"^profiles/.*$",
72
Daniel Erate3ea3fc2015-02-13 15:27:52 -070073 # Ignore minified js and jquery.
Mike Frysingerae409522014-02-01 03:16:11 -050074 r".*\.min\.js",
75 r".*jquery.*\.js",
Mike Frysinger33a458d2014-03-03 17:00:51 -050076
77 # Ignore license files as the content is often taken verbatim.
Daniel Erate3ea3fc2015-02-13 15:27:52 -070078 r".*/licenses/.*",
Ryan Cuiec4d6332011-05-02 14:15:25 -070079]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070080
Ryan Cui1562fb82011-05-09 11:01:31 -070081
Ryan Cui9b651632011-05-11 11:38:58 -070082_CONFIG_FILE = 'PRESUBMIT.cfg'
83
84
Daniel Erate3ea3fc2015-02-13 15:27:52 -070085# File containing wildcards, one per line, matching files that should be
86# excluded from presubmit checks. Lines beginning with '#' are ignored.
87_IGNORE_FILE = '.presubmitignore'
88
89
Doug Anderson44a644f2011-11-02 10:37:37 -070090# Exceptions
91
92
93class BadInvocation(Exception):
94 """An Exception indicating a bad invocation of the program."""
95 pass
96
97
Ryan Cui1562fb82011-05-09 11:01:31 -070098# General Helpers
99
Sean Paulba01d402011-05-05 11:36:23 -0400100
Alex Deymo643ac4c2015-09-03 10:40:50 -0700101Project = collections.namedtuple('Project', ['name', 'dir', 'remote'])
102
103
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700104# pylint: disable=redefined-builtin
105def _run_command(cmd, cwd=None, input=None,
106 redirect_stderr=False, combine_stdout_stderr=False):
Doug Anderson44a644f2011-11-02 10:37:37 -0700107 """Executes the passed in command and returns raw stdout output.
108
109 Args:
110 cmd: The command to run; should be a list of strings.
111 cwd: The directory to switch to for running the command.
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700112 input: The data to pipe into this command through stdin. If a file object
113 or file descriptor, stdin will be connected directly to that.
114 redirect_stderr: Redirect stderr away from console.
115 combine_stdout_stderr: Combines stdout and stderr streams into stdout.
Doug Anderson44a644f2011-11-02 10:37:37 -0700116
117 Returns:
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700118 The stdout from the process (discards stderr and returncode).
Doug Anderson44a644f2011-11-02 10:37:37 -0700119 """
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700120 return cros_build_lib.RunCommand(cmd=cmd,
121 cwd=cwd,
122 print_cmd=False,
123 input=input,
124 stdout_to_pipe=True,
125 redirect_stderr=redirect_stderr,
126 combine_stdout_stderr=combine_stdout_stderr,
127 error_code_ok=True).output
128# pylint: enable=redefined-builtin
Ryan Cui72834d12011-05-05 14:51:33 -0700129
Ryan Cui1562fb82011-05-09 11:01:31 -0700130
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700131def _get_hooks_dir():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700132 """Returns the absolute path to the repohooks directory."""
Doug Anderson44a644f2011-11-02 10:37:37 -0700133 if __name__ == '__main__':
134 # Works when file is run on its own (__file__ is defined)...
135 return os.path.abspath(os.path.dirname(__file__))
136 else:
137 # We need to do this when we're run through repo. Since repo executes
138 # us with execfile(), we don't get __file__ defined.
139 cmd = ['repo', 'forall', 'chromiumos/repohooks', '-c', 'pwd']
140 return _run_command(cmd).strip()
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700141
Ryan Cui1562fb82011-05-09 11:01:31 -0700142
Ryan Cuiec4d6332011-05-02 14:15:25 -0700143def _match_regex_list(subject, expressions):
144 """Try to match a list of regular expressions to a string.
145
146 Args:
147 subject: The string to match regexes on
148 expressions: A list of regular expressions to check for matches with.
149
150 Returns:
151 Whether the passed in subject matches any of the passed in regexes.
152 """
153 for expr in expressions:
Mike Frysingerae409522014-02-01 03:16:11 -0500154 if re.search(expr, subject):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700155 return True
156 return False
157
Ryan Cui1562fb82011-05-09 11:01:31 -0700158
Mike Frysingerae409522014-02-01 03:16:11 -0500159def _filter_files(files, include_list, exclude_list=()):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700160 """Filter out files based on the conditions passed in.
161
162 Args:
163 files: list of filepaths to filter
164 include_list: list of regex that when matched with a file path will cause it
165 to be added to the output list unless the file is also matched with a
166 regex in the exclude_list.
167 exclude_list: list of regex that when matched with a file will prevent it
168 from being added to the output list, even if it is also matched with a
169 regex in the include_list.
170
171 Returns:
172 A list of filepaths that contain files matched in the include_list and not
173 in the exclude_list.
174 """
175 filtered = []
176 for f in files:
177 if (_match_regex_list(f, include_list) and
178 not _match_regex_list(f, exclude_list)):
179 filtered.append(f)
180 return filtered
181
Ryan Cuiec4d6332011-05-02 14:15:25 -0700182
183# Git Helpers
Ryan Cui1562fb82011-05-09 11:01:31 -0700184
185
Ryan Cui4725d952011-05-05 15:41:19 -0700186def _get_upstream_branch():
187 """Returns the upstream tracking branch of the current branch.
188
189 Raises:
190 Error if there is no tracking branch
191 """
192 current_branch = _run_command(['git', 'symbolic-ref', 'HEAD']).strip()
193 current_branch = current_branch.replace('refs/heads/', '')
194 if not current_branch:
Ryan Cui1562fb82011-05-09 11:01:31 -0700195 raise VerifyException('Need to be on a tracking branch')
Ryan Cui4725d952011-05-05 15:41:19 -0700196
197 cfg_option = 'branch.' + current_branch + '.%s'
198 full_upstream = _run_command(['git', 'config', cfg_option % 'merge']).strip()
199 remote = _run_command(['git', 'config', cfg_option % 'remote']).strip()
200 if not remote or not full_upstream:
Ryan Cui1562fb82011-05-09 11:01:31 -0700201 raise VerifyException('Need to be on a tracking branch')
Ryan Cui4725d952011-05-05 15:41:19 -0700202
203 return full_upstream.replace('heads', 'remotes/' + remote)
204
Ryan Cui1562fb82011-05-09 11:01:31 -0700205
Che-Liang Chiou5ce2d7b2013-03-22 18:47:55 -0700206def _get_patch(commit):
207 """Returns the patch for this commit."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700208 if commit == PRE_SUBMIT:
209 return _run_command(['git', 'diff', '--cached', 'HEAD'])
210 else:
211 return _run_command(['git', 'format-patch', '--stdout', '-1', commit])
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700212
Ryan Cui1562fb82011-05-09 11:01:31 -0700213
Jon Salz98255932012-08-18 14:48:02 +0800214def _try_utf8_decode(data):
215 """Attempts to decode a string as UTF-8.
216
217 Returns:
218 The decoded Unicode object, or the original string if parsing fails.
219 """
220 try:
221 return unicode(data, 'utf-8', 'strict')
222 except UnicodeDecodeError:
223 return data
224
225
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500226def _get_file_content(path, commit):
227 """Returns the content of a file at a specific commit.
228
229 We can't rely on the file as it exists in the filesystem as people might be
230 uploading a series of changes which modifies the file multiple times.
231
232 Note: The "content" of a symlink is just the target. So if you're expecting
233 a full file, you should check that first. One way to detect is that the
234 content will not have any newlines.
235 """
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700236 if commit == PRE_SUBMIT:
237 return _run_command(['git', 'diff', 'HEAD', path])
238 else:
239 return _run_command(['git', 'show', '%s:%s' % (commit, path)])
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500240
241
Mike Frysingerae409522014-02-01 03:16:11 -0500242def _get_file_diff(path, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700243 """Returns a list of (linenum, lines) tuples that the commit touched."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700244 command = ['git', 'diff', '-p', '--pretty=format:', '--no-ext-diff']
245 if commit == PRE_SUBMIT:
246 command += ['HEAD', path]
247 else:
248 command += [commit, path]
249 output = _run_command(command)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700250
251 new_lines = []
252 line_num = 0
253 for line in output.splitlines():
254 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
255 if m:
256 line_num = int(m.groups(1)[0])
257 continue
258 if line.startswith('+') and not line.startswith('++'):
Jon Salz98255932012-08-18 14:48:02 +0800259 new_lines.append((line_num, _try_utf8_decode(line[1:])))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700260 if not line.startswith('-'):
261 line_num += 1
262 return new_lines
263
Ryan Cui1562fb82011-05-09 11:01:31 -0700264
Daniel Erate3ea3fc2015-02-13 15:27:52 -0700265def _get_ignore_wildcards(directory, cache):
266 """Get wildcards listed in a directory's _IGNORE_FILE.
267
268 Args:
269 directory: A string containing a directory path.
270 cache: A dictionary (opaque to caller) caching previously-read wildcards.
271
272 Returns:
273 A list of wildcards from _IGNORE_FILE or an empty list if _IGNORE_FILE
274 wasn't present.
275 """
276 # In the cache, keys are directories and values are lists of wildcards from
277 # _IGNORE_FILE within those directories (and empty if no file was present).
278 if directory not in cache:
279 wildcards = []
280 dotfile_path = os.path.join(directory, _IGNORE_FILE)
281 if os.path.exists(dotfile_path):
282 # TODO(derat): Consider using _get_file_content() to get the file as of
283 # this commit instead of the on-disk version. This may have a noticeable
284 # performance impact, as each call to _get_file_content() runs git.
285 with open(dotfile_path, 'r') as dotfile:
286 for line in dotfile.readlines():
287 line = line.strip()
288 if line.startswith('#'):
289 continue
290 if line.endswith('/'):
291 line += '*'
292 wildcards.append(line)
293 cache[directory] = wildcards
294
295 return cache[directory]
296
297
298def _path_is_ignored(path, cache):
299 """Check whether a path is ignored by _IGNORE_FILE.
300
301 Args:
302 path: A string containing a path.
303 cache: A dictionary (opaque to caller) caching previously-read wildcards.
304
305 Returns:
306 True if a file named _IGNORE_FILE in one of the passed-in path's parent
307 directories contains a wildcard matching the path.
308 """
309 # Skip ignore files.
310 if os.path.basename(path) == _IGNORE_FILE:
311 return True
312
313 path = os.path.abspath(path)
314 base = os.getcwd()
315
316 prefix = os.path.dirname(path)
317 while prefix.startswith(base):
318 rel_path = path[len(prefix) + 1:]
319 for wildcard in _get_ignore_wildcards(prefix, cache):
320 if fnmatch.fnmatch(rel_path, wildcard):
321 return True
322 prefix = os.path.dirname(prefix)
323
324 return False
325
326
Mike Frysinger292b45d2014-11-25 01:17:10 -0500327def _get_affected_files(commit, include_deletes=False, relative=False,
328 include_symlinks=False, include_adds=True,
Daniel Erate3ea3fc2015-02-13 15:27:52 -0700329 full_details=False, use_ignore_files=True):
Peter Ammon811f6702014-06-12 15:45:38 -0700330 """Returns list of file paths that were modified/added, excluding symlinks.
331
332 Args:
333 commit: The commit
334 include_deletes: If true, we'll include deleted files in the result
335 relative: Whether to return relative or full paths to files
Mike Frysinger292b45d2014-11-25 01:17:10 -0500336 include_symlinks: If true, we'll include symlinks in the result
337 include_adds: If true, we'll include new files in the result
338 full_details: If False, return filenames, else return structured results.
Daniel Erate3ea3fc2015-02-13 15:27:52 -0700339 use_ignore_files: Whether we ignore files matched by _IGNORE_FILE files.
Peter Ammon811f6702014-06-12 15:45:38 -0700340
341 Returns:
342 A list of modified/added (and perhaps deleted) files
343 """
Mike Frysinger292b45d2014-11-25 01:17:10 -0500344 if not relative and full_details:
345 raise ValueError('full_details only supports relative paths currently')
346
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700347 if commit == PRE_SUBMIT:
348 return _run_command(['git', 'diff-index', '--cached',
349 '--name-only', 'HEAD']).split()
Mike Frysingerd3bd32c2014-11-24 23:34:29 -0500350
351 path = os.getcwd()
352 files = git.RawDiff(path, '%s^!' % commit)
353
354 # Filter out symlinks.
Mike Frysinger292b45d2014-11-25 01:17:10 -0500355 if not include_symlinks:
356 files = [x for x in files if not stat.S_ISLNK(int(x.dst_mode, 8))]
Mike Frysingerd3bd32c2014-11-24 23:34:29 -0500357
358 if not include_deletes:
359 files = [x for x in files if x.status != 'D']
360
Mike Frysinger292b45d2014-11-25 01:17:10 -0500361 if not include_adds:
362 files = [x for x in files if x.status != 'A']
363
Daniel Erate3ea3fc2015-02-13 15:27:52 -0700364 if use_ignore_files:
365 cache = {}
366 is_ignored = lambda x: _path_is_ignored(x.dst_file or x.src_file, cache)
367 files = [x for x in files if not is_ignored(x)]
368
Mike Frysinger292b45d2014-11-25 01:17:10 -0500369 if full_details:
370 # Caller wants the raw objects to parse status/etc... themselves.
Mike Frysingerd3bd32c2014-11-24 23:34:29 -0500371 return files
372 else:
Mike Frysinger292b45d2014-11-25 01:17:10 -0500373 # Caller only cares about filenames.
374 files = [x.dst_file if x.dst_file else x.src_file for x in files]
375 if relative:
376 return files
377 else:
378 return [os.path.join(path, x) for x in files]
Peter Ammon811f6702014-06-12 15:45:38 -0700379
380
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700381def _get_commits():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700382 """Returns a list of commits for this review."""
Ryan Cui4725d952011-05-05 15:41:19 -0700383 cmd = ['git', 'log', '%s..' % _get_upstream_branch(), '--format=%H']
Ryan Cui72834d12011-05-05 14:51:33 -0700384 return _run_command(cmd).split()
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700385
Ryan Cui1562fb82011-05-09 11:01:31 -0700386
Ryan Cuiec4d6332011-05-02 14:15:25 -0700387def _get_commit_desc(commit):
388 """Returns the full commit message of a commit."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700389 if commit == PRE_SUBMIT:
390 return ''
Sean Paul23a2c582011-05-06 13:10:44 -0400391 return _run_command(['git', 'log', '--format=%s%n%n%b', commit + '^!'])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700392
393
394# Common Hooks
395
Ryan Cui1562fb82011-05-09 11:01:31 -0700396
Mike Frysingerae409522014-02-01 03:16:11 -0500397def _check_no_long_lines(_project, commit):
Mike Frysinger55f85b52014-12-18 14:45:21 -0500398 """Checks there are no lines longer than MAX_LEN in any of the text files."""
399
Ryan Cuiec4d6332011-05-02 14:15:25 -0700400 MAX_LEN = 80
Jon Salz98255932012-08-18 14:48:02 +0800401 SKIP_REGEXP = re.compile('|'.join([
402 r'https?://',
403 r'^#\s*(define|include|import|pragma|if|endif)\b']))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700404
405 errors = []
406 files = _filter_files(_get_affected_files(commit),
407 COMMON_INCLUDED_PATHS,
408 COMMON_EXCLUDED_PATHS)
409
410 for afile in files:
411 for line_num, line in _get_file_diff(afile, commit):
412 # Allow certain lines to exceed the maxlen rule.
Mike Frysingerae409522014-02-01 03:16:11 -0500413 if len(line) <= MAX_LEN or SKIP_REGEXP.search(line):
Jon Salz98255932012-08-18 14:48:02 +0800414 continue
415
416 errors.append('%s, line %s, %s chars' % (afile, line_num, len(line)))
417 if len(errors) == 5: # Just show the first 5 errors.
418 break
Ryan Cuiec4d6332011-05-02 14:15:25 -0700419
420 if errors:
421 msg = 'Found lines longer than %s characters (first 5 shown):' % MAX_LEN
Ryan Cui1562fb82011-05-09 11:01:31 -0700422 return HookFailure(msg, errors)
423
Ryan Cuiec4d6332011-05-02 14:15:25 -0700424
Mike Frysingerae409522014-02-01 03:16:11 -0500425def _check_no_stray_whitespace(_project, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700426 """Checks that there is no stray whitespace at source lines end."""
427 errors = []
428 files = _filter_files(_get_affected_files(commit),
Mike Frysingerae409522014-02-01 03:16:11 -0500429 COMMON_INCLUDED_PATHS,
430 COMMON_EXCLUDED_PATHS)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700431 for afile in files:
432 for line_num, line in _get_file_diff(afile, commit):
433 if line.rstrip() != line:
434 errors.append('%s, line %s' % (afile, line_num))
435 if errors:
Ryan Cui1562fb82011-05-09 11:01:31 -0700436 return HookFailure('Found line ending with white space in:', errors)
437
Ryan Cuiec4d6332011-05-02 14:15:25 -0700438
Mike Frysingerae409522014-02-01 03:16:11 -0500439def _check_no_tabs(_project, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700440 """Checks there are no unexpanded tabs."""
441 TAB_OK_PATHS = [
Ryan Cui31e0c172011-05-04 21:00:45 -0700442 r"/src/third_party/u-boot/",
Ryan Cuiec4d6332011-05-02 14:15:25 -0700443 r".*\.ebuild$",
444 r".*\.eclass$",
Elly Jones5ab34192011-11-15 14:57:06 -0500445 r".*/[M|m]akefile$",
446 r".*\.mk$"
Ryan Cuiec4d6332011-05-02 14:15:25 -0700447 ]
448
449 errors = []
450 files = _filter_files(_get_affected_files(commit),
451 COMMON_INCLUDED_PATHS,
452 COMMON_EXCLUDED_PATHS + TAB_OK_PATHS)
453
454 for afile in files:
455 for line_num, line in _get_file_diff(afile, commit):
456 if '\t' in line:
Mike Frysingerae409522014-02-01 03:16:11 -0500457 errors.append('%s, line %s' % (afile, line_num))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700458 if errors:
Ryan Cui1562fb82011-05-09 11:01:31 -0700459 return HookFailure('Found a tab character in:', errors)
460
Ryan Cuiec4d6332011-05-02 14:15:25 -0700461
Rahul Chaudhry09f61372015-07-31 17:14:26 -0700462def _check_gofmt(_project, commit):
463 """Checks that Go files are formatted with gofmt."""
464 errors = []
465 files = _filter_files(_get_affected_files(commit, relative=True),
466 [r'\.go$'])
467
468 for gofile in files:
469 contents = _get_file_content(gofile, commit)
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700470 output = _run_command(cmd=['gofmt', '-l'], input=contents,
471 combine_stdout_stderr=True)
Rahul Chaudhry09f61372015-07-31 17:14:26 -0700472 if output:
473 errors.append(gofile)
474 if errors:
475 return HookFailure('Files not formatted with gofmt:', errors)
476
477
Mike Frysingerae409522014-02-01 03:16:11 -0500478def _check_change_has_test_field(_project, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700479 """Check for a non-empty 'TEST=' field in the commit message."""
David McMahon8f6553e2011-06-10 15:46:36 -0700480 TEST_RE = r'\nTEST=\S+'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700481
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700482 if not re.search(TEST_RE, _get_commit_desc(commit)):
Ryan Cui1562fb82011-05-09 11:01:31 -0700483 msg = 'Changelist description needs TEST field (after first line)'
484 return HookFailure(msg)
485
Ryan Cuiec4d6332011-05-02 14:15:25 -0700486
Mike Frysingerae409522014-02-01 03:16:11 -0500487def _check_change_has_valid_cq_depend(_project, commit):
David Jamesc3b68b32013-04-03 09:17:03 -0700488 """Check for a correctly formatted CQ-DEPEND field in the commit message."""
489 msg = 'Changelist has invalid CQ-DEPEND target.'
490 example = 'Example: CQ-DEPEND=CL:1234, CL:2345'
491 try:
492 patch.GetPaladinDeps(_get_commit_desc(commit))
493 except ValueError as ex:
494 return HookFailure(msg, [example, str(ex)])
495
496
Alex Deymo643ac4c2015-09-03 10:40:50 -0700497def _check_change_has_bug_field(project, commit):
David McMahon8f6553e2011-06-10 15:46:36 -0700498 """Check for a correctly formatted 'BUG=' field in the commit message."""
David James5c0073d2013-04-03 08:48:52 -0700499 OLD_BUG_RE = r'\nBUG=.*chromium-os'
500 if re.search(OLD_BUG_RE, _get_commit_desc(commit)):
501 msg = ('The chromium-os bug tracker is now deprecated. Please use\n'
502 'the chromium tracker in your BUG= line now.')
503 return HookFailure(msg)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700504
Alex Deymo643ac4c2015-09-03 10:40:50 -0700505 # Android internal and external projects use "Bug: " to track bugs in
506 # buganizer.
507 BUG_COLON_REMOTES = (
508 'aosp',
509 'goog',
510 )
511 if project.remote in BUG_COLON_REMOTES:
512 BUG_RE = r'\nBug: ?([Nn]one|\d+)'
513 if not re.search(BUG_RE, _get_commit_desc(commit)):
514 msg = ('Changelist description needs BUG field (after first line):\n'
515 'Bug: 9999 (for buganizer)\n'
516 'BUG=None')
517 return HookFailure(msg)
518 else:
519 BUG_RE = r'\nBUG=([Nn]one|(chrome-os-partner|chromium|brillo|b):\d+)'
520 if not re.search(BUG_RE, _get_commit_desc(commit)):
521 msg = ('Changelist description needs BUG field (after first line):\n'
522 'BUG=brillo:9999 (for Brillo tracker)\n'
523 'BUG=chromium:9999 (for public tracker)\n'
524 'BUG=chrome-os-partner:9999 (for partner tracker)\n'
525 'BUG=b:9999 (for buganizer)\n'
526 'BUG=None')
527 return HookFailure(msg)
Ryan Cui1562fb82011-05-09 11:01:31 -0700528
Ryan Cuiec4d6332011-05-02 14:15:25 -0700529
Mike Frysinger292b45d2014-11-25 01:17:10 -0500530def _check_for_uprev(project, commit, project_top=None):
Doug Anderson42b8a052013-06-26 10:45:36 -0700531 """Check that we're not missing a revbump of an ebuild in the given commit.
532
533 If the given commit touches files in a directory that has ebuilds somewhere
534 up the directory hierarchy, it's very likely that we need an ebuild revbump
535 in order for those changes to take effect.
536
537 It's not totally trivial to detect a revbump, so at least detect that an
538 ebuild with a revision number in it was touched. This should handle the
539 common case where we use a symlink to do the revbump.
540
541 TODO: it would be nice to enhance this hook to:
542 * Handle cases where people revbump with a slightly different syntax. I see
543 one ebuild (puppy) that revbumps with _pN. This is a false positive.
544 * Catches cases where people aren't using symlinks for revbumps. If they
545 edit a revisioned file directly (and are expected to rename it for revbump)
546 we'll miss that. Perhaps we could detect that the file touched is a
547 symlink?
548
549 If a project doesn't use symlinks we'll potentially miss a revbump, but we're
550 still better off than without this check.
551
552 Args:
Alex Deymo643ac4c2015-09-03 10:40:50 -0700553 project: The Project to look at
Doug Anderson42b8a052013-06-26 10:45:36 -0700554 commit: The commit to look at
Mike Frysinger292b45d2014-11-25 01:17:10 -0500555 project_top: Top dir to process commits in
Doug Anderson42b8a052013-06-26 10:45:36 -0700556
557 Returns:
558 A HookFailure or None.
559 """
Mike Frysinger011af942014-01-17 16:12:22 -0500560 # If this is the portage-stable overlay, then ignore the check. It's rare
561 # that we're doing anything other than importing files from upstream, so
562 # forcing a rev bump makes no sense.
563 whitelist = (
564 'chromiumos/overlays/portage-stable',
565 )
Alex Deymo643ac4c2015-09-03 10:40:50 -0700566 if project.name in whitelist:
Mike Frysinger011af942014-01-17 16:12:22 -0500567 return None
568
Mike Frysinger292b45d2014-11-25 01:17:10 -0500569 def FinalName(obj):
570 # If the file is being deleted, then the dst_file is not set.
571 if obj.dst_file is None:
572 return obj.src_file
573 else:
574 return obj.dst_file
575
576 affected_path_objs = _get_affected_files(
577 commit, include_deletes=True, include_symlinks=True, relative=True,
578 full_details=True)
Doug Anderson42b8a052013-06-26 10:45:36 -0700579
580 # Don't yell about changes to whitelisted files...
Mike Frysinger011af942014-01-17 16:12:22 -0500581 whitelist = ('ChangeLog', 'Manifest', 'metadata.xml')
Mike Frysinger292b45d2014-11-25 01:17:10 -0500582 affected_path_objs = [x for x in affected_path_objs
583 if os.path.basename(FinalName(x)) not in whitelist]
584 if not affected_path_objs:
Doug Anderson42b8a052013-06-26 10:45:36 -0700585 return None
586
587 # If we've touched any file named with a -rN.ebuild then we'll say we're
588 # OK right away. See TODO above about enhancing this.
Mike Frysinger292b45d2014-11-25 01:17:10 -0500589 touched_revved_ebuild = any(re.search(r'-r\d*\.ebuild$', FinalName(x))
590 for x in affected_path_objs)
Doug Anderson42b8a052013-06-26 10:45:36 -0700591 if touched_revved_ebuild:
592 return None
593
Mike Frysinger292b45d2014-11-25 01:17:10 -0500594 # If we're creating new ebuilds from scratch, then we don't need an uprev.
595 # Find all the dirs that new ebuilds and ignore their files/.
596 ebuild_dirs = [os.path.dirname(FinalName(x)) + '/' for x in affected_path_objs
597 if FinalName(x).endswith('.ebuild') and x.status == 'A']
598 affected_path_objs = [obj for obj in affected_path_objs
599 if not any(FinalName(obj).startswith(x)
600 for x in ebuild_dirs)]
601 if not affected_path_objs:
602 return
603
Doug Anderson42b8a052013-06-26 10:45:36 -0700604 # We want to examine the current contents of all directories that are parents
605 # of files that were touched (up to the top of the project).
606 #
607 # ...note: we use the current directory contents even though it may have
608 # changed since the commit we're looking at. This is just a heuristic after
609 # all. Worst case we don't flag a missing revbump.
Mike Frysinger292b45d2014-11-25 01:17:10 -0500610 if project_top is None:
611 project_top = os.getcwd()
Doug Anderson42b8a052013-06-26 10:45:36 -0700612 dirs_to_check = set([project_top])
Mike Frysinger292b45d2014-11-25 01:17:10 -0500613 for obj in affected_path_objs:
614 path = os.path.join(project_top, os.path.dirname(FinalName(obj)))
Doug Anderson42b8a052013-06-26 10:45:36 -0700615 while os.path.exists(path) and not os.path.samefile(path, project_top):
616 dirs_to_check.add(path)
617 path = os.path.dirname(path)
618
619 # Look through each directory. If it's got an ebuild in it then we'll
620 # consider this as a case when we need a revbump.
Gwendal Grignoua3086c32014-12-09 11:17:22 -0800621 affected_paths = set(os.path.join(project_top, FinalName(x))
622 for x in affected_path_objs)
Doug Anderson42b8a052013-06-26 10:45:36 -0700623 for dir_path in dirs_to_check:
624 contents = os.listdir(dir_path)
625 ebuilds = [os.path.join(dir_path, path)
626 for path in contents if path.endswith('.ebuild')]
627 ebuilds_9999 = [path for path in ebuilds if path.endswith('-9999.ebuild')]
628
629 # If the -9999.ebuild file was touched the bot will uprev for us.
630 # ...we'll use a simple intersection here as a heuristic...
Mike Frysinger292b45d2014-11-25 01:17:10 -0500631 if set(ebuilds_9999) & affected_paths:
Doug Anderson42b8a052013-06-26 10:45:36 -0700632 continue
633
634 if ebuilds:
Mike Frysinger292b45d2014-11-25 01:17:10 -0500635 return HookFailure('Changelist probably needs a revbump of an ebuild, '
636 'or a -r1.ebuild symlink if this is a new ebuild:\n'
637 '%s' % dir_path)
Doug Anderson42b8a052013-06-26 10:45:36 -0700638
639 return None
640
641
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500642def _check_ebuild_eapi(project, commit):
643 """Make sure we have people use EAPI=4 or newer with custom ebuilds.
644
645 We want to get away from older EAPI's as it makes life confusing and they
646 have less builtin error checking.
647
648 Args:
Alex Deymo643ac4c2015-09-03 10:40:50 -0700649 project: The Project to look at
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500650 commit: The commit to look at
651
652 Returns:
653 A HookFailure or None.
654 """
655 # If this is the portage-stable overlay, then ignore the check. It's rare
Mike Frysingercd6adfc2014-02-06 01:03:56 -0500656 # that we're doing anything other than importing files from upstream, and
657 # we shouldn't be rewriting things fundamentally anyways.
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500658 whitelist = (
659 'chromiumos/overlays/portage-stable',
660 )
Alex Deymo643ac4c2015-09-03 10:40:50 -0700661 if project.name in whitelist:
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500662 return None
663
664 BAD_EAPIS = ('0', '1', '2', '3')
665
666 get_eapi = re.compile(r'^\s*EAPI=[\'"]?([^\'"]+)')
667
668 ebuilds_re = [r'\.ebuild$']
669 ebuilds = _filter_files(_get_affected_files(commit, relative=True),
670 ebuilds_re)
671 bad_ebuilds = []
672
673 for ebuild in ebuilds:
674 # If the ebuild does not specify an EAPI, it defaults to 0.
675 eapi = '0'
676
677 lines = _get_file_content(ebuild, commit).splitlines()
678 if len(lines) == 1:
679 # This is most likely a symlink, so skip it entirely.
680 continue
681
682 for line in lines:
683 m = get_eapi.match(line)
684 if m:
685 # Once we hit the first EAPI line in this ebuild, stop processing.
686 # The spec requires that there only be one and it be first, so
687 # checking all possible values is pointless. We also assume that
688 # it's "the" EAPI line and not something in the middle of a heredoc.
689 eapi = m.group(1)
690 break
691
692 if eapi in BAD_EAPIS:
693 bad_ebuilds.append((ebuild, eapi))
694
695 if bad_ebuilds:
696 # pylint: disable=C0301
697 url = 'http://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/upgrade-ebuild-eapis'
698 # pylint: enable=C0301
699 return HookFailure(
Mike Frysingercd6adfc2014-02-06 01:03:56 -0500700 'These ebuilds are using old EAPIs. If these are imported from\n'
701 'Gentoo, then you may ignore and upload once with the --no-verify\n'
702 'flag. Otherwise, please update to 4 or newer.\n'
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500703 '\t%s\n'
704 'See this guide for more details:\n%s\n' %
705 ('\n\t'.join(['%s: EAPI=%s' % x for x in bad_ebuilds]), url))
706
707
Mike Frysinger89bdb852014-02-01 05:26:26 -0500708def _check_ebuild_keywords(_project, commit):
Mike Frysingerc51ece72014-01-17 16:23:40 -0500709 """Make sure we use the new style KEYWORDS when possible in ebuilds.
710
711 If an ebuild generally does not care about the arch it is running on, then
712 ebuilds should flag it with one of:
713 KEYWORDS="*" # A stable ebuild.
714 KEYWORDS="~*" # An unstable ebuild.
715 KEYWORDS="-* ..." # Is known to only work on specific arches.
716
717 Args:
Alex Deymo643ac4c2015-09-03 10:40:50 -0700718 project: The Project to look at
Mike Frysingerc51ece72014-01-17 16:23:40 -0500719 commit: The commit to look at
720
721 Returns:
722 A HookFailure or None.
723 """
724 WHITELIST = set(('*', '-*', '~*'))
725
726 get_keywords = re.compile(r'^\s*KEYWORDS="(.*)"')
727
Mike Frysinger89bdb852014-02-01 05:26:26 -0500728 ebuilds_re = [r'\.ebuild$']
729 ebuilds = _filter_files(_get_affected_files(commit, relative=True),
730 ebuilds_re)
731
Mike Frysinger8d42d742014-09-22 15:50:21 -0400732 bad_ebuilds = []
Mike Frysingerc51ece72014-01-17 16:23:40 -0500733 for ebuild in ebuilds:
Mike Frysinger5c9e58d2014-09-09 03:32:50 -0400734 # We get the full content rather than a diff as the latter does not work
735 # on new files (like when adding new ebuilds).
736 lines = _get_file_content(ebuild, commit).splitlines()
737 for line in lines:
Mike Frysingerc51ece72014-01-17 16:23:40 -0500738 m = get_keywords.match(line)
739 if m:
740 keywords = set(m.group(1).split())
741 if not keywords or WHITELIST - keywords != WHITELIST:
742 continue
743
Mike Frysinger8d42d742014-09-22 15:50:21 -0400744 bad_ebuilds.append(ebuild)
745
746 if bad_ebuilds:
747 return HookFailure(
748 '%s\n'
749 'Please update KEYWORDS to use a glob:\n'
750 'If the ebuild should be marked stable (normal for non-9999 ebuilds):\n'
751 ' KEYWORDS="*"\n'
752 'If the ebuild should be marked unstable (normal for '
753 'cros-workon / 9999 ebuilds):\n'
754 ' KEYWORDS="~*"\n'
Mike Frysingerde8efea2015-05-17 03:42:26 -0400755 'If the ebuild needs to be marked for only specific arches, '
Mike Frysinger8d42d742014-09-22 15:50:21 -0400756 'then use -* like so:\n'
757 ' KEYWORDS="-* arm ..."\n' % '\n* '.join(bad_ebuilds))
Mike Frysingerc51ece72014-01-17 16:23:40 -0500758
759
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800760def _check_ebuild_licenses(_project, commit):
761 """Check if the LICENSE field in the ebuild is correct."""
762 affected_paths = _get_affected_files(commit)
763 touched_ebuilds = [x for x in affected_paths if x.endswith('.ebuild')]
764
765 # A list of licenses to ignore for now.
Yu-Ju Hongc0963fa2014-03-03 12:36:52 -0800766 LICENSES_IGNORE = ['||', '(', ')']
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800767
768 for ebuild in touched_ebuilds:
769 # Skip virutal packages.
770 if ebuild.split('/')[-3] == 'virtual':
771 continue
772
773 try:
Mike Frysinger2ec70ed2014-08-17 19:28:34 -0400774 license_types = licenses_lib.GetLicenseTypesFromEbuild(ebuild)
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800775 except ValueError as e:
776 return HookFailure(e.message, [ebuild])
777
778 # Also ignore licenses ending with '?'
779 for license_type in [x for x in license_types
780 if x not in LICENSES_IGNORE and not x.endswith('?')]:
781 try:
Mike Frysinger2ec70ed2014-08-17 19:28:34 -0400782 licenses_lib.Licensing.FindLicenseType(license_type)
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800783 except AssertionError as e:
784 return HookFailure(e.message, [ebuild])
785
786
Mike Frysingercd363c82014-02-01 05:20:18 -0500787def _check_ebuild_virtual_pv(project, commit):
788 """Enforce the virtual PV policies."""
789 # If this is the portage-stable overlay, then ignore the check.
790 # We want to import virtuals as-is from upstream Gentoo.
791 whitelist = (
792 'chromiumos/overlays/portage-stable',
793 )
Alex Deymo643ac4c2015-09-03 10:40:50 -0700794 if project.name in whitelist:
Mike Frysingercd363c82014-02-01 05:20:18 -0500795 return None
796
797 # We assume the repo name is the same as the dir name on disk.
798 # It would be dumb to not have them match though.
Alex Deymo643ac4c2015-09-03 10:40:50 -0700799 project_base = os.path.basename(project.name)
Mike Frysingercd363c82014-02-01 05:20:18 -0500800
801 is_variant = lambda x: x.startswith('overlay-variant-')
802 is_board = lambda x: x.startswith('overlay-')
803 is_private = lambda x: x.endswith('-private')
804
805 get_pv = re.compile(r'(.*?)virtual/([^/]+)/\2-([^/]*)\.ebuild$')
806
807 ebuilds_re = [r'\.ebuild$']
808 ebuilds = _filter_files(_get_affected_files(commit, relative=True),
809 ebuilds_re)
810 bad_ebuilds = []
811
812 for ebuild in ebuilds:
813 m = get_pv.match(ebuild)
814 if m:
815 overlay = m.group(1)
816 if not overlay or not is_board(overlay):
Alex Deymo643ac4c2015-09-03 10:40:50 -0700817 overlay = project_base
Mike Frysingercd363c82014-02-01 05:20:18 -0500818
819 pv = m.group(3).split('-', 1)[0]
820
821 if is_private(overlay):
822 want_pv = '3.5' if is_variant(overlay) else '3'
823 elif is_board(overlay):
824 want_pv = '2.5' if is_variant(overlay) else '2'
825 else:
826 want_pv = '1'
827
828 if pv != want_pv:
829 bad_ebuilds.append((ebuild, pv, want_pv))
830
831 if bad_ebuilds:
832 # pylint: disable=C0301
833 url = 'http://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/portage-build-faq#TOC-Virtuals-and-central-management'
834 # pylint: enable=C0301
835 return HookFailure(
836 'These virtuals have incorrect package versions (PVs). Please adjust:\n'
837 '\t%s\n'
838 'If this is an upstream Gentoo virtual, then you may ignore this\n'
839 'check (and re-run w/--no-verify). Otherwise, please see this\n'
840 'page for more details:\n%s\n' %
841 ('\n\t'.join(['%s:\n\t\tPV is %s but should be %s' % x
842 for x in bad_ebuilds]), url))
843
844
Daniel Erat9d203ff2015-02-17 10:12:21 -0700845def _check_portage_make_use_var(_project, commit):
846 """Verify that $USE is set correctly in make.conf and make.defaults."""
847 files = _filter_files(_get_affected_files(commit, relative=True),
848 [r'(^|/)make.(conf|defaults)$'])
849
850 errors = []
851 for path in files:
852 basename = os.path.basename(path)
853
854 # Has a USE= line already been encountered in this file?
855 saw_use = False
856
857 for i, line in enumerate(_get_file_content(path, commit).splitlines(), 1):
858 if not line.startswith('USE='):
859 continue
860
861 preserves_use = '${USE}' in line or '$USE' in line
862
863 if (basename == 'make.conf' or
864 (basename == 'make.defaults' and saw_use)) and not preserves_use:
865 errors.append('%s:%d: missing ${USE}' % (path, i))
866 elif basename == 'make.defaults' and not saw_use and preserves_use:
867 errors.append('%s:%d: ${USE} referenced in initial declaration' %
868 (path, i))
869
870 saw_use = True
871
872 if errors:
873 return HookFailure(
874 'One or more Portage make files appear to set USE incorrectly.\n'
875 '\n'
876 'All USE assignments in make.conf and all assignments after the\n'
877 'initial declaration in make.defaults should contain "${USE}" to\n'
878 'preserve previously-set flags.\n'
879 '\n'
880 'The initial USE declaration in make.defaults should not contain\n'
881 '"${USE}".\n',
882 errors)
883
884
Mike Frysingerae409522014-02-01 03:16:11 -0500885def _check_change_has_proper_changeid(_project, commit):
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700886 """Verify that Change-ID is present in last paragraph of commit message."""
Mike Frysinger4a22bf02014-10-31 13:53:35 -0400887 CHANGE_ID_RE = r'\nChange-Id: I[a-f0-9]+\n'
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700888 desc = _get_commit_desc(commit)
Mike Frysinger4a22bf02014-10-31 13:53:35 -0400889 m = re.search(CHANGE_ID_RE, desc)
Mike Frysinger02b88bd2014-11-21 00:29:38 -0500890 if not m:
Ryan Cui1562fb82011-05-09 11:01:31 -0700891 return HookFailure('Change-Id must be in last paragraph of description.')
892
Mike Frysinger02b88bd2014-11-21 00:29:38 -0500893 # Allow s-o-b tags to follow it, but only those.
894 end = desc[m.end():].strip().splitlines()
895 if [x for x in end if not x.startswith('Signed-off-by: ')]:
896 return HookFailure('Only "Signed-off-by:" tags may follow the Change-Id.')
897
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700898
Mike Frysinger36b2ebc2014-10-31 14:02:03 -0400899def _check_commit_message_style(_project, commit):
900 """Verify that the commit message matches our style.
901
902 We do not check for BUG=/TEST=/etc... lines here as that is handled by other
903 commit hooks.
904 """
905 desc = _get_commit_desc(commit)
906
907 # The first line should be by itself.
908 lines = desc.splitlines()
909 if len(lines) > 1 and lines[1]:
910 return HookFailure('The second line of the commit message must be blank.')
911
912 # The first line should be one sentence.
913 if '. ' in lines[0]:
914 return HookFailure('The first line cannot be more than one sentence.')
915
916 # The first line cannot be too long.
917 MAX_FIRST_LINE_LEN = 100
918 if len(lines[0]) > MAX_FIRST_LINE_LEN:
919 return HookFailure('The first line must be less than %i chars.' %
920 MAX_FIRST_LINE_LEN)
921
922
Alex Deymof5792ce2015-08-24 22:50:08 -0700923def _check_cros_license(_project, commit):
924 """Verifies the Chromium OS license/copyright header.
Ryan Cuiec4d6332011-05-02 14:15:25 -0700925
Mike Frysinger98638102014-08-28 00:15:08 -0400926 Should be following the spec:
927 http://dev.chromium.org/developers/coding-style#TOC-File-headers
928 """
929 # For older years, be a bit more flexible as our policy says leave them be.
930 LICENSE_HEADER = (
931 r'.* Copyright( \(c\))? 20[-0-9]{2,7} The Chromium OS Authors\. '
Mike Frysingerb81102f2014-11-21 00:33:35 -0500932 r'All rights reserved\.' r'\n'
Mike Frysinger98638102014-08-28 00:15:08 -0400933 r'.* Use of this source code is governed by a BSD-style license that can '
Mike Frysingerb81102f2014-11-21 00:33:35 -0500934 r'be\n'
Mike Frysinger98638102014-08-28 00:15:08 -0400935 r'.* found in the LICENSE file\.'
Mike Frysingerb81102f2014-11-21 00:33:35 -0500936 r'\n'
Mike Frysinger98638102014-08-28 00:15:08 -0400937 )
938 license_re = re.compile(LICENSE_HEADER, re.MULTILINE)
939
940 # For newer years, be stricter.
941 COPYRIGHT_LINE = (
942 r'.* Copyright \(c\) 20(1[5-9]|[2-9][0-9]) The Chromium OS Authors\. '
Mike Frysingerb81102f2014-11-21 00:33:35 -0500943 r'All rights reserved\.' r'\n'
Mike Frysinger98638102014-08-28 00:15:08 -0400944 )
945 copyright_re = re.compile(COPYRIGHT_LINE)
946
947 bad_files = []
948 bad_copyright_files = []
949 files = _filter_files(_get_affected_files(commit, relative=True),
950 COMMON_INCLUDED_PATHS,
951 COMMON_EXCLUDED_PATHS)
952
953 for f in files:
954 contents = _get_file_content(f, commit)
955 if not contents:
956 # Ignore empty files.
957 continue
958
959 if not license_re.search(contents):
960 bad_files.append(f)
961 elif copyright_re.search(contents):
962 bad_copyright_files.append(f)
963
964 if bad_files:
965 msg = '%s:\n%s\n%s' % (
966 'License must match', license_re.pattern,
967 'Found a bad header in these files:')
968 return HookFailure(msg, bad_files)
969
970 if bad_copyright_files:
971 msg = 'Do not use (c) in copyright headers in new files:'
972 return HookFailure(msg, bad_copyright_files)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700973
974
Alex Deymof5792ce2015-08-24 22:50:08 -0700975def _check_aosp_license(_project, commit):
976 """Verifies the AOSP license/copyright header.
977
978 AOSP uses the Apache2 License:
979 https://source.android.com/source/licenses.html
980 """
981 LICENSE_HEADER = (
982 r"""^[#/\*]*
983[#/\*]* ?Copyright( \([cC]\))? 20[-0-9]{2,7} The Android Open Source Project
984[#/\*]* ?
985[#/\*]* ?Licensed under the Apache License, Version 2.0 \(the "License"\);
986[#/\*]* ?you may not use this file except in compliance with the License\.
987[#/\*]* ?You may obtain a copy of the License at
988[#/\*]* ?
989[#/\*]* ? http://www\.apache\.org/licenses/LICENSE-2\.0
990[#/\*]* ?
991[#/\*]* ?Unless required by applicable law or agreed to in writing, software
992[#/\*]* ?distributed under the License is distributed on an "AS IS" BASIS,
993[#/\*]* ?WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or """
994 r"""implied\.
995[#/\*]* ?See the License for the specific language governing permissions and
996[#/\*]* ?limitations under the License\.
997[#/\*]*$
998"""
999 )
1000 license_re = re.compile(LICENSE_HEADER, re.MULTILINE)
1001
1002 files = _filter_files(_get_affected_files(commit, relative=True),
1003 COMMON_INCLUDED_PATHS,
1004 COMMON_EXCLUDED_PATHS)
1005
1006 bad_files = []
1007 for f in files:
1008 contents = _get_file_content(f, commit)
1009 if not contents:
1010 # Ignore empty files.
1011 continue
1012
1013 if not license_re.search(contents):
1014 bad_files.append(f)
1015
1016 if bad_files:
1017 msg = ('License must match:\n%s\nFound a bad header in these files:' %
1018 license_re.pattern)
1019 return HookFailure(msg, bad_files)
1020
1021
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001022def _check_layout_conf(_project, commit):
1023 """Verifies the metadata/layout.conf file."""
1024 repo_name = 'profiles/repo_name'
Mike Frysinger94a670c2014-09-19 12:46:26 -04001025 repo_names = []
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001026 layout_path = 'metadata/layout.conf'
Mike Frysinger94a670c2014-09-19 12:46:26 -04001027 layout_paths = []
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001028
Mike Frysinger94a670c2014-09-19 12:46:26 -04001029 # Handle multiple overlays in a single commit (like the public tree).
1030 for f in _get_affected_files(commit, relative=True):
1031 if f.endswith(repo_name):
1032 repo_names.append(f)
1033 elif f.endswith(layout_path):
1034 layout_paths.append(f)
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001035
1036 # Disallow new repos with the repo_name file.
Mike Frysinger94a670c2014-09-19 12:46:26 -04001037 if repo_names:
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001038 return HookFailure('%s: use "repo-name" in %s instead' %
Mike Frysinger94a670c2014-09-19 12:46:26 -04001039 (repo_names, layout_path))
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001040
Mike Frysinger94a670c2014-09-19 12:46:26 -04001041 # Gather all the errors in one pass so we show one full message.
1042 all_errors = {}
1043 for layout_path in layout_paths:
1044 all_errors[layout_path] = errors = []
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001045
Mike Frysinger94a670c2014-09-19 12:46:26 -04001046 # Make sure the config file is sorted.
1047 data = [x for x in _get_file_content(layout_path, commit).splitlines()
1048 if x and x[0] != '#']
1049 if sorted(data) != data:
1050 errors += ['keep lines sorted']
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001051
Mike Frysinger94a670c2014-09-19 12:46:26 -04001052 # Require people to set specific values all the time.
1053 settings = (
1054 # TODO: Enable this for everyone. http://crbug.com/408038
1055 #('fast caching', 'cache-format = md5-dict'),
1056 ('fast manifests', 'thin-manifests = true'),
Mike Frysingerd7734522015-02-26 16:12:43 -05001057 ('extra features', 'profile-formats = portage-2 profile-default-eapi'),
1058 ('newer eapi', 'profile_eapi_when_unspecified = 5-progress'),
Mike Frysinger94a670c2014-09-19 12:46:26 -04001059 )
1060 for reason, line in settings:
1061 if line not in data:
1062 errors += ['enable %s with: %s' % (reason, line)]
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001063
Mike Frysinger94a670c2014-09-19 12:46:26 -04001064 # Require one of these settings.
1065 if ('use-manifests = true' not in data and
1066 'use-manifests = strict' not in data):
1067 errors += ['enable file checking with: use-manifests = true']
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001068
Mike Frysinger94a670c2014-09-19 12:46:26 -04001069 # Require repo-name to be set.
Mike Frysinger324cf682014-09-22 15:52:50 -04001070 for line in data:
1071 if line.startswith('repo-name = '):
1072 break
1073 else:
Mike Frysinger94a670c2014-09-19 12:46:26 -04001074 errors += ['set the board name with: repo-name = $BOARD']
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001075
Mike Frysinger94a670c2014-09-19 12:46:26 -04001076 # Summarize all the errors we saw (if any).
1077 lines = ''
1078 for layout_path, errors in all_errors.items():
1079 if errors:
1080 lines += '\n\t- '.join(['\n* %s:' % layout_path] + errors)
1081 if lines:
1082 lines = 'See the portage(5) man page for layout.conf details' + lines + '\n'
1083 return HookFailure(lines)
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001084
1085
Ryan Cuiec4d6332011-05-02 14:15:25 -07001086# Project-specific hooks
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001087
Ryan Cui1562fb82011-05-09 11:01:31 -07001088
Mike Frysingerae409522014-02-01 03:16:11 -05001089def _run_checkpatch(_project, commit, options=()):
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001090 """Runs checkpatch.pl on the given project"""
1091 hooks_dir = _get_hooks_dir()
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001092 options = list(options)
1093 if commit == PRE_SUBMIT:
1094 # The --ignore option must be present and include 'MISSING_SIGN_OFF' in
1095 # this case.
1096 options.append('--ignore=MISSING_SIGN_OFF')
Filipe Brandenburger28d48d62015-10-07 09:48:54 -07001097 # Always ignore the check for the MAINTAINERS file. We do not track that
1098 # information on that file in our source trees, so let's suppress the
1099 # warning.
1100 options.append('--ignore=FILE_PATH_CHANGES')
Filipe Brandenburgerce978322015-10-09 10:04:15 -07001101 # Do not complain about the Change-Id: fields, since we use Gerrit.
1102 # Upstream does not want those lines (since they do not use Gerrit), but
1103 # we always do, so disable the check globally.
Daisuke Nojiri4844f892015-10-08 09:54:33 -07001104 options.append('--ignore=GERRIT_CHANGE_ID')
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001105 cmd = ['%s/checkpatch.pl' % hooks_dir] + options + ['-']
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001106 cmd_result = cros_build_lib.RunCommand(cmd=cmd,
1107 print_cmd=False,
1108 input=_get_patch(commit),
1109 stdout_to_pipe=True,
1110 combine_stdout_stderr=True,
1111 error_code_ok=True)
1112 if cmd_result.returncode:
1113 return HookFailure('checkpatch.pl errors/warnings\n\n' + cmd_result.output)
Ryan Cuiec4d6332011-05-02 14:15:25 -07001114
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001115
Mike Frysingerae409522014-02-01 03:16:11 -05001116def _kernel_configcheck(_project, commit):
Olof Johanssona96810f2012-09-04 16:20:03 -07001117 """Makes sure kernel config changes are not mixed with code changes"""
1118 files = _get_affected_files(commit)
1119 if not len(_filter_files(files, [r'chromeos/config'])) in [0, len(files)]:
1120 return HookFailure('Changes to chromeos/config/ and regular files must '
1121 'be in separate commits:\n%s' % '\n'.join(files))
Anton Staaf815d6852011-08-22 10:08:45 -07001122
Mike Frysingerae409522014-02-01 03:16:11 -05001123
1124def _run_json_check(_project, commit):
Dale Curtis2975c432011-05-03 17:25:20 -07001125 """Checks that all JSON files are syntactically valid."""
Dale Curtisa039cfd2011-05-04 12:01:05 -07001126 for f in _filter_files(_get_affected_files(commit), [r'.*\.json']):
Dale Curtis2975c432011-05-03 17:25:20 -07001127 try:
1128 json.load(open(f))
1129 except Exception, e:
Ryan Cui1562fb82011-05-09 11:01:31 -07001130 return HookFailure('Invalid JSON in %s: %s' % (f, e))
Dale Curtis2975c432011-05-03 17:25:20 -07001131
1132
Mike Frysingerae409522014-02-01 03:16:11 -05001133def _check_manifests(_project, commit):
Mike Frysinger52b537e2013-08-22 22:59:53 -04001134 """Make sure Manifest files only have DIST lines"""
1135 paths = []
1136
1137 for path in _get_affected_files(commit):
1138 if os.path.basename(path) != 'Manifest':
1139 continue
1140 if not os.path.exists(path):
1141 continue
1142
1143 with open(path, 'r') as f:
1144 for line in f.readlines():
1145 if not line.startswith('DIST '):
1146 paths.append(path)
1147 break
1148
1149 if paths:
1150 return HookFailure('Please remove lines that do not start with DIST:\n%s' %
1151 ('\n'.join(paths),))
1152
1153
Mike Frysingerae409522014-02-01 03:16:11 -05001154def _check_change_has_branch_field(_project, commit):
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001155 """Check for a non-empty 'BRANCH=' field in the commit message."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001156 if commit == PRE_SUBMIT:
1157 return
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001158 BRANCH_RE = r'\nBRANCH=\S+'
1159
1160 if not re.search(BRANCH_RE, _get_commit_desc(commit)):
1161 msg = ('Changelist description needs BRANCH field (after first line)\n'
1162 'E.g. BRANCH=none or BRANCH=link,snow')
1163 return HookFailure(msg)
1164
1165
Mike Frysingerae409522014-02-01 03:16:11 -05001166def _check_change_has_signoff_field(_project, commit):
Shawn Nematbakhsh51e16ac2014-01-28 15:31:07 -08001167 """Check for a non-empty 'Signed-off-by:' field in the commit message."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001168 if commit == PRE_SUBMIT:
1169 return
Shawn Nematbakhsh51e16ac2014-01-28 15:31:07 -08001170 SIGNOFF_RE = r'\nSigned-off-by: \S+'
1171
1172 if not re.search(SIGNOFF_RE, _get_commit_desc(commit)):
1173 msg = ('Changelist description needs Signed-off-by: field\n'
1174 'E.g. Signed-off-by: My Name <me@chromium.org>')
1175 return HookFailure(msg)
1176
1177
Jon Salz3ee59de2012-08-18 13:54:22 +08001178def _run_project_hook_script(script, project, commit):
1179 """Runs a project hook script.
1180
1181 The script is run with the following environment variables set:
1182 PRESUBMIT_PROJECT: The affected project
1183 PRESUBMIT_COMMIT: The affected commit
1184 PRESUBMIT_FILES: A newline-separated list of affected files
1185
1186 The script is considered to fail if the exit code is non-zero. It should
1187 write an error message to stdout.
1188 """
1189 env = dict(os.environ)
Alex Deymo643ac4c2015-09-03 10:40:50 -07001190 env['PRESUBMIT_PROJECT'] = project.name
Jon Salz3ee59de2012-08-18 13:54:22 +08001191 env['PRESUBMIT_COMMIT'] = commit
1192
1193 # Put affected files in an environment variable
1194 files = _get_affected_files(commit)
1195 env['PRESUBMIT_FILES'] = '\n'.join(files)
1196
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001197 cmd_result = cros_build_lib.RunCommand(cmd=script,
1198 env=env,
1199 shell=True,
1200 print_cmd=False,
1201 input=os.devnull,
1202 stdout_to_pipe=True,
1203 combine_stdout_stderr=True,
1204 error_code_ok=True)
1205 if cmd_result.returncode:
1206 stdout = cmd_result.output
Jon Salz7b618af2012-08-31 06:03:16 +08001207 if stdout:
1208 stdout = re.sub('(?m)^', ' ', stdout)
1209 return HookFailure('Hook script "%s" failed with code %d%s' %
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001210 (script, cmd_result.returncode,
Jon Salz3ee59de2012-08-18 13:54:22 +08001211 ':\n' + stdout if stdout else ''))
1212
1213
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001214def _check_project_prefix(_project, commit):
Mike Frysinger55f85b52014-12-18 14:45:21 -05001215 """Require the commit message have a project specific prefix as needed."""
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001216
1217 files = _get_affected_files(commit, relative=True)
1218 prefix = os.path.commonprefix(files)
1219 prefix = os.path.dirname(prefix)
1220
1221 # If there is no common prefix, the CL span multiple projects.
Daniel Erata350fd32014-09-29 14:02:34 -07001222 if not prefix:
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001223 return
1224
1225 project_name = prefix.split('/')[0]
Daniel Erata350fd32014-09-29 14:02:34 -07001226
1227 # The common files may all be within a subdirectory of the main project
1228 # directory, so walk up the tree until we find an alias file.
1229 # _get_affected_files() should return relative paths, but check against '/' to
1230 # ensure that this loop terminates even if it receives an absolute path.
1231 while prefix and prefix != '/':
1232 alias_file = os.path.join(prefix, '.project_alias')
1233
1234 # If an alias exists, use it.
1235 if os.path.isfile(alias_file):
1236 project_name = osutils.ReadFile(alias_file).strip()
1237
1238 prefix = os.path.dirname(prefix)
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001239
1240 if not _get_commit_desc(commit).startswith(project_name + ': '):
1241 return HookFailure('The commit title for changes affecting only %s'
1242 ' should start with \"%s: \"'
1243 % (project_name, project_name))
1244
1245
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001246# Base
1247
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001248# A list of hooks which are not project specific and check patch description
1249# (as opposed to patch body).
1250_PATCH_DESCRIPTION_HOOKS = [
Ryan Cui9b651632011-05-11 11:38:58 -07001251 _check_change_has_bug_field,
David Jamesc3b68b32013-04-03 09:17:03 -07001252 _check_change_has_valid_cq_depend,
Ryan Cui9b651632011-05-11 11:38:58 -07001253 _check_change_has_test_field,
1254 _check_change_has_proper_changeid,
Mike Frysinger36b2ebc2014-10-31 14:02:03 -04001255 _check_commit_message_style,
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001256]
1257
1258
1259# A list of hooks that are not project-specific
1260_COMMON_HOOKS = [
Mike Frysingerbf8b91c2014-02-01 02:50:27 -05001261 _check_ebuild_eapi,
Mike Frysinger89bdb852014-02-01 05:26:26 -05001262 _check_ebuild_keywords,
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -08001263 _check_ebuild_licenses,
Mike Frysingercd363c82014-02-01 05:20:18 -05001264 _check_ebuild_virtual_pv,
Daniel Erat9d203ff2015-02-17 10:12:21 -07001265 _check_for_uprev,
Rahul Chaudhry09f61372015-07-31 17:14:26 -07001266 _check_gofmt,
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001267 _check_layout_conf,
Alex Deymof5792ce2015-08-24 22:50:08 -07001268 _check_cros_license,
Daniel Erat9d203ff2015-02-17 10:12:21 -07001269 _check_no_long_lines,
1270 _check_no_stray_whitespace,
Ryan Cui9b651632011-05-11 11:38:58 -07001271 _check_no_tabs,
Daniel Erat9d203ff2015-02-17 10:12:21 -07001272 _check_portage_make_use_var,
Ryan Cui9b651632011-05-11 11:38:58 -07001273]
Ryan Cuiec4d6332011-05-02 14:15:25 -07001274
Ryan Cui1562fb82011-05-09 11:01:31 -07001275
Ryan Cui9b651632011-05-11 11:38:58 -07001276# A dictionary of project-specific hooks(callbacks), indexed by project name.
1277# dict[project] = [callback1, callback2]
1278_PROJECT_SPECIFIC_HOOKS = {
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001279 "chromiumos/platform2": [_check_project_prefix],
Mike Frysingeraf891292015-03-25 19:46:53 -04001280 "chromiumos/third_party/kernel": [_kernel_configcheck],
1281 "chromiumos/third_party/kernel-next": [_kernel_configcheck],
Ryan Cui9b651632011-05-11 11:38:58 -07001282}
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001283
Ryan Cui1562fb82011-05-09 11:01:31 -07001284
Ryan Cui9b651632011-05-11 11:38:58 -07001285# A dictionary of flags (keys) that can appear in the config file, and the hook
Mike Frysinger3554bc92015-03-11 04:59:21 -04001286# that the flag controls (value).
1287_HOOK_FLAGS = {
Mike Frysingera7642f52015-03-25 18:31:42 -04001288 'checkpatch_check': _run_checkpatch,
Ryan Cui9b651632011-05-11 11:38:58 -07001289 'stray_whitespace_check': _check_no_stray_whitespace,
Mike Frysingerff6c7d62015-03-24 13:49:46 -04001290 'json_check': _run_json_check,
Ryan Cui9b651632011-05-11 11:38:58 -07001291 'long_line_check': _check_no_long_lines,
Alex Deymof5792ce2015-08-24 22:50:08 -07001292 'cros_license_check': _check_cros_license,
1293 'aosp_license_check': _check_aosp_license,
Ryan Cui9b651632011-05-11 11:38:58 -07001294 'tab_check': _check_no_tabs,
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001295 'branch_check': _check_change_has_branch_field,
Shawn Nematbakhsh51e16ac2014-01-28 15:31:07 -08001296 'signoff_check': _check_change_has_signoff_field,
Josh Triplett0e8fc7f2014-04-23 16:00:00 -07001297 'bug_field_check': _check_change_has_bug_field,
1298 'test_field_check': _check_change_has_test_field,
Steve Fung49ec7e92015-03-23 16:07:12 -07001299 'manifest_check': _check_manifests,
Ryan Cui9b651632011-05-11 11:38:58 -07001300}
1301
1302
Mike Frysinger3554bc92015-03-11 04:59:21 -04001303def _get_override_hooks(config):
1304 """Returns a set of hooks controlled by the current project's config file.
Ryan Cui9b651632011-05-11 11:38:58 -07001305
1306 Expects to be called within the project root.
Jon Salz3ee59de2012-08-18 13:54:22 +08001307
1308 Args:
1309 config: A ConfigParser for the project's config file.
Ryan Cui9b651632011-05-11 11:38:58 -07001310 """
1311 SECTION = 'Hook Overrides'
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001312 SECTION_OPTIONS = 'Hook Overrides Options'
Jon Salz3ee59de2012-08-18 13:54:22 +08001313 if not config.has_section(SECTION):
Mike Frysinger3554bc92015-03-11 04:59:21 -04001314 return set(), set()
Ryan Cui9b651632011-05-11 11:38:58 -07001315
Mike Frysinger3554bc92015-03-11 04:59:21 -04001316 valid_keys = set(_HOOK_FLAGS.iterkeys())
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001317 hooks = _HOOK_FLAGS.copy()
Mike Frysinger3554bc92015-03-11 04:59:21 -04001318
1319 enable_flags = []
Ryan Cui9b651632011-05-11 11:38:58 -07001320 disable_flags = []
Jon Salz3ee59de2012-08-18 13:54:22 +08001321 for flag in config.options(SECTION):
Mike Frysinger3554bc92015-03-11 04:59:21 -04001322 if flag not in valid_keys:
1323 raise ValueError('Error: unknown key "%s" in hook section of "%s"' %
1324 (flag, _CONFIG_FILE))
1325
Ryan Cui9b651632011-05-11 11:38:58 -07001326 try:
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001327 enabled = config.getboolean(SECTION, flag)
Ryan Cui9b651632011-05-11 11:38:58 -07001328 except ValueError as e:
Mike Frysinger3554bc92015-03-11 04:59:21 -04001329 raise ValueError('Error: parsing flag "%s" in "%s" failed: %s' %
1330 (flag, _CONFIG_FILE, e))
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001331 if enabled:
1332 enable_flags.append(flag)
1333 else:
1334 disable_flags.append(flag)
Ryan Cui9b651632011-05-11 11:38:58 -07001335
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001336 # See if this hook has custom options.
1337 if enabled:
1338 try:
1339 options = config.get(SECTION_OPTIONS, flag)
1340 hooks[flag] = functools.partial(hooks[flag], options=options.split())
1341 except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
1342 pass
1343
1344 enabled_hooks = set(hooks[x] for x in enable_flags)
1345 disabled_hooks = set(hooks[x] for x in disable_flags)
Mike Frysinger3554bc92015-03-11 04:59:21 -04001346 return enabled_hooks, disabled_hooks
Ryan Cui9b651632011-05-11 11:38:58 -07001347
1348
Jon Salz3ee59de2012-08-18 13:54:22 +08001349def _get_project_hook_scripts(config):
1350 """Returns a list of project-specific hook scripts.
1351
1352 Args:
1353 config: A ConfigParser for the project's config file.
1354 """
1355 SECTION = 'Hook Scripts'
1356 if not config.has_section(SECTION):
1357 return []
1358
1359 hook_names_values = config.items(SECTION)
1360 hook_names_values.sort(key=lambda x: x[0])
1361 return [x[1] for x in hook_names_values]
1362
1363
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001364def _get_project_hooks(project, presubmit):
Ryan Cui9b651632011-05-11 11:38:58 -07001365 """Returns a list of hooks that need to be run for a project.
1366
1367 Expects to be called from within the project root.
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001368
1369 Args:
1370 project: A string, name of the project.
1371 presubmit: A Boolean, True if the check is run as a git pre-submit script.
Ryan Cui9b651632011-05-11 11:38:58 -07001372 """
Jon Salz3ee59de2012-08-18 13:54:22 +08001373 config = ConfigParser.RawConfigParser()
1374 try:
1375 config.read(_CONFIG_FILE)
1376 except ConfigParser.Error:
1377 # Just use an empty config file
1378 config = ConfigParser.RawConfigParser()
1379
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001380 if presubmit:
Filipe Brandenburgerf70d32c2015-10-09 13:35:45 -07001381 hooks = _COMMON_HOOKS
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001382 else:
Filipe Brandenburgerf70d32c2015-10-09 13:35:45 -07001383 hooks = _PATCH_DESCRIPTION_HOOKS + _COMMON_HOOKS
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001384
Mike Frysinger3554bc92015-03-11 04:59:21 -04001385 enabled_hooks, disabled_hooks = _get_override_hooks(config)
Filipe Brandenburgerf70d32c2015-10-09 13:35:45 -07001386 hooks = [hook for hook in hooks if hook not in disabled_hooks]
1387
1388 # If a list is both in _COMMON_HOOKS and also enabled explicitly through an
1389 # override, keep the override only. Note that the override may end up being
1390 # a functools.partial, in which case we need to extract the .func to compare
1391 # it to the common hooks.
1392 unwrapped_hooks = [getattr(hook, 'func', hook) for hook in enabled_hooks]
1393 hooks = [hook for hook in hooks if hook not in unwrapped_hooks]
1394
1395 hooks = list(enabled_hooks) + hooks
Ryan Cui9b651632011-05-11 11:38:58 -07001396
1397 if project in _PROJECT_SPECIFIC_HOOKS:
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001398 hooks.extend(hook for hook in _PROJECT_SPECIFIC_HOOKS[project]
1399 if hook not in disabled_hooks)
Ryan Cui9b651632011-05-11 11:38:58 -07001400
Jon Salz3ee59de2012-08-18 13:54:22 +08001401 for script in _get_project_hook_scripts(config):
1402 hooks.append(functools.partial(_run_project_hook_script, script))
1403
Ryan Cui9b651632011-05-11 11:38:58 -07001404 return hooks
1405
1406
Alex Deymo643ac4c2015-09-03 10:40:50 -07001407def _run_project_hooks(project_name, proj_dir=None,
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001408 commit_list=None, presubmit=False):
Ryan Cui1562fb82011-05-09 11:01:31 -07001409 """For each project run its project specific hook from the hooks dictionary.
1410
1411 Args:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001412 project_name: The name of project to run hooks for.
Doug Anderson44a644f2011-11-02 10:37:37 -07001413 proj_dir: If non-None, this is the directory the project is in. If None,
1414 we'll ask repo.
Doug Anderson14749562013-06-26 13:38:29 -07001415 commit_list: A list of commits to run hooks against. If None or empty list
1416 then we'll automatically get the list of commits that would be uploaded.
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001417 presubmit: A Boolean, True if the check is run as a git pre-submit script.
Ryan Cui1562fb82011-05-09 11:01:31 -07001418
1419 Returns:
1420 Boolean value of whether any errors were ecountered while running the hooks.
1421 """
Doug Anderson44a644f2011-11-02 10:37:37 -07001422 if proj_dir is None:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001423 proj_dirs = _run_command(
1424 ['repo', 'forall', project_name, '-c', 'pwd']).split()
David James2edd9002013-10-11 14:09:19 -07001425 if len(proj_dirs) == 0:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001426 print('%s cannot be found.' % project_name, file=sys.stderr)
David James2edd9002013-10-11 14:09:19 -07001427 print('Please specify a valid project.', file=sys.stderr)
1428 return True
1429 if len(proj_dirs) > 1:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001430 print('%s is associated with multiple directories.' % project_name,
David James2edd9002013-10-11 14:09:19 -07001431 file=sys.stderr)
1432 print('Please specify a directory to help disambiguate.', file=sys.stderr)
1433 return True
1434 proj_dir = proj_dirs[0]
Doug Anderson44a644f2011-11-02 10:37:37 -07001435
Ryan Cuiec4d6332011-05-02 14:15:25 -07001436 pwd = os.getcwd()
1437 # hooks assume they are run from the root of the project
1438 os.chdir(proj_dir)
1439
Alex Deymo643ac4c2015-09-03 10:40:50 -07001440 remote_branch = _run_command(['git', 'rev-parse', '--abbrev-ref',
1441 '--symbolic-full-name', '@{u}']).strip()
1442 if not remote_branch:
1443 print('Your project %s doesn\'t track any remote repo.' % project_name,
1444 file=sys.stderr)
1445 remote = None
1446 else:
1447 remote, _branch = remote_branch.split('/', 1)
1448
1449 project = Project(name=project_name, dir=proj_dir, remote=remote)
1450
Doug Anderson14749562013-06-26 13:38:29 -07001451 if not commit_list:
1452 try:
1453 commit_list = _get_commits()
1454 except VerifyException as e:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001455 PrintErrorForProject(project.name, HookFailure(str(e)))
Doug Anderson14749562013-06-26 13:38:29 -07001456 os.chdir(pwd)
1457 return True
Ryan Cuifa55df52011-05-06 11:16:55 -07001458
Alex Deymo643ac4c2015-09-03 10:40:50 -07001459 hooks = _get_project_hooks(project.name, presubmit)
Ryan Cui1562fb82011-05-09 11:01:31 -07001460 error_found = False
Ryan Cuifa55df52011-05-06 11:16:55 -07001461 for commit in commit_list:
Ryan Cui1562fb82011-05-09 11:01:31 -07001462 error_list = []
Ryan Cui9b651632011-05-11 11:38:58 -07001463 for hook in hooks:
Ryan Cui1562fb82011-05-09 11:01:31 -07001464 hook_error = hook(project, commit)
1465 if hook_error:
1466 error_list.append(hook_error)
1467 error_found = True
1468 if error_list:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001469 PrintErrorsForCommit(project.name, commit, _get_commit_desc(commit),
Ryan Cui1562fb82011-05-09 11:01:31 -07001470 error_list)
Don Garrettdba548a2011-05-05 15:17:14 -07001471
Ryan Cuiec4d6332011-05-02 14:15:25 -07001472 os.chdir(pwd)
Ryan Cui1562fb82011-05-09 11:01:31 -07001473 return error_found
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001474
Mike Frysingerae409522014-02-01 03:16:11 -05001475
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001476# Main
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -07001477
Ryan Cui1562fb82011-05-09 11:01:31 -07001478
Mike Frysingerae409522014-02-01 03:16:11 -05001479def main(project_list, worktree_list=None, **_kwargs):
Doug Anderson06456632012-01-05 11:02:14 -08001480 """Main function invoked directly by repo.
1481
1482 This function will exit directly upon error so that repo doesn't print some
1483 obscure error message.
1484
1485 Args:
1486 project_list: List of projects to run on.
David James2edd9002013-10-11 14:09:19 -07001487 worktree_list: A list of directories. It should be the same length as
1488 project_list, so that each entry in project_list matches with a directory
1489 in worktree_list. If None, we will attempt to calculate the directories
1490 automatically.
Doug Anderson06456632012-01-05 11:02:14 -08001491 kwargs: Leave this here for forward-compatibility.
1492 """
Ryan Cui1562fb82011-05-09 11:01:31 -07001493 found_error = False
David James2edd9002013-10-11 14:09:19 -07001494 if not worktree_list:
1495 worktree_list = [None] * len(project_list)
1496 for project, worktree in zip(project_list, worktree_list):
1497 if _run_project_hooks(project, proj_dir=worktree):
Ryan Cui1562fb82011-05-09 11:01:31 -07001498 found_error = True
1499
Mike Frysingerae409522014-02-01 03:16:11 -05001500 if found_error:
Ryan Cui1562fb82011-05-09 11:01:31 -07001501 msg = ('Preupload failed due to errors in project(s). HINTS:\n'
Ryan Cui9b651632011-05-11 11:38:58 -07001502 '- To disable some source style checks, and for other hints, see '
1503 '<checkout_dir>/src/repohooks/README\n'
1504 '- To upload only current project, run \'repo upload .\'')
Mike Frysinger09d6a3d2013-10-08 22:21:03 -04001505 print(msg, file=sys.stderr)
Don Garrettdba548a2011-05-05 15:17:14 -07001506 sys.exit(1)
Anush Elangovan63afad72011-03-23 00:41:27 -07001507
Ryan Cui1562fb82011-05-09 11:01:31 -07001508
Doug Anderson44a644f2011-11-02 10:37:37 -07001509def _identify_project(path):
1510 """Identify the repo project associated with the given path.
1511
1512 Returns:
1513 A string indicating what project is associated with the path passed in or
1514 a blank string upon failure.
1515 """
1516 return _run_command(['repo', 'forall', '.', '-c', 'echo ${REPO_PROJECT}'],
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001517 redirect_stderr=True, cwd=path).strip()
Doug Anderson44a644f2011-11-02 10:37:37 -07001518
1519
Mike Frysinger55f85b52014-12-18 14:45:21 -05001520def direct_main(argv):
Doug Anderson44a644f2011-11-02 10:37:37 -07001521 """Run hooks directly (outside of the context of repo).
1522
Doug Anderson44a644f2011-11-02 10:37:37 -07001523 Args:
Mike Frysinger55f85b52014-12-18 14:45:21 -05001524 argv: The command line args to process
Doug Anderson44a644f2011-11-02 10:37:37 -07001525
1526 Returns:
1527 0 if no pre-upload failures, 1 if failures.
1528
1529 Raises:
1530 BadInvocation: On some types of invocation errors.
1531 """
Mike Frysinger66142932014-12-18 14:55:57 -05001532 parser = commandline.ArgumentParser(description=__doc__)
1533 parser.add_argument('--dir', default=None,
1534 help='The directory that the project lives in. If not '
1535 'specified, use the git project root based on the cwd.')
1536 parser.add_argument('--project', default=None,
1537 help='The project repo path; this can affect how the '
1538 'hooks get run, since some hooks are project-specific. '
1539 'For chromite this is chromiumos/chromite. If not '
1540 'specified, the repo tool will be used to figure this '
1541 'out based on the dir.')
1542 parser.add_argument('--rerun-since', default=None,
1543 help='Rerun hooks on old commits since the given date. '
1544 'The date should match git log\'s concept of a date. '
1545 'e.g. 2012-06-20. This option is mutually exclusive '
1546 'with --pre-submit.')
1547 parser.add_argument('--pre-submit', action="store_true",
1548 help='Run the check against the pending commit. '
1549 'This option should be used at the \'git commit\' '
1550 'phase as opposed to \'repo upload\'. This option '
1551 'is mutually exclusive with --rerun-since.')
1552 parser.add_argument('commits', nargs='*',
1553 help='Check specific commits')
1554 opts = parser.parse_args(argv)
Doug Anderson44a644f2011-11-02 10:37:37 -07001555
Doug Anderson14749562013-06-26 13:38:29 -07001556 if opts.rerun_since:
Mike Frysinger66142932014-12-18 14:55:57 -05001557 if opts.commits:
Doug Anderson14749562013-06-26 13:38:29 -07001558 raise BadInvocation('Can\'t pass commits and use rerun-since: %s' %
Mike Frysinger66142932014-12-18 14:55:57 -05001559 ' '.join(opts.commits))
Doug Anderson14749562013-06-26 13:38:29 -07001560
1561 cmd = ['git', 'log', '--since="%s"' % opts.rerun_since, '--pretty=%H']
1562 all_commits = _run_command(cmd).splitlines()
1563 bot_commits = _run_command(cmd + ['--author=chrome-bot']).splitlines()
1564
1565 # Eliminate chrome-bot commits but keep ordering the same...
1566 bot_commits = set(bot_commits)
Mike Frysinger66142932014-12-18 14:55:57 -05001567 opts.commits = [c for c in all_commits if c not in bot_commits]
Doug Anderson14749562013-06-26 13:38:29 -07001568
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001569 if opts.pre_submit:
1570 raise BadInvocation('rerun-since and pre-submit can not be '
1571 'used together')
1572 if opts.pre_submit:
Mike Frysinger66142932014-12-18 14:55:57 -05001573 if opts.commits:
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001574 raise BadInvocation('Can\'t pass commits and use pre-submit: %s' %
Mike Frysinger66142932014-12-18 14:55:57 -05001575 ' '.join(opts.commits))
1576 opts.commits = [PRE_SUBMIT,]
Doug Anderson44a644f2011-11-02 10:37:37 -07001577
1578 # Check/normlaize git dir; if unspecified, we'll use the root of the git
1579 # project from CWD
1580 if opts.dir is None:
1581 git_dir = _run_command(['git', 'rev-parse', '--git-dir'],
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001582 redirect_stderr=True).strip()
Doug Anderson44a644f2011-11-02 10:37:37 -07001583 if not git_dir:
1584 raise BadInvocation('The current directory is not part of a git project.')
1585 opts.dir = os.path.dirname(os.path.abspath(git_dir))
1586 elif not os.path.isdir(opts.dir):
1587 raise BadInvocation('Invalid dir: %s' % opts.dir)
1588 elif not os.path.isdir(os.path.join(opts.dir, '.git')):
1589 raise BadInvocation('Not a git directory: %s' % opts.dir)
1590
1591 # Identify the project if it wasn't specified; this _requires_ the repo
1592 # tool to be installed and for the project to be part of a repo checkout.
1593 if not opts.project:
1594 opts.project = _identify_project(opts.dir)
1595 if not opts.project:
1596 raise BadInvocation("Repo couldn't identify the project of %s" % opts.dir)
1597
Doug Anderson14749562013-06-26 13:38:29 -07001598 found_error = _run_project_hooks(opts.project, proj_dir=opts.dir,
Mike Frysinger66142932014-12-18 14:55:57 -05001599 commit_list=opts.commits,
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001600 presubmit=opts.pre_submit)
Doug Anderson44a644f2011-11-02 10:37:37 -07001601 if found_error:
1602 return 1
1603 return 0
1604
1605
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -07001606if __name__ == '__main__':
Mike Frysinger55f85b52014-12-18 14:45:21 -05001607 sys.exit(direct_main(sys.argv[1:]))