[email protected] | 725f1c3 | 2011-04-01 20:24:54 | [diff] [blame] | 1 | #!/usr/bin/env python |
[email protected] | 3bbf294 | 2012-01-10 16:52:06 | [diff] [blame] | 2 | # Copyright (c) 2012 The Chromium Authors. All rights reserved. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3 | # Use of this source code is governed by a BSD-style license that can be |
| 4 | # found in the LICENSE file. |
| 5 | |
| 6 | """Enables directory-specific presubmit checks to run at upload and/or commit. |
| 7 | """ |
| 8 | |
[email protected] | f7d31f5 | 2014-01-03 20:14:46 | [diff] [blame] | 9 | __version__ = '1.8.0' |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 10 | |
| 11 | # TODO(joi) Add caching where appropriate/needed. The API is designed to allow |
| 12 | # caching (between all different invocations of presubmit scripts for a given |
| 13 | # change). We should add it as our presubmit scripts start feeling slow. |
| 14 | |
[email protected] | e72c5f5 | 2013-04-16 00:36:40 | [diff] [blame] | 15 | import cpplint |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 16 | import cPickle # Exposed through the API. |
| 17 | import cStringIO # Exposed through the API. |
[email protected] | 8a4a2bc | 2013-03-08 08:13:20 | [diff] [blame] | 18 | import contextlib |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 19 | import fnmatch |
| 20 | import glob |
[email protected] | 1516995 | 2011-09-27 14:30:53 | [diff] [blame] | 21 | import inspect |
[email protected] | 58a69cb | 2014-03-01 02:08:29 | [diff] [blame] | 22 | import itertools |
[email protected] | 4f6852c | 2012-04-20 20:39:20 | [diff] [blame] | 23 | import json # Exposed through the API. |
[email protected] | df1595a | 2009-06-11 02:00:13 | [diff] [blame] | 24 | import logging |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 25 | import marshal # Exposed through the API. |
[email protected] | bc11731 | 2013-04-20 03:57:56 | [diff] [blame] | 26 | import multiprocessing |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 27 | import optparse |
| 28 | import os # Somewhat exposed through the API. |
| 29 | import pickle # Exposed through the API. |
[email protected] | ce8e46b | 2009-06-26 22:31:51 | [diff] [blame] | 30 | import random |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 31 | import re # Exposed through the API. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 32 | import sys # Parts exposed through API. |
| 33 | import tempfile # Exposed through the API. |
[email protected] | 2a891dc | 2009-08-20 20:33:37 | [diff] [blame] | 34 | import time |
[email protected] | d7dccf5 | 2009-06-06 18:51:58 | [diff] [blame] | 35 | import traceback # Exposed through the API. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 36 | import types |
[email protected] | 1487d53 | 2009-06-06 00:22:57 | [diff] [blame] | 37 | import unittest # Exposed through the API. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 38 | import urllib2 # Exposed through the API. |
[email protected] | cb2985f | 2010-11-03 14:08:31 | [diff] [blame] | 39 | from warnings import warn |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 40 | |
| 41 | # Local imports. |
[email protected] | 35625c7 | 2011-03-23 17:34:02 | [diff] [blame] | 42 | import fix_encoding |
[email protected] | 5aeb7dd | 2009-11-17 18:09:01 | [diff] [blame] | 43 | import gclient_utils |
[email protected] | 2a00962 | 2011-03-01 02:43:31 | [diff] [blame] | 44 | import owners |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 45 | import presubmit_canned_checks |
[email protected] | 239f411 | 2011-06-03 20:08:23 | [diff] [blame] | 46 | import rietveld |
[email protected] | 5aeb7dd | 2009-11-17 18:09:01 | [diff] [blame] | 47 | import scm |
[email protected] | 84f4fe3 | 2011-04-06 13:26:45 | [diff] [blame] | 48 | import subprocess2 as subprocess # Exposed through the API. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 49 | |
| 50 | |
[email protected] | ce8e46b | 2009-06-26 22:31:51 | [diff] [blame] | 51 | # Ask for feedback only once in program lifetime. |
| 52 | _ASKED_FOR_FEEDBACK = False |
| 53 | |
| 54 | |
[email protected] | 899e1c1 | 2011-04-07 17:03:18 | [diff] [blame] | 55 | class PresubmitFailure(Exception): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 56 | pass |
| 57 | |
| 58 | |
[email protected] | ffeb2f3 | 2013-12-03 13:55:22 | [diff] [blame] | 59 | class CommandData(object): |
| 60 | def __init__(self, name, cmd, kwargs, message): |
| 61 | self.name = name |
| 62 | self.cmd = cmd |
| 63 | self.kwargs = kwargs |
| 64 | self.message = message |
| 65 | self.info = None |
| 66 | |
[email protected] | bc11731 | 2013-04-20 03:57:56 | [diff] [blame] | 67 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 68 | def normpath(path): |
| 69 | '''Version of os.path.normpath that also changes backward slashes to |
| 70 | forward slashes when not running on Windows. |
| 71 | ''' |
| 72 | # This is safe to always do because the Windows version of os.path.normpath |
| 73 | # will replace forward slashes with backward slashes. |
| 74 | path = path.replace(os.sep, '/') |
| 75 | return os.path.normpath(path) |
| 76 | |
[email protected] | cb2985f | 2010-11-03 14:08:31 | [diff] [blame] | 77 | |
[email protected] | cb2985f | 2010-11-03 14:08:31 | [diff] [blame] | 78 | def _RightHandSideLinesImpl(affected_files): |
| 79 | """Implements RightHandSideLines for InputApi and GclChange.""" |
| 80 | for af in affected_files: |
[email protected] | ab05d58 | 2011-02-09 23:41:22 | [diff] [blame] | 81 | lines = af.ChangedContents() |
[email protected] | cb2985f | 2010-11-03 14:08:31 | [diff] [blame] | 82 | for line in lines: |
[email protected] | ab05d58 | 2011-02-09 23:41:22 | [diff] [blame] | 83 | yield (af, line[0], line[1]) |
[email protected] | cb2985f | 2010-11-03 14:08:31 | [diff] [blame] | 84 | |
| 85 | |
[email protected] | 5ac2101 | 2011-03-16 02:58:25 | [diff] [blame] | 86 | class PresubmitOutput(object): |
| 87 | def __init__(self, input_stream=None, output_stream=None): |
| 88 | self.input_stream = input_stream |
| 89 | self.output_stream = output_stream |
| 90 | self.reviewers = [] |
| 91 | self.written_output = [] |
| 92 | self.error_count = 0 |
| 93 | |
| 94 | def prompt_yes_no(self, prompt_string): |
| 95 | self.write(prompt_string) |
| 96 | if self.input_stream: |
| 97 | response = self.input_stream.readline().strip().lower() |
| 98 | if response not in ('y', 'yes'): |
| 99 | self.fail() |
| 100 | else: |
| 101 | self.fail() |
| 102 | |
| 103 | def fail(self): |
| 104 | self.error_count += 1 |
| 105 | |
| 106 | def should_continue(self): |
| 107 | return not self.error_count |
| 108 | |
| 109 | def write(self, s): |
| 110 | self.written_output.append(s) |
| 111 | if self.output_stream: |
| 112 | self.output_stream.write(s) |
| 113 | |
| 114 | def getvalue(self): |
| 115 | return ''.join(self.written_output) |
| 116 | |
| 117 | |
[email protected] | bc11731 | 2013-04-20 03:57:56 | [diff] [blame] | 118 | # Top level object so multiprocessing can pickle |
| 119 | # Public access through OutputApi object. |
| 120 | class _PresubmitResult(object): |
| 121 | """Base class for result objects.""" |
| 122 | fatal = False |
| 123 | should_prompt = False |
| 124 | |
| 125 | def __init__(self, message, items=None, long_text=''): |
| 126 | """ |
| 127 | message: A short one-line message to indicate errors. |
| 128 | items: A list of short strings to indicate where errors occurred. |
| 129 | long_text: multi-line text output, e.g. from another tool |
| 130 | """ |
| 131 | self._message = message |
| 132 | self._items = items or [] |
| 133 | if items: |
| 134 | self._items = items |
| 135 | self._long_text = long_text.rstrip() |
| 136 | |
| 137 | def handle(self, output): |
| 138 | output.write(self._message) |
| 139 | output.write('\n') |
| 140 | for index, item in enumerate(self._items): |
| 141 | output.write(' ') |
| 142 | # Write separately in case it's unicode. |
| 143 | output.write(str(item)) |
| 144 | if index < len(self._items) - 1: |
| 145 | output.write(' \\') |
| 146 | output.write('\n') |
| 147 | if self._long_text: |
| 148 | output.write('\n***************\n') |
| 149 | # Write separately in case it's unicode. |
| 150 | output.write(self._long_text) |
| 151 | output.write('\n***************\n') |
| 152 | if self.fatal: |
| 153 | output.fail() |
| 154 | |
| 155 | |
| 156 | # Top level object so multiprocessing can pickle |
| 157 | # Public access through OutputApi object. |
| 158 | class _PresubmitAddReviewers(_PresubmitResult): |
| 159 | """Add some suggested reviewers to the change.""" |
| 160 | def __init__(self, reviewers): |
| 161 | super(_PresubmitAddReviewers, self).__init__('') |
| 162 | self.reviewers = reviewers |
| 163 | |
| 164 | def handle(self, output): |
| 165 | output.reviewers.extend(self.reviewers) |
| 166 | |
| 167 | |
| 168 | # Top level object so multiprocessing can pickle |
| 169 | # Public access through OutputApi object. |
| 170 | class _PresubmitError(_PresubmitResult): |
| 171 | """A hard presubmit error.""" |
| 172 | fatal = True |
| 173 | |
| 174 | |
| 175 | # Top level object so multiprocessing can pickle |
| 176 | # Public access through OutputApi object. |
| 177 | class _PresubmitPromptWarning(_PresubmitResult): |
| 178 | """An warning that prompts the user if they want to continue.""" |
| 179 | should_prompt = True |
| 180 | |
| 181 | |
| 182 | # Top level object so multiprocessing can pickle |
| 183 | # Public access through OutputApi object. |
| 184 | class _PresubmitNotifyResult(_PresubmitResult): |
| 185 | """Just print something to the screen -- but it's not even a warning.""" |
| 186 | pass |
| 187 | |
| 188 | |
| 189 | # Top level object so multiprocessing can pickle |
| 190 | # Public access through OutputApi object. |
| 191 | class _MailTextResult(_PresubmitResult): |
| 192 | """A warning that should be included in the review request email.""" |
| 193 | def __init__(self, *args, **kwargs): |
| 194 | super(_MailTextResult, self).__init__() |
| 195 | raise NotImplementedError() |
| 196 | |
| 197 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 198 | class OutputApi(object): |
[email protected] | a6d011e | 2013-03-26 17:31:49 | [diff] [blame] | 199 | """An instance of OutputApi gets passed to presubmit scripts so that they |
| 200 | can output various types of results. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 201 | """ |
[email protected] | bc11731 | 2013-04-20 03:57:56 | [diff] [blame] | 202 | PresubmitResult = _PresubmitResult |
| 203 | PresubmitAddReviewers = _PresubmitAddReviewers |
| 204 | PresubmitError = _PresubmitError |
| 205 | PresubmitPromptWarning = _PresubmitPromptWarning |
| 206 | PresubmitNotifyResult = _PresubmitNotifyResult |
| 207 | MailTextResult = _MailTextResult |
| 208 | |
[email protected] | a6d011e | 2013-03-26 17:31:49 | [diff] [blame] | 209 | def __init__(self, is_committing): |
| 210 | self.is_committing = is_committing |
| 211 | |
[email protected] | a6d011e | 2013-03-26 17:31:49 | [diff] [blame] | 212 | def PresubmitPromptOrNotify(self, *args, **kwargs): |
| 213 | """Warn the user when uploading, but only notify if committing.""" |
| 214 | if self.is_committing: |
| 215 | return self.PresubmitNotifyResult(*args, **kwargs) |
| 216 | return self.PresubmitPromptWarning(*args, **kwargs) |
| 217 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 218 | |
| 219 | class InputApi(object): |
| 220 | """An instance of this object is passed to presubmit scripts so they can |
| 221 | know stuff about the change they're looking at. |
| 222 | """ |
[email protected] | b17b55b | 2010-11-03 14:42:37 | [diff] [blame] | 223 | # Method could be a function |
| 224 | # pylint: disable=R0201 |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 225 | |
[email protected] | 3410d91 | 2009-06-09 20:56:16 | [diff] [blame] | 226 | # File extensions that are considered source files from a style guide |
| 227 | # perspective. Don't modify this list from a presubmit script! |
[email protected] | c33455a | 2011-06-24 19:14:18 | [diff] [blame] | 228 | # |
| 229 | # Files without an extension aren't included in the list. If you want to |
| 230 | # filter them as source files, add r"(^|.*?[\\\/])[^.]+$" to the white list. |
| 231 | # Note that ALL CAPS files are black listed in DEFAULT_BLACK_LIST below. |
[email protected] | 3410d91 | 2009-06-09 20:56:16 | [diff] [blame] | 232 | DEFAULT_WHITE_LIST = ( |
| 233 | # C++ and friends |
[email protected] | fe1211a | 2011-05-28 18:54:17 | [diff] [blame] | 234 | r".+\.c$", r".+\.cc$", r".+\.cpp$", r".+\.h$", r".+\.m$", r".+\.mm$", |
| 235 | r".+\.inl$", r".+\.asm$", r".+\.hxx$", r".+\.hpp$", r".+\.s$", r".+\.S$", |
[email protected] | 3410d91 | 2009-06-09 20:56:16 | [diff] [blame] | 236 | # Scripts |
[email protected] | fe1211a | 2011-05-28 18:54:17 | [diff] [blame] | 237 | r".+\.js$", r".+\.py$", r".+\.sh$", r".+\.rb$", r".+\.pl$", r".+\.pm$", |
[email protected] | 3410d91 | 2009-06-09 20:56:16 | [diff] [blame] | 238 | # Other |
[email protected] | ae7af92 | 2012-01-27 14:51:13 | [diff] [blame] | 239 | r".+\.java$", r".+\.mk$", r".+\.am$", r".+\.css$" |
[email protected] | 3410d91 | 2009-06-09 20:56:16 | [diff] [blame] | 240 | ) |
| 241 | |
| 242 | # Path regexp that should be excluded from being considered containing source |
| 243 | # files. Don't modify this list from a presubmit script! |
| 244 | DEFAULT_BLACK_LIST = ( |
[email protected] | 656326d | 2012-08-13 00:43:57 | [diff] [blame] | 245 | r"testing_support[\\\/]google_appengine[\\\/].*", |
[email protected] | 3410d91 | 2009-06-09 20:56:16 | [diff] [blame] | 246 | r".*\bexperimental[\\\/].*", |
| 247 | r".*\bthird_party[\\\/].*", |
| 248 | # Output directories (just in case) |
| 249 | r".*\bDebug[\\\/].*", |
| 250 | r".*\bRelease[\\\/].*", |
| 251 | r".*\bxcodebuild[\\\/].*", |
[email protected] | c1c9635 | 2013-10-09 19:50:27 | [diff] [blame] | 252 | r".*\bout[\\\/].*", |
[email protected] | 3410d91 | 2009-06-09 20:56:16 | [diff] [blame] | 253 | # All caps files like README and LICENCE. |
[email protected] | ab05d58 | 2011-02-09 23:41:22 | [diff] [blame] | 254 | r".*\b[A-Z0-9_]{2,}$", |
[email protected] | df1595a | 2009-06-11 02:00:13 | [diff] [blame] | 255 | # SCM (can happen in dual SCM configuration). (Slightly over aggressive) |
[email protected] | 5d0dc43 | 2011-01-03 02:40:37 | [diff] [blame] | 256 | r"(|.*[\\\/])\.git[\\\/].*", |
| 257 | r"(|.*[\\\/])\.svn[\\\/].*", |
[email protected] | 7ccb4bb | 2011-11-07 20:26:20 | [diff] [blame] | 258 | # There is no point in processing a patch file. |
| 259 | r".+\.diff$", |
| 260 | r".+\.patch$", |
[email protected] | 3410d91 | 2009-06-09 20:56:16 | [diff] [blame] | 261 | ) |
| 262 | |
[email protected] | cc73ad6 | 2011-07-06 17:39:26 | [diff] [blame] | 263 | def __init__(self, change, presubmit_path, is_committing, |
[email protected] | 239f411 | 2011-06-03 20:08:23 | [diff] [blame] | 264 | rietveld_obj, verbose): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 265 | """Builds an InputApi object. |
| 266 | |
| 267 | Args: |
[email protected] | 4ff922a | 2009-06-12 20:20:19 | [diff] [blame] | 268 | change: A presubmit.Change object. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 269 | presubmit_path: The path to the presubmit script being processed. |
[email protected] | d7dccf5 | 2009-06-06 18:51:58 | [diff] [blame] | 270 | is_committing: True if the change is about to be committed. |
[email protected] | 239f411 | 2011-06-03 20:08:23 | [diff] [blame] | 271 | rietveld_obj: rietveld.Rietveld client object |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 272 | """ |
[email protected] | 9711bba | 2009-05-22 23:51:39 | [diff] [blame] | 273 | # Version number of the presubmit_support script. |
| 274 | self.version = [int(x) for x in __version__.split('.')] |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 275 | self.change = change |
[email protected] | d7dccf5 | 2009-06-06 18:51:58 | [diff] [blame] | 276 | self.is_committing = is_committing |
[email protected] | 239f411 | 2011-06-03 20:08:23 | [diff] [blame] | 277 | self.rietveld = rietveld_obj |
[email protected] | cab38e9 | 2011-04-09 00:30:51 | [diff] [blame] | 278 | # TBD |
| 279 | self.host_url = 'http://codereview.chromium.org' |
| 280 | if self.rietveld: |
[email protected] | 239f411 | 2011-06-03 20:08:23 | [diff] [blame] | 281 | self.host_url = self.rietveld.url |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 282 | |
| 283 | # We expose various modules and functions as attributes of the input_api |
| 284 | # so that presubmit scripts don't have to import them. |
| 285 | self.basename = os.path.basename |
| 286 | self.cPickle = cPickle |
[email protected] | e72c5f5 | 2013-04-16 00:36:40 | [diff] [blame] | 287 | self.cpplint = cpplint |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 288 | self.cStringIO = cStringIO |
[email protected] | 17cc244 | 2012-10-17 21:12:09 | [diff] [blame] | 289 | self.glob = glob.glob |
[email protected] | fb11c7b | 2010-03-18 18:22:14 | [diff] [blame] | 290 | self.json = json |
[email protected] | 6fba34d | 2011-06-02 13:45:12 | [diff] [blame] | 291 | self.logging = logging.getLogger('PRESUBMIT') |
[email protected] | 2b5ce56 | 2011-03-31 16:15:44 | [diff] [blame] | 292 | self.os_listdir = os.listdir |
| 293 | self.os_walk = os.walk |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 294 | self.os_path = os.path |
| 295 | self.pickle = pickle |
| 296 | self.marshal = marshal |
| 297 | self.re = re |
| 298 | self.subprocess = subprocess |
| 299 | self.tempfile = tempfile |
[email protected] | 0d1bdea | 2011-03-24 22:54:38 | [diff] [blame] | 300 | self.time = time |
[email protected] | d7dccf5 | 2009-06-06 18:51:58 | [diff] [blame] | 301 | self.traceback = traceback |
[email protected] | 1487d53 | 2009-06-06 00:22:57 | [diff] [blame] | 302 | self.unittest = unittest |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 303 | self.urllib2 = urllib2 |
| 304 | |
[email protected] | c0b2297 | 2009-06-25 16:19:14 | [diff] [blame] | 305 | # To easily fork python. |
| 306 | self.python_executable = sys.executable |
| 307 | self.environ = os.environ |
| 308 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 309 | # InputApi.platform is the platform you're currently running on. |
| 310 | self.platform = sys.platform |
| 311 | |
| 312 | # The local path of the currently-being-processed presubmit script. |
[email protected] | 3d23524 | 2009-05-15 12:40:48 | [diff] [blame] | 313 | self._current_presubmit_path = os.path.dirname(presubmit_path) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 314 | |
| 315 | # We carry the canned checks so presubmit scripts can easily use them. |
| 316 | self.canned_checks = presubmit_canned_checks |
| 317 | |
[email protected] | 2a00962 | 2011-03-01 02:43:31 | [diff] [blame] | 318 | # TODO(dpranke): figure out a list of all approved owners for a repo |
| 319 | # in order to be able to handle wildcard OWNERS files? |
| 320 | self.owners_db = owners.Database(change.RepositoryRoot(), |
[email protected] | 17cc244 | 2012-10-17 21:12:09 | [diff] [blame] | 321 | fopen=file, os_path=self.os_path, glob=self.glob) |
[email protected] | 899e1c1 | 2011-04-07 17:03:18 | [diff] [blame] | 322 | self.verbose = verbose |
[email protected] | bc11731 | 2013-04-20 03:57:56 | [diff] [blame] | 323 | self.Command = CommandData |
[email protected] | 2a00962 | 2011-03-01 02:43:31 | [diff] [blame] | 324 | |
[email protected] | e72c5f5 | 2013-04-16 00:36:40 | [diff] [blame] | 325 | # Replace <hash_map> and <hash_set> as headers that need to be included |
[email protected] | 1827852 | 2013-06-11 22:42:32 | [diff] [blame] | 326 | # with "base/containers/hash_tables.h" instead. |
[email protected] | e72c5f5 | 2013-04-16 00:36:40 | [diff] [blame] | 327 | # Access to a protected member _XX of a client class |
| 328 | # pylint: disable=W0212 |
| 329 | self.cpplint._re_pattern_templates = [ |
[email protected] | 1827852 | 2013-06-11 22:42:32 | [diff] [blame] | 330 | (a, b, 'base/containers/hash_tables.h') |
[email protected] | e72c5f5 | 2013-04-16 00:36:40 | [diff] [blame] | 331 | if header in ('<hash_map>', '<hash_set>') else (a, b, header) |
| 332 | for (a, b, header) in cpplint._re_pattern_templates |
| 333 | ] |
| 334 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 335 | def PresubmitLocalPath(self): |
| 336 | """Returns the local path of the presubmit script currently being run. |
| 337 | |
| 338 | This is useful if you don't want to hard-code absolute paths in the |
| 339 | presubmit script. For example, It can be used to find another file |
| 340 | relative to the PRESUBMIT.py script, so the whole tree can be branched and |
| 341 | the presubmit script still works, without editing its content. |
| 342 | """ |
[email protected] | 3d23524 | 2009-05-15 12:40:48 | [diff] [blame] | 343 | return self._current_presubmit_path |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 344 | |
[email protected] | 1e08c00 | 2009-05-28 19:09:33 | [diff] [blame] | 345 | def DepotToLocalPath(self, depot_path): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 346 | """Translate a depot path to a local path (relative to client root). |
| 347 | |
| 348 | Args: |
| 349 | Depot path as a string. |
| 350 | |
| 351 | Returns: |
| 352 | The local path of the depot path under the user's current client, or None |
| 353 | if the file is not mapped. |
| 354 | |
| 355 | Remember to check for the None case and show an appropriate error! |
| 356 | """ |
[email protected] | d579fcf | 2011-12-13 20:36:03 | [diff] [blame] | 357 | return scm.SVN.CaptureLocalInfo([depot_path], self.change.RepositoryRoot() |
| 358 | ).get('Path') |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 359 | |
[email protected] | 1e08c00 | 2009-05-28 19:09:33 | [diff] [blame] | 360 | def LocalToDepotPath(self, local_path): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 361 | """Translate a local path to a depot path. |
| 362 | |
| 363 | Args: |
| 364 | Local path (relative to current directory, or absolute) as a string. |
| 365 | |
| 366 | Returns: |
| 367 | The depot path (SVN URL) of the file if mapped, otherwise None. |
| 368 | """ |
[email protected] | d579fcf | 2011-12-13 20:36:03 | [diff] [blame] | 369 | return scm.SVN.CaptureLocalInfo([local_path], self.change.RepositoryRoot() |
| 370 | ).get('URL') |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 371 | |
[email protected] | 5538e02 | 2011-05-12 17:53:16 | [diff] [blame] | 372 | def AffectedFiles(self, include_dirs=False, include_deletes=True, |
| 373 | file_filter=None): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 374 | """Same as input_api.change.AffectedFiles() except only lists files |
| 375 | (and optionally directories) in the same directory as the current presubmit |
| 376 | script, or subdirectories thereof. |
| 377 | """ |
[email protected] | 3d23524 | 2009-05-15 12:40:48 | [diff] [blame] | 378 | dir_with_slash = normpath("%s/" % self.PresubmitLocalPath()) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 379 | if len(dir_with_slash) == 1: |
| 380 | dir_with_slash = '' |
[email protected] | 5538e02 | 2011-05-12 17:53:16 | [diff] [blame] | 381 | |
[email protected] | 4661e0c | 2009-06-04 00:45:26 | [diff] [blame] | 382 | return filter( |
| 383 | lambda x: normpath(x.AbsoluteLocalPath()).startswith(dir_with_slash), |
[email protected] | 5538e02 | 2011-05-12 17:53:16 | [diff] [blame] | 384 | self.change.AffectedFiles(include_dirs, include_deletes, file_filter)) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 385 | |
| 386 | def LocalPaths(self, include_dirs=False): |
| 387 | """Returns local paths of input_api.AffectedFiles().""" |
| 388 | return [af.LocalPath() for af in self.AffectedFiles(include_dirs)] |
| 389 | |
| 390 | def AbsoluteLocalPaths(self, include_dirs=False): |
| 391 | """Returns absolute local paths of input_api.AffectedFiles().""" |
| 392 | return [af.AbsoluteLocalPath() for af in self.AffectedFiles(include_dirs)] |
| 393 | |
| 394 | def ServerPaths(self, include_dirs=False): |
| 395 | """Returns server paths of input_api.AffectedFiles().""" |
| 396 | return [af.ServerPath() for af in self.AffectedFiles(include_dirs)] |
| 397 | |
[email protected] | 77c4f0f | 2009-05-29 18:53:04 | [diff] [blame] | 398 | def AffectedTextFiles(self, include_deletes=None): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 399 | """Same as input_api.change.AffectedTextFiles() except only lists files |
| 400 | in the same directory as the current presubmit script, or subdirectories |
| 401 | thereof. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 402 | """ |
[email protected] | 77c4f0f | 2009-05-29 18:53:04 | [diff] [blame] | 403 | if include_deletes is not None: |
[email protected] | cb2985f | 2010-11-03 14:08:31 | [diff] [blame] | 404 | warn("AffectedTextFiles(include_deletes=%s)" |
| 405 | " is deprecated and ignored" % str(include_deletes), |
| 406 | category=DeprecationWarning, |
| 407 | stacklevel=2) |
[email protected] | 77c4f0f | 2009-05-29 18:53:04 | [diff] [blame] | 408 | return filter(lambda x: x.IsTextFile(), |
| 409 | self.AffectedFiles(include_dirs=False, include_deletes=False)) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 410 | |
[email protected] | 3410d91 | 2009-06-09 20:56:16 | [diff] [blame] | 411 | def FilterSourceFile(self, affected_file, white_list=None, black_list=None): |
| 412 | """Filters out files that aren't considered "source file". |
| 413 | |
| 414 | If white_list or black_list is None, InputApi.DEFAULT_WHITE_LIST |
| 415 | and InputApi.DEFAULT_BLACK_LIST is used respectively. |
| 416 | |
| 417 | The lists will be compiled as regular expression and |
| 418 | AffectedFile.LocalPath() needs to pass both list. |
| 419 | |
| 420 | Note: Copy-paste this function to suit your needs or use a lambda function. |
| 421 | """ |
[email protected] | cb2985f | 2010-11-03 14:08:31 | [diff] [blame] | 422 | def Find(affected_file, items): |
[email protected] | ab05d58 | 2011-02-09 23:41:22 | [diff] [blame] | 423 | local_path = affected_file.LocalPath() |
[email protected] | cb2985f | 2010-11-03 14:08:31 | [diff] [blame] | 424 | for item in items: |
[email protected] | df1595a | 2009-06-11 02:00:13 | [diff] [blame] | 425 | if self.re.match(item, local_path): |
| 426 | logging.debug("%s matched %s" % (item, local_path)) |
[email protected] | 3410d91 | 2009-06-09 20:56:16 | [diff] [blame] | 427 | return True |
| 428 | return False |
| 429 | return (Find(affected_file, white_list or self.DEFAULT_WHITE_LIST) and |
| 430 | not Find(affected_file, black_list or self.DEFAULT_BLACK_LIST)) |
| 431 | |
| 432 | def AffectedSourceFiles(self, source_file): |
| 433 | """Filter the list of AffectedTextFiles by the function source_file. |
| 434 | |
| 435 | If source_file is None, InputApi.FilterSourceFile() is used. |
| 436 | """ |
| 437 | if not source_file: |
| 438 | source_file = self.FilterSourceFile |
| 439 | return filter(source_file, self.AffectedTextFiles()) |
| 440 | |
| 441 | def RightHandSideLines(self, source_file_filter=None): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 442 | """An iterator over all text lines in "new" version of changed files. |
| 443 | |
| 444 | Only lists lines from new or modified text files in the change that are |
| 445 | contained by the directory of the currently executing presubmit script. |
| 446 | |
| 447 | This is useful for doing line-by-line regex checks, like checking for |
| 448 | trailing whitespace. |
| 449 | |
| 450 | Yields: |
| 451 | a 3 tuple: |
| 452 | the AffectedFile instance of the current file; |
| 453 | integer line number (1-based); and |
| 454 | the contents of the line as a string. |
[email protected] | 1487d53 | 2009-06-06 00:22:57 | [diff] [blame] | 455 | |
[email protected] | 2a3ab7e | 2011-04-27 22:06:27 | [diff] [blame] | 456 | Note: The carriage return (LF or CR) is stripped off. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 457 | """ |
[email protected] | 3410d91 | 2009-06-09 20:56:16 | [diff] [blame] | 458 | files = self.AffectedSourceFiles(source_file_filter) |
[email protected] | cb2985f | 2010-11-03 14:08:31 | [diff] [blame] | 459 | return _RightHandSideLinesImpl(files) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 460 | |
[email protected] | e3608df | 2009-11-10 20:22:57 | [diff] [blame] | 461 | def ReadFile(self, file_item, mode='r'): |
[email protected] | 44a17ad | 2009-06-08 14:14:35 | [diff] [blame] | 462 | """Reads an arbitrary file. |
[email protected] | da8cddd | 2009-08-13 00:25:55 | [diff] [blame] | 463 | |
[email protected] | 44a17ad | 2009-06-08 14:14:35 | [diff] [blame] | 464 | Deny reading anything outside the repository. |
| 465 | """ |
[email protected] | e3608df | 2009-11-10 20:22:57 | [diff] [blame] | 466 | if isinstance(file_item, AffectedFile): |
| 467 | file_item = file_item.AbsoluteLocalPath() |
| 468 | if not file_item.startswith(self.change.RepositoryRoot()): |
[email protected] | 44a17ad | 2009-06-08 14:14:35 | [diff] [blame] | 469 | raise IOError('Access outside the repository root is denied.') |
[email protected] | 5aeb7dd | 2009-11-17 18:09:01 | [diff] [blame] | 470 | return gclient_utils.FileRead(file_item, mode) |
[email protected] | 44a17ad | 2009-06-08 14:14:35 | [diff] [blame] | 471 | |
[email protected] | cc73ad6 | 2011-07-06 17:39:26 | [diff] [blame] | 472 | @property |
| 473 | def tbr(self): |
| 474 | """Returns if a change is TBR'ed.""" |
| 475 | return 'TBR' in self.change.tags |
| 476 | |
[email protected] | ffeb2f3 | 2013-12-03 13:55:22 | [diff] [blame] | 477 | def RunTests(self, tests_mix, parallel=True): |
[email protected] | bc11731 | 2013-04-20 03:57:56 | [diff] [blame] | 478 | tests = [] |
| 479 | msgs = [] |
| 480 | for t in tests_mix: |
| 481 | if isinstance(t, OutputApi.PresubmitResult): |
| 482 | msgs.append(t) |
| 483 | else: |
| 484 | assert issubclass(t.message, _PresubmitResult) |
| 485 | tests.append(t) |
[email protected] | ffeb2f3 | 2013-12-03 13:55:22 | [diff] [blame] | 486 | if self.verbose: |
| 487 | t.info = _PresubmitNotifyResult |
[email protected] | 5678d33 | 2013-05-18 01:34:14 | [diff] [blame] | 488 | if len(tests) > 1 and parallel: |
[email protected] | bc11731 | 2013-04-20 03:57:56 | [diff] [blame] | 489 | pool = multiprocessing.Pool() |
| 490 | # async recipe works around multiprocessing bug handling Ctrl-C |
| 491 | msgs.extend(pool.map_async(CallCommand, tests).get(99999)) |
| 492 | pool.close() |
| 493 | pool.join() |
| 494 | else: |
| 495 | msgs.extend(map(CallCommand, tests)) |
| 496 | return [m for m in msgs if m] |
| 497 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 498 | |
[email protected] | ff52619 | 2013-06-10 19:30:26 | [diff] [blame] | 499 | class _DiffCache(object): |
| 500 | """Caches diffs retrieved from a particular SCM.""" |
| 501 | |
| 502 | def GetDiff(self, path, local_root): |
| 503 | """Get the diff for a particular path.""" |
| 504 | raise NotImplementedError() |
| 505 | |
| 506 | |
| 507 | class _SvnDiffCache(_DiffCache): |
| 508 | """DiffCache implementation for subversion.""" |
| 509 | def __init__(self): |
| 510 | super(_SvnDiffCache, self).__init__() |
| 511 | self._diffs_by_file = {} |
| 512 | |
| 513 | def GetDiff(self, path, local_root): |
| 514 | if path not in self._diffs_by_file: |
| 515 | self._diffs_by_file[path] = scm.SVN.GenerateDiff([path], local_root, |
| 516 | False, None) |
| 517 | return self._diffs_by_file[path] |
| 518 | |
| 519 | |
| 520 | class _GitDiffCache(_DiffCache): |
| 521 | """DiffCache implementation for git; gets all file diffs at once.""" |
| 522 | def __init__(self): |
| 523 | super(_GitDiffCache, self).__init__() |
| 524 | self._diffs_by_file = None |
| 525 | |
| 526 | def GetDiff(self, path, local_root): |
| 527 | if not self._diffs_by_file: |
| 528 | # Compute a single diff for all files and parse the output; should |
| 529 | # with git this is much faster than computing one diff for each file. |
| 530 | diffs = {} |
| 531 | |
| 532 | # Don't specify any filenames below, because there are command line length |
| 533 | # limits on some platforms and GenerateDiff would fail. |
| 534 | unified_diff = scm.GIT.GenerateDiff(local_root, files=[], full_move=True) |
| 535 | |
| 536 | # This regex matches the path twice, separated by a space. Note that |
| 537 | # filename itself may contain spaces. |
| 538 | file_marker = re.compile('^diff --git (?P<filename>.*) (?P=filename)$') |
| 539 | current_diff = [] |
| 540 | keep_line_endings = True |
| 541 | for x in unified_diff.splitlines(keep_line_endings): |
| 542 | match = file_marker.match(x) |
| 543 | if match: |
| 544 | # Marks the start of a new per-file section. |
| 545 | diffs[match.group('filename')] = current_diff = [x] |
| 546 | elif x.startswith('diff --git'): |
| 547 | raise PresubmitFailure('Unexpected diff line: %s' % x) |
| 548 | else: |
| 549 | current_diff.append(x) |
| 550 | |
| 551 | self._diffs_by_file = dict( |
| 552 | (normpath(path), ''.join(diff)) for path, diff in diffs.items()) |
| 553 | |
| 554 | if path not in self._diffs_by_file: |
| 555 | raise PresubmitFailure( |
| 556 | 'Unified diff did not contain entry for file %s' % path) |
| 557 | |
| 558 | return self._diffs_by_file[path] |
| 559 | |
| 560 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 561 | class AffectedFile(object): |
| 562 | """Representation of a file in a change.""" |
[email protected] | ff52619 | 2013-06-10 19:30:26 | [diff] [blame] | 563 | |
| 564 | DIFF_CACHE = _DiffCache |
| 565 | |
[email protected] | b17b55b | 2010-11-03 14:42:37 | [diff] [blame] | 566 | # Method could be a function |
| 567 | # pylint: disable=R0201 |
[email protected] | ff52619 | 2013-06-10 19:30:26 | [diff] [blame] | 568 | def __init__(self, path, action, repository_root, diff_cache=None): |
[email protected] | 15bdffa | 2009-05-29 11:16:29 | [diff] [blame] | 569 | self._path = path |
| 570 | self._action = action |
[email protected] | 4ff922a | 2009-06-12 20:20:19 | [diff] [blame] | 571 | self._local_root = repository_root |
[email protected] | 15bdffa | 2009-05-29 11:16:29 | [diff] [blame] | 572 | self._is_directory = None |
| 573 | self._properties = {} |
[email protected] | 2a3ab7e | 2011-04-27 22:06:27 | [diff] [blame] | 574 | self._cached_changed_contents = None |
| 575 | self._cached_new_contents = None |
[email protected] | ff52619 | 2013-06-10 19:30:26 | [diff] [blame] | 576 | if diff_cache: |
| 577 | self._diff_cache = diff_cache |
| 578 | else: |
| 579 | self._diff_cache = self.DIFF_CACHE() |
[email protected] | 5d0dc43 | 2011-01-03 02:40:37 | [diff] [blame] | 580 | logging.debug('%s(%s)' % (self.__class__.__name__, self._path)) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 581 | |
| 582 | def ServerPath(self): |
| 583 | """Returns a path string that identifies the file in the SCM system. |
| 584 | |
| 585 | Returns the empty string if the file does not exist in SCM. |
| 586 | """ |
[email protected] | ff52619 | 2013-06-10 19:30:26 | [diff] [blame] | 587 | return '' |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 588 | |
| 589 | def LocalPath(self): |
| 590 | """Returns the path of this file on the local disk relative to client root. |
| 591 | """ |
[email protected] | 15bdffa | 2009-05-29 11:16:29 | [diff] [blame] | 592 | return normpath(self._path) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 593 | |
| 594 | def AbsoluteLocalPath(self): |
| 595 | """Returns the absolute path of this file on the local disk. |
| 596 | """ |
[email protected] | 8e416c8 | 2009-10-06 04:30:44 | [diff] [blame] | 597 | return os.path.abspath(os.path.join(self._local_root, self.LocalPath())) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 598 | |
| 599 | def IsDirectory(self): |
| 600 | """Returns true if this object is a directory.""" |
[email protected] | 15bdffa | 2009-05-29 11:16:29 | [diff] [blame] | 601 | if self._is_directory is None: |
| 602 | path = self.AbsoluteLocalPath() |
| 603 | self._is_directory = (os.path.exists(path) and |
| 604 | os.path.isdir(path)) |
| 605 | return self._is_directory |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 606 | |
| 607 | def Action(self): |
| 608 | """Returns the action on this opened file, e.g. A, M, D, etc.""" |
[email protected] | dbbeedc | 2009-05-22 20:26:17 | [diff] [blame] | 609 | # TODO(maruel): Somewhat crappy, Could be "A" or "A +" for svn but |
| 610 | # different for other SCM. |
[email protected] | 15bdffa | 2009-05-29 11:16:29 | [diff] [blame] | 611 | return self._action |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 612 | |
[email protected] | dbbeedc | 2009-05-22 20:26:17 | [diff] [blame] | 613 | def Property(self, property_name): |
| 614 | """Returns the specified SCM property of this file, or None if no such |
| 615 | property. |
| 616 | """ |
[email protected] | 15bdffa | 2009-05-29 11:16:29 | [diff] [blame] | 617 | return self._properties.get(property_name, None) |
[email protected] | dbbeedc | 2009-05-22 20:26:17 | [diff] [blame] | 618 | |
[email protected] | 1e08c00 | 2009-05-28 19:09:33 | [diff] [blame] | 619 | def IsTextFile(self): |
[email protected] | 77c4f0f | 2009-05-29 18:53:04 | [diff] [blame] | 620 | """Returns True if the file is a text file and not a binary file. |
[email protected] | da8cddd | 2009-08-13 00:25:55 | [diff] [blame] | 621 | |
[email protected] | 77c4f0f | 2009-05-29 18:53:04 | [diff] [blame] | 622 | Deleted files are not text file.""" |
[email protected] | 1e08c00 | 2009-05-28 19:09:33 | [diff] [blame] | 623 | raise NotImplementedError() # Implement when needed |
| 624 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 625 | def NewContents(self): |
| 626 | """Returns an iterator over the lines in the new version of file. |
| 627 | |
| 628 | The new version is the file in the user's workspace, i.e. the "right hand |
| 629 | side". |
| 630 | |
| 631 | Contents will be empty if the file is a directory or does not exist. |
[email protected] | 2a3ab7e | 2011-04-27 22:06:27 | [diff] [blame] | 632 | Note: The carriage returns (LF or CR) are stripped off. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 633 | """ |
[email protected] | 2a3ab7e | 2011-04-27 22:06:27 | [diff] [blame] | 634 | if self._cached_new_contents is None: |
| 635 | self._cached_new_contents = [] |
| 636 | if not self.IsDirectory(): |
| 637 | try: |
| 638 | self._cached_new_contents = gclient_utils.FileRead( |
| 639 | self.AbsoluteLocalPath(), 'rU').splitlines() |
| 640 | except IOError: |
| 641 | pass # File not found? That's fine; maybe it was deleted. |
| 642 | return self._cached_new_contents[:] |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 643 | |
[email protected] | ab05d58 | 2011-02-09 23:41:22 | [diff] [blame] | 644 | def ChangedContents(self): |
| 645 | """Returns a list of tuples (line number, line text) of all new lines. |
| 646 | |
| 647 | This relies on the scm diff output describing each changed code section |
| 648 | with a line of the form |
| 649 | |
| 650 | ^@@ <old line num>,<old size> <new line num>,<new size> @@$ |
| 651 | """ |
[email protected] | 2a3ab7e | 2011-04-27 22:06:27 | [diff] [blame] | 652 | if self._cached_changed_contents is not None: |
| 653 | return self._cached_changed_contents[:] |
| 654 | self._cached_changed_contents = [] |
[email protected] | ab05d58 | 2011-02-09 23:41:22 | [diff] [blame] | 655 | line_num = 0 |
| 656 | |
| 657 | if self.IsDirectory(): |
| 658 | return [] |
| 659 | |
| 660 | for line in self.GenerateScmDiff().splitlines(): |
| 661 | m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line) |
| 662 | if m: |
| 663 | line_num = int(m.groups(1)[0]) |
| 664 | continue |
| 665 | if line.startswith('+') and not line.startswith('++'): |
[email protected] | 2a3ab7e | 2011-04-27 22:06:27 | [diff] [blame] | 666 | self._cached_changed_contents.append((line_num, line[1:])) |
[email protected] | ab05d58 | 2011-02-09 23:41:22 | [diff] [blame] | 667 | if not line.startswith('-'): |
| 668 | line_num += 1 |
[email protected] | 2a3ab7e | 2011-04-27 22:06:27 | [diff] [blame] | 669 | return self._cached_changed_contents[:] |
[email protected] | ab05d58 | 2011-02-09 23:41:22 | [diff] [blame] | 670 | |
[email protected] | 5de1397 | 2009-06-10 18:16:06 | [diff] [blame] | 671 | def __str__(self): |
| 672 | return self.LocalPath() |
| 673 | |
[email protected] | ab05d58 | 2011-02-09 23:41:22 | [diff] [blame] | 674 | def GenerateScmDiff(self): |
[email protected] | ff52619 | 2013-06-10 19:30:26 | [diff] [blame] | 675 | return self._diff_cache.GetDiff(self.LocalPath(), self._local_root) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 676 | |
[email protected] | 58407af | 2011-04-12 23:15:57 | [diff] [blame] | 677 | |
[email protected] | dbbeedc | 2009-05-22 20:26:17 | [diff] [blame] | 678 | class SvnAffectedFile(AffectedFile): |
| 679 | """Representation of a file in a change out of a Subversion checkout.""" |
[email protected] | b17b55b | 2010-11-03 14:42:37 | [diff] [blame] | 680 | # Method 'NNN' is abstract in class 'NNN' but is not overridden |
| 681 | # pylint: disable=W0223 |
[email protected] | dbbeedc | 2009-05-22 20:26:17 | [diff] [blame] | 682 | |
[email protected] | ff52619 | 2013-06-10 19:30:26 | [diff] [blame] | 683 | DIFF_CACHE = _SvnDiffCache |
| 684 | |
[email protected] | 15bdffa | 2009-05-29 11:16:29 | [diff] [blame] | 685 | def __init__(self, *args, **kwargs): |
| 686 | AffectedFile.__init__(self, *args, **kwargs) |
| 687 | self._server_path = None |
| 688 | self._is_text_file = None |
[email protected] | 15bdffa | 2009-05-29 11:16:29 | [diff] [blame] | 689 | |
[email protected] | dbbeedc | 2009-05-22 20:26:17 | [diff] [blame] | 690 | def ServerPath(self): |
[email protected] | 15bdffa | 2009-05-29 11:16:29 | [diff] [blame] | 691 | if self._server_path is None: |
[email protected] | d579fcf | 2011-12-13 20:36:03 | [diff] [blame] | 692 | self._server_path = scm.SVN.CaptureLocalInfo( |
| 693 | [self.LocalPath()], self._local_root).get('URL', '') |
[email protected] | 15bdffa | 2009-05-29 11:16:29 | [diff] [blame] | 694 | return self._server_path |
[email protected] | dbbeedc | 2009-05-22 20:26:17 | [diff] [blame] | 695 | |
| 696 | def IsDirectory(self): |
[email protected] | 15bdffa | 2009-05-29 11:16:29 | [diff] [blame] | 697 | if self._is_directory is None: |
| 698 | path = self.AbsoluteLocalPath() |
[email protected] | dbbeedc | 2009-05-22 20:26:17 | [diff] [blame] | 699 | if os.path.exists(path): |
| 700 | # Retrieve directly from the file system; it is much faster than |
| 701 | # querying subversion, especially on Windows. |
[email protected] | 15bdffa | 2009-05-29 11:16:29 | [diff] [blame] | 702 | self._is_directory = os.path.isdir(path) |
[email protected] | dbbeedc | 2009-05-22 20:26:17 | [diff] [blame] | 703 | else: |
[email protected] | d579fcf | 2011-12-13 20:36:03 | [diff] [blame] | 704 | self._is_directory = scm.SVN.CaptureLocalInfo( |
| 705 | [self.LocalPath()], self._local_root |
| 706 | ).get('Node Kind') in ('dir', 'directory') |
[email protected] | 15bdffa | 2009-05-29 11:16:29 | [diff] [blame] | 707 | return self._is_directory |
[email protected] | dbbeedc | 2009-05-22 20:26:17 | [diff] [blame] | 708 | |
| 709 | def Property(self, property_name): |
[email protected] | 15bdffa | 2009-05-29 11:16:29 | [diff] [blame] | 710 | if not property_name in self._properties: |
[email protected] | 5aeb7dd | 2009-11-17 18:09:01 | [diff] [blame] | 711 | self._properties[property_name] = scm.SVN.GetFileProperty( |
[email protected] | d579fcf | 2011-12-13 20:36:03 | [diff] [blame] | 712 | self.LocalPath(), property_name, self._local_root).rstrip() |
[email protected] | 15bdffa | 2009-05-29 11:16:29 | [diff] [blame] | 713 | return self._properties[property_name] |
[email protected] | dbbeedc | 2009-05-22 20:26:17 | [diff] [blame] | 714 | |
[email protected] | 1e08c00 | 2009-05-28 19:09:33 | [diff] [blame] | 715 | def IsTextFile(self): |
[email protected] | 15bdffa | 2009-05-29 11:16:29 | [diff] [blame] | 716 | if self._is_text_file is None: |
| 717 | if self.Action() == 'D': |
| 718 | # A deleted file is not a text file. |
| 719 | self._is_text_file = False |
| 720 | elif self.IsDirectory(): |
| 721 | self._is_text_file = False |
| 722 | else: |
[email protected] | d579fcf | 2011-12-13 20:36:03 | [diff] [blame] | 723 | mime_type = scm.SVN.GetFileProperty( |
| 724 | self.LocalPath(), 'svn:mime-type', self._local_root) |
[email protected] | 15bdffa | 2009-05-29 11:16:29 | [diff] [blame] | 725 | self._is_text_file = (not mime_type or mime_type.startswith('text/')) |
| 726 | return self._is_text_file |
[email protected] | 1e08c00 | 2009-05-28 19:09:33 | [diff] [blame] | 727 | |
[email protected] | dbbeedc | 2009-05-22 20:26:17 | [diff] [blame] | 728 | |
[email protected] | c70a220 | 2009-06-17 12:55:10 | [diff] [blame] | 729 | class GitAffectedFile(AffectedFile): |
| 730 | """Representation of a file in a change out of a git checkout.""" |
[email protected] | b17b55b | 2010-11-03 14:42:37 | [diff] [blame] | 731 | # Method 'NNN' is abstract in class 'NNN' but is not overridden |
| 732 | # pylint: disable=W0223 |
[email protected] | c70a220 | 2009-06-17 12:55:10 | [diff] [blame] | 733 | |
[email protected] | ff52619 | 2013-06-10 19:30:26 | [diff] [blame] | 734 | DIFF_CACHE = _GitDiffCache |
| 735 | |
[email protected] | c70a220 | 2009-06-17 12:55:10 | [diff] [blame] | 736 | def __init__(self, *args, **kwargs): |
| 737 | AffectedFile.__init__(self, *args, **kwargs) |
| 738 | self._server_path = None |
| 739 | self._is_text_file = None |
[email protected] | c70a220 | 2009-06-17 12:55:10 | [diff] [blame] | 740 | |
| 741 | def ServerPath(self): |
| 742 | if self._server_path is None: |
[email protected] | 899e1c1 | 2011-04-07 17:03:18 | [diff] [blame] | 743 | raise NotImplementedError('TODO(maruel) Implement.') |
[email protected] | c70a220 | 2009-06-17 12:55:10 | [diff] [blame] | 744 | return self._server_path |
| 745 | |
| 746 | def IsDirectory(self): |
| 747 | if self._is_directory is None: |
| 748 | path = self.AbsoluteLocalPath() |
| 749 | if os.path.exists(path): |
| 750 | # Retrieve directly from the file system; it is much faster than |
| 751 | # querying subversion, especially on Windows. |
| 752 | self._is_directory = os.path.isdir(path) |
| 753 | else: |
[email protected] | c70a220 | 2009-06-17 12:55:10 | [diff] [blame] | 754 | self._is_directory = False |
| 755 | return self._is_directory |
| 756 | |
| 757 | def Property(self, property_name): |
| 758 | if not property_name in self._properties: |
[email protected] | 899e1c1 | 2011-04-07 17:03:18 | [diff] [blame] | 759 | raise NotImplementedError('TODO(maruel) Implement.') |
[email protected] | c70a220 | 2009-06-17 12:55:10 | [diff] [blame] | 760 | return self._properties[property_name] |
| 761 | |
| 762 | def IsTextFile(self): |
| 763 | if self._is_text_file is None: |
| 764 | if self.Action() == 'D': |
| 765 | # A deleted file is not a text file. |
| 766 | self._is_text_file = False |
| 767 | elif self.IsDirectory(): |
| 768 | self._is_text_file = False |
| 769 | else: |
[email protected] | c70a220 | 2009-06-17 12:55:10 | [diff] [blame] | 770 | self._is_text_file = os.path.isfile(self.AbsoluteLocalPath()) |
| 771 | return self._is_text_file |
| 772 | |
[email protected] | c193875 | 2011-04-12 23:11:13 | [diff] [blame] | 773 | |
[email protected] | 4ff922a | 2009-06-12 20:20:19 | [diff] [blame] | 774 | class Change(object): |
[email protected] | 6ebe68a | 2009-05-27 23:43:40 | [diff] [blame] | 775 | """Describe a change. |
| 776 | |
| 777 | Used directly by the presubmit scripts to query the current change being |
| 778 | tested. |
[email protected] | da8cddd | 2009-08-13 00:25:55 | [diff] [blame] | 779 | |
[email protected] | 6ebe68a | 2009-05-27 23:43:40 | [diff] [blame] | 780 | Instance members: |
[email protected] | ff52619 | 2013-06-10 19:30:26 | [diff] [blame] | 781 | tags: Dictionary of KEY=VALUE pairs found in the change description. |
[email protected] | 6ebe68a | 2009-05-27 23:43:40 | [diff] [blame] | 782 | self.KEY: equivalent to tags['KEY'] |
| 783 | """ |
| 784 | |
[email protected] | 4ff922a | 2009-06-12 20:20:19 | [diff] [blame] | 785 | _AFFECTED_FILES = AffectedFile |
| 786 | |
[email protected] | 6ebe68a | 2009-05-27 23:43:40 | [diff] [blame] | 787 | # Matches key/value (or "tag") lines in changelist descriptions. |
[email protected] | 428342a | 2011-11-10 15:46:33 | [diff] [blame] | 788 | TAG_LINE_RE = re.compile( |
[email protected] | c6f60e8 | 2013-04-19 17:01:57 | [diff] [blame] | 789 | '^[ \t]*(?P<key>[A-Z][A-Z_0-9]*)[ \t]*=[ \t]*(?P<value>.*?)[ \t]*$') |
[email protected] | c193875 | 2011-04-12 23:11:13 | [diff] [blame] | 790 | scm = '' |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 791 | |
[email protected] | 58407af | 2011-04-12 23:15:57 | [diff] [blame] | 792 | def __init__( |
| 793 | self, name, description, local_root, files, issue, patchset, author): |
[email protected] | 4ff922a | 2009-06-12 20:20:19 | [diff] [blame] | 794 | if files is None: |
| 795 | files = [] |
| 796 | self._name = name |
| 797 | self._full_description = description |
[email protected] | 8e416c8 | 2009-10-06 04:30:44 | [diff] [blame] | 798 | # Convert root into an absolute path. |
| 799 | self._local_root = os.path.abspath(local_root) |
[email protected] | 4ff922a | 2009-06-12 20:20:19 | [diff] [blame] | 800 | self.issue = issue |
| 801 | self.patchset = patchset |
[email protected] | 58407af | 2011-04-12 23:15:57 | [diff] [blame] | 802 | self.author_email = author |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 803 | |
| 804 | # From the description text, build up a dictionary of key/value pairs |
| 805 | # plus the description minus all key/value or "tag" lines. |
[email protected] | fa41037 | 2010-09-10 17:01:01 | [diff] [blame] | 806 | description_without_tags = [] |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 807 | self.tags = {} |
[email protected] | 8d5c9a5 | 2009-06-12 15:59:08 | [diff] [blame] | 808 | for line in self._full_description.splitlines(): |
[email protected] | 428342a | 2011-11-10 15:46:33 | [diff] [blame] | 809 | m = self.TAG_LINE_RE.match(line) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 810 | if m: |
| 811 | self.tags[m.group('key')] = m.group('value') |
| 812 | else: |
[email protected] | fa41037 | 2010-09-10 17:01:01 | [diff] [blame] | 813 | description_without_tags.append(line) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 814 | |
| 815 | # Change back to text and remove whitespace at end. |
[email protected] | fa41037 | 2010-09-10 17:01:01 | [diff] [blame] | 816 | self._description_without_tags = ( |
| 817 | '\n'.join(description_without_tags).rstrip()) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 818 | |
[email protected] | e085d81 | 2011-10-10 19:49:15 | [diff] [blame] | 819 | assert all( |
| 820 | (isinstance(f, (list, tuple)) and len(f) == 2) for f in files), files |
| 821 | |
[email protected] | ff52619 | 2013-06-10 19:30:26 | [diff] [blame] | 822 | diff_cache = self._AFFECTED_FILES.DIFF_CACHE() |
[email protected] | 6ebe68a | 2009-05-27 23:43:40 | [diff] [blame] | 823 | self._affected_files = [ |
[email protected] | ff52619 | 2013-06-10 19:30:26 | [diff] [blame] | 824 | self._AFFECTED_FILES(path, action.strip(), self._local_root, diff_cache) |
| 825 | for action, path in files |
[email protected] | dbbeedc | 2009-05-22 20:26:17 | [diff] [blame] | 826 | ] |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 827 | |
[email protected] | 92022ec | 2009-06-11 01:59:28 | [diff] [blame] | 828 | def Name(self): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 829 | """Returns the change name.""" |
[email protected] | 6ebe68a | 2009-05-27 23:43:40 | [diff] [blame] | 830 | return self._name |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 831 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 832 | def DescriptionText(self): |
| 833 | """Returns the user-entered changelist description, minus tags. |
| 834 | |
| 835 | Any line in the user-provided description starting with e.g. "FOO=" |
| 836 | (whitespace permitted before and around) is considered a tag line. Such |
| 837 | lines are stripped out of the description this function returns. |
| 838 | """ |
[email protected] | 6ebe68a | 2009-05-27 23:43:40 | [diff] [blame] | 839 | return self._description_without_tags |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 840 | |
| 841 | def FullDescriptionText(self): |
| 842 | """Returns the complete changelist description including tags.""" |
[email protected] | 6ebe68a | 2009-05-27 23:43:40 | [diff] [blame] | 843 | return self._full_description |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 844 | |
| 845 | def RepositoryRoot(self): |
[email protected] | 92022ec | 2009-06-11 01:59:28 | [diff] [blame] | 846 | """Returns the repository (checkout) root directory for this change, |
| 847 | as an absolute path. |
| 848 | """ |
[email protected] | 4ff922a | 2009-06-12 20:20:19 | [diff] [blame] | 849 | return self._local_root |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 850 | |
| 851 | def __getattr__(self, attr): |
[email protected] | 92022ec | 2009-06-11 01:59:28 | [diff] [blame] | 852 | """Return tags directly as attributes on the object.""" |
| 853 | if not re.match(r"^[A-Z_]*$", attr): |
| 854 | raise AttributeError(self, attr) |
[email protected] | e1a524f | 2009-05-27 14:43:46 | [diff] [blame] | 855 | return self.tags.get(attr) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 856 | |
[email protected] | 5538e02 | 2011-05-12 17:53:16 | [diff] [blame] | 857 | def AffectedFiles(self, include_dirs=False, include_deletes=True, |
| 858 | file_filter=None): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 859 | """Returns a list of AffectedFile instances for all files in the change. |
| 860 | |
| 861 | Args: |
| 862 | include_deletes: If false, deleted files will be filtered out. |
| 863 | include_dirs: True to include directories in the list |
[email protected] | 5538e02 | 2011-05-12 17:53:16 | [diff] [blame] | 864 | file_filter: An additional filter to apply. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 865 | |
| 866 | Returns: |
| 867 | [AffectedFile(path, action), AffectedFile(path, action)] |
| 868 | """ |
| 869 | if include_dirs: |
[email protected] | 6ebe68a | 2009-05-27 23:43:40 | [diff] [blame] | 870 | affected = self._affected_files |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 871 | else: |
[email protected] | 6ebe68a | 2009-05-27 23:43:40 | [diff] [blame] | 872 | affected = filter(lambda x: not x.IsDirectory(), self._affected_files) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 873 | |
[email protected] | 5538e02 | 2011-05-12 17:53:16 | [diff] [blame] | 874 | affected = filter(file_filter, affected) |
| 875 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 876 | if include_deletes: |
| 877 | return affected |
| 878 | else: |
| 879 | return filter(lambda x: x.Action() != 'D', affected) |
| 880 | |
[email protected] | 77c4f0f | 2009-05-29 18:53:04 | [diff] [blame] | 881 | def AffectedTextFiles(self, include_deletes=None): |
| 882 | """Return a list of the existing text files in a change.""" |
| 883 | if include_deletes is not None: |
[email protected] | cb2985f | 2010-11-03 14:08:31 | [diff] [blame] | 884 | warn("AffectedTextFiles(include_deletes=%s)" |
| 885 | " is deprecated and ignored" % str(include_deletes), |
| 886 | category=DeprecationWarning, |
| 887 | stacklevel=2) |
[email protected] | 77c4f0f | 2009-05-29 18:53:04 | [diff] [blame] | 888 | return filter(lambda x: x.IsTextFile(), |
| 889 | self.AffectedFiles(include_dirs=False, include_deletes=False)) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 890 | |
| 891 | def LocalPaths(self, include_dirs=False): |
| 892 | """Convenience function.""" |
| 893 | return [af.LocalPath() for af in self.AffectedFiles(include_dirs)] |
| 894 | |
| 895 | def AbsoluteLocalPaths(self, include_dirs=False): |
| 896 | """Convenience function.""" |
| 897 | return [af.AbsoluteLocalPath() for af in self.AffectedFiles(include_dirs)] |
| 898 | |
| 899 | def ServerPaths(self, include_dirs=False): |
| 900 | """Convenience function.""" |
| 901 | return [af.ServerPath() for af in self.AffectedFiles(include_dirs)] |
| 902 | |
| 903 | def RightHandSideLines(self): |
| 904 | """An iterator over all text lines in "new" version of changed files. |
| 905 | |
| 906 | Lists lines from new or modified text files in the change. |
| 907 | |
| 908 | This is useful for doing line-by-line regex checks, like checking for |
| 909 | trailing whitespace. |
| 910 | |
| 911 | Yields: |
| 912 | a 3 tuple: |
| 913 | the AffectedFile instance of the current file; |
| 914 | integer line number (1-based); and |
| 915 | the contents of the line as a string. |
| 916 | """ |
[email protected] | cb2985f | 2010-11-03 14:08:31 | [diff] [blame] | 917 | return _RightHandSideLinesImpl( |
| 918 | x for x in self.AffectedFiles(include_deletes=False) |
| 919 | if x.IsTextFile()) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 920 | |
| 921 | |
[email protected] | 4ff922a | 2009-06-12 20:20:19 | [diff] [blame] | 922 | class SvnChange(Change): |
| 923 | _AFFECTED_FILES = SvnAffectedFile |
[email protected] | c193875 | 2011-04-12 23:11:13 | [diff] [blame] | 924 | scm = 'svn' |
| 925 | _changelists = None |
[email protected] | 6bd3170 | 2009-09-02 23:29:07 | [diff] [blame] | 926 | |
| 927 | def _GetChangeLists(self): |
| 928 | """Get all change lists.""" |
| 929 | if self._changelists == None: |
| 930 | previous_cwd = os.getcwd() |
| 931 | os.chdir(self.RepositoryRoot()) |
[email protected] | cb2985f | 2010-11-03 14:08:31 | [diff] [blame] | 932 | # Need to import here to avoid circular dependency. |
| 933 | import gcl |
[email protected] | 6bd3170 | 2009-09-02 23:29:07 | [diff] [blame] | 934 | self._changelists = gcl.GetModifiedFiles() |
| 935 | os.chdir(previous_cwd) |
| 936 | return self._changelists |
[email protected] | da8cddd | 2009-08-13 00:25:55 | [diff] [blame] | 937 | |
| 938 | def GetAllModifiedFiles(self): |
| 939 | """Get all modified files.""" |
[email protected] | 6bd3170 | 2009-09-02 23:29:07 | [diff] [blame] | 940 | changelists = self._GetChangeLists() |
[email protected] | da8cddd | 2009-08-13 00:25:55 | [diff] [blame] | 941 | all_modified_files = [] |
| 942 | for cl in changelists.values(): |
[email protected] | 6bd3170 | 2009-09-02 23:29:07 | [diff] [blame] | 943 | all_modified_files.extend( |
| 944 | [os.path.join(self.RepositoryRoot(), f[1]) for f in cl]) |
[email protected] | da8cddd | 2009-08-13 00:25:55 | [diff] [blame] | 945 | return all_modified_files |
| 946 | |
| 947 | def GetModifiedFiles(self): |
| 948 | """Get modified files in the current CL.""" |
[email protected] | 6bd3170 | 2009-09-02 23:29:07 | [diff] [blame] | 949 | changelists = self._GetChangeLists() |
| 950 | return [os.path.join(self.RepositoryRoot(), f[1]) |
| 951 | for f in changelists[self.Name()]] |
[email protected] | da8cddd | 2009-08-13 00:25:55 | [diff] [blame] | 952 | |
[email protected] | 4ff922a | 2009-06-12 20:20:19 | [diff] [blame] | 953 | |
[email protected] | c70a220 | 2009-06-17 12:55:10 | [diff] [blame] | 954 | class GitChange(Change): |
| 955 | _AFFECTED_FILES = GitAffectedFile |
[email protected] | c193875 | 2011-04-12 23:11:13 | [diff] [blame] | 956 | scm = 'git' |
[email protected] | da8cddd | 2009-08-13 00:25:55 | [diff] [blame] | 957 | |
[email protected] | c70a220 | 2009-06-17 12:55:10 | [diff] [blame] | 958 | |
[email protected] | 4661e0c | 2009-06-04 00:45:26 | [diff] [blame] | 959 | def ListRelevantPresubmitFiles(files, root): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 960 | """Finds all presubmit files that apply to a given set of source files. |
| 961 | |
[email protected] | b1901a6 | 2010-06-16 00:18:47 | [diff] [blame] | 962 | If inherit-review-settings-ok is present right under root, looks for |
| 963 | PRESUBMIT.py in directories enclosing root. |
| 964 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 965 | Args: |
| 966 | files: An iterable container containing file paths. |
[email protected] | 4661e0c | 2009-06-04 00:45:26 | [diff] [blame] | 967 | root: Path where to stop searching. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 968 | |
| 969 | Return: |
[email protected] | 4661e0c | 2009-06-04 00:45:26 | [diff] [blame] | 970 | List of absolute paths of the existing PRESUBMIT.py scripts. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 971 | """ |
[email protected] | b1901a6 | 2010-06-16 00:18:47 | [diff] [blame] | 972 | files = [normpath(os.path.join(root, f)) for f in files] |
| 973 | |
| 974 | # List all the individual directories containing files. |
| 975 | directories = set([os.path.dirname(f) for f in files]) |
| 976 | |
| 977 | # Ignore root if inherit-review-settings-ok is present. |
| 978 | if os.path.isfile(os.path.join(root, 'inherit-review-settings-ok')): |
| 979 | root = None |
| 980 | |
| 981 | # Collect all unique directories that may contain PRESUBMIT.py. |
| 982 | candidates = set() |
| 983 | for directory in directories: |
| 984 | while True: |
| 985 | if directory in candidates: |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 986 | break |
[email protected] | b1901a6 | 2010-06-16 00:18:47 | [diff] [blame] | 987 | candidates.add(directory) |
| 988 | if directory == root: |
[email protected] | 4661e0c | 2009-06-04 00:45:26 | [diff] [blame] | 989 | break |
[email protected] | b1901a6 | 2010-06-16 00:18:47 | [diff] [blame] | 990 | parent_dir = os.path.dirname(directory) |
| 991 | if parent_dir == directory: |
| 992 | # We hit the system root directory. |
| 993 | break |
| 994 | directory = parent_dir |
| 995 | |
| 996 | # Look for PRESUBMIT.py in all candidate directories. |
| 997 | results = [] |
| 998 | for directory in sorted(list(candidates)): |
| 999 | p = os.path.join(directory, 'PRESUBMIT.py') |
| 1000 | if os.path.isfile(p): |
| 1001 | results.append(p) |
| 1002 | |
[email protected] | 5d0dc43 | 2011-01-03 02:40:37 | [diff] [blame] | 1003 | logging.debug('Presubmit files: %s' % ','.join(results)) |
[email protected] | b1901a6 | 2010-06-16 00:18:47 | [diff] [blame] | 1004 | return results |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1005 | |
| 1006 | |
[email protected] | de24345 | 2009-10-06 21:02:56 | [diff] [blame] | 1007 | class GetTrySlavesExecuter(object): |
[email protected] | cb2985f | 2010-11-03 14:08:31 | [diff] [blame] | 1008 | @staticmethod |
[email protected] | 1516995 | 2011-09-27 14:30:53 | [diff] [blame] | 1009 | def ExecPresubmitScript(script_text, presubmit_path, project, change): |
[email protected] | de24345 | 2009-10-06 21:02:56 | [diff] [blame] | 1010 | """Executes GetPreferredTrySlaves() from a single presubmit script. |
[email protected] | 58a69cb | 2014-03-01 02:08:29 | [diff] [blame] | 1011 | |
| 1012 | This will soon be deprecated and replaced by GetPreferredTryMasters(). |
[email protected] | de24345 | 2009-10-06 21:02:56 | [diff] [blame] | 1013 | |
| 1014 | Args: |
| 1015 | script_text: The text of the presubmit script. |
[email protected] | 7823002 | 2011-05-24 18:55:19 | [diff] [blame] | 1016 | presubmit_path: Project script to run. |
| 1017 | project: Project name to pass to presubmit script for bot selection. |
[email protected] | de24345 | 2009-10-06 21:02:56 | [diff] [blame] | 1018 | |
| 1019 | Return: |
| 1020 | A list of try slaves. |
| 1021 | """ |
| 1022 | context = {} |
[email protected] | f634964 | 2014-03-04 00:52:18 | [diff] [blame] | 1023 | main_path = os.getcwd() |
[email protected] | 899e1c1 | 2011-04-07 17:03:18 | [diff] [blame] | 1024 | try: |
[email protected] | f634964 | 2014-03-04 00:52:18 | [diff] [blame] | 1025 | os.chdir(os.path.dirname(presubmit_path)) |
[email protected] | 899e1c1 | 2011-04-07 17:03:18 | [diff] [blame] | 1026 | exec script_text in context |
| 1027 | except Exception, e: |
| 1028 | raise PresubmitFailure('"%s" had an exception.\n%s' % (presubmit_path, e)) |
[email protected] | f634964 | 2014-03-04 00:52:18 | [diff] [blame] | 1029 | finally: |
| 1030 | os.chdir(main_path) |
[email protected] | de24345 | 2009-10-06 21:02:56 | [diff] [blame] | 1031 | |
| 1032 | function_name = 'GetPreferredTrySlaves' |
| 1033 | if function_name in context: |
[email protected] | 1516995 | 2011-09-27 14:30:53 | [diff] [blame] | 1034 | get_preferred_try_slaves = context[function_name] |
| 1035 | function_info = inspect.getargspec(get_preferred_try_slaves) |
| 1036 | if len(function_info[0]) == 1: |
| 1037 | result = get_preferred_try_slaves(project) |
| 1038 | elif len(function_info[0]) == 2: |
| 1039 | result = get_preferred_try_slaves(project, change) |
| 1040 | else: |
| 1041 | result = get_preferred_try_slaves() |
[email protected] | de24345 | 2009-10-06 21:02:56 | [diff] [blame] | 1042 | if not isinstance(result, types.ListType): |
[email protected] | 899e1c1 | 2011-04-07 17:03:18 | [diff] [blame] | 1043 | raise PresubmitFailure( |
[email protected] | de24345 | 2009-10-06 21:02:56 | [diff] [blame] | 1044 | 'Presubmit functions must return a list, got a %s instead: %s' % |
| 1045 | (type(result), str(result))) |
| 1046 | for item in result: |
[email protected] | 68e0419 | 2013-11-04 22:14:38 | [diff] [blame] | 1047 | if isinstance(item, basestring): |
| 1048 | # Old-style ['bot'] format. |
| 1049 | botname = item |
| 1050 | elif isinstance(item, tuple): |
| 1051 | # New-style [('bot', set(['tests']))] format. |
| 1052 | botname = item[0] |
| 1053 | else: |
| 1054 | raise PresubmitFailure('PRESUBMIT.py returned invalid tryslave/test' |
| 1055 | ' format.') |
| 1056 | |
| 1057 | if botname != botname.strip(): |
[email protected] | 899e1c1 | 2011-04-07 17:03:18 | [diff] [blame] | 1058 | raise PresubmitFailure( |
| 1059 | 'Try slave names cannot start/end with whitespace') |
[email protected] | 68e0419 | 2013-11-04 22:14:38 | [diff] [blame] | 1060 | if ',' in botname: |
[email protected] | 3ecc8ea | 2012-03-10 01:47:46 | [diff] [blame] | 1061 | raise PresubmitFailure( |
[email protected] | 68e0419 | 2013-11-04 22:14:38 | [diff] [blame] | 1062 | 'Do not use \',\' separated builder or test names: %s' % botname) |
[email protected] | de24345 | 2009-10-06 21:02:56 | [diff] [blame] | 1063 | else: |
| 1064 | result = [] |
[email protected] | 5ca2762 | 2013-12-18 17:44:58 | [diff] [blame] | 1065 | |
| 1066 | def valid_oldstyle(result): |
| 1067 | return all(isinstance(i, basestring) for i in result) |
| 1068 | |
| 1069 | def valid_newstyle(result): |
| 1070 | return (all(isinstance(i, tuple) for i in result) and |
| 1071 | all(len(i) == 2 for i in result) and |
| 1072 | all(isinstance(i[0], basestring) for i in result) and |
| 1073 | all(isinstance(i[1], set) for i in result) |
| 1074 | ) |
| 1075 | |
| 1076 | # Ensure it's either all old-style or all new-style. |
| 1077 | if not valid_oldstyle(result) and not valid_newstyle(result): |
| 1078 | raise PresubmitFailure( |
| 1079 | 'PRESUBMIT.py returned invalid trybot specification!') |
| 1080 | |
[email protected] | de24345 | 2009-10-06 21:02:56 | [diff] [blame] | 1081 | return result |
| 1082 | |
| 1083 | |
[email protected] | 58a69cb | 2014-03-01 02:08:29 | [diff] [blame] | 1084 | class GetTryMastersExecuter(object): |
| 1085 | @staticmethod |
| 1086 | def ExecPresubmitScript(script_text, presubmit_path, project, change): |
| 1087 | """Executes GetPreferredTryMasters() from a single presubmit script. |
| 1088 | |
| 1089 | Args: |
| 1090 | script_text: The text of the presubmit script. |
| 1091 | presubmit_path: Project script to run. |
| 1092 | project: Project name to pass to presubmit script for bot selection. |
| 1093 | |
| 1094 | Return: |
| 1095 | A map of try masters to map of builders to set of tests. |
| 1096 | """ |
| 1097 | context = {} |
| 1098 | try: |
| 1099 | exec script_text in context |
| 1100 | except Exception, e: |
| 1101 | raise PresubmitFailure('"%s" had an exception.\n%s' |
| 1102 | % (presubmit_path, e)) |
| 1103 | |
| 1104 | function_name = 'GetPreferredTryMasters' |
| 1105 | if function_name not in context: |
| 1106 | return {} |
| 1107 | get_preferred_try_masters = context[function_name] |
| 1108 | if not len(inspect.getargspec(get_preferred_try_masters)[0]) == 2: |
| 1109 | raise PresubmitFailure( |
| 1110 | 'Expected function "GetPreferredTryMasters" to take two arguments.') |
| 1111 | return get_preferred_try_masters(project, change) |
| 1112 | |
| 1113 | |
[email protected] | 1516995 | 2011-09-27 14:30:53 | [diff] [blame] | 1114 | def DoGetTrySlaves(change, |
| 1115 | changed_files, |
[email protected] | de24345 | 2009-10-06 21:02:56 | [diff] [blame] | 1116 | repository_root, |
| 1117 | default_presubmit, |
[email protected] | 7823002 | 2011-05-24 18:55:19 | [diff] [blame] | 1118 | project, |
[email protected] | de24345 | 2009-10-06 21:02:56 | [diff] [blame] | 1119 | verbose, |
| 1120 | output_stream): |
[email protected] | 58a69cb | 2014-03-01 02:08:29 | [diff] [blame] | 1121 | """Get the list of try servers from the presubmit scripts (deprecated). |
[email protected] | de24345 | 2009-10-06 21:02:56 | [diff] [blame] | 1122 | |
| 1123 | Args: |
| 1124 | changed_files: List of modified files. |
| 1125 | repository_root: The repository root. |
| 1126 | default_presubmit: A default presubmit script to execute in any case. |
[email protected] | 7823002 | 2011-05-24 18:55:19 | [diff] [blame] | 1127 | project: Optional name of a project used in selecting trybots. |
[email protected] | de24345 | 2009-10-06 21:02:56 | [diff] [blame] | 1128 | verbose: Prints debug info. |
| 1129 | output_stream: A stream to write debug output to. |
| 1130 | |
| 1131 | Return: |
| 1132 | List of try slaves |
| 1133 | """ |
| 1134 | presubmit_files = ListRelevantPresubmitFiles(changed_files, repository_root) |
| 1135 | if not presubmit_files and verbose: |
[email protected] | d59e761 | 2014-03-05 19:55:56 | [diff] [blame^] | 1136 | output_stream.write("Warning, no PRESUBMIT.py found.\n") |
[email protected] | de24345 | 2009-10-06 21:02:56 | [diff] [blame] | 1137 | results = [] |
| 1138 | executer = GetTrySlavesExecuter() |
[email protected] | 5ca2762 | 2013-12-18 17:44:58 | [diff] [blame] | 1139 | |
[email protected] | de24345 | 2009-10-06 21:02:56 | [diff] [blame] | 1140 | if default_presubmit: |
| 1141 | if verbose: |
| 1142 | output_stream.write("Running default presubmit script.\n") |
[email protected] | 899e1c1 | 2011-04-07 17:03:18 | [diff] [blame] | 1143 | fake_path = os.path.join(repository_root, 'PRESUBMIT.py') |
[email protected] | 5ca2762 | 2013-12-18 17:44:58 | [diff] [blame] | 1144 | results.extend(executer.ExecPresubmitScript( |
| 1145 | default_presubmit, fake_path, project, change)) |
[email protected] | de24345 | 2009-10-06 21:02:56 | [diff] [blame] | 1146 | for filename in presubmit_files: |
| 1147 | filename = os.path.abspath(filename) |
| 1148 | if verbose: |
| 1149 | output_stream.write("Running %s\n" % filename) |
| 1150 | # Accept CRLF presubmit script. |
[email protected] | 5aeb7dd | 2009-11-17 18:09:01 | [diff] [blame] | 1151 | presubmit_script = gclient_utils.FileRead(filename, 'rU') |
[email protected] | 5ca2762 | 2013-12-18 17:44:58 | [diff] [blame] | 1152 | results.extend(executer.ExecPresubmitScript( |
| 1153 | presubmit_script, filename, project, change)) |
[email protected] | de24345 | 2009-10-06 21:02:56 | [diff] [blame] | 1154 | |
[email protected] | 5ca2762 | 2013-12-18 17:44:58 | [diff] [blame] | 1155 | |
| 1156 | slave_dict = {} |
| 1157 | old_style = filter(lambda x: isinstance(x, basestring), results) |
| 1158 | new_style = filter(lambda x: isinstance(x, tuple), results) |
| 1159 | |
| 1160 | for result in new_style: |
| 1161 | slave_dict.setdefault(result[0], set()).update(result[1]) |
| 1162 | slaves = list(slave_dict.items()) |
| 1163 | |
| 1164 | slaves.extend(set(old_style)) |
[email protected] | 68e0419 | 2013-11-04 22:14:38 | [diff] [blame] | 1165 | |
[email protected] | de24345 | 2009-10-06 21:02:56 | [diff] [blame] | 1166 | if slaves and verbose: |
[email protected] | 5ca2762 | 2013-12-18 17:44:58 | [diff] [blame] | 1167 | output_stream.write(', '.join((str(x) for x in slaves))) |
[email protected] | de24345 | 2009-10-06 21:02:56 | [diff] [blame] | 1168 | output_stream.write('\n') |
| 1169 | return slaves |
| 1170 | |
| 1171 | |
[email protected] | 58a69cb | 2014-03-01 02:08:29 | [diff] [blame] | 1172 | def _MergeMasters(masters1, masters2): |
| 1173 | """Merges two master maps. Merges also the tests of each builder.""" |
| 1174 | result = {} |
| 1175 | for (master, builders) in itertools.chain(masters1.iteritems(), |
| 1176 | masters2.iteritems()): |
| 1177 | new_builders = result.setdefault(master, {}) |
| 1178 | for (builder, tests) in builders.iteritems(): |
| 1179 | new_builders.setdefault(builder, set([])).update(tests) |
| 1180 | return result |
| 1181 | |
| 1182 | |
| 1183 | def DoGetTryMasters(change, |
| 1184 | changed_files, |
| 1185 | repository_root, |
| 1186 | default_presubmit, |
| 1187 | project, |
| 1188 | verbose, |
| 1189 | output_stream): |
| 1190 | """Get the list of try masters from the presubmit scripts. |
| 1191 | |
| 1192 | Args: |
| 1193 | changed_files: List of modified files. |
| 1194 | repository_root: The repository root. |
| 1195 | default_presubmit: A default presubmit script to execute in any case. |
| 1196 | project: Optional name of a project used in selecting trybots. |
| 1197 | verbose: Prints debug info. |
| 1198 | output_stream: A stream to write debug output to. |
| 1199 | |
| 1200 | Return: |
| 1201 | Map of try masters to map of builders to set of tests. |
| 1202 | """ |
| 1203 | presubmit_files = ListRelevantPresubmitFiles(changed_files, repository_root) |
| 1204 | if not presubmit_files and verbose: |
| 1205 | output_stream.write("Warning, no PRESUBMIT.py found.\n") |
| 1206 | results = {} |
| 1207 | executer = GetTryMastersExecuter() |
| 1208 | |
| 1209 | if default_presubmit: |
| 1210 | if verbose: |
| 1211 | output_stream.write("Running default presubmit script.\n") |
| 1212 | fake_path = os.path.join(repository_root, 'PRESUBMIT.py') |
| 1213 | results = _MergeMasters(results, executer.ExecPresubmitScript( |
| 1214 | default_presubmit, fake_path, project, change)) |
| 1215 | for filename in presubmit_files: |
| 1216 | filename = os.path.abspath(filename) |
| 1217 | if verbose: |
| 1218 | output_stream.write("Running %s\n" % filename) |
| 1219 | # Accept CRLF presubmit script. |
| 1220 | presubmit_script = gclient_utils.FileRead(filename, 'rU') |
| 1221 | results = _MergeMasters(results, executer.ExecPresubmitScript( |
| 1222 | presubmit_script, filename, project, change)) |
| 1223 | |
| 1224 | # Make sets to lists again for later JSON serialization. |
| 1225 | for builders in results.itervalues(): |
| 1226 | for builder in builders: |
| 1227 | builders[builder] = list(builders[builder]) |
| 1228 | |
| 1229 | if results and verbose: |
| 1230 | output_stream.write('%s\n' % str(results)) |
| 1231 | return results |
| 1232 | |
| 1233 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1234 | class PresubmitExecuter(object): |
[email protected] | cc73ad6 | 2011-07-06 17:39:26 | [diff] [blame] | 1235 | def __init__(self, change, committing, rietveld_obj, verbose): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1236 | """ |
| 1237 | Args: |
[email protected] | 4ff922a | 2009-06-12 20:20:19 | [diff] [blame] | 1238 | change: The Change object. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1239 | committing: True if 'gcl commit' is running, False if 'gcl upload' is. |
[email protected] | 239f411 | 2011-06-03 20:08:23 | [diff] [blame] | 1240 | rietveld_obj: rietveld.Rietveld client object. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1241 | """ |
[email protected] | 4ff922a | 2009-06-12 20:20:19 | [diff] [blame] | 1242 | self.change = change |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1243 | self.committing = committing |
[email protected] | 239f411 | 2011-06-03 20:08:23 | [diff] [blame] | 1244 | self.rietveld = rietveld_obj |
[email protected] | 899e1c1 | 2011-04-07 17:03:18 | [diff] [blame] | 1245 | self.verbose = verbose |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1246 | |
| 1247 | def ExecPresubmitScript(self, script_text, presubmit_path): |
| 1248 | """Executes a single presubmit script. |
| 1249 | |
| 1250 | Args: |
| 1251 | script_text: The text of the presubmit script. |
| 1252 | presubmit_path: The path to the presubmit file (this will be reported via |
| 1253 | input_api.PresubmitLocalPath()). |
| 1254 | |
| 1255 | Return: |
| 1256 | A list of result objects, empty if no problems. |
| 1257 | """ |
[email protected] | 8e416c8 | 2009-10-06 04:30:44 | [diff] [blame] | 1258 | |
| 1259 | # Change to the presubmit file's directory to support local imports. |
| 1260 | main_path = os.getcwd() |
| 1261 | os.chdir(os.path.dirname(presubmit_path)) |
| 1262 | |
| 1263 | # Load the presubmit script into context. |
[email protected] | 970c522 | 2011-03-12 00:32:24 | [diff] [blame] | 1264 | input_api = InputApi(self.change, presubmit_path, self.committing, |
[email protected] | cc73ad6 | 2011-07-06 17:39:26 | [diff] [blame] | 1265 | self.rietveld, self.verbose) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1266 | context = {} |
[email protected] | 899e1c1 | 2011-04-07 17:03:18 | [diff] [blame] | 1267 | try: |
| 1268 | exec script_text in context |
| 1269 | except Exception, e: |
| 1270 | raise PresubmitFailure('"%s" had an exception.\n%s' % (presubmit_path, e)) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1271 | |
| 1272 | # These function names must change if we make substantial changes to |
| 1273 | # the presubmit API that are not backwards compatible. |
| 1274 | if self.committing: |
| 1275 | function_name = 'CheckChangeOnCommit' |
| 1276 | else: |
| 1277 | function_name = 'CheckChangeOnUpload' |
| 1278 | if function_name in context: |
[email protected] | a6d011e | 2013-03-26 17:31:49 | [diff] [blame] | 1279 | context['__args'] = (input_api, OutputApi(self.committing)) |
[email protected] | 5d0dc43 | 2011-01-03 02:40:37 | [diff] [blame] | 1280 | logging.debug('Running %s in %s' % (function_name, presubmit_path)) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1281 | result = eval(function_name + '(*__args)', context) |
[email protected] | 5d0dc43 | 2011-01-03 02:40:37 | [diff] [blame] | 1282 | logging.debug('Running %s done.' % function_name) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1283 | if not (isinstance(result, types.TupleType) or |
| 1284 | isinstance(result, types.ListType)): |
[email protected] | 899e1c1 | 2011-04-07 17:03:18 | [diff] [blame] | 1285 | raise PresubmitFailure( |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1286 | 'Presubmit functions must return a tuple or list') |
| 1287 | for item in result: |
| 1288 | if not isinstance(item, OutputApi.PresubmitResult): |
[email protected] | 899e1c1 | 2011-04-07 17:03:18 | [diff] [blame] | 1289 | raise PresubmitFailure( |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1290 | 'All presubmit results must be of types derived from ' |
| 1291 | 'output_api.PresubmitResult') |
| 1292 | else: |
| 1293 | result = () # no error since the script doesn't care about current event. |
| 1294 | |
[email protected] | 8e416c8 | 2009-10-06 04:30:44 | [diff] [blame] | 1295 | # Return the process to the original working directory. |
| 1296 | os.chdir(main_path) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1297 | return result |
| 1298 | |
[email protected] | 5ac2101 | 2011-03-16 02:58:25 | [diff] [blame] | 1299 | |
[email protected] | 4ff922a | 2009-06-12 20:20:19 | [diff] [blame] | 1300 | def DoPresubmitChecks(change, |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1301 | committing, |
| 1302 | verbose, |
| 1303 | output_stream, |
[email protected] | 0ff1fab | 2009-05-22 13:08:15 | [diff] [blame] | 1304 | input_stream, |
[email protected] | b0dfd35 | 2009-06-10 14:12:54 | [diff] [blame] | 1305 | default_presubmit, |
[email protected] | 970c522 | 2011-03-12 00:32:24 | [diff] [blame] | 1306 | may_prompt, |
[email protected] | 239f411 | 2011-06-03 20:08:23 | [diff] [blame] | 1307 | rietveld_obj): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1308 | """Runs all presubmit checks that apply to the files in the change. |
| 1309 | |
| 1310 | This finds all PRESUBMIT.py files in directories enclosing the files in the |
| 1311 | change (up to the repository root) and calls the relevant entrypoint function |
| 1312 | depending on whether the change is being committed or uploaded. |
| 1313 | |
| 1314 | Prints errors, warnings and notifications. Prompts the user for warnings |
| 1315 | when needed. |
| 1316 | |
| 1317 | Args: |
[email protected] | 4ff922a | 2009-06-12 20:20:19 | [diff] [blame] | 1318 | change: The Change object. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1319 | committing: True if 'gcl commit' is running, False if 'gcl upload' is. |
| 1320 | verbose: Prints debug info. |
| 1321 | output_stream: A stream to write output from presubmit tests to. |
| 1322 | input_stream: A stream to read input from the user. |
[email protected] | 0ff1fab | 2009-05-22 13:08:15 | [diff] [blame] | 1323 | default_presubmit: A default presubmit script to execute in any case. |
[email protected] | b0dfd35 | 2009-06-10 14:12:54 | [diff] [blame] | 1324 | may_prompt: Enable (y/n) questions on warning or error. |
[email protected] | 239f411 | 2011-06-03 20:08:23 | [diff] [blame] | 1325 | rietveld_obj: rietveld.Rietveld object. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1326 | |
[email protected] | ce8e46b | 2009-06-26 22:31:51 | [diff] [blame] | 1327 | Warning: |
| 1328 | If may_prompt is true, output_stream SHOULD be sys.stdout and input_stream |
| 1329 | SHOULD be sys.stdin. |
| 1330 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1331 | Return: |
[email protected] | 5ac2101 | 2011-03-16 02:58:25 | [diff] [blame] | 1332 | A PresubmitOutput object. Use output.should_continue() to figure out |
| 1333 | if there were errors or warnings and the caller should abort. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1334 | """ |
[email protected] | ea7c855 | 2011-04-18 14:12:07 | [diff] [blame] | 1335 | old_environ = os.environ |
| 1336 | try: |
| 1337 | # Make sure python subprocesses won't generate .pyc files. |
| 1338 | os.environ = os.environ.copy() |
| 1339 | os.environ['PYTHONDONTWRITEBYTECODE'] = '1' |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1340 | |
[email protected] | ea7c855 | 2011-04-18 14:12:07 | [diff] [blame] | 1341 | output = PresubmitOutput(input_stream, output_stream) |
| 1342 | if committing: |
| 1343 | output.write("Running presubmit commit checks ...\n") |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1344 | else: |
[email protected] | ea7c855 | 2011-04-18 14:12:07 | [diff] [blame] | 1345 | output.write("Running presubmit upload checks ...\n") |
| 1346 | start_time = time.time() |
| 1347 | presubmit_files = ListRelevantPresubmitFiles( |
| 1348 | change.AbsoluteLocalPaths(True), change.RepositoryRoot()) |
| 1349 | if not presubmit_files and verbose: |
[email protected] | fae707b | 2011-09-15 18:57:58 | [diff] [blame] | 1350 | output.write("Warning, no PRESUBMIT.py found.\n") |
[email protected] | ea7c855 | 2011-04-18 14:12:07 | [diff] [blame] | 1351 | results = [] |
[email protected] | cc73ad6 | 2011-07-06 17:39:26 | [diff] [blame] | 1352 | executer = PresubmitExecuter(change, committing, rietveld_obj, verbose) |
[email protected] | ea7c855 | 2011-04-18 14:12:07 | [diff] [blame] | 1353 | if default_presubmit: |
| 1354 | if verbose: |
| 1355 | output.write("Running default presubmit script.\n") |
| 1356 | fake_path = os.path.join(change.RepositoryRoot(), 'PRESUBMIT.py') |
| 1357 | results += executer.ExecPresubmitScript(default_presubmit, fake_path) |
| 1358 | for filename in presubmit_files: |
| 1359 | filename = os.path.abspath(filename) |
| 1360 | if verbose: |
| 1361 | output.write("Running %s\n" % filename) |
| 1362 | # Accept CRLF presubmit script. |
| 1363 | presubmit_script = gclient_utils.FileRead(filename, 'rU') |
| 1364 | results += executer.ExecPresubmitScript(presubmit_script, filename) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1365 | |
[email protected] | ea7c855 | 2011-04-18 14:12:07 | [diff] [blame] | 1366 | errors = [] |
| 1367 | notifications = [] |
| 1368 | warnings = [] |
| 1369 | for result in results: |
| 1370 | if result.fatal: |
| 1371 | errors.append(result) |
| 1372 | elif result.should_prompt: |
| 1373 | warnings.append(result) |
| 1374 | else: |
| 1375 | notifications.append(result) |
[email protected] | ed9a083 | 2009-09-09 22:48:55 | [diff] [blame] | 1376 | |
[email protected] | ea7c855 | 2011-04-18 14:12:07 | [diff] [blame] | 1377 | output.write('\n') |
| 1378 | for name, items in (('Messages', notifications), |
| 1379 | ('Warnings', warnings), |
| 1380 | ('ERRORS', errors)): |
| 1381 | if items: |
| 1382 | output.write('** Presubmit %s **\n' % name) |
| 1383 | for item in items: |
| 1384 | item.handle(output) |
| 1385 | output.write('\n') |
[email protected] | ed9a083 | 2009-09-09 22:48:55 | [diff] [blame] | 1386 | |
[email protected] | ea7c855 | 2011-04-18 14:12:07 | [diff] [blame] | 1387 | total_time = time.time() - start_time |
| 1388 | if total_time > 1.0: |
| 1389 | output.write("Presubmit checks took %.1fs to calculate.\n\n" % total_time) |
[email protected] | ce8e46b | 2009-06-26 22:31:51 | [diff] [blame] | 1390 | |
[email protected] | ea7c855 | 2011-04-18 14:12:07 | [diff] [blame] | 1391 | if not errors: |
| 1392 | if not warnings: |
| 1393 | output.write('Presubmit checks passed.\n') |
| 1394 | elif may_prompt: |
| 1395 | output.prompt_yes_no('There were presubmit warnings. ' |
| 1396 | 'Are you sure you wish to continue? (y/N): ') |
| 1397 | else: |
| 1398 | output.fail() |
| 1399 | |
| 1400 | global _ASKED_FOR_FEEDBACK |
| 1401 | # Ask for feedback one time out of 5. |
| 1402 | if (len(results) and random.randint(0, 4) == 0 and not _ASKED_FOR_FEEDBACK): |
[email protected] | 1ce8e66 | 2014-01-14 15:23:00 | [diff] [blame] | 1403 | output.write( |
| 1404 | 'Was the presubmit check useful? If not, run "git cl presubmit -v"\n' |
| 1405 | 'to figure out which PRESUBMIT.py was run, then run git blame\n' |
| 1406 | 'on the file to figure out who to ask for help.\n') |
[email protected] | ea7c855 | 2011-04-18 14:12:07 | [diff] [blame] | 1407 | _ASKED_FOR_FEEDBACK = True |
| 1408 | return output |
| 1409 | finally: |
| 1410 | os.environ = old_environ |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1411 | |
| 1412 | |
| 1413 | def ScanSubDirs(mask, recursive): |
| 1414 | if not recursive: |
[email protected] | c70a220 | 2009-06-17 12:55:10 | [diff] [blame] | 1415 | return [x for x in glob.glob(mask) if '.svn' not in x and '.git' not in x] |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1416 | else: |
| 1417 | results = [] |
| 1418 | for root, dirs, files in os.walk('.'): |
| 1419 | if '.svn' in dirs: |
| 1420 | dirs.remove('.svn') |
[email protected] | c70a220 | 2009-06-17 12:55:10 | [diff] [blame] | 1421 | if '.git' in dirs: |
| 1422 | dirs.remove('.git') |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1423 | for name in files: |
| 1424 | if fnmatch.fnmatch(name, mask): |
| 1425 | results.append(os.path.join(root, name)) |
| 1426 | return results |
| 1427 | |
| 1428 | |
| 1429 | def ParseFiles(args, recursive): |
[email protected] | 7444c50 | 2011-02-09 14:02:11 | [diff] [blame] | 1430 | logging.debug('Searching for %s' % args) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1431 | files = [] |
| 1432 | for arg in args: |
[email protected] | e3608df | 2009-11-10 20:22:57 | [diff] [blame] | 1433 | files.extend([('M', f) for f in ScanSubDirs(arg, recursive)]) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1434 | return files |
| 1435 | |
| 1436 | |
[email protected] | 5c8c6de | 2011-03-18 16:20:18 | [diff] [blame] | 1437 | def load_files(options, args): |
| 1438 | """Tries to determine the SCM.""" |
| 1439 | change_scm = scm.determine_scm(options.root) |
| 1440 | files = [] |
[email protected] | 5c8c6de | 2011-03-18 16:20:18 | [diff] [blame] | 1441 | if args: |
| 1442 | files = ParseFiles(args, options.recursive) |
[email protected] | 9b31f16 | 2012-01-26 19:02:31 | [diff] [blame] | 1443 | if change_scm == 'svn': |
| 1444 | change_class = SvnChange |
| 1445 | if not files: |
| 1446 | files = scm.SVN.CaptureStatus([], options.root) |
| 1447 | elif change_scm == 'git': |
| 1448 | change_class = GitChange |
| 1449 | # TODO(maruel): Get upstream. |
| 1450 | if not files: |
| 1451 | files = scm.GIT.CaptureStatus([], options.root, None) |
[email protected] | 5c8c6de | 2011-03-18 16:20:18 | [diff] [blame] | 1452 | else: |
[email protected] | 9b31f16 | 2012-01-26 19:02:31 | [diff] [blame] | 1453 | logging.info('Doesn\'t seem under source control. Got %d files' % len(args)) |
| 1454 | if not files: |
| 1455 | return None, None |
| 1456 | change_class = Change |
[email protected] | 5c8c6de | 2011-03-18 16:20:18 | [diff] [blame] | 1457 | return change_class, files |
| 1458 | |
| 1459 | |
[email protected] | 8a4a2bc | 2013-03-08 08:13:20 | [diff] [blame] | 1460 | class NonexistantCannedCheckFilter(Exception): |
| 1461 | pass |
| 1462 | |
| 1463 | |
| 1464 | @contextlib.contextmanager |
| 1465 | def canned_check_filter(method_names): |
| 1466 | filtered = {} |
| 1467 | try: |
| 1468 | for method_name in method_names: |
| 1469 | if not hasattr(presubmit_canned_checks, method_name): |
| 1470 | raise NonexistantCannedCheckFilter(method_name) |
| 1471 | filtered[method_name] = getattr(presubmit_canned_checks, method_name) |
| 1472 | setattr(presubmit_canned_checks, method_name, lambda *_a, **_kw: []) |
| 1473 | yield |
| 1474 | finally: |
| 1475 | for name, method in filtered.iteritems(): |
| 1476 | setattr(presubmit_canned_checks, name, method) |
| 1477 | |
[email protected] | ffeb2f3 | 2013-12-03 13:55:22 | [diff] [blame] | 1478 | |
[email protected] | bc11731 | 2013-04-20 03:57:56 | [diff] [blame] | 1479 | def CallCommand(cmd_data): |
[email protected] | ffeb2f3 | 2013-12-03 13:55:22 | [diff] [blame] | 1480 | """Runs an external program, potentially from a child process created by the |
| 1481 | multiprocessing module. |
| 1482 | |
| 1483 | multiprocessing needs a top level function with a single argument. |
| 1484 | """ |
[email protected] | bc11731 | 2013-04-20 03:57:56 | [diff] [blame] | 1485 | cmd_data.kwargs['stdout'] = subprocess.PIPE |
| 1486 | cmd_data.kwargs['stderr'] = subprocess.STDOUT |
| 1487 | try: |
[email protected] | ffeb2f3 | 2013-12-03 13:55:22 | [diff] [blame] | 1488 | start = time.time() |
[email protected] | bc11731 | 2013-04-20 03:57:56 | [diff] [blame] | 1489 | (out, _), code = subprocess.communicate(cmd_data.cmd, **cmd_data.kwargs) |
[email protected] | ffeb2f3 | 2013-12-03 13:55:22 | [diff] [blame] | 1490 | duration = time.time() - start |
[email protected] | bc11731 | 2013-04-20 03:57:56 | [diff] [blame] | 1491 | except OSError as e: |
[email protected] | ffeb2f3 | 2013-12-03 13:55:22 | [diff] [blame] | 1492 | duration = time.time() - start |
[email protected] | bc11731 | 2013-04-20 03:57:56 | [diff] [blame] | 1493 | return cmd_data.message( |
[email protected] | ffeb2f3 | 2013-12-03 13:55:22 | [diff] [blame] | 1494 | '%s exec failure (%4.2fs)\n %s' % (cmd_data.name, duration, e)) |
| 1495 | if code != 0: |
| 1496 | return cmd_data.message( |
| 1497 | '%s (%4.2fs) failed\n%s' % (cmd_data.name, duration, out)) |
| 1498 | if cmd_data.info: |
| 1499 | return cmd_data.info('%s (%4.2fs)' % (cmd_data.name, duration)) |
[email protected] | bc11731 | 2013-04-20 03:57:56 | [diff] [blame] | 1500 | |
[email protected] | 8a4a2bc | 2013-03-08 08:13:20 | [diff] [blame] | 1501 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1502 | def Main(argv): |
[email protected] | 5c8c6de | 2011-03-18 16:20:18 | [diff] [blame] | 1503 | parser = optparse.OptionParser(usage="%prog [options] <files...>", |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1504 | version="%prog " + str(__version__)) |
[email protected] | c70a220 | 2009-06-17 12:55:10 | [diff] [blame] | 1505 | parser.add_option("-c", "--commit", action="store_true", default=False, |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1506 | help="Use commit instead of upload checks") |
[email protected] | c70a220 | 2009-06-17 12:55:10 | [diff] [blame] | 1507 | parser.add_option("-u", "--upload", action="store_false", dest='commit', |
| 1508 | help="Use upload instead of commit checks") |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1509 | parser.add_option("-r", "--recursive", action="store_true", |
| 1510 | help="Act recursively") |
[email protected] | 899e1c1 | 2011-04-07 17:03:18 | [diff] [blame] | 1511 | parser.add_option("-v", "--verbose", action="count", default=0, |
| 1512 | help="Use 2 times for more debug info") |
[email protected] | 4ff922a | 2009-06-12 20:20:19 | [diff] [blame] | 1513 | parser.add_option("--name", default='no name') |
[email protected] | 58407af | 2011-04-12 23:15:57 | [diff] [blame] | 1514 | parser.add_option("--author") |
[email protected] | 4ff922a | 2009-06-12 20:20:19 | [diff] [blame] | 1515 | parser.add_option("--description", default='') |
| 1516 | parser.add_option("--issue", type='int', default=0) |
| 1517 | parser.add_option("--patchset", type='int', default=0) |
[email protected] | b1901a6 | 2010-06-16 00:18:47 | [diff] [blame] | 1518 | parser.add_option("--root", default=os.getcwd(), |
| 1519 | help="Search for PRESUBMIT.py up to this directory. " |
| 1520 | "If inherit-review-settings-ok is present in this " |
| 1521 | "directory, parent directories up to the root file " |
| 1522 | "system directories will also be searched.") |
[email protected] | c70a220 | 2009-06-17 12:55:10 | [diff] [blame] | 1523 | parser.add_option("--default_presubmit") |
| 1524 | parser.add_option("--may_prompt", action='store_true', default=False) |
[email protected] | 8a4a2bc | 2013-03-08 08:13:20 | [diff] [blame] | 1525 | parser.add_option("--skip_canned", action='append', default=[], |
| 1526 | help="A list of checks to skip which appear in " |
| 1527 | "presubmit_canned_checks. Can be provided multiple times " |
| 1528 | "to skip multiple canned checks.") |
[email protected] | 239f411 | 2011-06-03 20:08:23 | [diff] [blame] | 1529 | parser.add_option("--rietveld_url", help=optparse.SUPPRESS_HELP) |
| 1530 | parser.add_option("--rietveld_email", help=optparse.SUPPRESS_HELP) |
| 1531 | parser.add_option("--rietveld_password", help=optparse.SUPPRESS_HELP) |
[email protected] | 720fd7a | 2013-04-24 04:13:50 | [diff] [blame] | 1532 | parser.add_option("--rietveld_fetch", action='store_true', default=False, |
| 1533 | help=optparse.SUPPRESS_HELP) |
[email protected] | f7d31f5 | 2014-01-03 20:14:46 | [diff] [blame] | 1534 | parser.add_option("--trybot-json", |
| 1535 | help="Output trybot information to the file specified.") |
[email protected] | 82e5f28 | 2011-03-17 14:08:55 | [diff] [blame] | 1536 | options, args = parser.parse_args(argv) |
[email protected] | 899e1c1 | 2011-04-07 17:03:18 | [diff] [blame] | 1537 | if options.verbose >= 2: |
[email protected] | 7444c50 | 2011-02-09 14:02:11 | [diff] [blame] | 1538 | logging.basicConfig(level=logging.DEBUG) |
[email protected] | 899e1c1 | 2011-04-07 17:03:18 | [diff] [blame] | 1539 | elif options.verbose: |
| 1540 | logging.basicConfig(level=logging.INFO) |
| 1541 | else: |
| 1542 | logging.basicConfig(level=logging.ERROR) |
[email protected] | 5c8c6de | 2011-03-18 16:20:18 | [diff] [blame] | 1543 | change_class, files = load_files(options, args) |
| 1544 | if not change_class: |
| 1545 | parser.error('For unversioned directory, <files> is not optional.') |
[email protected] | 899e1c1 | 2011-04-07 17:03:18 | [diff] [blame] | 1546 | logging.info('Found %d file(s).' % len(files)) |
[email protected] | 239f411 | 2011-06-03 20:08:23 | [diff] [blame] | 1547 | rietveld_obj = None |
| 1548 | if options.rietveld_url: |
[email protected] | 4bac4b5 | 2012-11-27 20:33:52 | [diff] [blame] | 1549 | rietveld_obj = rietveld.CachingRietveld( |
[email protected] | 239f411 | 2011-06-03 20:08:23 | [diff] [blame] | 1550 | options.rietveld_url, |
| 1551 | options.rietveld_email, |
| 1552 | options.rietveld_password) |
[email protected] | 720fd7a | 2013-04-24 04:13:50 | [diff] [blame] | 1553 | if options.rietveld_fetch: |
| 1554 | assert options.issue |
| 1555 | props = rietveld_obj.get_issue_properties(options.issue, False) |
| 1556 | options.author = props['owner_email'] |
| 1557 | options.description = props['description'] |
| 1558 | logging.info('Got author: "%s"', options.author) |
| 1559 | logging.info('Got description: """\n%s\n"""', options.description) |
[email protected] | f7d31f5 | 2014-01-03 20:14:46 | [diff] [blame] | 1560 | if options.trybot_json: |
| 1561 | with open(options.trybot_json, 'w') as f: |
| 1562 | # Python's sets aren't JSON-encodable, so we convert them to lists here. |
| 1563 | class SetEncoder(json.JSONEncoder): |
| 1564 | # pylint: disable=E0202 |
| 1565 | def default(self, obj): |
| 1566 | if isinstance(obj, set): |
| 1567 | return sorted(obj) |
| 1568 | return json.JSONEncoder.default(self, obj) |
| 1569 | change = change_class(options.name, |
| 1570 | options.description, |
| 1571 | options.root, |
| 1572 | files, |
| 1573 | options.issue, |
| 1574 | options.patchset, |
| 1575 | options.author) |
| 1576 | trybots = DoGetTrySlaves( |
| 1577 | change, |
| 1578 | change.LocalPaths(), |
| 1579 | change.RepositoryRoot(), |
| 1580 | None, |
| 1581 | None, |
| 1582 | options.verbose, |
| 1583 | sys.stdout) |
| 1584 | json.dump(trybots, f, cls=SetEncoder) |
[email protected] | 899e1c1 | 2011-04-07 17:03:18 | [diff] [blame] | 1585 | try: |
[email protected] | 8a4a2bc | 2013-03-08 08:13:20 | [diff] [blame] | 1586 | with canned_check_filter(options.skip_canned): |
| 1587 | results = DoPresubmitChecks( |
| 1588 | change_class(options.name, |
| 1589 | options.description, |
| 1590 | options.root, |
| 1591 | files, |
| 1592 | options.issue, |
| 1593 | options.patchset, |
| 1594 | options.author), |
| 1595 | options.commit, |
| 1596 | options.verbose, |
| 1597 | sys.stdout, |
| 1598 | sys.stdin, |
| 1599 | options.default_presubmit, |
| 1600 | options.may_prompt, |
| 1601 | rietveld_obj) |
[email protected] | 899e1c1 | 2011-04-07 17:03:18 | [diff] [blame] | 1602 | return not results.should_continue() |
[email protected] | 8a4a2bc | 2013-03-08 08:13:20 | [diff] [blame] | 1603 | except NonexistantCannedCheckFilter, e: |
| 1604 | print >> sys.stderr, ( |
| 1605 | 'Attempted to skip nonexistent canned presubmit check: %s' % e.message) |
| 1606 | return 2 |
[email protected] | 899e1c1 | 2011-04-07 17:03:18 | [diff] [blame] | 1607 | except PresubmitFailure, e: |
| 1608 | print >> sys.stderr, e |
| 1609 | print >> sys.stderr, 'Maybe your depot_tools is out of date?' |
| 1610 | print >> sys.stderr, 'If all fails, contact maruel@' |
| 1611 | return 2 |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1612 | |
| 1613 | |
| 1614 | if __name__ == '__main__': |
[email protected] | 35625c7 | 2011-03-23 17:34:02 | [diff] [blame] | 1615 | fix_encoding.fix_encoding() |
[email protected] | 82e5f28 | 2011-03-17 14:08:55 | [diff] [blame] | 1616 | sys.exit(Main(None)) |