blob: cd75d798f89380a3ed66b03499549196836f9a39 [file] [log] [blame]
Daniel Erat9d203ff2015-02-17 10:12:21 -07001#!/usr/bin/python2
Jon Salz98255932012-08-18 14:48:02 +08002# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07003# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
Mike Frysingerae409522014-02-01 03:16:11 -05006"""Presubmit checks to run when doing `repo upload`.
7
8You can add new checks by adding a functions to the HOOKS constants.
9"""
10
Mike Frysinger09d6a3d2013-10-08 22:21:03 -040011from __future__ import print_function
12
Ryan Cui9b651632011-05-11 11:38:58 -070013import ConfigParser
Daniel Erate3ea3fc2015-02-13 15:27:52 -070014import fnmatch
Jon Salz3ee59de2012-08-18 13:54:22 +080015import functools
Dale Curtis2975c432011-05-03 17:25:20 -070016import json
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070017import os
Ryan Cuiec4d6332011-05-02 14:15:25 -070018import re
Mandeep Singh Bainesa7ffa4b2011-05-03 11:37:02 -070019import sys
Peter Ammon811f6702014-06-12 15:45:38 -070020import stat
Mike Frysingerd3bd32c2014-11-24 23:34:29 -050021import subprocess
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070022
Ryan Cui1562fb82011-05-09 11:01:31 -070023from errors import (VerifyException, HookFailure, PrintErrorForProject,
24 PrintErrorsForCommit)
Ryan Cuiec4d6332011-05-02 14:15:25 -070025
David Jamesc3b68b32013-04-03 09:17:03 -070026# If repo imports us, the __name__ will be __builtin__, and the wrapper will
27# be in $CHROMEOS_CHECKOUT/.repo/repo/main.py, so we need to go two directories
28# up. The same logic also happens to work if we're executed directly.
29if __name__ in ('__builtin__', '__main__'):
30 sys.path.insert(0, os.path.join(os.path.dirname(sys.argv[0]), '..', '..'))
31
Mike Frysinger66142932014-12-18 14:55:57 -050032from chromite.lib import commandline
Mike Frysingerd3bd32c2014-11-24 23:34:29 -050033from chromite.lib import git
Daniel Erata350fd32014-09-29 14:02:34 -070034from chromite.lib import osutils
David Jamesc3b68b32013-04-03 09:17:03 -070035from chromite.lib import patch
Mike Frysinger2ec70ed2014-08-17 19:28:34 -040036from chromite.licensing import licenses_lib
David Jamesc3b68b32013-04-03 09:17:03 -070037
Vadim Bendebury2b62d742014-06-22 13:14:51 -070038PRE_SUBMIT = 'pre-submit'
Ryan Cuiec4d6332011-05-02 14:15:25 -070039
40COMMON_INCLUDED_PATHS = [
Mike Frysingerae409522014-02-01 03:16:11 -050041 # C++ and friends
42 r".*\.c$", r".*\.cc$", r".*\.cpp$", r".*\.h$", r".*\.m$", r".*\.mm$",
43 r".*\.inl$", r".*\.asm$", r".*\.hxx$", r".*\.hpp$", r".*\.s$", r".*\.S$",
44 # Scripts
45 r".*\.js$", r".*\.py$", r".*\.sh$", r".*\.rb$", r".*\.pl$", r".*\.pm$",
46 # No extension at all, note that ALL CAPS files are black listed in
47 # COMMON_EXCLUDED_LIST below.
48 r"(^|.*[\\\/])[^.]+$",
49 # Other
50 r".*\.java$", r".*\.mk$", r".*\.am$",
Ryan Cuiec4d6332011-05-02 14:15:25 -070051]
52
Ryan Cui1562fb82011-05-09 11:01:31 -070053
Ryan Cuiec4d6332011-05-02 14:15:25 -070054COMMON_EXCLUDED_PATHS = [
Daniel Erate3ea3fc2015-02-13 15:27:52 -070055 # Avoid doing source file checks for kernel.
Mike Frysingerae409522014-02-01 03:16:11 -050056 r"/src/third_party/kernel/",
57 r"/src/third_party/kernel-next/",
58 r"/src/third_party/ktop/",
59 r"/src/third_party/punybench/",
60 r".*\bexperimental[\\\/].*",
61 r".*\b[A-Z0-9_]{2,}$",
62 r".*[\\\/]debian[\\\/]rules$",
Daniel Erate3ea3fc2015-02-13 15:27:52 -070063
64 # For ebuild trees, ignore any caches and manifest data.
Mike Frysingerae409522014-02-01 03:16:11 -050065 r".*/Manifest$",
66 r".*/metadata/[^/]*cache[^/]*/[^/]+/[^/]+$",
Doug Anderson5bfb6792011-10-25 16:45:41 -070067
Daniel Erate3ea3fc2015-02-13 15:27:52 -070068 # Ignore profiles data (like overlay-tegra2/profiles).
Mike Frysinger94a670c2014-09-19 12:46:26 -040069 r"(^|.*/)overlay-.*/profiles/.*",
Mike Frysinger98638102014-08-28 00:15:08 -040070 r"^profiles/.*$",
71
Daniel Erate3ea3fc2015-02-13 15:27:52 -070072 # Ignore minified js and jquery.
Mike Frysingerae409522014-02-01 03:16:11 -050073 r".*\.min\.js",
74 r".*jquery.*\.js",
Mike Frysinger33a458d2014-03-03 17:00:51 -050075
76 # Ignore license files as the content is often taken verbatim.
Daniel Erate3ea3fc2015-02-13 15:27:52 -070077 r".*/licenses/.*",
Ryan Cuiec4d6332011-05-02 14:15:25 -070078]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070079
Ryan Cui1562fb82011-05-09 11:01:31 -070080
Ryan Cui9b651632011-05-11 11:38:58 -070081_CONFIG_FILE = 'PRESUBMIT.cfg'
82
83
Daniel Erate3ea3fc2015-02-13 15:27:52 -070084# File containing wildcards, one per line, matching files that should be
85# excluded from presubmit checks. Lines beginning with '#' are ignored.
86_IGNORE_FILE = '.presubmitignore'
87
88
Doug Anderson44a644f2011-11-02 10:37:37 -070089# Exceptions
90
91
92class BadInvocation(Exception):
93 """An Exception indicating a bad invocation of the program."""
94 pass
95
96
Ryan Cui1562fb82011-05-09 11:01:31 -070097# General Helpers
98
Sean Paulba01d402011-05-05 11:36:23 -040099
Doug Anderson44a644f2011-11-02 10:37:37 -0700100def _run_command(cmd, cwd=None, stderr=None):
101 """Executes the passed in command and returns raw stdout output.
102
103 Args:
104 cmd: The command to run; should be a list of strings.
105 cwd: The directory to switch to for running the command.
106 stderr: Can be one of None (print stderr to console), subprocess.STDOUT
107 (combine stderr with stdout), or subprocess.PIPE (ignore stderr).
108
109 Returns:
110 The standard out from the process.
111 """
112 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=stderr, cwd=cwd)
113 return p.communicate()[0]
Ryan Cui72834d12011-05-05 14:51:33 -0700114
Ryan Cui1562fb82011-05-09 11:01:31 -0700115
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700116def _get_hooks_dir():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700117 """Returns the absolute path to the repohooks directory."""
Doug Anderson44a644f2011-11-02 10:37:37 -0700118 if __name__ == '__main__':
119 # Works when file is run on its own (__file__ is defined)...
120 return os.path.abspath(os.path.dirname(__file__))
121 else:
122 # We need to do this when we're run through repo. Since repo executes
123 # us with execfile(), we don't get __file__ defined.
124 cmd = ['repo', 'forall', 'chromiumos/repohooks', '-c', 'pwd']
125 return _run_command(cmd).strip()
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700126
Ryan Cui1562fb82011-05-09 11:01:31 -0700127
Ryan Cuiec4d6332011-05-02 14:15:25 -0700128def _match_regex_list(subject, expressions):
129 """Try to match a list of regular expressions to a string.
130
131 Args:
132 subject: The string to match regexes on
133 expressions: A list of regular expressions to check for matches with.
134
135 Returns:
136 Whether the passed in subject matches any of the passed in regexes.
137 """
138 for expr in expressions:
Mike Frysingerae409522014-02-01 03:16:11 -0500139 if re.search(expr, subject):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700140 return True
141 return False
142
Ryan Cui1562fb82011-05-09 11:01:31 -0700143
Mike Frysingerae409522014-02-01 03:16:11 -0500144def _filter_files(files, include_list, exclude_list=()):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700145 """Filter out files based on the conditions passed in.
146
147 Args:
148 files: list of filepaths to filter
149 include_list: list of regex that when matched with a file path will cause it
150 to be added to the output list unless the file is also matched with a
151 regex in the exclude_list.
152 exclude_list: list of regex that when matched with a file will prevent it
153 from being added to the output list, even if it is also matched with a
154 regex in the include_list.
155
156 Returns:
157 A list of filepaths that contain files matched in the include_list and not
158 in the exclude_list.
159 """
160 filtered = []
161 for f in files:
162 if (_match_regex_list(f, include_list) and
163 not _match_regex_list(f, exclude_list)):
164 filtered.append(f)
165 return filtered
166
Ryan Cuiec4d6332011-05-02 14:15:25 -0700167
168# Git Helpers
Ryan Cui1562fb82011-05-09 11:01:31 -0700169
170
Ryan Cui4725d952011-05-05 15:41:19 -0700171def _get_upstream_branch():
172 """Returns the upstream tracking branch of the current branch.
173
174 Raises:
175 Error if there is no tracking branch
176 """
177 current_branch = _run_command(['git', 'symbolic-ref', 'HEAD']).strip()
178 current_branch = current_branch.replace('refs/heads/', '')
179 if not current_branch:
Ryan Cui1562fb82011-05-09 11:01:31 -0700180 raise VerifyException('Need to be on a tracking branch')
Ryan Cui4725d952011-05-05 15:41:19 -0700181
182 cfg_option = 'branch.' + current_branch + '.%s'
183 full_upstream = _run_command(['git', 'config', cfg_option % 'merge']).strip()
184 remote = _run_command(['git', 'config', cfg_option % 'remote']).strip()
185 if not remote or not full_upstream:
Ryan Cui1562fb82011-05-09 11:01:31 -0700186 raise VerifyException('Need to be on a tracking branch')
Ryan Cui4725d952011-05-05 15:41:19 -0700187
188 return full_upstream.replace('heads', 'remotes/' + remote)
189
Ryan Cui1562fb82011-05-09 11:01:31 -0700190
Che-Liang Chiou5ce2d7b2013-03-22 18:47:55 -0700191def _get_patch(commit):
192 """Returns the patch for this commit."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700193 if commit == PRE_SUBMIT:
194 return _run_command(['git', 'diff', '--cached', 'HEAD'])
195 else:
196 return _run_command(['git', 'format-patch', '--stdout', '-1', commit])
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700197
Ryan Cui1562fb82011-05-09 11:01:31 -0700198
Jon Salz98255932012-08-18 14:48:02 +0800199def _try_utf8_decode(data):
200 """Attempts to decode a string as UTF-8.
201
202 Returns:
203 The decoded Unicode object, or the original string if parsing fails.
204 """
205 try:
206 return unicode(data, 'utf-8', 'strict')
207 except UnicodeDecodeError:
208 return data
209
210
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500211def _get_file_content(path, commit):
212 """Returns the content of a file at a specific commit.
213
214 We can't rely on the file as it exists in the filesystem as people might be
215 uploading a series of changes which modifies the file multiple times.
216
217 Note: The "content" of a symlink is just the target. So if you're expecting
218 a full file, you should check that first. One way to detect is that the
219 content will not have any newlines.
220 """
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700221 if commit == PRE_SUBMIT:
222 return _run_command(['git', 'diff', 'HEAD', path])
223 else:
224 return _run_command(['git', 'show', '%s:%s' % (commit, path)])
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500225
226
Mike Frysingerae409522014-02-01 03:16:11 -0500227def _get_file_diff(path, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700228 """Returns a list of (linenum, lines) tuples that the commit touched."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700229 command = ['git', 'diff', '-p', '--pretty=format:', '--no-ext-diff']
230 if commit == PRE_SUBMIT:
231 command += ['HEAD', path]
232 else:
233 command += [commit, path]
234 output = _run_command(command)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700235
236 new_lines = []
237 line_num = 0
238 for line in output.splitlines():
239 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
240 if m:
241 line_num = int(m.groups(1)[0])
242 continue
243 if line.startswith('+') and not line.startswith('++'):
Jon Salz98255932012-08-18 14:48:02 +0800244 new_lines.append((line_num, _try_utf8_decode(line[1:])))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700245 if not line.startswith('-'):
246 line_num += 1
247 return new_lines
248
Ryan Cui1562fb82011-05-09 11:01:31 -0700249
Daniel Erate3ea3fc2015-02-13 15:27:52 -0700250def _get_ignore_wildcards(directory, cache):
251 """Get wildcards listed in a directory's _IGNORE_FILE.
252
253 Args:
254 directory: A string containing a directory path.
255 cache: A dictionary (opaque to caller) caching previously-read wildcards.
256
257 Returns:
258 A list of wildcards from _IGNORE_FILE or an empty list if _IGNORE_FILE
259 wasn't present.
260 """
261 # In the cache, keys are directories and values are lists of wildcards from
262 # _IGNORE_FILE within those directories (and empty if no file was present).
263 if directory not in cache:
264 wildcards = []
265 dotfile_path = os.path.join(directory, _IGNORE_FILE)
266 if os.path.exists(dotfile_path):
267 # TODO(derat): Consider using _get_file_content() to get the file as of
268 # this commit instead of the on-disk version. This may have a noticeable
269 # performance impact, as each call to _get_file_content() runs git.
270 with open(dotfile_path, 'r') as dotfile:
271 for line in dotfile.readlines():
272 line = line.strip()
273 if line.startswith('#'):
274 continue
275 if line.endswith('/'):
276 line += '*'
277 wildcards.append(line)
278 cache[directory] = wildcards
279
280 return cache[directory]
281
282
283def _path_is_ignored(path, cache):
284 """Check whether a path is ignored by _IGNORE_FILE.
285
286 Args:
287 path: A string containing a path.
288 cache: A dictionary (opaque to caller) caching previously-read wildcards.
289
290 Returns:
291 True if a file named _IGNORE_FILE in one of the passed-in path's parent
292 directories contains a wildcard matching the path.
293 """
294 # Skip ignore files.
295 if os.path.basename(path) == _IGNORE_FILE:
296 return True
297
298 path = os.path.abspath(path)
299 base = os.getcwd()
300
301 prefix = os.path.dirname(path)
302 while prefix.startswith(base):
303 rel_path = path[len(prefix) + 1:]
304 for wildcard in _get_ignore_wildcards(prefix, cache):
305 if fnmatch.fnmatch(rel_path, wildcard):
306 return True
307 prefix = os.path.dirname(prefix)
308
309 return False
310
311
Mike Frysinger292b45d2014-11-25 01:17:10 -0500312def _get_affected_files(commit, include_deletes=False, relative=False,
313 include_symlinks=False, include_adds=True,
Daniel Erate3ea3fc2015-02-13 15:27:52 -0700314 full_details=False, use_ignore_files=True):
Peter Ammon811f6702014-06-12 15:45:38 -0700315 """Returns list of file paths that were modified/added, excluding symlinks.
316
317 Args:
318 commit: The commit
319 include_deletes: If true, we'll include deleted files in the result
320 relative: Whether to return relative or full paths to files
Mike Frysinger292b45d2014-11-25 01:17:10 -0500321 include_symlinks: If true, we'll include symlinks in the result
322 include_adds: If true, we'll include new files in the result
323 full_details: If False, return filenames, else return structured results.
Daniel Erate3ea3fc2015-02-13 15:27:52 -0700324 use_ignore_files: Whether we ignore files matched by _IGNORE_FILE files.
Peter Ammon811f6702014-06-12 15:45:38 -0700325
326 Returns:
327 A list of modified/added (and perhaps deleted) files
328 """
Mike Frysinger292b45d2014-11-25 01:17:10 -0500329 if not relative and full_details:
330 raise ValueError('full_details only supports relative paths currently')
331
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700332 if commit == PRE_SUBMIT:
333 return _run_command(['git', 'diff-index', '--cached',
334 '--name-only', 'HEAD']).split()
Mike Frysingerd3bd32c2014-11-24 23:34:29 -0500335
336 path = os.getcwd()
337 files = git.RawDiff(path, '%s^!' % commit)
338
339 # Filter out symlinks.
Mike Frysinger292b45d2014-11-25 01:17:10 -0500340 if not include_symlinks:
341 files = [x for x in files if not stat.S_ISLNK(int(x.dst_mode, 8))]
Mike Frysingerd3bd32c2014-11-24 23:34:29 -0500342
343 if not include_deletes:
344 files = [x for x in files if x.status != 'D']
345
Mike Frysinger292b45d2014-11-25 01:17:10 -0500346 if not include_adds:
347 files = [x for x in files if x.status != 'A']
348
Daniel Erate3ea3fc2015-02-13 15:27:52 -0700349 if use_ignore_files:
350 cache = {}
351 is_ignored = lambda x: _path_is_ignored(x.dst_file or x.src_file, cache)
352 files = [x for x in files if not is_ignored(x)]
353
Mike Frysinger292b45d2014-11-25 01:17:10 -0500354 if full_details:
355 # Caller wants the raw objects to parse status/etc... themselves.
Mike Frysingerd3bd32c2014-11-24 23:34:29 -0500356 return files
357 else:
Mike Frysinger292b45d2014-11-25 01:17:10 -0500358 # Caller only cares about filenames.
359 files = [x.dst_file if x.dst_file else x.src_file for x in files]
360 if relative:
361 return files
362 else:
363 return [os.path.join(path, x) for x in files]
Peter Ammon811f6702014-06-12 15:45:38 -0700364
365
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700366def _get_commits():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700367 """Returns a list of commits for this review."""
Ryan Cui4725d952011-05-05 15:41:19 -0700368 cmd = ['git', 'log', '%s..' % _get_upstream_branch(), '--format=%H']
Ryan Cui72834d12011-05-05 14:51:33 -0700369 return _run_command(cmd).split()
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700370
Ryan Cui1562fb82011-05-09 11:01:31 -0700371
Ryan Cuiec4d6332011-05-02 14:15:25 -0700372def _get_commit_desc(commit):
373 """Returns the full commit message of a commit."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700374 if commit == PRE_SUBMIT:
375 return ''
Sean Paul23a2c582011-05-06 13:10:44 -0400376 return _run_command(['git', 'log', '--format=%s%n%n%b', commit + '^!'])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700377
378
379# Common Hooks
380
Ryan Cui1562fb82011-05-09 11:01:31 -0700381
Mike Frysingerae409522014-02-01 03:16:11 -0500382def _check_no_long_lines(_project, commit):
Mike Frysinger55f85b52014-12-18 14:45:21 -0500383 """Checks there are no lines longer than MAX_LEN in any of the text files."""
384
Ryan Cuiec4d6332011-05-02 14:15:25 -0700385 MAX_LEN = 80
Jon Salz98255932012-08-18 14:48:02 +0800386 SKIP_REGEXP = re.compile('|'.join([
387 r'https?://',
388 r'^#\s*(define|include|import|pragma|if|endif)\b']))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700389
390 errors = []
391 files = _filter_files(_get_affected_files(commit),
392 COMMON_INCLUDED_PATHS,
393 COMMON_EXCLUDED_PATHS)
394
395 for afile in files:
396 for line_num, line in _get_file_diff(afile, commit):
397 # Allow certain lines to exceed the maxlen rule.
Mike Frysingerae409522014-02-01 03:16:11 -0500398 if len(line) <= MAX_LEN or SKIP_REGEXP.search(line):
Jon Salz98255932012-08-18 14:48:02 +0800399 continue
400
401 errors.append('%s, line %s, %s chars' % (afile, line_num, len(line)))
402 if len(errors) == 5: # Just show the first 5 errors.
403 break
Ryan Cuiec4d6332011-05-02 14:15:25 -0700404
405 if errors:
406 msg = 'Found lines longer than %s characters (first 5 shown):' % MAX_LEN
Ryan Cui1562fb82011-05-09 11:01:31 -0700407 return HookFailure(msg, errors)
408
Ryan Cuiec4d6332011-05-02 14:15:25 -0700409
Mike Frysingerae409522014-02-01 03:16:11 -0500410def _check_no_stray_whitespace(_project, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700411 """Checks that there is no stray whitespace at source lines end."""
412 errors = []
413 files = _filter_files(_get_affected_files(commit),
Mike Frysingerae409522014-02-01 03:16:11 -0500414 COMMON_INCLUDED_PATHS,
415 COMMON_EXCLUDED_PATHS)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700416 for afile in files:
417 for line_num, line in _get_file_diff(afile, commit):
418 if line.rstrip() != line:
419 errors.append('%s, line %s' % (afile, line_num))
420 if errors:
Ryan Cui1562fb82011-05-09 11:01:31 -0700421 return HookFailure('Found line ending with white space in:', errors)
422
Ryan Cuiec4d6332011-05-02 14:15:25 -0700423
Mike Frysingerae409522014-02-01 03:16:11 -0500424def _check_no_tabs(_project, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700425 """Checks there are no unexpanded tabs."""
426 TAB_OK_PATHS = [
Ryan Cui31e0c172011-05-04 21:00:45 -0700427 r"/src/third_party/u-boot/",
Ryan Cuiec4d6332011-05-02 14:15:25 -0700428 r".*\.ebuild$",
429 r".*\.eclass$",
Elly Jones5ab34192011-11-15 14:57:06 -0500430 r".*/[M|m]akefile$",
431 r".*\.mk$"
Ryan Cuiec4d6332011-05-02 14:15:25 -0700432 ]
433
434 errors = []
435 files = _filter_files(_get_affected_files(commit),
436 COMMON_INCLUDED_PATHS,
437 COMMON_EXCLUDED_PATHS + TAB_OK_PATHS)
438
439 for afile in files:
440 for line_num, line in _get_file_diff(afile, commit):
441 if '\t' in line:
Mike Frysingerae409522014-02-01 03:16:11 -0500442 errors.append('%s, line %s' % (afile, line_num))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700443 if errors:
Ryan Cui1562fb82011-05-09 11:01:31 -0700444 return HookFailure('Found a tab character in:', errors)
445
Ryan Cuiec4d6332011-05-02 14:15:25 -0700446
Mike Frysingerae409522014-02-01 03:16:11 -0500447def _check_change_has_test_field(_project, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700448 """Check for a non-empty 'TEST=' field in the commit message."""
David McMahon8f6553e2011-06-10 15:46:36 -0700449 TEST_RE = r'\nTEST=\S+'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700450
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700451 if not re.search(TEST_RE, _get_commit_desc(commit)):
Ryan Cui1562fb82011-05-09 11:01:31 -0700452 msg = 'Changelist description needs TEST field (after first line)'
453 return HookFailure(msg)
454
Ryan Cuiec4d6332011-05-02 14:15:25 -0700455
Mike Frysingerae409522014-02-01 03:16:11 -0500456def _check_change_has_valid_cq_depend(_project, commit):
David Jamesc3b68b32013-04-03 09:17:03 -0700457 """Check for a correctly formatted CQ-DEPEND field in the commit message."""
458 msg = 'Changelist has invalid CQ-DEPEND target.'
459 example = 'Example: CQ-DEPEND=CL:1234, CL:2345'
460 try:
461 patch.GetPaladinDeps(_get_commit_desc(commit))
462 except ValueError as ex:
463 return HookFailure(msg, [example, str(ex)])
464
465
Mike Frysingerae409522014-02-01 03:16:11 -0500466def _check_change_has_bug_field(_project, commit):
David McMahon8f6553e2011-06-10 15:46:36 -0700467 """Check for a correctly formatted 'BUG=' field in the commit message."""
David James5c0073d2013-04-03 08:48:52 -0700468 OLD_BUG_RE = r'\nBUG=.*chromium-os'
469 if re.search(OLD_BUG_RE, _get_commit_desc(commit)):
470 msg = ('The chromium-os bug tracker is now deprecated. Please use\n'
471 'the chromium tracker in your BUG= line now.')
472 return HookFailure(msg)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700473
Stefan Sauerd74ad562015-03-10 10:14:28 +0100474 BUG_RE = r'\nBUG=([Nn]one|(chrome-os-partner|chromium|brillo|b):\d+)'
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700475 if not re.search(BUG_RE, _get_commit_desc(commit)):
David McMahon8f6553e2011-06-10 15:46:36 -0700476 msg = ('Changelist description needs BUG field (after first line):\n'
Christopher Wileyc92721b2015-01-26 13:07:39 -0800477 'BUG=brillo:9999 (for Brillo tracker)\n'
David James5c0073d2013-04-03 08:48:52 -0700478 'BUG=chromium:9999 (for public tracker)\n'
David McMahon8f6553e2011-06-10 15:46:36 -0700479 'BUG=chrome-os-partner:9999 (for partner tracker)\n'
Stefan Sauerd74ad562015-03-10 10:14:28 +0100480 'BUG=b:9999 (for buganizer)\n'
David McMahon8f6553e2011-06-10 15:46:36 -0700481 'BUG=None')
Ryan Cui1562fb82011-05-09 11:01:31 -0700482 return HookFailure(msg)
483
Ryan Cuiec4d6332011-05-02 14:15:25 -0700484
Mike Frysinger292b45d2014-11-25 01:17:10 -0500485def _check_for_uprev(project, commit, project_top=None):
Doug Anderson42b8a052013-06-26 10:45:36 -0700486 """Check that we're not missing a revbump of an ebuild in the given commit.
487
488 If the given commit touches files in a directory that has ebuilds somewhere
489 up the directory hierarchy, it's very likely that we need an ebuild revbump
490 in order for those changes to take effect.
491
492 It's not totally trivial to detect a revbump, so at least detect that an
493 ebuild with a revision number in it was touched. This should handle the
494 common case where we use a symlink to do the revbump.
495
496 TODO: it would be nice to enhance this hook to:
497 * Handle cases where people revbump with a slightly different syntax. I see
498 one ebuild (puppy) that revbumps with _pN. This is a false positive.
499 * Catches cases where people aren't using symlinks for revbumps. If they
500 edit a revisioned file directly (and are expected to rename it for revbump)
501 we'll miss that. Perhaps we could detect that the file touched is a
502 symlink?
503
504 If a project doesn't use symlinks we'll potentially miss a revbump, but we're
505 still better off than without this check.
506
507 Args:
508 project: The project to look at
509 commit: The commit to look at
Mike Frysinger292b45d2014-11-25 01:17:10 -0500510 project_top: Top dir to process commits in
Doug Anderson42b8a052013-06-26 10:45:36 -0700511
512 Returns:
513 A HookFailure or None.
514 """
Mike Frysinger011af942014-01-17 16:12:22 -0500515 # If this is the portage-stable overlay, then ignore the check. It's rare
516 # that we're doing anything other than importing files from upstream, so
517 # forcing a rev bump makes no sense.
518 whitelist = (
519 'chromiumos/overlays/portage-stable',
520 )
521 if project in whitelist:
522 return None
523
Mike Frysinger292b45d2014-11-25 01:17:10 -0500524 def FinalName(obj):
525 # If the file is being deleted, then the dst_file is not set.
526 if obj.dst_file is None:
527 return obj.src_file
528 else:
529 return obj.dst_file
530
531 affected_path_objs = _get_affected_files(
532 commit, include_deletes=True, include_symlinks=True, relative=True,
533 full_details=True)
Doug Anderson42b8a052013-06-26 10:45:36 -0700534
535 # Don't yell about changes to whitelisted files...
Mike Frysinger011af942014-01-17 16:12:22 -0500536 whitelist = ('ChangeLog', 'Manifest', 'metadata.xml')
Mike Frysinger292b45d2014-11-25 01:17:10 -0500537 affected_path_objs = [x for x in affected_path_objs
538 if os.path.basename(FinalName(x)) not in whitelist]
539 if not affected_path_objs:
Doug Anderson42b8a052013-06-26 10:45:36 -0700540 return None
541
542 # If we've touched any file named with a -rN.ebuild then we'll say we're
543 # OK right away. See TODO above about enhancing this.
Mike Frysinger292b45d2014-11-25 01:17:10 -0500544 touched_revved_ebuild = any(re.search(r'-r\d*\.ebuild$', FinalName(x))
545 for x in affected_path_objs)
Doug Anderson42b8a052013-06-26 10:45:36 -0700546 if touched_revved_ebuild:
547 return None
548
Mike Frysinger292b45d2014-11-25 01:17:10 -0500549 # If we're creating new ebuilds from scratch, then we don't need an uprev.
550 # Find all the dirs that new ebuilds and ignore their files/.
551 ebuild_dirs = [os.path.dirname(FinalName(x)) + '/' for x in affected_path_objs
552 if FinalName(x).endswith('.ebuild') and x.status == 'A']
553 affected_path_objs = [obj for obj in affected_path_objs
554 if not any(FinalName(obj).startswith(x)
555 for x in ebuild_dirs)]
556 if not affected_path_objs:
557 return
558
Doug Anderson42b8a052013-06-26 10:45:36 -0700559 # We want to examine the current contents of all directories that are parents
560 # of files that were touched (up to the top of the project).
561 #
562 # ...note: we use the current directory contents even though it may have
563 # changed since the commit we're looking at. This is just a heuristic after
564 # all. Worst case we don't flag a missing revbump.
Mike Frysinger292b45d2014-11-25 01:17:10 -0500565 if project_top is None:
566 project_top = os.getcwd()
Doug Anderson42b8a052013-06-26 10:45:36 -0700567 dirs_to_check = set([project_top])
Mike Frysinger292b45d2014-11-25 01:17:10 -0500568 for obj in affected_path_objs:
569 path = os.path.join(project_top, os.path.dirname(FinalName(obj)))
Doug Anderson42b8a052013-06-26 10:45:36 -0700570 while os.path.exists(path) and not os.path.samefile(path, project_top):
571 dirs_to_check.add(path)
572 path = os.path.dirname(path)
573
574 # Look through each directory. If it's got an ebuild in it then we'll
575 # consider this as a case when we need a revbump.
Gwendal Grignoua3086c32014-12-09 11:17:22 -0800576 affected_paths = set(os.path.join(project_top, FinalName(x))
577 for x in affected_path_objs)
Doug Anderson42b8a052013-06-26 10:45:36 -0700578 for dir_path in dirs_to_check:
579 contents = os.listdir(dir_path)
580 ebuilds = [os.path.join(dir_path, path)
581 for path in contents if path.endswith('.ebuild')]
582 ebuilds_9999 = [path for path in ebuilds if path.endswith('-9999.ebuild')]
583
584 # If the -9999.ebuild file was touched the bot will uprev for us.
585 # ...we'll use a simple intersection here as a heuristic...
Mike Frysinger292b45d2014-11-25 01:17:10 -0500586 if set(ebuilds_9999) & affected_paths:
Doug Anderson42b8a052013-06-26 10:45:36 -0700587 continue
588
589 if ebuilds:
Mike Frysinger292b45d2014-11-25 01:17:10 -0500590 return HookFailure('Changelist probably needs a revbump of an ebuild, '
591 'or a -r1.ebuild symlink if this is a new ebuild:\n'
592 '%s' % dir_path)
Doug Anderson42b8a052013-06-26 10:45:36 -0700593
594 return None
595
596
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500597def _check_ebuild_eapi(project, commit):
598 """Make sure we have people use EAPI=4 or newer with custom ebuilds.
599
600 We want to get away from older EAPI's as it makes life confusing and they
601 have less builtin error checking.
602
603 Args:
604 project: The project to look at
605 commit: The commit to look at
606
607 Returns:
608 A HookFailure or None.
609 """
610 # If this is the portage-stable overlay, then ignore the check. It's rare
Mike Frysingercd6adfc2014-02-06 01:03:56 -0500611 # that we're doing anything other than importing files from upstream, and
612 # we shouldn't be rewriting things fundamentally anyways.
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500613 whitelist = (
614 'chromiumos/overlays/portage-stable',
615 )
616 if project in whitelist:
617 return None
618
619 BAD_EAPIS = ('0', '1', '2', '3')
620
621 get_eapi = re.compile(r'^\s*EAPI=[\'"]?([^\'"]+)')
622
623 ebuilds_re = [r'\.ebuild$']
624 ebuilds = _filter_files(_get_affected_files(commit, relative=True),
625 ebuilds_re)
626 bad_ebuilds = []
627
628 for ebuild in ebuilds:
629 # If the ebuild does not specify an EAPI, it defaults to 0.
630 eapi = '0'
631
632 lines = _get_file_content(ebuild, commit).splitlines()
633 if len(lines) == 1:
634 # This is most likely a symlink, so skip it entirely.
635 continue
636
637 for line in lines:
638 m = get_eapi.match(line)
639 if m:
640 # Once we hit the first EAPI line in this ebuild, stop processing.
641 # The spec requires that there only be one and it be first, so
642 # checking all possible values is pointless. We also assume that
643 # it's "the" EAPI line and not something in the middle of a heredoc.
644 eapi = m.group(1)
645 break
646
647 if eapi in BAD_EAPIS:
648 bad_ebuilds.append((ebuild, eapi))
649
650 if bad_ebuilds:
651 # pylint: disable=C0301
652 url = 'http://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/upgrade-ebuild-eapis'
653 # pylint: enable=C0301
654 return HookFailure(
Mike Frysingercd6adfc2014-02-06 01:03:56 -0500655 'These ebuilds are using old EAPIs. If these are imported from\n'
656 'Gentoo, then you may ignore and upload once with the --no-verify\n'
657 'flag. Otherwise, please update to 4 or newer.\n'
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500658 '\t%s\n'
659 'See this guide for more details:\n%s\n' %
660 ('\n\t'.join(['%s: EAPI=%s' % x for x in bad_ebuilds]), url))
661
662
Mike Frysinger89bdb852014-02-01 05:26:26 -0500663def _check_ebuild_keywords(_project, commit):
Mike Frysingerc51ece72014-01-17 16:23:40 -0500664 """Make sure we use the new style KEYWORDS when possible in ebuilds.
665
666 If an ebuild generally does not care about the arch it is running on, then
667 ebuilds should flag it with one of:
668 KEYWORDS="*" # A stable ebuild.
669 KEYWORDS="~*" # An unstable ebuild.
670 KEYWORDS="-* ..." # Is known to only work on specific arches.
671
672 Args:
673 project: The project to look at
674 commit: The commit to look at
675
676 Returns:
677 A HookFailure or None.
678 """
679 WHITELIST = set(('*', '-*', '~*'))
680
681 get_keywords = re.compile(r'^\s*KEYWORDS="(.*)"')
682
Mike Frysinger89bdb852014-02-01 05:26:26 -0500683 ebuilds_re = [r'\.ebuild$']
684 ebuilds = _filter_files(_get_affected_files(commit, relative=True),
685 ebuilds_re)
686
Mike Frysinger8d42d742014-09-22 15:50:21 -0400687 bad_ebuilds = []
Mike Frysingerc51ece72014-01-17 16:23:40 -0500688 for ebuild in ebuilds:
Mike Frysinger5c9e58d2014-09-09 03:32:50 -0400689 # We get the full content rather than a diff as the latter does not work
690 # on new files (like when adding new ebuilds).
691 lines = _get_file_content(ebuild, commit).splitlines()
692 for line in lines:
Mike Frysingerc51ece72014-01-17 16:23:40 -0500693 m = get_keywords.match(line)
694 if m:
695 keywords = set(m.group(1).split())
696 if not keywords or WHITELIST - keywords != WHITELIST:
697 continue
698
Mike Frysinger8d42d742014-09-22 15:50:21 -0400699 bad_ebuilds.append(ebuild)
700
701 if bad_ebuilds:
702 return HookFailure(
703 '%s\n'
704 'Please update KEYWORDS to use a glob:\n'
705 'If the ebuild should be marked stable (normal for non-9999 ebuilds):\n'
706 ' KEYWORDS="*"\n'
707 'If the ebuild should be marked unstable (normal for '
708 'cros-workon / 9999 ebuilds):\n'
709 ' KEYWORDS="~*"\n'
Mike Frysingerde8efea2015-05-17 03:42:26 -0400710 'If the ebuild needs to be marked for only specific arches, '
Mike Frysinger8d42d742014-09-22 15:50:21 -0400711 'then use -* like so:\n'
712 ' KEYWORDS="-* arm ..."\n' % '\n* '.join(bad_ebuilds))
Mike Frysingerc51ece72014-01-17 16:23:40 -0500713
714
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800715def _check_ebuild_licenses(_project, commit):
716 """Check if the LICENSE field in the ebuild is correct."""
717 affected_paths = _get_affected_files(commit)
718 touched_ebuilds = [x for x in affected_paths if x.endswith('.ebuild')]
719
720 # A list of licenses to ignore for now.
Yu-Ju Hongc0963fa2014-03-03 12:36:52 -0800721 LICENSES_IGNORE = ['||', '(', ')']
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800722
723 for ebuild in touched_ebuilds:
724 # Skip virutal packages.
725 if ebuild.split('/')[-3] == 'virtual':
726 continue
727
728 try:
Mike Frysinger2ec70ed2014-08-17 19:28:34 -0400729 license_types = licenses_lib.GetLicenseTypesFromEbuild(ebuild)
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800730 except ValueError as e:
731 return HookFailure(e.message, [ebuild])
732
733 # Also ignore licenses ending with '?'
734 for license_type in [x for x in license_types
735 if x not in LICENSES_IGNORE and not x.endswith('?')]:
736 try:
Mike Frysinger2ec70ed2014-08-17 19:28:34 -0400737 licenses_lib.Licensing.FindLicenseType(license_type)
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800738 except AssertionError as e:
739 return HookFailure(e.message, [ebuild])
740
741
Mike Frysingercd363c82014-02-01 05:20:18 -0500742def _check_ebuild_virtual_pv(project, commit):
743 """Enforce the virtual PV policies."""
744 # If this is the portage-stable overlay, then ignore the check.
745 # We want to import virtuals as-is from upstream Gentoo.
746 whitelist = (
747 'chromiumos/overlays/portage-stable',
748 )
749 if project in whitelist:
750 return None
751
752 # We assume the repo name is the same as the dir name on disk.
753 # It would be dumb to not have them match though.
754 project = os.path.basename(project)
755
756 is_variant = lambda x: x.startswith('overlay-variant-')
757 is_board = lambda x: x.startswith('overlay-')
758 is_private = lambda x: x.endswith('-private')
759
760 get_pv = re.compile(r'(.*?)virtual/([^/]+)/\2-([^/]*)\.ebuild$')
761
762 ebuilds_re = [r'\.ebuild$']
763 ebuilds = _filter_files(_get_affected_files(commit, relative=True),
764 ebuilds_re)
765 bad_ebuilds = []
766
767 for ebuild in ebuilds:
768 m = get_pv.match(ebuild)
769 if m:
770 overlay = m.group(1)
771 if not overlay or not is_board(overlay):
772 overlay = project
773
774 pv = m.group(3).split('-', 1)[0]
775
776 if is_private(overlay):
777 want_pv = '3.5' if is_variant(overlay) else '3'
778 elif is_board(overlay):
779 want_pv = '2.5' if is_variant(overlay) else '2'
780 else:
781 want_pv = '1'
782
783 if pv != want_pv:
784 bad_ebuilds.append((ebuild, pv, want_pv))
785
786 if bad_ebuilds:
787 # pylint: disable=C0301
788 url = 'http://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/portage-build-faq#TOC-Virtuals-and-central-management'
789 # pylint: enable=C0301
790 return HookFailure(
791 'These virtuals have incorrect package versions (PVs). Please adjust:\n'
792 '\t%s\n'
793 'If this is an upstream Gentoo virtual, then you may ignore this\n'
794 'check (and re-run w/--no-verify). Otherwise, please see this\n'
795 'page for more details:\n%s\n' %
796 ('\n\t'.join(['%s:\n\t\tPV is %s but should be %s' % x
797 for x in bad_ebuilds]), url))
798
799
Daniel Erat9d203ff2015-02-17 10:12:21 -0700800def _check_portage_make_use_var(_project, commit):
801 """Verify that $USE is set correctly in make.conf and make.defaults."""
802 files = _filter_files(_get_affected_files(commit, relative=True),
803 [r'(^|/)make.(conf|defaults)$'])
804
805 errors = []
806 for path in files:
807 basename = os.path.basename(path)
808
809 # Has a USE= line already been encountered in this file?
810 saw_use = False
811
812 for i, line in enumerate(_get_file_content(path, commit).splitlines(), 1):
813 if not line.startswith('USE='):
814 continue
815
816 preserves_use = '${USE}' in line or '$USE' in line
817
818 if (basename == 'make.conf' or
819 (basename == 'make.defaults' and saw_use)) and not preserves_use:
820 errors.append('%s:%d: missing ${USE}' % (path, i))
821 elif basename == 'make.defaults' and not saw_use and preserves_use:
822 errors.append('%s:%d: ${USE} referenced in initial declaration' %
823 (path, i))
824
825 saw_use = True
826
827 if errors:
828 return HookFailure(
829 'One or more Portage make files appear to set USE incorrectly.\n'
830 '\n'
831 'All USE assignments in make.conf and all assignments after the\n'
832 'initial declaration in make.defaults should contain "${USE}" to\n'
833 'preserve previously-set flags.\n'
834 '\n'
835 'The initial USE declaration in make.defaults should not contain\n'
836 '"${USE}".\n',
837 errors)
838
839
Mike Frysingerae409522014-02-01 03:16:11 -0500840def _check_change_has_proper_changeid(_project, commit):
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700841 """Verify that Change-ID is present in last paragraph of commit message."""
Mike Frysinger4a22bf02014-10-31 13:53:35 -0400842 CHANGE_ID_RE = r'\nChange-Id: I[a-f0-9]+\n'
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700843 desc = _get_commit_desc(commit)
Mike Frysinger4a22bf02014-10-31 13:53:35 -0400844 m = re.search(CHANGE_ID_RE, desc)
Mike Frysinger02b88bd2014-11-21 00:29:38 -0500845 if not m:
Ryan Cui1562fb82011-05-09 11:01:31 -0700846 return HookFailure('Change-Id must be in last paragraph of description.')
847
Mike Frysinger02b88bd2014-11-21 00:29:38 -0500848 # Allow s-o-b tags to follow it, but only those.
849 end = desc[m.end():].strip().splitlines()
850 if [x for x in end if not x.startswith('Signed-off-by: ')]:
851 return HookFailure('Only "Signed-off-by:" tags may follow the Change-Id.')
852
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700853
Mike Frysinger36b2ebc2014-10-31 14:02:03 -0400854def _check_commit_message_style(_project, commit):
855 """Verify that the commit message matches our style.
856
857 We do not check for BUG=/TEST=/etc... lines here as that is handled by other
858 commit hooks.
859 """
860 desc = _get_commit_desc(commit)
861
862 # The first line should be by itself.
863 lines = desc.splitlines()
864 if len(lines) > 1 and lines[1]:
865 return HookFailure('The second line of the commit message must be blank.')
866
867 # The first line should be one sentence.
868 if '. ' in lines[0]:
869 return HookFailure('The first line cannot be more than one sentence.')
870
871 # The first line cannot be too long.
872 MAX_FIRST_LINE_LEN = 100
873 if len(lines[0]) > MAX_FIRST_LINE_LEN:
874 return HookFailure('The first line must be less than %i chars.' %
875 MAX_FIRST_LINE_LEN)
876
877
Mike Frysingerae409522014-02-01 03:16:11 -0500878def _check_license(_project, commit):
Mike Frysinger98638102014-08-28 00:15:08 -0400879 """Verifies the license/copyright header.
Ryan Cuiec4d6332011-05-02 14:15:25 -0700880
Mike Frysinger98638102014-08-28 00:15:08 -0400881 Should be following the spec:
882 http://dev.chromium.org/developers/coding-style#TOC-File-headers
883 """
884 # For older years, be a bit more flexible as our policy says leave them be.
885 LICENSE_HEADER = (
886 r'.* Copyright( \(c\))? 20[-0-9]{2,7} The Chromium OS Authors\. '
Mike Frysingerb81102f2014-11-21 00:33:35 -0500887 r'All rights reserved\.' r'\n'
Mike Frysinger98638102014-08-28 00:15:08 -0400888 r'.* Use of this source code is governed by a BSD-style license that can '
Mike Frysingerb81102f2014-11-21 00:33:35 -0500889 r'be\n'
Mike Frysinger98638102014-08-28 00:15:08 -0400890 r'.* found in the LICENSE file\.'
Mike Frysingerb81102f2014-11-21 00:33:35 -0500891 r'\n'
Mike Frysinger98638102014-08-28 00:15:08 -0400892 )
893 license_re = re.compile(LICENSE_HEADER, re.MULTILINE)
894
895 # For newer years, be stricter.
896 COPYRIGHT_LINE = (
897 r'.* Copyright \(c\) 20(1[5-9]|[2-9][0-9]) The Chromium OS Authors\. '
Mike Frysingerb81102f2014-11-21 00:33:35 -0500898 r'All rights reserved\.' r'\n'
Mike Frysinger98638102014-08-28 00:15:08 -0400899 )
900 copyright_re = re.compile(COPYRIGHT_LINE)
901
902 bad_files = []
903 bad_copyright_files = []
904 files = _filter_files(_get_affected_files(commit, relative=True),
905 COMMON_INCLUDED_PATHS,
906 COMMON_EXCLUDED_PATHS)
907
908 for f in files:
909 contents = _get_file_content(f, commit)
910 if not contents:
911 # Ignore empty files.
912 continue
913
914 if not license_re.search(contents):
915 bad_files.append(f)
916 elif copyright_re.search(contents):
917 bad_copyright_files.append(f)
918
919 if bad_files:
920 msg = '%s:\n%s\n%s' % (
921 'License must match', license_re.pattern,
922 'Found a bad header in these files:')
923 return HookFailure(msg, bad_files)
924
925 if bad_copyright_files:
926 msg = 'Do not use (c) in copyright headers in new files:'
927 return HookFailure(msg, bad_copyright_files)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700928
929
Mike Frysinger998c2cc2014-08-27 05:20:23 -0400930def _check_layout_conf(_project, commit):
931 """Verifies the metadata/layout.conf file."""
932 repo_name = 'profiles/repo_name'
Mike Frysinger94a670c2014-09-19 12:46:26 -0400933 repo_names = []
Mike Frysinger998c2cc2014-08-27 05:20:23 -0400934 layout_path = 'metadata/layout.conf'
Mike Frysinger94a670c2014-09-19 12:46:26 -0400935 layout_paths = []
Mike Frysinger998c2cc2014-08-27 05:20:23 -0400936
Mike Frysinger94a670c2014-09-19 12:46:26 -0400937 # Handle multiple overlays in a single commit (like the public tree).
938 for f in _get_affected_files(commit, relative=True):
939 if f.endswith(repo_name):
940 repo_names.append(f)
941 elif f.endswith(layout_path):
942 layout_paths.append(f)
Mike Frysinger998c2cc2014-08-27 05:20:23 -0400943
944 # Disallow new repos with the repo_name file.
Mike Frysinger94a670c2014-09-19 12:46:26 -0400945 if repo_names:
Mike Frysinger998c2cc2014-08-27 05:20:23 -0400946 return HookFailure('%s: use "repo-name" in %s instead' %
Mike Frysinger94a670c2014-09-19 12:46:26 -0400947 (repo_names, layout_path))
Mike Frysinger998c2cc2014-08-27 05:20:23 -0400948
Mike Frysinger94a670c2014-09-19 12:46:26 -0400949 # Gather all the errors in one pass so we show one full message.
950 all_errors = {}
951 for layout_path in layout_paths:
952 all_errors[layout_path] = errors = []
Mike Frysinger998c2cc2014-08-27 05:20:23 -0400953
Mike Frysinger94a670c2014-09-19 12:46:26 -0400954 # Make sure the config file is sorted.
955 data = [x for x in _get_file_content(layout_path, commit).splitlines()
956 if x and x[0] != '#']
957 if sorted(data) != data:
958 errors += ['keep lines sorted']
Mike Frysinger998c2cc2014-08-27 05:20:23 -0400959
Mike Frysinger94a670c2014-09-19 12:46:26 -0400960 # Require people to set specific values all the time.
961 settings = (
962 # TODO: Enable this for everyone. http://crbug.com/408038
963 #('fast caching', 'cache-format = md5-dict'),
964 ('fast manifests', 'thin-manifests = true'),
Mike Frysingerd7734522015-02-26 16:12:43 -0500965 ('extra features', 'profile-formats = portage-2 profile-default-eapi'),
966 ('newer eapi', 'profile_eapi_when_unspecified = 5-progress'),
Mike Frysinger94a670c2014-09-19 12:46:26 -0400967 )
968 for reason, line in settings:
969 if line not in data:
970 errors += ['enable %s with: %s' % (reason, line)]
Mike Frysinger998c2cc2014-08-27 05:20:23 -0400971
Mike Frysinger94a670c2014-09-19 12:46:26 -0400972 # Require one of these settings.
973 if ('use-manifests = true' not in data and
974 'use-manifests = strict' not in data):
975 errors += ['enable file checking with: use-manifests = true']
Mike Frysinger998c2cc2014-08-27 05:20:23 -0400976
Mike Frysinger94a670c2014-09-19 12:46:26 -0400977 # Require repo-name to be set.
Mike Frysinger324cf682014-09-22 15:52:50 -0400978 for line in data:
979 if line.startswith('repo-name = '):
980 break
981 else:
Mike Frysinger94a670c2014-09-19 12:46:26 -0400982 errors += ['set the board name with: repo-name = $BOARD']
Mike Frysinger998c2cc2014-08-27 05:20:23 -0400983
Mike Frysinger94a670c2014-09-19 12:46:26 -0400984 # Summarize all the errors we saw (if any).
985 lines = ''
986 for layout_path, errors in all_errors.items():
987 if errors:
988 lines += '\n\t- '.join(['\n* %s:' % layout_path] + errors)
989 if lines:
990 lines = 'See the portage(5) man page for layout.conf details' + lines + '\n'
991 return HookFailure(lines)
Mike Frysinger998c2cc2014-08-27 05:20:23 -0400992
993
Ryan Cuiec4d6332011-05-02 14:15:25 -0700994# Project-specific hooks
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700995
Ryan Cui1562fb82011-05-09 11:01:31 -0700996
Mike Frysingerae409522014-02-01 03:16:11 -0500997def _run_checkpatch(_project, commit, options=()):
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700998 """Runs checkpatch.pl on the given project"""
999 hooks_dir = _get_hooks_dir()
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001000 options = list(options)
1001 if commit == PRE_SUBMIT:
1002 # The --ignore option must be present and include 'MISSING_SIGN_OFF' in
1003 # this case.
1004 options.append('--ignore=MISSING_SIGN_OFF')
1005 cmd = ['%s/checkpatch.pl' % hooks_dir] + options + ['-']
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001006 p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Che-Liang Chiou5ce2d7b2013-03-22 18:47:55 -07001007 output = p.communicate(_get_patch(commit))[0]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001008 if p.returncode:
Ryan Cui1562fb82011-05-09 11:01:31 -07001009 return HookFailure('checkpatch.pl errors/warnings\n\n' + output)
Ryan Cuiec4d6332011-05-02 14:15:25 -07001010
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001011
Mike Frysingerae409522014-02-01 03:16:11 -05001012def _kernel_configcheck(_project, commit):
Olof Johanssona96810f2012-09-04 16:20:03 -07001013 """Makes sure kernel config changes are not mixed with code changes"""
1014 files = _get_affected_files(commit)
1015 if not len(_filter_files(files, [r'chromeos/config'])) in [0, len(files)]:
1016 return HookFailure('Changes to chromeos/config/ and regular files must '
1017 'be in separate commits:\n%s' % '\n'.join(files))
Anton Staaf815d6852011-08-22 10:08:45 -07001018
Mike Frysingerae409522014-02-01 03:16:11 -05001019
1020def _run_json_check(_project, commit):
Dale Curtis2975c432011-05-03 17:25:20 -07001021 """Checks that all JSON files are syntactically valid."""
Dale Curtisa039cfd2011-05-04 12:01:05 -07001022 for f in _filter_files(_get_affected_files(commit), [r'.*\.json']):
Dale Curtis2975c432011-05-03 17:25:20 -07001023 try:
1024 json.load(open(f))
1025 except Exception, e:
Ryan Cui1562fb82011-05-09 11:01:31 -07001026 return HookFailure('Invalid JSON in %s: %s' % (f, e))
Dale Curtis2975c432011-05-03 17:25:20 -07001027
1028
Mike Frysingerae409522014-02-01 03:16:11 -05001029def _check_manifests(_project, commit):
Mike Frysinger52b537e2013-08-22 22:59:53 -04001030 """Make sure Manifest files only have DIST lines"""
1031 paths = []
1032
1033 for path in _get_affected_files(commit):
1034 if os.path.basename(path) != 'Manifest':
1035 continue
1036 if not os.path.exists(path):
1037 continue
1038
1039 with open(path, 'r') as f:
1040 for line in f.readlines():
1041 if not line.startswith('DIST '):
1042 paths.append(path)
1043 break
1044
1045 if paths:
1046 return HookFailure('Please remove lines that do not start with DIST:\n%s' %
1047 ('\n'.join(paths),))
1048
1049
Mike Frysingerae409522014-02-01 03:16:11 -05001050def _check_change_has_branch_field(_project, commit):
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001051 """Check for a non-empty 'BRANCH=' field in the commit message."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001052 if commit == PRE_SUBMIT:
1053 return
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001054 BRANCH_RE = r'\nBRANCH=\S+'
1055
1056 if not re.search(BRANCH_RE, _get_commit_desc(commit)):
1057 msg = ('Changelist description needs BRANCH field (after first line)\n'
1058 'E.g. BRANCH=none or BRANCH=link,snow')
1059 return HookFailure(msg)
1060
1061
Mike Frysingerae409522014-02-01 03:16:11 -05001062def _check_change_has_signoff_field(_project, commit):
Shawn Nematbakhsh51e16ac2014-01-28 15:31:07 -08001063 """Check for a non-empty 'Signed-off-by:' field in the commit message."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001064 if commit == PRE_SUBMIT:
1065 return
Shawn Nematbakhsh51e16ac2014-01-28 15:31:07 -08001066 SIGNOFF_RE = r'\nSigned-off-by: \S+'
1067
1068 if not re.search(SIGNOFF_RE, _get_commit_desc(commit)):
1069 msg = ('Changelist description needs Signed-off-by: field\n'
1070 'E.g. Signed-off-by: My Name <me@chromium.org>')
1071 return HookFailure(msg)
1072
1073
Jon Salz3ee59de2012-08-18 13:54:22 +08001074def _run_project_hook_script(script, project, commit):
1075 """Runs a project hook script.
1076
1077 The script is run with the following environment variables set:
1078 PRESUBMIT_PROJECT: The affected project
1079 PRESUBMIT_COMMIT: The affected commit
1080 PRESUBMIT_FILES: A newline-separated list of affected files
1081
1082 The script is considered to fail if the exit code is non-zero. It should
1083 write an error message to stdout.
1084 """
1085 env = dict(os.environ)
1086 env['PRESUBMIT_PROJECT'] = project
1087 env['PRESUBMIT_COMMIT'] = commit
1088
1089 # Put affected files in an environment variable
1090 files = _get_affected_files(commit)
1091 env['PRESUBMIT_FILES'] = '\n'.join(files)
1092
1093 process = subprocess.Popen(script, env=env, shell=True,
1094 stdin=open(os.devnull),
Jon Salz7b618af2012-08-31 06:03:16 +08001095 stdout=subprocess.PIPE,
1096 stderr=subprocess.STDOUT)
Jon Salz3ee59de2012-08-18 13:54:22 +08001097 stdout, _ = process.communicate()
1098 if process.wait():
Jon Salz7b618af2012-08-31 06:03:16 +08001099 if stdout:
1100 stdout = re.sub('(?m)^', ' ', stdout)
1101 return HookFailure('Hook script "%s" failed with code %d%s' %
Jon Salz3ee59de2012-08-18 13:54:22 +08001102 (script, process.returncode,
1103 ':\n' + stdout if stdout else ''))
1104
1105
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001106def _check_project_prefix(_project, commit):
Mike Frysinger55f85b52014-12-18 14:45:21 -05001107 """Require the commit message have a project specific prefix as needed."""
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001108
1109 files = _get_affected_files(commit, relative=True)
1110 prefix = os.path.commonprefix(files)
1111 prefix = os.path.dirname(prefix)
1112
1113 # If there is no common prefix, the CL span multiple projects.
Daniel Erata350fd32014-09-29 14:02:34 -07001114 if not prefix:
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001115 return
1116
1117 project_name = prefix.split('/')[0]
Daniel Erata350fd32014-09-29 14:02:34 -07001118
1119 # The common files may all be within a subdirectory of the main project
1120 # directory, so walk up the tree until we find an alias file.
1121 # _get_affected_files() should return relative paths, but check against '/' to
1122 # ensure that this loop terminates even if it receives an absolute path.
1123 while prefix and prefix != '/':
1124 alias_file = os.path.join(prefix, '.project_alias')
1125
1126 # If an alias exists, use it.
1127 if os.path.isfile(alias_file):
1128 project_name = osutils.ReadFile(alias_file).strip()
1129
1130 prefix = os.path.dirname(prefix)
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001131
1132 if not _get_commit_desc(commit).startswith(project_name + ': '):
1133 return HookFailure('The commit title for changes affecting only %s'
1134 ' should start with \"%s: \"'
1135 % (project_name, project_name))
1136
1137
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001138# Base
1139
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001140# A list of hooks which are not project specific and check patch description
1141# (as opposed to patch body).
1142_PATCH_DESCRIPTION_HOOKS = [
Ryan Cui9b651632011-05-11 11:38:58 -07001143 _check_change_has_bug_field,
David Jamesc3b68b32013-04-03 09:17:03 -07001144 _check_change_has_valid_cq_depend,
Ryan Cui9b651632011-05-11 11:38:58 -07001145 _check_change_has_test_field,
1146 _check_change_has_proper_changeid,
Mike Frysinger36b2ebc2014-10-31 14:02:03 -04001147 _check_commit_message_style,
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001148]
1149
1150
1151# A list of hooks that are not project-specific
1152_COMMON_HOOKS = [
Mike Frysingerbf8b91c2014-02-01 02:50:27 -05001153 _check_ebuild_eapi,
Mike Frysinger89bdb852014-02-01 05:26:26 -05001154 _check_ebuild_keywords,
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -08001155 _check_ebuild_licenses,
Mike Frysingercd363c82014-02-01 05:20:18 -05001156 _check_ebuild_virtual_pv,
Daniel Erat9d203ff2015-02-17 10:12:21 -07001157 _check_for_uprev,
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001158 _check_layout_conf,
Ryan Cui9b651632011-05-11 11:38:58 -07001159 _check_license,
Daniel Erat9d203ff2015-02-17 10:12:21 -07001160 _check_no_long_lines,
1161 _check_no_stray_whitespace,
Ryan Cui9b651632011-05-11 11:38:58 -07001162 _check_no_tabs,
Daniel Erat9d203ff2015-02-17 10:12:21 -07001163 _check_portage_make_use_var,
Ryan Cui9b651632011-05-11 11:38:58 -07001164]
Ryan Cuiec4d6332011-05-02 14:15:25 -07001165
Ryan Cui1562fb82011-05-09 11:01:31 -07001166
Ryan Cui9b651632011-05-11 11:38:58 -07001167# A dictionary of project-specific hooks(callbacks), indexed by project name.
1168# dict[project] = [callback1, callback2]
1169_PROJECT_SPECIFIC_HOOKS = {
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001170 "chromiumos/platform2": [_check_project_prefix],
Mike Frysingeraf891292015-03-25 19:46:53 -04001171 "chromiumos/third_party/kernel": [_kernel_configcheck],
1172 "chromiumos/third_party/kernel-next": [_kernel_configcheck],
Ryan Cui9b651632011-05-11 11:38:58 -07001173}
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001174
Ryan Cui1562fb82011-05-09 11:01:31 -07001175
Ryan Cui9b651632011-05-11 11:38:58 -07001176# A dictionary of flags (keys) that can appear in the config file, and the hook
Mike Frysinger3554bc92015-03-11 04:59:21 -04001177# that the flag controls (value).
1178_HOOK_FLAGS = {
Mike Frysingera7642f52015-03-25 18:31:42 -04001179 'checkpatch_check': _run_checkpatch,
Ryan Cui9b651632011-05-11 11:38:58 -07001180 'stray_whitespace_check': _check_no_stray_whitespace,
Mike Frysingerff6c7d62015-03-24 13:49:46 -04001181 'json_check': _run_json_check,
Ryan Cui9b651632011-05-11 11:38:58 -07001182 'long_line_check': _check_no_long_lines,
1183 'cros_license_check': _check_license,
1184 'tab_check': _check_no_tabs,
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001185 'branch_check': _check_change_has_branch_field,
Shawn Nematbakhsh51e16ac2014-01-28 15:31:07 -08001186 'signoff_check': _check_change_has_signoff_field,
Josh Triplett0e8fc7f2014-04-23 16:00:00 -07001187 'bug_field_check': _check_change_has_bug_field,
1188 'test_field_check': _check_change_has_test_field,
Steve Fung49ec7e92015-03-23 16:07:12 -07001189 'manifest_check': _check_manifests,
Ryan Cui9b651632011-05-11 11:38:58 -07001190}
1191
1192
Mike Frysinger3554bc92015-03-11 04:59:21 -04001193def _get_override_hooks(config):
1194 """Returns a set of hooks controlled by the current project's config file.
Ryan Cui9b651632011-05-11 11:38:58 -07001195
1196 Expects to be called within the project root.
Jon Salz3ee59de2012-08-18 13:54:22 +08001197
1198 Args:
1199 config: A ConfigParser for the project's config file.
Ryan Cui9b651632011-05-11 11:38:58 -07001200 """
1201 SECTION = 'Hook Overrides'
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001202 SECTION_OPTIONS = 'Hook Overrides Options'
Jon Salz3ee59de2012-08-18 13:54:22 +08001203 if not config.has_section(SECTION):
Mike Frysinger3554bc92015-03-11 04:59:21 -04001204 return set(), set()
Ryan Cui9b651632011-05-11 11:38:58 -07001205
Mike Frysinger3554bc92015-03-11 04:59:21 -04001206 valid_keys = set(_HOOK_FLAGS.iterkeys())
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001207 hooks = _HOOK_FLAGS.copy()
Mike Frysinger3554bc92015-03-11 04:59:21 -04001208
1209 enable_flags = []
Ryan Cui9b651632011-05-11 11:38:58 -07001210 disable_flags = []
Jon Salz3ee59de2012-08-18 13:54:22 +08001211 for flag in config.options(SECTION):
Mike Frysinger3554bc92015-03-11 04:59:21 -04001212 if flag not in valid_keys:
1213 raise ValueError('Error: unknown key "%s" in hook section of "%s"' %
1214 (flag, _CONFIG_FILE))
1215
Ryan Cui9b651632011-05-11 11:38:58 -07001216 try:
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001217 enabled = config.getboolean(SECTION, flag)
Ryan Cui9b651632011-05-11 11:38:58 -07001218 except ValueError as e:
Mike Frysinger3554bc92015-03-11 04:59:21 -04001219 raise ValueError('Error: parsing flag "%s" in "%s" failed: %s' %
1220 (flag, _CONFIG_FILE, e))
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001221 if enabled:
1222 enable_flags.append(flag)
1223 else:
1224 disable_flags.append(flag)
Ryan Cui9b651632011-05-11 11:38:58 -07001225
Mike Frysingerf8ce1712015-03-25 18:32:33 -04001226 # See if this hook has custom options.
1227 if enabled:
1228 try:
1229 options = config.get(SECTION_OPTIONS, flag)
1230 hooks[flag] = functools.partial(hooks[flag], options=options.split())
1231 except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
1232 pass
1233
1234 enabled_hooks = set(hooks[x] for x in enable_flags)
1235 disabled_hooks = set(hooks[x] for x in disable_flags)
Mike Frysinger3554bc92015-03-11 04:59:21 -04001236 return enabled_hooks, disabled_hooks
Ryan Cui9b651632011-05-11 11:38:58 -07001237
1238
Jon Salz3ee59de2012-08-18 13:54:22 +08001239def _get_project_hook_scripts(config):
1240 """Returns a list of project-specific hook scripts.
1241
1242 Args:
1243 config: A ConfigParser for the project's config file.
1244 """
1245 SECTION = 'Hook Scripts'
1246 if not config.has_section(SECTION):
1247 return []
1248
1249 hook_names_values = config.items(SECTION)
1250 hook_names_values.sort(key=lambda x: x[0])
1251 return [x[1] for x in hook_names_values]
1252
1253
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001254def _get_project_hooks(project, presubmit):
Ryan Cui9b651632011-05-11 11:38:58 -07001255 """Returns a list of hooks that need to be run for a project.
1256
1257 Expects to be called from within the project root.
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001258
1259 Args:
1260 project: A string, name of the project.
1261 presubmit: A Boolean, True if the check is run as a git pre-submit script.
Ryan Cui9b651632011-05-11 11:38:58 -07001262 """
Jon Salz3ee59de2012-08-18 13:54:22 +08001263 config = ConfigParser.RawConfigParser()
1264 try:
1265 config.read(_CONFIG_FILE)
1266 except ConfigParser.Error:
1267 # Just use an empty config file
1268 config = ConfigParser.RawConfigParser()
1269
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001270 if presubmit:
1271 hook_list = _COMMON_HOOKS
1272 else:
1273 hook_list = _PATCH_DESCRIPTION_HOOKS + _COMMON_HOOKS
1274
Mike Frysinger3554bc92015-03-11 04:59:21 -04001275 enabled_hooks, disabled_hooks = _get_override_hooks(config)
1276 hooks = (list(enabled_hooks) +
1277 [hook for hook in hook_list if hook not in disabled_hooks])
Ryan Cui9b651632011-05-11 11:38:58 -07001278
1279 if project in _PROJECT_SPECIFIC_HOOKS:
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001280 hooks.extend(hook for hook in _PROJECT_SPECIFIC_HOOKS[project]
1281 if hook not in disabled_hooks)
Ryan Cui9b651632011-05-11 11:38:58 -07001282
Jon Salz3ee59de2012-08-18 13:54:22 +08001283 for script in _get_project_hook_scripts(config):
1284 hooks.append(functools.partial(_run_project_hook_script, script))
1285
Ryan Cui9b651632011-05-11 11:38:58 -07001286 return hooks
1287
1288
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001289def _run_project_hooks(project, proj_dir=None,
1290 commit_list=None, presubmit=False):
Ryan Cui1562fb82011-05-09 11:01:31 -07001291 """For each project run its project specific hook from the hooks dictionary.
1292
1293 Args:
Doug Anderson44a644f2011-11-02 10:37:37 -07001294 project: The name of project to run hooks for.
1295 proj_dir: If non-None, this is the directory the project is in. If None,
1296 we'll ask repo.
Doug Anderson14749562013-06-26 13:38:29 -07001297 commit_list: A list of commits to run hooks against. If None or empty list
1298 then we'll automatically get the list of commits that would be uploaded.
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001299 presubmit: A Boolean, True if the check is run as a git pre-submit script.
Ryan Cui1562fb82011-05-09 11:01:31 -07001300
1301 Returns:
1302 Boolean value of whether any errors were ecountered while running the hooks.
1303 """
Doug Anderson44a644f2011-11-02 10:37:37 -07001304 if proj_dir is None:
David James2edd9002013-10-11 14:09:19 -07001305 proj_dirs = _run_command(['repo', 'forall', project, '-c', 'pwd']).split()
1306 if len(proj_dirs) == 0:
1307 print('%s cannot be found.' % project, file=sys.stderr)
1308 print('Please specify a valid project.', file=sys.stderr)
1309 return True
1310 if len(proj_dirs) > 1:
1311 print('%s is associated with multiple directories.' % project,
1312 file=sys.stderr)
1313 print('Please specify a directory to help disambiguate.', file=sys.stderr)
1314 return True
1315 proj_dir = proj_dirs[0]
Doug Anderson44a644f2011-11-02 10:37:37 -07001316
Ryan Cuiec4d6332011-05-02 14:15:25 -07001317 pwd = os.getcwd()
1318 # hooks assume they are run from the root of the project
1319 os.chdir(proj_dir)
1320
Doug Anderson14749562013-06-26 13:38:29 -07001321 if not commit_list:
1322 try:
1323 commit_list = _get_commits()
1324 except VerifyException as e:
1325 PrintErrorForProject(project, HookFailure(str(e)))
1326 os.chdir(pwd)
1327 return True
Ryan Cuifa55df52011-05-06 11:16:55 -07001328
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001329 hooks = _get_project_hooks(project, presubmit)
Ryan Cui1562fb82011-05-09 11:01:31 -07001330 error_found = False
Ryan Cuifa55df52011-05-06 11:16:55 -07001331 for commit in commit_list:
Ryan Cui1562fb82011-05-09 11:01:31 -07001332 error_list = []
Ryan Cui9b651632011-05-11 11:38:58 -07001333 for hook in hooks:
Ryan Cui1562fb82011-05-09 11:01:31 -07001334 hook_error = hook(project, commit)
1335 if hook_error:
1336 error_list.append(hook_error)
1337 error_found = True
1338 if error_list:
1339 PrintErrorsForCommit(project, commit, _get_commit_desc(commit),
1340 error_list)
Don Garrettdba548a2011-05-05 15:17:14 -07001341
Ryan Cuiec4d6332011-05-02 14:15:25 -07001342 os.chdir(pwd)
Ryan Cui1562fb82011-05-09 11:01:31 -07001343 return error_found
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001344
Mike Frysingerae409522014-02-01 03:16:11 -05001345
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001346# Main
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -07001347
Ryan Cui1562fb82011-05-09 11:01:31 -07001348
Mike Frysingerae409522014-02-01 03:16:11 -05001349def main(project_list, worktree_list=None, **_kwargs):
Doug Anderson06456632012-01-05 11:02:14 -08001350 """Main function invoked directly by repo.
1351
1352 This function will exit directly upon error so that repo doesn't print some
1353 obscure error message.
1354
1355 Args:
1356 project_list: List of projects to run on.
David James2edd9002013-10-11 14:09:19 -07001357 worktree_list: A list of directories. It should be the same length as
1358 project_list, so that each entry in project_list matches with a directory
1359 in worktree_list. If None, we will attempt to calculate the directories
1360 automatically.
Doug Anderson06456632012-01-05 11:02:14 -08001361 kwargs: Leave this here for forward-compatibility.
1362 """
Ryan Cui1562fb82011-05-09 11:01:31 -07001363 found_error = False
David James2edd9002013-10-11 14:09:19 -07001364 if not worktree_list:
1365 worktree_list = [None] * len(project_list)
1366 for project, worktree in zip(project_list, worktree_list):
1367 if _run_project_hooks(project, proj_dir=worktree):
Ryan Cui1562fb82011-05-09 11:01:31 -07001368 found_error = True
1369
Mike Frysingerae409522014-02-01 03:16:11 -05001370 if found_error:
Ryan Cui1562fb82011-05-09 11:01:31 -07001371 msg = ('Preupload failed due to errors in project(s). HINTS:\n'
Ryan Cui9b651632011-05-11 11:38:58 -07001372 '- To disable some source style checks, and for other hints, see '
1373 '<checkout_dir>/src/repohooks/README\n'
1374 '- To upload only current project, run \'repo upload .\'')
Mike Frysinger09d6a3d2013-10-08 22:21:03 -04001375 print(msg, file=sys.stderr)
Don Garrettdba548a2011-05-05 15:17:14 -07001376 sys.exit(1)
Anush Elangovan63afad72011-03-23 00:41:27 -07001377
Ryan Cui1562fb82011-05-09 11:01:31 -07001378
Doug Anderson44a644f2011-11-02 10:37:37 -07001379def _identify_project(path):
1380 """Identify the repo project associated with the given path.
1381
1382 Returns:
1383 A string indicating what project is associated with the path passed in or
1384 a blank string upon failure.
1385 """
1386 return _run_command(['repo', 'forall', '.', '-c', 'echo ${REPO_PROJECT}'],
Mike Frysingerb81102f2014-11-21 00:33:35 -05001387 stderr=subprocess.PIPE, cwd=path).strip()
Doug Anderson44a644f2011-11-02 10:37:37 -07001388
1389
Mike Frysinger55f85b52014-12-18 14:45:21 -05001390def direct_main(argv):
Doug Anderson44a644f2011-11-02 10:37:37 -07001391 """Run hooks directly (outside of the context of repo).
1392
Doug Anderson44a644f2011-11-02 10:37:37 -07001393 Args:
Mike Frysinger55f85b52014-12-18 14:45:21 -05001394 argv: The command line args to process
Doug Anderson44a644f2011-11-02 10:37:37 -07001395
1396 Returns:
1397 0 if no pre-upload failures, 1 if failures.
1398
1399 Raises:
1400 BadInvocation: On some types of invocation errors.
1401 """
Mike Frysinger66142932014-12-18 14:55:57 -05001402 parser = commandline.ArgumentParser(description=__doc__)
1403 parser.add_argument('--dir', default=None,
1404 help='The directory that the project lives in. If not '
1405 'specified, use the git project root based on the cwd.')
1406 parser.add_argument('--project', default=None,
1407 help='The project repo path; this can affect how the '
1408 'hooks get run, since some hooks are project-specific. '
1409 'For chromite this is chromiumos/chromite. If not '
1410 'specified, the repo tool will be used to figure this '
1411 'out based on the dir.')
1412 parser.add_argument('--rerun-since', default=None,
1413 help='Rerun hooks on old commits since the given date. '
1414 'The date should match git log\'s concept of a date. '
1415 'e.g. 2012-06-20. This option is mutually exclusive '
1416 'with --pre-submit.')
1417 parser.add_argument('--pre-submit', action="store_true",
1418 help='Run the check against the pending commit. '
1419 'This option should be used at the \'git commit\' '
1420 'phase as opposed to \'repo upload\'. This option '
1421 'is mutually exclusive with --rerun-since.')
1422 parser.add_argument('commits', nargs='*',
1423 help='Check specific commits')
1424 opts = parser.parse_args(argv)
Doug Anderson44a644f2011-11-02 10:37:37 -07001425
Doug Anderson14749562013-06-26 13:38:29 -07001426 if opts.rerun_since:
Mike Frysinger66142932014-12-18 14:55:57 -05001427 if opts.commits:
Doug Anderson14749562013-06-26 13:38:29 -07001428 raise BadInvocation('Can\'t pass commits and use rerun-since: %s' %
Mike Frysinger66142932014-12-18 14:55:57 -05001429 ' '.join(opts.commits))
Doug Anderson14749562013-06-26 13:38:29 -07001430
1431 cmd = ['git', 'log', '--since="%s"' % opts.rerun_since, '--pretty=%H']
1432 all_commits = _run_command(cmd).splitlines()
1433 bot_commits = _run_command(cmd + ['--author=chrome-bot']).splitlines()
1434
1435 # Eliminate chrome-bot commits but keep ordering the same...
1436 bot_commits = set(bot_commits)
Mike Frysinger66142932014-12-18 14:55:57 -05001437 opts.commits = [c for c in all_commits if c not in bot_commits]
Doug Anderson14749562013-06-26 13:38:29 -07001438
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001439 if opts.pre_submit:
1440 raise BadInvocation('rerun-since and pre-submit can not be '
1441 'used together')
1442 if opts.pre_submit:
Mike Frysinger66142932014-12-18 14:55:57 -05001443 if opts.commits:
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001444 raise BadInvocation('Can\'t pass commits and use pre-submit: %s' %
Mike Frysinger66142932014-12-18 14:55:57 -05001445 ' '.join(opts.commits))
1446 opts.commits = [PRE_SUBMIT,]
Doug Anderson44a644f2011-11-02 10:37:37 -07001447
1448 # Check/normlaize git dir; if unspecified, we'll use the root of the git
1449 # project from CWD
1450 if opts.dir is None:
1451 git_dir = _run_command(['git', 'rev-parse', '--git-dir'],
1452 stderr=subprocess.PIPE).strip()
1453 if not git_dir:
1454 raise BadInvocation('The current directory is not part of a git project.')
1455 opts.dir = os.path.dirname(os.path.abspath(git_dir))
1456 elif not os.path.isdir(opts.dir):
1457 raise BadInvocation('Invalid dir: %s' % opts.dir)
1458 elif not os.path.isdir(os.path.join(opts.dir, '.git')):
1459 raise BadInvocation('Not a git directory: %s' % opts.dir)
1460
1461 # Identify the project if it wasn't specified; this _requires_ the repo
1462 # tool to be installed and for the project to be part of a repo checkout.
1463 if not opts.project:
1464 opts.project = _identify_project(opts.dir)
1465 if not opts.project:
1466 raise BadInvocation("Repo couldn't identify the project of %s" % opts.dir)
1467
Doug Anderson14749562013-06-26 13:38:29 -07001468 found_error = _run_project_hooks(opts.project, proj_dir=opts.dir,
Mike Frysinger66142932014-12-18 14:55:57 -05001469 commit_list=opts.commits,
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001470 presubmit=opts.pre_submit)
Doug Anderson44a644f2011-11-02 10:37:37 -07001471 if found_error:
1472 return 1
1473 return 0
1474
1475
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -07001476if __name__ == '__main__':
Mike Frysinger55f85b52014-12-18 14:45:21 -05001477 sys.exit(direct_main(sys.argv[1:]))