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