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