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