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