blob: 74cdda4b4caaa247ca66607533d9c78b68ec1936 [file] [log] [blame]
Prathmesh Prabhuc5254652016-12-22 12:58:05 -08001#!/usr/bin/env python2
Mike Frysingerb7d552e2017-11-23 11:50:47 -05002# -*- coding: utf-8 -*-
Jon Salz98255932012-08-18 14:48:02 +08003# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07004# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
Mike Frysingerae409522014-02-01 03:16:11 -05007"""Presubmit checks to run when doing `repo upload`.
8
9You can add new checks by adding a functions to the HOOKS constants.
10"""
11
Mike Frysinger09d6a3d2013-10-08 22:21:03 -040012from __future__ import print_function
13
Filipe Brandenburger4b542b12015-10-09 12:46:31 -070014import argparse
Alex Deymo643ac4c2015-09-03 10:40:50 -070015import collections
Ryan Cui9b651632011-05-11 11:38:58 -070016import ConfigParser
Daniel Erate3ea3fc2015-02-13 15:27:52 -070017import fnmatch
Jon Salz3ee59de2012-08-18 13:54:22 +080018import functools
Dale Curtis2975c432011-05-03 17:25:20 -070019import json
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070020import os
Ryan Cuiec4d6332011-05-02 14:15:25 -070021import re
Mandeep Singh Bainesa7ffa4b2011-05-03 11:37:02 -070022import sys
Peter Ammon811f6702014-06-12 15:45:38 -070023import stat
Aviv Keshet5ac59522017-01-31 14:28:27 -080024import StringIO
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070025
Ryan Cui1562fb82011-05-09 11:01:31 -070026from errors import (VerifyException, HookFailure, PrintErrorForProject,
27 PrintErrorsForCommit)
Ryan Cuiec4d6332011-05-02 14:15:25 -070028
David Jamesc3b68b32013-04-03 09:17:03 -070029# If repo imports us, the __name__ will be __builtin__, and the wrapper will
30# be in $CHROMEOS_CHECKOUT/.repo/repo/main.py, so we need to go two directories
31# up. The same logic also happens to work if we're executed directly.
32if __name__ in ('__builtin__', '__main__'):
33 sys.path.insert(0, os.path.join(os.path.dirname(sys.argv[0]), '..', '..'))
34
Mike Frysinger66142932014-12-18 14:55:57 -050035from chromite.lib import commandline
Aviv Keshet5ac59522017-01-31 14:28:27 -080036from chromite.lib import constants
Rahul Chaudhry0e515342015-08-07 12:00:43 -070037from chromite.lib import cros_build_lib
Mike Frysingerd3bd32c2014-11-24 23:34:29 -050038from chromite.lib import git
Daniel Erata350fd32014-09-29 14:02:34 -070039from chromite.lib import osutils
David Jamesc3b68b32013-04-03 09:17:03 -070040from chromite.lib import patch
Mike Frysinger2ec70ed2014-08-17 19:28:34 -040041from chromite.licensing import licenses_lib
David Jamesc3b68b32013-04-03 09:17:03 -070042
Vadim Bendebury2b62d742014-06-22 13:14:51 -070043PRE_SUBMIT = 'pre-submit'
Ryan Cuiec4d6332011-05-02 14:15:25 -070044
45COMMON_INCLUDED_PATHS = [
Mike Frysingerae409522014-02-01 03:16:11 -050046 # C++ and friends
47 r".*\.c$", r".*\.cc$", r".*\.cpp$", r".*\.h$", r".*\.m$", r".*\.mm$",
48 r".*\.inl$", r".*\.asm$", r".*\.hxx$", r".*\.hpp$", r".*\.s$", r".*\.S$",
49 # Scripts
50 r".*\.js$", r".*\.py$", r".*\.sh$", r".*\.rb$", r".*\.pl$", r".*\.pm$",
51 # No extension at all, note that ALL CAPS files are black listed in
52 # COMMON_EXCLUDED_LIST below.
53 r"(^|.*[\\\/])[^.]+$",
54 # Other
55 r".*\.java$", r".*\.mk$", r".*\.am$",
Brian Norrisfdbac8e2016-06-16 11:09:05 -070056 r".*\.policy$", r".*\.conf$",
Ryan Cuiec4d6332011-05-02 14:15:25 -070057]
58
Ryan Cui1562fb82011-05-09 11:01:31 -070059
Ryan Cuiec4d6332011-05-02 14:15:25 -070060COMMON_EXCLUDED_PATHS = [
Daniel Erate3ea3fc2015-02-13 15:27:52 -070061 # For ebuild trees, ignore any caches and manifest data.
Mike Frysingerae409522014-02-01 03:16:11 -050062 r".*/Manifest$",
63 r".*/metadata/[^/]*cache[^/]*/[^/]+/[^/]+$",
Doug Anderson5bfb6792011-10-25 16:45:41 -070064
Daniel Erate3ea3fc2015-02-13 15:27:52 -070065 # Ignore profiles data (like overlay-tegra2/profiles).
Mike Frysinger94a670c2014-09-19 12:46:26 -040066 r"(^|.*/)overlay-.*/profiles/.*",
Mike Frysinger98638102014-08-28 00:15:08 -040067 r"^profiles/.*$",
68
C Shapiro8f90e9b2017-06-28 09:54:50 -060069 # Ignore config files in ebuild setup.
70 r"(^|.*/)overlay-.*/chromeos-base/chromeos-bsp.*/files/.*",
71 r"^chromeos-base/chromeos-bsp.*/files/.*",
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
Ken Turnerd07564b2018-02-08 17:57:59 +110081LICENSE_EXCLUDED_PATHS = [
82 r".*/OWNERS$",
83]
Ryan Cui1562fb82011-05-09 11:01:31 -070084
Ryan Cui9b651632011-05-11 11:38:58 -070085_CONFIG_FILE = 'PRESUBMIT.cfg'
86
87
Daniel Erate3ea3fc2015-02-13 15:27:52 -070088# File containing wildcards, one per line, matching files that should be
89# excluded from presubmit checks. Lines beginning with '#' are ignored.
90_IGNORE_FILE = '.presubmitignore'
91
92
Doug Anderson44a644f2011-11-02 10:37:37 -070093# Exceptions
94
95
96class BadInvocation(Exception):
97 """An Exception indicating a bad invocation of the program."""
98 pass
99
100
Ryan Cui1562fb82011-05-09 11:01:31 -0700101# General Helpers
102
Sean Paulba01d402011-05-05 11:36:23 -0400103
Alex Deymo643ac4c2015-09-03 10:40:50 -0700104Project = collections.namedtuple('Project', ['name', 'dir', 'remote'])
105
106
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700107# pylint: disable=redefined-builtin
108def _run_command(cmd, cwd=None, input=None,
109 redirect_stderr=False, combine_stdout_stderr=False):
Doug Anderson44a644f2011-11-02 10:37:37 -0700110 """Executes the passed in command and returns raw stdout output.
111
112 Args:
113 cmd: The command to run; should be a list of strings.
114 cwd: The directory to switch to for running the command.
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700115 input: The data to pipe into this command through stdin. If a file object
116 or file descriptor, stdin will be connected directly to that.
117 redirect_stderr: Redirect stderr away from console.
118 combine_stdout_stderr: Combines stdout and stderr streams into stdout.
Doug Anderson44a644f2011-11-02 10:37:37 -0700119
120 Returns:
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700121 The stdout from the process (discards stderr and returncode).
Doug Anderson44a644f2011-11-02 10:37:37 -0700122 """
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700123 return cros_build_lib.RunCommand(cmd=cmd,
124 cwd=cwd,
125 print_cmd=False,
126 input=input,
127 stdout_to_pipe=True,
128 redirect_stderr=redirect_stderr,
129 combine_stdout_stderr=combine_stdout_stderr,
130 error_code_ok=True).output
131# pylint: enable=redefined-builtin
Ryan Cui72834d12011-05-05 14:51:33 -0700132
Ryan Cui1562fb82011-05-09 11:01:31 -0700133
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700134def _get_hooks_dir():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700135 """Returns the absolute path to the repohooks directory."""
Doug Anderson44a644f2011-11-02 10:37:37 -0700136 if __name__ == '__main__':
137 # Works when file is run on its own (__file__ is defined)...
138 return os.path.abspath(os.path.dirname(__file__))
139 else:
140 # We need to do this when we're run through repo. Since repo executes
141 # us with execfile(), we don't get __file__ defined.
142 cmd = ['repo', 'forall', 'chromiumos/repohooks', '-c', 'pwd']
143 return _run_command(cmd).strip()
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700144
Ryan Cui1562fb82011-05-09 11:01:31 -0700145
Ryan Cuiec4d6332011-05-02 14:15:25 -0700146def _match_regex_list(subject, expressions):
147 """Try to match a list of regular expressions to a string.
148
149 Args:
150 subject: The string to match regexes on
151 expressions: A list of regular expressions to check for matches with.
152
153 Returns:
154 Whether the passed in subject matches any of the passed in regexes.
155 """
156 for expr in expressions:
Mike Frysingerae409522014-02-01 03:16:11 -0500157 if re.search(expr, subject):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700158 return True
159 return False
160
Ryan Cui1562fb82011-05-09 11:01:31 -0700161
Mike Frysingerae409522014-02-01 03:16:11 -0500162def _filter_files(files, include_list, exclude_list=()):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700163 """Filter out files based on the conditions passed in.
164
165 Args:
166 files: list of filepaths to filter
167 include_list: list of regex that when matched with a file path will cause it
168 to be added to the output list unless the file is also matched with a
169 regex in the exclude_list.
170 exclude_list: list of regex that when matched with a file will prevent it
171 from being added to the output list, even if it is also matched with a
172 regex in the include_list.
173
174 Returns:
175 A list of filepaths that contain files matched in the include_list and not
176 in the exclude_list.
177 """
178 filtered = []
179 for f in files:
180 if (_match_regex_list(f, include_list) and
181 not _match_regex_list(f, exclude_list)):
182 filtered.append(f)
183 return filtered
184
Ryan Cuiec4d6332011-05-02 14:15:25 -0700185
186# Git Helpers
Ryan Cui1562fb82011-05-09 11:01:31 -0700187
188
Ryan Cui4725d952011-05-05 15:41:19 -0700189def _get_upstream_branch():
190 """Returns the upstream tracking branch of the current branch.
191
192 Raises:
193 Error if there is no tracking branch
194 """
195 current_branch = _run_command(['git', 'symbolic-ref', 'HEAD']).strip()
196 current_branch = current_branch.replace('refs/heads/', '')
197 if not current_branch:
Ryan Cui1562fb82011-05-09 11:01:31 -0700198 raise VerifyException('Need to be on a tracking branch')
Ryan Cui4725d952011-05-05 15:41:19 -0700199
200 cfg_option = 'branch.' + current_branch + '.%s'
201 full_upstream = _run_command(['git', 'config', cfg_option % 'merge']).strip()
202 remote = _run_command(['git', 'config', cfg_option % 'remote']).strip()
203 if not remote or not full_upstream:
Ryan Cui1562fb82011-05-09 11:01:31 -0700204 raise VerifyException('Need to be on a tracking branch')
Ryan Cui4725d952011-05-05 15:41:19 -0700205
206 return full_upstream.replace('heads', 'remotes/' + remote)
207
Ryan Cui1562fb82011-05-09 11:01:31 -0700208
Che-Liang Chiou5ce2d7b2013-03-22 18:47:55 -0700209def _get_patch(commit):
210 """Returns the patch for this commit."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700211 if commit == PRE_SUBMIT:
212 return _run_command(['git', 'diff', '--cached', 'HEAD'])
213 else:
214 return _run_command(['git', 'format-patch', '--stdout', '-1', commit])
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700215
Ryan Cui1562fb82011-05-09 11:01:31 -0700216
Jon Salz98255932012-08-18 14:48:02 +0800217def _try_utf8_decode(data):
218 """Attempts to decode a string as UTF-8.
219
220 Returns:
221 The decoded Unicode object, or the original string if parsing fails.
222 """
223 try:
224 return unicode(data, 'utf-8', 'strict')
225 except UnicodeDecodeError:
226 return data
227
228
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500229def _get_file_content(path, commit):
230 """Returns the content of a file at a specific commit.
231
232 We can't rely on the file as it exists in the filesystem as people might be
233 uploading a series of changes which modifies the file multiple times.
234
235 Note: The "content" of a symlink is just the target. So if you're expecting
236 a full file, you should check that first. One way to detect is that the
237 content will not have any newlines.
238 """
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700239 if commit == PRE_SUBMIT:
240 return _run_command(['git', 'diff', 'HEAD', path])
241 else:
Mike Frysingerd0523442018-01-03 17:05:29 -0500242 # Make sure people don't accidentally pass in full paths which will never
243 # work. You need to use relative=True with _get_affected_files.
244 if path.startswith('/'):
245 raise ValueError('_get_file_content must be called with relative paths: '
246 + path)
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700247 return _run_command(['git', 'show', '%s:%s' % (commit, path)])
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500248
249
Mike Frysingerae409522014-02-01 03:16:11 -0500250def _get_file_diff(path, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700251 """Returns a list of (linenum, lines) tuples that the commit touched."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700252 if commit == PRE_SUBMIT:
Prathmesh Prabhua9de1722016-12-22 14:56:40 -0800253 command = ['git', 'diff', '-p', '--pretty=format:', '--no-ext-diff', 'HEAD',
254 path]
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700255 else:
Prathmesh Prabhua9de1722016-12-22 14:56:40 -0800256 command = ['git', 'show', '-p', '--pretty=format:', '--no-ext-diff', commit,
257 path]
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700258 output = _run_command(command)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700259
260 new_lines = []
261 line_num = 0
262 for line in output.splitlines():
263 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
264 if m:
265 line_num = int(m.groups(1)[0])
266 continue
267 if line.startswith('+') and not line.startswith('++'):
Jon Salz98255932012-08-18 14:48:02 +0800268 new_lines.append((line_num, _try_utf8_decode(line[1:])))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700269 if not line.startswith('-'):
270 line_num += 1
271 return new_lines
272
Ryan Cui1562fb82011-05-09 11:01:31 -0700273
Daniel Erate3ea3fc2015-02-13 15:27:52 -0700274def _get_ignore_wildcards(directory, cache):
275 """Get wildcards listed in a directory's _IGNORE_FILE.
276
277 Args:
278 directory: A string containing a directory path.
279 cache: A dictionary (opaque to caller) caching previously-read wildcards.
280
281 Returns:
282 A list of wildcards from _IGNORE_FILE or an empty list if _IGNORE_FILE
283 wasn't present.
284 """
285 # In the cache, keys are directories and values are lists of wildcards from
286 # _IGNORE_FILE within those directories (and empty if no file was present).
287 if directory not in cache:
288 wildcards = []
289 dotfile_path = os.path.join(directory, _IGNORE_FILE)
290 if os.path.exists(dotfile_path):
291 # TODO(derat): Consider using _get_file_content() to get the file as of
292 # this commit instead of the on-disk version. This may have a noticeable
293 # performance impact, as each call to _get_file_content() runs git.
294 with open(dotfile_path, 'r') as dotfile:
295 for line in dotfile.readlines():
296 line = line.strip()
297 if line.startswith('#'):
298 continue
299 if line.endswith('/'):
300 line += '*'
301 wildcards.append(line)
302 cache[directory] = wildcards
303
304 return cache[directory]
305
306
307def _path_is_ignored(path, cache):
308 """Check whether a path is ignored by _IGNORE_FILE.
309
310 Args:
311 path: A string containing a path.
312 cache: A dictionary (opaque to caller) caching previously-read wildcards.
313
314 Returns:
315 True if a file named _IGNORE_FILE in one of the passed-in path's parent
316 directories contains a wildcard matching the path.
317 """
318 # Skip ignore files.
319 if os.path.basename(path) == _IGNORE_FILE:
320 return True
321
322 path = os.path.abspath(path)
323 base = os.getcwd()
324
325 prefix = os.path.dirname(path)
326 while prefix.startswith(base):
327 rel_path = path[len(prefix) + 1:]
328 for wildcard in _get_ignore_wildcards(prefix, cache):
329 if fnmatch.fnmatch(rel_path, wildcard):
330 return True
331 prefix = os.path.dirname(prefix)
332
333 return False
334
335
Mike Frysinger292b45d2014-11-25 01:17:10 -0500336def _get_affected_files(commit, include_deletes=False, relative=False,
337 include_symlinks=False, include_adds=True,
Daniel Erate3ea3fc2015-02-13 15:27:52 -0700338 full_details=False, use_ignore_files=True):
Peter Ammon811f6702014-06-12 15:45:38 -0700339 """Returns list of file paths that were modified/added, excluding symlinks.
340
341 Args:
342 commit: The commit
343 include_deletes: If true, we'll include deleted files in the result
344 relative: Whether to return relative or full paths to files
Mike Frysinger292b45d2014-11-25 01:17:10 -0500345 include_symlinks: If true, we'll include symlinks in the result
346 include_adds: If true, we'll include new files in the result
347 full_details: If False, return filenames, else return structured results.
Daniel Erate3ea3fc2015-02-13 15:27:52 -0700348 use_ignore_files: Whether we ignore files matched by _IGNORE_FILE files.
Peter Ammon811f6702014-06-12 15:45:38 -0700349
350 Returns:
351 A list of modified/added (and perhaps deleted) files
352 """
Mike Frysinger292b45d2014-11-25 01:17:10 -0500353 if not relative and full_details:
354 raise ValueError('full_details only supports relative paths currently')
355
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700356 if commit == PRE_SUBMIT:
357 return _run_command(['git', 'diff-index', '--cached',
358 '--name-only', 'HEAD']).split()
Mike Frysingerd3bd32c2014-11-24 23:34:29 -0500359
360 path = os.getcwd()
361 files = git.RawDiff(path, '%s^!' % commit)
362
363 # Filter out symlinks.
Mike Frysinger292b45d2014-11-25 01:17:10 -0500364 if not include_symlinks:
365 files = [x for x in files if not stat.S_ISLNK(int(x.dst_mode, 8))]
Mike Frysingerd3bd32c2014-11-24 23:34:29 -0500366
367 if not include_deletes:
368 files = [x for x in files if x.status != 'D']
369
Mike Frysinger292b45d2014-11-25 01:17:10 -0500370 if not include_adds:
371 files = [x for x in files if x.status != 'A']
372
Daniel Erate3ea3fc2015-02-13 15:27:52 -0700373 if use_ignore_files:
374 cache = {}
375 is_ignored = lambda x: _path_is_ignored(x.dst_file or x.src_file, cache)
376 files = [x for x in files if not is_ignored(x)]
377
Mike Frysinger292b45d2014-11-25 01:17:10 -0500378 if full_details:
379 # Caller wants the raw objects to parse status/etc... themselves.
Mike Frysingerd3bd32c2014-11-24 23:34:29 -0500380 return files
381 else:
Mike Frysinger292b45d2014-11-25 01:17:10 -0500382 # Caller only cares about filenames.
383 files = [x.dst_file if x.dst_file else x.src_file for x in files]
384 if relative:
385 return files
386 else:
387 return [os.path.join(path, x) for x in files]
Peter Ammon811f6702014-06-12 15:45:38 -0700388
389
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700390def _get_commits():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700391 """Returns a list of commits for this review."""
Ryan Cui4725d952011-05-05 15:41:19 -0700392 cmd = ['git', 'log', '%s..' % _get_upstream_branch(), '--format=%H']
Ryan Cui72834d12011-05-05 14:51:33 -0700393 return _run_command(cmd).split()
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700394
Ryan Cui1562fb82011-05-09 11:01:31 -0700395
Ryan Cuiec4d6332011-05-02 14:15:25 -0700396def _get_commit_desc(commit):
397 """Returns the full commit message of a commit."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700398 if commit == PRE_SUBMIT:
399 return ''
Sean Paul23a2c582011-05-06 13:10:44 -0400400 return _run_command(['git', 'log', '--format=%s%n%n%b', commit + '^!'])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700401
402
Prathmesh Prabhuc5254652016-12-22 12:58:05 -0800403def _check_lines_in_diff(commit, files, check_callable, error_description):
404 """Checks given file for errors via the given check.
405
406 This is a convenience function for common per-line checks. It goes through all
407 files and returns a HookFailure with the error description listing all the
408 failures.
409
410 Args:
411 commit: The commit we're working on.
412 files: The files to check.
413 check_callable: A callable that takes a line and returns True if this line
414 _fails_ the check.
415 error_description: A string describing the error.
416 """
417 errors = []
418 for afile in files:
419 for line_num, line in _get_file_diff(afile, commit):
420 if check_callable(line):
421 errors.append('%s, line %s' % (afile, line_num))
422 if errors:
423 return HookFailure(error_description, errors)
424
425
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900426def _parse_common_inclusion_options(options):
427 """Parses common hook options for including/excluding files.
428
429 Args:
430 options: Option string list.
431
432 Returns:
433 (included, excluded) where each one is a list of regex strings.
434 """
435 parser = argparse.ArgumentParser()
436 parser.add_argument('--exclude_regex', action='append')
437 parser.add_argument('--include_regex', action='append')
438 opts = parser.parse_args(options)
439 included = opts.include_regex or []
440 excluded = opts.exclude_regex or []
441 return included, excluded
442
443
Ryan Cuiec4d6332011-05-02 14:15:25 -0700444# Common Hooks
445
Ryan Cui1562fb82011-05-09 11:01:31 -0700446
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900447def _check_no_long_lines(_project, commit, options=()):
Mike Frysinger55f85b52014-12-18 14:45:21 -0500448 """Checks there are no lines longer than MAX_LEN in any of the text files."""
449
Ryan Cuiec4d6332011-05-02 14:15:25 -0700450 MAX_LEN = 80
Jon Salz98255932012-08-18 14:48:02 +0800451 SKIP_REGEXP = re.compile('|'.join([
452 r'https?://',
453 r'^#\s*(define|include|import|pragma|if|endif)\b']))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700454
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900455 included, excluded = _parse_common_inclusion_options(options)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700456 files = _filter_files(_get_affected_files(commit),
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900457 included + COMMON_INCLUDED_PATHS,
458 excluded + COMMON_EXCLUDED_PATHS)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700459
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900460 errors = []
Ryan Cuiec4d6332011-05-02 14:15:25 -0700461 for afile in files:
462 for line_num, line in _get_file_diff(afile, commit):
463 # Allow certain lines to exceed the maxlen rule.
Mike Frysingerae409522014-02-01 03:16:11 -0500464 if len(line) <= MAX_LEN or SKIP_REGEXP.search(line):
Jon Salz98255932012-08-18 14:48:02 +0800465 continue
466
467 errors.append('%s, line %s, %s chars' % (afile, line_num, len(line)))
468 if len(errors) == 5: # Just show the first 5 errors.
469 break
Ryan Cuiec4d6332011-05-02 14:15:25 -0700470
471 if errors:
472 msg = 'Found lines longer than %s characters (first 5 shown):' % MAX_LEN
Ryan Cui1562fb82011-05-09 11:01:31 -0700473 return HookFailure(msg, errors)
474
Ryan Cuiec4d6332011-05-02 14:15:25 -0700475
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900476def _check_no_stray_whitespace(_project, commit, options=()):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700477 """Checks that there is no stray whitespace at source lines end."""
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900478 included, excluded = _parse_common_inclusion_options(options)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700479 files = _filter_files(_get_affected_files(commit),
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900480 included + COMMON_INCLUDED_PATHS,
481 excluded + COMMON_EXCLUDED_PATHS)
Prathmesh Prabhuc5254652016-12-22 12:58:05 -0800482 return _check_lines_in_diff(commit, files,
483 lambda line: line.rstrip() != line,
484 'Found line ending with white space in:')
Ryan Cui1562fb82011-05-09 11:01:31 -0700485
Ryan Cuiec4d6332011-05-02 14:15:25 -0700486
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900487def _check_no_tabs(_project, commit, options=()):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700488 """Checks there are no unexpanded tabs."""
Mike Frysingercd134512017-10-26 04:36:33 -0400489 # Don't add entire repos here. Update the PRESUBMIT.cfg in each repo instead.
490 # We only whitelist known specific filetypes here that show up in all repos.
Ryan Cuiec4d6332011-05-02 14:15:25 -0700491 TAB_OK_PATHS = [
Ryan Cuiec4d6332011-05-02 14:15:25 -0700492 r".*\.ebuild$",
493 r".*\.eclass$",
Elly Jones5ab34192011-11-15 14:57:06 -0500494 r".*/[M|m]akefile$",
495 r".*\.mk$"
Ryan Cuiec4d6332011-05-02 14:15:25 -0700496 ]
497
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900498 included, excluded = _parse_common_inclusion_options(options)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700499 files = _filter_files(_get_affected_files(commit),
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900500 included + COMMON_INCLUDED_PATHS,
501 excluded + COMMON_EXCLUDED_PATHS + TAB_OK_PATHS)
Prathmesh Prabhuc5254652016-12-22 12:58:05 -0800502 return _check_lines_in_diff(commit, files,
503 lambda line: '\t' in line,
504 'Found a tab character in:')
Ryan Cuiec4d6332011-05-02 14:15:25 -0700505
Prathmesh Prabhuc5254652016-12-22 12:58:05 -0800506
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900507def _check_tabbed_indents(_project, commit, options=()):
Prathmesh Prabhuc5254652016-12-22 12:58:05 -0800508 """Checks that indents use tabs only."""
509 TABS_REQUIRED_PATHS = [
510 r".*\.ebuild$",
511 r".*\.eclass$",
512 ]
513 LEADING_SPACE_RE = re.compile('[\t]* ')
514
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900515 included, excluded = _parse_common_inclusion_options(options)
Prathmesh Prabhuc5254652016-12-22 12:58:05 -0800516 files = _filter_files(_get_affected_files(commit),
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900517 included + TABS_REQUIRED_PATHS,
518 excluded + COMMON_EXCLUDED_PATHS)
Prathmesh Prabhuc5254652016-12-22 12:58:05 -0800519 return _check_lines_in_diff(
520 commit, files,
521 lambda line: LEADING_SPACE_RE.match(line) is not None,
522 'Found a space in indentation (must be all tabs):')
Ryan Cui1562fb82011-05-09 11:01:31 -0700523
Ryan Cuiec4d6332011-05-02 14:15:25 -0700524
Rahul Chaudhry09f61372015-07-31 17:14:26 -0700525def _check_gofmt(_project, commit):
526 """Checks that Go files are formatted with gofmt."""
527 errors = []
528 files = _filter_files(_get_affected_files(commit, relative=True),
529 [r'\.go$'])
530
531 for gofile in files:
532 contents = _get_file_content(gofile, commit)
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700533 output = _run_command(cmd=['gofmt', '-l'], input=contents,
534 combine_stdout_stderr=True)
Rahul Chaudhry09f61372015-07-31 17:14:26 -0700535 if output:
536 errors.append(gofile)
537 if errors:
538 return HookFailure('Files not formatted with gofmt:', errors)
539
540
Mike Frysingerae409522014-02-01 03:16:11 -0500541def _check_change_has_test_field(_project, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700542 """Check for a non-empty 'TEST=' field in the commit message."""
David McMahon8f6553e2011-06-10 15:46:36 -0700543 TEST_RE = r'\nTEST=\S+'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700544
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700545 if not re.search(TEST_RE, _get_commit_desc(commit)):
Ryan Cui1562fb82011-05-09 11:01:31 -0700546 msg = 'Changelist description needs TEST field (after first line)'
547 return HookFailure(msg)
548
Ryan Cuiec4d6332011-05-02 14:15:25 -0700549
Mike Frysingerae409522014-02-01 03:16:11 -0500550def _check_change_has_valid_cq_depend(_project, commit):
David Jamesc3b68b32013-04-03 09:17:03 -0700551 """Check for a correctly formatted CQ-DEPEND field in the commit message."""
552 msg = 'Changelist has invalid CQ-DEPEND target.'
553 example = 'Example: CQ-DEPEND=CL:1234, CL:2345'
554 try:
555 patch.GetPaladinDeps(_get_commit_desc(commit))
556 except ValueError as ex:
557 return HookFailure(msg, [example, str(ex)])
558
559
Bernie Thompsonf8fea992016-01-14 10:27:18 -0800560def _check_change_is_contribution(_project, commit):
561 """Check that the change is a contribution."""
562 NO_CONTRIB = 'not a contribution'
563 if NO_CONTRIB in _get_commit_desc(commit).lower():
564 msg = ('Changelist is not a contribution, this cannot be accepted.\n'
565 'Please remove the "%s" text from the commit message.') % NO_CONTRIB
566 return HookFailure(msg)
567
568
Alex Deymo643ac4c2015-09-03 10:40:50 -0700569def _check_change_has_bug_field(project, commit):
David McMahon8f6553e2011-06-10 15:46:36 -0700570 """Check for a correctly formatted 'BUG=' field in the commit message."""
David James5c0073d2013-04-03 08:48:52 -0700571 OLD_BUG_RE = r'\nBUG=.*chromium-os'
572 if re.search(OLD_BUG_RE, _get_commit_desc(commit)):
573 msg = ('The chromium-os bug tracker is now deprecated. Please use\n'
574 'the chromium tracker in your BUG= line now.')
575 return HookFailure(msg)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700576
Alex Deymo643ac4c2015-09-03 10:40:50 -0700577 # Android internal and external projects use "Bug: " to track bugs in
578 # buganizer.
579 BUG_COLON_REMOTES = (
580 'aosp',
581 'goog',
582 )
583 if project.remote in BUG_COLON_REMOTES:
584 BUG_RE = r'\nBug: ?([Nn]one|\d+)'
585 if not re.search(BUG_RE, _get_commit_desc(commit)):
586 msg = ('Changelist description needs BUG field (after first line):\n'
587 'Bug: 9999 (for buganizer)\n'
588 'BUG=None')
589 return HookFailure(msg)
590 else:
Jorge Lucangeli Obesdce214e2017-10-25 15:04:39 -0400591 BUG_RE = r'\nBUG=([Nn]one|(chromium|b):\d+)'
Alex Deymo643ac4c2015-09-03 10:40:50 -0700592 if not re.search(BUG_RE, _get_commit_desc(commit)):
593 msg = ('Changelist description needs BUG field (after first line):\n'
Alex Deymo643ac4c2015-09-03 10:40:50 -0700594 'BUG=chromium:9999 (for public tracker)\n'
Alex Deymo643ac4c2015-09-03 10:40:50 -0700595 'BUG=b:9999 (for buganizer)\n'
596 'BUG=None')
597 return HookFailure(msg)
Ryan Cui1562fb82011-05-09 11:01:31 -0700598
Ryan Cuiec4d6332011-05-02 14:15:25 -0700599
Mike Frysinger292b45d2014-11-25 01:17:10 -0500600def _check_for_uprev(project, commit, project_top=None):
Doug Anderson42b8a052013-06-26 10:45:36 -0700601 """Check that we're not missing a revbump of an ebuild in the given commit.
602
603 If the given commit touches files in a directory that has ebuilds somewhere
604 up the directory hierarchy, it's very likely that we need an ebuild revbump
605 in order for those changes to take effect.
606
607 It's not totally trivial to detect a revbump, so at least detect that an
608 ebuild with a revision number in it was touched. This should handle the
609 common case where we use a symlink to do the revbump.
610
611 TODO: it would be nice to enhance this hook to:
612 * Handle cases where people revbump with a slightly different syntax. I see
613 one ebuild (puppy) that revbumps with _pN. This is a false positive.
614 * Catches cases where people aren't using symlinks for revbumps. If they
615 edit a revisioned file directly (and are expected to rename it for revbump)
616 we'll miss that. Perhaps we could detect that the file touched is a
617 symlink?
618
619 If a project doesn't use symlinks we'll potentially miss a revbump, but we're
620 still better off than without this check.
621
622 Args:
Alex Deymo643ac4c2015-09-03 10:40:50 -0700623 project: The Project to look at
Doug Anderson42b8a052013-06-26 10:45:36 -0700624 commit: The commit to look at
Mike Frysinger292b45d2014-11-25 01:17:10 -0500625 project_top: Top dir to process commits in
Doug Anderson42b8a052013-06-26 10:45:36 -0700626
627 Returns:
628 A HookFailure or None.
629 """
Mike Frysinger011af942014-01-17 16:12:22 -0500630 # If this is the portage-stable overlay, then ignore the check. It's rare
631 # that we're doing anything other than importing files from upstream, so
632 # forcing a rev bump makes no sense.
633 whitelist = (
634 'chromiumos/overlays/portage-stable',
635 )
Alex Deymo643ac4c2015-09-03 10:40:50 -0700636 if project.name in whitelist:
Mike Frysinger011af942014-01-17 16:12:22 -0500637 return None
638
Mike Frysinger292b45d2014-11-25 01:17:10 -0500639 def FinalName(obj):
640 # If the file is being deleted, then the dst_file is not set.
641 if obj.dst_file is None:
642 return obj.src_file
643 else:
644 return obj.dst_file
645
646 affected_path_objs = _get_affected_files(
647 commit, include_deletes=True, include_symlinks=True, relative=True,
648 full_details=True)
Doug Anderson42b8a052013-06-26 10:45:36 -0700649
650 # Don't yell about changes to whitelisted files...
Aviv Keshet272f2e52016-04-25 14:49:44 -0700651 whitelist = ('ChangeLog', 'Manifest', 'metadata.xml', 'COMMIT-QUEUE.ini')
Mike Frysinger292b45d2014-11-25 01:17:10 -0500652 affected_path_objs = [x for x in affected_path_objs
653 if os.path.basename(FinalName(x)) not in whitelist]
654 if not affected_path_objs:
Doug Anderson42b8a052013-06-26 10:45:36 -0700655 return None
656
657 # If we've touched any file named with a -rN.ebuild then we'll say we're
658 # OK right away. See TODO above about enhancing this.
Mike Frysinger292b45d2014-11-25 01:17:10 -0500659 touched_revved_ebuild = any(re.search(r'-r\d*\.ebuild$', FinalName(x))
660 for x in affected_path_objs)
Doug Anderson42b8a052013-06-26 10:45:36 -0700661 if touched_revved_ebuild:
662 return None
663
Mike Frysinger292b45d2014-11-25 01:17:10 -0500664 # If we're creating new ebuilds from scratch, then we don't need an uprev.
665 # Find all the dirs that new ebuilds and ignore their files/.
666 ebuild_dirs = [os.path.dirname(FinalName(x)) + '/' for x in affected_path_objs
667 if FinalName(x).endswith('.ebuild') and x.status == 'A']
668 affected_path_objs = [obj for obj in affected_path_objs
669 if not any(FinalName(obj).startswith(x)
670 for x in ebuild_dirs)]
671 if not affected_path_objs:
672 return
673
Doug Anderson42b8a052013-06-26 10:45:36 -0700674 # We want to examine the current contents of all directories that are parents
675 # of files that were touched (up to the top of the project).
676 #
677 # ...note: we use the current directory contents even though it may have
678 # changed since the commit we're looking at. This is just a heuristic after
679 # all. Worst case we don't flag a missing revbump.
Mike Frysinger292b45d2014-11-25 01:17:10 -0500680 if project_top is None:
681 project_top = os.getcwd()
Doug Anderson42b8a052013-06-26 10:45:36 -0700682 dirs_to_check = set([project_top])
Mike Frysinger292b45d2014-11-25 01:17:10 -0500683 for obj in affected_path_objs:
684 path = os.path.join(project_top, os.path.dirname(FinalName(obj)))
Doug Anderson42b8a052013-06-26 10:45:36 -0700685 while os.path.exists(path) and not os.path.samefile(path, project_top):
686 dirs_to_check.add(path)
687 path = os.path.dirname(path)
688
689 # Look through each directory. If it's got an ebuild in it then we'll
690 # consider this as a case when we need a revbump.
Gwendal Grignoua3086c32014-12-09 11:17:22 -0800691 affected_paths = set(os.path.join(project_top, FinalName(x))
692 for x in affected_path_objs)
Doug Anderson42b8a052013-06-26 10:45:36 -0700693 for dir_path in dirs_to_check:
694 contents = os.listdir(dir_path)
695 ebuilds = [os.path.join(dir_path, path)
696 for path in contents if path.endswith('.ebuild')]
697 ebuilds_9999 = [path for path in ebuilds if path.endswith('-9999.ebuild')]
698
C Shapiroae157ae2017-09-18 16:24:03 -0600699 affected_paths_under_9999_ebuilds = set()
700 for affected_path in affected_paths:
701 for ebuild_9999 in ebuilds_9999:
702 ebuild_dir = os.path.dirname(ebuild_9999)
703 if affected_path.startswith(ebuild_dir):
704 affected_paths_under_9999_ebuilds.add(affected_path)
705
706 # If every file changed exists under a 9999 ebuild, then skip
707 if len(affected_paths_under_9999_ebuilds) == len(affected_paths):
708 continue
709
Doug Anderson42b8a052013-06-26 10:45:36 -0700710 # If the -9999.ebuild file was touched the bot will uprev for us.
711 # ...we'll use a simple intersection here as a heuristic...
Mike Frysinger292b45d2014-11-25 01:17:10 -0500712 if set(ebuilds_9999) & affected_paths:
Doug Anderson42b8a052013-06-26 10:45:36 -0700713 continue
714
715 if ebuilds:
Mike Frysinger292b45d2014-11-25 01:17:10 -0500716 return HookFailure('Changelist probably needs a revbump of an ebuild, '
717 'or a -r1.ebuild symlink if this is a new ebuild:\n'
718 '%s' % dir_path)
Doug Anderson42b8a052013-06-26 10:45:36 -0700719
720 return None
721
722
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500723def _check_ebuild_eapi(project, commit):
Mike Frysinger948284a2018-02-01 15:22:56 -0500724 """Make sure we have people use EAPI=5 or newer with custom ebuilds.
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500725
726 We want to get away from older EAPI's as it makes life confusing and they
727 have less builtin error checking.
728
729 Args:
Alex Deymo643ac4c2015-09-03 10:40:50 -0700730 project: The Project to look at
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500731 commit: The commit to look at
732
733 Returns:
734 A HookFailure or None.
735 """
736 # If this is the portage-stable overlay, then ignore the check. It's rare
Mike Frysingercd6adfc2014-02-06 01:03:56 -0500737 # that we're doing anything other than importing files from upstream, and
738 # we shouldn't be rewriting things fundamentally anyways.
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500739 whitelist = (
740 'chromiumos/overlays/portage-stable',
741 )
Alex Deymo643ac4c2015-09-03 10:40:50 -0700742 if project.name in whitelist:
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500743 return None
744
Mike Frysinger948284a2018-02-01 15:22:56 -0500745 BAD_EAPIS = ('0', '1', '2', '3', '4')
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500746
747 get_eapi = re.compile(r'^\s*EAPI=[\'"]?([^\'"]+)')
748
749 ebuilds_re = [r'\.ebuild$']
750 ebuilds = _filter_files(_get_affected_files(commit, relative=True),
751 ebuilds_re)
752 bad_ebuilds = []
753
754 for ebuild in ebuilds:
755 # If the ebuild does not specify an EAPI, it defaults to 0.
756 eapi = '0'
757
758 lines = _get_file_content(ebuild, commit).splitlines()
759 if len(lines) == 1:
760 # This is most likely a symlink, so skip it entirely.
761 continue
762
763 for line in lines:
764 m = get_eapi.match(line)
765 if m:
766 # Once we hit the first EAPI line in this ebuild, stop processing.
767 # The spec requires that there only be one and it be first, so
768 # checking all possible values is pointless. We also assume that
769 # it's "the" EAPI line and not something in the middle of a heredoc.
770 eapi = m.group(1)
771 break
772
773 if eapi in BAD_EAPIS:
774 bad_ebuilds.append((ebuild, eapi))
775
776 if bad_ebuilds:
777 # pylint: disable=C0301
778 url = 'http://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/upgrade-ebuild-eapis'
779 # pylint: enable=C0301
780 return HookFailure(
Mike Frysingercd6adfc2014-02-06 01:03:56 -0500781 'These ebuilds are using old EAPIs. If these are imported from\n'
782 'Gentoo, then you may ignore and upload once with the --no-verify\n'
Mike Frysinger948284a2018-02-01 15:22:56 -0500783 'flag. Otherwise, please update to 5 or newer.\n'
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500784 '\t%s\n'
785 'See this guide for more details:\n%s\n' %
786 ('\n\t'.join(['%s: EAPI=%s' % x for x in bad_ebuilds]), url))
787
788
Mike Frysinger89bdb852014-02-01 05:26:26 -0500789def _check_ebuild_keywords(_project, commit):
Mike Frysingerc51ece72014-01-17 16:23:40 -0500790 """Make sure we use the new style KEYWORDS when possible in ebuilds.
791
792 If an ebuild generally does not care about the arch it is running on, then
793 ebuilds should flag it with one of:
794 KEYWORDS="*" # A stable ebuild.
795 KEYWORDS="~*" # An unstable ebuild.
796 KEYWORDS="-* ..." # Is known to only work on specific arches.
797
798 Args:
Alex Deymo643ac4c2015-09-03 10:40:50 -0700799 project: The Project to look at
Mike Frysingerc51ece72014-01-17 16:23:40 -0500800 commit: The commit to look at
801
802 Returns:
803 A HookFailure or None.
804 """
805 WHITELIST = set(('*', '-*', '~*'))
806
807 get_keywords = re.compile(r'^\s*KEYWORDS="(.*)"')
808
Mike Frysinger89bdb852014-02-01 05:26:26 -0500809 ebuilds_re = [r'\.ebuild$']
810 ebuilds = _filter_files(_get_affected_files(commit, relative=True),
811 ebuilds_re)
812
Mike Frysinger8d42d742014-09-22 15:50:21 -0400813 bad_ebuilds = []
Mike Frysingerc51ece72014-01-17 16:23:40 -0500814 for ebuild in ebuilds:
Mike Frysinger5c9e58d2014-09-09 03:32:50 -0400815 # We get the full content rather than a diff as the latter does not work
816 # on new files (like when adding new ebuilds).
817 lines = _get_file_content(ebuild, commit).splitlines()
818 for line in lines:
Mike Frysingerc51ece72014-01-17 16:23:40 -0500819 m = get_keywords.match(line)
820 if m:
821 keywords = set(m.group(1).split())
822 if not keywords or WHITELIST - keywords != WHITELIST:
823 continue
824
Mike Frysinger8d42d742014-09-22 15:50:21 -0400825 bad_ebuilds.append(ebuild)
826
827 if bad_ebuilds:
828 return HookFailure(
829 '%s\n'
830 'Please update KEYWORDS to use a glob:\n'
831 'If the ebuild should be marked stable (normal for non-9999 ebuilds):\n'
832 ' KEYWORDS="*"\n'
833 'If the ebuild should be marked unstable (normal for '
834 'cros-workon / 9999 ebuilds):\n'
835 ' KEYWORDS="~*"\n'
Mike Frysingerde8efea2015-05-17 03:42:26 -0400836 'If the ebuild needs to be marked for only specific arches, '
Mike Frysinger8d42d742014-09-22 15:50:21 -0400837 'then use -* like so:\n'
838 ' KEYWORDS="-* arm ..."\n' % '\n* '.join(bad_ebuilds))
Mike Frysingerc51ece72014-01-17 16:23:40 -0500839
840
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800841def _check_ebuild_licenses(_project, commit):
842 """Check if the LICENSE field in the ebuild is correct."""
Brian Norris7a610e82016-02-17 12:24:54 -0800843 affected_paths = _get_affected_files(commit, relative=True)
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800844 touched_ebuilds = [x for x in affected_paths if x.endswith('.ebuild')]
845
846 # A list of licenses to ignore for now.
Yu-Ju Hongc0963fa2014-03-03 12:36:52 -0800847 LICENSES_IGNORE = ['||', '(', ')']
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800848
849 for ebuild in touched_ebuilds:
850 # Skip virutal packages.
851 if ebuild.split('/')[-3] == 'virtual':
852 continue
853
854 try:
Brian Norris7a610e82016-02-17 12:24:54 -0800855 ebuild_content = _get_file_content(ebuild, commit)
856 license_types = licenses_lib.GetLicenseTypesFromEbuild(ebuild_content)
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800857 except ValueError as e:
858 return HookFailure(e.message, [ebuild])
859
860 # Also ignore licenses ending with '?'
861 for license_type in [x for x in license_types
862 if x not in LICENSES_IGNORE and not x.endswith('?')]:
863 try:
Mike Frysinger2ec70ed2014-08-17 19:28:34 -0400864 licenses_lib.Licensing.FindLicenseType(license_type)
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800865 except AssertionError as e:
866 return HookFailure(e.message, [ebuild])
867
868
Mike Frysingercd363c82014-02-01 05:20:18 -0500869def _check_ebuild_virtual_pv(project, commit):
870 """Enforce the virtual PV policies."""
871 # If this is the portage-stable overlay, then ignore the check.
872 # We want to import virtuals as-is from upstream Gentoo.
873 whitelist = (
874 'chromiumos/overlays/portage-stable',
875 )
Alex Deymo643ac4c2015-09-03 10:40:50 -0700876 if project.name in whitelist:
Mike Frysingercd363c82014-02-01 05:20:18 -0500877 return None
878
879 # We assume the repo name is the same as the dir name on disk.
880 # It would be dumb to not have them match though.
Alex Deymo643ac4c2015-09-03 10:40:50 -0700881 project_base = os.path.basename(project.name)
Mike Frysingercd363c82014-02-01 05:20:18 -0500882
883 is_variant = lambda x: x.startswith('overlay-variant-')
884 is_board = lambda x: x.startswith('overlay-')
885 is_private = lambda x: x.endswith('-private')
886
887 get_pv = re.compile(r'(.*?)virtual/([^/]+)/\2-([^/]*)\.ebuild$')
888
889 ebuilds_re = [r'\.ebuild$']
890 ebuilds = _filter_files(_get_affected_files(commit, relative=True),
891 ebuilds_re)
892 bad_ebuilds = []
893
894 for ebuild in ebuilds:
895 m = get_pv.match(ebuild)
896 if m:
897 overlay = m.group(1)
898 if not overlay or not is_board(overlay):
Alex Deymo643ac4c2015-09-03 10:40:50 -0700899 overlay = project_base
Mike Frysingercd363c82014-02-01 05:20:18 -0500900
901 pv = m.group(3).split('-', 1)[0]
902
Bernie Thompsone5ee1822016-01-12 14:22:23 -0800903 # Virtual versions >= 4 are special cases used above the standard
904 # versioning structure, e.g. if one has a board inheriting a board.
905 if float(pv) >= 4:
906 want_pv = pv
907 elif is_private(overlay):
Mike Frysingercd363c82014-02-01 05:20:18 -0500908 want_pv = '3.5' if is_variant(overlay) else '3'
909 elif is_board(overlay):
910 want_pv = '2.5' if is_variant(overlay) else '2'
911 else:
912 want_pv = '1'
913
914 if pv != want_pv:
915 bad_ebuilds.append((ebuild, pv, want_pv))
916
917 if bad_ebuilds:
918 # pylint: disable=C0301
919 url = 'http://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/portage-build-faq#TOC-Virtuals-and-central-management'
920 # pylint: enable=C0301
921 return HookFailure(
922 'These virtuals have incorrect package versions (PVs). Please adjust:\n'
923 '\t%s\n'
924 'If this is an upstream Gentoo virtual, then you may ignore this\n'
925 'check (and re-run w/--no-verify). Otherwise, please see this\n'
926 'page for more details:\n%s\n' %
927 ('\n\t'.join(['%s:\n\t\tPV is %s but should be %s' % x
928 for x in bad_ebuilds]), url))
929
930
Daniel Erat9d203ff2015-02-17 10:12:21 -0700931def _check_portage_make_use_var(_project, commit):
932 """Verify that $USE is set correctly in make.conf and make.defaults."""
933 files = _filter_files(_get_affected_files(commit, relative=True),
934 [r'(^|/)make.(conf|defaults)$'])
935
936 errors = []
937 for path in files:
938 basename = os.path.basename(path)
939
940 # Has a USE= line already been encountered in this file?
941 saw_use = False
942
943 for i, line in enumerate(_get_file_content(path, commit).splitlines(), 1):
944 if not line.startswith('USE='):
945 continue
946
947 preserves_use = '${USE}' in line or '$USE' in line
948
949 if (basename == 'make.conf' or
950 (basename == 'make.defaults' and saw_use)) and not preserves_use:
951 errors.append('%s:%d: missing ${USE}' % (path, i))
952 elif basename == 'make.defaults' and not saw_use and preserves_use:
953 errors.append('%s:%d: ${USE} referenced in initial declaration' %
954 (path, i))
955
956 saw_use = True
957
958 if errors:
959 return HookFailure(
960 'One or more Portage make files appear to set USE incorrectly.\n'
961 '\n'
962 'All USE assignments in make.conf and all assignments after the\n'
963 'initial declaration in make.defaults should contain "${USE}" to\n'
964 'preserve previously-set flags.\n'
965 '\n'
966 'The initial USE declaration in make.defaults should not contain\n'
967 '"${USE}".\n',
968 errors)
969
970
Mike Frysingerae409522014-02-01 03:16:11 -0500971def _check_change_has_proper_changeid(_project, commit):
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700972 """Verify that Change-ID is present in last paragraph of commit message."""
Mike Frysinger4a22bf02014-10-31 13:53:35 -0400973 CHANGE_ID_RE = r'\nChange-Id: I[a-f0-9]+\n'
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700974 desc = _get_commit_desc(commit)
Mike Frysinger4a22bf02014-10-31 13:53:35 -0400975 m = re.search(CHANGE_ID_RE, desc)
Mike Frysinger02b88bd2014-11-21 00:29:38 -0500976 if not m:
Vadim Bendebury20532ba2017-05-23 17:26:15 -0700977 return HookFailure('Last paragraph of description must include Change-Id.')
Ryan Cui1562fb82011-05-09 11:01:31 -0700978
Vadim Bendebury20532ba2017-05-23 17:26:15 -0700979 # S-o-b tags always allowed to follow Change-ID.
980 allowed_tags = ['Signed-off-by']
981
Mike Frysinger02b88bd2014-11-21 00:29:38 -0500982 end = desc[m.end():].strip().splitlines()
Vadim Bendebury6504aea2017-09-13 18:35:49 -0700983 cherry_pick_marker = 'cherry picked from commit'
984
985 if end and cherry_pick_marker in end[-1]:
Vadim Bendebury20532ba2017-05-23 17:26:15 -0700986 # Cherry picked patches allow more tags in the last paragraph.
Vadim Bendebury6504aea2017-09-13 18:35:49 -0700987 allowed_tags += ['Commit-Queue', 'Commit-Ready', 'Reviewed-by',
988 'Reviewed-on', 'Tested-by']
Vadim Bendebury20532ba2017-05-23 17:26:15 -0700989 end = end[:-1]
990
Vadim Bendebury6504aea2017-09-13 18:35:49 -0700991 # Note that descriptions could have multiple cherry pick markers.
992 tag_search = r'^(%s:|\(%s) ' % (':|'.join(allowed_tags), cherry_pick_marker)
Vadim Bendebury20532ba2017-05-23 17:26:15 -0700993
994 if [x for x in end if not re.search(tag_search, x)]:
995 return HookFailure('Only "%s:" tag(s) may follow the Change-Id.' %
996 ':", "'.join(allowed_tags))
Mike Frysinger02b88bd2014-11-21 00:29:38 -0500997
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700998
Mike Frysinger36b2ebc2014-10-31 14:02:03 -0400999def _check_commit_message_style(_project, commit):
1000 """Verify that the commit message matches our style.
1001
1002 We do not check for BUG=/TEST=/etc... lines here as that is handled by other
1003 commit hooks.
1004 """
1005 desc = _get_commit_desc(commit)
1006
1007 # The first line should be by itself.
1008 lines = desc.splitlines()
1009 if len(lines) > 1 and lines[1]:
1010 return HookFailure('The second line of the commit message must be blank.')
1011
1012 # The first line should be one sentence.
1013 if '. ' in lines[0]:
1014 return HookFailure('The first line cannot be more than one sentence.')
1015
1016 # The first line cannot be too long.
1017 MAX_FIRST_LINE_LEN = 100
1018 if len(lines[0]) > MAX_FIRST_LINE_LEN:
1019 return HookFailure('The first line must be less than %i chars.' %
1020 MAX_FIRST_LINE_LEN)
1021
1022
Filipe Brandenburger4b542b12015-10-09 12:46:31 -07001023def _check_cros_license(_project, commit, options=()):
Alex Deymof5792ce2015-08-24 22:50:08 -07001024 """Verifies the Chromium OS license/copyright header.
Ryan Cuiec4d6332011-05-02 14:15:25 -07001025
Mike Frysinger98638102014-08-28 00:15:08 -04001026 Should be following the spec:
1027 http://dev.chromium.org/developers/coding-style#TOC-File-headers
1028 """
1029 # For older years, be a bit more flexible as our policy says leave them be.
1030 LICENSE_HEADER = (
1031 r'.* Copyright( \(c\))? 20[-0-9]{2,7} The Chromium OS Authors\. '
Mike Frysingerb81102f2014-11-21 00:33:35 -05001032 r'All rights reserved\.' r'\n'
Mike Frysinger98638102014-08-28 00:15:08 -04001033 r'.* Use of this source code is governed by a BSD-style license that can '
Mike Frysingerb81102f2014-11-21 00:33:35 -05001034 r'be\n'
Mike Frysinger98638102014-08-28 00:15:08 -04001035 r'.* found in the LICENSE file\.'
Mike Frysingerb81102f2014-11-21 00:33:35 -05001036 r'\n'
Mike Frysinger98638102014-08-28 00:15:08 -04001037 )
1038 license_re = re.compile(LICENSE_HEADER, re.MULTILINE)
1039
1040 # For newer years, be stricter.
1041 COPYRIGHT_LINE = (
1042 r'.* Copyright \(c\) 20(1[5-9]|[2-9][0-9]) The Chromium OS Authors\. '
Mike Frysingerb81102f2014-11-21 00:33:35 -05001043 r'All rights reserved\.' r'\n'
Mike Frysinger98638102014-08-28 00:15:08 -04001044 )
1045 copyright_re = re.compile(COPYRIGHT_LINE)
1046
Shuhei Takahashiabc20f32017-07-10 19:35:45 +09001047 included, excluded = _parse_common_inclusion_options(options)
Filipe Brandenburger4b542b12015-10-09 12:46:31 -07001048
Mike Frysinger98638102014-08-28 00:15:08 -04001049 bad_files = []
1050 bad_copyright_files = []
Ken Turnerd07564b2018-02-08 17:57:59 +11001051 files = _filter_files(
1052 _get_affected_files(commit, relative=True),
1053 included + COMMON_INCLUDED_PATHS,
1054 excluded + COMMON_EXCLUDED_PATHS + LICENSE_EXCLUDED_PATHS)
Mike Frysinger98638102014-08-28 00:15:08 -04001055
1056 for f in files:
1057 contents = _get_file_content(f, commit)
1058 if not contents:
1059 # Ignore empty files.
1060 continue
1061
1062 if not license_re.search(contents):
1063 bad_files.append(f)
1064 elif copyright_re.search(contents):
1065 bad_copyright_files.append(f)
1066
1067 if bad_files:
1068 msg = '%s:\n%s\n%s' % (
1069 'License must match', license_re.pattern,
1070 'Found a bad header in these files:')
1071 return HookFailure(msg, bad_files)
1072
1073 if bad_copyright_files:
1074 msg = 'Do not use (c) in copyright headers in new files:'
1075 return HookFailure(msg, bad_copyright_files)
Ryan Cuiec4d6332011-05-02 14:15:25 -07001076
1077
Amin Hassani391efa92018-01-26 17:58:05 -08001078def _check_aosp_license(_project, commit, options=()):
Alex Deymof5792ce2015-08-24 22:50:08 -07001079 """Verifies the AOSP license/copyright header.
1080
1081 AOSP uses the Apache2 License:
1082 https://source.android.com/source/licenses.html
1083 """
1084 LICENSE_HEADER = (
1085 r"""^[#/\*]*
1086[#/\*]* ?Copyright( \([cC]\))? 20[-0-9]{2,7} The Android Open Source Project
1087[#/\*]* ?
1088[#/\*]* ?Licensed under the Apache License, Version 2.0 \(the "License"\);
1089[#/\*]* ?you may not use this file except in compliance with the License\.
1090[#/\*]* ?You may obtain a copy of the License at
1091[#/\*]* ?
1092[#/\*]* ? http://www\.apache\.org/licenses/LICENSE-2\.0
1093[#/\*]* ?
1094[#/\*]* ?Unless required by applicable law or agreed to in writing, software
1095[#/\*]* ?distributed under the License is distributed on an "AS IS" BASIS,
1096[#/\*]* ?WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or """
1097 r"""implied\.
1098[#/\*]* ?See the License for the specific language governing permissions and
1099[#/\*]* ?limitations under the License\.
1100[#/\*]*$
1101"""
1102 )
1103 license_re = re.compile(LICENSE_HEADER, re.MULTILINE)
1104
Amin Hassani391efa92018-01-26 17:58:05 -08001105 included, excluded = _parse_common_inclusion_options(options)
1106
Ken Turnerd07564b2018-02-08 17:57:59 +11001107 files = _filter_files(
1108 _get_affected_files(commit, relative=True),
1109 included + COMMON_INCLUDED_PATHS,
1110 excluded + COMMON_EXCLUDED_PATHS + LICENSE_EXCLUDED_PATHS)
Alex Deymof5792ce2015-08-24 22:50:08 -07001111
1112 bad_files = []
1113 for f in files:
1114 contents = _get_file_content(f, commit)
1115 if not contents:
1116 # Ignore empty files.
1117 continue
1118
1119 if not license_re.search(contents):
1120 bad_files.append(f)
1121
1122 if bad_files:
1123 msg = ('License must match:\n%s\nFound a bad header in these files:' %
1124 license_re.pattern)
1125 return HookFailure(msg, bad_files)
1126
1127
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001128def _check_layout_conf(_project, commit):
1129 """Verifies the metadata/layout.conf file."""
1130 repo_name = 'profiles/repo_name'
Mike Frysinger94a670c2014-09-19 12:46:26 -04001131 repo_names = []
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001132 layout_path = 'metadata/layout.conf'
Mike Frysinger94a670c2014-09-19 12:46:26 -04001133 layout_paths = []
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001134
Mike Frysinger94a670c2014-09-19 12:46:26 -04001135 # Handle multiple overlays in a single commit (like the public tree).
1136 for f in _get_affected_files(commit, relative=True):
1137 if f.endswith(repo_name):
1138 repo_names.append(f)
1139 elif f.endswith(layout_path):
1140 layout_paths.append(f)
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001141
1142 # Disallow new repos with the repo_name file.
Mike Frysinger94a670c2014-09-19 12:46:26 -04001143 if repo_names:
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001144 return HookFailure('%s: use "repo-name" in %s instead' %
Mike Frysinger94a670c2014-09-19 12:46:26 -04001145 (repo_names, layout_path))
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001146
Mike Frysinger94a670c2014-09-19 12:46:26 -04001147 # Gather all the errors in one pass so we show one full message.
1148 all_errors = {}
1149 for layout_path in layout_paths:
1150 all_errors[layout_path] = errors = []
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001151
Mike Frysinger94a670c2014-09-19 12:46:26 -04001152 # Make sure the config file is sorted.
1153 data = [x for x in _get_file_content(layout_path, commit).splitlines()
1154 if x and x[0] != '#']
1155 if sorted(data) != data:
1156 errors += ['keep lines sorted']
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001157
Mike Frysinger94a670c2014-09-19 12:46:26 -04001158 # Require people to set specific values all the time.
1159 settings = (
1160 # TODO: Enable this for everyone. http://crbug.com/408038
1161 #('fast caching', 'cache-format = md5-dict'),
1162 ('fast manifests', 'thin-manifests = true'),
Mike Frysingerd7734522015-02-26 16:12:43 -05001163 ('extra features', 'profile-formats = portage-2 profile-default-eapi'),
1164 ('newer eapi', 'profile_eapi_when_unspecified = 5-progress'),
Mike Frysinger94a670c2014-09-19 12:46:26 -04001165 )
1166 for reason, line in settings:
1167 if line not in data:
1168 errors += ['enable %s with: %s' % (reason, line)]
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001169
Mike Frysinger94a670c2014-09-19 12:46:26 -04001170 # Require one of these settings.
Mike Frysinger5fae62d2015-11-11 20:12:15 -05001171 if 'use-manifests = strict' not in data:
1172 errors += ['enable file checking with: use-manifests = strict']
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001173
Mike Frysinger94a670c2014-09-19 12:46:26 -04001174 # Require repo-name to be set.
Mike Frysinger324cf682014-09-22 15:52:50 -04001175 for line in data:
1176 if line.startswith('repo-name = '):
1177 break
1178 else:
Mike Frysinger94a670c2014-09-19 12:46:26 -04001179 errors += ['set the board name with: repo-name = $BOARD']
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001180
Mike Frysinger94a670c2014-09-19 12:46:26 -04001181 # Summarize all the errors we saw (if any).
1182 lines = ''
1183 for layout_path, errors in all_errors.items():
1184 if errors:
1185 lines += '\n\t- '.join(['\n* %s:' % layout_path] + errors)
1186 if lines:
1187 lines = 'See the portage(5) man page for layout.conf details' + lines + '\n'
1188 return HookFailure(lines)
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001189
1190
Ryan Cuiec4d6332011-05-02 14:15:25 -07001191# Project-specific hooks
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001192
Ryan Cui1562fb82011-05-09 11:01:31 -07001193
Luis Hector Chavezb50391d2017-09-26 15:48:15 -07001194def _check_clang_format(_project, commit, options=()):
1195 """Runs clang-format on the given project"""
1196 hooks_dir = _get_hooks_dir()
1197 options = list(options)
1198 if commit == PRE_SUBMIT:
1199 options.append('--commit=HEAD')
1200 else:
1201 options.extend(['--commit', commit])
1202 cmd = ['%s/clang-format.py' % hooks_dir] + options
1203 cmd_result = cros_build_lib.RunCommand(cmd=cmd,
1204 print_cmd=False,
1205 input=_get_patch(commit),
1206 stdout_to_pipe=True,
1207 combine_stdout_stderr=True,
1208 error_code_ok=True)
1209 if cmd_result.returncode:
1210 return HookFailure('clang-format.py errors/warnings\n\n' +
1211 cmd_result.output)
1212
1213
Mike Frysingerae409522014-02-01 03:16:11 -05001214def _run_checkpatch(_project, commit, options=()):
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001215 """Runs checkpatch.pl on the given project"""
1216 hooks_dir = _get_hooks_dir()
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001217 options = list(options)
1218 if commit == PRE_SUBMIT:
1219 # The --ignore option must be present and include 'MISSING_SIGN_OFF' in
1220 # this case.
1221 options.append('--ignore=MISSING_SIGN_OFF')
Filipe Brandenburger28d48d62015-10-07 09:48:54 -07001222 # Always ignore the check for the MAINTAINERS file. We do not track that
1223 # information on that file in our source trees, so let's suppress the
1224 # warning.
1225 options.append('--ignore=FILE_PATH_CHANGES')
Filipe Brandenburgerce978322015-10-09 10:04:15 -07001226 # Do not complain about the Change-Id: fields, since we use Gerrit.
1227 # Upstream does not want those lines (since they do not use Gerrit), but
1228 # we always do, so disable the check globally.
Daisuke Nojiri4844f892015-10-08 09:54:33 -07001229 options.append('--ignore=GERRIT_CHANGE_ID')
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001230 cmd = ['%s/checkpatch.pl' % hooks_dir] + options + ['-']
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001231 cmd_result = cros_build_lib.RunCommand(cmd=cmd,
1232 print_cmd=False,
1233 input=_get_patch(commit),
1234 stdout_to_pipe=True,
1235 combine_stdout_stderr=True,
1236 error_code_ok=True)
1237 if cmd_result.returncode:
1238 return HookFailure('checkpatch.pl errors/warnings\n\n' + cmd_result.output)
Ryan Cuiec4d6332011-05-02 14:15:25 -07001239
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001240
Mike Frysingerae409522014-02-01 03:16:11 -05001241def _kernel_configcheck(_project, commit):
Olof Johanssona96810f2012-09-04 16:20:03 -07001242 """Makes sure kernel config changes are not mixed with code changes"""
1243 files = _get_affected_files(commit)
1244 if not len(_filter_files(files, [r'chromeos/config'])) in [0, len(files)]:
1245 return HookFailure('Changes to chromeos/config/ and regular files must '
1246 'be in separate commits:\n%s' % '\n'.join(files))
Anton Staaf815d6852011-08-22 10:08:45 -07001247
Mike Frysingerae409522014-02-01 03:16:11 -05001248
1249def _run_json_check(_project, commit):
Dale Curtis2975c432011-05-03 17:25:20 -07001250 """Checks that all JSON files are syntactically valid."""
Dale Curtisa039cfd2011-05-04 12:01:05 -07001251 for f in _filter_files(_get_affected_files(commit), [r'.*\.json']):
Dale Curtis2975c432011-05-03 17:25:20 -07001252 try:
1253 json.load(open(f))
1254 except Exception, e:
Ryan Cui1562fb82011-05-09 11:01:31 -07001255 return HookFailure('Invalid JSON in %s: %s' % (f, e))
Dale Curtis2975c432011-05-03 17:25:20 -07001256
1257
Mike Frysingerae409522014-02-01 03:16:11 -05001258def _check_manifests(_project, commit):
Mike Frysingeraae3cb52018-01-03 16:49:33 -05001259 """Make sure Manifest files only have comments & DIST lines."""
1260 ret = []
Mike Frysinger52b537e2013-08-22 22:59:53 -04001261
Mike Frysingeraae3cb52018-01-03 16:49:33 -05001262 manifests = _filter_files(_get_affected_files(commit, relative=True),
1263 [r'.*/Manifest$'])
1264 for path in manifests:
1265 data = _get_file_content(path, commit)
1266
1267 # Disallow blank files.
1268 if not data.strip():
1269 ret.append('%s: delete empty file' % (path,))
Mike Frysinger52b537e2013-08-22 22:59:53 -04001270 continue
1271
Mike Frysingeraae3cb52018-01-03 16:49:33 -05001272 # Make sure the last newline isn't omitted.
1273 if data[-1] != '\n':
1274 ret.append('%s: missing trailing newline' % (path,))
Mike Frysinger52b537e2013-08-22 22:59:53 -04001275
Mike Frysingeraae3cb52018-01-03 16:49:33 -05001276 # Do not allow leading or trailing blank lines.
1277 lines = data.splitlines()
1278 if not lines[0]:
1279 ret.append('%s: delete leading blank lines' % (path,))
1280 if not lines[-1]:
1281 ret.append('%s: delete trailing blank lines' % (path,))
1282
1283 for line in lines:
1284 # Disallow leading/trailing whitespace.
1285 if line != line.strip():
1286 ret.append('%s: remove leading/trailing whitespace: %s' % (path, line))
1287
1288 # Allow blank lines & comments.
1289 line = line.split('#', 1)[0]
1290 if not line:
1291 continue
1292
1293 # All other linse should start with DIST.
1294 if not line.startswith('DIST '):
1295 ret.append('%s: remove non-DIST lines: %s' % (path, line))
1296 break
1297
1298 if ret:
1299 return HookFailure('\n'.join(ret))
Mike Frysinger52b537e2013-08-22 22:59:53 -04001300
1301
Mike Frysingerae409522014-02-01 03:16:11 -05001302def _check_change_has_branch_field(_project, commit):
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001303 """Check for a non-empty 'BRANCH=' field in the commit message."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001304 if commit == PRE_SUBMIT:
1305 return
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001306 BRANCH_RE = r'\nBRANCH=\S+'
1307
1308 if not re.search(BRANCH_RE, _get_commit_desc(commit)):
1309 msg = ('Changelist description needs BRANCH field (after first line)\n'
1310 'E.g. BRANCH=none or BRANCH=link,snow')
1311 return HookFailure(msg)
1312
1313
Mike Frysingerae409522014-02-01 03:16:11 -05001314def _check_change_has_signoff_field(_project, commit):
Shawn Nematbakhsh51e16ac2014-01-28 15:31:07 -08001315 """Check for a non-empty 'Signed-off-by:' field in the commit message."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001316 if commit == PRE_SUBMIT:
1317 return
Shawn Nematbakhsh51e16ac2014-01-28 15:31:07 -08001318 SIGNOFF_RE = r'\nSigned-off-by: \S+'
1319
1320 if not re.search(SIGNOFF_RE, _get_commit_desc(commit)):
1321 msg = ('Changelist description needs Signed-off-by: field\n'
1322 'E.g. Signed-off-by: My Name <me@chromium.org>')
1323 return HookFailure(msg)
1324
1325
Aviv Keshet5ac59522017-01-31 14:28:27 -08001326def _check_cq_ini_well_formed(_project, commit):
1327 """Check that any modified COMMIT-QUEUE.ini files are well formed."""
1328 pattern = '.*' + constants.CQ_CONFIG_FILENAME
Mike Frysingerd0523442018-01-03 17:05:29 -05001329 files = _filter_files(_get_affected_files(commit, relative=True), (pattern,))
Aviv Keshet5ac59522017-01-31 14:28:27 -08001330
1331 # TODO(akeshet): Check not only that the file is parseable, but that all the
1332 # pre-cq configs it requests are existing ones.
1333 for f in files:
1334 try:
1335 parser = ConfigParser.SafeConfigParser()
1336 # Prior to python3, ConfigParser has no read_string method, so we must
1337 # pass it either a file path or file like object. And we must use
1338 # _get_file_content to fetch file contents to ensure we are examining the
1339 # commit diff, rather than whatever's on disk.
1340 contents = _get_file_content(f, commit)
1341 parser.readfp(StringIO.StringIO(contents))
1342 except ConfigParser.Error as e:
1343 msg = ('Unable to parse COMMIT-QUEUE.ini file at %s due to %s.' %
1344 (f, e))
1345 return HookFailure(msg)
1346
1347
Jon Salz3ee59de2012-08-18 13:54:22 +08001348def _run_project_hook_script(script, project, commit):
1349 """Runs a project hook script.
1350
1351 The script is run with the following environment variables set:
1352 PRESUBMIT_PROJECT: The affected project
1353 PRESUBMIT_COMMIT: The affected commit
1354 PRESUBMIT_FILES: A newline-separated list of affected files
1355
1356 The script is considered to fail if the exit code is non-zero. It should
1357 write an error message to stdout.
1358 """
1359 env = dict(os.environ)
Alex Deymo643ac4c2015-09-03 10:40:50 -07001360 env['PRESUBMIT_PROJECT'] = project.name
Jon Salz3ee59de2012-08-18 13:54:22 +08001361 env['PRESUBMIT_COMMIT'] = commit
1362
1363 # Put affected files in an environment variable
1364 files = _get_affected_files(commit)
1365 env['PRESUBMIT_FILES'] = '\n'.join(files)
1366
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001367 cmd_result = cros_build_lib.RunCommand(cmd=script,
1368 env=env,
1369 shell=True,
1370 print_cmd=False,
1371 input=os.devnull,
1372 stdout_to_pipe=True,
1373 combine_stdout_stderr=True,
1374 error_code_ok=True)
1375 if cmd_result.returncode:
1376 stdout = cmd_result.output
Jon Salz7b618af2012-08-31 06:03:16 +08001377 if stdout:
1378 stdout = re.sub('(?m)^', ' ', stdout)
1379 return HookFailure('Hook script "%s" failed with code %d%s' %
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001380 (script, cmd_result.returncode,
Jon Salz3ee59de2012-08-18 13:54:22 +08001381 ':\n' + stdout if stdout else ''))
1382
1383
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001384def _check_project_prefix(_project, commit):
Mike Frysinger55f85b52014-12-18 14:45:21 -05001385 """Require the commit message have a project specific prefix as needed."""
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001386
1387 files = _get_affected_files(commit, relative=True)
1388 prefix = os.path.commonprefix(files)
1389 prefix = os.path.dirname(prefix)
1390
1391 # If there is no common prefix, the CL span multiple projects.
Daniel Erata350fd32014-09-29 14:02:34 -07001392 if not prefix:
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001393 return
1394
1395 project_name = prefix.split('/')[0]
Daniel Erata350fd32014-09-29 14:02:34 -07001396
1397 # The common files may all be within a subdirectory of the main project
1398 # directory, so walk up the tree until we find an alias file.
1399 # _get_affected_files() should return relative paths, but check against '/' to
1400 # ensure that this loop terminates even if it receives an absolute path.
1401 while prefix and prefix != '/':
1402 alias_file = os.path.join(prefix, '.project_alias')
1403
1404 # If an alias exists, use it.
1405 if os.path.isfile(alias_file):
1406 project_name = osutils.ReadFile(alias_file).strip()
1407
1408 prefix = os.path.dirname(prefix)
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001409
1410 if not _get_commit_desc(commit).startswith(project_name + ': '):
1411 return HookFailure('The commit title for changes affecting only %s'
1412 ' should start with \"%s: \"'
1413 % (project_name, project_name))
1414
1415
Mike Frysingerf9d41b32017-02-23 15:20:04 -05001416def _check_exec_files(_project, commit):
1417 """Make +x bits on files."""
1418 # List of files that should never be +x.
1419 NO_EXEC = (
1420 'ChangeLog*',
1421 'COPYING',
1422 'make.conf',
1423 'make.defaults',
1424 'Manifest',
1425 'OWNERS',
1426 'package.use',
1427 'package.keywords',
1428 'package.mask',
1429 'parent',
1430 'README',
1431 'TODO',
1432 '.gitignore',
1433 '*.[achly]',
1434 '*.[ch]xx',
1435 '*.boto',
1436 '*.cc',
1437 '*.cfg',
1438 '*.conf',
1439 '*.config',
1440 '*.cpp',
1441 '*.css',
1442 '*.ebuild',
1443 '*.eclass',
1444 '*.gyp',
1445 '*.gypi',
1446 '*.htm',
1447 '*.html',
1448 '*.ini',
1449 '*.js',
1450 '*.json',
1451 '*.md',
1452 '*.mk',
1453 '*.patch',
1454 '*.policy',
1455 '*.proto',
1456 '*.raw',
1457 '*.rules',
1458 '*.service',
1459 '*.target',
1460 '*.txt',
1461 '*.xml',
1462 '*.yaml',
1463 )
1464
1465 def FinalName(obj):
1466 # If the file is being deleted, then the dst_file is not set.
1467 if obj.dst_file is None:
1468 return obj.src_file
1469 else:
1470 return obj.dst_file
1471
1472 bad_files = []
1473 files = _get_affected_files(commit, relative=True, full_details=True)
1474 for f in files:
1475 mode = int(f.dst_mode, 8)
1476 if not mode & 0o111:
1477 continue
1478 name = FinalName(f)
1479 for no_exec in NO_EXEC:
1480 if fnmatch.fnmatch(name, no_exec):
1481 bad_files.append(name)
1482 break
1483
1484 if bad_files:
1485 return HookFailure('These files should not be executable. '
1486 'Please `chmod -x` them.', bad_files)
1487
1488
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001489# Base
1490
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001491# A list of hooks which are not project specific and check patch description
1492# (as opposed to patch body).
1493_PATCH_DESCRIPTION_HOOKS = [
Ryan Cui9b651632011-05-11 11:38:58 -07001494 _check_change_has_bug_field,
David Jamesc3b68b32013-04-03 09:17:03 -07001495 _check_change_has_valid_cq_depend,
Ryan Cui9b651632011-05-11 11:38:58 -07001496 _check_change_has_test_field,
1497 _check_change_has_proper_changeid,
Mike Frysinger36b2ebc2014-10-31 14:02:03 -04001498 _check_commit_message_style,
Bernie Thompsonf8fea992016-01-14 10:27:18 -08001499 _check_change_is_contribution,
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001500]
1501
1502
1503# A list of hooks that are not project-specific
1504_COMMON_HOOKS = [
Aviv Keshet5ac59522017-01-31 14:28:27 -08001505 _check_cq_ini_well_formed,
1506 _check_cros_license,
Mike Frysingerbf8b91c2014-02-01 02:50:27 -05001507 _check_ebuild_eapi,
Mike Frysinger89bdb852014-02-01 05:26:26 -05001508 _check_ebuild_keywords,
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -08001509 _check_ebuild_licenses,
Mike Frysingercd363c82014-02-01 05:20:18 -05001510 _check_ebuild_virtual_pv,
Mike Frysingerf9d41b32017-02-23 15:20:04 -05001511 _check_exec_files,
Daniel Erat9d203ff2015-02-17 10:12:21 -07001512 _check_for_uprev,
Rahul Chaudhry09f61372015-07-31 17:14:26 -07001513 _check_gofmt,
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001514 _check_layout_conf,
Daniel Erat9d203ff2015-02-17 10:12:21 -07001515 _check_no_long_lines,
1516 _check_no_stray_whitespace,
Ryan Cui9b651632011-05-11 11:38:58 -07001517 _check_no_tabs,
Daniel Erat9d203ff2015-02-17 10:12:21 -07001518 _check_portage_make_use_var,
Aviv Keshet5ac59522017-01-31 14:28:27 -08001519 _check_tabbed_indents,
Ryan Cui9b651632011-05-11 11:38:58 -07001520]
Ryan Cuiec4d6332011-05-02 14:15:25 -07001521
Ryan Cui1562fb82011-05-09 11:01:31 -07001522
Ryan Cui9b651632011-05-11 11:38:58 -07001523# A dictionary of project-specific hooks(callbacks), indexed by project name.
1524# dict[project] = [callback1, callback2]
1525_PROJECT_SPECIFIC_HOOKS = {
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001526 "chromiumos/platform2": [_check_project_prefix],
Mike Frysingeraf891292015-03-25 19:46:53 -04001527 "chromiumos/third_party/kernel": [_kernel_configcheck],
1528 "chromiumos/third_party/kernel-next": [_kernel_configcheck],
Ryan Cui9b651632011-05-11 11:38:58 -07001529}
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001530
Ryan Cui1562fb82011-05-09 11:01:31 -07001531
Ryan Cui9b651632011-05-11 11:38:58 -07001532# A dictionary of flags (keys) that can appear in the config file, and the hook
Mike Frysinger3554bc92015-03-11 04:59:21 -04001533# that the flag controls (value).
1534_HOOK_FLAGS = {
Luis Hector Chavezb50391d2017-09-26 15:48:15 -07001535 'clang_format_check': _check_clang_format,
Mike Frysingera7642f52015-03-25 18:31:42 -04001536 'checkpatch_check': _run_checkpatch,
Ryan Cui9b651632011-05-11 11:38:58 -07001537 'stray_whitespace_check': _check_no_stray_whitespace,
Mike Frysingerff6c7d62015-03-24 13:49:46 -04001538 'json_check': _run_json_check,
Ryan Cui9b651632011-05-11 11:38:58 -07001539 'long_line_check': _check_no_long_lines,
Alex Deymof5792ce2015-08-24 22:50:08 -07001540 'cros_license_check': _check_cros_license,
1541 'aosp_license_check': _check_aosp_license,
Ryan Cui9b651632011-05-11 11:38:58 -07001542 'tab_check': _check_no_tabs,
Prathmesh Prabhuc5254652016-12-22 12:58:05 -08001543 'tabbed_indent_required_check': _check_tabbed_indents,
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001544 'branch_check': _check_change_has_branch_field,
Shawn Nematbakhsh51e16ac2014-01-28 15:31:07 -08001545 'signoff_check': _check_change_has_signoff_field,
Josh Triplett0e8fc7f2014-04-23 16:00:00 -07001546 'bug_field_check': _check_change_has_bug_field,
1547 'test_field_check': _check_change_has_test_field,
Steve Fung49ec7e92015-03-23 16:07:12 -07001548 'manifest_check': _check_manifests,
Bernie Thompsonf8fea992016-01-14 10:27:18 -08001549 'contribution_check': _check_change_is_contribution,
Ryan Cui9b651632011-05-11 11:38:58 -07001550}
1551
1552
Mike Frysinger3554bc92015-03-11 04:59:21 -04001553def _get_override_hooks(config):
1554 """Returns a set of hooks controlled by the current project's config file.
Ryan Cui9b651632011-05-11 11:38:58 -07001555
1556 Expects to be called within the project root.
Jon Salz3ee59de2012-08-18 13:54:22 +08001557
1558 Args:
1559 config: A ConfigParser for the project's config file.
Ryan Cui9b651632011-05-11 11:38:58 -07001560 """
1561 SECTION = 'Hook Overrides'
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001562 SECTION_OPTIONS = 'Hook Overrides Options'
Jon Salz3ee59de2012-08-18 13:54:22 +08001563 if not config.has_section(SECTION):
Mike Frysinger3554bc92015-03-11 04:59:21 -04001564 return set(), set()
Ryan Cui9b651632011-05-11 11:38:58 -07001565
Mike Frysinger3554bc92015-03-11 04:59:21 -04001566 valid_keys = set(_HOOK_FLAGS.iterkeys())
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001567 hooks = _HOOK_FLAGS.copy()
Mike Frysinger3554bc92015-03-11 04:59:21 -04001568
1569 enable_flags = []
Ryan Cui9b651632011-05-11 11:38:58 -07001570 disable_flags = []
Jon Salz3ee59de2012-08-18 13:54:22 +08001571 for flag in config.options(SECTION):
Mike Frysinger3554bc92015-03-11 04:59:21 -04001572 if flag not in valid_keys:
1573 raise ValueError('Error: unknown key "%s" in hook section of "%s"' %
1574 (flag, _CONFIG_FILE))
1575
Ryan Cui9b651632011-05-11 11:38:58 -07001576 try:
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001577 enabled = config.getboolean(SECTION, flag)
Ryan Cui9b651632011-05-11 11:38:58 -07001578 except ValueError as e:
Mike Frysinger3554bc92015-03-11 04:59:21 -04001579 raise ValueError('Error: parsing flag "%s" in "%s" failed: %s' %
1580 (flag, _CONFIG_FILE, e))
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001581 if enabled:
1582 enable_flags.append(flag)
1583 else:
1584 disable_flags.append(flag)
Ryan Cui9b651632011-05-11 11:38:58 -07001585
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001586 # See if this hook has custom options.
1587 if enabled:
1588 try:
1589 options = config.get(SECTION_OPTIONS, flag)
1590 hooks[flag] = functools.partial(hooks[flag], options=options.split())
Mike Frysingerb7d552e2017-11-23 11:50:47 -05001591 hooks[flag].__name__ = flag
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001592 except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
1593 pass
1594
1595 enabled_hooks = set(hooks[x] for x in enable_flags)
1596 disabled_hooks = set(hooks[x] for x in disable_flags)
Mike Frysinger3554bc92015-03-11 04:59:21 -04001597 return enabled_hooks, disabled_hooks
Ryan Cui9b651632011-05-11 11:38:58 -07001598
1599
Jon Salz3ee59de2012-08-18 13:54:22 +08001600def _get_project_hook_scripts(config):
1601 """Returns a list of project-specific hook scripts.
1602
1603 Args:
1604 config: A ConfigParser for the project's config file.
1605 """
1606 SECTION = 'Hook Scripts'
1607 if not config.has_section(SECTION):
1608 return []
1609
Mike Frysingerb7d552e2017-11-23 11:50:47 -05001610 return config.items(SECTION)
Jon Salz3ee59de2012-08-18 13:54:22 +08001611
1612
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001613def _get_project_hooks(project, presubmit):
Ryan Cui9b651632011-05-11 11:38:58 -07001614 """Returns a list of hooks that need to be run for a project.
1615
1616 Expects to be called from within the project root.
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001617
1618 Args:
1619 project: A string, name of the project.
1620 presubmit: A Boolean, True if the check is run as a git pre-submit script.
Ryan Cui9b651632011-05-11 11:38:58 -07001621 """
Jon Salz3ee59de2012-08-18 13:54:22 +08001622 config = ConfigParser.RawConfigParser()
1623 try:
1624 config.read(_CONFIG_FILE)
1625 except ConfigParser.Error:
1626 # Just use an empty config file
1627 config = ConfigParser.RawConfigParser()
1628
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001629 if presubmit:
Filipe Brandenburgerf70d32c2015-10-09 13:35:45 -07001630 hooks = _COMMON_HOOKS
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001631 else:
Filipe Brandenburgerf70d32c2015-10-09 13:35:45 -07001632 hooks = _PATCH_DESCRIPTION_HOOKS + _COMMON_HOOKS
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001633
Mike Frysinger3554bc92015-03-11 04:59:21 -04001634 enabled_hooks, disabled_hooks = _get_override_hooks(config)
Filipe Brandenburgerf70d32c2015-10-09 13:35:45 -07001635 hooks = [hook for hook in hooks if hook not in disabled_hooks]
1636
1637 # If a list is both in _COMMON_HOOKS and also enabled explicitly through an
1638 # override, keep the override only. Note that the override may end up being
1639 # a functools.partial, in which case we need to extract the .func to compare
1640 # it to the common hooks.
1641 unwrapped_hooks = [getattr(hook, 'func', hook) for hook in enabled_hooks]
1642 hooks = [hook for hook in hooks if hook not in unwrapped_hooks]
1643
1644 hooks = list(enabled_hooks) + hooks
Ryan Cui9b651632011-05-11 11:38:58 -07001645
1646 if project in _PROJECT_SPECIFIC_HOOKS:
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001647 hooks.extend(hook for hook in _PROJECT_SPECIFIC_HOOKS[project]
1648 if hook not in disabled_hooks)
Ryan Cui9b651632011-05-11 11:38:58 -07001649
Mike Frysingerb7d552e2017-11-23 11:50:47 -05001650 for name, script in _get_project_hook_scripts(config):
1651 func = functools.partial(_run_project_hook_script, script)
1652 func.__name__ = name
1653 hooks.append(func)
Jon Salz3ee59de2012-08-18 13:54:22 +08001654
Ryan Cui9b651632011-05-11 11:38:58 -07001655 return hooks
1656
1657
Alex Deymo643ac4c2015-09-03 10:40:50 -07001658def _run_project_hooks(project_name, proj_dir=None,
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001659 commit_list=None, presubmit=False):
Ryan Cui1562fb82011-05-09 11:01:31 -07001660 """For each project run its project specific hook from the hooks dictionary.
1661
1662 Args:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001663 project_name: The name of project to run hooks for.
Doug Anderson44a644f2011-11-02 10:37:37 -07001664 proj_dir: If non-None, this is the directory the project is in. If None,
1665 we'll ask repo.
Doug Anderson14749562013-06-26 13:38:29 -07001666 commit_list: A list of commits to run hooks against. If None or empty list
1667 then we'll automatically get the list of commits that would be uploaded.
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001668 presubmit: A Boolean, True if the check is run as a git pre-submit script.
Ryan Cui1562fb82011-05-09 11:01:31 -07001669
1670 Returns:
1671 Boolean value of whether any errors were ecountered while running the hooks.
1672 """
Doug Anderson44a644f2011-11-02 10:37:37 -07001673 if proj_dir is None:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001674 proj_dirs = _run_command(
1675 ['repo', 'forall', project_name, '-c', 'pwd']).split()
David James2edd9002013-10-11 14:09:19 -07001676 if len(proj_dirs) == 0:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001677 print('%s cannot be found.' % project_name, file=sys.stderr)
David James2edd9002013-10-11 14:09:19 -07001678 print('Please specify a valid project.', file=sys.stderr)
1679 return True
1680 if len(proj_dirs) > 1:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001681 print('%s is associated with multiple directories.' % project_name,
David James2edd9002013-10-11 14:09:19 -07001682 file=sys.stderr)
1683 print('Please specify a directory to help disambiguate.', file=sys.stderr)
1684 return True
1685 proj_dir = proj_dirs[0]
Doug Anderson44a644f2011-11-02 10:37:37 -07001686
Ryan Cuiec4d6332011-05-02 14:15:25 -07001687 pwd = os.getcwd()
1688 # hooks assume they are run from the root of the project
1689 os.chdir(proj_dir)
1690
Alex Deymo643ac4c2015-09-03 10:40:50 -07001691 remote_branch = _run_command(['git', 'rev-parse', '--abbrev-ref',
1692 '--symbolic-full-name', '@{u}']).strip()
1693 if not remote_branch:
1694 print('Your project %s doesn\'t track any remote repo.' % project_name,
1695 file=sys.stderr)
1696 remote = None
1697 else:
1698 remote, _branch = remote_branch.split('/', 1)
1699
1700 project = Project(name=project_name, dir=proj_dir, remote=remote)
1701
Doug Anderson14749562013-06-26 13:38:29 -07001702 if not commit_list:
1703 try:
1704 commit_list = _get_commits()
1705 except VerifyException as e:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001706 PrintErrorForProject(project.name, HookFailure(str(e)))
Doug Anderson14749562013-06-26 13:38:29 -07001707 os.chdir(pwd)
1708 return True
Ryan Cuifa55df52011-05-06 11:16:55 -07001709
Alex Deymo643ac4c2015-09-03 10:40:50 -07001710 hooks = _get_project_hooks(project.name, presubmit)
Ryan Cui1562fb82011-05-09 11:01:31 -07001711 error_found = False
Mike Frysingerb7d552e2017-11-23 11:50:47 -05001712 commit_count = len(commit_list)
1713 for i, commit in enumerate(commit_list):
Ryan Cui1562fb82011-05-09 11:01:31 -07001714 error_list = []
Ryan Cui9b651632011-05-11 11:38:58 -07001715 for hook in hooks:
Mike Frysingerb7d552e2017-11-23 11:50:47 -05001716 output = ('PRESUBMIT.cfg: [%i/%i]: %s: Running %s' %
1717 (i + 1, commit_count, commit, hook.__name__))
1718 print(output, end='\r')
1719 sys.stdout.flush()
Ryan Cui1562fb82011-05-09 11:01:31 -07001720 hook_error = hook(project, commit)
Mike Frysingerb7d552e2017-11-23 11:50:47 -05001721 print(' ' * len(output), end='\r')
1722 sys.stdout.flush()
Ryan Cui1562fb82011-05-09 11:01:31 -07001723 if hook_error:
1724 error_list.append(hook_error)
1725 error_found = True
1726 if error_list:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001727 PrintErrorsForCommit(project.name, commit, _get_commit_desc(commit),
Ryan Cui1562fb82011-05-09 11:01:31 -07001728 error_list)
Don Garrettdba548a2011-05-05 15:17:14 -07001729
Ryan Cuiec4d6332011-05-02 14:15:25 -07001730 os.chdir(pwd)
Ryan Cui1562fb82011-05-09 11:01:31 -07001731 return error_found
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001732
Mike Frysingerae409522014-02-01 03:16:11 -05001733
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001734# Main
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -07001735
Ryan Cui1562fb82011-05-09 11:01:31 -07001736
Mike Frysingerae409522014-02-01 03:16:11 -05001737def main(project_list, worktree_list=None, **_kwargs):
Doug Anderson06456632012-01-05 11:02:14 -08001738 """Main function invoked directly by repo.
1739
1740 This function will exit directly upon error so that repo doesn't print some
1741 obscure error message.
1742
1743 Args:
1744 project_list: List of projects to run on.
David James2edd9002013-10-11 14:09:19 -07001745 worktree_list: A list of directories. It should be the same length as
1746 project_list, so that each entry in project_list matches with a directory
1747 in worktree_list. If None, we will attempt to calculate the directories
1748 automatically.
Doug Anderson06456632012-01-05 11:02:14 -08001749 kwargs: Leave this here for forward-compatibility.
1750 """
Ryan Cui1562fb82011-05-09 11:01:31 -07001751 found_error = False
David James2edd9002013-10-11 14:09:19 -07001752 if not worktree_list:
1753 worktree_list = [None] * len(project_list)
1754 for project, worktree in zip(project_list, worktree_list):
1755 if _run_project_hooks(project, proj_dir=worktree):
Ryan Cui1562fb82011-05-09 11:01:31 -07001756 found_error = True
1757
Mike Frysingerae409522014-02-01 03:16:11 -05001758 if found_error:
Ryan Cui1562fb82011-05-09 11:01:31 -07001759 msg = ('Preupload failed due to errors in project(s). HINTS:\n'
Ryan Cui9b651632011-05-11 11:38:58 -07001760 '- To disable some source style checks, and for other hints, see '
1761 '<checkout_dir>/src/repohooks/README\n'
1762 '- To upload only current project, run \'repo upload .\'')
Mike Frysinger09d6a3d2013-10-08 22:21:03 -04001763 print(msg, file=sys.stderr)
Don Garrettdba548a2011-05-05 15:17:14 -07001764 sys.exit(1)
Anush Elangovan63afad72011-03-23 00:41:27 -07001765
Ryan Cui1562fb82011-05-09 11:01:31 -07001766
Doug Anderson44a644f2011-11-02 10:37:37 -07001767def _identify_project(path):
1768 """Identify the repo project associated with the given path.
1769
1770 Returns:
1771 A string indicating what project is associated with the path passed in or
1772 a blank string upon failure.
1773 """
1774 return _run_command(['repo', 'forall', '.', '-c', 'echo ${REPO_PROJECT}'],
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001775 redirect_stderr=True, cwd=path).strip()
Doug Anderson44a644f2011-11-02 10:37:37 -07001776
1777
Mike Frysinger55f85b52014-12-18 14:45:21 -05001778def direct_main(argv):
Doug Anderson44a644f2011-11-02 10:37:37 -07001779 """Run hooks directly (outside of the context of repo).
1780
Doug Anderson44a644f2011-11-02 10:37:37 -07001781 Args:
Mike Frysinger55f85b52014-12-18 14:45:21 -05001782 argv: The command line args to process
Doug Anderson44a644f2011-11-02 10:37:37 -07001783
1784 Returns:
1785 0 if no pre-upload failures, 1 if failures.
1786
1787 Raises:
1788 BadInvocation: On some types of invocation errors.
1789 """
Mike Frysinger66142932014-12-18 14:55:57 -05001790 parser = commandline.ArgumentParser(description=__doc__)
1791 parser.add_argument('--dir', default=None,
1792 help='The directory that the project lives in. If not '
1793 'specified, use the git project root based on the cwd.')
1794 parser.add_argument('--project', default=None,
1795 help='The project repo path; this can affect how the '
1796 'hooks get run, since some hooks are project-specific. '
1797 'For chromite this is chromiumos/chromite. If not '
1798 'specified, the repo tool will be used to figure this '
1799 'out based on the dir.')
1800 parser.add_argument('--rerun-since', default=None,
Vadim Bendebury75447b92018-01-10 12:06:01 -08001801 help='Rerun hooks on old commits since some point '
1802 'in the past. The argument could be a date (should '
1803 'match git log\'s concept of a date, e.g. 2012-06-20), '
1804 'or a SHA1, or just a number of commits to check (from 1 '
1805 'to 99). This option is mutually exclusive with '
1806 '--pre-submit.')
Mike Frysinger66142932014-12-18 14:55:57 -05001807 parser.add_argument('--pre-submit', action="store_true",
1808 help='Run the check against the pending commit. '
1809 'This option should be used at the \'git commit\' '
1810 'phase as opposed to \'repo upload\'. This option '
1811 'is mutually exclusive with --rerun-since.')
1812 parser.add_argument('commits', nargs='*',
1813 help='Check specific commits')
1814 opts = parser.parse_args(argv)
Doug Anderson44a644f2011-11-02 10:37:37 -07001815
Doug Anderson14749562013-06-26 13:38:29 -07001816 if opts.rerun_since:
Mike Frysinger66142932014-12-18 14:55:57 -05001817 if opts.commits:
Doug Anderson14749562013-06-26 13:38:29 -07001818 raise BadInvocation('Can\'t pass commits and use rerun-since: %s' %
Mike Frysinger66142932014-12-18 14:55:57 -05001819 ' '.join(opts.commits))
Doug Anderson14749562013-06-26 13:38:29 -07001820
Vadim Bendebury75447b92018-01-10 12:06:01 -08001821 if len(opts.rerun_since) < 3 and opts.rerun_since.isdigit():
1822 # This must be the number of commits to check. We don't expect the user
1823 # to want to check more than 99 commits.
1824 limit = '-n%s' % opts.rerun_since
1825 elif git.IsSHA1(opts.rerun_since, False):
1826 limit = '%s..' % opts.rerun_since
1827 else:
1828 # This better be a date.
1829 limit = '--since=%s' % opts.rerun_since
1830 cmd = ['git', 'log', limit, '--pretty=%H']
Doug Anderson14749562013-06-26 13:38:29 -07001831 all_commits = _run_command(cmd).splitlines()
1832 bot_commits = _run_command(cmd + ['--author=chrome-bot']).splitlines()
1833
1834 # Eliminate chrome-bot commits but keep ordering the same...
1835 bot_commits = set(bot_commits)
Mike Frysinger66142932014-12-18 14:55:57 -05001836 opts.commits = [c for c in all_commits if c not in bot_commits]
Doug Anderson14749562013-06-26 13:38:29 -07001837
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001838 if opts.pre_submit:
1839 raise BadInvocation('rerun-since and pre-submit can not be '
1840 'used together')
1841 if opts.pre_submit:
Mike Frysinger66142932014-12-18 14:55:57 -05001842 if opts.commits:
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001843 raise BadInvocation('Can\'t pass commits and use pre-submit: %s' %
Mike Frysinger66142932014-12-18 14:55:57 -05001844 ' '.join(opts.commits))
1845 opts.commits = [PRE_SUBMIT,]
Doug Anderson44a644f2011-11-02 10:37:37 -07001846
1847 # Check/normlaize git dir; if unspecified, we'll use the root of the git
1848 # project from CWD
1849 if opts.dir is None:
1850 git_dir = _run_command(['git', 'rev-parse', '--git-dir'],
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001851 redirect_stderr=True).strip()
Doug Anderson44a644f2011-11-02 10:37:37 -07001852 if not git_dir:
1853 raise BadInvocation('The current directory is not part of a git project.')
1854 opts.dir = os.path.dirname(os.path.abspath(git_dir))
1855 elif not os.path.isdir(opts.dir):
1856 raise BadInvocation('Invalid dir: %s' % opts.dir)
1857 elif not os.path.isdir(os.path.join(opts.dir, '.git')):
1858 raise BadInvocation('Not a git directory: %s' % opts.dir)
1859
1860 # Identify the project if it wasn't specified; this _requires_ the repo
1861 # tool to be installed and for the project to be part of a repo checkout.
1862 if not opts.project:
1863 opts.project = _identify_project(opts.dir)
1864 if not opts.project:
1865 raise BadInvocation("Repo couldn't identify the project of %s" % opts.dir)
1866
Doug Anderson14749562013-06-26 13:38:29 -07001867 found_error = _run_project_hooks(opts.project, proj_dir=opts.dir,
Mike Frysinger66142932014-12-18 14:55:57 -05001868 commit_list=opts.commits,
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001869 presubmit=opts.pre_submit)
Doug Anderson44a644f2011-11-02 10:37:37 -07001870 if found_error:
1871 return 1
1872 return 0
1873
1874
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -07001875if __name__ == '__main__':
Mike Frysinger55f85b52014-12-18 14:45:21 -05001876 sys.exit(direct_main(sys.argv[1:]))