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