blob: 5432d4010369650b98bbe7278ac89d3b001deee6 [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
Ryan Cui9b651632011-05-11 11:38:58 -070013import ConfigParser
Daniel Erate3ea3fc2015-02-13 15:27:52 -070014import fnmatch
Jon Salz3ee59de2012-08-18 13:54:22 +080015import functools
Dale Curtis2975c432011-05-03 17:25:20 -070016import json
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070017import os
Ryan Cuiec4d6332011-05-02 14:15:25 -070018import re
Mandeep Singh Bainesa7ffa4b2011-05-03 11:37:02 -070019import sys
Peter Ammon811f6702014-06-12 15:45:38 -070020import stat
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070021
Ryan Cui1562fb82011-05-09 11:01:31 -070022from errors import (VerifyException, HookFailure, PrintErrorForProject,
23 PrintErrorsForCommit)
Ryan Cuiec4d6332011-05-02 14:15:25 -070024
David Jamesc3b68b32013-04-03 09:17:03 -070025# If repo imports us, the __name__ will be __builtin__, and the wrapper will
26# be in $CHROMEOS_CHECKOUT/.repo/repo/main.py, so we need to go two directories
27# up. The same logic also happens to work if we're executed directly.
28if __name__ in ('__builtin__', '__main__'):
29 sys.path.insert(0, os.path.join(os.path.dirname(sys.argv[0]), '..', '..'))
30
Mike Frysinger66142932014-12-18 14:55:57 -050031from chromite.lib import commandline
Rahul Chaudhry0e515342015-08-07 12:00:43 -070032from chromite.lib import cros_build_lib
Mike Frysingerd3bd32c2014-11-24 23:34:29 -050033from chromite.lib import git
Daniel Erata350fd32014-09-29 14:02:34 -070034from chromite.lib import osutils
David Jamesc3b68b32013-04-03 09:17:03 -070035from chromite.lib import patch
Mike Frysinger2ec70ed2014-08-17 19:28:34 -040036from chromite.licensing import licenses_lib
David Jamesc3b68b32013-04-03 09:17:03 -070037
Vadim Bendebury2b62d742014-06-22 13:14:51 -070038PRE_SUBMIT = 'pre-submit'
Ryan Cuiec4d6332011-05-02 14:15:25 -070039
40COMMON_INCLUDED_PATHS = [
Mike Frysingerae409522014-02-01 03:16:11 -050041 # C++ and friends
42 r".*\.c$", r".*\.cc$", r".*\.cpp$", r".*\.h$", r".*\.m$", r".*\.mm$",
43 r".*\.inl$", r".*\.asm$", r".*\.hxx$", r".*\.hpp$", r".*\.s$", r".*\.S$",
44 # Scripts
45 r".*\.js$", r".*\.py$", r".*\.sh$", r".*\.rb$", r".*\.pl$", r".*\.pm$",
46 # No extension at all, note that ALL CAPS files are black listed in
47 # COMMON_EXCLUDED_LIST below.
48 r"(^|.*[\\\/])[^.]+$",
49 # Other
50 r".*\.java$", r".*\.mk$", r".*\.am$",
Ryan Cuiec4d6332011-05-02 14:15:25 -070051]
52
Ryan Cui1562fb82011-05-09 11:01:31 -070053
Ryan Cuiec4d6332011-05-02 14:15:25 -070054COMMON_EXCLUDED_PATHS = [
Daniel Erate3ea3fc2015-02-13 15:27:52 -070055 # Avoid doing source file checks for kernel.
Mike Frysingerae409522014-02-01 03:16:11 -050056 r"/src/third_party/kernel/",
57 r"/src/third_party/kernel-next/",
58 r"/src/third_party/ktop/",
59 r"/src/third_party/punybench/",
60 r".*\bexperimental[\\\/].*",
61 r".*\b[A-Z0-9_]{2,}$",
62 r".*[\\\/]debian[\\\/]rules$",
Daniel Erate3ea3fc2015-02-13 15:27:52 -070063
64 # For ebuild trees, ignore any caches and manifest data.
Mike Frysingerae409522014-02-01 03:16:11 -050065 r".*/Manifest$",
66 r".*/metadata/[^/]*cache[^/]*/[^/]+/[^/]+$",
Doug Anderson5bfb6792011-10-25 16:45:41 -070067
Daniel Erate3ea3fc2015-02-13 15:27:52 -070068 # Ignore profiles data (like overlay-tegra2/profiles).
Mike Frysinger94a670c2014-09-19 12:46:26 -040069 r"(^|.*/)overlay-.*/profiles/.*",
Mike Frysinger98638102014-08-28 00:15:08 -040070 r"^profiles/.*$",
71
Daniel Erate3ea3fc2015-02-13 15:27:52 -070072 # Ignore minified js and jquery.
Mike Frysingerae409522014-02-01 03:16:11 -050073 r".*\.min\.js",
74 r".*jquery.*\.js",
Mike Frysinger33a458d2014-03-03 17:00:51 -050075
76 # Ignore license files as the content is often taken verbatim.
Daniel Erate3ea3fc2015-02-13 15:27:52 -070077 r".*/licenses/.*",
Ryan Cuiec4d6332011-05-02 14:15:25 -070078]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070079
Ryan Cui1562fb82011-05-09 11:01:31 -070080
Ryan Cui9b651632011-05-11 11:38:58 -070081_CONFIG_FILE = 'PRESUBMIT.cfg'
82
83
Daniel Erate3ea3fc2015-02-13 15:27:52 -070084# File containing wildcards, one per line, matching files that should be
85# excluded from presubmit checks. Lines beginning with '#' are ignored.
86_IGNORE_FILE = '.presubmitignore'
87
88
Doug Anderson44a644f2011-11-02 10:37:37 -070089# Exceptions
90
91
92class BadInvocation(Exception):
93 """An Exception indicating a bad invocation of the program."""
94 pass
95
96
Ryan Cui1562fb82011-05-09 11:01:31 -070097# General Helpers
98
Sean Paulba01d402011-05-05 11:36:23 -040099
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700100# pylint: disable=redefined-builtin
101def _run_command(cmd, cwd=None, input=None,
102 redirect_stderr=False, combine_stdout_stderr=False):
Doug Anderson44a644f2011-11-02 10:37:37 -0700103 """Executes the passed in command and returns raw stdout output.
104
105 Args:
106 cmd: The command to run; should be a list of strings.
107 cwd: The directory to switch to for running the command.
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700108 input: The data to pipe into this command through stdin. If a file object
109 or file descriptor, stdin will be connected directly to that.
110 redirect_stderr: Redirect stderr away from console.
111 combine_stdout_stderr: Combines stdout and stderr streams into stdout.
Doug Anderson44a644f2011-11-02 10:37:37 -0700112
113 Returns:
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700114 The stdout from the process (discards stderr and returncode).
Doug Anderson44a644f2011-11-02 10:37:37 -0700115 """
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700116 return cros_build_lib.RunCommand(cmd=cmd,
117 cwd=cwd,
118 print_cmd=False,
119 input=input,
120 stdout_to_pipe=True,
121 redirect_stderr=redirect_stderr,
122 combine_stdout_stderr=combine_stdout_stderr,
123 error_code_ok=True).output
124# pylint: enable=redefined-builtin
Ryan Cui72834d12011-05-05 14:51:33 -0700125
Ryan Cui1562fb82011-05-09 11:01:31 -0700126
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700127def _get_hooks_dir():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700128 """Returns the absolute path to the repohooks directory."""
Doug Anderson44a644f2011-11-02 10:37:37 -0700129 if __name__ == '__main__':
130 # Works when file is run on its own (__file__ is defined)...
131 return os.path.abspath(os.path.dirname(__file__))
132 else:
133 # We need to do this when we're run through repo. Since repo executes
134 # us with execfile(), we don't get __file__ defined.
135 cmd = ['repo', 'forall', 'chromiumos/repohooks', '-c', 'pwd']
136 return _run_command(cmd).strip()
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700137
Ryan Cui1562fb82011-05-09 11:01:31 -0700138
Ryan Cuiec4d6332011-05-02 14:15:25 -0700139def _match_regex_list(subject, expressions):
140 """Try to match a list of regular expressions to a string.
141
142 Args:
143 subject: The string to match regexes on
144 expressions: A list of regular expressions to check for matches with.
145
146 Returns:
147 Whether the passed in subject matches any of the passed in regexes.
148 """
149 for expr in expressions:
Mike Frysingerae409522014-02-01 03:16:11 -0500150 if re.search(expr, subject):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700151 return True
152 return False
153
Ryan Cui1562fb82011-05-09 11:01:31 -0700154
Mike Frysingerae409522014-02-01 03:16:11 -0500155def _filter_files(files, include_list, exclude_list=()):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700156 """Filter out files based on the conditions passed in.
157
158 Args:
159 files: list of filepaths to filter
160 include_list: list of regex that when matched with a file path will cause it
161 to be added to the output list unless the file is also matched with a
162 regex in the exclude_list.
163 exclude_list: list of regex that when matched with a file will prevent it
164 from being added to the output list, even if it is also matched with a
165 regex in the include_list.
166
167 Returns:
168 A list of filepaths that contain files matched in the include_list and not
169 in the exclude_list.
170 """
171 filtered = []
172 for f in files:
173 if (_match_regex_list(f, include_list) and
174 not _match_regex_list(f, exclude_list)):
175 filtered.append(f)
176 return filtered
177
Ryan Cuiec4d6332011-05-02 14:15:25 -0700178
179# Git Helpers
Ryan Cui1562fb82011-05-09 11:01:31 -0700180
181
Ryan Cui4725d952011-05-05 15:41:19 -0700182def _get_upstream_branch():
183 """Returns the upstream tracking branch of the current branch.
184
185 Raises:
186 Error if there is no tracking branch
187 """
188 current_branch = _run_command(['git', 'symbolic-ref', 'HEAD']).strip()
189 current_branch = current_branch.replace('refs/heads/', '')
190 if not current_branch:
Ryan Cui1562fb82011-05-09 11:01:31 -0700191 raise VerifyException('Need to be on a tracking branch')
Ryan Cui4725d952011-05-05 15:41:19 -0700192
193 cfg_option = 'branch.' + current_branch + '.%s'
194 full_upstream = _run_command(['git', 'config', cfg_option % 'merge']).strip()
195 remote = _run_command(['git', 'config', cfg_option % 'remote']).strip()
196 if not remote or not full_upstream:
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 return full_upstream.replace('heads', 'remotes/' + remote)
200
Ryan Cui1562fb82011-05-09 11:01:31 -0700201
Che-Liang Chiou5ce2d7b2013-03-22 18:47:55 -0700202def _get_patch(commit):
203 """Returns the patch for this commit."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700204 if commit == PRE_SUBMIT:
205 return _run_command(['git', 'diff', '--cached', 'HEAD'])
206 else:
207 return _run_command(['git', 'format-patch', '--stdout', '-1', commit])
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700208
Ryan Cui1562fb82011-05-09 11:01:31 -0700209
Jon Salz98255932012-08-18 14:48:02 +0800210def _try_utf8_decode(data):
211 """Attempts to decode a string as UTF-8.
212
213 Returns:
214 The decoded Unicode object, or the original string if parsing fails.
215 """
216 try:
217 return unicode(data, 'utf-8', 'strict')
218 except UnicodeDecodeError:
219 return data
220
221
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500222def _get_file_content(path, commit):
223 """Returns the content of a file at a specific commit.
224
225 We can't rely on the file as it exists in the filesystem as people might be
226 uploading a series of changes which modifies the file multiple times.
227
228 Note: The "content" of a symlink is just the target. So if you're expecting
229 a full file, you should check that first. One way to detect is that the
230 content will not have any newlines.
231 """
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700232 if commit == PRE_SUBMIT:
233 return _run_command(['git', 'diff', 'HEAD', path])
234 else:
235 return _run_command(['git', 'show', '%s:%s' % (commit, path)])
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500236
237
Mike Frysingerae409522014-02-01 03:16:11 -0500238def _get_file_diff(path, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700239 """Returns a list of (linenum, lines) tuples that the commit touched."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700240 command = ['git', 'diff', '-p', '--pretty=format:', '--no-ext-diff']
241 if commit == PRE_SUBMIT:
242 command += ['HEAD', path]
243 else:
244 command += [commit, path]
245 output = _run_command(command)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700246
247 new_lines = []
248 line_num = 0
249 for line in output.splitlines():
250 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
251 if m:
252 line_num = int(m.groups(1)[0])
253 continue
254 if line.startswith('+') and not line.startswith('++'):
Jon Salz98255932012-08-18 14:48:02 +0800255 new_lines.append((line_num, _try_utf8_decode(line[1:])))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700256 if not line.startswith('-'):
257 line_num += 1
258 return new_lines
259
Ryan Cui1562fb82011-05-09 11:01:31 -0700260
Daniel Erate3ea3fc2015-02-13 15:27:52 -0700261def _get_ignore_wildcards(directory, cache):
262 """Get wildcards listed in a directory's _IGNORE_FILE.
263
264 Args:
265 directory: A string containing a directory path.
266 cache: A dictionary (opaque to caller) caching previously-read wildcards.
267
268 Returns:
269 A list of wildcards from _IGNORE_FILE or an empty list if _IGNORE_FILE
270 wasn't present.
271 """
272 # In the cache, keys are directories and values are lists of wildcards from
273 # _IGNORE_FILE within those directories (and empty if no file was present).
274 if directory not in cache:
275 wildcards = []
276 dotfile_path = os.path.join(directory, _IGNORE_FILE)
277 if os.path.exists(dotfile_path):
278 # TODO(derat): Consider using _get_file_content() to get the file as of
279 # this commit instead of the on-disk version. This may have a noticeable
280 # performance impact, as each call to _get_file_content() runs git.
281 with open(dotfile_path, 'r') as dotfile:
282 for line in dotfile.readlines():
283 line = line.strip()
284 if line.startswith('#'):
285 continue
286 if line.endswith('/'):
287 line += '*'
288 wildcards.append(line)
289 cache[directory] = wildcards
290
291 return cache[directory]
292
293
294def _path_is_ignored(path, cache):
295 """Check whether a path is ignored by _IGNORE_FILE.
296
297 Args:
298 path: A string containing a path.
299 cache: A dictionary (opaque to caller) caching previously-read wildcards.
300
301 Returns:
302 True if a file named _IGNORE_FILE in one of the passed-in path's parent
303 directories contains a wildcard matching the path.
304 """
305 # Skip ignore files.
306 if os.path.basename(path) == _IGNORE_FILE:
307 return True
308
309 path = os.path.abspath(path)
310 base = os.getcwd()
311
312 prefix = os.path.dirname(path)
313 while prefix.startswith(base):
314 rel_path = path[len(prefix) + 1:]
315 for wildcard in _get_ignore_wildcards(prefix, cache):
316 if fnmatch.fnmatch(rel_path, wildcard):
317 return True
318 prefix = os.path.dirname(prefix)
319
320 return False
321
322
Mike Frysinger292b45d2014-11-25 01:17:10 -0500323def _get_affected_files(commit, include_deletes=False, relative=False,
324 include_symlinks=False, include_adds=True,
Daniel Erate3ea3fc2015-02-13 15:27:52 -0700325 full_details=False, use_ignore_files=True):
Peter Ammon811f6702014-06-12 15:45:38 -0700326 """Returns list of file paths that were modified/added, excluding symlinks.
327
328 Args:
329 commit: The commit
330 include_deletes: If true, we'll include deleted files in the result
331 relative: Whether to return relative or full paths to files
Mike Frysinger292b45d2014-11-25 01:17:10 -0500332 include_symlinks: If true, we'll include symlinks in the result
333 include_adds: If true, we'll include new files in the result
334 full_details: If False, return filenames, else return structured results.
Daniel Erate3ea3fc2015-02-13 15:27:52 -0700335 use_ignore_files: Whether we ignore files matched by _IGNORE_FILE files.
Peter Ammon811f6702014-06-12 15:45:38 -0700336
337 Returns:
338 A list of modified/added (and perhaps deleted) files
339 """
Mike Frysinger292b45d2014-11-25 01:17:10 -0500340 if not relative and full_details:
341 raise ValueError('full_details only supports relative paths currently')
342
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700343 if commit == PRE_SUBMIT:
344 return _run_command(['git', 'diff-index', '--cached',
345 '--name-only', 'HEAD']).split()
Mike Frysingerd3bd32c2014-11-24 23:34:29 -0500346
347 path = os.getcwd()
348 files = git.RawDiff(path, '%s^!' % commit)
349
350 # Filter out symlinks.
Mike Frysinger292b45d2014-11-25 01:17:10 -0500351 if not include_symlinks:
352 files = [x for x in files if not stat.S_ISLNK(int(x.dst_mode, 8))]
Mike Frysingerd3bd32c2014-11-24 23:34:29 -0500353
354 if not include_deletes:
355 files = [x for x in files if x.status != 'D']
356
Mike Frysinger292b45d2014-11-25 01:17:10 -0500357 if not include_adds:
358 files = [x for x in files if x.status != 'A']
359
Daniel Erate3ea3fc2015-02-13 15:27:52 -0700360 if use_ignore_files:
361 cache = {}
362 is_ignored = lambda x: _path_is_ignored(x.dst_file or x.src_file, cache)
363 files = [x for x in files if not is_ignored(x)]
364
Mike Frysinger292b45d2014-11-25 01:17:10 -0500365 if full_details:
366 # Caller wants the raw objects to parse status/etc... themselves.
Mike Frysingerd3bd32c2014-11-24 23:34:29 -0500367 return files
368 else:
Mike Frysinger292b45d2014-11-25 01:17:10 -0500369 # Caller only cares about filenames.
370 files = [x.dst_file if x.dst_file else x.src_file for x in files]
371 if relative:
372 return files
373 else:
374 return [os.path.join(path, x) for x in files]
Peter Ammon811f6702014-06-12 15:45:38 -0700375
376
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700377def _get_commits():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700378 """Returns a list of commits for this review."""
Ryan Cui4725d952011-05-05 15:41:19 -0700379 cmd = ['git', 'log', '%s..' % _get_upstream_branch(), '--format=%H']
Ryan Cui72834d12011-05-05 14:51:33 -0700380 return _run_command(cmd).split()
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700381
Ryan Cui1562fb82011-05-09 11:01:31 -0700382
Ryan Cuiec4d6332011-05-02 14:15:25 -0700383def _get_commit_desc(commit):
384 """Returns the full commit message of a commit."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700385 if commit == PRE_SUBMIT:
386 return ''
Sean Paul23a2c582011-05-06 13:10:44 -0400387 return _run_command(['git', 'log', '--format=%s%n%n%b', commit + '^!'])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700388
389
390# Common Hooks
391
Ryan Cui1562fb82011-05-09 11:01:31 -0700392
Mike Frysingerae409522014-02-01 03:16:11 -0500393def _check_no_long_lines(_project, commit):
Mike Frysinger55f85b52014-12-18 14:45:21 -0500394 """Checks there are no lines longer than MAX_LEN in any of the text files."""
395
Ryan Cuiec4d6332011-05-02 14:15:25 -0700396 MAX_LEN = 80
Jon Salz98255932012-08-18 14:48:02 +0800397 SKIP_REGEXP = re.compile('|'.join([
398 r'https?://',
399 r'^#\s*(define|include|import|pragma|if|endif)\b']))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700400
401 errors = []
402 files = _filter_files(_get_affected_files(commit),
403 COMMON_INCLUDED_PATHS,
404 COMMON_EXCLUDED_PATHS)
405
406 for afile in files:
407 for line_num, line in _get_file_diff(afile, commit):
408 # Allow certain lines to exceed the maxlen rule.
Mike Frysingerae409522014-02-01 03:16:11 -0500409 if len(line) <= MAX_LEN or SKIP_REGEXP.search(line):
Jon Salz98255932012-08-18 14:48:02 +0800410 continue
411
412 errors.append('%s, line %s, %s chars' % (afile, line_num, len(line)))
413 if len(errors) == 5: # Just show the first 5 errors.
414 break
Ryan Cuiec4d6332011-05-02 14:15:25 -0700415
416 if errors:
417 msg = 'Found lines longer than %s characters (first 5 shown):' % MAX_LEN
Ryan Cui1562fb82011-05-09 11:01:31 -0700418 return HookFailure(msg, errors)
419
Ryan Cuiec4d6332011-05-02 14:15:25 -0700420
Mike Frysingerae409522014-02-01 03:16:11 -0500421def _check_no_stray_whitespace(_project, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700422 """Checks that there is no stray whitespace at source lines end."""
423 errors = []
424 files = _filter_files(_get_affected_files(commit),
Mike Frysingerae409522014-02-01 03:16:11 -0500425 COMMON_INCLUDED_PATHS,
426 COMMON_EXCLUDED_PATHS)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700427 for afile in files:
428 for line_num, line in _get_file_diff(afile, commit):
429 if line.rstrip() != line:
430 errors.append('%s, line %s' % (afile, line_num))
431 if errors:
Ryan Cui1562fb82011-05-09 11:01:31 -0700432 return HookFailure('Found line ending with white space in:', errors)
433
Ryan Cuiec4d6332011-05-02 14:15:25 -0700434
Mike Frysingerae409522014-02-01 03:16:11 -0500435def _check_no_tabs(_project, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700436 """Checks there are no unexpanded tabs."""
437 TAB_OK_PATHS = [
Ryan Cui31e0c172011-05-04 21:00:45 -0700438 r"/src/third_party/u-boot/",
Ryan Cuiec4d6332011-05-02 14:15:25 -0700439 r".*\.ebuild$",
440 r".*\.eclass$",
Elly Jones5ab34192011-11-15 14:57:06 -0500441 r".*/[M|m]akefile$",
442 r".*\.mk$"
Ryan Cuiec4d6332011-05-02 14:15:25 -0700443 ]
444
445 errors = []
446 files = _filter_files(_get_affected_files(commit),
447 COMMON_INCLUDED_PATHS,
448 COMMON_EXCLUDED_PATHS + TAB_OK_PATHS)
449
450 for afile in files:
451 for line_num, line in _get_file_diff(afile, commit):
452 if '\t' in line:
Mike Frysingerae409522014-02-01 03:16:11 -0500453 errors.append('%s, line %s' % (afile, line_num))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700454 if errors:
Ryan Cui1562fb82011-05-09 11:01:31 -0700455 return HookFailure('Found a tab character in:', errors)
456
Ryan Cuiec4d6332011-05-02 14:15:25 -0700457
Rahul Chaudhry09f61372015-07-31 17:14:26 -0700458def _check_gofmt(_project, commit):
459 """Checks that Go files are formatted with gofmt."""
460 errors = []
461 files = _filter_files(_get_affected_files(commit, relative=True),
462 [r'\.go$'])
463
464 for gofile in files:
465 contents = _get_file_content(gofile, commit)
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700466 output = _run_command(cmd=['gofmt', '-l'], input=contents,
467 combine_stdout_stderr=True)
Rahul Chaudhry09f61372015-07-31 17:14:26 -0700468 if output:
469 errors.append(gofile)
470 if errors:
471 return HookFailure('Files not formatted with gofmt:', errors)
472
473
Mike Frysingerae409522014-02-01 03:16:11 -0500474def _check_change_has_test_field(_project, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700475 """Check for a non-empty 'TEST=' field in the commit message."""
David McMahon8f6553e2011-06-10 15:46:36 -0700476 TEST_RE = r'\nTEST=\S+'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700477
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700478 if not re.search(TEST_RE, _get_commit_desc(commit)):
Ryan Cui1562fb82011-05-09 11:01:31 -0700479 msg = 'Changelist description needs TEST field (after first line)'
480 return HookFailure(msg)
481
Ryan Cuiec4d6332011-05-02 14:15:25 -0700482
Mike Frysingerae409522014-02-01 03:16:11 -0500483def _check_change_has_valid_cq_depend(_project, commit):
David Jamesc3b68b32013-04-03 09:17:03 -0700484 """Check for a correctly formatted CQ-DEPEND field in the commit message."""
485 msg = 'Changelist has invalid CQ-DEPEND target.'
486 example = 'Example: CQ-DEPEND=CL:1234, CL:2345'
487 try:
488 patch.GetPaladinDeps(_get_commit_desc(commit))
489 except ValueError as ex:
490 return HookFailure(msg, [example, str(ex)])
491
492
Mike Frysingerae409522014-02-01 03:16:11 -0500493def _check_change_has_bug_field(_project, commit):
David McMahon8f6553e2011-06-10 15:46:36 -0700494 """Check for a correctly formatted 'BUG=' field in the commit message."""
David James5c0073d2013-04-03 08:48:52 -0700495 OLD_BUG_RE = r'\nBUG=.*chromium-os'
496 if re.search(OLD_BUG_RE, _get_commit_desc(commit)):
497 msg = ('The chromium-os bug tracker is now deprecated. Please use\n'
498 'the chromium tracker in your BUG= line now.')
499 return HookFailure(msg)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700500
Stefan Sauerd74ad562015-03-10 10:14:28 +0100501 BUG_RE = r'\nBUG=([Nn]one|(chrome-os-partner|chromium|brillo|b):\d+)'
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700502 if not re.search(BUG_RE, _get_commit_desc(commit)):
David McMahon8f6553e2011-06-10 15:46:36 -0700503 msg = ('Changelist description needs BUG field (after first line):\n'
Christopher Wileyc92721b2015-01-26 13:07:39 -0800504 'BUG=brillo:9999 (for Brillo tracker)\n'
David James5c0073d2013-04-03 08:48:52 -0700505 'BUG=chromium:9999 (for public tracker)\n'
David McMahon8f6553e2011-06-10 15:46:36 -0700506 'BUG=chrome-os-partner:9999 (for partner tracker)\n'
Stefan Sauerd74ad562015-03-10 10:14:28 +0100507 'BUG=b:9999 (for buganizer)\n'
David McMahon8f6553e2011-06-10 15:46:36 -0700508 'BUG=None')
Ryan Cui1562fb82011-05-09 11:01:31 -0700509 return HookFailure(msg)
510
Ryan Cuiec4d6332011-05-02 14:15:25 -0700511
Mike Frysinger292b45d2014-11-25 01:17:10 -0500512def _check_for_uprev(project, commit, project_top=None):
Doug Anderson42b8a052013-06-26 10:45:36 -0700513 """Check that we're not missing a revbump of an ebuild in the given commit.
514
515 If the given commit touches files in a directory that has ebuilds somewhere
516 up the directory hierarchy, it's very likely that we need an ebuild revbump
517 in order for those changes to take effect.
518
519 It's not totally trivial to detect a revbump, so at least detect that an
520 ebuild with a revision number in it was touched. This should handle the
521 common case where we use a symlink to do the revbump.
522
523 TODO: it would be nice to enhance this hook to:
524 * Handle cases where people revbump with a slightly different syntax. I see
525 one ebuild (puppy) that revbumps with _pN. This is a false positive.
526 * Catches cases where people aren't using symlinks for revbumps. If they
527 edit a revisioned file directly (and are expected to rename it for revbump)
528 we'll miss that. Perhaps we could detect that the file touched is a
529 symlink?
530
531 If a project doesn't use symlinks we'll potentially miss a revbump, but we're
532 still better off than without this check.
533
534 Args:
535 project: The project to look at
536 commit: The commit to look at
Mike Frysinger292b45d2014-11-25 01:17:10 -0500537 project_top: Top dir to process commits in
Doug Anderson42b8a052013-06-26 10:45:36 -0700538
539 Returns:
540 A HookFailure or None.
541 """
Mike Frysinger011af942014-01-17 16:12:22 -0500542 # If this is the portage-stable overlay, then ignore the check. It's rare
543 # that we're doing anything other than importing files from upstream, so
544 # forcing a rev bump makes no sense.
545 whitelist = (
546 'chromiumos/overlays/portage-stable',
547 )
548 if project in whitelist:
549 return None
550
Mike Frysinger292b45d2014-11-25 01:17:10 -0500551 def FinalName(obj):
552 # If the file is being deleted, then the dst_file is not set.
553 if obj.dst_file is None:
554 return obj.src_file
555 else:
556 return obj.dst_file
557
558 affected_path_objs = _get_affected_files(
559 commit, include_deletes=True, include_symlinks=True, relative=True,
560 full_details=True)
Doug Anderson42b8a052013-06-26 10:45:36 -0700561
562 # Don't yell about changes to whitelisted files...
Mike Frysinger011af942014-01-17 16:12:22 -0500563 whitelist = ('ChangeLog', 'Manifest', 'metadata.xml')
Mike Frysinger292b45d2014-11-25 01:17:10 -0500564 affected_path_objs = [x for x in affected_path_objs
565 if os.path.basename(FinalName(x)) not in whitelist]
566 if not affected_path_objs:
Doug Anderson42b8a052013-06-26 10:45:36 -0700567 return None
568
569 # If we've touched any file named with a -rN.ebuild then we'll say we're
570 # OK right away. See TODO above about enhancing this.
Mike Frysinger292b45d2014-11-25 01:17:10 -0500571 touched_revved_ebuild = any(re.search(r'-r\d*\.ebuild$', FinalName(x))
572 for x in affected_path_objs)
Doug Anderson42b8a052013-06-26 10:45:36 -0700573 if touched_revved_ebuild:
574 return None
575
Mike Frysinger292b45d2014-11-25 01:17:10 -0500576 # If we're creating new ebuilds from scratch, then we don't need an uprev.
577 # Find all the dirs that new ebuilds and ignore their files/.
578 ebuild_dirs = [os.path.dirname(FinalName(x)) + '/' for x in affected_path_objs
579 if FinalName(x).endswith('.ebuild') and x.status == 'A']
580 affected_path_objs = [obj for obj in affected_path_objs
581 if not any(FinalName(obj).startswith(x)
582 for x in ebuild_dirs)]
583 if not affected_path_objs:
584 return
585
Doug Anderson42b8a052013-06-26 10:45:36 -0700586 # We want to examine the current contents of all directories that are parents
587 # of files that were touched (up to the top of the project).
588 #
589 # ...note: we use the current directory contents even though it may have
590 # changed since the commit we're looking at. This is just a heuristic after
591 # all. Worst case we don't flag a missing revbump.
Mike Frysinger292b45d2014-11-25 01:17:10 -0500592 if project_top is None:
593 project_top = os.getcwd()
Doug Anderson42b8a052013-06-26 10:45:36 -0700594 dirs_to_check = set([project_top])
Mike Frysinger292b45d2014-11-25 01:17:10 -0500595 for obj in affected_path_objs:
596 path = os.path.join(project_top, os.path.dirname(FinalName(obj)))
Doug Anderson42b8a052013-06-26 10:45:36 -0700597 while os.path.exists(path) and not os.path.samefile(path, project_top):
598 dirs_to_check.add(path)
599 path = os.path.dirname(path)
600
601 # Look through each directory. If it's got an ebuild in it then we'll
602 # consider this as a case when we need a revbump.
Gwendal Grignoua3086c32014-12-09 11:17:22 -0800603 affected_paths = set(os.path.join(project_top, FinalName(x))
604 for x in affected_path_objs)
Doug Anderson42b8a052013-06-26 10:45:36 -0700605 for dir_path in dirs_to_check:
606 contents = os.listdir(dir_path)
607 ebuilds = [os.path.join(dir_path, path)
608 for path in contents if path.endswith('.ebuild')]
609 ebuilds_9999 = [path for path in ebuilds if path.endswith('-9999.ebuild')]
610
611 # If the -9999.ebuild file was touched the bot will uprev for us.
612 # ...we'll use a simple intersection here as a heuristic...
Mike Frysinger292b45d2014-11-25 01:17:10 -0500613 if set(ebuilds_9999) & affected_paths:
Doug Anderson42b8a052013-06-26 10:45:36 -0700614 continue
615
616 if ebuilds:
Mike Frysinger292b45d2014-11-25 01:17:10 -0500617 return HookFailure('Changelist probably needs a revbump of an ebuild, '
618 'or a -r1.ebuild symlink if this is a new ebuild:\n'
619 '%s' % dir_path)
Doug Anderson42b8a052013-06-26 10:45:36 -0700620
621 return None
622
623
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500624def _check_ebuild_eapi(project, commit):
625 """Make sure we have people use EAPI=4 or newer with custom ebuilds.
626
627 We want to get away from older EAPI's as it makes life confusing and they
628 have less builtin error checking.
629
630 Args:
631 project: The project to look at
632 commit: The commit to look at
633
634 Returns:
635 A HookFailure or None.
636 """
637 # If this is the portage-stable overlay, then ignore the check. It's rare
Mike Frysingercd6adfc2014-02-06 01:03:56 -0500638 # that we're doing anything other than importing files from upstream, and
639 # we shouldn't be rewriting things fundamentally anyways.
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500640 whitelist = (
641 'chromiumos/overlays/portage-stable',
642 )
643 if project in whitelist:
644 return None
645
646 BAD_EAPIS = ('0', '1', '2', '3')
647
648 get_eapi = re.compile(r'^\s*EAPI=[\'"]?([^\'"]+)')
649
650 ebuilds_re = [r'\.ebuild$']
651 ebuilds = _filter_files(_get_affected_files(commit, relative=True),
652 ebuilds_re)
653 bad_ebuilds = []
654
655 for ebuild in ebuilds:
656 # If the ebuild does not specify an EAPI, it defaults to 0.
657 eapi = '0'
658
659 lines = _get_file_content(ebuild, commit).splitlines()
660 if len(lines) == 1:
661 # This is most likely a symlink, so skip it entirely.
662 continue
663
664 for line in lines:
665 m = get_eapi.match(line)
666 if m:
667 # Once we hit the first EAPI line in this ebuild, stop processing.
668 # The spec requires that there only be one and it be first, so
669 # checking all possible values is pointless. We also assume that
670 # it's "the" EAPI line and not something in the middle of a heredoc.
671 eapi = m.group(1)
672 break
673
674 if eapi in BAD_EAPIS:
675 bad_ebuilds.append((ebuild, eapi))
676
677 if bad_ebuilds:
678 # pylint: disable=C0301
679 url = 'http://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/upgrade-ebuild-eapis'
680 # pylint: enable=C0301
681 return HookFailure(
Mike Frysingercd6adfc2014-02-06 01:03:56 -0500682 'These ebuilds are using old EAPIs. If these are imported from\n'
683 'Gentoo, then you may ignore and upload once with the --no-verify\n'
684 'flag. Otherwise, please update to 4 or newer.\n'
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500685 '\t%s\n'
686 'See this guide for more details:\n%s\n' %
687 ('\n\t'.join(['%s: EAPI=%s' % x for x in bad_ebuilds]), url))
688
689
Mike Frysinger89bdb852014-02-01 05:26:26 -0500690def _check_ebuild_keywords(_project, commit):
Mike Frysingerc51ece72014-01-17 16:23:40 -0500691 """Make sure we use the new style KEYWORDS when possible in ebuilds.
692
693 If an ebuild generally does not care about the arch it is running on, then
694 ebuilds should flag it with one of:
695 KEYWORDS="*" # A stable ebuild.
696 KEYWORDS="~*" # An unstable ebuild.
697 KEYWORDS="-* ..." # Is known to only work on specific arches.
698
699 Args:
700 project: The project to look at
701 commit: The commit to look at
702
703 Returns:
704 A HookFailure or None.
705 """
706 WHITELIST = set(('*', '-*', '~*'))
707
708 get_keywords = re.compile(r'^\s*KEYWORDS="(.*)"')
709
Mike Frysinger89bdb852014-02-01 05:26:26 -0500710 ebuilds_re = [r'\.ebuild$']
711 ebuilds = _filter_files(_get_affected_files(commit, relative=True),
712 ebuilds_re)
713
Mike Frysinger8d42d742014-09-22 15:50:21 -0400714 bad_ebuilds = []
Mike Frysingerc51ece72014-01-17 16:23:40 -0500715 for ebuild in ebuilds:
Mike Frysinger5c9e58d2014-09-09 03:32:50 -0400716 # We get the full content rather than a diff as the latter does not work
717 # on new files (like when adding new ebuilds).
718 lines = _get_file_content(ebuild, commit).splitlines()
719 for line in lines:
Mike Frysingerc51ece72014-01-17 16:23:40 -0500720 m = get_keywords.match(line)
721 if m:
722 keywords = set(m.group(1).split())
723 if not keywords or WHITELIST - keywords != WHITELIST:
724 continue
725
Mike Frysinger8d42d742014-09-22 15:50:21 -0400726 bad_ebuilds.append(ebuild)
727
728 if bad_ebuilds:
729 return HookFailure(
730 '%s\n'
731 'Please update KEYWORDS to use a glob:\n'
732 'If the ebuild should be marked stable (normal for non-9999 ebuilds):\n'
733 ' KEYWORDS="*"\n'
734 'If the ebuild should be marked unstable (normal for '
735 'cros-workon / 9999 ebuilds):\n'
736 ' KEYWORDS="~*"\n'
Mike Frysingerde8efea2015-05-17 03:42:26 -0400737 'If the ebuild needs to be marked for only specific arches, '
Mike Frysinger8d42d742014-09-22 15:50:21 -0400738 'then use -* like so:\n'
739 ' KEYWORDS="-* arm ..."\n' % '\n* '.join(bad_ebuilds))
Mike Frysingerc51ece72014-01-17 16:23:40 -0500740
741
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800742def _check_ebuild_licenses(_project, commit):
743 """Check if the LICENSE field in the ebuild is correct."""
744 affected_paths = _get_affected_files(commit)
745 touched_ebuilds = [x for x in affected_paths if x.endswith('.ebuild')]
746
747 # A list of licenses to ignore for now.
Yu-Ju Hongc0963fa2014-03-03 12:36:52 -0800748 LICENSES_IGNORE = ['||', '(', ')']
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800749
750 for ebuild in touched_ebuilds:
751 # Skip virutal packages.
752 if ebuild.split('/')[-3] == 'virtual':
753 continue
754
755 try:
Mike Frysinger2ec70ed2014-08-17 19:28:34 -0400756 license_types = licenses_lib.GetLicenseTypesFromEbuild(ebuild)
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800757 except ValueError as e:
758 return HookFailure(e.message, [ebuild])
759
760 # Also ignore licenses ending with '?'
761 for license_type in [x for x in license_types
762 if x not in LICENSES_IGNORE and not x.endswith('?')]:
763 try:
Mike Frysinger2ec70ed2014-08-17 19:28:34 -0400764 licenses_lib.Licensing.FindLicenseType(license_type)
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800765 except AssertionError as e:
766 return HookFailure(e.message, [ebuild])
767
768
Mike Frysingercd363c82014-02-01 05:20:18 -0500769def _check_ebuild_virtual_pv(project, commit):
770 """Enforce the virtual PV policies."""
771 # If this is the portage-stable overlay, then ignore the check.
772 # We want to import virtuals as-is from upstream Gentoo.
773 whitelist = (
774 'chromiumos/overlays/portage-stable',
775 )
776 if project in whitelist:
777 return None
778
779 # We assume the repo name is the same as the dir name on disk.
780 # It would be dumb to not have them match though.
781 project = os.path.basename(project)
782
783 is_variant = lambda x: x.startswith('overlay-variant-')
784 is_board = lambda x: x.startswith('overlay-')
785 is_private = lambda x: x.endswith('-private')
786
787 get_pv = re.compile(r'(.*?)virtual/([^/]+)/\2-([^/]*)\.ebuild$')
788
789 ebuilds_re = [r'\.ebuild$']
790 ebuilds = _filter_files(_get_affected_files(commit, relative=True),
791 ebuilds_re)
792 bad_ebuilds = []
793
794 for ebuild in ebuilds:
795 m = get_pv.match(ebuild)
796 if m:
797 overlay = m.group(1)
798 if not overlay or not is_board(overlay):
799 overlay = project
800
801 pv = m.group(3).split('-', 1)[0]
802
803 if is_private(overlay):
804 want_pv = '3.5' if is_variant(overlay) else '3'
805 elif is_board(overlay):
806 want_pv = '2.5' if is_variant(overlay) else '2'
807 else:
808 want_pv = '1'
809
810 if pv != want_pv:
811 bad_ebuilds.append((ebuild, pv, want_pv))
812
813 if bad_ebuilds:
814 # pylint: disable=C0301
815 url = 'http://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/portage-build-faq#TOC-Virtuals-and-central-management'
816 # pylint: enable=C0301
817 return HookFailure(
818 'These virtuals have incorrect package versions (PVs). Please adjust:\n'
819 '\t%s\n'
820 'If this is an upstream Gentoo virtual, then you may ignore this\n'
821 'check (and re-run w/--no-verify). Otherwise, please see this\n'
822 'page for more details:\n%s\n' %
823 ('\n\t'.join(['%s:\n\t\tPV is %s but should be %s' % x
824 for x in bad_ebuilds]), url))
825
826
Daniel Erat9d203ff2015-02-17 10:12:21 -0700827def _check_portage_make_use_var(_project, commit):
828 """Verify that $USE is set correctly in make.conf and make.defaults."""
829 files = _filter_files(_get_affected_files(commit, relative=True),
830 [r'(^|/)make.(conf|defaults)$'])
831
832 errors = []
833 for path in files:
834 basename = os.path.basename(path)
835
836 # Has a USE= line already been encountered in this file?
837 saw_use = False
838
839 for i, line in enumerate(_get_file_content(path, commit).splitlines(), 1):
840 if not line.startswith('USE='):
841 continue
842
843 preserves_use = '${USE}' in line or '$USE' in line
844
845 if (basename == 'make.conf' or
846 (basename == 'make.defaults' and saw_use)) and not preserves_use:
847 errors.append('%s:%d: missing ${USE}' % (path, i))
848 elif basename == 'make.defaults' and not saw_use and preserves_use:
849 errors.append('%s:%d: ${USE} referenced in initial declaration' %
850 (path, i))
851
852 saw_use = True
853
854 if errors:
855 return HookFailure(
856 'One or more Portage make files appear to set USE incorrectly.\n'
857 '\n'
858 'All USE assignments in make.conf and all assignments after the\n'
859 'initial declaration in make.defaults should contain "${USE}" to\n'
860 'preserve previously-set flags.\n'
861 '\n'
862 'The initial USE declaration in make.defaults should not contain\n'
863 '"${USE}".\n',
864 errors)
865
866
Mike Frysingerae409522014-02-01 03:16:11 -0500867def _check_change_has_proper_changeid(_project, commit):
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700868 """Verify that Change-ID is present in last paragraph of commit message."""
Mike Frysinger4a22bf02014-10-31 13:53:35 -0400869 CHANGE_ID_RE = r'\nChange-Id: I[a-f0-9]+\n'
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700870 desc = _get_commit_desc(commit)
Mike Frysinger4a22bf02014-10-31 13:53:35 -0400871 m = re.search(CHANGE_ID_RE, desc)
Mike Frysinger02b88bd2014-11-21 00:29:38 -0500872 if not m:
Ryan Cui1562fb82011-05-09 11:01:31 -0700873 return HookFailure('Change-Id must be in last paragraph of description.')
874
Mike Frysinger02b88bd2014-11-21 00:29:38 -0500875 # Allow s-o-b tags to follow it, but only those.
876 end = desc[m.end():].strip().splitlines()
877 if [x for x in end if not x.startswith('Signed-off-by: ')]:
878 return HookFailure('Only "Signed-off-by:" tags may follow the Change-Id.')
879
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700880
Mike Frysinger36b2ebc2014-10-31 14:02:03 -0400881def _check_commit_message_style(_project, commit):
882 """Verify that the commit message matches our style.
883
884 We do not check for BUG=/TEST=/etc... lines here as that is handled by other
885 commit hooks.
886 """
887 desc = _get_commit_desc(commit)
888
889 # The first line should be by itself.
890 lines = desc.splitlines()
891 if len(lines) > 1 and lines[1]:
892 return HookFailure('The second line of the commit message must be blank.')
893
894 # The first line should be one sentence.
895 if '. ' in lines[0]:
896 return HookFailure('The first line cannot be more than one sentence.')
897
898 # The first line cannot be too long.
899 MAX_FIRST_LINE_LEN = 100
900 if len(lines[0]) > MAX_FIRST_LINE_LEN:
901 return HookFailure('The first line must be less than %i chars.' %
902 MAX_FIRST_LINE_LEN)
903
904
Alex Deymof5792ce2015-08-24 22:50:08 -0700905def _check_cros_license(_project, commit):
906 """Verifies the Chromium OS license/copyright header.
Ryan Cuiec4d6332011-05-02 14:15:25 -0700907
Mike Frysinger98638102014-08-28 00:15:08 -0400908 Should be following the spec:
909 http://dev.chromium.org/developers/coding-style#TOC-File-headers
910 """
911 # For older years, be a bit more flexible as our policy says leave them be.
912 LICENSE_HEADER = (
913 r'.* Copyright( \(c\))? 20[-0-9]{2,7} The Chromium OS Authors\. '
Mike Frysingerb81102f2014-11-21 00:33:35 -0500914 r'All rights reserved\.' r'\n'
Mike Frysinger98638102014-08-28 00:15:08 -0400915 r'.* Use of this source code is governed by a BSD-style license that can '
Mike Frysingerb81102f2014-11-21 00:33:35 -0500916 r'be\n'
Mike Frysinger98638102014-08-28 00:15:08 -0400917 r'.* found in the LICENSE file\.'
Mike Frysingerb81102f2014-11-21 00:33:35 -0500918 r'\n'
Mike Frysinger98638102014-08-28 00:15:08 -0400919 )
920 license_re = re.compile(LICENSE_HEADER, re.MULTILINE)
921
922 # For newer years, be stricter.
923 COPYRIGHT_LINE = (
924 r'.* Copyright \(c\) 20(1[5-9]|[2-9][0-9]) The Chromium OS Authors\. '
Mike Frysingerb81102f2014-11-21 00:33:35 -0500925 r'All rights reserved\.' r'\n'
Mike Frysinger98638102014-08-28 00:15:08 -0400926 )
927 copyright_re = re.compile(COPYRIGHT_LINE)
928
929 bad_files = []
930 bad_copyright_files = []
931 files = _filter_files(_get_affected_files(commit, relative=True),
932 COMMON_INCLUDED_PATHS,
933 COMMON_EXCLUDED_PATHS)
934
935 for f in files:
936 contents = _get_file_content(f, commit)
937 if not contents:
938 # Ignore empty files.
939 continue
940
941 if not license_re.search(contents):
942 bad_files.append(f)
943 elif copyright_re.search(contents):
944 bad_copyright_files.append(f)
945
946 if bad_files:
947 msg = '%s:\n%s\n%s' % (
948 'License must match', license_re.pattern,
949 'Found a bad header in these files:')
950 return HookFailure(msg, bad_files)
951
952 if bad_copyright_files:
953 msg = 'Do not use (c) in copyright headers in new files:'
954 return HookFailure(msg, bad_copyright_files)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700955
956
Alex Deymof5792ce2015-08-24 22:50:08 -0700957def _check_aosp_license(_project, commit):
958 """Verifies the AOSP license/copyright header.
959
960 AOSP uses the Apache2 License:
961 https://source.android.com/source/licenses.html
962 """
963 LICENSE_HEADER = (
964 r"""^[#/\*]*
965[#/\*]* ?Copyright( \([cC]\))? 20[-0-9]{2,7} The Android Open Source Project
966[#/\*]* ?
967[#/\*]* ?Licensed under the Apache License, Version 2.0 \(the "License"\);
968[#/\*]* ?you may not use this file except in compliance with the License\.
969[#/\*]* ?You may obtain a copy of the License at
970[#/\*]* ?
971[#/\*]* ? http://www\.apache\.org/licenses/LICENSE-2\.0
972[#/\*]* ?
973[#/\*]* ?Unless required by applicable law or agreed to in writing, software
974[#/\*]* ?distributed under the License is distributed on an "AS IS" BASIS,
975[#/\*]* ?WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or """
976 r"""implied\.
977[#/\*]* ?See the License for the specific language governing permissions and
978[#/\*]* ?limitations under the License\.
979[#/\*]*$
980"""
981 )
982 license_re = re.compile(LICENSE_HEADER, re.MULTILINE)
983
984 files = _filter_files(_get_affected_files(commit, relative=True),
985 COMMON_INCLUDED_PATHS,
986 COMMON_EXCLUDED_PATHS)
987
988 bad_files = []
989 for f in files:
990 contents = _get_file_content(f, commit)
991 if not contents:
992 # Ignore empty files.
993 continue
994
995 if not license_re.search(contents):
996 bad_files.append(f)
997
998 if bad_files:
999 msg = ('License must match:\n%s\nFound a bad header in these files:' %
1000 license_re.pattern)
1001 return HookFailure(msg, bad_files)
1002
1003
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001004def _check_layout_conf(_project, commit):
1005 """Verifies the metadata/layout.conf file."""
1006 repo_name = 'profiles/repo_name'
Mike Frysinger94a670c2014-09-19 12:46:26 -04001007 repo_names = []
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001008 layout_path = 'metadata/layout.conf'
Mike Frysinger94a670c2014-09-19 12:46:26 -04001009 layout_paths = []
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001010
Mike Frysinger94a670c2014-09-19 12:46:26 -04001011 # Handle multiple overlays in a single commit (like the public tree).
1012 for f in _get_affected_files(commit, relative=True):
1013 if f.endswith(repo_name):
1014 repo_names.append(f)
1015 elif f.endswith(layout_path):
1016 layout_paths.append(f)
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001017
1018 # Disallow new repos with the repo_name file.
Mike Frysinger94a670c2014-09-19 12:46:26 -04001019 if repo_names:
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001020 return HookFailure('%s: use "repo-name" in %s instead' %
Mike Frysinger94a670c2014-09-19 12:46:26 -04001021 (repo_names, layout_path))
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001022
Mike Frysinger94a670c2014-09-19 12:46:26 -04001023 # Gather all the errors in one pass so we show one full message.
1024 all_errors = {}
1025 for layout_path in layout_paths:
1026 all_errors[layout_path] = errors = []
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001027
Mike Frysinger94a670c2014-09-19 12:46:26 -04001028 # Make sure the config file is sorted.
1029 data = [x for x in _get_file_content(layout_path, commit).splitlines()
1030 if x and x[0] != '#']
1031 if sorted(data) != data:
1032 errors += ['keep lines sorted']
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001033
Mike Frysinger94a670c2014-09-19 12:46:26 -04001034 # Require people to set specific values all the time.
1035 settings = (
1036 # TODO: Enable this for everyone. http://crbug.com/408038
1037 #('fast caching', 'cache-format = md5-dict'),
1038 ('fast manifests', 'thin-manifests = true'),
Mike Frysingerd7734522015-02-26 16:12:43 -05001039 ('extra features', 'profile-formats = portage-2 profile-default-eapi'),
1040 ('newer eapi', 'profile_eapi_when_unspecified = 5-progress'),
Mike Frysinger94a670c2014-09-19 12:46:26 -04001041 )
1042 for reason, line in settings:
1043 if line not in data:
1044 errors += ['enable %s with: %s' % (reason, line)]
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001045
Mike Frysinger94a670c2014-09-19 12:46:26 -04001046 # Require one of these settings.
1047 if ('use-manifests = true' not in data and
1048 'use-manifests = strict' not in data):
1049 errors += ['enable file checking with: use-manifests = true']
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001050
Mike Frysinger94a670c2014-09-19 12:46:26 -04001051 # Require repo-name to be set.
Mike Frysinger324cf682014-09-22 15:52:50 -04001052 for line in data:
1053 if line.startswith('repo-name = '):
1054 break
1055 else:
Mike Frysinger94a670c2014-09-19 12:46:26 -04001056 errors += ['set the board name with: repo-name = $BOARD']
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001057
Mike Frysinger94a670c2014-09-19 12:46:26 -04001058 # Summarize all the errors we saw (if any).
1059 lines = ''
1060 for layout_path, errors in all_errors.items():
1061 if errors:
1062 lines += '\n\t- '.join(['\n* %s:' % layout_path] + errors)
1063 if lines:
1064 lines = 'See the portage(5) man page for layout.conf details' + lines + '\n'
1065 return HookFailure(lines)
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001066
1067
Ryan Cuiec4d6332011-05-02 14:15:25 -07001068# Project-specific hooks
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001069
Ryan Cui1562fb82011-05-09 11:01:31 -07001070
Mike Frysingerae409522014-02-01 03:16:11 -05001071def _run_checkpatch(_project, commit, options=()):
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001072 """Runs checkpatch.pl on the given project"""
1073 hooks_dir = _get_hooks_dir()
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001074 options = list(options)
1075 if commit == PRE_SUBMIT:
1076 # The --ignore option must be present and include 'MISSING_SIGN_OFF' in
1077 # this case.
1078 options.append('--ignore=MISSING_SIGN_OFF')
1079 cmd = ['%s/checkpatch.pl' % hooks_dir] + options + ['-']
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001080 cmd_result = cros_build_lib.RunCommand(cmd=cmd,
1081 print_cmd=False,
1082 input=_get_patch(commit),
1083 stdout_to_pipe=True,
1084 combine_stdout_stderr=True,
1085 error_code_ok=True)
1086 if cmd_result.returncode:
1087 return HookFailure('checkpatch.pl errors/warnings\n\n' + cmd_result.output)
Ryan Cuiec4d6332011-05-02 14:15:25 -07001088
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001089
Mike Frysingerae409522014-02-01 03:16:11 -05001090def _kernel_configcheck(_project, commit):
Olof Johanssona96810f2012-09-04 16:20:03 -07001091 """Makes sure kernel config changes are not mixed with code changes"""
1092 files = _get_affected_files(commit)
1093 if not len(_filter_files(files, [r'chromeos/config'])) in [0, len(files)]:
1094 return HookFailure('Changes to chromeos/config/ and regular files must '
1095 'be in separate commits:\n%s' % '\n'.join(files))
Anton Staaf815d6852011-08-22 10:08:45 -07001096
Mike Frysingerae409522014-02-01 03:16:11 -05001097
1098def _run_json_check(_project, commit):
Dale Curtis2975c432011-05-03 17:25:20 -07001099 """Checks that all JSON files are syntactically valid."""
Dale Curtisa039cfd2011-05-04 12:01:05 -07001100 for f in _filter_files(_get_affected_files(commit), [r'.*\.json']):
Dale Curtis2975c432011-05-03 17:25:20 -07001101 try:
1102 json.load(open(f))
1103 except Exception, e:
Ryan Cui1562fb82011-05-09 11:01:31 -07001104 return HookFailure('Invalid JSON in %s: %s' % (f, e))
Dale Curtis2975c432011-05-03 17:25:20 -07001105
1106
Mike Frysingerae409522014-02-01 03:16:11 -05001107def _check_manifests(_project, commit):
Mike Frysinger52b537e2013-08-22 22:59:53 -04001108 """Make sure Manifest files only have DIST lines"""
1109 paths = []
1110
1111 for path in _get_affected_files(commit):
1112 if os.path.basename(path) != 'Manifest':
1113 continue
1114 if not os.path.exists(path):
1115 continue
1116
1117 with open(path, 'r') as f:
1118 for line in f.readlines():
1119 if not line.startswith('DIST '):
1120 paths.append(path)
1121 break
1122
1123 if paths:
1124 return HookFailure('Please remove lines that do not start with DIST:\n%s' %
1125 ('\n'.join(paths),))
1126
1127
Mike Frysingerae409522014-02-01 03:16:11 -05001128def _check_change_has_branch_field(_project, commit):
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001129 """Check for a non-empty 'BRANCH=' field in the commit message."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001130 if commit == PRE_SUBMIT:
1131 return
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001132 BRANCH_RE = r'\nBRANCH=\S+'
1133
1134 if not re.search(BRANCH_RE, _get_commit_desc(commit)):
1135 msg = ('Changelist description needs BRANCH field (after first line)\n'
1136 'E.g. BRANCH=none or BRANCH=link,snow')
1137 return HookFailure(msg)
1138
1139
Mike Frysingerae409522014-02-01 03:16:11 -05001140def _check_change_has_signoff_field(_project, commit):
Shawn Nematbakhsh51e16ac2014-01-28 15:31:07 -08001141 """Check for a non-empty 'Signed-off-by:' field in the commit message."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001142 if commit == PRE_SUBMIT:
1143 return
Shawn Nematbakhsh51e16ac2014-01-28 15:31:07 -08001144 SIGNOFF_RE = r'\nSigned-off-by: \S+'
1145
1146 if not re.search(SIGNOFF_RE, _get_commit_desc(commit)):
1147 msg = ('Changelist description needs Signed-off-by: field\n'
1148 'E.g. Signed-off-by: My Name <me@chromium.org>')
1149 return HookFailure(msg)
1150
1151
Jon Salz3ee59de2012-08-18 13:54:22 +08001152def _run_project_hook_script(script, project, commit):
1153 """Runs a project hook script.
1154
1155 The script is run with the following environment variables set:
1156 PRESUBMIT_PROJECT: The affected project
1157 PRESUBMIT_COMMIT: The affected commit
1158 PRESUBMIT_FILES: A newline-separated list of affected files
1159
1160 The script is considered to fail if the exit code is non-zero. It should
1161 write an error message to stdout.
1162 """
1163 env = dict(os.environ)
1164 env['PRESUBMIT_PROJECT'] = project
1165 env['PRESUBMIT_COMMIT'] = commit
1166
1167 # Put affected files in an environment variable
1168 files = _get_affected_files(commit)
1169 env['PRESUBMIT_FILES'] = '\n'.join(files)
1170
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001171 cmd_result = cros_build_lib.RunCommand(cmd=script,
1172 env=env,
1173 shell=True,
1174 print_cmd=False,
1175 input=os.devnull,
1176 stdout_to_pipe=True,
1177 combine_stdout_stderr=True,
1178 error_code_ok=True)
1179 if cmd_result.returncode:
1180 stdout = cmd_result.output
Jon Salz7b618af2012-08-31 06:03:16 +08001181 if stdout:
1182 stdout = re.sub('(?m)^', ' ', stdout)
1183 return HookFailure('Hook script "%s" failed with code %d%s' %
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001184 (script, cmd_result.returncode,
Jon Salz3ee59de2012-08-18 13:54:22 +08001185 ':\n' + stdout if stdout else ''))
1186
1187
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001188def _check_project_prefix(_project, commit):
Mike Frysinger55f85b52014-12-18 14:45:21 -05001189 """Require the commit message have a project specific prefix as needed."""
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001190
1191 files = _get_affected_files(commit, relative=True)
1192 prefix = os.path.commonprefix(files)
1193 prefix = os.path.dirname(prefix)
1194
1195 # If there is no common prefix, the CL span multiple projects.
Daniel Erata350fd32014-09-29 14:02:34 -07001196 if not prefix:
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001197 return
1198
1199 project_name = prefix.split('/')[0]
Daniel Erata350fd32014-09-29 14:02:34 -07001200
1201 # The common files may all be within a subdirectory of the main project
1202 # directory, so walk up the tree until we find an alias file.
1203 # _get_affected_files() should return relative paths, but check against '/' to
1204 # ensure that this loop terminates even if it receives an absolute path.
1205 while prefix and prefix != '/':
1206 alias_file = os.path.join(prefix, '.project_alias')
1207
1208 # If an alias exists, use it.
1209 if os.path.isfile(alias_file):
1210 project_name = osutils.ReadFile(alias_file).strip()
1211
1212 prefix = os.path.dirname(prefix)
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001213
1214 if not _get_commit_desc(commit).startswith(project_name + ': '):
1215 return HookFailure('The commit title for changes affecting only %s'
1216 ' should start with \"%s: \"'
1217 % (project_name, project_name))
1218
1219
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001220# Base
1221
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001222# A list of hooks which are not project specific and check patch description
1223# (as opposed to patch body).
1224_PATCH_DESCRIPTION_HOOKS = [
Ryan Cui9b651632011-05-11 11:38:58 -07001225 _check_change_has_bug_field,
David Jamesc3b68b32013-04-03 09:17:03 -07001226 _check_change_has_valid_cq_depend,
Ryan Cui9b651632011-05-11 11:38:58 -07001227 _check_change_has_test_field,
1228 _check_change_has_proper_changeid,
Mike Frysinger36b2ebc2014-10-31 14:02:03 -04001229 _check_commit_message_style,
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001230]
1231
1232
1233# A list of hooks that are not project-specific
1234_COMMON_HOOKS = [
Mike Frysingerbf8b91c2014-02-01 02:50:27 -05001235 _check_ebuild_eapi,
Mike Frysinger89bdb852014-02-01 05:26:26 -05001236 _check_ebuild_keywords,
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -08001237 _check_ebuild_licenses,
Mike Frysingercd363c82014-02-01 05:20:18 -05001238 _check_ebuild_virtual_pv,
Daniel Erat9d203ff2015-02-17 10:12:21 -07001239 _check_for_uprev,
Rahul Chaudhry09f61372015-07-31 17:14:26 -07001240 _check_gofmt,
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001241 _check_layout_conf,
Alex Deymof5792ce2015-08-24 22:50:08 -07001242 _check_cros_license,
Daniel Erat9d203ff2015-02-17 10:12:21 -07001243 _check_no_long_lines,
1244 _check_no_stray_whitespace,
Ryan Cui9b651632011-05-11 11:38:58 -07001245 _check_no_tabs,
Daniel Erat9d203ff2015-02-17 10:12:21 -07001246 _check_portage_make_use_var,
Ryan Cui9b651632011-05-11 11:38:58 -07001247]
Ryan Cuiec4d6332011-05-02 14:15:25 -07001248
Ryan Cui1562fb82011-05-09 11:01:31 -07001249
Ryan Cui9b651632011-05-11 11:38:58 -07001250# A dictionary of project-specific hooks(callbacks), indexed by project name.
1251# dict[project] = [callback1, callback2]
1252_PROJECT_SPECIFIC_HOOKS = {
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001253 "chromiumos/platform2": [_check_project_prefix],
Mike Frysingeraf891292015-03-25 19:46:53 -04001254 "chromiumos/third_party/kernel": [_kernel_configcheck],
1255 "chromiumos/third_party/kernel-next": [_kernel_configcheck],
Ryan Cui9b651632011-05-11 11:38:58 -07001256}
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001257
Ryan Cui1562fb82011-05-09 11:01:31 -07001258
Ryan Cui9b651632011-05-11 11:38:58 -07001259# A dictionary of flags (keys) that can appear in the config file, and the hook
Mike Frysinger3554bc92015-03-11 04:59:21 -04001260# that the flag controls (value).
1261_HOOK_FLAGS = {
Mike Frysingera7642f52015-03-25 18:31:42 -04001262 'checkpatch_check': _run_checkpatch,
Ryan Cui9b651632011-05-11 11:38:58 -07001263 'stray_whitespace_check': _check_no_stray_whitespace,
Mike Frysingerff6c7d62015-03-24 13:49:46 -04001264 'json_check': _run_json_check,
Ryan Cui9b651632011-05-11 11:38:58 -07001265 'long_line_check': _check_no_long_lines,
Alex Deymof5792ce2015-08-24 22:50:08 -07001266 'cros_license_check': _check_cros_license,
1267 'aosp_license_check': _check_aosp_license,
Ryan Cui9b651632011-05-11 11:38:58 -07001268 'tab_check': _check_no_tabs,
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001269 'branch_check': _check_change_has_branch_field,
Shawn Nematbakhsh51e16ac2014-01-28 15:31:07 -08001270 'signoff_check': _check_change_has_signoff_field,
Josh Triplett0e8fc7f2014-04-23 16:00:00 -07001271 'bug_field_check': _check_change_has_bug_field,
1272 'test_field_check': _check_change_has_test_field,
Steve Fung49ec7e92015-03-23 16:07:12 -07001273 'manifest_check': _check_manifests,
Ryan Cui9b651632011-05-11 11:38:58 -07001274}
1275
1276
Mike Frysinger3554bc92015-03-11 04:59:21 -04001277def _get_override_hooks(config):
1278 """Returns a set of hooks controlled by the current project's config file.
Ryan Cui9b651632011-05-11 11:38:58 -07001279
1280 Expects to be called within the project root.
Jon Salz3ee59de2012-08-18 13:54:22 +08001281
1282 Args:
1283 config: A ConfigParser for the project's config file.
Ryan Cui9b651632011-05-11 11:38:58 -07001284 """
1285 SECTION = 'Hook Overrides'
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001286 SECTION_OPTIONS = 'Hook Overrides Options'
Jon Salz3ee59de2012-08-18 13:54:22 +08001287 if not config.has_section(SECTION):
Mike Frysinger3554bc92015-03-11 04:59:21 -04001288 return set(), set()
Ryan Cui9b651632011-05-11 11:38:58 -07001289
Mike Frysinger3554bc92015-03-11 04:59:21 -04001290 valid_keys = set(_HOOK_FLAGS.iterkeys())
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001291 hooks = _HOOK_FLAGS.copy()
Mike Frysinger3554bc92015-03-11 04:59:21 -04001292
1293 enable_flags = []
Ryan Cui9b651632011-05-11 11:38:58 -07001294 disable_flags = []
Jon Salz3ee59de2012-08-18 13:54:22 +08001295 for flag in config.options(SECTION):
Mike Frysinger3554bc92015-03-11 04:59:21 -04001296 if flag not in valid_keys:
1297 raise ValueError('Error: unknown key "%s" in hook section of "%s"' %
1298 (flag, _CONFIG_FILE))
1299
Ryan Cui9b651632011-05-11 11:38:58 -07001300 try:
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001301 enabled = config.getboolean(SECTION, flag)
Ryan Cui9b651632011-05-11 11:38:58 -07001302 except ValueError as e:
Mike Frysinger3554bc92015-03-11 04:59:21 -04001303 raise ValueError('Error: parsing flag "%s" in "%s" failed: %s' %
1304 (flag, _CONFIG_FILE, e))
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001305 if enabled:
1306 enable_flags.append(flag)
1307 else:
1308 disable_flags.append(flag)
Ryan Cui9b651632011-05-11 11:38:58 -07001309
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001310 # See if this hook has custom options.
1311 if enabled:
1312 try:
1313 options = config.get(SECTION_OPTIONS, flag)
1314 hooks[flag] = functools.partial(hooks[flag], options=options.split())
1315 except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
1316 pass
1317
1318 enabled_hooks = set(hooks[x] for x in enable_flags)
1319 disabled_hooks = set(hooks[x] for x in disable_flags)
Mike Frysinger3554bc92015-03-11 04:59:21 -04001320 return enabled_hooks, disabled_hooks
Ryan Cui9b651632011-05-11 11:38:58 -07001321
1322
Jon Salz3ee59de2012-08-18 13:54:22 +08001323def _get_project_hook_scripts(config):
1324 """Returns a list of project-specific hook scripts.
1325
1326 Args:
1327 config: A ConfigParser for the project's config file.
1328 """
1329 SECTION = 'Hook Scripts'
1330 if not config.has_section(SECTION):
1331 return []
1332
1333 hook_names_values = config.items(SECTION)
1334 hook_names_values.sort(key=lambda x: x[0])
1335 return [x[1] for x in hook_names_values]
1336
1337
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001338def _get_project_hooks(project, presubmit):
Ryan Cui9b651632011-05-11 11:38:58 -07001339 """Returns a list of hooks that need to be run for a project.
1340
1341 Expects to be called from within the project root.
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001342
1343 Args:
1344 project: A string, name of the project.
1345 presubmit: A Boolean, True if the check is run as a git pre-submit script.
Ryan Cui9b651632011-05-11 11:38:58 -07001346 """
Jon Salz3ee59de2012-08-18 13:54:22 +08001347 config = ConfigParser.RawConfigParser()
1348 try:
1349 config.read(_CONFIG_FILE)
1350 except ConfigParser.Error:
1351 # Just use an empty config file
1352 config = ConfigParser.RawConfigParser()
1353
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001354 if presubmit:
1355 hook_list = _COMMON_HOOKS
1356 else:
1357 hook_list = _PATCH_DESCRIPTION_HOOKS + _COMMON_HOOKS
1358
Mike Frysinger3554bc92015-03-11 04:59:21 -04001359 enabled_hooks, disabled_hooks = _get_override_hooks(config)
1360 hooks = (list(enabled_hooks) +
1361 [hook for hook in hook_list if hook not in disabled_hooks])
Ryan Cui9b651632011-05-11 11:38:58 -07001362
1363 if project in _PROJECT_SPECIFIC_HOOKS:
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001364 hooks.extend(hook for hook in _PROJECT_SPECIFIC_HOOKS[project]
1365 if hook not in disabled_hooks)
Ryan Cui9b651632011-05-11 11:38:58 -07001366
Jon Salz3ee59de2012-08-18 13:54:22 +08001367 for script in _get_project_hook_scripts(config):
1368 hooks.append(functools.partial(_run_project_hook_script, script))
1369
Ryan Cui9b651632011-05-11 11:38:58 -07001370 return hooks
1371
1372
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001373def _run_project_hooks(project, proj_dir=None,
1374 commit_list=None, presubmit=False):
Ryan Cui1562fb82011-05-09 11:01:31 -07001375 """For each project run its project specific hook from the hooks dictionary.
1376
1377 Args:
Doug Anderson44a644f2011-11-02 10:37:37 -07001378 project: The name of project to run hooks for.
1379 proj_dir: If non-None, this is the directory the project is in. If None,
1380 we'll ask repo.
Doug Anderson14749562013-06-26 13:38:29 -07001381 commit_list: A list of commits to run hooks against. If None or empty list
1382 then we'll automatically get the list of commits that would be uploaded.
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001383 presubmit: A Boolean, True if the check is run as a git pre-submit script.
Ryan Cui1562fb82011-05-09 11:01:31 -07001384
1385 Returns:
1386 Boolean value of whether any errors were ecountered while running the hooks.
1387 """
Doug Anderson44a644f2011-11-02 10:37:37 -07001388 if proj_dir is None:
David James2edd9002013-10-11 14:09:19 -07001389 proj_dirs = _run_command(['repo', 'forall', project, '-c', 'pwd']).split()
1390 if len(proj_dirs) == 0:
1391 print('%s cannot be found.' % project, file=sys.stderr)
1392 print('Please specify a valid project.', file=sys.stderr)
1393 return True
1394 if len(proj_dirs) > 1:
1395 print('%s is associated with multiple directories.' % project,
1396 file=sys.stderr)
1397 print('Please specify a directory to help disambiguate.', file=sys.stderr)
1398 return True
1399 proj_dir = proj_dirs[0]
Doug Anderson44a644f2011-11-02 10:37:37 -07001400
Ryan Cuiec4d6332011-05-02 14:15:25 -07001401 pwd = os.getcwd()
1402 # hooks assume they are run from the root of the project
1403 os.chdir(proj_dir)
1404
Doug Anderson14749562013-06-26 13:38:29 -07001405 if not commit_list:
1406 try:
1407 commit_list = _get_commits()
1408 except VerifyException as e:
1409 PrintErrorForProject(project, HookFailure(str(e)))
1410 os.chdir(pwd)
1411 return True
Ryan Cuifa55df52011-05-06 11:16:55 -07001412
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001413 hooks = _get_project_hooks(project, presubmit)
Ryan Cui1562fb82011-05-09 11:01:31 -07001414 error_found = False
Ryan Cuifa55df52011-05-06 11:16:55 -07001415 for commit in commit_list:
Ryan Cui1562fb82011-05-09 11:01:31 -07001416 error_list = []
Ryan Cui9b651632011-05-11 11:38:58 -07001417 for hook in hooks:
Ryan Cui1562fb82011-05-09 11:01:31 -07001418 hook_error = hook(project, commit)
1419 if hook_error:
1420 error_list.append(hook_error)
1421 error_found = True
1422 if error_list:
1423 PrintErrorsForCommit(project, commit, _get_commit_desc(commit),
1424 error_list)
Don Garrettdba548a2011-05-05 15:17:14 -07001425
Ryan Cuiec4d6332011-05-02 14:15:25 -07001426 os.chdir(pwd)
Ryan Cui1562fb82011-05-09 11:01:31 -07001427 return error_found
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001428
Mike Frysingerae409522014-02-01 03:16:11 -05001429
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001430# Main
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -07001431
Ryan Cui1562fb82011-05-09 11:01:31 -07001432
Mike Frysingerae409522014-02-01 03:16:11 -05001433def main(project_list, worktree_list=None, **_kwargs):
Doug Anderson06456632012-01-05 11:02:14 -08001434 """Main function invoked directly by repo.
1435
1436 This function will exit directly upon error so that repo doesn't print some
1437 obscure error message.
1438
1439 Args:
1440 project_list: List of projects to run on.
David James2edd9002013-10-11 14:09:19 -07001441 worktree_list: A list of directories. It should be the same length as
1442 project_list, so that each entry in project_list matches with a directory
1443 in worktree_list. If None, we will attempt to calculate the directories
1444 automatically.
Doug Anderson06456632012-01-05 11:02:14 -08001445 kwargs: Leave this here for forward-compatibility.
1446 """
Ryan Cui1562fb82011-05-09 11:01:31 -07001447 found_error = False
David James2edd9002013-10-11 14:09:19 -07001448 if not worktree_list:
1449 worktree_list = [None] * len(project_list)
1450 for project, worktree in zip(project_list, worktree_list):
1451 if _run_project_hooks(project, proj_dir=worktree):
Ryan Cui1562fb82011-05-09 11:01:31 -07001452 found_error = True
1453
Mike Frysingerae409522014-02-01 03:16:11 -05001454 if found_error:
Ryan Cui1562fb82011-05-09 11:01:31 -07001455 msg = ('Preupload failed due to errors in project(s). HINTS:\n'
Ryan Cui9b651632011-05-11 11:38:58 -07001456 '- To disable some source style checks, and for other hints, see '
1457 '<checkout_dir>/src/repohooks/README\n'
1458 '- To upload only current project, run \'repo upload .\'')
Mike Frysinger09d6a3d2013-10-08 22:21:03 -04001459 print(msg, file=sys.stderr)
Don Garrettdba548a2011-05-05 15:17:14 -07001460 sys.exit(1)
Anush Elangovan63afad72011-03-23 00:41:27 -07001461
Ryan Cui1562fb82011-05-09 11:01:31 -07001462
Doug Anderson44a644f2011-11-02 10:37:37 -07001463def _identify_project(path):
1464 """Identify the repo project associated with the given path.
1465
1466 Returns:
1467 A string indicating what project is associated with the path passed in or
1468 a blank string upon failure.
1469 """
1470 return _run_command(['repo', 'forall', '.', '-c', 'echo ${REPO_PROJECT}'],
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001471 redirect_stderr=True, cwd=path).strip()
Doug Anderson44a644f2011-11-02 10:37:37 -07001472
1473
Mike Frysinger55f85b52014-12-18 14:45:21 -05001474def direct_main(argv):
Doug Anderson44a644f2011-11-02 10:37:37 -07001475 """Run hooks directly (outside of the context of repo).
1476
Doug Anderson44a644f2011-11-02 10:37:37 -07001477 Args:
Mike Frysinger55f85b52014-12-18 14:45:21 -05001478 argv: The command line args to process
Doug Anderson44a644f2011-11-02 10:37:37 -07001479
1480 Returns:
1481 0 if no pre-upload failures, 1 if failures.
1482
1483 Raises:
1484 BadInvocation: On some types of invocation errors.
1485 """
Mike Frysinger66142932014-12-18 14:55:57 -05001486 parser = commandline.ArgumentParser(description=__doc__)
1487 parser.add_argument('--dir', default=None,
1488 help='The directory that the project lives in. If not '
1489 'specified, use the git project root based on the cwd.')
1490 parser.add_argument('--project', default=None,
1491 help='The project repo path; this can affect how the '
1492 'hooks get run, since some hooks are project-specific. '
1493 'For chromite this is chromiumos/chromite. If not '
1494 'specified, the repo tool will be used to figure this '
1495 'out based on the dir.')
1496 parser.add_argument('--rerun-since', default=None,
1497 help='Rerun hooks on old commits since the given date. '
1498 'The date should match git log\'s concept of a date. '
1499 'e.g. 2012-06-20. This option is mutually exclusive '
1500 'with --pre-submit.')
1501 parser.add_argument('--pre-submit', action="store_true",
1502 help='Run the check against the pending commit. '
1503 'This option should be used at the \'git commit\' '
1504 'phase as opposed to \'repo upload\'. This option '
1505 'is mutually exclusive with --rerun-since.')
1506 parser.add_argument('commits', nargs='*',
1507 help='Check specific commits')
1508 opts = parser.parse_args(argv)
Doug Anderson44a644f2011-11-02 10:37:37 -07001509
Doug Anderson14749562013-06-26 13:38:29 -07001510 if opts.rerun_since:
Mike Frysinger66142932014-12-18 14:55:57 -05001511 if opts.commits:
Doug Anderson14749562013-06-26 13:38:29 -07001512 raise BadInvocation('Can\'t pass commits and use rerun-since: %s' %
Mike Frysinger66142932014-12-18 14:55:57 -05001513 ' '.join(opts.commits))
Doug Anderson14749562013-06-26 13:38:29 -07001514
1515 cmd = ['git', 'log', '--since="%s"' % opts.rerun_since, '--pretty=%H']
1516 all_commits = _run_command(cmd).splitlines()
1517 bot_commits = _run_command(cmd + ['--author=chrome-bot']).splitlines()
1518
1519 # Eliminate chrome-bot commits but keep ordering the same...
1520 bot_commits = set(bot_commits)
Mike Frysinger66142932014-12-18 14:55:57 -05001521 opts.commits = [c for c in all_commits if c not in bot_commits]
Doug Anderson14749562013-06-26 13:38:29 -07001522
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001523 if opts.pre_submit:
1524 raise BadInvocation('rerun-since and pre-submit can not be '
1525 'used together')
1526 if opts.pre_submit:
Mike Frysinger66142932014-12-18 14:55:57 -05001527 if opts.commits:
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001528 raise BadInvocation('Can\'t pass commits and use pre-submit: %s' %
Mike Frysinger66142932014-12-18 14:55:57 -05001529 ' '.join(opts.commits))
1530 opts.commits = [PRE_SUBMIT,]
Doug Anderson44a644f2011-11-02 10:37:37 -07001531
1532 # Check/normlaize git dir; if unspecified, we'll use the root of the git
1533 # project from CWD
1534 if opts.dir is None:
1535 git_dir = _run_command(['git', 'rev-parse', '--git-dir'],
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001536 redirect_stderr=True).strip()
Doug Anderson44a644f2011-11-02 10:37:37 -07001537 if not git_dir:
1538 raise BadInvocation('The current directory is not part of a git project.')
1539 opts.dir = os.path.dirname(os.path.abspath(git_dir))
1540 elif not os.path.isdir(opts.dir):
1541 raise BadInvocation('Invalid dir: %s' % opts.dir)
1542 elif not os.path.isdir(os.path.join(opts.dir, '.git')):
1543 raise BadInvocation('Not a git directory: %s' % opts.dir)
1544
1545 # Identify the project if it wasn't specified; this _requires_ the repo
1546 # tool to be installed and for the project to be part of a repo checkout.
1547 if not opts.project:
1548 opts.project = _identify_project(opts.dir)
1549 if not opts.project:
1550 raise BadInvocation("Repo couldn't identify the project of %s" % opts.dir)
1551
Doug Anderson14749562013-06-26 13:38:29 -07001552 found_error = _run_project_hooks(opts.project, proj_dir=opts.dir,
Mike Frysinger66142932014-12-18 14:55:57 -05001553 commit_list=opts.commits,
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001554 presubmit=opts.pre_submit)
Doug Anderson44a644f2011-11-02 10:37:37 -07001555 if found_error:
1556 return 1
1557 return 0
1558
1559
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -07001560if __name__ == '__main__':
Mike Frysinger55f85b52014-12-18 14:45:21 -05001561 sys.exit(direct_main(sys.argv[1:]))