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