blob: 5279da5ff31cfe98d25035d8d4305bd28647df39 [file] [log] [blame]
Doug Anderson44a644f2011-11-02 10:37:37 -07001#!/usr/bin/env python
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
Jon Salz3ee59de2012-08-18 13:54:22 +080014import functools
Dale Curtis2975c432011-05-03 17:25:20 -070015import json
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070016import os
Ryan Cuiec4d6332011-05-02 14:15:25 -070017import re
Mandeep Singh Bainesa7ffa4b2011-05-03 11:37:02 -070018import sys
Peter Ammon811f6702014-06-12 15:45:38 -070019import stat
Mike Frysingerd3bd32c2014-11-24 23:34:29 -050020import subprocess
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070021
Ryan Cui1562fb82011-05-09 11:01:31 -070022from errors import (VerifyException, HookFailure, PrintErrorForProject,
23 PrintErrorsForCommit)
Ryan Cuiec4d6332011-05-02 14:15:25 -070024
David Jamesc3b68b32013-04-03 09:17:03 -070025# If repo imports us, the __name__ will be __builtin__, and the wrapper will
26# be in $CHROMEOS_CHECKOUT/.repo/repo/main.py, so we need to go two directories
27# up. The same logic also happens to work if we're executed directly.
28if __name__ in ('__builtin__', '__main__'):
29 sys.path.insert(0, os.path.join(os.path.dirname(sys.argv[0]), '..', '..'))
30
Mike Frysinger66142932014-12-18 14:55:57 -050031from chromite.lib import commandline
Mike Frysingerd3bd32c2014-11-24 23:34:29 -050032from chromite.lib import git
Daniel Erata350fd32014-09-29 14:02:34 -070033from chromite.lib import osutils
David Jamesc3b68b32013-04-03 09:17:03 -070034from chromite.lib import patch
Mike Frysinger2ec70ed2014-08-17 19:28:34 -040035from chromite.licensing import licenses_lib
David Jamesc3b68b32013-04-03 09:17:03 -070036
Vadim Bendebury2b62d742014-06-22 13:14:51 -070037PRE_SUBMIT = 'pre-submit'
Ryan Cuiec4d6332011-05-02 14:15:25 -070038
39COMMON_INCLUDED_PATHS = [
Mike Frysingerae409522014-02-01 03:16:11 -050040 # C++ and friends
41 r".*\.c$", r".*\.cc$", r".*\.cpp$", r".*\.h$", r".*\.m$", r".*\.mm$",
42 r".*\.inl$", r".*\.asm$", r".*\.hxx$", r".*\.hpp$", r".*\.s$", r".*\.S$",
43 # Scripts
44 r".*\.js$", r".*\.py$", r".*\.sh$", r".*\.rb$", r".*\.pl$", r".*\.pm$",
45 # No extension at all, note that ALL CAPS files are black listed in
46 # COMMON_EXCLUDED_LIST below.
47 r"(^|.*[\\\/])[^.]+$",
48 # Other
49 r".*\.java$", r".*\.mk$", r".*\.am$",
Ryan Cuiec4d6332011-05-02 14:15:25 -070050]
51
Ryan Cui1562fb82011-05-09 11:01:31 -070052
Ryan Cuiec4d6332011-05-02 14:15:25 -070053COMMON_EXCLUDED_PATHS = [
Mike Frysingerae409522014-02-01 03:16:11 -050054 # avoid doing source file checks for kernel
55 r"/src/third_party/kernel/",
56 r"/src/third_party/kernel-next/",
57 r"/src/third_party/ktop/",
58 r"/src/third_party/punybench/",
59 r".*\bexperimental[\\\/].*",
60 r".*\b[A-Z0-9_]{2,}$",
61 r".*[\\\/]debian[\\\/]rules$",
62 # for ebuild trees, ignore any caches and manifest data
63 r".*/Manifest$",
64 r".*/metadata/[^/]*cache[^/]*/[^/]+/[^/]+$",
Doug Anderson5bfb6792011-10-25 16:45:41 -070065
Mike Frysingerae409522014-02-01 03:16:11 -050066 # ignore profiles data (like overlay-tegra2/profiles)
Mike Frysinger94a670c2014-09-19 12:46:26 -040067 r"(^|.*/)overlay-.*/profiles/.*",
Mike Frysinger98638102014-08-28 00:15:08 -040068 r"^profiles/.*$",
69
Mike Frysingerae409522014-02-01 03:16:11 -050070 # ignore minified js and jquery
71 r".*\.min\.js",
72 r".*jquery.*\.js",
Mike Frysinger33a458d2014-03-03 17:00:51 -050073
74 # Ignore license files as the content is often taken verbatim.
75 r'.*/licenses/.*',
Ryan Cuiec4d6332011-05-02 14:15:25 -070076]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -070077
Ryan Cui1562fb82011-05-09 11:01:31 -070078
Ryan Cui9b651632011-05-11 11:38:58 -070079_CONFIG_FILE = 'PRESUBMIT.cfg'
80
81
Doug Anderson44a644f2011-11-02 10:37:37 -070082# Exceptions
83
84
85class BadInvocation(Exception):
86 """An Exception indicating a bad invocation of the program."""
87 pass
88
89
Ryan Cui1562fb82011-05-09 11:01:31 -070090# General Helpers
91
Sean Paulba01d402011-05-05 11:36:23 -040092
Doug Anderson44a644f2011-11-02 10:37:37 -070093def _run_command(cmd, cwd=None, stderr=None):
94 """Executes the passed in command and returns raw stdout output.
95
96 Args:
97 cmd: The command to run; should be a list of strings.
98 cwd: The directory to switch to for running the command.
99 stderr: Can be one of None (print stderr to console), subprocess.STDOUT
100 (combine stderr with stdout), or subprocess.PIPE (ignore stderr).
101
102 Returns:
103 The standard out from the process.
104 """
105 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=stderr, cwd=cwd)
106 return p.communicate()[0]
Ryan Cui72834d12011-05-05 14:51:33 -0700107
Ryan Cui1562fb82011-05-09 11:01:31 -0700108
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700109def _get_hooks_dir():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700110 """Returns the absolute path to the repohooks directory."""
Doug Anderson44a644f2011-11-02 10:37:37 -0700111 if __name__ == '__main__':
112 # Works when file is run on its own (__file__ is defined)...
113 return os.path.abspath(os.path.dirname(__file__))
114 else:
115 # We need to do this when we're run through repo. Since repo executes
116 # us with execfile(), we don't get __file__ defined.
117 cmd = ['repo', 'forall', 'chromiumos/repohooks', '-c', 'pwd']
118 return _run_command(cmd).strip()
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700119
Ryan Cui1562fb82011-05-09 11:01:31 -0700120
Ryan Cuiec4d6332011-05-02 14:15:25 -0700121def _match_regex_list(subject, expressions):
122 """Try to match a list of regular expressions to a string.
123
124 Args:
125 subject: The string to match regexes on
126 expressions: A list of regular expressions to check for matches with.
127
128 Returns:
129 Whether the passed in subject matches any of the passed in regexes.
130 """
131 for expr in expressions:
Mike Frysingerae409522014-02-01 03:16:11 -0500132 if re.search(expr, subject):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700133 return True
134 return False
135
Ryan Cui1562fb82011-05-09 11:01:31 -0700136
Mike Frysingerae409522014-02-01 03:16:11 -0500137def _filter_files(files, include_list, exclude_list=()):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700138 """Filter out files based on the conditions passed in.
139
140 Args:
141 files: list of filepaths to filter
142 include_list: list of regex that when matched with a file path will cause it
143 to be added to the output list unless the file is also matched with a
144 regex in the exclude_list.
145 exclude_list: list of regex that when matched with a file will prevent it
146 from being added to the output list, even if it is also matched with a
147 regex in the include_list.
148
149 Returns:
150 A list of filepaths that contain files matched in the include_list and not
151 in the exclude_list.
152 """
153 filtered = []
154 for f in files:
155 if (_match_regex_list(f, include_list) and
156 not _match_regex_list(f, exclude_list)):
157 filtered.append(f)
158 return filtered
159
Ryan Cuiec4d6332011-05-02 14:15:25 -0700160
161# Git Helpers
Ryan Cui1562fb82011-05-09 11:01:31 -0700162
163
Ryan Cui4725d952011-05-05 15:41:19 -0700164def _get_upstream_branch():
165 """Returns the upstream tracking branch of the current branch.
166
167 Raises:
168 Error if there is no tracking branch
169 """
170 current_branch = _run_command(['git', 'symbolic-ref', 'HEAD']).strip()
171 current_branch = current_branch.replace('refs/heads/', '')
172 if not current_branch:
Ryan Cui1562fb82011-05-09 11:01:31 -0700173 raise VerifyException('Need to be on a tracking branch')
Ryan Cui4725d952011-05-05 15:41:19 -0700174
175 cfg_option = 'branch.' + current_branch + '.%s'
176 full_upstream = _run_command(['git', 'config', cfg_option % 'merge']).strip()
177 remote = _run_command(['git', 'config', cfg_option % 'remote']).strip()
178 if not remote or not full_upstream:
Ryan Cui1562fb82011-05-09 11:01:31 -0700179 raise VerifyException('Need to be on a tracking branch')
Ryan Cui4725d952011-05-05 15:41:19 -0700180
181 return full_upstream.replace('heads', 'remotes/' + remote)
182
Ryan Cui1562fb82011-05-09 11:01:31 -0700183
Che-Liang Chiou5ce2d7b2013-03-22 18:47:55 -0700184def _get_patch(commit):
185 """Returns the patch for this commit."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700186 if commit == PRE_SUBMIT:
187 return _run_command(['git', 'diff', '--cached', 'HEAD'])
188 else:
189 return _run_command(['git', 'format-patch', '--stdout', '-1', commit])
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700190
Ryan Cui1562fb82011-05-09 11:01:31 -0700191
Jon Salz98255932012-08-18 14:48:02 +0800192def _try_utf8_decode(data):
193 """Attempts to decode a string as UTF-8.
194
195 Returns:
196 The decoded Unicode object, or the original string if parsing fails.
197 """
198 try:
199 return unicode(data, 'utf-8', 'strict')
200 except UnicodeDecodeError:
201 return data
202
203
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500204def _get_file_content(path, commit):
205 """Returns the content of a file at a specific commit.
206
207 We can't rely on the file as it exists in the filesystem as people might be
208 uploading a series of changes which modifies the file multiple times.
209
210 Note: The "content" of a symlink is just the target. So if you're expecting
211 a full file, you should check that first. One way to detect is that the
212 content will not have any newlines.
213 """
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700214 if commit == PRE_SUBMIT:
215 return _run_command(['git', 'diff', 'HEAD', path])
216 else:
217 return _run_command(['git', 'show', '%s:%s' % (commit, path)])
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500218
219
Mike Frysingerae409522014-02-01 03:16:11 -0500220def _get_file_diff(path, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700221 """Returns a list of (linenum, lines) tuples that the commit touched."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700222 command = ['git', 'diff', '-p', '--pretty=format:', '--no-ext-diff']
223 if commit == PRE_SUBMIT:
224 command += ['HEAD', path]
225 else:
226 command += [commit, path]
227 output = _run_command(command)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700228
229 new_lines = []
230 line_num = 0
231 for line in output.splitlines():
232 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
233 if m:
234 line_num = int(m.groups(1)[0])
235 continue
236 if line.startswith('+') and not line.startswith('++'):
Jon Salz98255932012-08-18 14:48:02 +0800237 new_lines.append((line_num, _try_utf8_decode(line[1:])))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700238 if not line.startswith('-'):
239 line_num += 1
240 return new_lines
241
Ryan Cui1562fb82011-05-09 11:01:31 -0700242
Mike Frysinger292b45d2014-11-25 01:17:10 -0500243def _get_affected_files(commit, include_deletes=False, relative=False,
244 include_symlinks=False, include_adds=True,
245 full_details=False):
Peter Ammon811f6702014-06-12 15:45:38 -0700246 """Returns list of file paths that were modified/added, excluding symlinks.
247
248 Args:
249 commit: The commit
250 include_deletes: If true, we'll include deleted files in the result
251 relative: Whether to return relative or full paths to files
Mike Frysinger292b45d2014-11-25 01:17:10 -0500252 include_symlinks: If true, we'll include symlinks in the result
253 include_adds: If true, we'll include new files in the result
254 full_details: If False, return filenames, else return structured results.
Peter Ammon811f6702014-06-12 15:45:38 -0700255
256 Returns:
257 A list of modified/added (and perhaps deleted) files
258 """
Mike Frysinger292b45d2014-11-25 01:17:10 -0500259 if not relative and full_details:
260 raise ValueError('full_details only supports relative paths currently')
261
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700262 if commit == PRE_SUBMIT:
263 return _run_command(['git', 'diff-index', '--cached',
264 '--name-only', 'HEAD']).split()
Mike Frysingerd3bd32c2014-11-24 23:34:29 -0500265
266 path = os.getcwd()
267 files = git.RawDiff(path, '%s^!' % commit)
268
269 # Filter out symlinks.
Mike Frysinger292b45d2014-11-25 01:17:10 -0500270 if not include_symlinks:
271 files = [x for x in files if not stat.S_ISLNK(int(x.dst_mode, 8))]
Mike Frysingerd3bd32c2014-11-24 23:34:29 -0500272
273 if not include_deletes:
274 files = [x for x in files if x.status != 'D']
275
Mike Frysinger292b45d2014-11-25 01:17:10 -0500276 if not include_adds:
277 files = [x for x in files if x.status != 'A']
278
279 if full_details:
280 # Caller wants the raw objects to parse status/etc... themselves.
Mike Frysingerd3bd32c2014-11-24 23:34:29 -0500281 return files
282 else:
Mike Frysinger292b45d2014-11-25 01:17:10 -0500283 # Caller only cares about filenames.
284 files = [x.dst_file if x.dst_file else x.src_file for x in files]
285 if relative:
286 return files
287 else:
288 return [os.path.join(path, x) for x in files]
Peter Ammon811f6702014-06-12 15:45:38 -0700289
290
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700291def _get_commits():
Ryan Cuiec4d6332011-05-02 14:15:25 -0700292 """Returns a list of commits for this review."""
Ryan Cui4725d952011-05-05 15:41:19 -0700293 cmd = ['git', 'log', '%s..' % _get_upstream_branch(), '--format=%H']
Ryan Cui72834d12011-05-05 14:51:33 -0700294 return _run_command(cmd).split()
Mandeep Singh Bainesb9ed1402011-04-29 15:32:06 -0700295
Ryan Cui1562fb82011-05-09 11:01:31 -0700296
Ryan Cuiec4d6332011-05-02 14:15:25 -0700297def _get_commit_desc(commit):
298 """Returns the full commit message of a commit."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700299 if commit == PRE_SUBMIT:
300 return ''
Sean Paul23a2c582011-05-06 13:10:44 -0400301 return _run_command(['git', 'log', '--format=%s%n%n%b', commit + '^!'])
Ryan Cuiec4d6332011-05-02 14:15:25 -0700302
303
304# Common Hooks
305
Ryan Cui1562fb82011-05-09 11:01:31 -0700306
Mike Frysingerae409522014-02-01 03:16:11 -0500307def _check_no_long_lines(_project, commit):
Mike Frysinger55f85b52014-12-18 14:45:21 -0500308 """Checks there are no lines longer than MAX_LEN in any of the text files."""
309
Ryan Cuiec4d6332011-05-02 14:15:25 -0700310 MAX_LEN = 80
Jon Salz98255932012-08-18 14:48:02 +0800311 SKIP_REGEXP = re.compile('|'.join([
312 r'https?://',
313 r'^#\s*(define|include|import|pragma|if|endif)\b']))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700314
315 errors = []
316 files = _filter_files(_get_affected_files(commit),
317 COMMON_INCLUDED_PATHS,
318 COMMON_EXCLUDED_PATHS)
319
320 for afile in files:
321 for line_num, line in _get_file_diff(afile, commit):
322 # Allow certain lines to exceed the maxlen rule.
Mike Frysingerae409522014-02-01 03:16:11 -0500323 if len(line) <= MAX_LEN or SKIP_REGEXP.search(line):
Jon Salz98255932012-08-18 14:48:02 +0800324 continue
325
326 errors.append('%s, line %s, %s chars' % (afile, line_num, len(line)))
327 if len(errors) == 5: # Just show the first 5 errors.
328 break
Ryan Cuiec4d6332011-05-02 14:15:25 -0700329
330 if errors:
331 msg = 'Found lines longer than %s characters (first 5 shown):' % MAX_LEN
Ryan Cui1562fb82011-05-09 11:01:31 -0700332 return HookFailure(msg, errors)
333
Ryan Cuiec4d6332011-05-02 14:15:25 -0700334
Mike Frysingerae409522014-02-01 03:16:11 -0500335def _check_no_stray_whitespace(_project, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700336 """Checks that there is no stray whitespace at source lines end."""
337 errors = []
338 files = _filter_files(_get_affected_files(commit),
Mike Frysingerae409522014-02-01 03:16:11 -0500339 COMMON_INCLUDED_PATHS,
340 COMMON_EXCLUDED_PATHS)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700341 for afile in files:
342 for line_num, line in _get_file_diff(afile, commit):
343 if line.rstrip() != line:
344 errors.append('%s, line %s' % (afile, line_num))
345 if errors:
Ryan Cui1562fb82011-05-09 11:01:31 -0700346 return HookFailure('Found line ending with white space in:', errors)
347
Ryan Cuiec4d6332011-05-02 14:15:25 -0700348
Mike Frysingerae409522014-02-01 03:16:11 -0500349def _check_no_tabs(_project, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700350 """Checks there are no unexpanded tabs."""
351 TAB_OK_PATHS = [
Ryan Cui31e0c172011-05-04 21:00:45 -0700352 r"/src/third_party/u-boot/",
Ryan Cuiec4d6332011-05-02 14:15:25 -0700353 r".*\.ebuild$",
354 r".*\.eclass$",
Elly Jones5ab34192011-11-15 14:57:06 -0500355 r".*/[M|m]akefile$",
356 r".*\.mk$"
Ryan Cuiec4d6332011-05-02 14:15:25 -0700357 ]
358
359 errors = []
360 files = _filter_files(_get_affected_files(commit),
361 COMMON_INCLUDED_PATHS,
362 COMMON_EXCLUDED_PATHS + TAB_OK_PATHS)
363
364 for afile in files:
365 for line_num, line in _get_file_diff(afile, commit):
366 if '\t' in line:
Mike Frysingerae409522014-02-01 03:16:11 -0500367 errors.append('%s, line %s' % (afile, line_num))
Ryan Cuiec4d6332011-05-02 14:15:25 -0700368 if errors:
Ryan Cui1562fb82011-05-09 11:01:31 -0700369 return HookFailure('Found a tab character in:', errors)
370
Ryan Cuiec4d6332011-05-02 14:15:25 -0700371
Mike Frysingerae409522014-02-01 03:16:11 -0500372def _check_change_has_test_field(_project, commit):
Ryan Cuiec4d6332011-05-02 14:15:25 -0700373 """Check for a non-empty 'TEST=' field in the commit message."""
David McMahon8f6553e2011-06-10 15:46:36 -0700374 TEST_RE = r'\nTEST=\S+'
Ryan Cuiec4d6332011-05-02 14:15:25 -0700375
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700376 if not re.search(TEST_RE, _get_commit_desc(commit)):
Ryan Cui1562fb82011-05-09 11:01:31 -0700377 msg = 'Changelist description needs TEST field (after first line)'
378 return HookFailure(msg)
379
Ryan Cuiec4d6332011-05-02 14:15:25 -0700380
Mike Frysingerae409522014-02-01 03:16:11 -0500381def _check_change_has_valid_cq_depend(_project, commit):
David Jamesc3b68b32013-04-03 09:17:03 -0700382 """Check for a correctly formatted CQ-DEPEND field in the commit message."""
383 msg = 'Changelist has invalid CQ-DEPEND target.'
384 example = 'Example: CQ-DEPEND=CL:1234, CL:2345'
385 try:
386 patch.GetPaladinDeps(_get_commit_desc(commit))
387 except ValueError as ex:
388 return HookFailure(msg, [example, str(ex)])
389
390
Mike Frysingerae409522014-02-01 03:16:11 -0500391def _check_change_has_bug_field(_project, commit):
David McMahon8f6553e2011-06-10 15:46:36 -0700392 """Check for a correctly formatted 'BUG=' field in the commit message."""
David James5c0073d2013-04-03 08:48:52 -0700393 OLD_BUG_RE = r'\nBUG=.*chromium-os'
394 if re.search(OLD_BUG_RE, _get_commit_desc(commit)):
395 msg = ('The chromium-os bug tracker is now deprecated. Please use\n'
396 'the chromium tracker in your BUG= line now.')
397 return HookFailure(msg)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700398
Christopher Wileyc92721b2015-01-26 13:07:39 -0800399 BUG_RE = r'\nBUG=([Nn]one|(chrome-os-partner|chromium|brillo):\d+)'
Mandeep Singh Baines96a53be2011-05-03 11:10:25 -0700400 if not re.search(BUG_RE, _get_commit_desc(commit)):
David McMahon8f6553e2011-06-10 15:46:36 -0700401 msg = ('Changelist description needs BUG field (after first line):\n'
Christopher Wileyc92721b2015-01-26 13:07:39 -0800402 'BUG=brillo:9999 (for Brillo tracker)\n'
David James5c0073d2013-04-03 08:48:52 -0700403 'BUG=chromium:9999 (for public tracker)\n'
David McMahon8f6553e2011-06-10 15:46:36 -0700404 'BUG=chrome-os-partner:9999 (for partner tracker)\n'
405 'BUG=None')
Ryan Cui1562fb82011-05-09 11:01:31 -0700406 return HookFailure(msg)
407
Ryan Cuiec4d6332011-05-02 14:15:25 -0700408
Mike Frysinger292b45d2014-11-25 01:17:10 -0500409def _check_for_uprev(project, commit, project_top=None):
Doug Anderson42b8a052013-06-26 10:45:36 -0700410 """Check that we're not missing a revbump of an ebuild in the given commit.
411
412 If the given commit touches files in a directory that has ebuilds somewhere
413 up the directory hierarchy, it's very likely that we need an ebuild revbump
414 in order for those changes to take effect.
415
416 It's not totally trivial to detect a revbump, so at least detect that an
417 ebuild with a revision number in it was touched. This should handle the
418 common case where we use a symlink to do the revbump.
419
420 TODO: it would be nice to enhance this hook to:
421 * Handle cases where people revbump with a slightly different syntax. I see
422 one ebuild (puppy) that revbumps with _pN. This is a false positive.
423 * Catches cases where people aren't using symlinks for revbumps. If they
424 edit a revisioned file directly (and are expected to rename it for revbump)
425 we'll miss that. Perhaps we could detect that the file touched is a
426 symlink?
427
428 If a project doesn't use symlinks we'll potentially miss a revbump, but we're
429 still better off than without this check.
430
431 Args:
432 project: The project to look at
433 commit: The commit to look at
Mike Frysinger292b45d2014-11-25 01:17:10 -0500434 project_top: Top dir to process commits in
Doug Anderson42b8a052013-06-26 10:45:36 -0700435
436 Returns:
437 A HookFailure or None.
438 """
Mike Frysinger011af942014-01-17 16:12:22 -0500439 # If this is the portage-stable overlay, then ignore the check. It's rare
440 # that we're doing anything other than importing files from upstream, so
441 # forcing a rev bump makes no sense.
442 whitelist = (
443 'chromiumos/overlays/portage-stable',
444 )
445 if project in whitelist:
446 return None
447
Mike Frysinger292b45d2014-11-25 01:17:10 -0500448 def FinalName(obj):
449 # If the file is being deleted, then the dst_file is not set.
450 if obj.dst_file is None:
451 return obj.src_file
452 else:
453 return obj.dst_file
454
455 affected_path_objs = _get_affected_files(
456 commit, include_deletes=True, include_symlinks=True, relative=True,
457 full_details=True)
Doug Anderson42b8a052013-06-26 10:45:36 -0700458
459 # Don't yell about changes to whitelisted files...
Mike Frysinger011af942014-01-17 16:12:22 -0500460 whitelist = ('ChangeLog', 'Manifest', 'metadata.xml')
Mike Frysinger292b45d2014-11-25 01:17:10 -0500461 affected_path_objs = [x for x in affected_path_objs
462 if os.path.basename(FinalName(x)) not in whitelist]
463 if not affected_path_objs:
Doug Anderson42b8a052013-06-26 10:45:36 -0700464 return None
465
466 # If we've touched any file named with a -rN.ebuild then we'll say we're
467 # OK right away. See TODO above about enhancing this.
Mike Frysinger292b45d2014-11-25 01:17:10 -0500468 touched_revved_ebuild = any(re.search(r'-r\d*\.ebuild$', FinalName(x))
469 for x in affected_path_objs)
Doug Anderson42b8a052013-06-26 10:45:36 -0700470 if touched_revved_ebuild:
471 return None
472
Mike Frysinger292b45d2014-11-25 01:17:10 -0500473 # If we're creating new ebuilds from scratch, then we don't need an uprev.
474 # Find all the dirs that new ebuilds and ignore their files/.
475 ebuild_dirs = [os.path.dirname(FinalName(x)) + '/' for x in affected_path_objs
476 if FinalName(x).endswith('.ebuild') and x.status == 'A']
477 affected_path_objs = [obj for obj in affected_path_objs
478 if not any(FinalName(obj).startswith(x)
479 for x in ebuild_dirs)]
480 if not affected_path_objs:
481 return
482
Doug Anderson42b8a052013-06-26 10:45:36 -0700483 # We want to examine the current contents of all directories that are parents
484 # of files that were touched (up to the top of the project).
485 #
486 # ...note: we use the current directory contents even though it may have
487 # changed since the commit we're looking at. This is just a heuristic after
488 # all. Worst case we don't flag a missing revbump.
Mike Frysinger292b45d2014-11-25 01:17:10 -0500489 if project_top is None:
490 project_top = os.getcwd()
Doug Anderson42b8a052013-06-26 10:45:36 -0700491 dirs_to_check = set([project_top])
Mike Frysinger292b45d2014-11-25 01:17:10 -0500492 for obj in affected_path_objs:
493 path = os.path.join(project_top, os.path.dirname(FinalName(obj)))
Doug Anderson42b8a052013-06-26 10:45:36 -0700494 while os.path.exists(path) and not os.path.samefile(path, project_top):
495 dirs_to_check.add(path)
496 path = os.path.dirname(path)
497
498 # Look through each directory. If it's got an ebuild in it then we'll
499 # consider this as a case when we need a revbump.
Gwendal Grignoua3086c32014-12-09 11:17:22 -0800500 affected_paths = set(os.path.join(project_top, FinalName(x))
501 for x in affected_path_objs)
Doug Anderson42b8a052013-06-26 10:45:36 -0700502 for dir_path in dirs_to_check:
503 contents = os.listdir(dir_path)
504 ebuilds = [os.path.join(dir_path, path)
505 for path in contents if path.endswith('.ebuild')]
506 ebuilds_9999 = [path for path in ebuilds if path.endswith('-9999.ebuild')]
507
508 # If the -9999.ebuild file was touched the bot will uprev for us.
509 # ...we'll use a simple intersection here as a heuristic...
Mike Frysinger292b45d2014-11-25 01:17:10 -0500510 if set(ebuilds_9999) & affected_paths:
Doug Anderson42b8a052013-06-26 10:45:36 -0700511 continue
512
513 if ebuilds:
Mike Frysinger292b45d2014-11-25 01:17:10 -0500514 return HookFailure('Changelist probably needs a revbump of an ebuild, '
515 'or a -r1.ebuild symlink if this is a new ebuild:\n'
516 '%s' % dir_path)
Doug Anderson42b8a052013-06-26 10:45:36 -0700517
518 return None
519
520
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500521def _check_ebuild_eapi(project, commit):
522 """Make sure we have people use EAPI=4 or newer with custom ebuilds.
523
524 We want to get away from older EAPI's as it makes life confusing and they
525 have less builtin error checking.
526
527 Args:
528 project: The project to look at
529 commit: The commit to look at
530
531 Returns:
532 A HookFailure or None.
533 """
534 # If this is the portage-stable overlay, then ignore the check. It's rare
Mike Frysingercd6adfc2014-02-06 01:03:56 -0500535 # that we're doing anything other than importing files from upstream, and
536 # we shouldn't be rewriting things fundamentally anyways.
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500537 whitelist = (
538 'chromiumos/overlays/portage-stable',
539 )
540 if project in whitelist:
541 return None
542
543 BAD_EAPIS = ('0', '1', '2', '3')
544
545 get_eapi = re.compile(r'^\s*EAPI=[\'"]?([^\'"]+)')
546
547 ebuilds_re = [r'\.ebuild$']
548 ebuilds = _filter_files(_get_affected_files(commit, relative=True),
549 ebuilds_re)
550 bad_ebuilds = []
551
552 for ebuild in ebuilds:
553 # If the ebuild does not specify an EAPI, it defaults to 0.
554 eapi = '0'
555
556 lines = _get_file_content(ebuild, commit).splitlines()
557 if len(lines) == 1:
558 # This is most likely a symlink, so skip it entirely.
559 continue
560
561 for line in lines:
562 m = get_eapi.match(line)
563 if m:
564 # Once we hit the first EAPI line in this ebuild, stop processing.
565 # The spec requires that there only be one and it be first, so
566 # checking all possible values is pointless. We also assume that
567 # it's "the" EAPI line and not something in the middle of a heredoc.
568 eapi = m.group(1)
569 break
570
571 if eapi in BAD_EAPIS:
572 bad_ebuilds.append((ebuild, eapi))
573
574 if bad_ebuilds:
575 # pylint: disable=C0301
576 url = 'http://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/upgrade-ebuild-eapis'
577 # pylint: enable=C0301
578 return HookFailure(
Mike Frysingercd6adfc2014-02-06 01:03:56 -0500579 'These ebuilds are using old EAPIs. If these are imported from\n'
580 'Gentoo, then you may ignore and upload once with the --no-verify\n'
581 'flag. Otherwise, please update to 4 or newer.\n'
Mike Frysingerbf8b91c2014-02-01 02:50:27 -0500582 '\t%s\n'
583 'See this guide for more details:\n%s\n' %
584 ('\n\t'.join(['%s: EAPI=%s' % x for x in bad_ebuilds]), url))
585
586
Mike Frysinger89bdb852014-02-01 05:26:26 -0500587def _check_ebuild_keywords(_project, commit):
Mike Frysingerc51ece72014-01-17 16:23:40 -0500588 """Make sure we use the new style KEYWORDS when possible in ebuilds.
589
590 If an ebuild generally does not care about the arch it is running on, then
591 ebuilds should flag it with one of:
592 KEYWORDS="*" # A stable ebuild.
593 KEYWORDS="~*" # An unstable ebuild.
594 KEYWORDS="-* ..." # Is known to only work on specific arches.
595
596 Args:
597 project: The project to look at
598 commit: The commit to look at
599
600 Returns:
601 A HookFailure or None.
602 """
603 WHITELIST = set(('*', '-*', '~*'))
604
605 get_keywords = re.compile(r'^\s*KEYWORDS="(.*)"')
606
Mike Frysinger89bdb852014-02-01 05:26:26 -0500607 ebuilds_re = [r'\.ebuild$']
608 ebuilds = _filter_files(_get_affected_files(commit, relative=True),
609 ebuilds_re)
610
Mike Frysinger8d42d742014-09-22 15:50:21 -0400611 bad_ebuilds = []
Mike Frysingerc51ece72014-01-17 16:23:40 -0500612 for ebuild in ebuilds:
Mike Frysinger5c9e58d2014-09-09 03:32:50 -0400613 # We get the full content rather than a diff as the latter does not work
614 # on new files (like when adding new ebuilds).
615 lines = _get_file_content(ebuild, commit).splitlines()
616 for line in lines:
Mike Frysingerc51ece72014-01-17 16:23:40 -0500617 m = get_keywords.match(line)
618 if m:
619 keywords = set(m.group(1).split())
620 if not keywords or WHITELIST - keywords != WHITELIST:
621 continue
622
Mike Frysinger8d42d742014-09-22 15:50:21 -0400623 bad_ebuilds.append(ebuild)
624
625 if bad_ebuilds:
626 return HookFailure(
627 '%s\n'
628 'Please update KEYWORDS to use a glob:\n'
629 'If the ebuild should be marked stable (normal for non-9999 ebuilds):\n'
630 ' KEYWORDS="*"\n'
631 'If the ebuild should be marked unstable (normal for '
632 'cros-workon / 9999 ebuilds):\n'
633 ' KEYWORDS="~*"\n'
634 'If the ebuild needs to be marked for only specific arches,'
635 'then use -* like so:\n'
636 ' KEYWORDS="-* arm ..."\n' % '\n* '.join(bad_ebuilds))
Mike Frysingerc51ece72014-01-17 16:23:40 -0500637
638
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800639def _check_ebuild_licenses(_project, commit):
640 """Check if the LICENSE field in the ebuild is correct."""
641 affected_paths = _get_affected_files(commit)
642 touched_ebuilds = [x for x in affected_paths if x.endswith('.ebuild')]
643
644 # A list of licenses to ignore for now.
Yu-Ju Hongc0963fa2014-03-03 12:36:52 -0800645 LICENSES_IGNORE = ['||', '(', ')']
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800646
647 for ebuild in touched_ebuilds:
648 # Skip virutal packages.
649 if ebuild.split('/')[-3] == 'virtual':
650 continue
651
652 try:
Mike Frysinger2ec70ed2014-08-17 19:28:34 -0400653 license_types = licenses_lib.GetLicenseTypesFromEbuild(ebuild)
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800654 except ValueError as e:
655 return HookFailure(e.message, [ebuild])
656
657 # Also ignore licenses ending with '?'
658 for license_type in [x for x in license_types
659 if x not in LICENSES_IGNORE and not x.endswith('?')]:
660 try:
Mike Frysinger2ec70ed2014-08-17 19:28:34 -0400661 licenses_lib.Licensing.FindLicenseType(license_type)
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -0800662 except AssertionError as e:
663 return HookFailure(e.message, [ebuild])
664
665
Mike Frysingercd363c82014-02-01 05:20:18 -0500666def _check_ebuild_virtual_pv(project, commit):
667 """Enforce the virtual PV policies."""
668 # If this is the portage-stable overlay, then ignore the check.
669 # We want to import virtuals as-is from upstream Gentoo.
670 whitelist = (
671 'chromiumos/overlays/portage-stable',
672 )
673 if project in whitelist:
674 return None
675
676 # We assume the repo name is the same as the dir name on disk.
677 # It would be dumb to not have them match though.
678 project = os.path.basename(project)
679
680 is_variant = lambda x: x.startswith('overlay-variant-')
681 is_board = lambda x: x.startswith('overlay-')
682 is_private = lambda x: x.endswith('-private')
683
684 get_pv = re.compile(r'(.*?)virtual/([^/]+)/\2-([^/]*)\.ebuild$')
685
686 ebuilds_re = [r'\.ebuild$']
687 ebuilds = _filter_files(_get_affected_files(commit, relative=True),
688 ebuilds_re)
689 bad_ebuilds = []
690
691 for ebuild in ebuilds:
692 m = get_pv.match(ebuild)
693 if m:
694 overlay = m.group(1)
695 if not overlay or not is_board(overlay):
696 overlay = project
697
698 pv = m.group(3).split('-', 1)[0]
699
700 if is_private(overlay):
701 want_pv = '3.5' if is_variant(overlay) else '3'
702 elif is_board(overlay):
703 want_pv = '2.5' if is_variant(overlay) else '2'
704 else:
705 want_pv = '1'
706
707 if pv != want_pv:
708 bad_ebuilds.append((ebuild, pv, want_pv))
709
710 if bad_ebuilds:
711 # pylint: disable=C0301
712 url = 'http://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/portage-build-faq#TOC-Virtuals-and-central-management'
713 # pylint: enable=C0301
714 return HookFailure(
715 'These virtuals have incorrect package versions (PVs). Please adjust:\n'
716 '\t%s\n'
717 'If this is an upstream Gentoo virtual, then you may ignore this\n'
718 'check (and re-run w/--no-verify). Otherwise, please see this\n'
719 'page for more details:\n%s\n' %
720 ('\n\t'.join(['%s:\n\t\tPV is %s but should be %s' % x
721 for x in bad_ebuilds]), url))
722
723
Mike Frysingerae409522014-02-01 03:16:11 -0500724def _check_change_has_proper_changeid(_project, commit):
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700725 """Verify that Change-ID is present in last paragraph of commit message."""
Mike Frysinger4a22bf02014-10-31 13:53:35 -0400726 CHANGE_ID_RE = r'\nChange-Id: I[a-f0-9]+\n'
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700727 desc = _get_commit_desc(commit)
Mike Frysinger4a22bf02014-10-31 13:53:35 -0400728 m = re.search(CHANGE_ID_RE, desc)
Mike Frysinger02b88bd2014-11-21 00:29:38 -0500729 if not m:
Ryan Cui1562fb82011-05-09 11:01:31 -0700730 return HookFailure('Change-Id must be in last paragraph of description.')
731
Mike Frysinger02b88bd2014-11-21 00:29:38 -0500732 # Allow s-o-b tags to follow it, but only those.
733 end = desc[m.end():].strip().splitlines()
734 if [x for x in end if not x.startswith('Signed-off-by: ')]:
735 return HookFailure('Only "Signed-off-by:" tags may follow the Change-Id.')
736
Mandeep Singh Bainesa23eb5f2011-05-04 13:43:25 -0700737
Mike Frysinger36b2ebc2014-10-31 14:02:03 -0400738def _check_commit_message_style(_project, commit):
739 """Verify that the commit message matches our style.
740
741 We do not check for BUG=/TEST=/etc... lines here as that is handled by other
742 commit hooks.
743 """
744 desc = _get_commit_desc(commit)
745
746 # The first line should be by itself.
747 lines = desc.splitlines()
748 if len(lines) > 1 and lines[1]:
749 return HookFailure('The second line of the commit message must be blank.')
750
751 # The first line should be one sentence.
752 if '. ' in lines[0]:
753 return HookFailure('The first line cannot be more than one sentence.')
754
755 # The first line cannot be too long.
756 MAX_FIRST_LINE_LEN = 100
757 if len(lines[0]) > MAX_FIRST_LINE_LEN:
758 return HookFailure('The first line must be less than %i chars.' %
759 MAX_FIRST_LINE_LEN)
760
761
Mike Frysingerae409522014-02-01 03:16:11 -0500762def _check_license(_project, commit):
Mike Frysinger98638102014-08-28 00:15:08 -0400763 """Verifies the license/copyright header.
Ryan Cuiec4d6332011-05-02 14:15:25 -0700764
Mike Frysinger98638102014-08-28 00:15:08 -0400765 Should be following the spec:
766 http://dev.chromium.org/developers/coding-style#TOC-File-headers
767 """
768 # For older years, be a bit more flexible as our policy says leave them be.
769 LICENSE_HEADER = (
770 r'.* Copyright( \(c\))? 20[-0-9]{2,7} The Chromium OS Authors\. '
Mike Frysingerb81102f2014-11-21 00:33:35 -0500771 r'All rights reserved\.' r'\n'
Mike Frysinger98638102014-08-28 00:15:08 -0400772 r'.* Use of this source code is governed by a BSD-style license that can '
Mike Frysingerb81102f2014-11-21 00:33:35 -0500773 r'be\n'
Mike Frysinger98638102014-08-28 00:15:08 -0400774 r'.* found in the LICENSE file\.'
Mike Frysingerb81102f2014-11-21 00:33:35 -0500775 r'\n'
Mike Frysinger98638102014-08-28 00:15:08 -0400776 )
777 license_re = re.compile(LICENSE_HEADER, re.MULTILINE)
778
779 # For newer years, be stricter.
780 COPYRIGHT_LINE = (
781 r'.* Copyright \(c\) 20(1[5-9]|[2-9][0-9]) The Chromium OS Authors\. '
Mike Frysingerb81102f2014-11-21 00:33:35 -0500782 r'All rights reserved\.' r'\n'
Mike Frysinger98638102014-08-28 00:15:08 -0400783 )
784 copyright_re = re.compile(COPYRIGHT_LINE)
785
786 bad_files = []
787 bad_copyright_files = []
788 files = _filter_files(_get_affected_files(commit, relative=True),
789 COMMON_INCLUDED_PATHS,
790 COMMON_EXCLUDED_PATHS)
791
792 for f in files:
793 contents = _get_file_content(f, commit)
794 if not contents:
795 # Ignore empty files.
796 continue
797
798 if not license_re.search(contents):
799 bad_files.append(f)
800 elif copyright_re.search(contents):
801 bad_copyright_files.append(f)
802
803 if bad_files:
804 msg = '%s:\n%s\n%s' % (
805 'License must match', license_re.pattern,
806 'Found a bad header in these files:')
807 return HookFailure(msg, bad_files)
808
809 if bad_copyright_files:
810 msg = 'Do not use (c) in copyright headers in new files:'
811 return HookFailure(msg, bad_copyright_files)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700812
813
Mike Frysinger998c2cc2014-08-27 05:20:23 -0400814def _check_layout_conf(_project, commit):
815 """Verifies the metadata/layout.conf file."""
816 repo_name = 'profiles/repo_name'
Mike Frysinger94a670c2014-09-19 12:46:26 -0400817 repo_names = []
Mike Frysinger998c2cc2014-08-27 05:20:23 -0400818 layout_path = 'metadata/layout.conf'
Mike Frysinger94a670c2014-09-19 12:46:26 -0400819 layout_paths = []
Mike Frysinger998c2cc2014-08-27 05:20:23 -0400820
Mike Frysinger94a670c2014-09-19 12:46:26 -0400821 # Handle multiple overlays in a single commit (like the public tree).
822 for f in _get_affected_files(commit, relative=True):
823 if f.endswith(repo_name):
824 repo_names.append(f)
825 elif f.endswith(layout_path):
826 layout_paths.append(f)
Mike Frysinger998c2cc2014-08-27 05:20:23 -0400827
828 # Disallow new repos with the repo_name file.
Mike Frysinger94a670c2014-09-19 12:46:26 -0400829 if repo_names:
Mike Frysinger998c2cc2014-08-27 05:20:23 -0400830 return HookFailure('%s: use "repo-name" in %s instead' %
Mike Frysinger94a670c2014-09-19 12:46:26 -0400831 (repo_names, layout_path))
Mike Frysinger998c2cc2014-08-27 05:20:23 -0400832
Mike Frysinger94a670c2014-09-19 12:46:26 -0400833 # Gather all the errors in one pass so we show one full message.
834 all_errors = {}
835 for layout_path in layout_paths:
836 all_errors[layout_path] = errors = []
Mike Frysinger998c2cc2014-08-27 05:20:23 -0400837
Mike Frysinger94a670c2014-09-19 12:46:26 -0400838 # Make sure the config file is sorted.
839 data = [x for x in _get_file_content(layout_path, commit).splitlines()
840 if x and x[0] != '#']
841 if sorted(data) != data:
842 errors += ['keep lines sorted']
Mike Frysinger998c2cc2014-08-27 05:20:23 -0400843
Mike Frysinger94a670c2014-09-19 12:46:26 -0400844 # Require people to set specific values all the time.
845 settings = (
846 # TODO: Enable this for everyone. http://crbug.com/408038
847 #('fast caching', 'cache-format = md5-dict'),
848 ('fast manifests', 'thin-manifests = true'),
849 ('extra features', 'profile-formats = portage-2'),
850 )
851 for reason, line in settings:
852 if line not in data:
853 errors += ['enable %s with: %s' % (reason, line)]
Mike Frysinger998c2cc2014-08-27 05:20:23 -0400854
Mike Frysinger94a670c2014-09-19 12:46:26 -0400855 # Require one of these settings.
856 if ('use-manifests = true' not in data and
857 'use-manifests = strict' not in data):
858 errors += ['enable file checking with: use-manifests = true']
Mike Frysinger998c2cc2014-08-27 05:20:23 -0400859
Mike Frysinger94a670c2014-09-19 12:46:26 -0400860 # Require repo-name to be set.
Mike Frysinger324cf682014-09-22 15:52:50 -0400861 for line in data:
862 if line.startswith('repo-name = '):
863 break
864 else:
Mike Frysinger94a670c2014-09-19 12:46:26 -0400865 errors += ['set the board name with: repo-name = $BOARD']
Mike Frysinger998c2cc2014-08-27 05:20:23 -0400866
Mike Frysinger94a670c2014-09-19 12:46:26 -0400867 # Summarize all the errors we saw (if any).
868 lines = ''
869 for layout_path, errors in all_errors.items():
870 if errors:
871 lines += '\n\t- '.join(['\n* %s:' % layout_path] + errors)
872 if lines:
873 lines = 'See the portage(5) man page for layout.conf details' + lines + '\n'
874 return HookFailure(lines)
Mike Frysinger998c2cc2014-08-27 05:20:23 -0400875
876
Ryan Cuiec4d6332011-05-02 14:15:25 -0700877# Project-specific hooks
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700878
Ryan Cui1562fb82011-05-09 11:01:31 -0700879
Mike Frysingerae409522014-02-01 03:16:11 -0500880def _run_checkpatch(_project, commit, options=()):
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700881 """Runs checkpatch.pl on the given project"""
882 hooks_dir = _get_hooks_dir()
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700883 options = list(options)
884 if commit == PRE_SUBMIT:
885 # The --ignore option must be present and include 'MISSING_SIGN_OFF' in
886 # this case.
887 options.append('--ignore=MISSING_SIGN_OFF')
888 cmd = ['%s/checkpatch.pl' % hooks_dir] + options + ['-']
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700889 p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Che-Liang Chiou5ce2d7b2013-03-22 18:47:55 -0700890 output = p.communicate(_get_patch(commit))[0]
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700891 if p.returncode:
Ryan Cui1562fb82011-05-09 11:01:31 -0700892 return HookFailure('checkpatch.pl errors/warnings\n\n' + output)
Ryan Cuiec4d6332011-05-02 14:15:25 -0700893
Mandeep Singh Baines116ad102011-04-27 15:16:37 -0700894
Anton Staaf815d6852011-08-22 10:08:45 -0700895def _run_checkpatch_no_tree(project, commit):
896 return _run_checkpatch(project, commit, ['--no-tree'])
897
Mike Frysingerae409522014-02-01 03:16:11 -0500898
Randall Spangler7318fd62013-11-21 12:16:58 -0800899def _run_checkpatch_ec(project, commit):
900 """Runs checkpatch with options for Chromium EC projects."""
901 return _run_checkpatch(project, commit, ['--no-tree',
902 '--ignore=MSLEEP,VOLATILE'])
903
Mike Frysingerae409522014-02-01 03:16:11 -0500904
Vadim Bendeburyf8536032014-06-22 12:42:18 -0700905def _run_checkpatch_depthcharge(project, commit):
906 """Runs checkpatch with options for depthcharge."""
907 return _run_checkpatch(project, commit, [
908 '--no-tree',
Julius Werner83a35bb2014-06-23 12:51:48 -0700909 '--ignore=CAMELCASE,C99_COMMENTS,NEW_TYPEDEFS,CONFIG_DESCRIPTION,'
910 'SPACING,PREFER_PACKED,PREFER_PRINTF,PREFER_ALIGNED,GLOBAL_INITIALISERS,'
911 'INITIALISED_STATIC,OPEN_BRACE,TRAILING_STATEMENTS'])
Vadim Bendeburyf8536032014-06-22 12:42:18 -0700912
Vadim Bendebury4bcd9fa2014-08-07 12:27:37 -0700913def _run_checkpatch_coreboot(project, commit):
914 """Runs checkpatch with options for coreboot."""
915 return _run_checkpatch(project, commit, [
Vadim Bendeburyac4bc6c2014-08-29 19:56:43 -0700916 '--min-conf-desc-length=2',
Vadim Bendebury4bcd9fa2014-08-07 12:27:37 -0700917 '--no-tree',
918 '--ignore=NEW_TYPEDEFS,PREFER_PACKED,PREFER_PRINTF,PREFER_ALIGNED,'
Shawn Nematbakhsh6442c582014-08-22 14:32:06 -0700919 'GLOBAL_INITIALISERS,INITIALISED_STATIC,C99_COMMENTS'])
Vadim Bendebury4bcd9fa2014-08-07 12:27:37 -0700920
Vadim Bendeburyf8536032014-06-22 12:42:18 -0700921
Mike Frysingerae409522014-02-01 03:16:11 -0500922def _kernel_configcheck(_project, commit):
Olof Johanssona96810f2012-09-04 16:20:03 -0700923 """Makes sure kernel config changes are not mixed with code changes"""
924 files = _get_affected_files(commit)
925 if not len(_filter_files(files, [r'chromeos/config'])) in [0, len(files)]:
926 return HookFailure('Changes to chromeos/config/ and regular files must '
927 'be in separate commits:\n%s' % '\n'.join(files))
Anton Staaf815d6852011-08-22 10:08:45 -0700928
Mike Frysingerae409522014-02-01 03:16:11 -0500929
930def _run_json_check(_project, commit):
Dale Curtis2975c432011-05-03 17:25:20 -0700931 """Checks that all JSON files are syntactically valid."""
Dale Curtisa039cfd2011-05-04 12:01:05 -0700932 for f in _filter_files(_get_affected_files(commit), [r'.*\.json']):
Dale Curtis2975c432011-05-03 17:25:20 -0700933 try:
934 json.load(open(f))
935 except Exception, e:
Ryan Cui1562fb82011-05-09 11:01:31 -0700936 return HookFailure('Invalid JSON in %s: %s' % (f, e))
Dale Curtis2975c432011-05-03 17:25:20 -0700937
938
Mike Frysingerae409522014-02-01 03:16:11 -0500939def _check_manifests(_project, commit):
Mike Frysinger52b537e2013-08-22 22:59:53 -0400940 """Make sure Manifest files only have DIST lines"""
941 paths = []
942
943 for path in _get_affected_files(commit):
944 if os.path.basename(path) != 'Manifest':
945 continue
946 if not os.path.exists(path):
947 continue
948
949 with open(path, 'r') as f:
950 for line in f.readlines():
951 if not line.startswith('DIST '):
952 paths.append(path)
953 break
954
955 if paths:
956 return HookFailure('Please remove lines that do not start with DIST:\n%s' %
957 ('\n'.join(paths),))
958
959
Mike Frysingerae409522014-02-01 03:16:11 -0500960def _check_change_has_branch_field(_project, commit):
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700961 """Check for a non-empty 'BRANCH=' field in the commit message."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700962 if commit == PRE_SUBMIT:
963 return
Puneet Kumarc80e3f62012-08-13 19:01:18 -0700964 BRANCH_RE = r'\nBRANCH=\S+'
965
966 if not re.search(BRANCH_RE, _get_commit_desc(commit)):
967 msg = ('Changelist description needs BRANCH field (after first line)\n'
968 'E.g. BRANCH=none or BRANCH=link,snow')
969 return HookFailure(msg)
970
971
Mike Frysingerae409522014-02-01 03:16:11 -0500972def _check_change_has_signoff_field(_project, commit):
Shawn Nematbakhsh51e16ac2014-01-28 15:31:07 -0800973 """Check for a non-empty 'Signed-off-by:' field in the commit message."""
Vadim Bendebury2b62d742014-06-22 13:14:51 -0700974 if commit == PRE_SUBMIT:
975 return
Shawn Nematbakhsh51e16ac2014-01-28 15:31:07 -0800976 SIGNOFF_RE = r'\nSigned-off-by: \S+'
977
978 if not re.search(SIGNOFF_RE, _get_commit_desc(commit)):
979 msg = ('Changelist description needs Signed-off-by: field\n'
980 'E.g. Signed-off-by: My Name <me@chromium.org>')
981 return HookFailure(msg)
982
983
Jon Salz3ee59de2012-08-18 13:54:22 +0800984def _run_project_hook_script(script, project, commit):
985 """Runs a project hook script.
986
987 The script is run with the following environment variables set:
988 PRESUBMIT_PROJECT: The affected project
989 PRESUBMIT_COMMIT: The affected commit
990 PRESUBMIT_FILES: A newline-separated list of affected files
991
992 The script is considered to fail if the exit code is non-zero. It should
993 write an error message to stdout.
994 """
995 env = dict(os.environ)
996 env['PRESUBMIT_PROJECT'] = project
997 env['PRESUBMIT_COMMIT'] = commit
998
999 # Put affected files in an environment variable
1000 files = _get_affected_files(commit)
1001 env['PRESUBMIT_FILES'] = '\n'.join(files)
1002
1003 process = subprocess.Popen(script, env=env, shell=True,
1004 stdin=open(os.devnull),
Jon Salz7b618af2012-08-31 06:03:16 +08001005 stdout=subprocess.PIPE,
1006 stderr=subprocess.STDOUT)
Jon Salz3ee59de2012-08-18 13:54:22 +08001007 stdout, _ = process.communicate()
1008 if process.wait():
Jon Salz7b618af2012-08-31 06:03:16 +08001009 if stdout:
1010 stdout = re.sub('(?m)^', ' ', stdout)
1011 return HookFailure('Hook script "%s" failed with code %d%s' %
Jon Salz3ee59de2012-08-18 13:54:22 +08001012 (script, process.returncode,
1013 ':\n' + stdout if stdout else ''))
1014
1015
Bertrand SIMONNET6ec83f92014-05-30 10:42:34 -07001016def _moved_to_platform2(project, _commit):
1017 """Forbids commits to legacy repo in src/platform."""
1018 return HookFailure('%s has been moved to platform2. This change should be '
1019 'made there.' % project)
1020
1021
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001022def _check_project_prefix(_project, commit):
Mike Frysinger55f85b52014-12-18 14:45:21 -05001023 """Require the commit message have a project specific prefix as needed."""
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001024
1025 files = _get_affected_files(commit, relative=True)
1026 prefix = os.path.commonprefix(files)
1027 prefix = os.path.dirname(prefix)
1028
1029 # If there is no common prefix, the CL span multiple projects.
Daniel Erata350fd32014-09-29 14:02:34 -07001030 if not prefix:
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001031 return
1032
1033 project_name = prefix.split('/')[0]
Daniel Erata350fd32014-09-29 14:02:34 -07001034
1035 # The common files may all be within a subdirectory of the main project
1036 # directory, so walk up the tree until we find an alias file.
1037 # _get_affected_files() should return relative paths, but check against '/' to
1038 # ensure that this loop terminates even if it receives an absolute path.
1039 while prefix and prefix != '/':
1040 alias_file = os.path.join(prefix, '.project_alias')
1041
1042 # If an alias exists, use it.
1043 if os.path.isfile(alias_file):
1044 project_name = osutils.ReadFile(alias_file).strip()
1045
1046 prefix = os.path.dirname(prefix)
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001047
1048 if not _get_commit_desc(commit).startswith(project_name + ': '):
1049 return HookFailure('The commit title for changes affecting only %s'
1050 ' should start with \"%s: \"'
1051 % (project_name, project_name))
1052
1053
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001054# Base
1055
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001056# A list of hooks which are not project specific and check patch description
1057# (as opposed to patch body).
1058_PATCH_DESCRIPTION_HOOKS = [
Ryan Cui9b651632011-05-11 11:38:58 -07001059 _check_change_has_bug_field,
David Jamesc3b68b32013-04-03 09:17:03 -07001060 _check_change_has_valid_cq_depend,
Ryan Cui9b651632011-05-11 11:38:58 -07001061 _check_change_has_test_field,
1062 _check_change_has_proper_changeid,
Mike Frysinger36b2ebc2014-10-31 14:02:03 -04001063 _check_commit_message_style,
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001064]
1065
1066
1067# A list of hooks that are not project-specific
1068_COMMON_HOOKS = [
Mike Frysingerbf8b91c2014-02-01 02:50:27 -05001069 _check_ebuild_eapi,
Mike Frysinger89bdb852014-02-01 05:26:26 -05001070 _check_ebuild_keywords,
Yu-Ju Hong5e0efa72013-11-19 16:28:10 -08001071 _check_ebuild_licenses,
Mike Frysingercd363c82014-02-01 05:20:18 -05001072 _check_ebuild_virtual_pv,
Ryan Cui9b651632011-05-11 11:38:58 -07001073 _check_no_stray_whitespace,
1074 _check_no_long_lines,
Mike Frysinger998c2cc2014-08-27 05:20:23 -04001075 _check_layout_conf,
Ryan Cui9b651632011-05-11 11:38:58 -07001076 _check_license,
1077 _check_no_tabs,
Doug Anderson42b8a052013-06-26 10:45:36 -07001078 _check_for_uprev,
Ryan Cui9b651632011-05-11 11:38:58 -07001079]
Ryan Cuiec4d6332011-05-02 14:15:25 -07001080
Ryan Cui1562fb82011-05-09 11:01:31 -07001081
Ryan Cui9b651632011-05-11 11:38:58 -07001082# A dictionary of project-specific hooks(callbacks), indexed by project name.
1083# dict[project] = [callback1, callback2]
1084_PROJECT_SPECIFIC_HOOKS = {
Mike Frysingerdf980702013-08-22 22:25:22 -04001085 "chromeos/autotest-tools": [_run_json_check],
Mike Frysinger52b537e2013-08-22 22:59:53 -04001086 "chromeos/overlays/chromeos-overlay": [_check_manifests],
1087 "chromeos/overlays/chromeos-partner-overlay": [_check_manifests],
Randall Spangler7318fd62013-11-21 12:16:58 -08001088 "chromeos/platform/ec-private": [_run_checkpatch_ec,
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001089 _check_change_has_branch_field],
Puneet Kumar57b9c092012-08-14 18:58:29 -07001090 "chromeos/third_party/intel-framework": [_check_change_has_branch_field],
Mike Frysingerdf980702013-08-22 22:25:22 -04001091 "chromeos/vendor/kernel-exynos-staging": [_run_checkpatch,
1092 _kernel_configcheck],
Mike Frysinger52b537e2013-08-22 22:59:53 -04001093 "chromiumos/overlays/board-overlays": [_check_manifests],
1094 "chromiumos/overlays/chromiumos-overlay": [_check_manifests],
1095 "chromiumos/overlays/portage-stable": [_check_manifests],
Bertrand SIMONNET0022fff2014-07-07 09:52:15 -07001096 "chromiumos/platform2": [_check_project_prefix],
Vadim Bendebury42052852014-10-06 16:02:38 -07001097 "chromiumos/platform/depthcharge": [_check_change_has_branch_field,
1098 _check_change_has_signoff_field,
Vadim Bendebury4bcd9fa2014-08-07 12:27:37 -07001099 _run_checkpatch_depthcharge],
Randall Spangler7318fd62013-11-21 12:16:58 -08001100 "chromiumos/platform/ec": [_run_checkpatch_ec,
Mike Frysingerdf980702013-08-22 22:25:22 -04001101 _check_change_has_branch_field],
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001102 "chromiumos/platform/mosys": [_check_change_has_branch_field],
Mike Frysingerdf980702013-08-22 22:25:22 -04001103 "chromiumos/platform/vboot_reference": [_check_change_has_branch_field],
Vadim Bendebury42052852014-10-06 16:02:38 -07001104 "chromiumos/third_party/coreboot": [_check_change_has_branch_field,
1105 _check_change_has_signoff_field,
Vadim Bendebury4bcd9fa2014-08-07 12:27:37 -07001106 _run_checkpatch_coreboot],
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001107 "chromiumos/third_party/flashrom": [_check_change_has_branch_field],
Mike Frysingerdf980702013-08-22 22:25:22 -04001108 "chromiumos/third_party/kernel": [_run_checkpatch, _kernel_configcheck],
1109 "chromiumos/third_party/kernel-next": [_run_checkpatch,
1110 _kernel_configcheck],
Vadim Bendebury203fbc22014-04-22 11:58:14 -07001111 "chromiumos/third_party/u-boot": [_run_checkpatch_no_tree],
Ryan Cui9b651632011-05-11 11:38:58 -07001112}
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001113
Ryan Cui1562fb82011-05-09 11:01:31 -07001114
Ryan Cui9b651632011-05-11 11:38:58 -07001115# A dictionary of flags (keys) that can appear in the config file, and the hook
1116# that the flag disables (value)
1117_DISABLE_FLAGS = {
1118 'stray_whitespace_check': _check_no_stray_whitespace,
1119 'long_line_check': _check_no_long_lines,
1120 'cros_license_check': _check_license,
1121 'tab_check': _check_no_tabs,
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001122 'branch_check': _check_change_has_branch_field,
Shawn Nematbakhsh51e16ac2014-01-28 15:31:07 -08001123 'signoff_check': _check_change_has_signoff_field,
Josh Triplett0e8fc7f2014-04-23 16:00:00 -07001124 'bug_field_check': _check_change_has_bug_field,
1125 'test_field_check': _check_change_has_test_field,
Ryan Cui9b651632011-05-11 11:38:58 -07001126}
1127
1128
Jon Salz3ee59de2012-08-18 13:54:22 +08001129def _get_disabled_hooks(config):
Ryan Cui9b651632011-05-11 11:38:58 -07001130 """Returns a set of hooks disabled by the current project's config file.
1131
1132 Expects to be called within the project root.
Jon Salz3ee59de2012-08-18 13:54:22 +08001133
1134 Args:
1135 config: A ConfigParser for the project's config file.
Ryan Cui9b651632011-05-11 11:38:58 -07001136 """
1137 SECTION = 'Hook Overrides'
Jon Salz3ee59de2012-08-18 13:54:22 +08001138 if not config.has_section(SECTION):
1139 return set()
Ryan Cui9b651632011-05-11 11:38:58 -07001140
1141 disable_flags = []
Jon Salz3ee59de2012-08-18 13:54:22 +08001142 for flag in config.options(SECTION):
Ryan Cui9b651632011-05-11 11:38:58 -07001143 try:
Mike Frysingerae409522014-02-01 03:16:11 -05001144 if not config.getboolean(SECTION, flag):
1145 disable_flags.append(flag)
Ryan Cui9b651632011-05-11 11:38:58 -07001146 except ValueError as e:
1147 msg = "Error parsing flag \'%s\' in %s file - " % (flag, _CONFIG_FILE)
Mike Frysinger09d6a3d2013-10-08 22:21:03 -04001148 print(msg + str(e))
Ryan Cui9b651632011-05-11 11:38:58 -07001149
1150 disabled_keys = set(_DISABLE_FLAGS.iterkeys()).intersection(disable_flags)
1151 return set([_DISABLE_FLAGS[key] for key in disabled_keys])
1152
1153
Jon Salz3ee59de2012-08-18 13:54:22 +08001154def _get_project_hook_scripts(config):
1155 """Returns a list of project-specific hook scripts.
1156
1157 Args:
1158 config: A ConfigParser for the project's config file.
1159 """
1160 SECTION = 'Hook Scripts'
1161 if not config.has_section(SECTION):
1162 return []
1163
1164 hook_names_values = config.items(SECTION)
1165 hook_names_values.sort(key=lambda x: x[0])
1166 return [x[1] for x in hook_names_values]
1167
1168
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001169def _get_project_hooks(project, presubmit):
Ryan Cui9b651632011-05-11 11:38:58 -07001170 """Returns a list of hooks that need to be run for a project.
1171
1172 Expects to be called from within the project root.
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001173
1174 Args:
1175 project: A string, name of the project.
1176 presubmit: A Boolean, True if the check is run as a git pre-submit script.
Ryan Cui9b651632011-05-11 11:38:58 -07001177 """
Jon Salz3ee59de2012-08-18 13:54:22 +08001178 config = ConfigParser.RawConfigParser()
1179 try:
1180 config.read(_CONFIG_FILE)
1181 except ConfigParser.Error:
1182 # Just use an empty config file
1183 config = ConfigParser.RawConfigParser()
1184
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001185 if presubmit:
1186 hook_list = _COMMON_HOOKS
1187 else:
1188 hook_list = _PATCH_DESCRIPTION_HOOKS + _COMMON_HOOKS
1189
Jon Salz3ee59de2012-08-18 13:54:22 +08001190 disabled_hooks = _get_disabled_hooks(config)
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001191 hooks = [hook for hook in hook_list if hook not in disabled_hooks]
Ryan Cui9b651632011-05-11 11:38:58 -07001192
1193 if project in _PROJECT_SPECIFIC_HOOKS:
Puneet Kumarc80e3f62012-08-13 19:01:18 -07001194 hooks.extend(hook for hook in _PROJECT_SPECIFIC_HOOKS[project]
1195 if hook not in disabled_hooks)
Ryan Cui9b651632011-05-11 11:38:58 -07001196
Jon Salz3ee59de2012-08-18 13:54:22 +08001197 for script in _get_project_hook_scripts(config):
1198 hooks.append(functools.partial(_run_project_hook_script, script))
1199
Ryan Cui9b651632011-05-11 11:38:58 -07001200 return hooks
1201
1202
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001203def _run_project_hooks(project, proj_dir=None,
1204 commit_list=None, presubmit=False):
Ryan Cui1562fb82011-05-09 11:01:31 -07001205 """For each project run its project specific hook from the hooks dictionary.
1206
1207 Args:
Doug Anderson44a644f2011-11-02 10:37:37 -07001208 project: The name of project to run hooks for.
1209 proj_dir: If non-None, this is the directory the project is in. If None,
1210 we'll ask repo.
Doug Anderson14749562013-06-26 13:38:29 -07001211 commit_list: A list of commits to run hooks against. If None or empty list
1212 then we'll automatically get the list of commits that would be uploaded.
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001213 presubmit: A Boolean, True if the check is run as a git pre-submit script.
Ryan Cui1562fb82011-05-09 11:01:31 -07001214
1215 Returns:
1216 Boolean value of whether any errors were ecountered while running the hooks.
1217 """
Doug Anderson44a644f2011-11-02 10:37:37 -07001218 if proj_dir is None:
David James2edd9002013-10-11 14:09:19 -07001219 proj_dirs = _run_command(['repo', 'forall', project, '-c', 'pwd']).split()
1220 if len(proj_dirs) == 0:
1221 print('%s cannot be found.' % project, file=sys.stderr)
1222 print('Please specify a valid project.', file=sys.stderr)
1223 return True
1224 if len(proj_dirs) > 1:
1225 print('%s is associated with multiple directories.' % project,
1226 file=sys.stderr)
1227 print('Please specify a directory to help disambiguate.', file=sys.stderr)
1228 return True
1229 proj_dir = proj_dirs[0]
Doug Anderson44a644f2011-11-02 10:37:37 -07001230
Ryan Cuiec4d6332011-05-02 14:15:25 -07001231 pwd = os.getcwd()
1232 # hooks assume they are run from the root of the project
1233 os.chdir(proj_dir)
1234
Doug Anderson14749562013-06-26 13:38:29 -07001235 if not commit_list:
1236 try:
1237 commit_list = _get_commits()
1238 except VerifyException as e:
1239 PrintErrorForProject(project, HookFailure(str(e)))
1240 os.chdir(pwd)
1241 return True
Ryan Cuifa55df52011-05-06 11:16:55 -07001242
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001243 hooks = _get_project_hooks(project, presubmit)
Ryan Cui1562fb82011-05-09 11:01:31 -07001244 error_found = False
Ryan Cuifa55df52011-05-06 11:16:55 -07001245 for commit in commit_list:
Ryan Cui1562fb82011-05-09 11:01:31 -07001246 error_list = []
Ryan Cui9b651632011-05-11 11:38:58 -07001247 for hook in hooks:
Ryan Cui1562fb82011-05-09 11:01:31 -07001248 hook_error = hook(project, commit)
1249 if hook_error:
1250 error_list.append(hook_error)
1251 error_found = True
1252 if error_list:
1253 PrintErrorsForCommit(project, commit, _get_commit_desc(commit),
1254 error_list)
Don Garrettdba548a2011-05-05 15:17:14 -07001255
Ryan Cuiec4d6332011-05-02 14:15:25 -07001256 os.chdir(pwd)
Ryan Cui1562fb82011-05-09 11:01:31 -07001257 return error_found
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001258
Mike Frysingerae409522014-02-01 03:16:11 -05001259
Mandeep Singh Baines116ad102011-04-27 15:16:37 -07001260# Main
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -07001261
Ryan Cui1562fb82011-05-09 11:01:31 -07001262
Mike Frysingerae409522014-02-01 03:16:11 -05001263def main(project_list, worktree_list=None, **_kwargs):
Doug Anderson06456632012-01-05 11:02:14 -08001264 """Main function invoked directly by repo.
1265
1266 This function will exit directly upon error so that repo doesn't print some
1267 obscure error message.
1268
1269 Args:
1270 project_list: List of projects to run on.
David James2edd9002013-10-11 14:09:19 -07001271 worktree_list: A list of directories. It should be the same length as
1272 project_list, so that each entry in project_list matches with a directory
1273 in worktree_list. If None, we will attempt to calculate the directories
1274 automatically.
Doug Anderson06456632012-01-05 11:02:14 -08001275 kwargs: Leave this here for forward-compatibility.
1276 """
Ryan Cui1562fb82011-05-09 11:01:31 -07001277 found_error = False
David James2edd9002013-10-11 14:09:19 -07001278 if not worktree_list:
1279 worktree_list = [None] * len(project_list)
1280 for project, worktree in zip(project_list, worktree_list):
1281 if _run_project_hooks(project, proj_dir=worktree):
Ryan Cui1562fb82011-05-09 11:01:31 -07001282 found_error = True
1283
Mike Frysingerae409522014-02-01 03:16:11 -05001284 if found_error:
Ryan Cui1562fb82011-05-09 11:01:31 -07001285 msg = ('Preupload failed due to errors in project(s). HINTS:\n'
Ryan Cui9b651632011-05-11 11:38:58 -07001286 '- To disable some source style checks, and for other hints, see '
1287 '<checkout_dir>/src/repohooks/README\n'
1288 '- To upload only current project, run \'repo upload .\'')
Mike Frysinger09d6a3d2013-10-08 22:21:03 -04001289 print(msg, file=sys.stderr)
Don Garrettdba548a2011-05-05 15:17:14 -07001290 sys.exit(1)
Anush Elangovan63afad72011-03-23 00:41:27 -07001291
Ryan Cui1562fb82011-05-09 11:01:31 -07001292
Doug Anderson44a644f2011-11-02 10:37:37 -07001293def _identify_project(path):
1294 """Identify the repo project associated with the given path.
1295
1296 Returns:
1297 A string indicating what project is associated with the path passed in or
1298 a blank string upon failure.
1299 """
1300 return _run_command(['repo', 'forall', '.', '-c', 'echo ${REPO_PROJECT}'],
Mike Frysingerb81102f2014-11-21 00:33:35 -05001301 stderr=subprocess.PIPE, cwd=path).strip()
Doug Anderson44a644f2011-11-02 10:37:37 -07001302
1303
Mike Frysinger55f85b52014-12-18 14:45:21 -05001304def direct_main(argv):
Doug Anderson44a644f2011-11-02 10:37:37 -07001305 """Run hooks directly (outside of the context of repo).
1306
Doug Anderson44a644f2011-11-02 10:37:37 -07001307 Args:
Mike Frysinger55f85b52014-12-18 14:45:21 -05001308 argv: The command line args to process
Doug Anderson44a644f2011-11-02 10:37:37 -07001309
1310 Returns:
1311 0 if no pre-upload failures, 1 if failures.
1312
1313 Raises:
1314 BadInvocation: On some types of invocation errors.
1315 """
Mike Frysinger66142932014-12-18 14:55:57 -05001316 parser = commandline.ArgumentParser(description=__doc__)
1317 parser.add_argument('--dir', default=None,
1318 help='The directory that the project lives in. If not '
1319 'specified, use the git project root based on the cwd.')
1320 parser.add_argument('--project', default=None,
1321 help='The project repo path; this can affect how the '
1322 'hooks get run, since some hooks are project-specific. '
1323 'For chromite this is chromiumos/chromite. If not '
1324 'specified, the repo tool will be used to figure this '
1325 'out based on the dir.')
1326 parser.add_argument('--rerun-since', default=None,
1327 help='Rerun hooks on old commits since the given date. '
1328 'The date should match git log\'s concept of a date. '
1329 'e.g. 2012-06-20. This option is mutually exclusive '
1330 'with --pre-submit.')
1331 parser.add_argument('--pre-submit', action="store_true",
1332 help='Run the check against the pending commit. '
1333 'This option should be used at the \'git commit\' '
1334 'phase as opposed to \'repo upload\'. This option '
1335 'is mutually exclusive with --rerun-since.')
1336 parser.add_argument('commits', nargs='*',
1337 help='Check specific commits')
1338 opts = parser.parse_args(argv)
Doug Anderson44a644f2011-11-02 10:37:37 -07001339
Doug Anderson14749562013-06-26 13:38:29 -07001340 if opts.rerun_since:
Mike Frysinger66142932014-12-18 14:55:57 -05001341 if opts.commits:
Doug Anderson14749562013-06-26 13:38:29 -07001342 raise BadInvocation('Can\'t pass commits and use rerun-since: %s' %
Mike Frysinger66142932014-12-18 14:55:57 -05001343 ' '.join(opts.commits))
Doug Anderson14749562013-06-26 13:38:29 -07001344
1345 cmd = ['git', 'log', '--since="%s"' % opts.rerun_since, '--pretty=%H']
1346 all_commits = _run_command(cmd).splitlines()
1347 bot_commits = _run_command(cmd + ['--author=chrome-bot']).splitlines()
1348
1349 # Eliminate chrome-bot commits but keep ordering the same...
1350 bot_commits = set(bot_commits)
Mike Frysinger66142932014-12-18 14:55:57 -05001351 opts.commits = [c for c in all_commits if c not in bot_commits]
Doug Anderson14749562013-06-26 13:38:29 -07001352
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001353 if opts.pre_submit:
1354 raise BadInvocation('rerun-since and pre-submit can not be '
1355 'used together')
1356 if opts.pre_submit:
Mike Frysinger66142932014-12-18 14:55:57 -05001357 if opts.commits:
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001358 raise BadInvocation('Can\'t pass commits and use pre-submit: %s' %
Mike Frysinger66142932014-12-18 14:55:57 -05001359 ' '.join(opts.commits))
1360 opts.commits = [PRE_SUBMIT,]
Doug Anderson44a644f2011-11-02 10:37:37 -07001361
1362 # Check/normlaize git dir; if unspecified, we'll use the root of the git
1363 # project from CWD
1364 if opts.dir is None:
1365 git_dir = _run_command(['git', 'rev-parse', '--git-dir'],
1366 stderr=subprocess.PIPE).strip()
1367 if not git_dir:
1368 raise BadInvocation('The current directory is not part of a git project.')
1369 opts.dir = os.path.dirname(os.path.abspath(git_dir))
1370 elif not os.path.isdir(opts.dir):
1371 raise BadInvocation('Invalid dir: %s' % opts.dir)
1372 elif not os.path.isdir(os.path.join(opts.dir, '.git')):
1373 raise BadInvocation('Not a git directory: %s' % opts.dir)
1374
1375 # Identify the project if it wasn't specified; this _requires_ the repo
1376 # tool to be installed and for the project to be part of a repo checkout.
1377 if not opts.project:
1378 opts.project = _identify_project(opts.dir)
1379 if not opts.project:
1380 raise BadInvocation("Repo couldn't identify the project of %s" % opts.dir)
1381
Doug Anderson14749562013-06-26 13:38:29 -07001382 found_error = _run_project_hooks(opts.project, proj_dir=opts.dir,
Mike Frysinger66142932014-12-18 14:55:57 -05001383 commit_list=opts.commits,
Vadim Bendebury2b62d742014-06-22 13:14:51 -07001384 presubmit=opts.pre_submit)
Doug Anderson44a644f2011-11-02 10:37:37 -07001385 if found_error:
1386 return 1
1387 return 0
1388
1389
Mandeep Singh Baines69e470e2011-04-06 10:34:52 -07001390if __name__ == '__main__':
Mike Frysinger55f85b52014-12-18 14:45:21 -05001391 sys.exit(direct_main(sys.argv[1:]))