[email protected] | 725f1c3 | 2011-04-01 20:24:54 | [diff] [blame] | 1 | #!/usr/bin/env python |
[email protected] | 3bbf294 | 2012-01-10 16:52:06 | [diff] [blame] | 2 | # Copyright (c) 2012 The Chromium Authors. All rights reserved. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3 | # Use of this source code is governed by a BSD-style license that can be |
| 4 | # found in the LICENSE file. |
| 5 | |
| 6 | """Enables directory-specific presubmit checks to run at upload and/or commit. |
| 7 | """ |
| 8 | |
[email protected] | f7d31f5 | 2014-01-03 20:14:46 | [diff] [blame] | 9 | __version__ = '1.8.0' |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 10 | |
| 11 | # TODO(joi) Add caching where appropriate/needed. The API is designed to allow |
| 12 | # caching (between all different invocations of presubmit scripts for a given |
| 13 | # change). We should add it as our presubmit scripts start feeling slow. |
| 14 | |
Takeshi Yoshino | 07a6bea | 2017-08-01 17:44:06 | [diff] [blame] | 15 | import ast # Exposed through the API. |
[email protected] | 8a4a2bc | 2013-03-08 08:13:20 | [diff] [blame] | 16 | import contextlib |
Yoshisato Yanagisawa | 406de13 | 2018-06-29 05:43:25 | [diff] [blame] | 17 | import cPickle # Exposed through the API. |
| 18 | import cpplint |
| 19 | import cStringIO # Exposed through the API. |
dcheng | 091b7db | 2016-06-16 08:27:51 | [diff] [blame] | 20 | import fnmatch # Exposed through the API. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 21 | import glob |
[email protected] | 1516995 | 2011-09-27 14:30:53 | [diff] [blame] | 22 | import inspect |
[email protected] | 58a69cb | 2014-03-01 02:08:29 | [diff] [blame] | 23 | import itertools |
[email protected] | 4f6852c | 2012-04-20 20:39:20 | [diff] [blame] | 24 | import json # Exposed through the API. |
[email protected] | df1595a | 2009-06-11 02:00:13 | [diff] [blame] | 25 | import logging |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 26 | import marshal # Exposed through the API. |
[email protected] | bc11731 | 2013-04-20 03:57:56 | [diff] [blame] | 27 | import multiprocessing |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 28 | import optparse |
| 29 | import os # Somewhat exposed through the API. |
| 30 | import pickle # Exposed through the API. |
[email protected] | ce8e46b | 2009-06-26 22:31:51 | [diff] [blame] | 31 | import random |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 32 | import re # Exposed through the API. |
Edward Lesmes | 8e28279 | 2018-04-03 22:50:29 | [diff] [blame] | 33 | import signal |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 34 | import sys # Parts exposed through API. |
| 35 | import tempfile # Exposed through the API. |
Edward Lesmes | 8e28279 | 2018-04-03 22:50:29 | [diff] [blame] | 36 | import threading |
[email protected] | 2a891dc | 2009-08-20 20:33:37 | [diff] [blame] | 37 | import time |
[email protected] | d7dccf5 | 2009-06-06 18:51:58 | [diff] [blame] | 38 | import traceback # Exposed through the API. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 39 | import types |
[email protected] | 1487d53 | 2009-06-06 00:22:57 | [diff] [blame] | 40 | import unittest # Exposed through the API. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 41 | import urllib2 # Exposed through the API. |
[email protected] | 015ebae | 2016-04-25 19:37:22 | [diff] [blame] | 42 | import urlparse |
[email protected] | cb2985f | 2010-11-03 14:08:31 | [diff] [blame] | 43 | from warnings import warn |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 44 | |
| 45 | # Local imports. |
[email protected] | 35625c7 | 2011-03-23 17:34:02 | [diff] [blame] | 46 | import fix_encoding |
Yoshisato Yanagisawa | 406de13 | 2018-06-29 05:43:25 | [diff] [blame] | 47 | import gclient_utils # Exposed through the API |
Aaron Gable | b584c4f | 2017-04-26 23:28:08 | [diff] [blame] | 48 | import git_footers |
[email protected] | 015ebae | 2016-04-25 19:37:22 | [diff] [blame] | 49 | import gerrit_util |
[email protected] | 2a00962 | 2011-03-01 02:43:31 | [diff] [blame] | 50 | import owners |
Jochen Eisinger | 76f5fc6 | 2017-04-07 14:27:46 | [diff] [blame] | 51 | import owners_finder |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 52 | import presubmit_canned_checks |
[email protected] | 5aeb7dd | 2009-11-17 18:09:01 | [diff] [blame] | 53 | import scm |
[email protected] | 84f4fe3 | 2011-04-06 13:26:45 | [diff] [blame] | 54 | import subprocess2 as subprocess # Exposed through the API. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 55 | |
| 56 | |
[email protected] | ce8e46b | 2009-06-26 22:31:51 | [diff] [blame] | 57 | # Ask for feedback only once in program lifetime. |
| 58 | _ASKED_FOR_FEEDBACK = False |
| 59 | |
| 60 | |
[email protected] | 899e1c1 | 2011-04-07 17:03:18 | [diff] [blame] | 61 | class PresubmitFailure(Exception): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 62 | pass |
| 63 | |
| 64 | |
[email protected] | ffeb2f3 | 2013-12-03 13:55:22 | [diff] [blame] | 65 | class CommandData(object): |
| 66 | def __init__(self, name, cmd, kwargs, message): |
| 67 | self.name = name |
| 68 | self.cmd = cmd |
Edward Lesmes | 8e28279 | 2018-04-03 22:50:29 | [diff] [blame] | 69 | self.stdin = kwargs.get('stdin', None) |
[email protected] | ffeb2f3 | 2013-12-03 13:55:22 | [diff] [blame] | 70 | self.kwargs = kwargs |
Edward Lesmes | 8e28279 | 2018-04-03 22:50:29 | [diff] [blame] | 71 | self.kwargs['stdout'] = subprocess.PIPE |
| 72 | self.kwargs['stderr'] = subprocess.STDOUT |
| 73 | self.kwargs['stdin'] = subprocess.PIPE |
[email protected] | ffeb2f3 | 2013-12-03 13:55:22 | [diff] [blame] | 74 | self.message = message |
| 75 | self.info = None |
| 76 | |
[email protected] | bc11731 | 2013-04-20 03:57:56 | [diff] [blame] | 77 | |
Edward Lesmes | 8e28279 | 2018-04-03 22:50:29 | [diff] [blame] | 78 | # Adapted from |
| 79 | # https://github.com/google/gtest-parallel/blob/master/gtest_parallel.py#L37 |
| 80 | # |
| 81 | # An object that catches SIGINT sent to the Python process and notices |
| 82 | # if processes passed to wait() die by SIGINT (we need to look for |
| 83 | # both of those cases, because pressing Ctrl+C can result in either |
| 84 | # the main process or one of the subprocesses getting the signal). |
| 85 | # |
| 86 | # Before a SIGINT is seen, wait(p) will simply call p.wait() and |
| 87 | # return the result. Once a SIGINT has been seen (in the main process |
| 88 | # or a subprocess, including the one the current call is waiting for), |
| 89 | # wait(p) will call p.terminate() and raise ProcessWasInterrupted. |
| 90 | class SigintHandler(object): |
| 91 | class ProcessWasInterrupted(Exception): |
| 92 | pass |
| 93 | |
| 94 | sigint_returncodes = {-signal.SIGINT, # Unix |
| 95 | -1073741510, # Windows |
| 96 | } |
| 97 | def __init__(self): |
| 98 | self.__lock = threading.Lock() |
| 99 | self.__processes = set() |
| 100 | self.__got_sigint = False |
| 101 | signal.signal(signal.SIGINT, lambda signal_num, frame: self.interrupt()) |
| 102 | |
| 103 | def __on_sigint(self): |
| 104 | self.__got_sigint = True |
| 105 | while self.__processes: |
| 106 | try: |
| 107 | self.__processes.pop().terminate() |
| 108 | except OSError: |
| 109 | pass |
| 110 | |
| 111 | def interrupt(self): |
| 112 | with self.__lock: |
| 113 | self.__on_sigint() |
| 114 | |
| 115 | def got_sigint(self): |
| 116 | with self.__lock: |
| 117 | return self.__got_sigint |
| 118 | |
| 119 | def wait(self, p, stdin): |
| 120 | with self.__lock: |
| 121 | if self.__got_sigint: |
| 122 | p.terminate() |
| 123 | self.__processes.add(p) |
| 124 | stdout, stderr = p.communicate(stdin) |
| 125 | code = p.returncode |
| 126 | with self.__lock: |
| 127 | self.__processes.discard(p) |
| 128 | if code in self.sigint_returncodes: |
| 129 | self.__on_sigint() |
| 130 | if self.__got_sigint: |
| 131 | raise self.ProcessWasInterrupted |
| 132 | return stdout, stderr |
| 133 | |
| 134 | sigint_handler = SigintHandler() |
| 135 | |
| 136 | |
| 137 | class ThreadPool(object): |
| 138 | def __init__(self, pool_size=None): |
| 139 | self._pool_size = pool_size or multiprocessing.cpu_count() |
| 140 | self._messages = [] |
| 141 | self._messages_lock = threading.Lock() |
| 142 | self._tests = [] |
| 143 | self._tests_lock = threading.Lock() |
| 144 | self._nonparallel_tests = [] |
| 145 | |
| 146 | def CallCommand(self, test): |
| 147 | """Runs an external program. |
| 148 | |
| 149 | This function converts invocation of .py files and invocations of "python" |
| 150 | to vpython invocations. |
| 151 | """ |
| 152 | vpython = 'vpython.bat' if sys.platform == 'win32' else 'vpython' |
| 153 | |
| 154 | cmd = test.cmd |
| 155 | if cmd[0] == 'python': |
| 156 | cmd = list(cmd) |
| 157 | cmd[0] = vpython |
| 158 | elif cmd[0].endswith('.py'): |
| 159 | cmd = [vpython] + cmd |
| 160 | |
| 161 | try: |
| 162 | start = time.time() |
| 163 | p = subprocess.Popen(cmd, **test.kwargs) |
| 164 | stdout, _ = sigint_handler.wait(p, test.stdin) |
| 165 | duration = time.time() - start |
| 166 | except OSError as e: |
| 167 | duration = time.time() - start |
| 168 | return test.message( |
| 169 | '%s exec failure (%4.2fs)\n %s' % (test.name, duration, e)) |
| 170 | if p.returncode != 0: |
| 171 | return test.message( |
| 172 | '%s (%4.2fs) failed\n%s' % (test.name, duration, stdout)) |
| 173 | if test.info: |
| 174 | return test.info('%s (%4.2fs)' % (test.name, duration)) |
| 175 | |
| 176 | def AddTests(self, tests, parallel=True): |
| 177 | if parallel: |
| 178 | self._tests.extend(tests) |
| 179 | else: |
| 180 | self._nonparallel_tests.extend(tests) |
| 181 | |
| 182 | def RunAsync(self): |
| 183 | self._messages = [] |
| 184 | |
| 185 | def _WorkerFn(): |
| 186 | while True: |
| 187 | test = None |
| 188 | with self._tests_lock: |
| 189 | if not self._tests: |
| 190 | break |
| 191 | test = self._tests.pop() |
| 192 | result = self.CallCommand(test) |
| 193 | if result: |
| 194 | with self._messages_lock: |
| 195 | self._messages.append(result) |
| 196 | |
| 197 | def _StartDaemon(): |
| 198 | t = threading.Thread(target=_WorkerFn) |
| 199 | t.daemon = True |
| 200 | t.start() |
| 201 | return t |
| 202 | |
| 203 | while self._nonparallel_tests: |
| 204 | test = self._nonparallel_tests.pop() |
| 205 | result = self.CallCommand(test) |
| 206 | if result: |
| 207 | self._messages.append(result) |
| 208 | |
| 209 | if self._tests: |
| 210 | threads = [_StartDaemon() for _ in range(self._pool_size)] |
| 211 | for worker in threads: |
| 212 | worker.join() |
| 213 | |
| 214 | return self._messages |
| 215 | |
| 216 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 217 | def normpath(path): |
| 218 | '''Version of os.path.normpath that also changes backward slashes to |
| 219 | forward slashes when not running on Windows. |
| 220 | ''' |
| 221 | # This is safe to always do because the Windows version of os.path.normpath |
| 222 | # will replace forward slashes with backward slashes. |
| 223 | path = path.replace(os.sep, '/') |
| 224 | return os.path.normpath(path) |
| 225 | |
[email protected] | cb2985f | 2010-11-03 14:08:31 | [diff] [blame] | 226 | |
[email protected] | cb2985f | 2010-11-03 14:08:31 | [diff] [blame] | 227 | def _RightHandSideLinesImpl(affected_files): |
| 228 | """Implements RightHandSideLines for InputApi and GclChange.""" |
| 229 | for af in affected_files: |
[email protected] | ab05d58 | 2011-02-09 23:41:22 | [diff] [blame] | 230 | lines = af.ChangedContents() |
[email protected] | cb2985f | 2010-11-03 14:08:31 | [diff] [blame] | 231 | for line in lines: |
[email protected] | ab05d58 | 2011-02-09 23:41:22 | [diff] [blame] | 232 | yield (af, line[0], line[1]) |
[email protected] | cb2985f | 2010-11-03 14:08:31 | [diff] [blame] | 233 | |
| 234 | |
[email protected] | 5ac2101 | 2011-03-16 02:58:25 | [diff] [blame] | 235 | class PresubmitOutput(object): |
| 236 | def __init__(self, input_stream=None, output_stream=None): |
| 237 | self.input_stream = input_stream |
| 238 | self.output_stream = output_stream |
| 239 | self.reviewers = [] |
Daniel Cheng | 7227d21 | 2017-11-17 16:12:37 | [diff] [blame] | 240 | self.more_cc = [] |
[email protected] | 5ac2101 | 2011-03-16 02:58:25 | [diff] [blame] | 241 | self.written_output = [] |
| 242 | self.error_count = 0 |
| 243 | |
| 244 | def prompt_yes_no(self, prompt_string): |
| 245 | self.write(prompt_string) |
| 246 | if self.input_stream: |
| 247 | response = self.input_stream.readline().strip().lower() |
| 248 | if response not in ('y', 'yes'): |
| 249 | self.fail() |
| 250 | else: |
| 251 | self.fail() |
| 252 | |
| 253 | def fail(self): |
| 254 | self.error_count += 1 |
| 255 | |
| 256 | def should_continue(self): |
| 257 | return not self.error_count |
| 258 | |
| 259 | def write(self, s): |
| 260 | self.written_output.append(s) |
| 261 | if self.output_stream: |
| 262 | self.output_stream.write(s) |
| 263 | |
| 264 | def getvalue(self): |
| 265 | return ''.join(self.written_output) |
| 266 | |
| 267 | |
[email protected] | bc11731 | 2013-04-20 03:57:56 | [diff] [blame] | 268 | # Top level object so multiprocessing can pickle |
| 269 | # Public access through OutputApi object. |
| 270 | class _PresubmitResult(object): |
| 271 | """Base class for result objects.""" |
| 272 | fatal = False |
| 273 | should_prompt = False |
| 274 | |
| 275 | def __init__(self, message, items=None, long_text=''): |
| 276 | """ |
| 277 | message: A short one-line message to indicate errors. |
| 278 | items: A list of short strings to indicate where errors occurred. |
| 279 | long_text: multi-line text output, e.g. from another tool |
| 280 | """ |
| 281 | self._message = message |
| 282 | self._items = items or [] |
[email protected] | bc11731 | 2013-04-20 03:57:56 | [diff] [blame] | 283 | self._long_text = long_text.rstrip() |
| 284 | |
| 285 | def handle(self, output): |
| 286 | output.write(self._message) |
| 287 | output.write('\n') |
| 288 | for index, item in enumerate(self._items): |
| 289 | output.write(' ') |
| 290 | # Write separately in case it's unicode. |
| 291 | output.write(str(item)) |
| 292 | if index < len(self._items) - 1: |
| 293 | output.write(' \\') |
| 294 | output.write('\n') |
| 295 | if self._long_text: |
| 296 | output.write('\n***************\n') |
| 297 | # Write separately in case it's unicode. |
| 298 | output.write(self._long_text) |
| 299 | output.write('\n***************\n') |
| 300 | if self.fatal: |
| 301 | output.fail() |
| 302 | |
| 303 | |
| 304 | # Top level object so multiprocessing can pickle |
| 305 | # Public access through OutputApi object. |
[email protected] | bc11731 | 2013-04-20 03:57:56 | [diff] [blame] | 306 | class _PresubmitError(_PresubmitResult): |
| 307 | """A hard presubmit error.""" |
| 308 | fatal = True |
| 309 | |
| 310 | |
| 311 | # Top level object so multiprocessing can pickle |
| 312 | # Public access through OutputApi object. |
| 313 | class _PresubmitPromptWarning(_PresubmitResult): |
| 314 | """An warning that prompts the user if they want to continue.""" |
| 315 | should_prompt = True |
| 316 | |
| 317 | |
| 318 | # Top level object so multiprocessing can pickle |
| 319 | # Public access through OutputApi object. |
| 320 | class _PresubmitNotifyResult(_PresubmitResult): |
| 321 | """Just print something to the screen -- but it's not even a warning.""" |
| 322 | pass |
| 323 | |
| 324 | |
| 325 | # Top level object so multiprocessing can pickle |
| 326 | # Public access through OutputApi object. |
| 327 | class _MailTextResult(_PresubmitResult): |
| 328 | """A warning that should be included in the review request email.""" |
| 329 | def __init__(self, *args, **kwargs): |
| 330 | super(_MailTextResult, self).__init__() |
| 331 | raise NotImplementedError() |
| 332 | |
[email protected] | 37b07a7 | 2016-04-29 16:42:28 | [diff] [blame] | 333 | class GerritAccessor(object): |
| 334 | """Limited Gerrit functionality for canned presubmit checks to work. |
| 335 | |
| 336 | To avoid excessive Gerrit calls, caches the results. |
| 337 | """ |
| 338 | |
| 339 | def __init__(self, host): |
| 340 | self.host = host |
| 341 | self.cache = {} |
| 342 | |
| 343 | def _FetchChangeDetail(self, issue): |
| 344 | # Separate function to be easily mocked in tests. |
Andrii Shyshkalov | c6c8b4c | 2016-11-09 19:51:20 | [diff] [blame] | 345 | try: |
| 346 | return gerrit_util.GetChangeDetail( |
| 347 | self.host, str(issue), |
Aaron Gable | 6f5a8d9 | 2017-04-18 21:49:05 | [diff] [blame] | 348 | ['ALL_REVISIONS', 'DETAILED_LABELS', 'ALL_COMMITS']) |
Andrii Shyshkalov | c6c8b4c | 2016-11-09 19:51:20 | [diff] [blame] | 349 | except gerrit_util.GerritError as e: |
| 350 | if e.http_status == 404: |
| 351 | raise Exception('Either Gerrit issue %s doesn\'t exist, or ' |
| 352 | 'no credentials to fetch issue details' % issue) |
| 353 | raise |
[email protected] | 37b07a7 | 2016-04-29 16:42:28 | [diff] [blame] | 354 | |
| 355 | def GetChangeInfo(self, issue): |
| 356 | """Returns labels and all revisions (patchsets) for this issue. |
| 357 | |
| 358 | The result is a dictionary according to Gerrit REST Api. |
| 359 | https://gerrit-review.googlesource.com/Documentation/rest-api.html |
| 360 | |
| 361 | However, API isn't very clear what's inside, so see tests for example. |
| 362 | """ |
| 363 | assert issue |
| 364 | cache_key = int(issue) |
| 365 | if cache_key not in self.cache: |
| 366 | self.cache[cache_key] = self._FetchChangeDetail(issue) |
| 367 | return self.cache[cache_key] |
| 368 | |
| 369 | def GetChangeDescription(self, issue, patchset=None): |
| 370 | """If patchset is none, fetches current patchset.""" |
| 371 | info = self.GetChangeInfo(issue) |
| 372 | # info is a reference to cache. We'll modify it here adding description to |
| 373 | # it to the right patchset, if it is not yet there. |
| 374 | |
| 375 | # Find revision info for the patchset we want. |
| 376 | if patchset is not None: |
| 377 | for rev, rev_info in info['revisions'].iteritems(): |
| 378 | if str(rev_info['_number']) == str(patchset): |
| 379 | break |
| 380 | else: |
| 381 | raise Exception('patchset %s doesn\'t exist in issue %s' % ( |
| 382 | patchset, issue)) |
| 383 | else: |
| 384 | rev = info['current_revision'] |
| 385 | rev_info = info['revisions'][rev] |
| 386 | |
Andrii Shyshkalov | 9c3a464 | 2017-01-24 16:41:22 | [diff] [blame] | 387 | return rev_info['commit']['message'] |
[email protected] | 37b07a7 | 2016-04-29 16:42:28 | [diff] [blame] | 388 | |
Mun Yong Jang | 603d01e | 2017-12-20 00:38:30 | [diff] [blame] | 389 | def GetDestRef(self, issue): |
| 390 | ref = self.GetChangeInfo(issue)['branch'] |
| 391 | if not ref.startswith('refs/'): |
| 392 | # NOTE: it is possible to create 'refs/x' branch, |
| 393 | # aka 'refs/heads/refs/x'. However, this is ill-advised. |
| 394 | ref = 'refs/heads/%s' % ref |
| 395 | return ref |
| 396 | |
[email protected] | 37b07a7 | 2016-04-29 16:42:28 | [diff] [blame] | 397 | def GetChangeOwner(self, issue): |
| 398 | return self.GetChangeInfo(issue)['owner']['email'] |
| 399 | |
| 400 | def GetChangeReviewers(self, issue, approving_only=True): |
Aaron Gable | 8b478f0 | 2017-07-31 22:33:19 | [diff] [blame] | 401 | changeinfo = self.GetChangeInfo(issue) |
| 402 | if approving_only: |
| 403 | labelinfo = changeinfo.get('labels', {}).get('Code-Review', {}) |
| 404 | values = labelinfo.get('values', {}).keys() |
| 405 | try: |
| 406 | max_value = max(int(v) for v in values) |
| 407 | reviewers = [r for r in labelinfo.get('all', []) |
| 408 | if r.get('value', 0) == max_value] |
| 409 | except ValueError: # values is the empty list |
| 410 | reviewers = [] |
| 411 | else: |
| 412 | reviewers = changeinfo.get('reviewers', {}).get('REVIEWER', []) |
| 413 | return [r.get('email') for r in reviewers] |
[email protected] | 37b07a7 | 2016-04-29 16:42:28 | [diff] [blame] | 414 | |
[email protected] | bc11731 | 2013-04-20 03:57:56 | [diff] [blame] | 415 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 416 | class OutputApi(object): |
[email protected] | a6d011e | 2013-03-26 17:31:49 | [diff] [blame] | 417 | """An instance of OutputApi gets passed to presubmit scripts so that they |
| 418 | can output various types of results. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 419 | """ |
[email protected] | bc11731 | 2013-04-20 03:57:56 | [diff] [blame] | 420 | PresubmitResult = _PresubmitResult |
[email protected] | bc11731 | 2013-04-20 03:57:56 | [diff] [blame] | 421 | PresubmitError = _PresubmitError |
| 422 | PresubmitPromptWarning = _PresubmitPromptWarning |
| 423 | PresubmitNotifyResult = _PresubmitNotifyResult |
| 424 | MailTextResult = _MailTextResult |
| 425 | |
[email protected] | a6d011e | 2013-03-26 17:31:49 | [diff] [blame] | 426 | def __init__(self, is_committing): |
| 427 | self.is_committing = is_committing |
Daniel Cheng | 7227d21 | 2017-11-17 16:12:37 | [diff] [blame] | 428 | self.more_cc = [] |
| 429 | |
| 430 | def AppendCC(self, cc): |
| 431 | """Appends a user to cc for this change.""" |
| 432 | self.more_cc.append(cc) |
[email protected] | a6d011e | 2013-03-26 17:31:49 | [diff] [blame] | 433 | |
[email protected] | a6d011e | 2013-03-26 17:31:49 | [diff] [blame] | 434 | def PresubmitPromptOrNotify(self, *args, **kwargs): |
| 435 | """Warn the user when uploading, but only notify if committing.""" |
| 436 | if self.is_committing: |
| 437 | return self.PresubmitNotifyResult(*args, **kwargs) |
| 438 | return self.PresubmitPromptWarning(*args, **kwargs) |
| 439 | |
Kenneth Russell | 61e2ed4 | 2017-02-15 19:47:13 | [diff] [blame] | 440 | def EnsureCQIncludeTrybotsAreAdded(self, cl, bots_to_include, message): |
| 441 | """Helper for any PostUploadHook wishing to add CQ_INCLUDE_TRYBOTS. |
| 442 | |
| 443 | Merges the bots_to_include into the current CQ_INCLUDE_TRYBOTS list, |
| 444 | keeping it alphabetically sorted. Returns the results that should be |
| 445 | returned from the PostUploadHook. |
| 446 | |
| 447 | Args: |
| 448 | cl: The git_cl.Changelist object. |
| 449 | bots_to_include: A list of strings of bots to include, in the form |
| 450 | "master:slave". |
| 451 | message: A message to be printed in the case that |
| 452 | CQ_INCLUDE_TRYBOTS was updated. |
| 453 | """ |
| 454 | description = cl.GetDescription(force=True) |
Aaron Gable | 4b23a2c | 2018-05-24 17:46:48 | [diff] [blame] | 455 | trybot_footers = git_footers.parse_footers(description).get( |
| 456 | git_footers.normalize_name('Cq-Include-Trybots'), []) |
Aaron Gable | b584c4f | 2017-04-26 23:28:08 | [diff] [blame] | 457 | prior_bots = [] |
Aaron Gable | 4b23a2c | 2018-05-24 17:46:48 | [diff] [blame] | 458 | for f in trybot_footers: |
| 459 | prior_bots += [b.strip() for b in f.split(';') if b.strip()] |
Aaron Gable | b584c4f | 2017-04-26 23:28:08 | [diff] [blame] | 460 | |
| 461 | if set(prior_bots) >= set(bots_to_include): |
| 462 | return [] |
| 463 | all_bots = ';'.join(sorted(set(prior_bots) | set(bots_to_include))) |
| 464 | |
Aaron Gable | 4b23a2c | 2018-05-24 17:46:48 | [diff] [blame] | 465 | description = git_footers.remove_footer(description, 'Cq-Include-Trybots') |
| 466 | description = git_footers.add_footer( |
| 467 | description, 'Cq-Include-Trybots', all_bots, |
| 468 | before_keys=['Change-Id']) |
Aaron Gable | b584c4f | 2017-04-26 23:28:08 | [diff] [blame] | 469 | |
| 470 | cl.UpdateDescription(description, force=True) |
Kenneth Russell | 61e2ed4 | 2017-02-15 19:47:13 | [diff] [blame] | 471 | return [self.PresubmitNotifyResult(message)] |
| 472 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 473 | |
| 474 | class InputApi(object): |
| 475 | """An instance of this object is passed to presubmit scripts so they can |
| 476 | know stuff about the change they're looking at. |
| 477 | """ |
[email protected] | b17b55b | 2010-11-03 14:42:37 | [diff] [blame] | 478 | # Method could be a function |
Quinten Yearsley | b2cc4a9 | 2016-12-15 21:53:26 | [diff] [blame] | 479 | # pylint: disable=no-self-use |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 480 | |
[email protected] | 3410d91 | 2009-06-09 20:56:16 | [diff] [blame] | 481 | # File extensions that are considered source files from a style guide |
| 482 | # perspective. Don't modify this list from a presubmit script! |
[email protected] | c33455a | 2011-06-24 19:14:18 | [diff] [blame] | 483 | # |
| 484 | # Files without an extension aren't included in the list. If you want to |
| 485 | # filter them as source files, add r"(^|.*?[\\\/])[^.]+$" to the white list. |
| 486 | # Note that ALL CAPS files are black listed in DEFAULT_BLACK_LIST below. |
[email protected] | 3410d91 | 2009-06-09 20:56:16 | [diff] [blame] | 487 | DEFAULT_WHITE_LIST = ( |
| 488 | # C++ and friends |
[email protected] | fe1211a | 2011-05-28 18:54:17 | [diff] [blame] | 489 | r".+\.c$", r".+\.cc$", r".+\.cpp$", r".+\.h$", r".+\.m$", r".+\.mm$", |
| 490 | r".+\.inl$", r".+\.asm$", r".+\.hxx$", r".+\.hpp$", r".+\.s$", r".+\.S$", |
[email protected] | 3410d91 | 2009-06-09 20:56:16 | [diff] [blame] | 491 | # Scripts |
[email protected] | fe1211a | 2011-05-28 18:54:17 | [diff] [blame] | 492 | r".+\.js$", r".+\.py$", r".+\.sh$", r".+\.rb$", r".+\.pl$", r".+\.pm$", |
[email protected] | 3410d91 | 2009-06-09 20:56:16 | [diff] [blame] | 493 | # Other |
Sergey Ulanov | 166bc4c | 2018-05-01 00:03:38 | [diff] [blame] | 494 | r".+\.java$", r".+\.mk$", r".+\.am$", r".+\.css$", r".+\.mojom$", |
| 495 | r".+\.fidl$" |
[email protected] | 3410d91 | 2009-06-09 20:56:16 | [diff] [blame] | 496 | ) |
| 497 | |
| 498 | # Path regexp that should be excluded from being considered containing source |
| 499 | # files. Don't modify this list from a presubmit script! |
| 500 | DEFAULT_BLACK_LIST = ( |
[email protected] | 656326d | 2012-08-13 00:43:57 | [diff] [blame] | 501 | r"testing_support[\\\/]google_appengine[\\\/].*", |
[email protected] | 3410d91 | 2009-06-09 20:56:16 | [diff] [blame] | 502 | r".*\bexperimental[\\\/].*", |
Kent Tamura | 179dd1e | 2018-04-26 06:07:41 | [diff] [blame] | 503 | # Exclude third_party/.* but NOT third_party/{WebKit,blink} |
| 504 | # (crbug.com/539768 and crbug.com/836555). |
| 505 | r".*\bthird_party[\\\/](?!(WebKit|blink)[\\\/]).*", |
[email protected] | 3410d91 | 2009-06-09 20:56:16 | [diff] [blame] | 506 | # Output directories (just in case) |
| 507 | r".*\bDebug[\\\/].*", |
| 508 | r".*\bRelease[\\\/].*", |
| 509 | r".*\bxcodebuild[\\\/].*", |
[email protected] | c1c9635 | 2013-10-09 19:50:27 | [diff] [blame] | 510 | r".*\bout[\\\/].*", |
[email protected] | 3410d91 | 2009-06-09 20:56:16 | [diff] [blame] | 511 | # All caps files like README and LICENCE. |
[email protected] | ab05d58 | 2011-02-09 23:41:22 | [diff] [blame] | 512 | r".*\b[A-Z0-9_]{2,}$", |
[email protected] | df1595a | 2009-06-11 02:00:13 | [diff] [blame] | 513 | # SCM (can happen in dual SCM configuration). (Slightly over aggressive) |
[email protected] | 5d0dc43 | 2011-01-03 02:40:37 | [diff] [blame] | 514 | r"(|.*[\\\/])\.git[\\\/].*", |
| 515 | r"(|.*[\\\/])\.svn[\\\/].*", |
[email protected] | 7ccb4bb | 2011-11-07 20:26:20 | [diff] [blame] | 516 | # There is no point in processing a patch file. |
| 517 | r".+\.diff$", |
| 518 | r".+\.patch$", |
[email protected] | 3410d91 | 2009-06-09 20:56:16 | [diff] [blame] | 519 | ) |
| 520 | |
[email protected] | cc73ad6 | 2011-07-06 17:39:26 | [diff] [blame] | 521 | def __init__(self, change, presubmit_path, is_committing, |
Edward Lesmes | 8e28279 | 2018-04-03 22:50:29 | [diff] [blame] | 522 | verbose, gerrit_obj, dry_run=None, thread_pool=None, parallel=False): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 523 | """Builds an InputApi object. |
| 524 | |
| 525 | Args: |
[email protected] | 4ff922a | 2009-06-12 20:20:19 | [diff] [blame] | 526 | change: A presubmit.Change object. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 527 | presubmit_path: The path to the presubmit script being processed. |
[email protected] | d7dccf5 | 2009-06-06 18:51:58 | [diff] [blame] | 528 | is_committing: True if the change is about to be committed. |
[email protected] | 37b07a7 | 2016-04-29 16:42:28 | [diff] [blame] | 529 | gerrit_obj: provides basic Gerrit codereview functionality. |
| 530 | dry_run: if true, some Checks will be skipped. |
Edward Lesmes | 8e28279 | 2018-04-03 22:50:29 | [diff] [blame] | 531 | parallel: if true, all tests reported via input_api.RunTests for all |
| 532 | PRESUBMIT files will be run in parallel. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 533 | """ |
[email protected] | 9711bba | 2009-05-22 23:51:39 | [diff] [blame] | 534 | # Version number of the presubmit_support script. |
| 535 | self.version = [int(x) for x in __version__.split('.')] |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 536 | self.change = change |
[email protected] | d7dccf5 | 2009-06-06 18:51:58 | [diff] [blame] | 537 | self.is_committing = is_committing |
[email protected] | 37b07a7 | 2016-04-29 16:42:28 | [diff] [blame] | 538 | self.gerrit = gerrit_obj |
[email protected] | 57bafac | 2016-04-28 05:09:03 | [diff] [blame] | 539 | self.dry_run = dry_run |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 540 | |
Edward Lesmes | 8e28279 | 2018-04-03 22:50:29 | [diff] [blame] | 541 | self.parallel = parallel |
| 542 | self.thread_pool = thread_pool or ThreadPool() |
| 543 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 544 | # We expose various modules and functions as attributes of the input_api |
| 545 | # so that presubmit scripts don't have to import them. |
Takeshi Yoshino | 07a6bea | 2017-08-01 17:44:06 | [diff] [blame] | 546 | self.ast = ast |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 547 | self.basename = os.path.basename |
| 548 | self.cPickle = cPickle |
[email protected] | e72c5f5 | 2013-04-16 00:36:40 | [diff] [blame] | 549 | self.cpplint = cpplint |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 550 | self.cStringIO = cStringIO |
dcheng | 091b7db | 2016-06-16 08:27:51 | [diff] [blame] | 551 | self.fnmatch = fnmatch |
Yoshisato Yanagisawa | 406de13 | 2018-06-29 05:43:25 | [diff] [blame] | 552 | self.gclient_utils = gclient_utils |
[email protected] | 17cc244 | 2012-10-17 21:12:09 | [diff] [blame] | 553 | self.glob = glob.glob |
[email protected] | fb11c7b | 2010-03-18 18:22:14 | [diff] [blame] | 554 | self.json = json |
[email protected] | 6fba34d | 2011-06-02 13:45:12 | [diff] [blame] | 555 | self.logging = logging.getLogger('PRESUBMIT') |
Yoshisato Yanagisawa | 406de13 | 2018-06-29 05:43:25 | [diff] [blame] | 556 | self.marshal = marshal |
[email protected] | 2b5ce56 | 2011-03-31 16:15:44 | [diff] [blame] | 557 | self.os_listdir = os.listdir |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 558 | self.os_path = os.path |
[email protected] | bd0cace | 2014-10-02 23:23:46 | [diff] [blame] | 559 | self.os_stat = os.stat |
Yoshisato Yanagisawa | 406de13 | 2018-06-29 05:43:25 | [diff] [blame] | 560 | self.os_walk = os.walk |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 561 | self.pickle = pickle |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 562 | self.re = re |
| 563 | self.subprocess = subprocess |
| 564 | self.tempfile = tempfile |
[email protected] | 0d1bdea | 2011-03-24 22:54:38 | [diff] [blame] | 565 | self.time = time |
[email protected] | d7dccf5 | 2009-06-06 18:51:58 | [diff] [blame] | 566 | self.traceback = traceback |
[email protected] | 1487d53 | 2009-06-06 00:22:57 | [diff] [blame] | 567 | self.unittest = unittest |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 568 | self.urllib2 = urllib2 |
| 569 | |
Robert Iannucci | 5025893 | 2018-03-19 17:30:59 | [diff] [blame] | 570 | self.is_windows = sys.platform == 'win32' |
| 571 | |
| 572 | # Set python_executable to 'python'. This is interpreted in CallCommand to |
| 573 | # convert to vpython in order to allow scripts in other repos (e.g. src.git) |
| 574 | # to automatically pick up that repo's .vpython file, instead of inheriting |
| 575 | # the one in depot_tools. |
| 576 | self.python_executable = 'python' |
[email protected] | c0b2297 | 2009-06-25 16:19:14 | [diff] [blame] | 577 | self.environ = os.environ |
| 578 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 579 | # InputApi.platform is the platform you're currently running on. |
| 580 | self.platform = sys.platform |
| 581 | |
[email protected] | 0af3bb3 | 2015-06-12 20:44:35 | [diff] [blame] | 582 | self.cpu_count = multiprocessing.cpu_count() |
| 583 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 584 | # The local path of the currently-being-processed presubmit script. |
[email protected] | 3d23524 | 2009-05-15 12:40:48 | [diff] [blame] | 585 | self._current_presubmit_path = os.path.dirname(presubmit_path) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 586 | |
| 587 | # We carry the canned checks so presubmit scripts can easily use them. |
| 588 | self.canned_checks = presubmit_canned_checks |
| 589 | |
Raphael Kubo da Costa | f2d1615 | 2017-11-10 17:07:58 | [diff] [blame] | 590 | # Temporary files we must manually remove at the end of a run. |
| 591 | self._named_temporary_files = [] |
Jochen Eisinger | 72606f8 | 2017-04-04 08:44:18 | [diff] [blame] | 592 | |
[email protected] | 2a00962 | 2011-03-01 02:43:31 | [diff] [blame] | 593 | # TODO(dpranke): figure out a list of all approved owners for a repo |
| 594 | # in order to be able to handle wildcard OWNERS files? |
| 595 | self.owners_db = owners.Database(change.RepositoryRoot(), |
Jochen Eisinger | 72606f8 | 2017-04-04 08:44:18 | [diff] [blame] | 596 | fopen=file, os_path=self.os_path) |
Jochen Eisinger | 76f5fc6 | 2017-04-07 14:27:46 | [diff] [blame] | 597 | self.owners_finder = owners_finder.OwnersFinder |
[email protected] | 899e1c1 | 2011-04-07 17:03:18 | [diff] [blame] | 598 | self.verbose = verbose |
[email protected] | bc11731 | 2013-04-20 03:57:56 | [diff] [blame] | 599 | self.Command = CommandData |
[email protected] | 2a00962 | 2011-03-01 02:43:31 | [diff] [blame] | 600 | |
[email protected] | e72c5f5 | 2013-04-16 00:36:40 | [diff] [blame] | 601 | # Replace <hash_map> and <hash_set> as headers that need to be included |
[email protected] | 1827852 | 2013-06-11 22:42:32 | [diff] [blame] | 602 | # with "base/containers/hash_tables.h" instead. |
[email protected] | e72c5f5 | 2013-04-16 00:36:40 | [diff] [blame] | 603 | # Access to a protected member _XX of a client class |
Quinten Yearsley | b2cc4a9 | 2016-12-15 21:53:26 | [diff] [blame] | 604 | # pylint: disable=protected-access |
[email protected] | e72c5f5 | 2013-04-16 00:36:40 | [diff] [blame] | 605 | self.cpplint._re_pattern_templates = [ |
[email protected] | 1827852 | 2013-06-11 22:42:32 | [diff] [blame] | 606 | (a, b, 'base/containers/hash_tables.h') |
[email protected] | e72c5f5 | 2013-04-16 00:36:40 | [diff] [blame] | 607 | if header in ('<hash_map>', '<hash_set>') else (a, b, header) |
| 608 | for (a, b, header) in cpplint._re_pattern_templates |
| 609 | ] |
| 610 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 611 | def PresubmitLocalPath(self): |
| 612 | """Returns the local path of the presubmit script currently being run. |
| 613 | |
| 614 | This is useful if you don't want to hard-code absolute paths in the |
| 615 | presubmit script. For example, It can be used to find another file |
| 616 | relative to the PRESUBMIT.py script, so the whole tree can be branched and |
| 617 | the presubmit script still works, without editing its content. |
| 618 | """ |
[email protected] | 3d23524 | 2009-05-15 12:40:48 | [diff] [blame] | 619 | return self._current_presubmit_path |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 620 | |
agable | 0b65e73 | 2016-11-22 17:25:46 | [diff] [blame] | 621 | def AffectedFiles(self, include_deletes=True, file_filter=None): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 622 | """Same as input_api.change.AffectedFiles() except only lists files |
| 623 | (and optionally directories) in the same directory as the current presubmit |
| 624 | script, or subdirectories thereof. |
| 625 | """ |
[email protected] | 3d23524 | 2009-05-15 12:40:48 | [diff] [blame] | 626 | dir_with_slash = normpath("%s/" % self.PresubmitLocalPath()) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 627 | if len(dir_with_slash) == 1: |
| 628 | dir_with_slash = '' |
[email protected] | 5538e02 | 2011-05-12 17:53:16 | [diff] [blame] | 629 | |
[email protected] | 4661e0c | 2009-06-04 00:45:26 | [diff] [blame] | 630 | return filter( |
| 631 | lambda x: normpath(x.AbsoluteLocalPath()).startswith(dir_with_slash), |
agable | 0b65e73 | 2016-11-22 17:25:46 | [diff] [blame] | 632 | self.change.AffectedFiles(include_deletes, file_filter)) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 633 | |
agable | 0b65e73 | 2016-11-22 17:25:46 | [diff] [blame] | 634 | def LocalPaths(self): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 635 | """Returns local paths of input_api.AffectedFiles().""" |
agable | 0b65e73 | 2016-11-22 17:25:46 | [diff] [blame] | 636 | paths = [af.LocalPath() for af in self.AffectedFiles()] |
[email protected] | 2f64f78 | 2014-04-25 00:12:33 | [diff] [blame] | 637 | logging.debug("LocalPaths: %s", paths) |
| 638 | return paths |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 639 | |
agable | 0b65e73 | 2016-11-22 17:25:46 | [diff] [blame] | 640 | def AbsoluteLocalPaths(self): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 641 | """Returns absolute local paths of input_api.AffectedFiles().""" |
agable | 0b65e73 | 2016-11-22 17:25:46 | [diff] [blame] | 642 | return [af.AbsoluteLocalPath() for af in self.AffectedFiles()] |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 643 | |
John Budorick | 1616237 | 2018-04-18 17:39:53 | [diff] [blame] | 644 | def AffectedTestableFiles(self, include_deletes=None, **kwargs): |
agable | 0b65e73 | 2016-11-22 17:25:46 | [diff] [blame] | 645 | """Same as input_api.change.AffectedTestableFiles() except only lists files |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 646 | in the same directory as the current presubmit script, or subdirectories |
| 647 | thereof. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 648 | """ |
[email protected] | 77c4f0f | 2009-05-29 18:53:04 | [diff] [blame] | 649 | if include_deletes is not None: |
agable | 0b65e73 | 2016-11-22 17:25:46 | [diff] [blame] | 650 | warn("AffectedTestableFiles(include_deletes=%s)" |
[email protected] | cb2985f | 2010-11-03 14:08:31 | [diff] [blame] | 651 | " is deprecated and ignored" % str(include_deletes), |
| 652 | category=DeprecationWarning, |
| 653 | stacklevel=2) |
agable | 0b65e73 | 2016-11-22 17:25:46 | [diff] [blame] | 654 | return filter(lambda x: x.IsTestableFile(), |
John Budorick | 1616237 | 2018-04-18 17:39:53 | [diff] [blame] | 655 | self.AffectedFiles(include_deletes=False, **kwargs)) |
agable | 0b65e73 | 2016-11-22 17:25:46 | [diff] [blame] | 656 | |
| 657 | def AffectedTextFiles(self, include_deletes=None): |
| 658 | """An alias to AffectedTestableFiles for backwards compatibility.""" |
| 659 | return self.AffectedTestableFiles(include_deletes=include_deletes) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 660 | |
[email protected] | 3410d91 | 2009-06-09 20:56:16 | [diff] [blame] | 661 | def FilterSourceFile(self, affected_file, white_list=None, black_list=None): |
| 662 | """Filters out files that aren't considered "source file". |
| 663 | |
| 664 | If white_list or black_list is None, InputApi.DEFAULT_WHITE_LIST |
| 665 | and InputApi.DEFAULT_BLACK_LIST is used respectively. |
| 666 | |
| 667 | The lists will be compiled as regular expression and |
| 668 | AffectedFile.LocalPath() needs to pass both list. |
| 669 | |
| 670 | Note: Copy-paste this function to suit your needs or use a lambda function. |
| 671 | """ |
[email protected] | cb2985f | 2010-11-03 14:08:31 | [diff] [blame] | 672 | def Find(affected_file, items): |
[email protected] | ab05d58 | 2011-02-09 23:41:22 | [diff] [blame] | 673 | local_path = affected_file.LocalPath() |
[email protected] | cb2985f | 2010-11-03 14:08:31 | [diff] [blame] | 674 | for item in items: |
[email protected] | df1595a | 2009-06-11 02:00:13 | [diff] [blame] | 675 | if self.re.match(item, local_path): |
[email protected] | 3410d91 | 2009-06-09 20:56:16 | [diff] [blame] | 676 | return True |
| 677 | return False |
| 678 | return (Find(affected_file, white_list or self.DEFAULT_WHITE_LIST) and |
| 679 | not Find(affected_file, black_list or self.DEFAULT_BLACK_LIST)) |
| 680 | |
| 681 | def AffectedSourceFiles(self, source_file): |
agable | 0b65e73 | 2016-11-22 17:25:46 | [diff] [blame] | 682 | """Filter the list of AffectedTestableFiles by the function source_file. |
[email protected] | 3410d91 | 2009-06-09 20:56:16 | [diff] [blame] | 683 | |
| 684 | If source_file is None, InputApi.FilterSourceFile() is used. |
| 685 | """ |
| 686 | if not source_file: |
| 687 | source_file = self.FilterSourceFile |
agable | 0b65e73 | 2016-11-22 17:25:46 | [diff] [blame] | 688 | return filter(source_file, self.AffectedTestableFiles()) |
[email protected] | 3410d91 | 2009-06-09 20:56:16 | [diff] [blame] | 689 | |
| 690 | def RightHandSideLines(self, source_file_filter=None): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 691 | """An iterator over all text lines in "new" version of changed files. |
| 692 | |
| 693 | Only lists lines from new or modified text files in the change that are |
| 694 | contained by the directory of the currently executing presubmit script. |
| 695 | |
| 696 | This is useful for doing line-by-line regex checks, like checking for |
| 697 | trailing whitespace. |
| 698 | |
| 699 | Yields: |
| 700 | a 3 tuple: |
| 701 | the AffectedFile instance of the current file; |
| 702 | integer line number (1-based); and |
| 703 | the contents of the line as a string. |
[email protected] | 1487d53 | 2009-06-06 00:22:57 | [diff] [blame] | 704 | |
[email protected] | 2a3ab7e | 2011-04-27 22:06:27 | [diff] [blame] | 705 | Note: The carriage return (LF or CR) is stripped off. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 706 | """ |
[email protected] | 3410d91 | 2009-06-09 20:56:16 | [diff] [blame] | 707 | files = self.AffectedSourceFiles(source_file_filter) |
[email protected] | cb2985f | 2010-11-03 14:08:31 | [diff] [blame] | 708 | return _RightHandSideLinesImpl(files) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 709 | |
[email protected] | e3608df | 2009-11-10 20:22:57 | [diff] [blame] | 710 | def ReadFile(self, file_item, mode='r'): |
[email protected] | 44a17ad | 2009-06-08 14:14:35 | [diff] [blame] | 711 | """Reads an arbitrary file. |
[email protected] | da8cddd | 2009-08-13 00:25:55 | [diff] [blame] | 712 | |
[email protected] | 44a17ad | 2009-06-08 14:14:35 | [diff] [blame] | 713 | Deny reading anything outside the repository. |
| 714 | """ |
[email protected] | e3608df | 2009-11-10 20:22:57 | [diff] [blame] | 715 | if isinstance(file_item, AffectedFile): |
| 716 | file_item = file_item.AbsoluteLocalPath() |
| 717 | if not file_item.startswith(self.change.RepositoryRoot()): |
[email protected] | 44a17ad | 2009-06-08 14:14:35 | [diff] [blame] | 718 | raise IOError('Access outside the repository root is denied.') |
[email protected] | 5aeb7dd | 2009-11-17 18:09:01 | [diff] [blame] | 719 | return gclient_utils.FileRead(file_item, mode) |
[email protected] | 44a17ad | 2009-06-08 14:14:35 | [diff] [blame] | 720 | |
Raphael Kubo da Costa | f2d1615 | 2017-11-10 17:07:58 | [diff] [blame] | 721 | def CreateTemporaryFile(self, **kwargs): |
| 722 | """Returns a named temporary file that must be removed with a call to |
| 723 | RemoveTemporaryFiles(). |
| 724 | |
| 725 | All keyword arguments are forwarded to tempfile.NamedTemporaryFile(), |
| 726 | except for |delete|, which is always set to False. |
| 727 | |
| 728 | Presubmit checks that need to create a temporary file and pass it for |
| 729 | reading should use this function instead of NamedTemporaryFile(), as |
| 730 | Windows fails to open a file that is already open for writing. |
| 731 | |
| 732 | with input_api.CreateTemporaryFile() as f: |
| 733 | f.write('xyz') |
| 734 | f.close() |
| 735 | input_api.subprocess.check_output(['script-that', '--reads-from', |
| 736 | f.name]) |
| 737 | |
| 738 | |
| 739 | Note that callers of CreateTemporaryFile() should not worry about removing |
| 740 | any temporary file; this is done transparently by the presubmit handling |
| 741 | code. |
| 742 | """ |
| 743 | if 'delete' in kwargs: |
| 744 | # Prevent users from passing |delete|; we take care of file deletion |
| 745 | # ourselves and this prevents unintuitive error messages when we pass |
| 746 | # delete=False and 'delete' is also in kwargs. |
| 747 | raise TypeError('CreateTemporaryFile() does not take a "delete" ' |
| 748 | 'argument, file deletion is handled automatically by ' |
| 749 | 'the same presubmit_support code that creates InputApi ' |
| 750 | 'objects.') |
| 751 | temp_file = self.tempfile.NamedTemporaryFile(delete=False, **kwargs) |
| 752 | self._named_temporary_files.append(temp_file.name) |
| 753 | return temp_file |
| 754 | |
[email protected] | cc73ad6 | 2011-07-06 17:39:26 | [diff] [blame] | 755 | @property |
| 756 | def tbr(self): |
| 757 | """Returns if a change is TBR'ed.""" |
Jeremy Roman | dce2250 | 2017-06-20 19:37:29 | [diff] [blame] | 758 | return 'TBR' in self.change.tags or self.change.TBRsFromDescription() |
[email protected] | cc73ad6 | 2011-07-06 17:39:26 | [diff] [blame] | 759 | |
[email protected] | ffeb2f3 | 2013-12-03 13:55:22 | [diff] [blame] | 760 | def RunTests(self, tests_mix, parallel=True): |
Edward Lesmes | 8e28279 | 2018-04-03 22:50:29 | [diff] [blame] | 761 | # RunTests doesn't actually run tests. It adds them to a ThreadPool that |
| 762 | # will run all tests once all PRESUBMIT files are processed. |
[email protected] | bc11731 | 2013-04-20 03:57:56 | [diff] [blame] | 763 | tests = [] |
| 764 | msgs = [] |
Edward Lemur | 7e3c67f | 2018-07-20 20:52:49 | [diff] [blame] | 765 | parallel = parallel and self.parallel |
[email protected] | bc11731 | 2013-04-20 03:57:56 | [diff] [blame] | 766 | for t in tests_mix: |
Edward Lesmes | 8e28279 | 2018-04-03 22:50:29 | [diff] [blame] | 767 | if isinstance(t, OutputApi.PresubmitResult) and t: |
[email protected] | bc11731 | 2013-04-20 03:57:56 | [diff] [blame] | 768 | msgs.append(t) |
| 769 | else: |
| 770 | assert issubclass(t.message, _PresubmitResult) |
| 771 | tests.append(t) |
[email protected] | ffeb2f3 | 2013-12-03 13:55:22 | [diff] [blame] | 772 | if self.verbose: |
| 773 | t.info = _PresubmitNotifyResult |
Edward Lemur | 1037c74 | 2018-05-01 22:56:04 | [diff] [blame] | 774 | if not t.kwargs.get('cwd'): |
| 775 | t.kwargs['cwd'] = self.PresubmitLocalPath() |
Edward Lesmes | 8e28279 | 2018-04-03 22:50:29 | [diff] [blame] | 776 | self.thread_pool.AddTests(tests, parallel) |
Edward Lemur | 7e3c67f | 2018-07-20 20:52:49 | [diff] [blame] | 777 | if not parallel: |
Edward Lesmes | 8e28279 | 2018-04-03 22:50:29 | [diff] [blame] | 778 | msgs.extend(self.thread_pool.RunAsync()) |
| 779 | return msgs |
scottmg | 86099d7 | 2016-09-01 16:16:51 | [diff] [blame] | 780 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 781 | |
[email protected] | ff52619 | 2013-06-10 19:30:26 | [diff] [blame] | 782 | class _DiffCache(object): |
| 783 | """Caches diffs retrieved from a particular SCM.""" |
[email protected] | ea84ef1 | 2014-04-30 19:55:12 | [diff] [blame] | 784 | def __init__(self, upstream=None): |
| 785 | """Stores the upstream revision against which all diffs will be computed.""" |
| 786 | self._upstream = upstream |
[email protected] | ff52619 | 2013-06-10 19:30:26 | [diff] [blame] | 787 | |
| 788 | def GetDiff(self, path, local_root): |
| 789 | """Get the diff for a particular path.""" |
| 790 | raise NotImplementedError() |
| 791 | |
Daniel Cheng | 7a1f04d | 2017-03-22 02:12:31 | [diff] [blame] | 792 | def GetOldContents(self, path, local_root): |
| 793 | """Get the old version for a particular path.""" |
| 794 | raise NotImplementedError() |
| 795 | |
[email protected] | ff52619 | 2013-06-10 19:30:26 | [diff] [blame] | 796 | |
[email protected] | ff52619 | 2013-06-10 19:30:26 | [diff] [blame] | 797 | class _GitDiffCache(_DiffCache): |
| 798 | """DiffCache implementation for git; gets all file diffs at once.""" |
[email protected] | ea84ef1 | 2014-04-30 19:55:12 | [diff] [blame] | 799 | def __init__(self, upstream): |
| 800 | super(_GitDiffCache, self).__init__(upstream=upstream) |
[email protected] | ff52619 | 2013-06-10 19:30:26 | [diff] [blame] | 801 | self._diffs_by_file = None |
| 802 | |
| 803 | def GetDiff(self, path, local_root): |
| 804 | if not self._diffs_by_file: |
| 805 | # Compute a single diff for all files and parse the output; should |
| 806 | # with git this is much faster than computing one diff for each file. |
| 807 | diffs = {} |
| 808 | |
| 809 | # Don't specify any filenames below, because there are command line length |
| 810 | # limits on some platforms and GenerateDiff would fail. |
[email protected] | ea84ef1 | 2014-04-30 19:55:12 | [diff] [blame] | 811 | unified_diff = scm.GIT.GenerateDiff(local_root, files=[], full_move=True, |
| 812 | branch=self._upstream) |
[email protected] | ff52619 | 2013-06-10 19:30:26 | [diff] [blame] | 813 | |
| 814 | # This regex matches the path twice, separated by a space. Note that |
| 815 | # filename itself may contain spaces. |
| 816 | file_marker = re.compile('^diff --git (?P<filename>.*) (?P=filename)$') |
| 817 | current_diff = [] |
| 818 | keep_line_endings = True |
| 819 | for x in unified_diff.splitlines(keep_line_endings): |
| 820 | match = file_marker.match(x) |
| 821 | if match: |
| 822 | # Marks the start of a new per-file section. |
| 823 | diffs[match.group('filename')] = current_diff = [x] |
| 824 | elif x.startswith('diff --git'): |
| 825 | raise PresubmitFailure('Unexpected diff line: %s' % x) |
| 826 | else: |
| 827 | current_diff.append(x) |
| 828 | |
| 829 | self._diffs_by_file = dict( |
| 830 | (normpath(path), ''.join(diff)) for path, diff in diffs.items()) |
| 831 | |
| 832 | if path not in self._diffs_by_file: |
| 833 | raise PresubmitFailure( |
| 834 | 'Unified diff did not contain entry for file %s' % path) |
| 835 | |
| 836 | return self._diffs_by_file[path] |
| 837 | |
Daniel Cheng | 7a1f04d | 2017-03-22 02:12:31 | [diff] [blame] | 838 | def GetOldContents(self, path, local_root): |
| 839 | return scm.GIT.GetOldContents(local_root, path, branch=self._upstream) |
| 840 | |
[email protected] | ff52619 | 2013-06-10 19:30:26 | [diff] [blame] | 841 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 842 | class AffectedFile(object): |
| 843 | """Representation of a file in a change.""" |
[email protected] | ff52619 | 2013-06-10 19:30:26 | [diff] [blame] | 844 | |
| 845 | DIFF_CACHE = _DiffCache |
| 846 | |
[email protected] | b17b55b | 2010-11-03 14:42:37 | [diff] [blame] | 847 | # Method could be a function |
Quinten Yearsley | b2cc4a9 | 2016-12-15 21:53:26 | [diff] [blame] | 848 | # pylint: disable=no-self-use |
[email protected] | ea84ef1 | 2014-04-30 19:55:12 | [diff] [blame] | 849 | def __init__(self, path, action, repository_root, diff_cache): |
[email protected] | 15bdffa | 2009-05-29 11:16:29 | [diff] [blame] | 850 | self._path = path |
| 851 | self._action = action |
[email protected] | 4ff922a | 2009-06-12 20:20:19 | [diff] [blame] | 852 | self._local_root = repository_root |
[email protected] | 15bdffa | 2009-05-29 11:16:29 | [diff] [blame] | 853 | self._is_directory = None |
[email protected] | 2a3ab7e | 2011-04-27 22:06:27 | [diff] [blame] | 854 | self._cached_changed_contents = None |
| 855 | self._cached_new_contents = None |
[email protected] | ea84ef1 | 2014-04-30 19:55:12 | [diff] [blame] | 856 | self._diff_cache = diff_cache |
tobiasjs | 2836bcf | 2016-08-16 11:08:16 | [diff] [blame] | 857 | logging.debug('%s(%s)', self.__class__.__name__, self._path) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 858 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 859 | def LocalPath(self): |
| 860 | """Returns the path of this file on the local disk relative to client root. |
Andrew Grieve | 92b8b99 | 2017-11-02 13:42:24 | [diff] [blame] | 861 | |
| 862 | This should be used for error messages but not for accessing files, |
| 863 | because presubmit checks are run with CWD=PresubmitLocalPath() (which is |
| 864 | often != client root). |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 865 | """ |
[email protected] | 15bdffa | 2009-05-29 11:16:29 | [diff] [blame] | 866 | return normpath(self._path) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 867 | |
| 868 | def AbsoluteLocalPath(self): |
| 869 | """Returns the absolute path of this file on the local disk. |
| 870 | """ |
[email protected] | 8e416c8 | 2009-10-06 04:30:44 | [diff] [blame] | 871 | return os.path.abspath(os.path.join(self._local_root, self.LocalPath())) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 872 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 873 | def Action(self): |
| 874 | """Returns the action on this opened file, e.g. A, M, D, etc.""" |
[email protected] | 15bdffa | 2009-05-29 11:16:29 | [diff] [blame] | 875 | return self._action |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 876 | |
agable | 0b65e73 | 2016-11-22 17:25:46 | [diff] [blame] | 877 | def IsTestableFile(self): |
[email protected] | 77c4f0f | 2009-05-29 18:53:04 | [diff] [blame] | 878 | """Returns True if the file is a text file and not a binary file. |
[email protected] | da8cddd | 2009-08-13 00:25:55 | [diff] [blame] | 879 | |
[email protected] | 77c4f0f | 2009-05-29 18:53:04 | [diff] [blame] | 880 | Deleted files are not text file.""" |
[email protected] | 1e08c00 | 2009-05-28 19:09:33 | [diff] [blame] | 881 | raise NotImplementedError() # Implement when needed |
| 882 | |
agable | 0b65e73 | 2016-11-22 17:25:46 | [diff] [blame] | 883 | def IsTextFile(self): |
| 884 | """An alias to IsTestableFile for backwards compatibility.""" |
| 885 | return self.IsTestableFile() |
| 886 | |
Daniel Cheng | 7a1f04d | 2017-03-22 02:12:31 | [diff] [blame] | 887 | def OldContents(self): |
| 888 | """Returns an iterator over the lines in the old version of file. |
| 889 | |
Daniel Cheng | 2da34fe | 2017-03-22 03:42:12 | [diff] [blame] | 890 | The old version is the file before any modifications in the user's |
| 891 | workspace, i.e. the "left hand side". |
Daniel Cheng | 7a1f04d | 2017-03-22 02:12:31 | [diff] [blame] | 892 | |
| 893 | Contents will be empty if the file is a directory or does not exist. |
| 894 | Note: The carriage returns (LF or CR) are stripped off. |
| 895 | """ |
| 896 | return self._diff_cache.GetOldContents(self.LocalPath(), |
| 897 | self._local_root).splitlines() |
| 898 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 899 | def NewContents(self): |
| 900 | """Returns an iterator over the lines in the new version of file. |
| 901 | |
| 902 | The new version is the file in the user's workspace, i.e. the "right hand |
| 903 | side". |
| 904 | |
| 905 | Contents will be empty if the file is a directory or does not exist. |
[email protected] | 2a3ab7e | 2011-04-27 22:06:27 | [diff] [blame] | 906 | Note: The carriage returns (LF or CR) are stripped off. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 907 | """ |
[email protected] | 2a3ab7e | 2011-04-27 22:06:27 | [diff] [blame] | 908 | if self._cached_new_contents is None: |
| 909 | self._cached_new_contents = [] |
agable | 0b65e73 | 2016-11-22 17:25:46 | [diff] [blame] | 910 | try: |
| 911 | self._cached_new_contents = gclient_utils.FileRead( |
| 912 | self.AbsoluteLocalPath(), 'rU').splitlines() |
| 913 | except IOError: |
| 914 | pass # File not found? That's fine; maybe it was deleted. |
[email protected] | 2a3ab7e | 2011-04-27 22:06:27 | [diff] [blame] | 915 | return self._cached_new_contents[:] |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 916 | |
[email protected] | ab05d58 | 2011-02-09 23:41:22 | [diff] [blame] | 917 | def ChangedContents(self): |
| 918 | """Returns a list of tuples (line number, line text) of all new lines. |
| 919 | |
| 920 | This relies on the scm diff output describing each changed code section |
| 921 | with a line of the form |
| 922 | |
| 923 | ^@@ <old line num>,<old size> <new line num>,<new size> @@$ |
| 924 | """ |
[email protected] | 2a3ab7e | 2011-04-27 22:06:27 | [diff] [blame] | 925 | if self._cached_changed_contents is not None: |
| 926 | return self._cached_changed_contents[:] |
| 927 | self._cached_changed_contents = [] |
[email protected] | ab05d58 | 2011-02-09 23:41:22 | [diff] [blame] | 928 | line_num = 0 |
| 929 | |
[email protected] | ab05d58 | 2011-02-09 23:41:22 | [diff] [blame] | 930 | for line in self.GenerateScmDiff().splitlines(): |
| 931 | m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line) |
| 932 | if m: |
| 933 | line_num = int(m.groups(1)[0]) |
| 934 | continue |
| 935 | if line.startswith('+') and not line.startswith('++'): |
[email protected] | 2a3ab7e | 2011-04-27 22:06:27 | [diff] [blame] | 936 | self._cached_changed_contents.append((line_num, line[1:])) |
[email protected] | ab05d58 | 2011-02-09 23:41:22 | [diff] [blame] | 937 | if not line.startswith('-'): |
| 938 | line_num += 1 |
[email protected] | 2a3ab7e | 2011-04-27 22:06:27 | [diff] [blame] | 939 | return self._cached_changed_contents[:] |
[email protected] | ab05d58 | 2011-02-09 23:41:22 | [diff] [blame] | 940 | |
[email protected] | 5de1397 | 2009-06-10 18:16:06 | [diff] [blame] | 941 | def __str__(self): |
| 942 | return self.LocalPath() |
| 943 | |
[email protected] | ab05d58 | 2011-02-09 23:41:22 | [diff] [blame] | 944 | def GenerateScmDiff(self): |
[email protected] | ff52619 | 2013-06-10 19:30:26 | [diff] [blame] | 945 | return self._diff_cache.GetDiff(self.LocalPath(), self._local_root) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 946 | |
[email protected] | 58407af | 2011-04-12 23:15:57 | [diff] [blame] | 947 | |
[email protected] | c70a220 | 2009-06-17 12:55:10 | [diff] [blame] | 948 | class GitAffectedFile(AffectedFile): |
| 949 | """Representation of a file in a change out of a git checkout.""" |
[email protected] | b17b55b | 2010-11-03 14:42:37 | [diff] [blame] | 950 | # Method 'NNN' is abstract in class 'NNN' but is not overridden |
Quinten Yearsley | b2cc4a9 | 2016-12-15 21:53:26 | [diff] [blame] | 951 | # pylint: disable=abstract-method |
[email protected] | c70a220 | 2009-06-17 12:55:10 | [diff] [blame] | 952 | |
[email protected] | ff52619 | 2013-06-10 19:30:26 | [diff] [blame] | 953 | DIFF_CACHE = _GitDiffCache |
| 954 | |
[email protected] | c70a220 | 2009-06-17 12:55:10 | [diff] [blame] | 955 | def __init__(self, *args, **kwargs): |
| 956 | AffectedFile.__init__(self, *args, **kwargs) |
| 957 | self._server_path = None |
agable | 0b65e73 | 2016-11-22 17:25:46 | [diff] [blame] | 958 | self._is_testable_file = None |
[email protected] | c70a220 | 2009-06-17 12:55:10 | [diff] [blame] | 959 | |
agable | 0b65e73 | 2016-11-22 17:25:46 | [diff] [blame] | 960 | def IsTestableFile(self): |
| 961 | if self._is_testable_file is None: |
[email protected] | c70a220 | 2009-06-17 12:55:10 | [diff] [blame] | 962 | if self.Action() == 'D': |
agable | 0b65e73 | 2016-11-22 17:25:46 | [diff] [blame] | 963 | # A deleted file is not testable. |
| 964 | self._is_testable_file = False |
[email protected] | c70a220 | 2009-06-17 12:55:10 | [diff] [blame] | 965 | else: |
agable | 0b65e73 | 2016-11-22 17:25:46 | [diff] [blame] | 966 | self._is_testable_file = os.path.isfile(self.AbsoluteLocalPath()) |
| 967 | return self._is_testable_file |
[email protected] | c70a220 | 2009-06-17 12:55:10 | [diff] [blame] | 968 | |
[email protected] | c193875 | 2011-04-12 23:11:13 | [diff] [blame] | 969 | |
[email protected] | 4ff922a | 2009-06-12 20:20:19 | [diff] [blame] | 970 | class Change(object): |
[email protected] | 6ebe68a | 2009-05-27 23:43:40 | [diff] [blame] | 971 | """Describe a change. |
| 972 | |
| 973 | Used directly by the presubmit scripts to query the current change being |
| 974 | tested. |
[email protected] | da8cddd | 2009-08-13 00:25:55 | [diff] [blame] | 975 | |
[email protected] | 6ebe68a | 2009-05-27 23:43:40 | [diff] [blame] | 976 | Instance members: |
[email protected] | ff52619 | 2013-06-10 19:30:26 | [diff] [blame] | 977 | tags: Dictionary of KEY=VALUE pairs found in the change description. |
[email protected] | 6ebe68a | 2009-05-27 23:43:40 | [diff] [blame] | 978 | self.KEY: equivalent to tags['KEY'] |
| 979 | """ |
| 980 | |
[email protected] | 4ff922a | 2009-06-12 20:20:19 | [diff] [blame] | 981 | _AFFECTED_FILES = AffectedFile |
| 982 | |
[email protected] | 6ebe68a | 2009-05-27 23:43:40 | [diff] [blame] | 983 | # Matches key/value (or "tag") lines in changelist descriptions. |
[email protected] | 428342a | 2011-11-10 15:46:33 | [diff] [blame] | 984 | TAG_LINE_RE = re.compile( |
[email protected] | c6f60e8 | 2013-04-19 17:01:57 | [diff] [blame] | 985 | '^[ \t]*(?P<key>[A-Z][A-Z_0-9]*)[ \t]*=[ \t]*(?P<value>.*?)[ \t]*$') |
[email protected] | c193875 | 2011-04-12 23:11:13 | [diff] [blame] | 986 | scm = '' |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 987 | |
[email protected] | 58407af | 2011-04-12 23:15:57 | [diff] [blame] | 988 | def __init__( |
[email protected] | ea84ef1 | 2014-04-30 19:55:12 | [diff] [blame] | 989 | self, name, description, local_root, files, issue, patchset, author, |
| 990 | upstream=None): |
[email protected] | 4ff922a | 2009-06-12 20:20:19 | [diff] [blame] | 991 | if files is None: |
| 992 | files = [] |
| 993 | self._name = name |
[email protected] | 8e416c8 | 2009-10-06 04:30:44 | [diff] [blame] | 994 | # Convert root into an absolute path. |
| 995 | self._local_root = os.path.abspath(local_root) |
[email protected] | ea84ef1 | 2014-04-30 19:55:12 | [diff] [blame] | 996 | self._upstream = upstream |
[email protected] | 4ff922a | 2009-06-12 20:20:19 | [diff] [blame] | 997 | self.issue = issue |
| 998 | self.patchset = patchset |
[email protected] | 58407af | 2011-04-12 23:15:57 | [diff] [blame] | 999 | self.author_email = author |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1000 | |
[email protected] | b5cded6 | 2014-03-25 17:47:57 | [diff] [blame] | 1001 | self._full_description = '' |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1002 | self.tags = {} |
[email protected] | b5cded6 | 2014-03-25 17:47:57 | [diff] [blame] | 1003 | self._description_without_tags = '' |
| 1004 | self.SetDescriptionText(description) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1005 | |
[email protected] | e085d81 | 2011-10-10 19:49:15 | [diff] [blame] | 1006 | assert all( |
| 1007 | (isinstance(f, (list, tuple)) and len(f) == 2) for f in files), files |
| 1008 | |
[email protected] | ea84ef1 | 2014-04-30 19:55:12 | [diff] [blame] | 1009 | diff_cache = self._AFFECTED_FILES.DIFF_CACHE(self._upstream) |
[email protected] | 6ebe68a | 2009-05-27 23:43:40 | [diff] [blame] | 1010 | self._affected_files = [ |
[email protected] | ff52619 | 2013-06-10 19:30:26 | [diff] [blame] | 1011 | self._AFFECTED_FILES(path, action.strip(), self._local_root, diff_cache) |
| 1012 | for action, path in files |
[email protected] | dbbeedc | 2009-05-22 20:26:17 | [diff] [blame] | 1013 | ] |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1014 | |
[email protected] | 92022ec | 2009-06-11 01:59:28 | [diff] [blame] | 1015 | def Name(self): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1016 | """Returns the change name.""" |
[email protected] | 6ebe68a | 2009-05-27 23:43:40 | [diff] [blame] | 1017 | return self._name |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1018 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1019 | def DescriptionText(self): |
| 1020 | """Returns the user-entered changelist description, minus tags. |
| 1021 | |
| 1022 | Any line in the user-provided description starting with e.g. "FOO=" |
| 1023 | (whitespace permitted before and around) is considered a tag line. Such |
| 1024 | lines are stripped out of the description this function returns. |
| 1025 | """ |
[email protected] | 6ebe68a | 2009-05-27 23:43:40 | [diff] [blame] | 1026 | return self._description_without_tags |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1027 | |
| 1028 | def FullDescriptionText(self): |
| 1029 | """Returns the complete changelist description including tags.""" |
[email protected] | 6ebe68a | 2009-05-27 23:43:40 | [diff] [blame] | 1030 | return self._full_description |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1031 | |
[email protected] | b5cded6 | 2014-03-25 17:47:57 | [diff] [blame] | 1032 | def SetDescriptionText(self, description): |
| 1033 | """Sets the full description text (including tags) to |description|. |
[email protected] | 92c3009 | 2014-04-15 00:30:37 | [diff] [blame] | 1034 | |
[email protected] | b5cded6 | 2014-03-25 17:47:57 | [diff] [blame] | 1035 | Also updates the list of tags.""" |
| 1036 | self._full_description = description |
| 1037 | |
| 1038 | # From the description text, build up a dictionary of key/value pairs |
| 1039 | # plus the description minus all key/value or "tag" lines. |
| 1040 | description_without_tags = [] |
| 1041 | self.tags = {} |
| 1042 | for line in self._full_description.splitlines(): |
| 1043 | m = self.TAG_LINE_RE.match(line) |
| 1044 | if m: |
| 1045 | self.tags[m.group('key')] = m.group('value') |
| 1046 | else: |
| 1047 | description_without_tags.append(line) |
| 1048 | |
| 1049 | # Change back to text and remove whitespace at end. |
| 1050 | self._description_without_tags = ( |
| 1051 | '\n'.join(description_without_tags).rstrip()) |
| 1052 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1053 | def RepositoryRoot(self): |
[email protected] | 92022ec | 2009-06-11 01:59:28 | [diff] [blame] | 1054 | """Returns the repository (checkout) root directory for this change, |
| 1055 | as an absolute path. |
| 1056 | """ |
[email protected] | 4ff922a | 2009-06-12 20:20:19 | [diff] [blame] | 1057 | return self._local_root |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1058 | |
| 1059 | def __getattr__(self, attr): |
[email protected] | 92022ec | 2009-06-11 01:59:28 | [diff] [blame] | 1060 | """Return tags directly as attributes on the object.""" |
| 1061 | if not re.match(r"^[A-Z_]*$", attr): |
| 1062 | raise AttributeError(self, attr) |
[email protected] | e1a524f | 2009-05-27 14:43:46 | [diff] [blame] | 1063 | return self.tags.get(attr) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1064 | |
Aaron Gable | fc03e67 | 2017-05-15 21:09:42 | [diff] [blame] | 1065 | def BugsFromDescription(self): |
| 1066 | """Returns all bugs referenced in the commit description.""" |
Aaron Gable | 12ef501 | 2017-05-15 21:29:00 | [diff] [blame] | 1067 | tags = [b.strip() for b in self.tags.get('BUG', '').split(',') if b.strip()] |
| 1068 | footers = git_footers.parse_footers(self._full_description).get('Bug', []) |
| 1069 | return sorted(set(tags + footers)) |
Aaron Gable | fc03e67 | 2017-05-15 21:09:42 | [diff] [blame] | 1070 | |
| 1071 | def ReviewersFromDescription(self): |
| 1072 | """Returns all reviewers listed in the commit description.""" |
Aaron Gable | 12ef501 | 2017-05-15 21:29:00 | [diff] [blame] | 1073 | # We don't support a "R:" git-footer for reviewers; that is in metadata. |
| 1074 | tags = [r.strip() for r in self.tags.get('R', '').split(',') if r.strip()] |
| 1075 | return sorted(set(tags)) |
Aaron Gable | fc03e67 | 2017-05-15 21:09:42 | [diff] [blame] | 1076 | |
| 1077 | def TBRsFromDescription(self): |
| 1078 | """Returns all TBR reviewers listed in the commit description.""" |
Aaron Gable | 12ef501 | 2017-05-15 21:29:00 | [diff] [blame] | 1079 | tags = [r.strip() for r in self.tags.get('TBR', '').split(',') if r.strip()] |
| 1080 | # TODO(agable): Remove support for 'Tbr:' when TBRs are programmatically |
| 1081 | # determined by self-CR+1s. |
| 1082 | footers = git_footers.parse_footers(self._full_description).get('Tbr', []) |
| 1083 | return sorted(set(tags + footers)) |
Aaron Gable | fc03e67 | 2017-05-15 21:09:42 | [diff] [blame] | 1084 | |
| 1085 | # TODO(agable): Delete these once we're sure they're unused. |
| 1086 | @property |
| 1087 | def BUG(self): |
| 1088 | return ','.join(self.BugsFromDescription()) |
| 1089 | @property |
| 1090 | def R(self): |
| 1091 | return ','.join(self.ReviewersFromDescription()) |
| 1092 | @property |
| 1093 | def TBR(self): |
| 1094 | return ','.join(self.TBRsFromDescription()) |
| 1095 | |
[email protected] | 40a3d0b | 2014-05-15 01:59:16 | [diff] [blame] | 1096 | def AllFiles(self, root=None): |
| 1097 | """List all files under source control in the repo.""" |
| 1098 | raise NotImplementedError() |
| 1099 | |
agable | 0b65e73 | 2016-11-22 17:25:46 | [diff] [blame] | 1100 | def AffectedFiles(self, include_deletes=True, file_filter=None): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1101 | """Returns a list of AffectedFile instances for all files in the change. |
| 1102 | |
| 1103 | Args: |
| 1104 | include_deletes: If false, deleted files will be filtered out. |
[email protected] | 5538e02 | 2011-05-12 17:53:16 | [diff] [blame] | 1105 | file_filter: An additional filter to apply. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1106 | |
| 1107 | Returns: |
| 1108 | [AffectedFile(path, action), AffectedFile(path, action)] |
| 1109 | """ |
agable | 0b65e73 | 2016-11-22 17:25:46 | [diff] [blame] | 1110 | affected = filter(file_filter, self._affected_files) |
[email protected] | 5538e02 | 2011-05-12 17:53:16 | [diff] [blame] | 1111 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1112 | if include_deletes: |
| 1113 | return affected |
Lei Zhang | 9611c4c | 2017-04-04 08:41:56 | [diff] [blame] | 1114 | return filter(lambda x: x.Action() != 'D', affected) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1115 | |
John Budorick | 1616237 | 2018-04-18 17:39:53 | [diff] [blame] | 1116 | def AffectedTestableFiles(self, include_deletes=None, **kwargs): |
[email protected] | 77c4f0f | 2009-05-29 18:53:04 | [diff] [blame] | 1117 | """Return a list of the existing text files in a change.""" |
| 1118 | if include_deletes is not None: |
agable | 0b65e73 | 2016-11-22 17:25:46 | [diff] [blame] | 1119 | warn("AffectedTeestableFiles(include_deletes=%s)" |
[email protected] | cb2985f | 2010-11-03 14:08:31 | [diff] [blame] | 1120 | " is deprecated and ignored" % str(include_deletes), |
| 1121 | category=DeprecationWarning, |
| 1122 | stacklevel=2) |
agable | 0b65e73 | 2016-11-22 17:25:46 | [diff] [blame] | 1123 | return filter(lambda x: x.IsTestableFile(), |
John Budorick | 1616237 | 2018-04-18 17:39:53 | [diff] [blame] | 1124 | self.AffectedFiles(include_deletes=False, **kwargs)) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1125 | |
agable | 0b65e73 | 2016-11-22 17:25:46 | [diff] [blame] | 1126 | def AffectedTextFiles(self, include_deletes=None): |
| 1127 | """An alias to AffectedTestableFiles for backwards compatibility.""" |
| 1128 | return self.AffectedTestableFiles(include_deletes=include_deletes) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1129 | |
agable | 0b65e73 | 2016-11-22 17:25:46 | [diff] [blame] | 1130 | def LocalPaths(self): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1131 | """Convenience function.""" |
agable | 0b65e73 | 2016-11-22 17:25:46 | [diff] [blame] | 1132 | return [af.LocalPath() for af in self.AffectedFiles()] |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1133 | |
agable | 0b65e73 | 2016-11-22 17:25:46 | [diff] [blame] | 1134 | def AbsoluteLocalPaths(self): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1135 | """Convenience function.""" |
agable | 0b65e73 | 2016-11-22 17:25:46 | [diff] [blame] | 1136 | return [af.AbsoluteLocalPath() for af in self.AffectedFiles()] |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1137 | |
| 1138 | def RightHandSideLines(self): |
| 1139 | """An iterator over all text lines in "new" version of changed files. |
| 1140 | |
| 1141 | Lists lines from new or modified text files in the change. |
| 1142 | |
| 1143 | This is useful for doing line-by-line regex checks, like checking for |
| 1144 | trailing whitespace. |
| 1145 | |
| 1146 | Yields: |
| 1147 | a 3 tuple: |
| 1148 | the AffectedFile instance of the current file; |
| 1149 | integer line number (1-based); and |
| 1150 | the contents of the line as a string. |
| 1151 | """ |
[email protected] | cb2985f | 2010-11-03 14:08:31 | [diff] [blame] | 1152 | return _RightHandSideLinesImpl( |
| 1153 | x for x in self.AffectedFiles(include_deletes=False) |
agable | 0b65e73 | 2016-11-22 17:25:46 | [diff] [blame] | 1154 | if x.IsTestableFile()) |
[email protected] | 40a3d0b | 2014-05-15 01:59:16 | [diff] [blame] | 1155 | |
Jochen Eisinger | d0573ec | 2017-04-13 08:55:06 | [diff] [blame] | 1156 | def OriginalOwnersFiles(self): |
| 1157 | """A map from path names of affected OWNERS files to their old content.""" |
| 1158 | def owners_file_filter(f): |
| 1159 | return 'OWNERS' in os.path.split(f.LocalPath())[1] |
| 1160 | files = self.AffectedFiles(file_filter=owners_file_filter) |
| 1161 | return dict([(f.LocalPath(), f.OldContents()) for f in files]) |
| 1162 | |
[email protected] | 4ff922a | 2009-06-12 20:20:19 | [diff] [blame] | 1163 | |
[email protected] | c70a220 | 2009-06-17 12:55:10 | [diff] [blame] | 1164 | class GitChange(Change): |
| 1165 | _AFFECTED_FILES = GitAffectedFile |
[email protected] | c193875 | 2011-04-12 23:11:13 | [diff] [blame] | 1166 | scm = 'git' |
[email protected] | da8cddd | 2009-08-13 00:25:55 | [diff] [blame] | 1167 | |
[email protected] | 40a3d0b | 2014-05-15 01:59:16 | [diff] [blame] | 1168 | def AllFiles(self, root=None): |
| 1169 | """List all files under source control in the repo.""" |
| 1170 | root = root or self.RepositoryRoot() |
| 1171 | return subprocess.check_output( |
Aaron Gable | 7817f02 | 2017-12-12 17:43:17 | [diff] [blame] | 1172 | ['git', '-c', 'core.quotePath=false', 'ls-files', '--', '.'], |
| 1173 | cwd=root).splitlines() |
[email protected] | 40a3d0b | 2014-05-15 01:59:16 | [diff] [blame] | 1174 | |
[email protected] | c70a220 | 2009-06-17 12:55:10 | [diff] [blame] | 1175 | |
[email protected] | 4661e0c | 2009-06-04 00:45:26 | [diff] [blame] | 1176 | def ListRelevantPresubmitFiles(files, root): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1177 | """Finds all presubmit files that apply to a given set of source files. |
| 1178 | |
[email protected] | b1901a6 | 2010-06-16 00:18:47 | [diff] [blame] | 1179 | If inherit-review-settings-ok is present right under root, looks for |
| 1180 | PRESUBMIT.py in directories enclosing root. |
| 1181 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1182 | Args: |
| 1183 | files: An iterable container containing file paths. |
[email protected] | 4661e0c | 2009-06-04 00:45:26 | [diff] [blame] | 1184 | root: Path where to stop searching. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1185 | |
| 1186 | Return: |
[email protected] | 4661e0c | 2009-06-04 00:45:26 | [diff] [blame] | 1187 | List of absolute paths of the existing PRESUBMIT.py scripts. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1188 | """ |
[email protected] | b1901a6 | 2010-06-16 00:18:47 | [diff] [blame] | 1189 | files = [normpath(os.path.join(root, f)) for f in files] |
| 1190 | |
| 1191 | # List all the individual directories containing files. |
| 1192 | directories = set([os.path.dirname(f) for f in files]) |
| 1193 | |
| 1194 | # Ignore root if inherit-review-settings-ok is present. |
| 1195 | if os.path.isfile(os.path.join(root, 'inherit-review-settings-ok')): |
| 1196 | root = None |
| 1197 | |
| 1198 | # Collect all unique directories that may contain PRESUBMIT.py. |
| 1199 | candidates = set() |
| 1200 | for directory in directories: |
| 1201 | while True: |
| 1202 | if directory in candidates: |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1203 | break |
[email protected] | b1901a6 | 2010-06-16 00:18:47 | [diff] [blame] | 1204 | candidates.add(directory) |
| 1205 | if directory == root: |
[email protected] | 4661e0c | 2009-06-04 00:45:26 | [diff] [blame] | 1206 | break |
[email protected] | b1901a6 | 2010-06-16 00:18:47 | [diff] [blame] | 1207 | parent_dir = os.path.dirname(directory) |
| 1208 | if parent_dir == directory: |
| 1209 | # We hit the system root directory. |
| 1210 | break |
| 1211 | directory = parent_dir |
| 1212 | |
| 1213 | # Look for PRESUBMIT.py in all candidate directories. |
| 1214 | results = [] |
| 1215 | for directory in sorted(list(candidates)): |
tobiasjs | ff061c0 | 2016-08-17 10:23:57 | [diff] [blame] | 1216 | try: |
| 1217 | for f in os.listdir(directory): |
| 1218 | p = os.path.join(directory, f) |
| 1219 | if os.path.isfile(p) and re.match( |
| 1220 | r'PRESUBMIT.*\.py$', f) and not f.startswith('PRESUBMIT_test'): |
| 1221 | results.append(p) |
| 1222 | except OSError: |
| 1223 | pass |
[email protected] | b1901a6 | 2010-06-16 00:18:47 | [diff] [blame] | 1224 | |
tobiasjs | 2836bcf | 2016-08-16 11:08:16 | [diff] [blame] | 1225 | logging.debug('Presubmit files: %s', ','.join(results)) |
[email protected] | b1901a6 | 2010-06-16 00:18:47 | [diff] [blame] | 1226 | return results |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1227 | |
| 1228 | |
[email protected] | 58a69cb | 2014-03-01 02:08:29 | [diff] [blame] | 1229 | class GetTryMastersExecuter(object): |
| 1230 | @staticmethod |
| 1231 | def ExecPresubmitScript(script_text, presubmit_path, project, change): |
| 1232 | """Executes GetPreferredTryMasters() from a single presubmit script. |
| 1233 | |
| 1234 | Args: |
| 1235 | script_text: The text of the presubmit script. |
| 1236 | presubmit_path: Project script to run. |
| 1237 | project: Project name to pass to presubmit script for bot selection. |
| 1238 | |
| 1239 | Return: |
| 1240 | A map of try masters to map of builders to set of tests. |
| 1241 | """ |
| 1242 | context = {} |
| 1243 | try: |
| 1244 | exec script_text in context |
| 1245 | except Exception, e: |
| 1246 | raise PresubmitFailure('"%s" had an exception.\n%s' |
| 1247 | % (presubmit_path, e)) |
| 1248 | |
| 1249 | function_name = 'GetPreferredTryMasters' |
| 1250 | if function_name not in context: |
| 1251 | return {} |
| 1252 | get_preferred_try_masters = context[function_name] |
| 1253 | if not len(inspect.getargspec(get_preferred_try_masters)[0]) == 2: |
| 1254 | raise PresubmitFailure( |
| 1255 | 'Expected function "GetPreferredTryMasters" to take two arguments.') |
| 1256 | return get_preferred_try_masters(project, change) |
| 1257 | |
| 1258 | |
[email protected] | 5626a92 | 2015-02-26 14:03:30 | [diff] [blame] | 1259 | class GetPostUploadExecuter(object): |
| 1260 | @staticmethod |
| 1261 | def ExecPresubmitScript(script_text, presubmit_path, cl, change): |
| 1262 | """Executes PostUploadHook() from a single presubmit script. |
| 1263 | |
| 1264 | Args: |
| 1265 | script_text: The text of the presubmit script. |
| 1266 | presubmit_path: Project script to run. |
| 1267 | cl: The Changelist object. |
| 1268 | change: The Change object. |
| 1269 | |
| 1270 | Return: |
| 1271 | A list of results objects. |
| 1272 | """ |
| 1273 | context = {} |
| 1274 | try: |
| 1275 | exec script_text in context |
| 1276 | except Exception, e: |
| 1277 | raise PresubmitFailure('"%s" had an exception.\n%s' |
| 1278 | % (presubmit_path, e)) |
| 1279 | |
| 1280 | function_name = 'PostUploadHook' |
| 1281 | if function_name not in context: |
| 1282 | return {} |
| 1283 | post_upload_hook = context[function_name] |
| 1284 | if not len(inspect.getargspec(post_upload_hook)[0]) == 3: |
| 1285 | raise PresubmitFailure( |
| 1286 | 'Expected function "PostUploadHook" to take three arguments.') |
| 1287 | return post_upload_hook(cl, change, OutputApi(False)) |
| 1288 | |
| 1289 | |
[email protected] | 58a69cb | 2014-03-01 02:08:29 | [diff] [blame] | 1290 | def _MergeMasters(masters1, masters2): |
| 1291 | """Merges two master maps. Merges also the tests of each builder.""" |
| 1292 | result = {} |
| 1293 | for (master, builders) in itertools.chain(masters1.iteritems(), |
| 1294 | masters2.iteritems()): |
| 1295 | new_builders = result.setdefault(master, {}) |
| 1296 | for (builder, tests) in builders.iteritems(): |
| 1297 | new_builders.setdefault(builder, set([])).update(tests) |
| 1298 | return result |
| 1299 | |
| 1300 | |
| 1301 | def DoGetTryMasters(change, |
| 1302 | changed_files, |
| 1303 | repository_root, |
| 1304 | default_presubmit, |
| 1305 | project, |
| 1306 | verbose, |
| 1307 | output_stream): |
| 1308 | """Get the list of try masters from the presubmit scripts. |
| 1309 | |
| 1310 | Args: |
| 1311 | changed_files: List of modified files. |
| 1312 | repository_root: The repository root. |
| 1313 | default_presubmit: A default presubmit script to execute in any case. |
| 1314 | project: Optional name of a project used in selecting trybots. |
| 1315 | verbose: Prints debug info. |
| 1316 | output_stream: A stream to write debug output to. |
| 1317 | |
| 1318 | Return: |
| 1319 | Map of try masters to map of builders to set of tests. |
| 1320 | """ |
| 1321 | presubmit_files = ListRelevantPresubmitFiles(changed_files, repository_root) |
| 1322 | if not presubmit_files and verbose: |
| 1323 | output_stream.write("Warning, no PRESUBMIT.py found.\n") |
| 1324 | results = {} |
| 1325 | executer = GetTryMastersExecuter() |
| 1326 | |
| 1327 | if default_presubmit: |
| 1328 | if verbose: |
| 1329 | output_stream.write("Running default presubmit script.\n") |
| 1330 | fake_path = os.path.join(repository_root, 'PRESUBMIT.py') |
| 1331 | results = _MergeMasters(results, executer.ExecPresubmitScript( |
| 1332 | default_presubmit, fake_path, project, change)) |
| 1333 | for filename in presubmit_files: |
| 1334 | filename = os.path.abspath(filename) |
| 1335 | if verbose: |
| 1336 | output_stream.write("Running %s\n" % filename) |
| 1337 | # Accept CRLF presubmit script. |
| 1338 | presubmit_script = gclient_utils.FileRead(filename, 'rU') |
| 1339 | results = _MergeMasters(results, executer.ExecPresubmitScript( |
| 1340 | presubmit_script, filename, project, change)) |
| 1341 | |
| 1342 | # Make sets to lists again for later JSON serialization. |
| 1343 | for builders in results.itervalues(): |
| 1344 | for builder in builders: |
| 1345 | builders[builder] = list(builders[builder]) |
| 1346 | |
| 1347 | if results and verbose: |
| 1348 | output_stream.write('%s\n' % str(results)) |
| 1349 | return results |
| 1350 | |
| 1351 | |
[email protected] | 5626a92 | 2015-02-26 14:03:30 | [diff] [blame] | 1352 | def DoPostUploadExecuter(change, |
| 1353 | cl, |
| 1354 | repository_root, |
| 1355 | verbose, |
| 1356 | output_stream): |
| 1357 | """Execute the post upload hook. |
| 1358 | |
| 1359 | Args: |
| 1360 | change: The Change object. |
| 1361 | cl: The Changelist object. |
| 1362 | repository_root: The repository root. |
| 1363 | verbose: Prints debug info. |
| 1364 | output_stream: A stream to write debug output to. |
| 1365 | """ |
| 1366 | presubmit_files = ListRelevantPresubmitFiles( |
| 1367 | change.LocalPaths(), repository_root) |
| 1368 | if not presubmit_files and verbose: |
| 1369 | output_stream.write("Warning, no PRESUBMIT.py found.\n") |
| 1370 | results = [] |
| 1371 | executer = GetPostUploadExecuter() |
| 1372 | # The root presubmit file should be executed after the ones in subdirectories. |
| 1373 | # i.e. the specific post upload hooks should run before the general ones. |
| 1374 | # Thus, reverse the order provided by ListRelevantPresubmitFiles. |
| 1375 | presubmit_files.reverse() |
| 1376 | |
| 1377 | for filename in presubmit_files: |
| 1378 | filename = os.path.abspath(filename) |
| 1379 | if verbose: |
| 1380 | output_stream.write("Running %s\n" % filename) |
| 1381 | # Accept CRLF presubmit script. |
| 1382 | presubmit_script = gclient_utils.FileRead(filename, 'rU') |
| 1383 | results.extend(executer.ExecPresubmitScript( |
| 1384 | presubmit_script, filename, cl, change)) |
| 1385 | output_stream.write('\n') |
| 1386 | if results: |
| 1387 | output_stream.write('** Post Upload Hook Messages **\n') |
| 1388 | for result in results: |
| 1389 | result.handle(output_stream) |
| 1390 | output_stream.write('\n') |
| 1391 | |
| 1392 | return results |
| 1393 | |
| 1394 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1395 | class PresubmitExecuter(object): |
Aaron Gable | 668c1d8 | 2018-04-03 17:19:16 | [diff] [blame] | 1396 | def __init__(self, change, committing, verbose, |
Edward Lesmes | 8e28279 | 2018-04-03 22:50:29 | [diff] [blame] | 1397 | gerrit_obj, dry_run=None, thread_pool=None, parallel=False): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1398 | """ |
| 1399 | Args: |
[email protected] | 4ff922a | 2009-06-12 20:20:19 | [diff] [blame] | 1400 | change: The Change object. |
agable | 92bec4f | 2016-08-24 16:27:27 | [diff] [blame] | 1401 | committing: True if 'git cl land' is running, False if 'git cl upload' is. |
[email protected] | 37b07a7 | 2016-04-29 16:42:28 | [diff] [blame] | 1402 | gerrit_obj: provides basic Gerrit codereview functionality. |
| 1403 | dry_run: if true, some Checks will be skipped. |
Edward Lesmes | 8e28279 | 2018-04-03 22:50:29 | [diff] [blame] | 1404 | parallel: if true, all tests reported via input_api.RunTests for all |
| 1405 | PRESUBMIT files will be run in parallel. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1406 | """ |
[email protected] | 4ff922a | 2009-06-12 20:20:19 | [diff] [blame] | 1407 | self.change = change |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1408 | self.committing = committing |
[email protected] | 37b07a7 | 2016-04-29 16:42:28 | [diff] [blame] | 1409 | self.gerrit = gerrit_obj |
[email protected] | 899e1c1 | 2011-04-07 17:03:18 | [diff] [blame] | 1410 | self.verbose = verbose |
[email protected] | 57bafac | 2016-04-28 05:09:03 | [diff] [blame] | 1411 | self.dry_run = dry_run |
Daniel Cheng | 7227d21 | 2017-11-17 16:12:37 | [diff] [blame] | 1412 | self.more_cc = [] |
Edward Lesmes | 8e28279 | 2018-04-03 22:50:29 | [diff] [blame] | 1413 | self.thread_pool = thread_pool |
| 1414 | self.parallel = parallel |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1415 | |
| 1416 | def ExecPresubmitScript(self, script_text, presubmit_path): |
| 1417 | """Executes a single presubmit script. |
| 1418 | |
| 1419 | Args: |
| 1420 | script_text: The text of the presubmit script. |
| 1421 | presubmit_path: The path to the presubmit file (this will be reported via |
| 1422 | input_api.PresubmitLocalPath()). |
| 1423 | |
| 1424 | Return: |
| 1425 | A list of result objects, empty if no problems. |
| 1426 | """ |
[email protected] | c6ef53a | 2014-11-04 00:13:54 | [diff] [blame] | 1427 | |
[email protected] | 8e416c8 | 2009-10-06 04:30:44 | [diff] [blame] | 1428 | # Change to the presubmit file's directory to support local imports. |
| 1429 | main_path = os.getcwd() |
| 1430 | os.chdir(os.path.dirname(presubmit_path)) |
| 1431 | |
| 1432 | # Load the presubmit script into context. |
[email protected] | 970c522 | 2011-03-12 00:32:24 | [diff] [blame] | 1433 | input_api = InputApi(self.change, presubmit_path, self.committing, |
Aaron Gable | 668c1d8 | 2018-04-03 17:19:16 | [diff] [blame] | 1434 | self.verbose, gerrit_obj=self.gerrit, |
Edward Lesmes | 8e28279 | 2018-04-03 22:50:29 | [diff] [blame] | 1435 | dry_run=self.dry_run, thread_pool=self.thread_pool, |
| 1436 | parallel=self.parallel) |
Daniel Cheng | 7227d21 | 2017-11-17 16:12:37 | [diff] [blame] | 1437 | output_api = OutputApi(self.committing) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1438 | context = {} |
[email protected] | 899e1c1 | 2011-04-07 17:03:18 | [diff] [blame] | 1439 | try: |
| 1440 | exec script_text in context |
| 1441 | except Exception, e: |
| 1442 | raise PresubmitFailure('"%s" had an exception.\n%s' % (presubmit_path, e)) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1443 | |
| 1444 | # These function names must change if we make substantial changes to |
| 1445 | # the presubmit API that are not backwards compatible. |
| 1446 | if self.committing: |
| 1447 | function_name = 'CheckChangeOnCommit' |
| 1448 | else: |
| 1449 | function_name = 'CheckChangeOnUpload' |
| 1450 | if function_name in context: |
Raphael Kubo da Costa | f2d1615 | 2017-11-10 17:07:58 | [diff] [blame] | 1451 | try: |
Daniel Cheng | 7227d21 | 2017-11-17 16:12:37 | [diff] [blame] | 1452 | context['__args'] = (input_api, output_api) |
Raphael Kubo da Costa | f2d1615 | 2017-11-10 17:07:58 | [diff] [blame] | 1453 | logging.debug('Running %s in %s', function_name, presubmit_path) |
| 1454 | result = eval(function_name + '(*__args)', context) |
| 1455 | logging.debug('Running %s done.', function_name) |
Daniel Cheng | d36fce4 | 2017-11-22 05:52:52 | [diff] [blame] | 1456 | self.more_cc.extend(output_api.more_cc) |
Raphael Kubo da Costa | f2d1615 | 2017-11-10 17:07:58 | [diff] [blame] | 1457 | finally: |
| 1458 | map(os.remove, input_api._named_temporary_files) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1459 | if not (isinstance(result, types.TupleType) or |
| 1460 | isinstance(result, types.ListType)): |
[email protected] | 899e1c1 | 2011-04-07 17:03:18 | [diff] [blame] | 1461 | raise PresubmitFailure( |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1462 | 'Presubmit functions must return a tuple or list') |
| 1463 | for item in result: |
| 1464 | if not isinstance(item, OutputApi.PresubmitResult): |
[email protected] | 899e1c1 | 2011-04-07 17:03:18 | [diff] [blame] | 1465 | raise PresubmitFailure( |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1466 | 'All presubmit results must be of types derived from ' |
| 1467 | 'output_api.PresubmitResult') |
| 1468 | else: |
| 1469 | result = () # no error since the script doesn't care about current event. |
| 1470 | |
[email protected] | 8e416c8 | 2009-10-06 04:30:44 | [diff] [blame] | 1471 | # Return the process to the original working directory. |
| 1472 | os.chdir(main_path) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1473 | return result |
| 1474 | |
[email protected] | 4ff922a | 2009-06-12 20:20:19 | [diff] [blame] | 1475 | def DoPresubmitChecks(change, |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1476 | committing, |
| 1477 | verbose, |
| 1478 | output_stream, |
[email protected] | 0ff1fab | 2009-05-22 13:08:15 | [diff] [blame] | 1479 | input_stream, |
[email protected] | b0dfd35 | 2009-06-10 14:12:54 | [diff] [blame] | 1480 | default_presubmit, |
[email protected] | 970c522 | 2011-03-12 00:32:24 | [diff] [blame] | 1481 | may_prompt, |
Aaron Gable | 668c1d8 | 2018-04-03 17:19:16 | [diff] [blame] | 1482 | gerrit_obj, |
Edward Lesmes | 8e28279 | 2018-04-03 22:50:29 | [diff] [blame] | 1483 | dry_run=None, |
| 1484 | parallel=False): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1485 | """Runs all presubmit checks that apply to the files in the change. |
| 1486 | |
| 1487 | This finds all PRESUBMIT.py files in directories enclosing the files in the |
| 1488 | change (up to the repository root) and calls the relevant entrypoint function |
| 1489 | depending on whether the change is being committed or uploaded. |
| 1490 | |
| 1491 | Prints errors, warnings and notifications. Prompts the user for warnings |
| 1492 | when needed. |
| 1493 | |
| 1494 | Args: |
[email protected] | 4ff922a | 2009-06-12 20:20:19 | [diff] [blame] | 1495 | change: The Change object. |
agable | 92bec4f | 2016-08-24 16:27:27 | [diff] [blame] | 1496 | committing: True if 'git cl land' is running, False if 'git cl upload' is. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1497 | verbose: Prints debug info. |
| 1498 | output_stream: A stream to write output from presubmit tests to. |
| 1499 | input_stream: A stream to read input from the user. |
[email protected] | 0ff1fab | 2009-05-22 13:08:15 | [diff] [blame] | 1500 | default_presubmit: A default presubmit script to execute in any case. |
Quinten Yearsley | 516fe7f | 2016-12-14 19:50:18 | [diff] [blame] | 1501 | may_prompt: Enable (y/n) questions on warning or error. If False, |
| 1502 | any questions are answered with yes by default. |
[email protected] | 37b07a7 | 2016-04-29 16:42:28 | [diff] [blame] | 1503 | gerrit_obj: provides basic Gerrit codereview functionality. |
[email protected] | 57bafac | 2016-04-28 05:09:03 | [diff] [blame] | 1504 | dry_run: if true, some Checks will be skipped. |
Edward Lesmes | 8e28279 | 2018-04-03 22:50:29 | [diff] [blame] | 1505 | parallel: if true, all tests specified by input_api.RunTests in all |
| 1506 | PRESUBMIT files will be run in parallel. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1507 | |
[email protected] | ce8e46b | 2009-06-26 22:31:51 | [diff] [blame] | 1508 | Warning: |
| 1509 | If may_prompt is true, output_stream SHOULD be sys.stdout and input_stream |
| 1510 | SHOULD be sys.stdin. |
| 1511 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1512 | Return: |
[email protected] | 5ac2101 | 2011-03-16 02:58:25 | [diff] [blame] | 1513 | A PresubmitOutput object. Use output.should_continue() to figure out |
| 1514 | if there were errors or warnings and the caller should abort. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1515 | """ |
[email protected] | ea7c855 | 2011-04-18 14:12:07 | [diff] [blame] | 1516 | old_environ = os.environ |
| 1517 | try: |
| 1518 | # Make sure python subprocesses won't generate .pyc files. |
| 1519 | os.environ = os.environ.copy() |
| 1520 | os.environ['PYTHONDONTWRITEBYTECODE'] = '1' |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1521 | |
[email protected] | ea7c855 | 2011-04-18 14:12:07 | [diff] [blame] | 1522 | output = PresubmitOutput(input_stream, output_stream) |
| 1523 | if committing: |
| 1524 | output.write("Running presubmit commit checks ...\n") |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1525 | else: |
[email protected] | ea7c855 | 2011-04-18 14:12:07 | [diff] [blame] | 1526 | output.write("Running presubmit upload checks ...\n") |
| 1527 | start_time = time.time() |
| 1528 | presubmit_files = ListRelevantPresubmitFiles( |
agable | 0b65e73 | 2016-11-22 17:25:46 | [diff] [blame] | 1529 | change.AbsoluteLocalPaths(), change.RepositoryRoot()) |
[email protected] | ea7c855 | 2011-04-18 14:12:07 | [diff] [blame] | 1530 | if not presubmit_files and verbose: |
[email protected] | fae707b | 2011-09-15 18:57:58 | [diff] [blame] | 1531 | output.write("Warning, no PRESUBMIT.py found.\n") |
[email protected] | ea7c855 | 2011-04-18 14:12:07 | [diff] [blame] | 1532 | results = [] |
Edward Lesmes | 8e28279 | 2018-04-03 22:50:29 | [diff] [blame] | 1533 | thread_pool = ThreadPool() |
Edward Lemur | 7e3c67f | 2018-07-20 20:52:49 | [diff] [blame] | 1534 | executer = PresubmitExecuter(change, committing, verbose, gerrit_obj, |
| 1535 | dry_run, thread_pool, parallel) |
[email protected] | ea7c855 | 2011-04-18 14:12:07 | [diff] [blame] | 1536 | if default_presubmit: |
| 1537 | if verbose: |
| 1538 | output.write("Running default presubmit script.\n") |
| 1539 | fake_path = os.path.join(change.RepositoryRoot(), 'PRESUBMIT.py') |
| 1540 | results += executer.ExecPresubmitScript(default_presubmit, fake_path) |
| 1541 | for filename in presubmit_files: |
| 1542 | filename = os.path.abspath(filename) |
| 1543 | if verbose: |
| 1544 | output.write("Running %s\n" % filename) |
| 1545 | # Accept CRLF presubmit script. |
| 1546 | presubmit_script = gclient_utils.FileRead(filename, 'rU') |
| 1547 | results += executer.ExecPresubmitScript(presubmit_script, filename) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1548 | |
Edward Lesmes | 8e28279 | 2018-04-03 22:50:29 | [diff] [blame] | 1549 | results += thread_pool.RunAsync() |
| 1550 | |
Daniel Cheng | 7227d21 | 2017-11-17 16:12:37 | [diff] [blame] | 1551 | output.more_cc.extend(executer.more_cc) |
[email protected] | ea7c855 | 2011-04-18 14:12:07 | [diff] [blame] | 1552 | errors = [] |
| 1553 | notifications = [] |
| 1554 | warnings = [] |
| 1555 | for result in results: |
| 1556 | if result.fatal: |
| 1557 | errors.append(result) |
| 1558 | elif result.should_prompt: |
| 1559 | warnings.append(result) |
| 1560 | else: |
| 1561 | notifications.append(result) |
[email protected] | ed9a083 | 2009-09-09 22:48:55 | [diff] [blame] | 1562 | |
[email protected] | ea7c855 | 2011-04-18 14:12:07 | [diff] [blame] | 1563 | output.write('\n') |
| 1564 | for name, items in (('Messages', notifications), |
| 1565 | ('Warnings', warnings), |
| 1566 | ('ERRORS', errors)): |
| 1567 | if items: |
| 1568 | output.write('** Presubmit %s **\n' % name) |
| 1569 | for item in items: |
| 1570 | item.handle(output) |
| 1571 | output.write('\n') |
[email protected] | ed9a083 | 2009-09-09 22:48:55 | [diff] [blame] | 1572 | |
[email protected] | ea7c855 | 2011-04-18 14:12:07 | [diff] [blame] | 1573 | total_time = time.time() - start_time |
| 1574 | if total_time > 1.0: |
| 1575 | output.write("Presubmit checks took %.1fs to calculate.\n\n" % total_time) |
[email protected] | ce8e46b | 2009-06-26 22:31:51 | [diff] [blame] | 1576 | |
Quinten Yearsley | 516fe7f | 2016-12-14 19:50:18 | [diff] [blame] | 1577 | if errors: |
| 1578 | output.fail() |
| 1579 | elif warnings: |
| 1580 | output.write('There were presubmit warnings. ') |
| 1581 | if may_prompt: |
| 1582 | output.prompt_yes_no('Are you sure you wish to continue? (y/N): ') |
| 1583 | else: |
| 1584 | output.write('Presubmit checks passed.\n') |
[email protected] | ea7c855 | 2011-04-18 14:12:07 | [diff] [blame] | 1585 | |
| 1586 | global _ASKED_FOR_FEEDBACK |
| 1587 | # Ask for feedback one time out of 5. |
| 1588 | if (len(results) and random.randint(0, 4) == 0 and not _ASKED_FOR_FEEDBACK): |
[email protected] | 1ce8e66 | 2014-01-14 15:23:00 | [diff] [blame] | 1589 | output.write( |
| 1590 | 'Was the presubmit check useful? If not, run "git cl presubmit -v"\n' |
| 1591 | 'to figure out which PRESUBMIT.py was run, then run git blame\n' |
| 1592 | 'on the file to figure out who to ask for help.\n') |
[email protected] | ea7c855 | 2011-04-18 14:12:07 | [diff] [blame] | 1593 | _ASKED_FOR_FEEDBACK = True |
| 1594 | return output |
| 1595 | finally: |
| 1596 | os.environ = old_environ |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1597 | |
| 1598 | |
| 1599 | def ScanSubDirs(mask, recursive): |
| 1600 | if not recursive: |
[email protected] | e57b09d | 2014-05-07 00:58:13 | [diff] [blame] | 1601 | return [x for x in glob.glob(mask) if x not in ('.svn', '.git')] |
Lei Zhang | 9611c4c | 2017-04-04 08:41:56 | [diff] [blame] | 1602 | |
| 1603 | results = [] |
| 1604 | for root, dirs, files in os.walk('.'): |
| 1605 | if '.svn' in dirs: |
| 1606 | dirs.remove('.svn') |
| 1607 | if '.git' in dirs: |
| 1608 | dirs.remove('.git') |
| 1609 | for name in files: |
| 1610 | if fnmatch.fnmatch(name, mask): |
| 1611 | results.append(os.path.join(root, name)) |
| 1612 | return results |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1613 | |
| 1614 | |
| 1615 | def ParseFiles(args, recursive): |
tobiasjs | 2836bcf | 2016-08-16 11:08:16 | [diff] [blame] | 1616 | logging.debug('Searching for %s', args) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1617 | files = [] |
| 1618 | for arg in args: |
[email protected] | e3608df | 2009-11-10 20:22:57 | [diff] [blame] | 1619 | files.extend([('M', f) for f in ScanSubDirs(arg, recursive)]) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1620 | return files |
| 1621 | |
| 1622 | |
[email protected] | 5c8c6de | 2011-03-18 16:20:18 | [diff] [blame] | 1623 | def load_files(options, args): |
| 1624 | """Tries to determine the SCM.""" |
[email protected] | 5c8c6de | 2011-03-18 16:20:18 | [diff] [blame] | 1625 | files = [] |
[email protected] | 5c8c6de | 2011-03-18 16:20:18 | [diff] [blame] | 1626 | if args: |
| 1627 | files = ParseFiles(args, options.recursive) |
agable | 0b65e73 | 2016-11-22 17:25:46 | [diff] [blame] | 1628 | change_scm = scm.determine_scm(options.root) |
| 1629 | if change_scm == 'git': |
[email protected] | 9b31f16 | 2012-01-26 19:02:31 | [diff] [blame] | 1630 | change_class = GitChange |
[email protected] | 2da1ade | 2014-04-30 17:40:45 | [diff] [blame] | 1631 | upstream = options.upstream or None |
[email protected] | 9b31f16 | 2012-01-26 19:02:31 | [diff] [blame] | 1632 | if not files: |
[email protected] | 2da1ade | 2014-04-30 17:40:45 | [diff] [blame] | 1633 | files = scm.GIT.CaptureStatus([], options.root, upstream) |
[email protected] | 5c8c6de | 2011-03-18 16:20:18 | [diff] [blame] | 1634 | else: |
tobiasjs | 2836bcf | 2016-08-16 11:08:16 | [diff] [blame] | 1635 | logging.info('Doesn\'t seem under source control. Got %d files', len(args)) |
[email protected] | 9b31f16 | 2012-01-26 19:02:31 | [diff] [blame] | 1636 | if not files: |
| 1637 | return None, None |
| 1638 | change_class = Change |
[email protected] | 5c8c6de | 2011-03-18 16:20:18 | [diff] [blame] | 1639 | return change_class, files |
| 1640 | |
| 1641 | |
[email protected] | 8a4a2bc | 2013-03-08 08:13:20 | [diff] [blame] | 1642 | @contextlib.contextmanager |
| 1643 | def canned_check_filter(method_names): |
| 1644 | filtered = {} |
| 1645 | try: |
| 1646 | for method_name in method_names: |
| 1647 | if not hasattr(presubmit_canned_checks, method_name): |
Aaron Gable | ecee74c | 2018-04-02 22:13:08 | [diff] [blame] | 1648 | logging.warn('Skipping unknown "canned" check %s' % method_name) |
| 1649 | continue |
[email protected] | 8a4a2bc | 2013-03-08 08:13:20 | [diff] [blame] | 1650 | filtered[method_name] = getattr(presubmit_canned_checks, method_name) |
| 1651 | setattr(presubmit_canned_checks, method_name, lambda *_a, **_kw: []) |
| 1652 | yield |
| 1653 | finally: |
| 1654 | for name, method in filtered.iteritems(): |
| 1655 | setattr(presubmit_canned_checks, name, method) |
| 1656 | |
[email protected] | ffeb2f3 | 2013-12-03 13:55:22 | [diff] [blame] | 1657 | |
[email protected] | 013731e | 2015-02-26 18:28:43 | [diff] [blame] | 1658 | def main(argv=None): |
[email protected] | 5c8c6de | 2011-03-18 16:20:18 | [diff] [blame] | 1659 | parser = optparse.OptionParser(usage="%prog [options] <files...>", |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1660 | version="%prog " + str(__version__)) |
[email protected] | c70a220 | 2009-06-17 12:55:10 | [diff] [blame] | 1661 | parser.add_option("-c", "--commit", action="store_true", default=False, |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1662 | help="Use commit instead of upload checks") |
[email protected] | c70a220 | 2009-06-17 12:55:10 | [diff] [blame] | 1663 | parser.add_option("-u", "--upload", action="store_false", dest='commit', |
| 1664 | help="Use upload instead of commit checks") |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1665 | parser.add_option("-r", "--recursive", action="store_true", |
| 1666 | help="Act recursively") |
[email protected] | 899e1c1 | 2011-04-07 17:03:18 | [diff] [blame] | 1667 | parser.add_option("-v", "--verbose", action="count", default=0, |
| 1668 | help="Use 2 times for more debug info") |
[email protected] | 4ff922a | 2009-06-12 20:20:19 | [diff] [blame] | 1669 | parser.add_option("--name", default='no name') |
[email protected] | 58407af | 2011-04-12 23:15:57 | [diff] [blame] | 1670 | parser.add_option("--author") |
[email protected] | 4ff922a | 2009-06-12 20:20:19 | [diff] [blame] | 1671 | parser.add_option("--description", default='') |
| 1672 | parser.add_option("--issue", type='int', default=0) |
| 1673 | parser.add_option("--patchset", type='int', default=0) |
[email protected] | b1901a6 | 2010-06-16 00:18:47 | [diff] [blame] | 1674 | parser.add_option("--root", default=os.getcwd(), |
| 1675 | help="Search for PRESUBMIT.py up to this directory. " |
| 1676 | "If inherit-review-settings-ok is present in this " |
| 1677 | "directory, parent directories up to the root file " |
| 1678 | "system directories will also be searched.") |
[email protected] | 2da1ade | 2014-04-30 17:40:45 | [diff] [blame] | 1679 | parser.add_option("--upstream", |
| 1680 | help="Git only: the base ref or upstream branch against " |
| 1681 | "which the diff should be computed.") |
[email protected] | c70a220 | 2009-06-17 12:55:10 | [diff] [blame] | 1682 | parser.add_option("--default_presubmit") |
| 1683 | parser.add_option("--may_prompt", action='store_true', default=False) |
[email protected] | 8a4a2bc | 2013-03-08 08:13:20 | [diff] [blame] | 1684 | parser.add_option("--skip_canned", action='append', default=[], |
| 1685 | help="A list of checks to skip which appear in " |
| 1686 | "presubmit_canned_checks. Can be provided multiple times " |
| 1687 | "to skip multiple canned checks.") |
[email protected] | 57bafac | 2016-04-28 05:09:03 | [diff] [blame] | 1688 | parser.add_option("--dry_run", action='store_true', |
| 1689 | help=optparse.SUPPRESS_HELP) |
[email protected] | 015ebae | 2016-04-25 19:37:22 | [diff] [blame] | 1690 | parser.add_option("--gerrit_url", help=optparse.SUPPRESS_HELP) |
[email protected] | 57bafac | 2016-04-28 05:09:03 | [diff] [blame] | 1691 | parser.add_option("--gerrit_fetch", action='store_true', |
| 1692 | help=optparse.SUPPRESS_HELP) |
Edward Lesmes | 8e28279 | 2018-04-03 22:50:29 | [diff] [blame] | 1693 | parser.add_option('--parallel', action='store_true', |
| 1694 | help='Run all tests specified by input_api.RunTests in all ' |
| 1695 | 'PRESUBMIT files in parallel.') |
[email protected] | 92c3009 | 2014-04-15 00:30:37 | [diff] [blame] | 1696 | |
[email protected] | 82e5f28 | 2011-03-17 14:08:55 | [diff] [blame] | 1697 | options, args = parser.parse_args(argv) |
[email protected] | 92c3009 | 2014-04-15 00:30:37 | [diff] [blame] | 1698 | |
[email protected] | 899e1c1 | 2011-04-07 17:03:18 | [diff] [blame] | 1699 | if options.verbose >= 2: |
[email protected] | 7444c50 | 2011-02-09 14:02:11 | [diff] [blame] | 1700 | logging.basicConfig(level=logging.DEBUG) |
[email protected] | 899e1c1 | 2011-04-07 17:03:18 | [diff] [blame] | 1701 | elif options.verbose: |
| 1702 | logging.basicConfig(level=logging.INFO) |
| 1703 | else: |
| 1704 | logging.basicConfig(level=logging.ERROR) |
[email protected] | 92c3009 | 2014-04-15 00:30:37 | [diff] [blame] | 1705 | |
[email protected] | 5c8c6de | 2011-03-18 16:20:18 | [diff] [blame] | 1706 | change_class, files = load_files(options, args) |
| 1707 | if not change_class: |
| 1708 | parser.error('For unversioned directory, <files> is not optional.') |
tobiasjs | 2836bcf | 2016-08-16 11:08:16 | [diff] [blame] | 1709 | logging.info('Found %d file(s).', len(files)) |
[email protected] | 92c3009 | 2014-04-15 00:30:37 | [diff] [blame] | 1710 | |
Aaron Gable | 668c1d8 | 2018-04-03 17:19:16 | [diff] [blame] | 1711 | gerrit_obj = None |
[email protected] | 015ebae | 2016-04-25 19:37:22 | [diff] [blame] | 1712 | if options.gerrit_url and options.gerrit_fetch: |
[email protected] | 83b1b23 | 2016-04-29 16:33:19 | [diff] [blame] | 1713 | assert options.issue and options.patchset |
[email protected] | 37b07a7 | 2016-04-29 16:42:28 | [diff] [blame] | 1714 | gerrit_obj = GerritAccessor(urlparse.urlparse(options.gerrit_url).netloc) |
| 1715 | options.author = gerrit_obj.GetChangeOwner(options.issue) |
| 1716 | options.description = gerrit_obj.GetChangeDescription(options.issue, |
| 1717 | options.patchset) |
[email protected] | 015ebae | 2016-04-25 19:37:22 | [diff] [blame] | 1718 | logging.info('Got author: "%s"', options.author) |
| 1719 | logging.info('Got description: """\n%s\n"""', options.description) |
| 1720 | |
[email protected] | 899e1c1 | 2011-04-07 17:03:18 | [diff] [blame] | 1721 | try: |
[email protected] | 8a4a2bc | 2013-03-08 08:13:20 | [diff] [blame] | 1722 | with canned_check_filter(options.skip_canned): |
| 1723 | results = DoPresubmitChecks( |
| 1724 | change_class(options.name, |
[email protected] | 57bafac | 2016-04-28 05:09:03 | [diff] [blame] | 1725 | options.description, |
| 1726 | options.root, |
| 1727 | files, |
| 1728 | options.issue, |
| 1729 | options.patchset, |
| 1730 | options.author, |
| 1731 | upstream=options.upstream), |
[email protected] | 8a4a2bc | 2013-03-08 08:13:20 | [diff] [blame] | 1732 | options.commit, |
| 1733 | options.verbose, |
| 1734 | sys.stdout, |
| 1735 | sys.stdin, |
| 1736 | options.default_presubmit, |
| 1737 | options.may_prompt, |
[email protected] | 37b07a7 | 2016-04-29 16:42:28 | [diff] [blame] | 1738 | gerrit_obj, |
Edward Lesmes | 8e28279 | 2018-04-03 22:50:29 | [diff] [blame] | 1739 | options.dry_run, |
| 1740 | options.parallel) |
[email protected] | 899e1c1 | 2011-04-07 17:03:18 | [diff] [blame] | 1741 | return not results.should_continue() |
[email protected] | 899e1c1 | 2011-04-07 17:03:18 | [diff] [blame] | 1742 | except PresubmitFailure, e: |
| 1743 | print >> sys.stderr, e |
| 1744 | print >> sys.stderr, 'Maybe your depot_tools is out of date?' |
[email protected] | 899e1c1 | 2011-04-07 17:03:18 | [diff] [blame] | 1745 | return 2 |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1746 | |
| 1747 | |
| 1748 | if __name__ == '__main__': |
[email protected] | 35625c7 | 2011-03-23 17:34:02 | [diff] [blame] | 1749 | fix_encoding.fix_encoding() |
[email protected] | 013731e | 2015-02-26 18:28:43 | [diff] [blame] | 1750 | try: |
| 1751 | sys.exit(main()) |
| 1752 | except KeyboardInterrupt: |
| 1753 | sys.stderr.write('interrupted\n') |
sergiyb | f8a3b38 | 2016-07-05 18:21:30 | [diff] [blame] | 1754 | sys.exit(2) |