blob: 4baf40e44ad6a2ccd2222d23c0de01d9d833691d [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
Keigo Okadd908822019-06-04 11:30:25 +090014import 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
Mike Frysinger6850d512018-05-21 12:12:14 -040029# If repo imports us, the __name__ will be __builtin__, and the cwd will be in
30# the top level of the checkout (i.e. $CHROMEOS_CHECKOUT). chromite will be in
31# that directory, so add it to our path. This works whether we're running the
32# repo in $CHROMEOS_CHECKOUT/.repo/repo/ or a custom version in a completely
33# different tree.
34if __name__ == '__builtin__':
35 sys.path.insert(0, os.getcwd())
36
37# If we're run directly, we'll find chromite relative to the repohooks dir in
38# $CHROMEOS_CHECKOUT/src/repohooks, so go up two dirs.
39if __name__ == '__main__':
David Jamesc3b68b32013-04-03 09:17:03 -070040 sys.path.insert(0, os.path.join(os.path.dirname(sys.argv[0]), '..', '..'))
41
Mike Frysinger66142932014-12-18 14:55:57 -050042from chromite.lib import commandline
Aviv Keshet5ac59522017-01-31 14:28:27 -080043from chromite.lib import constants
Rahul Chaudhry0e515342015-08-07 12:00:43 -070044from chromite.lib import cros_build_lib
Mike Frysingerd3bd32c2014-11-24 23:34:29 -050045from chromite.lib import git
Daniel Erata350fd32014-09-29 14:02:34 -070046from chromite.lib import osutils
David Jamesc3b68b32013-04-03 09:17:03 -070047from chromite.lib import patch
Mike Frysinger2ec70ed2014-08-17 19:28:34 -040048from chromite.licensing import licenses_lib
David Jamesc3b68b32013-04-03 09:17:03 -070049
Vadim Bendebury2b62d742014-06-22 13:14:51 -070050PRE_SUBMIT = 'pre-submit'
Ryan Cuiec4d6332011-05-02 14:15:25 -070051
52COMMON_INCLUDED_PATHS = [
Mike Frysingerae409522014-02-01 03:16:11 -050053 # C++ and friends
54 r".*\.c$", r".*\.cc$", r".*\.cpp$", r".*\.h$", r".*\.m$", r".*\.mm$",
55 r".*\.inl$", r".*\.asm$", r".*\.hxx$", r".*\.hpp$", r".*\.s$", r".*\.S$",
56 # Scripts
57 r".*\.js$", r".*\.py$", r".*\.sh$", r".*\.rb$", r".*\.pl$", r".*\.pm$",
58 # No extension at all, note that ALL CAPS files are black listed in
59 # COMMON_EXCLUDED_LIST below.
60 r"(^|.*[\\\/])[^.]+$",
61 # Other
62 r".*\.java$", r".*\.mk$", r".*\.am$",
Brian Norrisfdbac8e2016-06-16 11:09:05 -070063 r".*\.policy$", r".*\.conf$",
Ryan Cuiec4d6332011-05-02 14:15:25 -070064]
65
Ryan Cui1562fb82011-05-09 11:01:31 -070066
Ryan Cuiec4d6332011-05-02 14:15:25 -070067COMMON_EXCLUDED_PATHS = [
Daniel Erate3ea3fc2015-02-13 15:27:52 -070068 # For ebuild trees, ignore any caches and manifest data.
Mike Frysingerae409522014-02-01 03:16:11 -050069 r".*/Manifest$",
70 r".*/metadata/[^/]*cache[^/]*/[^/]+/[^/]+$",
Doug Anderson5bfb6792011-10-25 16:45:41 -070071
Daniel Erate3ea3fc2015-02-13 15:27:52 -070072 # Ignore profiles data (like overlay-tegra2/profiles).
Mike Frysinger94a670c2014-09-19 12:46:26 -040073 r"(^|.*/)overlay-.*/profiles/.*",
Mike Frysinger98638102014-08-28 00:15:08 -040074 r"^profiles/.*$",
75
C Shapiro8f90e9b2017-06-28 09:54:50 -060076 # Ignore config files in ebuild setup.
77 r"(^|.*/)overlay-.*/chromeos-base/chromeos-bsp.*/files/.*",
78 r"^chromeos-base/chromeos-bsp.*/files/.*",
79
Daniel Erate3ea3fc2015-02-13 15:27:52 -070080 # Ignore minified js and jquery.
Mike Frysingerae409522014-02-01 03:16:11 -050081 r".*\.min\.js",
82 r".*jquery.*\.js",
Mike Frysinger33a458d2014-03-03 17:00:51 -050083
84 # Ignore license files as the content is often taken verbatim.
Daniel Erate3ea3fc2015-02-13 15:27:52 -070085 r".*/licenses/.*",
Alex Klein619c0912019-01-30 17:13:23 -070086
87 # Exclude generated python protobuf files.
88 r".*_pb2\.py$",
Ryan Cuiec4d6332011-05-02 14:15:25 -070089]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070090
Ken Turnerd07564b2018-02-08 17:57:59 +110091LICENSE_EXCLUDED_PATHS = [
Chris McDonald7b63c8e2019-04-25 10:27:27 -060092 r"^(.*/)?OWNERS$",
Ken Turnerd07564b2018-02-08 17:57:59 +110093]
Ryan Cui1562fb82011-05-09 11:01:31 -070094
Ryan Cui9b651632011-05-11 11:38:58 -070095_CONFIG_FILE = 'PRESUBMIT.cfg'
96
97
Daniel Erate3ea3fc2015-02-13 15:27:52 -070098# File containing wildcards, one per line, matching files that should be
99# excluded from presubmit checks. Lines beginning with '#' are ignored.
100_IGNORE_FILE = '.presubmitignore'
101
Doug Anderson44a644f2011-11-02 10:37:37 -0700102# Exceptions
103
104
105class BadInvocation(Exception):
106 """An Exception indicating a bad invocation of the program."""
107 pass
108
109
Ryan Cui1562fb82011-05-09 11:01:31 -0700110# General Helpers
111
Sean Paulba01d402011-05-05 11:36:23 -0400112
Alex Deymo643ac4c2015-09-03 10:40:50 -0700113Project = collections.namedtuple('Project', ['name', 'dir', 'remote'])
114
115
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700116# pylint: disable=redefined-builtin
117def _run_command(cmd, cwd=None, input=None,
118 redirect_stderr=False, combine_stdout_stderr=False):
Doug Anderson44a644f2011-11-02 10:37:37 -0700119 """Executes the passed in command and returns raw stdout output.
120
121 Args:
122 cmd: The command to run; should be a list of strings.
123 cwd: The directory to switch to for running the command.
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700124 input: The data to pipe into this command through stdin. If a file object
125 or file descriptor, stdin will be connected directly to that.
126 redirect_stderr: Redirect stderr away from console.
127 combine_stdout_stderr: Combines stdout and stderr streams into stdout.
Doug Anderson44a644f2011-11-02 10:37:37 -0700128
129 Returns:
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700130 The stdout from the process (discards stderr and returncode).
Doug Anderson44a644f2011-11-02 10:37:37 -0700131 """
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700132 return cros_build_lib.RunCommand(cmd=cmd,
133 cwd=cwd,
134 print_cmd=False,
135 input=input,
136 stdout_to_pipe=True,
137 redirect_stderr=redirect_stderr,
138 combine_stdout_stderr=combine_stdout_stderr,
139 error_code_ok=True).output
140# pylint: enable=redefined-builtin
Ryan Cui72834d12011-05-05 14:51:33 -0700141
Ryan Cui1562fb82011-05-09 11:01:31 -0700142
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700143def _get_hooks_dir():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700144 """Returns the absolute path to the repohooks directory."""
Doug Anderson44a644f2011-11-02 10:37:37 -0700145 if __name__ == '__main__':
146 # Works when file is run on its own (__file__ is defined)...
147 return os.path.abspath(os.path.dirname(__file__))
148 else:
149 # We need to do this when we're run through repo. Since repo executes
150 # us with execfile(), we don't get __file__ defined.
151 cmd = ['repo', 'forall', 'chromiumos/repohooks', '-c', 'pwd']
152 return _run_command(cmd).strip()
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700153
Ryan Cui1562fb82011-05-09 11:01:31 -0700154
Ryan Cuiec4d6332011-05-02 14:15:25 -0700155def _match_regex_list(subject, expressions):
156 """Try to match a list of regular expressions to a string.
157
158 Args:
159 subject: The string to match regexes on
160 expressions: A list of regular expressions to check for matches with.
161
162 Returns:
163 Whether the passed in subject matches any of the passed in regexes.
164 """
165 for expr in expressions:
Mike Frysingerae409522014-02-01 03:16:11 -0500166 if re.search(expr, subject):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700167 return True
168 return False
169
Ryan Cui1562fb82011-05-09 11:01:31 -0700170
Mike Frysingerae409522014-02-01 03:16:11 -0500171def _filter_files(files, include_list, exclude_list=()):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700172 """Filter out files based on the conditions passed in.
173
174 Args:
175 files: list of filepaths to filter
176 include_list: list of regex that when matched with a file path will cause it
177 to be added to the output list unless the file is also matched with a
178 regex in the exclude_list.
179 exclude_list: list of regex that when matched with a file will prevent it
180 from being added to the output list, even if it is also matched with a
181 regex in the include_list.
182
183 Returns:
184 A list of filepaths that contain files matched in the include_list and not
185 in the exclude_list.
186 """
187 filtered = []
188 for f in files:
189 if (_match_regex_list(f, include_list) and
190 not _match_regex_list(f, exclude_list)):
191 filtered.append(f)
192 return filtered
193
Ryan Cuiec4d6332011-05-02 14:15:25 -0700194
195# Git Helpers
Ryan Cui1562fb82011-05-09 11:01:31 -0700196
197
Ryan Cui4725d952011-05-05 15:41:19 -0700198def _get_upstream_branch():
199 """Returns the upstream tracking branch of the current branch.
200
201 Raises:
202 Error if there is no tracking branch
203 """
204 current_branch = _run_command(['git', 'symbolic-ref', 'HEAD']).strip()
205 current_branch = current_branch.replace('refs/heads/', '')
206 if not current_branch:
Ryan Cui1562fb82011-05-09 11:01:31 -0700207 raise VerifyException('Need to be on a tracking branch')
Ryan Cui4725d952011-05-05 15:41:19 -0700208
209 cfg_option = 'branch.' + current_branch + '.%s'
210 full_upstream = _run_command(['git', 'config', cfg_option % 'merge']).strip()
211 remote = _run_command(['git', 'config', cfg_option % 'remote']).strip()
212 if not remote or not full_upstream:
Ryan Cui1562fb82011-05-09 11:01:31 -0700213 raise VerifyException('Need to be on a tracking branch')
Ryan Cui4725d952011-05-05 15:41:19 -0700214
215 return full_upstream.replace('heads', 'remotes/' + remote)
216
Ryan Cui1562fb82011-05-09 11:01:31 -0700217
Che-Liang Chiou5ce2d7b2013-03-22 18:47:55 -0700218def _get_patch(commit):
219 """Returns the patch for this commit."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700220 if commit == PRE_SUBMIT:
221 return _run_command(['git', 'diff', '--cached', 'HEAD'])
222 else:
223 return _run_command(['git', 'format-patch', '--stdout', '-1', commit])
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700224
Ryan Cui1562fb82011-05-09 11:01:31 -0700225
Jon Salz98255932012-08-18 14:48:02 +0800226def _try_utf8_decode(data):
227 """Attempts to decode a string as UTF-8.
228
229 Returns:
230 The decoded Unicode object, or the original string if parsing fails.
231 """
232 try:
233 return unicode(data, 'utf-8', 'strict')
234 except UnicodeDecodeError:
235 return data
236
237
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500238def _get_file_content(path, commit):
239 """Returns the content of a file at a specific commit.
240
241 We can't rely on the file as it exists in the filesystem as people might be
242 uploading a series of changes which modifies the file multiple times.
243
244 Note: The "content" of a symlink is just the target. So if you're expecting
245 a full file, you should check that first. One way to detect is that the
246 content will not have any newlines.
247 """
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700248 if commit == PRE_SUBMIT:
249 return _run_command(['git', 'diff', 'HEAD', path])
250 else:
Mike Frysingerd0523442018-01-03 17:05:29 -0500251 # Make sure people don't accidentally pass in full paths which will never
252 # work. You need to use relative=True with _get_affected_files.
253 if path.startswith('/'):
254 raise ValueError('_get_file_content must be called with relative paths: '
255 + path)
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700256 return _run_command(['git', 'show', '%s:%s' % (commit, path)])
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500257
258
Mike Frysingerae409522014-02-01 03:16:11 -0500259def _get_file_diff(path, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700260 """Returns a list of (linenum, lines) tuples that the commit touched."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700261 if commit == PRE_SUBMIT:
Prathmesh Prabhua9de1722016-12-22 14:56:40 -0800262 command = ['git', 'diff', '-p', '--pretty=format:', '--no-ext-diff', 'HEAD',
263 path]
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700264 else:
Prathmesh Prabhua9de1722016-12-22 14:56:40 -0800265 command = ['git', 'show', '-p', '--pretty=format:', '--no-ext-diff', commit,
266 path]
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700267 output = _run_command(command)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700268
269 new_lines = []
270 line_num = 0
271 for line in output.splitlines():
272 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
273 if m:
274 line_num = int(m.groups(1)[0])
275 continue
276 if line.startswith('+') and not line.startswith('++'):
Jon Salz98255932012-08-18 14:48:02 +0800277 new_lines.append((line_num, _try_utf8_decode(line[1:])))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700278 if not line.startswith('-'):
279 line_num += 1
280 return new_lines
281
Ryan Cui1562fb82011-05-09 11:01:31 -0700282
Daniel Erate3ea3fc2015-02-13 15:27:52 -0700283def _get_ignore_wildcards(directory, cache):
284 """Get wildcards listed in a directory's _IGNORE_FILE.
285
286 Args:
287 directory: A string containing a directory path.
288 cache: A dictionary (opaque to caller) caching previously-read wildcards.
289
290 Returns:
291 A list of wildcards from _IGNORE_FILE or an empty list if _IGNORE_FILE
292 wasn't present.
293 """
294 # In the cache, keys are directories and values are lists of wildcards from
295 # _IGNORE_FILE within those directories (and empty if no file was present).
296 if directory not in cache:
297 wildcards = []
298 dotfile_path = os.path.join(directory, _IGNORE_FILE)
299 if os.path.exists(dotfile_path):
300 # TODO(derat): Consider using _get_file_content() to get the file as of
301 # this commit instead of the on-disk version. This may have a noticeable
302 # performance impact, as each call to _get_file_content() runs git.
303 with open(dotfile_path, 'r') as dotfile:
304 for line in dotfile.readlines():
305 line = line.strip()
306 if line.startswith('#'):
307 continue
308 if line.endswith('/'):
309 line += '*'
310 wildcards.append(line)
311 cache[directory] = wildcards
312
313 return cache[directory]
314
315
316def _path_is_ignored(path, cache):
317 """Check whether a path is ignored by _IGNORE_FILE.
318
319 Args:
320 path: A string containing a path.
321 cache: A dictionary (opaque to caller) caching previously-read wildcards.
322
323 Returns:
324 True if a file named _IGNORE_FILE in one of the passed-in path's parent
325 directories contains a wildcard matching the path.
326 """
327 # Skip ignore files.
328 if os.path.basename(path) == _IGNORE_FILE:
329 return True
330
331 path = os.path.abspath(path)
332 base = os.getcwd()
333
334 prefix = os.path.dirname(path)
335 while prefix.startswith(base):
336 rel_path = path[len(prefix) + 1:]
337 for wildcard in _get_ignore_wildcards(prefix, cache):
338 if fnmatch.fnmatch(rel_path, wildcard):
339 return True
340 prefix = os.path.dirname(prefix)
341
342 return False
343
344
Mike Frysinger292b45d2014-11-25 01:17:10 -0500345def _get_affected_files(commit, include_deletes=False, relative=False,
346 include_symlinks=False, include_adds=True,
Daniel Erate3ea3fc2015-02-13 15:27:52 -0700347 full_details=False, use_ignore_files=True):
Peter Ammon811f6702014-06-12 15:45:38 -0700348 """Returns list of file paths that were modified/added, excluding symlinks.
349
350 Args:
351 commit: The commit
352 include_deletes: If true, we'll include deleted files in the result
353 relative: Whether to return relative or full paths to files
Mike Frysinger292b45d2014-11-25 01:17:10 -0500354 include_symlinks: If true, we'll include symlinks in the result
355 include_adds: If true, we'll include new files in the result
356 full_details: If False, return filenames, else return structured results.
Daniel Erate3ea3fc2015-02-13 15:27:52 -0700357 use_ignore_files: Whether we ignore files matched by _IGNORE_FILE files.
Peter Ammon811f6702014-06-12 15:45:38 -0700358
359 Returns:
360 A list of modified/added (and perhaps deleted) files
361 """
Mike Frysinger292b45d2014-11-25 01:17:10 -0500362 if not relative and full_details:
363 raise ValueError('full_details only supports relative paths currently')
364
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700365 if commit == PRE_SUBMIT:
366 return _run_command(['git', 'diff-index', '--cached',
367 '--name-only', 'HEAD']).split()
Mike Frysingerd3bd32c2014-11-24 23:34:29 -0500368
369 path = os.getcwd()
370 files = git.RawDiff(path, '%s^!' % commit)
371
372 # Filter out symlinks.
Mike Frysinger292b45d2014-11-25 01:17:10 -0500373 if not include_symlinks:
374 files = [x for x in files if not stat.S_ISLNK(int(x.dst_mode, 8))]
Mike Frysingerd3bd32c2014-11-24 23:34:29 -0500375
376 if not include_deletes:
377 files = [x for x in files if x.status != 'D']
378
Mike Frysinger292b45d2014-11-25 01:17:10 -0500379 if not include_adds:
380 files = [x for x in files if x.status != 'A']
381
Daniel Erate3ea3fc2015-02-13 15:27:52 -0700382 if use_ignore_files:
383 cache = {}
384 is_ignored = lambda x: _path_is_ignored(x.dst_file or x.src_file, cache)
385 files = [x for x in files if not is_ignored(x)]
386
Mike Frysinger292b45d2014-11-25 01:17:10 -0500387 if full_details:
388 # Caller wants the raw objects to parse status/etc... themselves.
Mike Frysingerd3bd32c2014-11-24 23:34:29 -0500389 return files
390 else:
Mike Frysinger292b45d2014-11-25 01:17:10 -0500391 # Caller only cares about filenames.
392 files = [x.dst_file if x.dst_file else x.src_file for x in files]
393 if relative:
394 return files
395 else:
396 return [os.path.join(path, x) for x in files]
Peter Ammon811f6702014-06-12 15:45:38 -0700397
398
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700399def _get_commits():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700400 """Returns a list of commits for this review."""
Ryan Cui4725d952011-05-05 15:41:19 -0700401 cmd = ['git', 'log', '%s..' % _get_upstream_branch(), '--format=%H']
Ryan Cui72834d12011-05-05 14:51:33 -0700402 return _run_command(cmd).split()
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700403
Ryan Cui1562fb82011-05-09 11:01:31 -0700404
Ryan Cuiec4d6332011-05-02 14:15:25 -0700405def _get_commit_desc(commit):
406 """Returns the full commit message of a commit."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700407 if commit == PRE_SUBMIT:
408 return ''
Sean Paul23a2c582011-05-06 13:10:44 -0400409 return _run_command(['git', 'log', '--format=%s%n%n%b', commit + '^!'])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700410
411
Prathmesh Prabhuc5254652016-12-22 12:58:05 -0800412def _check_lines_in_diff(commit, files, check_callable, error_description):
413 """Checks given file for errors via the given check.
414
415 This is a convenience function for common per-line checks. It goes through all
416 files and returns a HookFailure with the error description listing all the
417 failures.
418
419 Args:
420 commit: The commit we're working on.
421 files: The files to check.
422 check_callable: A callable that takes a line and returns True if this line
423 _fails_ the check.
424 error_description: A string describing the error.
425 """
426 errors = []
427 for afile in files:
428 for line_num, line in _get_file_diff(afile, commit):
429 if check_callable(line):
430 errors.append('%s, line %s' % (afile, line_num))
431 if errors:
432 return HookFailure(error_description, errors)
433
434
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900435def _parse_common_inclusion_options(options):
436 """Parses common hook options for including/excluding files.
437
438 Args:
439 options: Option string list.
440
441 Returns:
442 (included, excluded) where each one is a list of regex strings.
443 """
444 parser = argparse.ArgumentParser()
445 parser.add_argument('--exclude_regex', action='append')
446 parser.add_argument('--include_regex', action='append')
447 opts = parser.parse_args(options)
448 included = opts.include_regex or []
449 excluded = opts.exclude_regex or []
450 return included, excluded
451
452
Ryan Cuiec4d6332011-05-02 14:15:25 -0700453# Common Hooks
454
Ryan Cui1562fb82011-05-09 11:01:31 -0700455
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900456def _check_no_long_lines(_project, commit, options=()):
Mike Frysinger55f85b52014-12-18 14:45:21 -0500457 """Checks there are no lines longer than MAX_LEN in any of the text files."""
458
Ryan Cuiec4d6332011-05-02 14:15:25 -0700459 MAX_LEN = 80
Jon Salz98255932012-08-18 14:48:02 +0800460 SKIP_REGEXP = re.compile('|'.join([
461 r'https?://',
Maksim Ivanov3f677b92018-06-05 16:10:24 +0200462 r'^#\s*(define|include|import|pragma|if|ifndef|endif)\b']))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700463
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900464 included, excluded = _parse_common_inclusion_options(options)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700465 files = _filter_files(_get_affected_files(commit),
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900466 included + COMMON_INCLUDED_PATHS,
467 excluded + COMMON_EXCLUDED_PATHS)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700468
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900469 errors = []
Ryan Cuiec4d6332011-05-02 14:15:25 -0700470 for afile in files:
471 for line_num, line in _get_file_diff(afile, commit):
472 # Allow certain lines to exceed the maxlen rule.
Mike Frysingerae409522014-02-01 03:16:11 -0500473 if len(line) <= MAX_LEN or SKIP_REGEXP.search(line):
Jon Salz98255932012-08-18 14:48:02 +0800474 continue
475
476 errors.append('%s, line %s, %s chars' % (afile, line_num, len(line)))
477 if len(errors) == 5: # Just show the first 5 errors.
478 break
Ryan Cuiec4d6332011-05-02 14:15:25 -0700479
480 if errors:
481 msg = 'Found lines longer than %s characters (first 5 shown):' % MAX_LEN
Ryan Cui1562fb82011-05-09 11:01:31 -0700482 return HookFailure(msg, errors)
483
Ryan Cuiec4d6332011-05-02 14:15:25 -0700484
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900485def _check_no_stray_whitespace(_project, commit, options=()):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700486 """Checks that there is no stray whitespace at source lines end."""
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900487 included, excluded = _parse_common_inclusion_options(options)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700488 files = _filter_files(_get_affected_files(commit),
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900489 included + COMMON_INCLUDED_PATHS,
490 excluded + COMMON_EXCLUDED_PATHS)
Prathmesh Prabhuc5254652016-12-22 12:58:05 -0800491 return _check_lines_in_diff(commit, files,
492 lambda line: line.rstrip() != line,
493 'Found line ending with white space in:')
Ryan Cui1562fb82011-05-09 11:01:31 -0700494
Ryan Cuiec4d6332011-05-02 14:15:25 -0700495
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900496def _check_no_tabs(_project, commit, options=()):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700497 """Checks there are no unexpanded tabs."""
Mike Frysingercd134512017-10-26 04:36:33 -0400498 # Don't add entire repos here. Update the PRESUBMIT.cfg in each repo instead.
499 # We only whitelist known specific filetypes here that show up in all repos.
Ryan Cuiec4d6332011-05-02 14:15:25 -0700500 TAB_OK_PATHS = [
Ryan Cuiec4d6332011-05-02 14:15:25 -0700501 r".*\.ebuild$",
502 r".*\.eclass$",
Elly Jones5ab34192011-11-15 14:57:06 -0500503 r".*/[M|m]akefile$",
504 r".*\.mk$"
Ryan Cuiec4d6332011-05-02 14:15:25 -0700505 ]
506
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900507 included, excluded = _parse_common_inclusion_options(options)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700508 files = _filter_files(_get_affected_files(commit),
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900509 included + COMMON_INCLUDED_PATHS,
510 excluded + COMMON_EXCLUDED_PATHS + TAB_OK_PATHS)
Prathmesh Prabhuc5254652016-12-22 12:58:05 -0800511 return _check_lines_in_diff(commit, files,
512 lambda line: '\t' in line,
513 'Found a tab character in:')
Ryan Cuiec4d6332011-05-02 14:15:25 -0700514
Prathmesh Prabhuc5254652016-12-22 12:58:05 -0800515
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900516def _check_tabbed_indents(_project, commit, options=()):
Prathmesh Prabhuc5254652016-12-22 12:58:05 -0800517 """Checks that indents use tabs only."""
518 TABS_REQUIRED_PATHS = [
519 r".*\.ebuild$",
520 r".*\.eclass$",
521 ]
522 LEADING_SPACE_RE = re.compile('[\t]* ')
523
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900524 included, excluded = _parse_common_inclusion_options(options)
Prathmesh Prabhuc5254652016-12-22 12:58:05 -0800525 files = _filter_files(_get_affected_files(commit),
Shuhei Takahashiabc20f32017-07-10 19:35:45 +0900526 included + TABS_REQUIRED_PATHS,
527 excluded + COMMON_EXCLUDED_PATHS)
Prathmesh Prabhuc5254652016-12-22 12:58:05 -0800528 return _check_lines_in_diff(
529 commit, files,
530 lambda line: LEADING_SPACE_RE.match(line) is not None,
531 'Found a space in indentation (must be all tabs):')
Ryan Cui1562fb82011-05-09 11:01:31 -0700532
Ryan Cuiec4d6332011-05-02 14:15:25 -0700533
Rahul Chaudhry09f61372015-07-31 17:14:26 -0700534def _check_gofmt(_project, commit):
535 """Checks that Go files are formatted with gofmt."""
536 errors = []
537 files = _filter_files(_get_affected_files(commit, relative=True),
538 [r'\.go$'])
539
540 for gofile in files:
541 contents = _get_file_content(gofile, commit)
Rahul Chaudhry0e515342015-08-07 12:00:43 -0700542 output = _run_command(cmd=['gofmt', '-l'], input=contents,
543 combine_stdout_stderr=True)
Rahul Chaudhry09f61372015-07-31 17:14:26 -0700544 if output:
545 errors.append(gofile)
546 if errors:
547 return HookFailure('Files not formatted with gofmt:', errors)
548
549
Mike Frysingerae409522014-02-01 03:16:11 -0500550def _check_change_has_test_field(_project, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700551 """Check for a non-empty 'TEST=' field in the commit message."""
David McMahon8f6553e2011-06-10 15:46:36 -0700552 TEST_RE = r'\nTEST=\S+'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700553
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700554 if not re.search(TEST_RE, _get_commit_desc(commit)):
Ryan Cui1562fb82011-05-09 11:01:31 -0700555 msg = 'Changelist description needs TEST field (after first line)'
556 return HookFailure(msg)
557
Ryan Cuiec4d6332011-05-02 14:15:25 -0700558
Mike Frysingerae409522014-02-01 03:16:11 -0500559def _check_change_has_valid_cq_depend(_project, commit):
Jason D. Clinton299e3222019-05-23 09:42:03 -0600560 """Check for a correctly formatted Cq-Depend field in the commit message."""
Luigi Semenzatob8c7d7d2019-06-03 09:43:21 -0700561 desc = _get_commit_desc(commit)
Jason D. Clinton299e3222019-05-23 09:42:03 -0600562 msg = 'Changelist has invalid Cq-Depend target.'
563 example = 'Example: Cq-Depend: chromium:1234, chrome-internal:2345'
David Jamesc3b68b32013-04-03 09:17:03 -0700564 try:
Luigi Semenzatob8c7d7d2019-06-03 09:43:21 -0700565 patch.GetPaladinDeps(desc)
David Jamesc3b68b32013-04-03 09:17:03 -0700566 except ValueError as ex:
567 return HookFailure(msg, [example, str(ex)])
Luigi Semenzatob8c7d7d2019-06-03 09:43:21 -0700568 # Check that Cq-Depend is in the same paragraph as Change-Id.
569 msg = 'Cq-Depend (or CQ-DEPEND) is not in the same paragraph as Change-Id.'
570 paragraphs = desc.split('\n\n')
571 for paragraph in paragraphs:
572 if (re.search(r'^Cq-Depend:', paragraph, re.M) or
573 re.search(r'^CQ-DEPEND=', paragraph, re.M)) \
574 and not re.search('^Change-Id:', paragraph, re.M):
575 return HookFailure(msg)
David Jamesc3b68b32013-04-03 09:17:03 -0700576
577
Bernie Thompsonf8fea992016-01-14 10:27:18 -0800578def _check_change_is_contribution(_project, commit):
579 """Check that the change is a contribution."""
580 NO_CONTRIB = 'not a contribution'
581 if NO_CONTRIB in _get_commit_desc(commit).lower():
582 msg = ('Changelist is not a contribution, this cannot be accepted.\n'
583 'Please remove the "%s" text from the commit message.') % NO_CONTRIB
584 return HookFailure(msg)
585
586
Alex Deymo643ac4c2015-09-03 10:40:50 -0700587def _check_change_has_bug_field(project, commit):
David McMahon8f6553e2011-06-10 15:46:36 -0700588 """Check for a correctly formatted 'BUG=' field in the commit message."""
David James5c0073d2013-04-03 08:48:52 -0700589 OLD_BUG_RE = r'\nBUG=.*chromium-os'
590 if re.search(OLD_BUG_RE, _get_commit_desc(commit)):
591 msg = ('The chromium-os bug tracker is now deprecated. Please use\n'
592 'the chromium tracker in your BUG= line now.')
593 return HookFailure(msg)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700594
Alex Deymo643ac4c2015-09-03 10:40:50 -0700595 # Android internal and external projects use "Bug: " to track bugs in
596 # buganizer.
597 BUG_COLON_REMOTES = (
598 'aosp',
599 'goog',
600 )
601 if project.remote in BUG_COLON_REMOTES:
602 BUG_RE = r'\nBug: ?([Nn]one|\d+)'
603 if not re.search(BUG_RE, _get_commit_desc(commit)):
604 msg = ('Changelist description needs BUG field (after first line):\n'
605 'Bug: 9999 (for buganizer)\n'
606 'BUG=None')
607 return HookFailure(msg)
608 else:
Jorge Lucangeli Obesdce214e2017-10-25 15:04:39 -0400609 BUG_RE = r'\nBUG=([Nn]one|(chromium|b):\d+)'
Alex Deymo643ac4c2015-09-03 10:40:50 -0700610 if not re.search(BUG_RE, _get_commit_desc(commit)):
611 msg = ('Changelist description needs BUG field (after first line):\n'
Alex Deymo643ac4c2015-09-03 10:40:50 -0700612 'BUG=chromium:9999 (for public tracker)\n'
Alex Deymo643ac4c2015-09-03 10:40:50 -0700613 'BUG=b:9999 (for buganizer)\n'
614 'BUG=None')
615 return HookFailure(msg)
Ryan Cui1562fb82011-05-09 11:01:31 -0700616
Ryan Cuiec4d6332011-05-02 14:15:25 -0700617
Mike Frysinger292b45d2014-11-25 01:17:10 -0500618def _check_for_uprev(project, commit, project_top=None):
Doug Anderson42b8a052013-06-26 10:45:36 -0700619 """Check that we're not missing a revbump of an ebuild in the given commit.
620
621 If the given commit touches files in a directory that has ebuilds somewhere
622 up the directory hierarchy, it's very likely that we need an ebuild revbump
623 in order for those changes to take effect.
624
625 It's not totally trivial to detect a revbump, so at least detect that an
626 ebuild with a revision number in it was touched. This should handle the
627 common case where we use a symlink to do the revbump.
628
629 TODO: it would be nice to enhance this hook to:
630 * Handle cases where people revbump with a slightly different syntax. I see
631 one ebuild (puppy) that revbumps with _pN. This is a false positive.
632 * Catches cases where people aren't using symlinks for revbumps. If they
633 edit a revisioned file directly (and are expected to rename it for revbump)
634 we'll miss that. Perhaps we could detect that the file touched is a
635 symlink?
636
637 If a project doesn't use symlinks we'll potentially miss a revbump, but we're
638 still better off than without this check.
639
640 Args:
Alex Deymo643ac4c2015-09-03 10:40:50 -0700641 project: The Project to look at
Doug Anderson42b8a052013-06-26 10:45:36 -0700642 commit: The commit to look at
Mike Frysinger292b45d2014-11-25 01:17:10 -0500643 project_top: Top dir to process commits in
Doug Anderson42b8a052013-06-26 10:45:36 -0700644
645 Returns:
646 A HookFailure or None.
647 """
Mike Frysinger011af942014-01-17 16:12:22 -0500648 # If this is the portage-stable overlay, then ignore the check. It's rare
649 # that we're doing anything other than importing files from upstream, so
650 # forcing a rev bump makes no sense.
651 whitelist = (
652 'chromiumos/overlays/portage-stable',
653 )
Alex Deymo643ac4c2015-09-03 10:40:50 -0700654 if project.name in whitelist:
Mike Frysinger011af942014-01-17 16:12:22 -0500655 return None
656
Mike Frysinger292b45d2014-11-25 01:17:10 -0500657 def FinalName(obj):
658 # If the file is being deleted, then the dst_file is not set.
659 if obj.dst_file is None:
660 return obj.src_file
661 else:
662 return obj.dst_file
663
664 affected_path_objs = _get_affected_files(
665 commit, include_deletes=True, include_symlinks=True, relative=True,
666 full_details=True)
Doug Anderson42b8a052013-06-26 10:45:36 -0700667
668 # Don't yell about changes to whitelisted files...
Aviv Keshet272f2e52016-04-25 14:49:44 -0700669 whitelist = ('ChangeLog', 'Manifest', 'metadata.xml', 'COMMIT-QUEUE.ini')
Mike Frysinger292b45d2014-11-25 01:17:10 -0500670 affected_path_objs = [x for x in affected_path_objs
671 if os.path.basename(FinalName(x)) not in whitelist]
672 if not affected_path_objs:
Doug Anderson42b8a052013-06-26 10:45:36 -0700673 return None
674
675 # If we've touched any file named with a -rN.ebuild then we'll say we're
676 # OK right away. See TODO above about enhancing this.
Mike Frysinger292b45d2014-11-25 01:17:10 -0500677 touched_revved_ebuild = any(re.search(r'-r\d*\.ebuild$', FinalName(x))
678 for x in affected_path_objs)
Doug Anderson42b8a052013-06-26 10:45:36 -0700679 if touched_revved_ebuild:
680 return None
681
Mike Frysinger292b45d2014-11-25 01:17:10 -0500682 # If we're creating new ebuilds from scratch, then we don't need an uprev.
683 # Find all the dirs that new ebuilds and ignore their files/.
684 ebuild_dirs = [os.path.dirname(FinalName(x)) + '/' for x in affected_path_objs
685 if FinalName(x).endswith('.ebuild') and x.status == 'A']
686 affected_path_objs = [obj for obj in affected_path_objs
687 if not any(FinalName(obj).startswith(x)
688 for x in ebuild_dirs)]
689 if not affected_path_objs:
690 return
691
Doug Anderson42b8a052013-06-26 10:45:36 -0700692 # We want to examine the current contents of all directories that are parents
693 # of files that were touched (up to the top of the project).
694 #
695 # ...note: we use the current directory contents even though it may have
696 # changed since the commit we're looking at. This is just a heuristic after
697 # all. Worst case we don't flag a missing revbump.
Mike Frysinger292b45d2014-11-25 01:17:10 -0500698 if project_top is None:
699 project_top = os.getcwd()
Doug Anderson42b8a052013-06-26 10:45:36 -0700700 dirs_to_check = set([project_top])
Mike Frysinger292b45d2014-11-25 01:17:10 -0500701 for obj in affected_path_objs:
702 path = os.path.join(project_top, os.path.dirname(FinalName(obj)))
Doug Anderson42b8a052013-06-26 10:45:36 -0700703 while os.path.exists(path) and not os.path.samefile(path, project_top):
704 dirs_to_check.add(path)
705 path = os.path.dirname(path)
706
707 # Look through each directory. If it's got an ebuild in it then we'll
708 # consider this as a case when we need a revbump.
Gwendal Grignoua3086c32014-12-09 11:17:22 -0800709 affected_paths = set(os.path.join(project_top, FinalName(x))
710 for x in affected_path_objs)
Doug Anderson42b8a052013-06-26 10:45:36 -0700711 for dir_path in dirs_to_check:
712 contents = os.listdir(dir_path)
713 ebuilds = [os.path.join(dir_path, path)
714 for path in contents if path.endswith('.ebuild')]
715 ebuilds_9999 = [path for path in ebuilds if path.endswith('-9999.ebuild')]
716
C Shapiroae157ae2017-09-18 16:24:03 -0600717 affected_paths_under_9999_ebuilds = set()
718 for affected_path in affected_paths:
719 for ebuild_9999 in ebuilds_9999:
720 ebuild_dir = os.path.dirname(ebuild_9999)
721 if affected_path.startswith(ebuild_dir):
722 affected_paths_under_9999_ebuilds.add(affected_path)
723
724 # If every file changed exists under a 9999 ebuild, then skip
725 if len(affected_paths_under_9999_ebuilds) == len(affected_paths):
726 continue
727
Doug Anderson42b8a052013-06-26 10:45:36 -0700728 # If the -9999.ebuild file was touched the bot will uprev for us.
729 # ...we'll use a simple intersection here as a heuristic...
Mike Frysinger292b45d2014-11-25 01:17:10 -0500730 if set(ebuilds_9999) & affected_paths:
Doug Anderson42b8a052013-06-26 10:45:36 -0700731 continue
732
733 if ebuilds:
Mike Frysinger292b45d2014-11-25 01:17:10 -0500734 return HookFailure('Changelist probably needs a revbump of an ebuild, '
735 'or a -r1.ebuild symlink if this is a new ebuild:\n'
736 '%s' % dir_path)
Doug Anderson42b8a052013-06-26 10:45:36 -0700737
738 return None
739
740
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500741def _check_ebuild_eapi(project, commit):
Mike Frysinger948284a2018-02-01 15:22:56 -0500742 """Make sure we have people use EAPI=5 or newer with custom ebuilds.
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500743
744 We want to get away from older EAPI's as it makes life confusing and they
745 have less builtin error checking.
746
747 Args:
Alex Deymo643ac4c2015-09-03 10:40:50 -0700748 project: The Project to look at
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500749 commit: The commit to look at
750
751 Returns:
752 A HookFailure or None.
753 """
754 # If this is the portage-stable overlay, then ignore the check. It's rare
Mike Frysingercd6adfc2014-02-06 01:03:56 -0500755 # that we're doing anything other than importing files from upstream, and
756 # we shouldn't be rewriting things fundamentally anyways.
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500757 whitelist = (
758 'chromiumos/overlays/portage-stable',
759 )
Alex Deymo643ac4c2015-09-03 10:40:50 -0700760 if project.name in whitelist:
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500761 return None
762
Mike Frysinger948284a2018-02-01 15:22:56 -0500763 BAD_EAPIS = ('0', '1', '2', '3', '4')
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500764
765 get_eapi = re.compile(r'^\s*EAPI=[\'"]?([^\'"]+)')
766
767 ebuilds_re = [r'\.ebuild$']
768 ebuilds = _filter_files(_get_affected_files(commit, relative=True),
769 ebuilds_re)
770 bad_ebuilds = []
771
772 for ebuild in ebuilds:
773 # If the ebuild does not specify an EAPI, it defaults to 0.
774 eapi = '0'
775
776 lines = _get_file_content(ebuild, commit).splitlines()
777 if len(lines) == 1:
778 # This is most likely a symlink, so skip it entirely.
779 continue
780
781 for line in lines:
782 m = get_eapi.match(line)
783 if m:
784 # Once we hit the first EAPI line in this ebuild, stop processing.
785 # The spec requires that there only be one and it be first, so
786 # checking all possible values is pointless. We also assume that
787 # it's "the" EAPI line and not something in the middle of a heredoc.
788 eapi = m.group(1)
789 break
790
791 if eapi in BAD_EAPIS:
792 bad_ebuilds.append((ebuild, eapi))
793
794 if bad_ebuilds:
795 # pylint: disable=C0301
796 url = 'http://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/upgrade-ebuild-eapis'
797 # pylint: enable=C0301
798 return HookFailure(
Mike Frysingercd6adfc2014-02-06 01:03:56 -0500799 'These ebuilds are using old EAPIs. If these are imported from\n'
800 'Gentoo, then you may ignore and upload once with the --no-verify\n'
Mike Frysinger948284a2018-02-01 15:22:56 -0500801 'flag. Otherwise, please update to 5 or newer.\n'
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500802 '\t%s\n'
803 'See this guide for more details:\n%s\n' %
804 ('\n\t'.join(['%s: EAPI=%s' % x for x in bad_ebuilds]), url))
805
806
Mike Frysinger89bdb852014-02-01 05:26:26 -0500807def _check_ebuild_keywords(_project, commit):
Mike Frysingerc51ece72014-01-17 16:23:40 -0500808 """Make sure we use the new style KEYWORDS when possible in ebuilds.
809
810 If an ebuild generally does not care about the arch it is running on, then
811 ebuilds should flag it with one of:
812 KEYWORDS="*" # A stable ebuild.
813 KEYWORDS="~*" # An unstable ebuild.
814 KEYWORDS="-* ..." # Is known to only work on specific arches.
815
816 Args:
Alex Deymo643ac4c2015-09-03 10:40:50 -0700817 project: The Project to look at
Mike Frysingerc51ece72014-01-17 16:23:40 -0500818 commit: The commit to look at
819
820 Returns:
821 A HookFailure or None.
822 """
823 WHITELIST = set(('*', '-*', '~*'))
824
825 get_keywords = re.compile(r'^\s*KEYWORDS="(.*)"')
826
Mike Frysinger89bdb852014-02-01 05:26:26 -0500827 ebuilds_re = [r'\.ebuild$']
828 ebuilds = _filter_files(_get_affected_files(commit, relative=True),
829 ebuilds_re)
830
Mike Frysinger8d42d742014-09-22 15:50:21 -0400831 bad_ebuilds = []
Mike Frysingerc51ece72014-01-17 16:23:40 -0500832 for ebuild in ebuilds:
Mike Frysinger5c9e58d2014-09-09 03:32:50 -0400833 # We get the full content rather than a diff as the latter does not work
834 # on new files (like when adding new ebuilds).
835 lines = _get_file_content(ebuild, commit).splitlines()
836 for line in lines:
Mike Frysingerc51ece72014-01-17 16:23:40 -0500837 m = get_keywords.match(line)
838 if m:
839 keywords = set(m.group(1).split())
840 if not keywords or WHITELIST - keywords != WHITELIST:
841 continue
842
Mike Frysinger8d42d742014-09-22 15:50:21 -0400843 bad_ebuilds.append(ebuild)
844
845 if bad_ebuilds:
846 return HookFailure(
847 '%s\n'
848 'Please update KEYWORDS to use a glob:\n'
849 'If the ebuild should be marked stable (normal for non-9999 ebuilds):\n'
850 ' KEYWORDS="*"\n'
851 'If the ebuild should be marked unstable (normal for '
852 'cros-workon / 9999 ebuilds):\n'
853 ' KEYWORDS="~*"\n'
Mike Frysingerde8efea2015-05-17 03:42:26 -0400854 'If the ebuild needs to be marked for only specific arches, '
Mike Frysinger8d42d742014-09-22 15:50:21 -0400855 'then use -* like so:\n'
856 ' KEYWORDS="-* arm ..."\n' % '\n* '.join(bad_ebuilds))
Mike Frysingerc51ece72014-01-17 16:23:40 -0500857
858
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800859def _check_ebuild_licenses(_project, commit):
860 """Check if the LICENSE field in the ebuild is correct."""
Brian Norris7a610e82016-02-17 12:24:54 -0800861 affected_paths = _get_affected_files(commit, relative=True)
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800862 touched_ebuilds = [x for x in affected_paths if x.endswith('.ebuild')]
863
864 # A list of licenses to ignore for now.
Yu-Ju Hongc0963fa2014-03-03 12:36:52 -0800865 LICENSES_IGNORE = ['||', '(', ')']
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800866
867 for ebuild in touched_ebuilds:
868 # Skip virutal packages.
869 if ebuild.split('/')[-3] == 'virtual':
870 continue
871
Alex Kleinb5953522018-08-03 11:44:21 -0600872 # e.g. path/to/overlay/category/package/package.ebuild -> path/to/overlay
873 overlay_path = os.sep.join(ebuild.split(os.sep)[:-3])
874
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800875 try:
Brian Norris7a610e82016-02-17 12:24:54 -0800876 ebuild_content = _get_file_content(ebuild, commit)
Alex Kleinb5953522018-08-03 11:44:21 -0600877 license_types = licenses_lib.GetLicenseTypesFromEbuild(ebuild_content,
878 overlay_path)
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800879 except ValueError as e:
880 return HookFailure(e.message, [ebuild])
881
882 # Also ignore licenses ending with '?'
883 for license_type in [x for x in license_types
884 if x not in LICENSES_IGNORE and not x.endswith('?')]:
885 try:
Alex Kleinb5953522018-08-03 11:44:21 -0600886 licenses_lib.Licensing.FindLicenseType(license_type,
887 overlay_path=overlay_path)
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800888 except AssertionError as e:
889 return HookFailure(e.message, [ebuild])
890
891
Mike Frysingercd363c82014-02-01 05:20:18 -0500892def _check_ebuild_virtual_pv(project, commit):
893 """Enforce the virtual PV policies."""
894 # If this is the portage-stable overlay, then ignore the check.
895 # We want to import virtuals as-is from upstream Gentoo.
896 whitelist = (
897 'chromiumos/overlays/portage-stable',
898 )
Alex Deymo643ac4c2015-09-03 10:40:50 -0700899 if project.name in whitelist:
Mike Frysingercd363c82014-02-01 05:20:18 -0500900 return None
901
902 # We assume the repo name is the same as the dir name on disk.
903 # It would be dumb to not have them match though.
Alex Deymo643ac4c2015-09-03 10:40:50 -0700904 project_base = os.path.basename(project.name)
Mike Frysingercd363c82014-02-01 05:20:18 -0500905
906 is_variant = lambda x: x.startswith('overlay-variant-')
907 is_board = lambda x: x.startswith('overlay-')
Douglas Andersonb43df7f2018-06-25 13:40:50 -0700908 is_baseboard = lambda x: x.startswith('baseboard-')
909 is_chipset = lambda x: x.startswith('chipset-')
910 is_project = lambda x: x.startswith('project-')
Mike Frysingercd363c82014-02-01 05:20:18 -0500911 is_private = lambda x: x.endswith('-private')
912
Douglas Andersonb43df7f2018-06-25 13:40:50 -0700913 is_special_overlay = lambda x: (is_board(x) or is_chipset(x) or
914 is_baseboard(x) or is_project(x))
915
Mike Frysingercd363c82014-02-01 05:20:18 -0500916 get_pv = re.compile(r'(.*?)virtual/([^/]+)/\2-([^/]*)\.ebuild$')
917
918 ebuilds_re = [r'\.ebuild$']
919 ebuilds = _filter_files(_get_affected_files(commit, relative=True),
920 ebuilds_re)
921 bad_ebuilds = []
922
923 for ebuild in ebuilds:
924 m = get_pv.match(ebuild)
925 if m:
926 overlay = m.group(1)
Douglas Andersonb43df7f2018-06-25 13:40:50 -0700927 if not overlay or not is_special_overlay(overlay):
Alex Deymo643ac4c2015-09-03 10:40:50 -0700928 overlay = project_base
Mike Frysingercd363c82014-02-01 05:20:18 -0500929
930 pv = m.group(3).split('-', 1)[0]
931
Bernie Thompsone5ee1822016-01-12 14:22:23 -0800932 # Virtual versions >= 4 are special cases used above the standard
933 # versioning structure, e.g. if one has a board inheriting a board.
934 if float(pv) >= 4:
935 want_pv = pv
Mike Frysingercd363c82014-02-01 05:20:18 -0500936 elif is_board(overlay):
Douglas Andersonb43df7f2018-06-25 13:40:50 -0700937 if is_private(overlay):
938 want_pv = '3.5' if is_variant(overlay) else '3'
939 elif is_board(overlay):
940 want_pv = '2.5' if is_variant(overlay) else '2'
941 elif is_baseboard(overlay):
942 want_pv = '1.9'
943 elif is_chipset(overlay):
944 want_pv = '1.8'
945 elif is_project(overlay):
946 want_pv = '1.7' if is_private(overlay) else '1.5'
Mike Frysingercd363c82014-02-01 05:20:18 -0500947 else:
948 want_pv = '1'
949
950 if pv != want_pv:
951 bad_ebuilds.append((ebuild, pv, want_pv))
952
953 if bad_ebuilds:
954 # pylint: disable=C0301
955 url = 'http://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/portage-build-faq#TOC-Virtuals-and-central-management'
956 # pylint: enable=C0301
957 return HookFailure(
958 'These virtuals have incorrect package versions (PVs). Please adjust:\n'
959 '\t%s\n'
960 'If this is an upstream Gentoo virtual, then you may ignore this\n'
961 'check (and re-run w/--no-verify). Otherwise, please see this\n'
962 'page for more details:\n%s\n' %
963 ('\n\t'.join(['%s:\n\t\tPV is %s but should be %s' % x
964 for x in bad_ebuilds]), url))
965
966
Daniel Erat9d203ff2015-02-17 10:12:21 -0700967def _check_portage_make_use_var(_project, commit):
968 """Verify that $USE is set correctly in make.conf and make.defaults."""
969 files = _filter_files(_get_affected_files(commit, relative=True),
970 [r'(^|/)make.(conf|defaults)$'])
971
972 errors = []
973 for path in files:
974 basename = os.path.basename(path)
975
976 # Has a USE= line already been encountered in this file?
977 saw_use = False
978
979 for i, line in enumerate(_get_file_content(path, commit).splitlines(), 1):
980 if not line.startswith('USE='):
981 continue
982
983 preserves_use = '${USE}' in line or '$USE' in line
984
985 if (basename == 'make.conf' or
986 (basename == 'make.defaults' and saw_use)) and not preserves_use:
987 errors.append('%s:%d: missing ${USE}' % (path, i))
988 elif basename == 'make.defaults' and not saw_use and preserves_use:
989 errors.append('%s:%d: ${USE} referenced in initial declaration' %
990 (path, i))
991
992 saw_use = True
993
994 if errors:
995 return HookFailure(
996 'One or more Portage make files appear to set USE incorrectly.\n'
997 '\n'
998 'All USE assignments in make.conf and all assignments after the\n'
999 'initial declaration in make.defaults should contain "${USE}" to\n'
1000 'preserve previously-set flags.\n'
1001 '\n'
1002 'The initial USE declaration in make.defaults should not contain\n'
1003 '"${USE}".\n',
1004 errors)
1005
1006
Mike Frysingerae409522014-02-01 03:16:11 -05001007def _check_change_has_proper_changeid(_project, commit):
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -07001008 """Verify that Change-ID is present in last paragraph of commit message."""
Mike Frysinger4a22bf02014-10-31 13:53:35 -04001009 CHANGE_ID_RE = r'\nChange-Id: I[a-f0-9]+\n'
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -07001010 desc = _get_commit_desc(commit)
Mike Frysinger4a22bf02014-10-31 13:53:35 -04001011 m = re.search(CHANGE_ID_RE, desc)
Mike Frysinger02b88bd2014-11-21 00:29:38 -05001012 if not m:
Vadim Bendebury20532ba2017-05-23 17:26:15 -07001013 return HookFailure('Last paragraph of description must include Change-Id.')
Ryan Cui1562fb82011-05-09 11:01:31 -07001014
Vadim Bendebury20532ba2017-05-23 17:26:15 -07001015 # S-o-b tags always allowed to follow Change-ID.
1016 allowed_tags = ['Signed-off-by']
1017
Mike Frysinger02b88bd2014-11-21 00:29:38 -05001018 end = desc[m.end():].strip().splitlines()
Vadim Bendebury6504aea2017-09-13 18:35:49 -07001019 cherry_pick_marker = 'cherry picked from commit'
1020
1021 if end and cherry_pick_marker in end[-1]:
Vadim Bendebury20532ba2017-05-23 17:26:15 -07001022 # Cherry picked patches allow more tags in the last paragraph.
Vadim Bendebury6504aea2017-09-13 18:35:49 -07001023 allowed_tags += ['Commit-Queue', 'Commit-Ready', 'Reviewed-by',
1024 'Reviewed-on', 'Tested-by']
Vadim Bendebury20532ba2017-05-23 17:26:15 -07001025 end = end[:-1]
1026
Vadim Bendebury6504aea2017-09-13 18:35:49 -07001027 # Note that descriptions could have multiple cherry pick markers.
1028 tag_search = r'^(%s:|\(%s) ' % (':|'.join(allowed_tags), cherry_pick_marker)
Vadim Bendebury20532ba2017-05-23 17:26:15 -07001029
1030 if [x for x in end if not re.search(tag_search, x)]:
1031 return HookFailure('Only "%s:" tag(s) may follow the Change-Id.' %
1032 ':", "'.join(allowed_tags))
Mike Frysinger02b88bd2014-11-21 00:29:38 -05001033
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -07001034
Mike Frysinger36b2ebc2014-10-31 14:02:03 -04001035def _check_commit_message_style(_project, commit):
1036 """Verify that the commit message matches our style.
1037
1038 We do not check for BUG=/TEST=/etc... lines here as that is handled by other
1039 commit hooks.
1040 """
1041 desc = _get_commit_desc(commit)
1042
1043 # The first line should be by itself.
1044 lines = desc.splitlines()
1045 if len(lines) > 1 and lines[1]:
1046 return HookFailure('The second line of the commit message must be blank.')
1047
1048 # The first line should be one sentence.
1049 if '. ' in lines[0]:
1050 return HookFailure('The first line cannot be more than one sentence.')
1051
1052 # The first line cannot be too long.
1053 MAX_FIRST_LINE_LEN = 100
1054 if len(lines[0]) > MAX_FIRST_LINE_LEN:
1055 return HookFailure('The first line must be less than %i chars.' %
1056 MAX_FIRST_LINE_LEN)
1057
1058
Filipe Brandenburger4b542b12015-10-09 12:46:31 -07001059def _check_cros_license(_project, commit, options=()):
Alex Deymof5792ce2015-08-24 22:50:08 -07001060 """Verifies the Chromium OS license/copyright header.
Ryan Cuiec4d6332011-05-02 14:15:25 -07001061
Mike Frysinger98638102014-08-28 00:15:08 -04001062 Should be following the spec:
1063 http://dev.chromium.org/developers/coding-style#TOC-File-headers
1064 """
1065 # For older years, be a bit more flexible as our policy says leave them be.
1066 LICENSE_HEADER = (
Brian Norris68838dd2018-09-26 18:30:24 -07001067 r'.*Copyright( \(c\))? 20[-0-9]{2,7} The Chromium OS Authors\. '
Mike Frysingerb81102f2014-11-21 00:33:35 -05001068 r'All rights reserved\.' r'\n'
Brian Norris68838dd2018-09-26 18:30:24 -07001069 r'.*Use of this source code is governed by a BSD-style license that can '
Mike Frysingerb81102f2014-11-21 00:33:35 -05001070 r'be\n'
Brian Norris68838dd2018-09-26 18:30:24 -07001071 r'.*found in the LICENSE file\.'
Mike Frysingerb81102f2014-11-21 00:33:35 -05001072 r'\n'
Mike Frysinger98638102014-08-28 00:15:08 -04001073 )
1074 license_re = re.compile(LICENSE_HEADER, re.MULTILINE)
1075
1076 # For newer years, be stricter.
1077 COPYRIGHT_LINE = (
Brian Norris68838dd2018-09-26 18:30:24 -07001078 r'.*Copyright \(c\) 20(1[5-9]|[2-9][0-9]) The Chromium OS Authors\. '
Mike Frysingerb81102f2014-11-21 00:33:35 -05001079 r'All rights reserved\.' r'\n'
Mike Frysinger98638102014-08-28 00:15:08 -04001080 )
1081 copyright_re = re.compile(COPYRIGHT_LINE)
1082
Shuhei Takahashiabc20f32017-07-10 19:35:45 +09001083 included, excluded = _parse_common_inclusion_options(options)
Filipe Brandenburger4b542b12015-10-09 12:46:31 -07001084
Mike Frysinger98638102014-08-28 00:15:08 -04001085 bad_files = []
1086 bad_copyright_files = []
Ken Turnerd07564b2018-02-08 17:57:59 +11001087 files = _filter_files(
1088 _get_affected_files(commit, relative=True),
1089 included + COMMON_INCLUDED_PATHS,
1090 excluded + COMMON_EXCLUDED_PATHS + LICENSE_EXCLUDED_PATHS)
Mike Frysinger98638102014-08-28 00:15:08 -04001091
1092 for f in files:
1093 contents = _get_file_content(f, commit)
1094 if not contents:
1095 # Ignore empty files.
1096 continue
1097
1098 if not license_re.search(contents):
1099 bad_files.append(f)
1100 elif copyright_re.search(contents):
1101 bad_copyright_files.append(f)
1102
1103 if bad_files:
1104 msg = '%s:\n%s\n%s' % (
1105 'License must match', license_re.pattern,
1106 'Found a bad header in these files:')
1107 return HookFailure(msg, bad_files)
1108
1109 if bad_copyright_files:
1110 msg = 'Do not use (c) in copyright headers in new files:'
1111 return HookFailure(msg, bad_copyright_files)
Ryan Cuiec4d6332011-05-02 14:15:25 -07001112
1113
Amin Hassani391efa92018-01-26 17:58:05 -08001114def _check_aosp_license(_project, commit, options=()):
Alex Deymof5792ce2015-08-24 22:50:08 -07001115 """Verifies the AOSP license/copyright header.
1116
1117 AOSP uses the Apache2 License:
1118 https://source.android.com/source/licenses.html
1119 """
1120 LICENSE_HEADER = (
1121 r"""^[#/\*]*
1122[#/\*]* ?Copyright( \([cC]\))? 20[-0-9]{2,7} The Android Open Source Project
1123[#/\*]* ?
1124[#/\*]* ?Licensed under the Apache License, Version 2.0 \(the "License"\);
1125[#/\*]* ?you may not use this file except in compliance with the License\.
1126[#/\*]* ?You may obtain a copy of the License at
1127[#/\*]* ?
1128[#/\*]* ? http://www\.apache\.org/licenses/LICENSE-2\.0
1129[#/\*]* ?
1130[#/\*]* ?Unless required by applicable law or agreed to in writing, software
1131[#/\*]* ?distributed under the License is distributed on an "AS IS" BASIS,
1132[#/\*]* ?WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or """
1133 r"""implied\.
1134[#/\*]* ?See the License for the specific language governing permissions and
1135[#/\*]* ?limitations under the License\.
1136[#/\*]*$
1137"""
1138 )
1139 license_re = re.compile(LICENSE_HEADER, re.MULTILINE)
1140
Amin Hassani391efa92018-01-26 17:58:05 -08001141 included, excluded = _parse_common_inclusion_options(options)
1142
Ken Turnerd07564b2018-02-08 17:57:59 +11001143 files = _filter_files(
1144 _get_affected_files(commit, relative=True),
1145 included + COMMON_INCLUDED_PATHS,
1146 excluded + COMMON_EXCLUDED_PATHS + LICENSE_EXCLUDED_PATHS)
Alex Deymof5792ce2015-08-24 22:50:08 -07001147
1148 bad_files = []
1149 for f in files:
1150 contents = _get_file_content(f, commit)
1151 if not contents:
1152 # Ignore empty files.
1153 continue
1154
1155 if not license_re.search(contents):
1156 bad_files.append(f)
1157
1158 if bad_files:
1159 msg = ('License must match:\n%s\nFound a bad header in these files:' %
1160 license_re.pattern)
1161 return HookFailure(msg, bad_files)
1162
1163
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001164def _check_layout_conf(_project, commit):
1165 """Verifies the metadata/layout.conf file."""
1166 repo_name = 'profiles/repo_name'
Mike Frysinger94a670c2014-09-19 12:46:26 -04001167 repo_names = []
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001168 layout_path = 'metadata/layout.conf'
Mike Frysinger94a670c2014-09-19 12:46:26 -04001169 layout_paths = []
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001170
Mike Frysinger94a670c2014-09-19 12:46:26 -04001171 # Handle multiple overlays in a single commit (like the public tree).
1172 for f in _get_affected_files(commit, relative=True):
1173 if f.endswith(repo_name):
1174 repo_names.append(f)
1175 elif f.endswith(layout_path):
1176 layout_paths.append(f)
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001177
1178 # Disallow new repos with the repo_name file.
Mike Frysinger94a670c2014-09-19 12:46:26 -04001179 if repo_names:
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001180 return HookFailure('%s: use "repo-name" in %s instead' %
Mike Frysinger94a670c2014-09-19 12:46:26 -04001181 (repo_names, layout_path))
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001182
Mike Frysinger94a670c2014-09-19 12:46:26 -04001183 # Gather all the errors in one pass so we show one full message.
1184 all_errors = {}
1185 for layout_path in layout_paths:
1186 all_errors[layout_path] = errors = []
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001187
Mike Frysinger94a670c2014-09-19 12:46:26 -04001188 # Make sure the config file is sorted.
1189 data = [x for x in _get_file_content(layout_path, commit).splitlines()
1190 if x and x[0] != '#']
1191 if sorted(data) != data:
1192 errors += ['keep lines sorted']
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001193
Mike Frysinger94a670c2014-09-19 12:46:26 -04001194 # Require people to set specific values all the time.
1195 settings = (
1196 # TODO: Enable this for everyone. http://crbug.com/408038
1197 #('fast caching', 'cache-format = md5-dict'),
1198 ('fast manifests', 'thin-manifests = true'),
Mike Frysingerd7734522015-02-26 16:12:43 -05001199 ('extra features', 'profile-formats = portage-2 profile-default-eapi'),
1200 ('newer eapi', 'profile_eapi_when_unspecified = 5-progress'),
Mike Frysinger94a670c2014-09-19 12:46:26 -04001201 )
1202 for reason, line in settings:
1203 if line not in data:
1204 errors += ['enable %s with: %s' % (reason, line)]
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001205
Mike Frysinger94a670c2014-09-19 12:46:26 -04001206 # Require one of these settings.
Mike Frysinger5fae62d2015-11-11 20:12:15 -05001207 if 'use-manifests = strict' not in data:
1208 errors += ['enable file checking with: use-manifests = strict']
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001209
Mike Frysinger94a670c2014-09-19 12:46:26 -04001210 # Require repo-name to be set.
Mike Frysinger324cf682014-09-22 15:52:50 -04001211 for line in data:
1212 if line.startswith('repo-name = '):
1213 break
1214 else:
Mike Frysinger94a670c2014-09-19 12:46:26 -04001215 errors += ['set the board name with: repo-name = $BOARD']
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001216
Mike Frysinger94a670c2014-09-19 12:46:26 -04001217 # Summarize all the errors we saw (if any).
1218 lines = ''
1219 for layout_path, errors in all_errors.items():
1220 if errors:
1221 lines += '\n\t- '.join(['\n* %s:' % layout_path] + errors)
1222 if lines:
1223 lines = 'See the portage(5) man page for layout.conf details' + lines + '\n'
1224 return HookFailure(lines)
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001225
1226
Keigo Oka4a09bd92019-05-07 14:01:00 +09001227def _check_no_new_gyp(_project, commit):
1228 """Verifies no project starts to use GYP."""
1229 whitelist = [
Keigo Oka4a09bd92019-05-07 14:01:00 +09001230 'chromeos/ap',
1231 'chromeos/ap-daemons',
Keigo Oka150a6fd2019-06-04 11:30:25 +09001232 'chromeos/ap/security',
1233 'chromeos/ap/wireless',
Keigo Oka4a09bd92019-05-07 14:01:00 +09001234 'chromeos/platform/actions',
Keigo Oka4a09bd92019-05-07 14:01:00 +09001235 'chromeos/platform/drivefs-google3',
1236 'chromeos/platform/experimental-touch-fw',
Keigo Oka4a09bd92019-05-07 14:01:00 +09001237 'chromeos/thermald',
Keigo Oka4a09bd92019-05-07 14:01:00 +09001238 'chromiumos/platform2',
Keigo Oka4a09bd92019-05-07 14:01:00 +09001239 'weave/libweave',
1240 ]
1241 if _project.name in whitelist:
1242 return None
1243
1244 gypfiles = _filter_files(
1245 _get_affected_files(commit, include_symlinks=True, relative=True),
1246 [r'\.gyp$'])
1247
1248 if gypfiles:
1249 return HookFailure('GYP is deprecated and not allowed in a new project:',
1250 gypfiles)
1251
1252
Ryan Cuiec4d6332011-05-02 14:15:25 -07001253# Project-specific hooks
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001254
Ryan Cui1562fb82011-05-09 11:01:31 -07001255
Luis Hector Chavezb50391d2017-09-26 15:48:15 -07001256def _check_clang_format(_project, commit, options=()):
1257 """Runs clang-format on the given project"""
1258 hooks_dir = _get_hooks_dir()
1259 options = list(options)
1260 if commit == PRE_SUBMIT:
1261 options.append('--commit=HEAD')
1262 else:
1263 options.extend(['--commit', commit])
Brian Norris0c62a142018-12-11 13:24:29 -08001264 cmd = [os.path.join(hooks_dir, 'clang-format.py')] + options
Luis Hector Chavezb50391d2017-09-26 15:48:15 -07001265 cmd_result = cros_build_lib.RunCommand(cmd=cmd,
1266 print_cmd=False,
Luis Hector Chavezb50391d2017-09-26 15:48:15 -07001267 stdout_to_pipe=True,
1268 combine_stdout_stderr=True,
1269 error_code_ok=True)
1270 if cmd_result.returncode:
1271 return HookFailure('clang-format.py errors/warnings\n\n' +
1272 cmd_result.output)
1273
1274
Mike Frysingerae409522014-02-01 03:16:11 -05001275def _run_checkpatch(_project, commit, options=()):
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001276 """Runs checkpatch.pl on the given project"""
1277 hooks_dir = _get_hooks_dir()
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001278 options = list(options)
1279 if commit == PRE_SUBMIT:
1280 # The --ignore option must be present and include 'MISSING_SIGN_OFF' in
1281 # this case.
1282 options.append('--ignore=MISSING_SIGN_OFF')
Filipe Brandenburger28d48d62015-10-07 09:48:54 -07001283 # Always ignore the check for the MAINTAINERS file. We do not track that
1284 # information on that file in our source trees, so let's suppress the
1285 # warning.
1286 options.append('--ignore=FILE_PATH_CHANGES')
Filipe Brandenburgerce978322015-10-09 10:04:15 -07001287 # Do not complain about the Change-Id: fields, since we use Gerrit.
1288 # Upstream does not want those lines (since they do not use Gerrit), but
1289 # we always do, so disable the check globally.
Daisuke Nojiri4844f892015-10-08 09:54:33 -07001290 options.append('--ignore=GERRIT_CHANGE_ID')
Brian Norris0c62a142018-12-11 13:24:29 -08001291 cmd = [os.path.join(hooks_dir, 'checkpatch.pl')] + options + ['-']
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001292 cmd_result = cros_build_lib.RunCommand(cmd=cmd,
1293 print_cmd=False,
1294 input=_get_patch(commit),
1295 stdout_to_pipe=True,
1296 combine_stdout_stderr=True,
1297 error_code_ok=True)
1298 if cmd_result.returncode:
1299 return HookFailure('checkpatch.pl errors/warnings\n\n' + cmd_result.output)
Ryan Cuiec4d6332011-05-02 14:15:25 -07001300
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001301
Brian Norris23c62e92018-11-14 12:25:51 -08001302def _run_kerneldoc(_project, commit, options=()):
1303 """Runs kernel-doc validator on the given project"""
1304 included, excluded = _parse_common_inclusion_options(options)
1305 files = _filter_files(_get_affected_files(commit, relative=True),
1306 included, excluded)
1307 if files:
1308 hooks_dir = _get_hooks_dir()
Brian Norris0c62a142018-12-11 13:24:29 -08001309 cmd = [os.path.join(hooks_dir, 'kernel-doc'), '-none'] + files
Brian Norris23c62e92018-11-14 12:25:51 -08001310 output = _run_command(cmd=cmd, combine_stdout_stderr=True)
1311 if output:
Brian Norris0c62a142018-12-11 13:24:29 -08001312 return HookFailure('kernel-doc errors/warnings:',
1313 items=output.splitlines())
Brian Norris23c62e92018-11-14 12:25:51 -08001314
1315
Mike Frysingerae409522014-02-01 03:16:11 -05001316def _kernel_configcheck(_project, commit):
Olof Johanssona96810f2012-09-04 16:20:03 -07001317 """Makes sure kernel config changes are not mixed with code changes"""
1318 files = _get_affected_files(commit)
1319 if not len(_filter_files(files, [r'chromeos/config'])) in [0, len(files)]:
1320 return HookFailure('Changes to chromeos/config/ and regular files must '
1321 'be in separate commits:\n%s' % '\n'.join(files))
Anton Staaf815d6852011-08-22 10:08:45 -07001322
Mike Frysingerae409522014-02-01 03:16:11 -05001323
1324def _run_json_check(_project, commit):
Dale Curtis2975c432011-05-03 17:25:20 -07001325 """Checks that all JSON files are syntactically valid."""
Mike Frysinger908be682018-01-04 02:21:50 -05001326 ret = []
1327
1328 files = _filter_files(_get_affected_files(commit, relative=True),
1329 [r'.*\.json$'])
1330 for f in files:
1331 data = _get_file_content(f, commit)
Dale Curtis2975c432011-05-03 17:25:20 -07001332 try:
Mike Frysinger908be682018-01-04 02:21:50 -05001333 json.loads(data)
1334 except Exception as e:
1335 ret.append('%s: Invalid JSON: %s' % (f, e))
1336
1337 if ret:
1338 return HookFailure('\n'.join(ret))
Dale Curtis2975c432011-05-03 17:25:20 -07001339
1340
Mike Frysingerae409522014-02-01 03:16:11 -05001341def _check_manifests(_project, commit):
Mike Frysingeraae3cb52018-01-03 16:49:33 -05001342 """Make sure Manifest files only have comments & DIST lines."""
1343 ret = []
Mike Frysinger52b537e2013-08-22 22:59:53 -04001344
Mike Frysingeraae3cb52018-01-03 16:49:33 -05001345 manifests = _filter_files(_get_affected_files(commit, relative=True),
1346 [r'.*/Manifest$'])
1347 for path in manifests:
1348 data = _get_file_content(path, commit)
1349
1350 # Disallow blank files.
1351 if not data.strip():
1352 ret.append('%s: delete empty file' % (path,))
Mike Frysinger52b537e2013-08-22 22:59:53 -04001353 continue
1354
Mike Frysingeraae3cb52018-01-03 16:49:33 -05001355 # Make sure the last newline isn't omitted.
1356 if data[-1] != '\n':
1357 ret.append('%s: missing trailing newline' % (path,))
Mike Frysinger52b537e2013-08-22 22:59:53 -04001358
Mike Frysingeraae3cb52018-01-03 16:49:33 -05001359 # Do not allow leading or trailing blank lines.
1360 lines = data.splitlines()
1361 if not lines[0]:
1362 ret.append('%s: delete leading blank lines' % (path,))
1363 if not lines[-1]:
1364 ret.append('%s: delete trailing blank lines' % (path,))
1365
1366 for line in lines:
1367 # Disallow leading/trailing whitespace.
1368 if line != line.strip():
1369 ret.append('%s: remove leading/trailing whitespace: %s' % (path, line))
1370
1371 # Allow blank lines & comments.
1372 line = line.split('#', 1)[0]
1373 if not line:
1374 continue
1375
1376 # All other linse should start with DIST.
1377 if not line.startswith('DIST '):
1378 ret.append('%s: remove non-DIST lines: %s' % (path, line))
1379 break
1380
1381 if ret:
1382 return HookFailure('\n'.join(ret))
Mike Frysinger52b537e2013-08-22 22:59:53 -04001383
1384
Mike Frysingerae409522014-02-01 03:16:11 -05001385def _check_change_has_branch_field(_project, commit):
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001386 """Check for a non-empty 'BRANCH=' field in the commit message."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001387 if commit == PRE_SUBMIT:
1388 return
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001389 BRANCH_RE = r'\nBRANCH=\S+'
1390
1391 if not re.search(BRANCH_RE, _get_commit_desc(commit)):
1392 msg = ('Changelist description needs BRANCH field (after first line)\n'
1393 'E.g. BRANCH=none or BRANCH=link,snow')
1394 return HookFailure(msg)
1395
1396
Mike Frysingerae409522014-02-01 03:16:11 -05001397def _check_change_has_signoff_field(_project, commit):
Shawn Nematbakhsh51e16ac2014-01-28 15:31:07 -08001398 """Check for a non-empty 'Signed-off-by:' field in the commit message."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001399 if commit == PRE_SUBMIT:
1400 return
Shawn Nematbakhsh51e16ac2014-01-28 15:31:07 -08001401 SIGNOFF_RE = r'\nSigned-off-by: \S+'
1402
1403 if not re.search(SIGNOFF_RE, _get_commit_desc(commit)):
1404 msg = ('Changelist description needs Signed-off-by: field\n'
1405 'E.g. Signed-off-by: My Name <me@chromium.org>')
1406 return HookFailure(msg)
1407
1408
Aviv Keshet5ac59522017-01-31 14:28:27 -08001409def _check_cq_ini_well_formed(_project, commit):
1410 """Check that any modified COMMIT-QUEUE.ini files are well formed."""
1411 pattern = '.*' + constants.CQ_CONFIG_FILENAME
Mike Frysingerd0523442018-01-03 17:05:29 -05001412 files = _filter_files(_get_affected_files(commit, relative=True), (pattern,))
Aviv Keshet5ac59522017-01-31 14:28:27 -08001413
1414 # TODO(akeshet): Check not only that the file is parseable, but that all the
1415 # pre-cq configs it requests are existing ones.
1416 for f in files:
1417 try:
1418 parser = ConfigParser.SafeConfigParser()
1419 # Prior to python3, ConfigParser has no read_string method, so we must
1420 # pass it either a file path or file like object. And we must use
1421 # _get_file_content to fetch file contents to ensure we are examining the
1422 # commit diff, rather than whatever's on disk.
1423 contents = _get_file_content(f, commit)
1424 parser.readfp(StringIO.StringIO(contents))
1425 except ConfigParser.Error as e:
1426 msg = ('Unable to parse COMMIT-QUEUE.ini file at %s due to %s.' %
1427 (f, e))
1428 return HookFailure(msg)
1429
1430
Jon Salz3ee59de2012-08-18 13:54:22 +08001431def _run_project_hook_script(script, project, commit):
1432 """Runs a project hook script.
1433
1434 The script is run with the following environment variables set:
1435 PRESUBMIT_PROJECT: The affected project
1436 PRESUBMIT_COMMIT: The affected commit
1437 PRESUBMIT_FILES: A newline-separated list of affected files
1438
1439 The script is considered to fail if the exit code is non-zero. It should
1440 write an error message to stdout.
1441 """
1442 env = dict(os.environ)
Alex Deymo643ac4c2015-09-03 10:40:50 -07001443 env['PRESUBMIT_PROJECT'] = project.name
Jon Salz3ee59de2012-08-18 13:54:22 +08001444 env['PRESUBMIT_COMMIT'] = commit
1445
1446 # Put affected files in an environment variable
1447 files = _get_affected_files(commit)
1448 env['PRESUBMIT_FILES'] = '\n'.join(files)
1449
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001450 cmd_result = cros_build_lib.RunCommand(cmd=script,
1451 env=env,
1452 shell=True,
1453 print_cmd=False,
1454 input=os.devnull,
1455 stdout_to_pipe=True,
1456 combine_stdout_stderr=True,
1457 error_code_ok=True)
1458 if cmd_result.returncode:
1459 stdout = cmd_result.output
Jon Salz7b618af2012-08-31 06:03:16 +08001460 if stdout:
1461 stdout = re.sub('(?m)^', ' ', stdout)
1462 return HookFailure('Hook script "%s" failed with code %d%s' %
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001463 (script, cmd_result.returncode,
Jon Salz3ee59de2012-08-18 13:54:22 +08001464 ':\n' + stdout if stdout else ''))
1465
1466
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001467def _check_project_prefix(_project, commit):
Mike Frysinger55f85b52014-12-18 14:45:21 -05001468 """Require the commit message have a project specific prefix as needed."""
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001469
Brian Norris77608e12018-04-06 10:38:43 -07001470 files = _get_affected_files(commit, include_deletes=True, relative=True)
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001471 prefix = os.path.commonprefix(files)
1472 prefix = os.path.dirname(prefix)
1473
1474 # If there is no common prefix, the CL span multiple projects.
Daniel Erata350fd32014-09-29 14:02:34 -07001475 if not prefix:
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001476 return
1477
1478 project_name = prefix.split('/')[0]
Daniel Erata350fd32014-09-29 14:02:34 -07001479
1480 # The common files may all be within a subdirectory of the main project
1481 # directory, so walk up the tree until we find an alias file.
1482 # _get_affected_files() should return relative paths, but check against '/' to
1483 # ensure that this loop terminates even if it receives an absolute path.
1484 while prefix and prefix != '/':
1485 alias_file = os.path.join(prefix, '.project_alias')
1486
1487 # If an alias exists, use it.
1488 if os.path.isfile(alias_file):
1489 project_name = osutils.ReadFile(alias_file).strip()
1490
1491 prefix = os.path.dirname(prefix)
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001492
1493 if not _get_commit_desc(commit).startswith(project_name + ': '):
1494 return HookFailure('The commit title for changes affecting only %s'
1495 ' should start with \"%s: \"'
1496 % (project_name, project_name))
1497
1498
Satoru Takabayashi15d17a52018-08-06 11:12:15 +09001499def _check_filepath_chartype(_project, commit):
1500 """Checks that FilePath::CharType stuff is not used."""
1501
1502 FILEPATH_REGEXP = re.compile('|'.join(
1503 [r'(?:base::)?FilePath::(?:Char|String|StringPiece)Type',
Satoru Takabayashi4ca37922018-08-08 10:16:38 +09001504 r'(?:base::)?FilePath::FromUTF8Unsafe',
1505 r'AsUTF8Unsafe',
Satoru Takabayashi15d17a52018-08-06 11:12:15 +09001506 r'FILE_PATH_LITERAL']))
1507 files = _filter_files(_get_affected_files(commit, relative=True),
1508 [r'.*\.(cc|h)$'])
1509
1510 errors = []
1511 for afile in files:
1512 for line_num, line in _get_file_diff(afile, commit):
1513 m = re.search(FILEPATH_REGEXP, line)
1514 if m:
1515 errors.append('%s, line %s has %s' % (afile, line_num, m.group(0)))
1516
1517 if errors:
1518 msg = 'Please assume FilePath::CharType is char (crbug.com/870621):'
1519 return HookFailure(msg, errors)
1520
1521
Mike Frysingerf9d41b32017-02-23 15:20:04 -05001522def _check_exec_files(_project, commit):
1523 """Make +x bits on files."""
1524 # List of files that should never be +x.
1525 NO_EXEC = (
1526 'ChangeLog*',
1527 'COPYING',
1528 'make.conf',
1529 'make.defaults',
1530 'Manifest',
1531 'OWNERS',
1532 'package.use',
1533 'package.keywords',
1534 'package.mask',
1535 'parent',
1536 'README',
1537 'TODO',
1538 '.gitignore',
1539 '*.[achly]',
1540 '*.[ch]xx',
1541 '*.boto',
1542 '*.cc',
1543 '*.cfg',
1544 '*.conf',
1545 '*.config',
1546 '*.cpp',
1547 '*.css',
1548 '*.ebuild',
1549 '*.eclass',
Tatsuhisa Yamaguchi3b053632019-01-10 14:45:14 +09001550 '*.gn',
1551 '*.gni',
Mike Frysingerf9d41b32017-02-23 15:20:04 -05001552 '*.gyp',
1553 '*.gypi',
1554 '*.htm',
1555 '*.html',
1556 '*.ini',
1557 '*.js',
1558 '*.json',
1559 '*.md',
1560 '*.mk',
1561 '*.patch',
1562 '*.policy',
1563 '*.proto',
1564 '*.raw',
1565 '*.rules',
1566 '*.service',
1567 '*.target',
1568 '*.txt',
1569 '*.xml',
1570 '*.yaml',
1571 )
1572
1573 def FinalName(obj):
1574 # If the file is being deleted, then the dst_file is not set.
1575 if obj.dst_file is None:
1576 return obj.src_file
1577 else:
1578 return obj.dst_file
1579
1580 bad_files = []
1581 files = _get_affected_files(commit, relative=True, full_details=True)
1582 for f in files:
1583 mode = int(f.dst_mode, 8)
1584 if not mode & 0o111:
1585 continue
1586 name = FinalName(f)
1587 for no_exec in NO_EXEC:
1588 if fnmatch.fnmatch(name, no_exec):
1589 bad_files.append(name)
1590 break
1591
1592 if bad_files:
1593 return HookFailure('These files should not be executable. '
1594 'Please `chmod -x` them.', bad_files)
1595
1596
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001597# Base
1598
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001599# A list of hooks which are not project specific and check patch description
1600# (as opposed to patch body).
1601_PATCH_DESCRIPTION_HOOKS = [
Ryan Cui9b651632011-05-11 11:38:58 -07001602 _check_change_has_bug_field,
David Jamesc3b68b32013-04-03 09:17:03 -07001603 _check_change_has_valid_cq_depend,
Ryan Cui9b651632011-05-11 11:38:58 -07001604 _check_change_has_test_field,
1605 _check_change_has_proper_changeid,
Mike Frysinger36b2ebc2014-10-31 14:02:03 -04001606 _check_commit_message_style,
Bernie Thompsonf8fea992016-01-14 10:27:18 -08001607 _check_change_is_contribution,
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001608]
1609
1610
1611# A list of hooks that are not project-specific
1612_COMMON_HOOKS = [
Aviv Keshet5ac59522017-01-31 14:28:27 -08001613 _check_cq_ini_well_formed,
1614 _check_cros_license,
Mike Frysingerbf8b91c2014-02-01 02:50:27 -05001615 _check_ebuild_eapi,
Mike Frysinger89bdb852014-02-01 05:26:26 -05001616 _check_ebuild_keywords,
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -08001617 _check_ebuild_licenses,
Mike Frysingercd363c82014-02-01 05:20:18 -05001618 _check_ebuild_virtual_pv,
Mike Frysingerf9d41b32017-02-23 15:20:04 -05001619 _check_exec_files,
Daniel Erat9d203ff2015-02-17 10:12:21 -07001620 _check_for_uprev,
Rahul Chaudhry09f61372015-07-31 17:14:26 -07001621 _check_gofmt,
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001622 _check_layout_conf,
Daniel Erat9d203ff2015-02-17 10:12:21 -07001623 _check_no_long_lines,
Keigo Oka4a09bd92019-05-07 14:01:00 +09001624 _check_no_new_gyp,
Daniel Erat9d203ff2015-02-17 10:12:21 -07001625 _check_no_stray_whitespace,
Ryan Cui9b651632011-05-11 11:38:58 -07001626 _check_no_tabs,
Daniel Erat9d203ff2015-02-17 10:12:21 -07001627 _check_portage_make_use_var,
Aviv Keshet5ac59522017-01-31 14:28:27 -08001628 _check_tabbed_indents,
Ryan Cui9b651632011-05-11 11:38:58 -07001629]
Ryan Cuiec4d6332011-05-02 14:15:25 -07001630
Ryan Cui1562fb82011-05-09 11:01:31 -07001631
Ryan Cui9b651632011-05-11 11:38:58 -07001632# A dictionary of project-specific hooks(callbacks), indexed by project name.
1633# dict[project] = [callback1, callback2]
1634_PROJECT_SPECIFIC_HOOKS = {
Mike Frysingeraf891292015-03-25 19:46:53 -04001635 "chromiumos/third_party/kernel": [_kernel_configcheck],
1636 "chromiumos/third_party/kernel-next": [_kernel_configcheck],
Ryan Cui9b651632011-05-11 11:38:58 -07001637}
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001638
Ryan Cui1562fb82011-05-09 11:01:31 -07001639
Ryan Cui9b651632011-05-11 11:38:58 -07001640# A dictionary of flags (keys) that can appear in the config file, and the hook
Mike Frysinger3554bc92015-03-11 04:59:21 -04001641# that the flag controls (value).
1642_HOOK_FLAGS = {
Luis Hector Chavezb50391d2017-09-26 15:48:15 -07001643 'clang_format_check': _check_clang_format,
Mike Frysingera7642f52015-03-25 18:31:42 -04001644 'checkpatch_check': _run_checkpatch,
Brian Norris23c62e92018-11-14 12:25:51 -08001645 'kerneldoc_check': _run_kerneldoc,
Ryan Cui9b651632011-05-11 11:38:58 -07001646 'stray_whitespace_check': _check_no_stray_whitespace,
Mike Frysingerff6c7d62015-03-24 13:49:46 -04001647 'json_check': _run_json_check,
Ryan Cui9b651632011-05-11 11:38:58 -07001648 'long_line_check': _check_no_long_lines,
Alex Deymof5792ce2015-08-24 22:50:08 -07001649 'cros_license_check': _check_cros_license,
1650 'aosp_license_check': _check_aosp_license,
Ryan Cui9b651632011-05-11 11:38:58 -07001651 'tab_check': _check_no_tabs,
Prathmesh Prabhuc5254652016-12-22 12:58:05 -08001652 'tabbed_indent_required_check': _check_tabbed_indents,
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001653 'branch_check': _check_change_has_branch_field,
Shawn Nematbakhsh51e16ac2014-01-28 15:31:07 -08001654 'signoff_check': _check_change_has_signoff_field,
Josh Triplett0e8fc7f2014-04-23 16:00:00 -07001655 'bug_field_check': _check_change_has_bug_field,
1656 'test_field_check': _check_change_has_test_field,
Steve Fung49ec7e92015-03-23 16:07:12 -07001657 'manifest_check': _check_manifests,
Bernie Thompsonf8fea992016-01-14 10:27:18 -08001658 'contribution_check': _check_change_is_contribution,
Mike Frysinger47bd1252018-06-11 12:12:20 -04001659 'project_prefix_check': _check_project_prefix,
Satoru Takabayashi15d17a52018-08-06 11:12:15 +09001660 'filepath_chartype_check': _check_filepath_chartype,
Ryan Cui9b651632011-05-11 11:38:58 -07001661}
1662
1663
Mike Frysinger3554bc92015-03-11 04:59:21 -04001664def _get_override_hooks(config):
1665 """Returns a set of hooks controlled by the current project's config file.
Ryan Cui9b651632011-05-11 11:38:58 -07001666
1667 Expects to be called within the project root.
Jon Salz3ee59de2012-08-18 13:54:22 +08001668
1669 Args:
1670 config: A ConfigParser for the project's config file.
Ryan Cui9b651632011-05-11 11:38:58 -07001671 """
1672 SECTION = 'Hook Overrides'
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001673 SECTION_OPTIONS = 'Hook Overrides Options'
Jon Salz3ee59de2012-08-18 13:54:22 +08001674 if not config.has_section(SECTION):
Mike Frysinger3554bc92015-03-11 04:59:21 -04001675 return set(), set()
Ryan Cui9b651632011-05-11 11:38:58 -07001676
Mike Frysinger3554bc92015-03-11 04:59:21 -04001677 valid_keys = set(_HOOK_FLAGS.iterkeys())
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001678 hooks = _HOOK_FLAGS.copy()
Mike Frysinger3554bc92015-03-11 04:59:21 -04001679
1680 enable_flags = []
Ryan Cui9b651632011-05-11 11:38:58 -07001681 disable_flags = []
Jon Salz3ee59de2012-08-18 13:54:22 +08001682 for flag in config.options(SECTION):
Mike Frysinger3554bc92015-03-11 04:59:21 -04001683 if flag not in valid_keys:
1684 raise ValueError('Error: unknown key "%s" in hook section of "%s"' %
1685 (flag, _CONFIG_FILE))
1686
Ryan Cui9b651632011-05-11 11:38:58 -07001687 try:
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001688 enabled = config.getboolean(SECTION, flag)
Ryan Cui9b651632011-05-11 11:38:58 -07001689 except ValueError as e:
Mike Frysinger3554bc92015-03-11 04:59:21 -04001690 raise ValueError('Error: parsing flag "%s" in "%s" failed: %s' %
1691 (flag, _CONFIG_FILE, e))
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001692 if enabled:
1693 enable_flags.append(flag)
1694 else:
1695 disable_flags.append(flag)
Ryan Cui9b651632011-05-11 11:38:58 -07001696
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001697 # See if this hook has custom options.
1698 if enabled:
1699 try:
1700 options = config.get(SECTION_OPTIONS, flag)
1701 hooks[flag] = functools.partial(hooks[flag], options=options.split())
Mike Frysingerb7d552e2017-11-23 11:50:47 -05001702 hooks[flag].__name__ = flag
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001703 except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
1704 pass
1705
1706 enabled_hooks = set(hooks[x] for x in enable_flags)
1707 disabled_hooks = set(hooks[x] for x in disable_flags)
Mike Frysinger3554bc92015-03-11 04:59:21 -04001708 return enabled_hooks, disabled_hooks
Ryan Cui9b651632011-05-11 11:38:58 -07001709
1710
Jon Salz3ee59de2012-08-18 13:54:22 +08001711def _get_project_hook_scripts(config):
1712 """Returns a list of project-specific hook scripts.
1713
1714 Args:
1715 config: A ConfigParser for the project's config file.
1716 """
1717 SECTION = 'Hook Scripts'
1718 if not config.has_section(SECTION):
1719 return []
1720
Mike Frysingerb7d552e2017-11-23 11:50:47 -05001721 return config.items(SECTION)
Jon Salz3ee59de2012-08-18 13:54:22 +08001722
1723
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001724def _get_project_hooks(project, presubmit):
Ryan Cui9b651632011-05-11 11:38:58 -07001725 """Returns a list of hooks that need to be run for a project.
1726
1727 Expects to be called from within the project root.
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001728
1729 Args:
1730 project: A string, name of the project.
1731 presubmit: A Boolean, True if the check is run as a git pre-submit script.
Ryan Cui9b651632011-05-11 11:38:58 -07001732 """
Jon Salz3ee59de2012-08-18 13:54:22 +08001733 config = ConfigParser.RawConfigParser()
1734 try:
1735 config.read(_CONFIG_FILE)
1736 except ConfigParser.Error:
1737 # Just use an empty config file
1738 config = ConfigParser.RawConfigParser()
1739
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001740 if presubmit:
Filipe Brandenburgerf70d32c2015-10-09 13:35:45 -07001741 hooks = _COMMON_HOOKS
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001742 else:
Filipe Brandenburgerf70d32c2015-10-09 13:35:45 -07001743 hooks = _PATCH_DESCRIPTION_HOOKS + _COMMON_HOOKS
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001744
Mike Frysinger3554bc92015-03-11 04:59:21 -04001745 enabled_hooks, disabled_hooks = _get_override_hooks(config)
Filipe Brandenburgerf70d32c2015-10-09 13:35:45 -07001746 hooks = [hook for hook in hooks if hook not in disabled_hooks]
1747
1748 # If a list is both in _COMMON_HOOKS and also enabled explicitly through an
1749 # override, keep the override only. Note that the override may end up being
1750 # a functools.partial, in which case we need to extract the .func to compare
1751 # it to the common hooks.
1752 unwrapped_hooks = [getattr(hook, 'func', hook) for hook in enabled_hooks]
1753 hooks = [hook for hook in hooks if hook not in unwrapped_hooks]
1754
1755 hooks = list(enabled_hooks) + hooks
Ryan Cui9b651632011-05-11 11:38:58 -07001756
1757 if project in _PROJECT_SPECIFIC_HOOKS:
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001758 hooks.extend(hook for hook in _PROJECT_SPECIFIC_HOOKS[project]
1759 if hook not in disabled_hooks)
Ryan Cui9b651632011-05-11 11:38:58 -07001760
Mike Frysingerb7d552e2017-11-23 11:50:47 -05001761 for name, script in _get_project_hook_scripts(config):
1762 func = functools.partial(_run_project_hook_script, script)
1763 func.__name__ = name
1764 hooks.append(func)
Jon Salz3ee59de2012-08-18 13:54:22 +08001765
Ryan Cui9b651632011-05-11 11:38:58 -07001766 return hooks
1767
1768
Alex Deymo643ac4c2015-09-03 10:40:50 -07001769def _run_project_hooks(project_name, proj_dir=None,
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001770 commit_list=None, presubmit=False):
Ryan Cui1562fb82011-05-09 11:01:31 -07001771 """For each project run its project specific hook from the hooks dictionary.
1772
1773 Args:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001774 project_name: The name of project to run hooks for.
Doug Anderson44a644f2011-11-02 10:37:37 -07001775 proj_dir: If non-None, this is the directory the project is in. If None,
1776 we'll ask repo.
Doug Anderson14749562013-06-26 13:38:29 -07001777 commit_list: A list of commits to run hooks against. If None or empty list
1778 then we'll automatically get the list of commits that would be uploaded.
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001779 presubmit: A Boolean, True if the check is run as a git pre-submit script.
Ryan Cui1562fb82011-05-09 11:01:31 -07001780
1781 Returns:
1782 Boolean value of whether any errors were ecountered while running the hooks.
1783 """
Doug Anderson44a644f2011-11-02 10:37:37 -07001784 if proj_dir is None:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001785 proj_dirs = _run_command(
1786 ['repo', 'forall', project_name, '-c', 'pwd']).split()
David James2edd9002013-10-11 14:09:19 -07001787 if len(proj_dirs) == 0:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001788 print('%s cannot be found.' % project_name, file=sys.stderr)
David James2edd9002013-10-11 14:09:19 -07001789 print('Please specify a valid project.', file=sys.stderr)
1790 return True
1791 if len(proj_dirs) > 1:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001792 print('%s is associated with multiple directories.' % project_name,
David James2edd9002013-10-11 14:09:19 -07001793 file=sys.stderr)
1794 print('Please specify a directory to help disambiguate.', file=sys.stderr)
1795 return True
1796 proj_dir = proj_dirs[0]
Doug Anderson44a644f2011-11-02 10:37:37 -07001797
Ryan Cuiec4d6332011-05-02 14:15:25 -07001798 pwd = os.getcwd()
1799 # hooks assume they are run from the root of the project
1800 os.chdir(proj_dir)
1801
Alex Deymo643ac4c2015-09-03 10:40:50 -07001802 remote_branch = _run_command(['git', 'rev-parse', '--abbrev-ref',
1803 '--symbolic-full-name', '@{u}']).strip()
1804 if not remote_branch:
1805 print('Your project %s doesn\'t track any remote repo.' % project_name,
1806 file=sys.stderr)
1807 remote = None
1808 else:
Josh Pratt15d13ab2018-08-13 11:52:48 +10001809 branch_items = remote_branch.split('/', 1)
1810 if len(branch_items) != 2:
1811 PrintErrorForProject(
1812 project_name,
1813 HookFailure(
1814 'Cannot get remote and branch name (%s)' % remote_branch))
1815 os.chdir(pwd)
1816 return True
1817 remote, _branch = branch_items
Alex Deymo643ac4c2015-09-03 10:40:50 -07001818
1819 project = Project(name=project_name, dir=proj_dir, remote=remote)
1820
Doug Anderson14749562013-06-26 13:38:29 -07001821 if not commit_list:
1822 try:
1823 commit_list = _get_commits()
1824 except VerifyException as e:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001825 PrintErrorForProject(project.name, HookFailure(str(e)))
Doug Anderson14749562013-06-26 13:38:29 -07001826 os.chdir(pwd)
1827 return True
Ryan Cuifa55df52011-05-06 11:16:55 -07001828
Alex Deymo643ac4c2015-09-03 10:40:50 -07001829 hooks = _get_project_hooks(project.name, presubmit)
Ryan Cui1562fb82011-05-09 11:01:31 -07001830 error_found = False
Mike Frysingerb7d552e2017-11-23 11:50:47 -05001831 commit_count = len(commit_list)
1832 for i, commit in enumerate(commit_list):
Ryan Cui1562fb82011-05-09 11:01:31 -07001833 error_list = []
Ryan Cui9b651632011-05-11 11:38:58 -07001834 for hook in hooks:
Mike Frysingerb7d552e2017-11-23 11:50:47 -05001835 output = ('PRESUBMIT.cfg: [%i/%i]: %s: Running %s' %
1836 (i + 1, commit_count, commit, hook.__name__))
1837 print(output, end='\r')
1838 sys.stdout.flush()
Ryan Cui1562fb82011-05-09 11:01:31 -07001839 hook_error = hook(project, commit)
Mike Frysingerb7d552e2017-11-23 11:50:47 -05001840 print(' ' * len(output), end='\r')
1841 sys.stdout.flush()
Ryan Cui1562fb82011-05-09 11:01:31 -07001842 if hook_error:
1843 error_list.append(hook_error)
1844 error_found = True
1845 if error_list:
Alex Deymo643ac4c2015-09-03 10:40:50 -07001846 PrintErrorsForCommit(project.name, commit, _get_commit_desc(commit),
Ryan Cui1562fb82011-05-09 11:01:31 -07001847 error_list)
Don Garrettdba548a2011-05-05 15:17:14 -07001848
Ryan Cuiec4d6332011-05-02 14:15:25 -07001849 os.chdir(pwd)
Ryan Cui1562fb82011-05-09 11:01:31 -07001850 return error_found
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001851
Mike Frysingerae409522014-02-01 03:16:11 -05001852
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001853# Main
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -07001854
Ryan Cui1562fb82011-05-09 11:01:31 -07001855
Mike Frysingerae409522014-02-01 03:16:11 -05001856def main(project_list, worktree_list=None, **_kwargs):
Doug Anderson06456632012-01-05 11:02:14 -08001857 """Main function invoked directly by repo.
1858
1859 This function will exit directly upon error so that repo doesn't print some
1860 obscure error message.
1861
1862 Args:
1863 project_list: List of projects to run on.
David James2edd9002013-10-11 14:09:19 -07001864 worktree_list: A list of directories. It should be the same length as
1865 project_list, so that each entry in project_list matches with a directory
1866 in worktree_list. If None, we will attempt to calculate the directories
1867 automatically.
Doug Anderson06456632012-01-05 11:02:14 -08001868 kwargs: Leave this here for forward-compatibility.
1869 """
Ryan Cui1562fb82011-05-09 11:01:31 -07001870 found_error = False
David James2edd9002013-10-11 14:09:19 -07001871 if not worktree_list:
1872 worktree_list = [None] * len(project_list)
1873 for project, worktree in zip(project_list, worktree_list):
1874 if _run_project_hooks(project, proj_dir=worktree):
Ryan Cui1562fb82011-05-09 11:01:31 -07001875 found_error = True
1876
Mike Frysingerae409522014-02-01 03:16:11 -05001877 if found_error:
Ryan Cui1562fb82011-05-09 11:01:31 -07001878 msg = ('Preupload failed due to errors in project(s). HINTS:\n'
Ryan Cui9b651632011-05-11 11:38:58 -07001879 '- To disable some source style checks, and for other hints, see '
1880 '<checkout_dir>/src/repohooks/README\n'
1881 '- To upload only current project, run \'repo upload .\'')
Mike Frysinger09d6a3d2013-10-08 22:21:03 -04001882 print(msg, file=sys.stderr)
Don Garrettdba548a2011-05-05 15:17:14 -07001883 sys.exit(1)
Anush Elangovan63afad72011-03-23 00:41:27 -07001884
Ryan Cui1562fb82011-05-09 11:01:31 -07001885
Doug Anderson44a644f2011-11-02 10:37:37 -07001886def _identify_project(path):
1887 """Identify the repo project associated with the given path.
1888
1889 Returns:
1890 A string indicating what project is associated with the path passed in or
1891 a blank string upon failure.
1892 """
1893 return _run_command(['repo', 'forall', '.', '-c', 'echo ${REPO_PROJECT}'],
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001894 redirect_stderr=True, cwd=path).strip()
Doug Anderson44a644f2011-11-02 10:37:37 -07001895
1896
Mike Frysinger55f85b52014-12-18 14:45:21 -05001897def direct_main(argv):
Doug Anderson44a644f2011-11-02 10:37:37 -07001898 """Run hooks directly (outside of the context of repo).
1899
Doug Anderson44a644f2011-11-02 10:37:37 -07001900 Args:
Mike Frysinger55f85b52014-12-18 14:45:21 -05001901 argv: The command line args to process
Doug Anderson44a644f2011-11-02 10:37:37 -07001902
1903 Returns:
1904 0 if no pre-upload failures, 1 if failures.
1905
1906 Raises:
1907 BadInvocation: On some types of invocation errors.
1908 """
Mike Frysinger66142932014-12-18 14:55:57 -05001909 parser = commandline.ArgumentParser(description=__doc__)
1910 parser.add_argument('--dir', default=None,
1911 help='The directory that the project lives in. If not '
1912 'specified, use the git project root based on the cwd.')
1913 parser.add_argument('--project', default=None,
1914 help='The project repo path; this can affect how the '
1915 'hooks get run, since some hooks are project-specific. '
1916 'For chromite this is chromiumos/chromite. If not '
1917 'specified, the repo tool will be used to figure this '
1918 'out based on the dir.')
1919 parser.add_argument('--rerun-since', default=None,
Vadim Bendebury75447b92018-01-10 12:06:01 -08001920 help='Rerun hooks on old commits since some point '
1921 'in the past. The argument could be a date (should '
1922 'match git log\'s concept of a date, e.g. 2012-06-20), '
1923 'or a SHA1, or just a number of commits to check (from 1 '
1924 'to 99). This option is mutually exclusive with '
1925 '--pre-submit.')
Mike Frysinger66142932014-12-18 14:55:57 -05001926 parser.add_argument('--pre-submit', action="store_true",
1927 help='Run the check against the pending commit. '
1928 'This option should be used at the \'git commit\' '
1929 'phase as opposed to \'repo upload\'. This option '
1930 'is mutually exclusive with --rerun-since.')
1931 parser.add_argument('commits', nargs='*',
1932 help='Check specific commits')
1933 opts = parser.parse_args(argv)
Doug Anderson44a644f2011-11-02 10:37:37 -07001934
Doug Anderson14749562013-06-26 13:38:29 -07001935 if opts.rerun_since:
Mike Frysinger66142932014-12-18 14:55:57 -05001936 if opts.commits:
Doug Anderson14749562013-06-26 13:38:29 -07001937 raise BadInvocation('Can\'t pass commits and use rerun-since: %s' %
Mike Frysinger66142932014-12-18 14:55:57 -05001938 ' '.join(opts.commits))
Doug Anderson14749562013-06-26 13:38:29 -07001939
Vadim Bendebury75447b92018-01-10 12:06:01 -08001940 if len(opts.rerun_since) < 3 and opts.rerun_since.isdigit():
1941 # This must be the number of commits to check. We don't expect the user
1942 # to want to check more than 99 commits.
1943 limit = '-n%s' % opts.rerun_since
1944 elif git.IsSHA1(opts.rerun_since, False):
1945 limit = '%s..' % opts.rerun_since
1946 else:
1947 # This better be a date.
1948 limit = '--since=%s' % opts.rerun_since
1949 cmd = ['git', 'log', limit, '--pretty=%H']
Doug Anderson14749562013-06-26 13:38:29 -07001950 all_commits = _run_command(cmd).splitlines()
1951 bot_commits = _run_command(cmd + ['--author=chrome-bot']).splitlines()
1952
1953 # Eliminate chrome-bot commits but keep ordering the same...
1954 bot_commits = set(bot_commits)
Mike Frysinger66142932014-12-18 14:55:57 -05001955 opts.commits = [c for c in all_commits if c not in bot_commits]
Doug Anderson14749562013-06-26 13:38:29 -07001956
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001957 if opts.pre_submit:
1958 raise BadInvocation('rerun-since and pre-submit can not be '
1959 'used together')
1960 if opts.pre_submit:
Mike Frysinger66142932014-12-18 14:55:57 -05001961 if opts.commits:
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001962 raise BadInvocation('Can\'t pass commits and use pre-submit: %s' %
Mike Frysinger66142932014-12-18 14:55:57 -05001963 ' '.join(opts.commits))
1964 opts.commits = [PRE_SUBMIT,]
Doug Anderson44a644f2011-11-02 10:37:37 -07001965
1966 # Check/normlaize git dir; if unspecified, we'll use the root of the git
1967 # project from CWD
1968 if opts.dir is None:
1969 git_dir = _run_command(['git', 'rev-parse', '--git-dir'],
Rahul Chaudhry0e515342015-08-07 12:00:43 -07001970 redirect_stderr=True).strip()
Doug Anderson44a644f2011-11-02 10:37:37 -07001971 if not git_dir:
1972 raise BadInvocation('The current directory is not part of a git project.')
1973 opts.dir = os.path.dirname(os.path.abspath(git_dir))
1974 elif not os.path.isdir(opts.dir):
1975 raise BadInvocation('Invalid dir: %s' % opts.dir)
1976 elif not os.path.isdir(os.path.join(opts.dir, '.git')):
1977 raise BadInvocation('Not a git directory: %s' % opts.dir)
1978
1979 # Identify the project if it wasn't specified; this _requires_ the repo
1980 # tool to be installed and for the project to be part of a repo checkout.
1981 if not opts.project:
1982 opts.project = _identify_project(opts.dir)
1983 if not opts.project:
1984 raise BadInvocation("Repo couldn't identify the project of %s" % opts.dir)
1985
Doug Anderson14749562013-06-26 13:38:29 -07001986 found_error = _run_project_hooks(opts.project, proj_dir=opts.dir,
Mike Frysinger66142932014-12-18 14:55:57 -05001987 commit_list=opts.commits,
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001988 presubmit=opts.pre_submit)
Doug Anderson44a644f2011-11-02 10:37:37 -07001989 if found_error:
1990 return 1
1991 return 0
1992
1993
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -07001994if __name__ == '__main__':
Mike Frysinger55f85b52014-12-18 14:45:21 -05001995 sys.exit(direct_main(sys.argv[1:]))