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