maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 1 | #!/usr/bin/python |
| 2 | # Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. |
| 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 | |
maruel@chromium.org | b7d4690 | 2009-06-10 14:12:10 +0000 | [diff] [blame] | 9 | __version__ = '1.3.2' |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 10 | |
| 11 | # TODO(joi) Add caching where appropriate/needed. The API is designed to allow |
| 12 | # caching (between all different invocations of presubmit scripts for a given |
| 13 | # change). We should add it as our presubmit scripts start feeling slow. |
| 14 | |
| 15 | import cPickle # Exposed through the API. |
| 16 | import cStringIO # Exposed through the API. |
| 17 | import exceptions |
| 18 | import fnmatch |
| 19 | import glob |
maruel@chromium.org | df1595a | 2009-06-11 02:00:13 +0000 | [diff] [blame] | 20 | import logging |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [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. |
maruel@chromium.org | ce8e46b | 2009-06-26 22:31:51 +0000 | [diff] [blame] | 25 | import random |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [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. |
jam@chromium.org | 2a891dc | 2009-08-20 20:33:37 +0000 | [diff] [blame] | 30 | import time |
maruel@chromium.org | d7dccf5 | 2009-06-06 18:51:58 +0000 | [diff] [blame] | 31 | import traceback # Exposed through the API. |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 32 | import types |
maruel@chromium.org | 1487d53 | 2009-06-06 00:22:57 +0000 | [diff] [blame] | 33 | import unittest # Exposed through the API. |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 34 | import urllib2 # Exposed through the API. |
maruel@chromium.org | 1e08c00 | 2009-05-28 19:09:33 +0000 | [diff] [blame] | 35 | import warnings |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 36 | |
| 37 | # Local imports. |
| 38 | # TODO(joi) Would be cleaner to factor out utils in gcl to separate module, but |
| 39 | # for now it would only be a couple of functions so hardly worth it. |
| 40 | import gcl |
maruel@chromium.org | 46a9410 | 2009-05-12 20:32:43 +0000 | [diff] [blame] | 41 | import gclient |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 42 | import presubmit_canned_checks |
| 43 | |
| 44 | |
maruel@chromium.org | ce8e46b | 2009-06-26 22:31:51 +0000 | [diff] [blame] | 45 | # Ask for feedback only once in program lifetime. |
| 46 | _ASKED_FOR_FEEDBACK = False |
| 47 | |
| 48 | |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 49 | class NotImplementedException(Exception): |
| 50 | """We're leaving placeholders in a bunch of places to remind us of the |
| 51 | design of the API, but we have not implemented all of it yet. Implement as |
| 52 | the need arises. |
| 53 | """ |
| 54 | pass |
| 55 | |
| 56 | |
| 57 | def normpath(path): |
| 58 | '''Version of os.path.normpath that also changes backward slashes to |
| 59 | forward slashes when not running on Windows. |
| 60 | ''' |
| 61 | # This is safe to always do because the Windows version of os.path.normpath |
| 62 | # will replace forward slashes with backward slashes. |
| 63 | path = path.replace(os.sep, '/') |
| 64 | return os.path.normpath(path) |
| 65 | |
| 66 | |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 67 | class OutputApi(object): |
| 68 | """This class (more like a module) gets passed to presubmit scripts so that |
| 69 | they can specify various types of results. |
| 70 | """ |
| 71 | |
| 72 | class PresubmitResult(object): |
| 73 | """Base class for result objects.""" |
| 74 | |
| 75 | def __init__(self, message, items=None, long_text=''): |
| 76 | """ |
| 77 | message: A short one-line message to indicate errors. |
| 78 | items: A list of short strings to indicate where errors occurred. |
| 79 | long_text: multi-line text output, e.g. from another tool |
| 80 | """ |
| 81 | self._message = message |
| 82 | self._items = [] |
| 83 | if items: |
| 84 | self._items = items |
| 85 | self._long_text = long_text.rstrip() |
| 86 | |
| 87 | def _Handle(self, output_stream, input_stream, may_prompt=True): |
| 88 | """Writes this result to the output stream. |
| 89 | |
| 90 | Args: |
| 91 | output_stream: Where to write |
| 92 | |
| 93 | Returns: |
| 94 | True if execution may continue, False otherwise. |
| 95 | """ |
| 96 | output_stream.write(self._message) |
| 97 | output_stream.write('\n') |
| 98 | for item in self._items: |
maruel@chromium.org | 5de1397 | 2009-06-10 18:16:06 +0000 | [diff] [blame] | 99 | output_stream.write(' %s\n' % str(item)) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 100 | if self._long_text: |
maruel@chromium.org | b0dfd35 | 2009-06-10 14:12:54 +0000 | [diff] [blame] | 101 | output_stream.write('\n***************\n%s\n***************\n' % |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 102 | self._long_text) |
| 103 | |
| 104 | if self.ShouldPrompt() and may_prompt: |
| 105 | output_stream.write('Are you sure you want to continue? (y/N): ') |
| 106 | response = input_stream.readline() |
| 107 | if response.strip().lower() != 'y': |
| 108 | return False |
| 109 | |
| 110 | return not self.IsFatal() |
| 111 | |
| 112 | def IsFatal(self): |
| 113 | """An error that is fatal stops g4 mail/submit immediately, i.e. before |
| 114 | other presubmit scripts are run. |
| 115 | """ |
| 116 | return False |
| 117 | |
| 118 | def ShouldPrompt(self): |
| 119 | """Whether this presubmit result should result in a prompt warning.""" |
| 120 | return False |
| 121 | |
| 122 | class PresubmitError(PresubmitResult): |
| 123 | """A hard presubmit error.""" |
| 124 | def IsFatal(self): |
| 125 | return True |
| 126 | |
| 127 | class PresubmitPromptWarning(PresubmitResult): |
| 128 | """An warning that prompts the user if they want to continue.""" |
| 129 | def ShouldPrompt(self): |
| 130 | return True |
| 131 | |
| 132 | class PresubmitNotifyResult(PresubmitResult): |
| 133 | """Just print something to the screen -- but it's not even a warning.""" |
| 134 | pass |
| 135 | |
| 136 | class MailTextResult(PresubmitResult): |
| 137 | """A warning that should be included in the review request email.""" |
| 138 | def __init__(self, *args, **kwargs): |
| 139 | raise NotImplementedException() # TODO(joi) Implement. |
| 140 | |
| 141 | |
| 142 | class InputApi(object): |
| 143 | """An instance of this object is passed to presubmit scripts so they can |
| 144 | know stuff about the change they're looking at. |
| 145 | """ |
| 146 | |
maruel@chromium.org | 3410d91 | 2009-06-09 20:56:16 +0000 | [diff] [blame] | 147 | # File extensions that are considered source files from a style guide |
| 148 | # perspective. Don't modify this list from a presubmit script! |
| 149 | DEFAULT_WHITE_LIST = ( |
| 150 | # C++ and friends |
| 151 | r".*\.c", r".*\.cc", r".*\.cpp", r".*\.h", r".*\.m", r".*\.mm", |
| 152 | r".*\.inl", r".*\.asm", r".*\.hxx", r".*\.hpp", |
| 153 | # Scripts |
| 154 | r".*\.js", r".*\.py", r".*\.json", r".*\.sh", r".*\.rb", |
| 155 | # No extension at all |
| 156 | r"(^|.*[\\\/])[^.]+$", |
| 157 | # Other |
maruel@chromium.org | d59982a | 2009-08-24 15:48:47 +0000 | [diff] [blame] | 158 | r".*\.java", r".*\.mk", r".*\.am", r".*\.txt", |
maruel@chromium.org | 3410d91 | 2009-06-09 20:56:16 +0000 | [diff] [blame] | 159 | ) |
| 160 | |
| 161 | # Path regexp that should be excluded from being considered containing source |
| 162 | # files. Don't modify this list from a presubmit script! |
| 163 | DEFAULT_BLACK_LIST = ( |
| 164 | r".*\bexperimental[\\\/].*", |
| 165 | r".*\bthird_party[\\\/].*", |
| 166 | # Output directories (just in case) |
| 167 | r".*\bDebug[\\\/].*", |
| 168 | r".*\bRelease[\\\/].*", |
| 169 | r".*\bxcodebuild[\\\/].*", |
| 170 | r".*\bsconsbuild[\\\/].*", |
| 171 | # All caps files like README and LICENCE. |
maruel@chromium.org | df1595a | 2009-06-11 02:00:13 +0000 | [diff] [blame] | 172 | r".*\b[A-Z0-9_]+$", |
| 173 | # SCM (can happen in dual SCM configuration). (Slightly over aggressive) |
| 174 | r".*\.git[\\\/].*", |
| 175 | r".*\.svn[\\\/].*", |
maruel@chromium.org | 3410d91 | 2009-06-09 20:56:16 +0000 | [diff] [blame] | 176 | ) |
| 177 | |
maruel@chromium.org | d7dccf5 | 2009-06-06 18:51:58 +0000 | [diff] [blame] | 178 | def __init__(self, change, presubmit_path, is_committing): |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 179 | """Builds an InputApi object. |
| 180 | |
| 181 | Args: |
maruel@chromium.org | 4ff922a | 2009-06-12 20:20:19 +0000 | [diff] [blame] | 182 | change: A presubmit.Change object. |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 183 | presubmit_path: The path to the presubmit script being processed. |
maruel@chromium.org | d7dccf5 | 2009-06-06 18:51:58 +0000 | [diff] [blame] | 184 | is_committing: True if the change is about to be committed. |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 185 | """ |
maruel@chromium.org | 9711bba | 2009-05-22 23:51:39 +0000 | [diff] [blame] | 186 | # Version number of the presubmit_support script. |
| 187 | self.version = [int(x) for x in __version__.split('.')] |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 188 | self.change = change |
maruel@chromium.org | d7dccf5 | 2009-06-06 18:51:58 +0000 | [diff] [blame] | 189 | self.is_committing = is_committing |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 190 | |
| 191 | # We expose various modules and functions as attributes of the input_api |
| 192 | # so that presubmit scripts don't have to import them. |
| 193 | self.basename = os.path.basename |
| 194 | self.cPickle = cPickle |
| 195 | self.cStringIO = cStringIO |
| 196 | self.os_path = os.path |
| 197 | self.pickle = pickle |
| 198 | self.marshal = marshal |
| 199 | self.re = re |
| 200 | self.subprocess = subprocess |
| 201 | self.tempfile = tempfile |
maruel@chromium.org | d7dccf5 | 2009-06-06 18:51:58 +0000 | [diff] [blame] | 202 | self.traceback = traceback |
maruel@chromium.org | 1487d53 | 2009-06-06 00:22:57 +0000 | [diff] [blame] | 203 | self.unittest = unittest |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 204 | self.urllib2 = urllib2 |
| 205 | |
maruel@chromium.org | c0b2297 | 2009-06-25 16:19:14 +0000 | [diff] [blame] | 206 | # To easily fork python. |
| 207 | self.python_executable = sys.executable |
| 208 | self.environ = os.environ |
| 209 | |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 210 | # InputApi.platform is the platform you're currently running on. |
| 211 | self.platform = sys.platform |
| 212 | |
| 213 | # The local path of the currently-being-processed presubmit script. |
maruel@chromium.org | 3d23524 | 2009-05-15 12:40:48 +0000 | [diff] [blame] | 214 | self._current_presubmit_path = os.path.dirname(presubmit_path) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 215 | |
| 216 | # We carry the canned checks so presubmit scripts can easily use them. |
| 217 | self.canned_checks = presubmit_canned_checks |
| 218 | |
| 219 | def PresubmitLocalPath(self): |
| 220 | """Returns the local path of the presubmit script currently being run. |
| 221 | |
| 222 | This is useful if you don't want to hard-code absolute paths in the |
| 223 | presubmit script. For example, It can be used to find another file |
| 224 | relative to the PRESUBMIT.py script, so the whole tree can be branched and |
| 225 | the presubmit script still works, without editing its content. |
| 226 | """ |
maruel@chromium.org | 3d23524 | 2009-05-15 12:40:48 +0000 | [diff] [blame] | 227 | return self._current_presubmit_path |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 228 | |
maruel@chromium.org | 1e08c00 | 2009-05-28 19:09:33 +0000 | [diff] [blame] | 229 | def DepotToLocalPath(self, depot_path): |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 230 | """Translate a depot path to a local path (relative to client root). |
| 231 | |
| 232 | Args: |
| 233 | Depot path as a string. |
| 234 | |
| 235 | Returns: |
| 236 | The local path of the depot path under the user's current client, or None |
| 237 | if the file is not mapped. |
| 238 | |
| 239 | Remember to check for the None case and show an appropriate error! |
| 240 | """ |
maruel@chromium.org | 46a9410 | 2009-05-12 20:32:43 +0000 | [diff] [blame] | 241 | local_path = gclient.CaptureSVNInfo(depot_path).get('Path') |
maruel@chromium.org | 1e08c00 | 2009-05-28 19:09:33 +0000 | [diff] [blame] | 242 | if local_path: |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 243 | return local_path |
| 244 | |
maruel@chromium.org | 1e08c00 | 2009-05-28 19:09:33 +0000 | [diff] [blame] | 245 | def LocalToDepotPath(self, local_path): |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 246 | """Translate a local path to a depot path. |
| 247 | |
| 248 | Args: |
| 249 | Local path (relative to current directory, or absolute) as a string. |
| 250 | |
| 251 | Returns: |
| 252 | The depot path (SVN URL) of the file if mapped, otherwise None. |
| 253 | """ |
maruel@chromium.org | 46a9410 | 2009-05-12 20:32:43 +0000 | [diff] [blame] | 254 | depot_path = gclient.CaptureSVNInfo(local_path).get('URL') |
maruel@chromium.org | 1e08c00 | 2009-05-28 19:09:33 +0000 | [diff] [blame] | 255 | if depot_path: |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 256 | return depot_path |
| 257 | |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 258 | def AffectedFiles(self, include_dirs=False, include_deletes=True): |
| 259 | """Same as input_api.change.AffectedFiles() except only lists files |
| 260 | (and optionally directories) in the same directory as the current presubmit |
| 261 | script, or subdirectories thereof. |
| 262 | """ |
maruel@chromium.org | 3d23524 | 2009-05-15 12:40:48 +0000 | [diff] [blame] | 263 | dir_with_slash = normpath("%s/" % self.PresubmitLocalPath()) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 264 | if len(dir_with_slash) == 1: |
| 265 | dir_with_slash = '' |
maruel@chromium.org | 4661e0c | 2009-06-04 00:45:26 +0000 | [diff] [blame] | 266 | return filter( |
| 267 | lambda x: normpath(x.AbsoluteLocalPath()).startswith(dir_with_slash), |
| 268 | self.change.AffectedFiles(include_dirs, include_deletes)) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 269 | |
| 270 | def LocalPaths(self, include_dirs=False): |
| 271 | """Returns local paths of input_api.AffectedFiles().""" |
| 272 | return [af.LocalPath() for af in self.AffectedFiles(include_dirs)] |
| 273 | |
| 274 | def AbsoluteLocalPaths(self, include_dirs=False): |
| 275 | """Returns absolute local paths of input_api.AffectedFiles().""" |
| 276 | return [af.AbsoluteLocalPath() for af in self.AffectedFiles(include_dirs)] |
| 277 | |
| 278 | def ServerPaths(self, include_dirs=False): |
| 279 | """Returns server paths of input_api.AffectedFiles().""" |
| 280 | return [af.ServerPath() for af in self.AffectedFiles(include_dirs)] |
| 281 | |
maruel@chromium.org | 77c4f0f | 2009-05-29 18:53:04 +0000 | [diff] [blame] | 282 | def AffectedTextFiles(self, include_deletes=None): |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 283 | """Same as input_api.change.AffectedTextFiles() except only lists files |
| 284 | in the same directory as the current presubmit script, or subdirectories |
| 285 | thereof. |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 286 | """ |
maruel@chromium.org | 77c4f0f | 2009-05-29 18:53:04 +0000 | [diff] [blame] | 287 | if include_deletes is not None: |
| 288 | warnings.warn("AffectedTextFiles(include_deletes=%s)" |
| 289 | " is deprecated and ignored" % str(include_deletes), |
| 290 | category=DeprecationWarning, |
| 291 | stacklevel=2) |
| 292 | return filter(lambda x: x.IsTextFile(), |
| 293 | self.AffectedFiles(include_dirs=False, include_deletes=False)) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 294 | |
maruel@chromium.org | 3410d91 | 2009-06-09 20:56:16 +0000 | [diff] [blame] | 295 | def FilterSourceFile(self, affected_file, white_list=None, black_list=None): |
| 296 | """Filters out files that aren't considered "source file". |
| 297 | |
| 298 | If white_list or black_list is None, InputApi.DEFAULT_WHITE_LIST |
| 299 | and InputApi.DEFAULT_BLACK_LIST is used respectively. |
| 300 | |
| 301 | The lists will be compiled as regular expression and |
| 302 | AffectedFile.LocalPath() needs to pass both list. |
| 303 | |
| 304 | Note: Copy-paste this function to suit your needs or use a lambda function. |
| 305 | """ |
| 306 | def Find(affected_file, list): |
| 307 | for item in list: |
maruel@chromium.org | df1595a | 2009-06-11 02:00:13 +0000 | [diff] [blame] | 308 | local_path = affected_file.LocalPath() |
| 309 | if self.re.match(item, local_path): |
| 310 | logging.debug("%s matched %s" % (item, local_path)) |
maruel@chromium.org | 3410d91 | 2009-06-09 20:56:16 +0000 | [diff] [blame] | 311 | return True |
| 312 | return False |
| 313 | return (Find(affected_file, white_list or self.DEFAULT_WHITE_LIST) and |
| 314 | not Find(affected_file, black_list or self.DEFAULT_BLACK_LIST)) |
| 315 | |
| 316 | def AffectedSourceFiles(self, source_file): |
| 317 | """Filter the list of AffectedTextFiles by the function source_file. |
| 318 | |
| 319 | If source_file is None, InputApi.FilterSourceFile() is used. |
| 320 | """ |
| 321 | if not source_file: |
| 322 | source_file = self.FilterSourceFile |
| 323 | return filter(source_file, self.AffectedTextFiles()) |
| 324 | |
| 325 | def RightHandSideLines(self, source_file_filter=None): |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 326 | """An iterator over all text lines in "new" version of changed files. |
| 327 | |
| 328 | Only lists lines from new or modified text files in the change that are |
| 329 | contained by the directory of the currently executing presubmit script. |
| 330 | |
| 331 | This is useful for doing line-by-line regex checks, like checking for |
| 332 | trailing whitespace. |
| 333 | |
| 334 | Yields: |
| 335 | a 3 tuple: |
| 336 | the AffectedFile instance of the current file; |
| 337 | integer line number (1-based); and |
| 338 | the contents of the line as a string. |
maruel@chromium.org | 1487d53 | 2009-06-06 00:22:57 +0000 | [diff] [blame] | 339 | |
| 340 | Note: The cariage return (LF or CR) is stripped off. |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 341 | """ |
maruel@chromium.org | 3410d91 | 2009-06-09 20:56:16 +0000 | [diff] [blame] | 342 | files = self.AffectedSourceFiles(source_file_filter) |
| 343 | return InputApi._RightHandSideLinesImpl(files) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 344 | |
maruel@chromium.org | 44a17ad | 2009-06-08 14:14:35 +0000 | [diff] [blame] | 345 | def ReadFile(self, file, mode='r'): |
| 346 | """Reads an arbitrary file. |
thestig@chromium.org | da8cddd | 2009-08-13 00:25:55 +0000 | [diff] [blame] | 347 | |
maruel@chromium.org | 44a17ad | 2009-06-08 14:14:35 +0000 | [diff] [blame] | 348 | Deny reading anything outside the repository. |
| 349 | """ |
| 350 | if isinstance(file, AffectedFile): |
| 351 | file = file.AbsoluteLocalPath() |
| 352 | if not file.startswith(self.change.RepositoryRoot()): |
| 353 | raise IOError('Access outside the repository root is denied.') |
| 354 | return gcl.ReadFile(file, mode) |
| 355 | |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 356 | @staticmethod |
| 357 | def _RightHandSideLinesImpl(affected_files): |
| 358 | """Implements RightHandSideLines for InputApi and GclChange.""" |
| 359 | for af in affected_files: |
| 360 | lines = af.NewContents() |
| 361 | line_number = 0 |
| 362 | for line in lines: |
| 363 | line_number += 1 |
| 364 | yield (af, line_number, line) |
| 365 | |
| 366 | |
| 367 | class AffectedFile(object): |
| 368 | """Representation of a file in a change.""" |
| 369 | |
| 370 | def __init__(self, path, action, repository_root=''): |
maruel@chromium.org | 15bdffa | 2009-05-29 11:16:29 +0000 | [diff] [blame] | 371 | self._path = path |
| 372 | self._action = action |
maruel@chromium.org | 4ff922a | 2009-06-12 20:20:19 +0000 | [diff] [blame] | 373 | self._local_root = repository_root |
maruel@chromium.org | 15bdffa | 2009-05-29 11:16:29 +0000 | [diff] [blame] | 374 | self._is_directory = None |
| 375 | self._properties = {} |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 376 | |
| 377 | def ServerPath(self): |
| 378 | """Returns a path string that identifies the file in the SCM system. |
| 379 | |
| 380 | Returns the empty string if the file does not exist in SCM. |
| 381 | """ |
maruel@chromium.org | dbbeedc | 2009-05-22 20:26:17 +0000 | [diff] [blame] | 382 | return "" |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 383 | |
| 384 | def LocalPath(self): |
| 385 | """Returns the path of this file on the local disk relative to client root. |
| 386 | """ |
maruel@chromium.org | 15bdffa | 2009-05-29 11:16:29 +0000 | [diff] [blame] | 387 | return normpath(self._path) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 388 | |
| 389 | def AbsoluteLocalPath(self): |
| 390 | """Returns the absolute path of this file on the local disk. |
| 391 | """ |
maruel@chromium.org | 4ff922a | 2009-06-12 20:20:19 +0000 | [diff] [blame] | 392 | return normpath(os.path.join(self._local_root, self.LocalPath())) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 393 | |
| 394 | def IsDirectory(self): |
| 395 | """Returns true if this object is a directory.""" |
maruel@chromium.org | 15bdffa | 2009-05-29 11:16:29 +0000 | [diff] [blame] | 396 | if self._is_directory is None: |
| 397 | path = self.AbsoluteLocalPath() |
| 398 | self._is_directory = (os.path.exists(path) and |
| 399 | os.path.isdir(path)) |
| 400 | return self._is_directory |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 401 | |
| 402 | def Action(self): |
| 403 | """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] | 404 | # TODO(maruel): Somewhat crappy, Could be "A" or "A +" for svn but |
| 405 | # different for other SCM. |
maruel@chromium.org | 15bdffa | 2009-05-29 11:16:29 +0000 | [diff] [blame] | 406 | return self._action |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 407 | |
maruel@chromium.org | dbbeedc | 2009-05-22 20:26:17 +0000 | [diff] [blame] | 408 | def Property(self, property_name): |
| 409 | """Returns the specified SCM property of this file, or None if no such |
| 410 | property. |
| 411 | """ |
maruel@chromium.org | 15bdffa | 2009-05-29 11:16:29 +0000 | [diff] [blame] | 412 | return self._properties.get(property_name, None) |
maruel@chromium.org | dbbeedc | 2009-05-22 20:26:17 +0000 | [diff] [blame] | 413 | |
maruel@chromium.org | 1e08c00 | 2009-05-28 19:09:33 +0000 | [diff] [blame] | 414 | def IsTextFile(self): |
maruel@chromium.org | 77c4f0f | 2009-05-29 18:53:04 +0000 | [diff] [blame] | 415 | """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] | 416 | |
maruel@chromium.org | 77c4f0f | 2009-05-29 18:53:04 +0000 | [diff] [blame] | 417 | Deleted files are not text file.""" |
maruel@chromium.org | 1e08c00 | 2009-05-28 19:09:33 +0000 | [diff] [blame] | 418 | raise NotImplementedError() # Implement when needed |
| 419 | |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 420 | def NewContents(self): |
| 421 | """Returns an iterator over the lines in the new version of file. |
| 422 | |
| 423 | The new version is the file in the user's workspace, i.e. the "right hand |
| 424 | side". |
| 425 | |
| 426 | Contents will be empty if the file is a directory or does not exist. |
maruel@chromium.org | 1487d53 | 2009-06-06 00:22:57 +0000 | [diff] [blame] | 427 | Note: The cariage returns (LF or CR) are stripped off. |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 428 | """ |
| 429 | if self.IsDirectory(): |
| 430 | return [] |
| 431 | else: |
| 432 | return gcl.ReadFile(self.AbsoluteLocalPath()).splitlines() |
| 433 | |
| 434 | def OldContents(self): |
| 435 | """Returns an iterator over the lines in the old version of file. |
| 436 | |
| 437 | The old version is the file in depot, i.e. the "left hand side". |
| 438 | """ |
| 439 | raise NotImplementedError() # Implement when needed |
| 440 | |
| 441 | def OldFileTempPath(self): |
| 442 | """Returns the path on local disk where the old contents resides. |
| 443 | |
| 444 | The old version is the file in depot, i.e. the "left hand side". |
| 445 | This is a read-only cached copy of the old contents. *DO NOT* try to |
| 446 | modify this file. |
| 447 | """ |
| 448 | raise NotImplementedError() # Implement if/when needed. |
| 449 | |
maruel@chromium.org | 5de1397 | 2009-06-10 18:16:06 +0000 | [diff] [blame] | 450 | def __str__(self): |
| 451 | return self.LocalPath() |
| 452 | |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 453 | |
maruel@chromium.org | dbbeedc | 2009-05-22 20:26:17 +0000 | [diff] [blame] | 454 | class SvnAffectedFile(AffectedFile): |
| 455 | """Representation of a file in a change out of a Subversion checkout.""" |
| 456 | |
maruel@chromium.org | 15bdffa | 2009-05-29 11:16:29 +0000 | [diff] [blame] | 457 | def __init__(self, *args, **kwargs): |
| 458 | AffectedFile.__init__(self, *args, **kwargs) |
| 459 | self._server_path = None |
| 460 | self._is_text_file = None |
| 461 | |
maruel@chromium.org | dbbeedc | 2009-05-22 20:26:17 +0000 | [diff] [blame] | 462 | def ServerPath(self): |
maruel@chromium.org | 15bdffa | 2009-05-29 11:16:29 +0000 | [diff] [blame] | 463 | if self._server_path is None: |
| 464 | self._server_path = gclient.CaptureSVNInfo( |
maruel@chromium.org | dbbeedc | 2009-05-22 20:26:17 +0000 | [diff] [blame] | 465 | self.AbsoluteLocalPath()).get('URL', '') |
maruel@chromium.org | 15bdffa | 2009-05-29 11:16:29 +0000 | [diff] [blame] | 466 | return self._server_path |
maruel@chromium.org | dbbeedc | 2009-05-22 20:26:17 +0000 | [diff] [blame] | 467 | |
| 468 | def IsDirectory(self): |
maruel@chromium.org | 15bdffa | 2009-05-29 11:16:29 +0000 | [diff] [blame] | 469 | if self._is_directory is None: |
| 470 | path = self.AbsoluteLocalPath() |
maruel@chromium.org | dbbeedc | 2009-05-22 20:26:17 +0000 | [diff] [blame] | 471 | if os.path.exists(path): |
| 472 | # Retrieve directly from the file system; it is much faster than |
| 473 | # querying subversion, especially on Windows. |
maruel@chromium.org | 15bdffa | 2009-05-29 11:16:29 +0000 | [diff] [blame] | 474 | self._is_directory = os.path.isdir(path) |
maruel@chromium.org | dbbeedc | 2009-05-22 20:26:17 +0000 | [diff] [blame] | 475 | else: |
maruel@chromium.org | 15bdffa | 2009-05-29 11:16:29 +0000 | [diff] [blame] | 476 | self._is_directory = gclient.CaptureSVNInfo( |
maruel@chromium.org | dbbeedc | 2009-05-22 20:26:17 +0000 | [diff] [blame] | 477 | path).get('Node Kind') in ('dir', 'directory') |
maruel@chromium.org | 15bdffa | 2009-05-29 11:16:29 +0000 | [diff] [blame] | 478 | return self._is_directory |
maruel@chromium.org | dbbeedc | 2009-05-22 20:26:17 +0000 | [diff] [blame] | 479 | |
| 480 | def Property(self, property_name): |
maruel@chromium.org | 15bdffa | 2009-05-29 11:16:29 +0000 | [diff] [blame] | 481 | if not property_name in self._properties: |
| 482 | self._properties[property_name] = gcl.GetSVNFileProperty( |
maruel@chromium.org | 196f8cb | 2009-06-11 00:32:06 +0000 | [diff] [blame] | 483 | self.AbsoluteLocalPath(), property_name).rstrip() |
maruel@chromium.org | 15bdffa | 2009-05-29 11:16:29 +0000 | [diff] [blame] | 484 | return self._properties[property_name] |
maruel@chromium.org | dbbeedc | 2009-05-22 20:26:17 +0000 | [diff] [blame] | 485 | |
maruel@chromium.org | 1e08c00 | 2009-05-28 19:09:33 +0000 | [diff] [blame] | 486 | def IsTextFile(self): |
maruel@chromium.org | 15bdffa | 2009-05-29 11:16:29 +0000 | [diff] [blame] | 487 | if self._is_text_file is None: |
| 488 | if self.Action() == 'D': |
| 489 | # A deleted file is not a text file. |
| 490 | self._is_text_file = False |
| 491 | elif self.IsDirectory(): |
| 492 | self._is_text_file = False |
| 493 | else: |
| 494 | mime_type = gcl.GetSVNFileProperty(self.AbsoluteLocalPath(), |
| 495 | 'svn:mime-type') |
| 496 | self._is_text_file = (not mime_type or mime_type.startswith('text/')) |
| 497 | return self._is_text_file |
maruel@chromium.org | 1e08c00 | 2009-05-28 19:09:33 +0000 | [diff] [blame] | 498 | |
maruel@chromium.org | dbbeedc | 2009-05-22 20:26:17 +0000 | [diff] [blame] | 499 | |
maruel@chromium.org | c70a220 | 2009-06-17 12:55:10 +0000 | [diff] [blame] | 500 | class GitAffectedFile(AffectedFile): |
| 501 | """Representation of a file in a change out of a git checkout.""" |
| 502 | |
| 503 | def __init__(self, *args, **kwargs): |
| 504 | AffectedFile.__init__(self, *args, **kwargs) |
| 505 | self._server_path = None |
| 506 | self._is_text_file = None |
maruel@chromium.org | c70a220 | 2009-06-17 12:55:10 +0000 | [diff] [blame] | 507 | |
| 508 | def ServerPath(self): |
| 509 | if self._server_path is None: |
| 510 | raise NotImplementedException() # TODO(maruel) Implement. |
| 511 | return self._server_path |
| 512 | |
| 513 | def IsDirectory(self): |
| 514 | if self._is_directory is None: |
| 515 | path = self.AbsoluteLocalPath() |
| 516 | if os.path.exists(path): |
| 517 | # Retrieve directly from the file system; it is much faster than |
| 518 | # querying subversion, especially on Windows. |
| 519 | self._is_directory = os.path.isdir(path) |
| 520 | else: |
| 521 | # raise NotImplementedException() # TODO(maruel) Implement. |
| 522 | self._is_directory = False |
| 523 | return self._is_directory |
| 524 | |
| 525 | def Property(self, property_name): |
| 526 | if not property_name in self._properties: |
| 527 | raise NotImplementedException() # TODO(maruel) Implement. |
| 528 | return self._properties[property_name] |
| 529 | |
| 530 | def IsTextFile(self): |
| 531 | if self._is_text_file is None: |
| 532 | if self.Action() == 'D': |
| 533 | # A deleted file is not a text file. |
| 534 | self._is_text_file = False |
| 535 | elif self.IsDirectory(): |
| 536 | self._is_text_file = False |
| 537 | else: |
| 538 | # raise NotImplementedException() # TODO(maruel) Implement. |
| 539 | self._is_text_file = os.path.isfile(self.AbsoluteLocalPath()) |
| 540 | return self._is_text_file |
| 541 | |
| 542 | |
maruel@chromium.org | 4ff922a | 2009-06-12 20:20:19 +0000 | [diff] [blame] | 543 | class Change(object): |
maruel@chromium.org | 6ebe68a | 2009-05-27 23:43:40 +0000 | [diff] [blame] | 544 | """Describe a change. |
| 545 | |
| 546 | Used directly by the presubmit scripts to query the current change being |
| 547 | tested. |
thestig@chromium.org | da8cddd | 2009-08-13 00:25:55 +0000 | [diff] [blame] | 548 | |
maruel@chromium.org | 6ebe68a | 2009-05-27 23:43:40 +0000 | [diff] [blame] | 549 | Instance members: |
| 550 | tags: Dictionnary of KEY=VALUE pairs found in the change description. |
| 551 | self.KEY: equivalent to tags['KEY'] |
| 552 | """ |
| 553 | |
maruel@chromium.org | 4ff922a | 2009-06-12 20:20:19 +0000 | [diff] [blame] | 554 | _AFFECTED_FILES = AffectedFile |
| 555 | |
maruel@chromium.org | 6ebe68a | 2009-05-27 23:43:40 +0000 | [diff] [blame] | 556 | # Matches key/value (or "tag") lines in changelist descriptions. |
maruel@chromium.org | 4ff922a | 2009-06-12 20:20:19 +0000 | [diff] [blame] | 557 | _TAG_LINE_RE = re.compile( |
maruel@chromium.org | 6ebe68a | 2009-05-27 23:43:40 +0000 | [diff] [blame] | 558 | '^\s*(?P<key>[A-Z][A-Z_0-9]*)\s*=\s*(?P<value>.*?)\s*$') |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 559 | |
maruel@chromium.org | 4ff922a | 2009-06-12 20:20:19 +0000 | [diff] [blame] | 560 | def __init__(self, name, description, local_root, files, issue, patchset): |
| 561 | if files is None: |
| 562 | files = [] |
| 563 | self._name = name |
| 564 | self._full_description = description |
| 565 | self._local_root = local_root |
| 566 | self.issue = issue |
| 567 | self.patchset = patchset |
thestig@chromium.org | da8cddd | 2009-08-13 00:25:55 +0000 | [diff] [blame] | 568 | self.scm = '' |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 569 | |
| 570 | # From the description text, build up a dictionary of key/value pairs |
| 571 | # plus the description minus all key/value or "tag" lines. |
maruel@chromium.org | 6ebe68a | 2009-05-27 23:43:40 +0000 | [diff] [blame] | 572 | self._description_without_tags = [] |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 573 | self.tags = {} |
maruel@chromium.org | 8d5c9a5 | 2009-06-12 15:59:08 +0000 | [diff] [blame] | 574 | for line in self._full_description.splitlines(): |
maruel@chromium.org | 4ff922a | 2009-06-12 20:20:19 +0000 | [diff] [blame] | 575 | m = self._TAG_LINE_RE.match(line) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 576 | if m: |
| 577 | self.tags[m.group('key')] = m.group('value') |
| 578 | else: |
maruel@chromium.org | 6ebe68a | 2009-05-27 23:43:40 +0000 | [diff] [blame] | 579 | self._description_without_tags.append(line) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 580 | |
| 581 | # Change back to text and remove whitespace at end. |
maruel@chromium.org | 6ebe68a | 2009-05-27 23:43:40 +0000 | [diff] [blame] | 582 | self._description_without_tags = '\n'.join(self._description_without_tags) |
| 583 | self._description_without_tags = self._description_without_tags.rstrip() |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 584 | |
maruel@chromium.org | 6ebe68a | 2009-05-27 23:43:40 +0000 | [diff] [blame] | 585 | self._affected_files = [ |
maruel@chromium.org | 4ff922a | 2009-06-12 20:20:19 +0000 | [diff] [blame] | 586 | self._AFFECTED_FILES(info[1], info[0].strip(), self._local_root) |
| 587 | for info in files |
maruel@chromium.org | dbbeedc | 2009-05-22 20:26:17 +0000 | [diff] [blame] | 588 | ] |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 589 | |
maruel@chromium.org | 92022ec | 2009-06-11 01:59:28 +0000 | [diff] [blame] | 590 | def Name(self): |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 591 | """Returns the change name.""" |
maruel@chromium.org | 6ebe68a | 2009-05-27 23:43:40 +0000 | [diff] [blame] | 592 | return self._name |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 593 | |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 594 | def DescriptionText(self): |
| 595 | """Returns the user-entered changelist description, minus tags. |
| 596 | |
| 597 | Any line in the user-provided description starting with e.g. "FOO=" |
| 598 | (whitespace permitted before and around) is considered a tag line. Such |
| 599 | lines are stripped out of the description this function returns. |
| 600 | """ |
maruel@chromium.org | 6ebe68a | 2009-05-27 23:43:40 +0000 | [diff] [blame] | 601 | return self._description_without_tags |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 602 | |
| 603 | def FullDescriptionText(self): |
| 604 | """Returns the complete changelist description including tags.""" |
maruel@chromium.org | 6ebe68a | 2009-05-27 23:43:40 +0000 | [diff] [blame] | 605 | return self._full_description |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 606 | |
| 607 | def RepositoryRoot(self): |
maruel@chromium.org | 92022ec | 2009-06-11 01:59:28 +0000 | [diff] [blame] | 608 | """Returns the repository (checkout) root directory for this change, |
| 609 | as an absolute path. |
| 610 | """ |
maruel@chromium.org | 4ff922a | 2009-06-12 20:20:19 +0000 | [diff] [blame] | 611 | return self._local_root |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 612 | |
| 613 | def __getattr__(self, attr): |
maruel@chromium.org | 92022ec | 2009-06-11 01:59:28 +0000 | [diff] [blame] | 614 | """Return tags directly as attributes on the object.""" |
| 615 | if not re.match(r"^[A-Z_]*$", attr): |
| 616 | raise AttributeError(self, attr) |
maruel@chromium.org | e1a524f | 2009-05-27 14:43:46 +0000 | [diff] [blame] | 617 | return self.tags.get(attr) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 618 | |
| 619 | def AffectedFiles(self, include_dirs=False, include_deletes=True): |
| 620 | """Returns a list of AffectedFile instances for all files in the change. |
| 621 | |
| 622 | Args: |
| 623 | include_deletes: If false, deleted files will be filtered out. |
| 624 | include_dirs: True to include directories in the list |
| 625 | |
| 626 | Returns: |
| 627 | [AffectedFile(path, action), AffectedFile(path, action)] |
| 628 | """ |
| 629 | if include_dirs: |
maruel@chromium.org | 6ebe68a | 2009-05-27 23:43:40 +0000 | [diff] [blame] | 630 | affected = self._affected_files |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 631 | else: |
maruel@chromium.org | 6ebe68a | 2009-05-27 23:43:40 +0000 | [diff] [blame] | 632 | affected = filter(lambda x: not x.IsDirectory(), self._affected_files) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 633 | |
| 634 | if include_deletes: |
| 635 | return affected |
| 636 | else: |
| 637 | return filter(lambda x: x.Action() != 'D', affected) |
| 638 | |
maruel@chromium.org | 77c4f0f | 2009-05-29 18:53:04 +0000 | [diff] [blame] | 639 | def AffectedTextFiles(self, include_deletes=None): |
| 640 | """Return a list of the existing text files in a change.""" |
| 641 | if include_deletes is not None: |
| 642 | warnings.warn("AffectedTextFiles(include_deletes=%s)" |
| 643 | " is deprecated and ignored" % str(include_deletes), |
| 644 | category=DeprecationWarning, |
| 645 | stacklevel=2) |
| 646 | return filter(lambda x: x.IsTextFile(), |
| 647 | self.AffectedFiles(include_dirs=False, include_deletes=False)) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 648 | |
| 649 | def LocalPaths(self, include_dirs=False): |
| 650 | """Convenience function.""" |
| 651 | return [af.LocalPath() for af in self.AffectedFiles(include_dirs)] |
| 652 | |
| 653 | def AbsoluteLocalPaths(self, include_dirs=False): |
| 654 | """Convenience function.""" |
| 655 | return [af.AbsoluteLocalPath() for af in self.AffectedFiles(include_dirs)] |
| 656 | |
| 657 | def ServerPaths(self, include_dirs=False): |
| 658 | """Convenience function.""" |
| 659 | return [af.ServerPath() for af in self.AffectedFiles(include_dirs)] |
| 660 | |
| 661 | def RightHandSideLines(self): |
| 662 | """An iterator over all text lines in "new" version of changed files. |
| 663 | |
| 664 | Lists lines from new or modified text files in the change. |
| 665 | |
| 666 | This is useful for doing line-by-line regex checks, like checking for |
| 667 | trailing whitespace. |
| 668 | |
| 669 | Yields: |
| 670 | a 3 tuple: |
| 671 | the AffectedFile instance of the current file; |
| 672 | integer line number (1-based); and |
| 673 | the contents of the line as a string. |
| 674 | """ |
| 675 | return InputApi._RightHandSideLinesImpl( |
maruel@chromium.org | 1e08c00 | 2009-05-28 19:09:33 +0000 | [diff] [blame] | 676 | filter(lambda x: x.IsTextFile(), |
| 677 | self.AffectedFiles(include_deletes=False))) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 678 | |
| 679 | |
maruel@chromium.org | 4ff922a | 2009-06-12 20:20:19 +0000 | [diff] [blame] | 680 | class SvnChange(Change): |
| 681 | _AFFECTED_FILES = SvnAffectedFile |
| 682 | |
thestig@chromium.org | da8cddd | 2009-08-13 00:25:55 +0000 | [diff] [blame] | 683 | def __init__(self, *args, **kwargs): |
| 684 | Change.__init__(self, *args, **kwargs) |
| 685 | self.scm = 'svn' |
thestig@chromium.org | 6bd3170 | 2009-09-02 23:29:07 +0000 | [diff] [blame] | 686 | self._changelists = None |
| 687 | |
| 688 | def _GetChangeLists(self): |
| 689 | """Get all change lists.""" |
| 690 | if self._changelists == None: |
| 691 | previous_cwd = os.getcwd() |
| 692 | os.chdir(self.RepositoryRoot()) |
| 693 | self._changelists = gcl.GetModifiedFiles() |
| 694 | os.chdir(previous_cwd) |
| 695 | return self._changelists |
thestig@chromium.org | da8cddd | 2009-08-13 00:25:55 +0000 | [diff] [blame] | 696 | |
| 697 | def GetAllModifiedFiles(self): |
| 698 | """Get all modified files.""" |
thestig@chromium.org | 6bd3170 | 2009-09-02 23:29:07 +0000 | [diff] [blame] | 699 | changelists = self._GetChangeLists() |
thestig@chromium.org | da8cddd | 2009-08-13 00:25:55 +0000 | [diff] [blame] | 700 | all_modified_files = [] |
| 701 | for cl in changelists.values(): |
thestig@chromium.org | 6bd3170 | 2009-09-02 23:29:07 +0000 | [diff] [blame] | 702 | all_modified_files.extend( |
| 703 | [os.path.join(self.RepositoryRoot(), f[1]) for f in cl]) |
thestig@chromium.org | da8cddd | 2009-08-13 00:25:55 +0000 | [diff] [blame] | 704 | return all_modified_files |
| 705 | |
| 706 | def GetModifiedFiles(self): |
| 707 | """Get modified files in the current CL.""" |
thestig@chromium.org | 6bd3170 | 2009-09-02 23:29:07 +0000 | [diff] [blame] | 708 | changelists = self._GetChangeLists() |
| 709 | return [os.path.join(self.RepositoryRoot(), f[1]) |
| 710 | for f in changelists[self.Name()]] |
thestig@chromium.org | da8cddd | 2009-08-13 00:25:55 +0000 | [diff] [blame] | 711 | |
maruel@chromium.org | 4ff922a | 2009-06-12 20:20:19 +0000 | [diff] [blame] | 712 | |
maruel@chromium.org | c70a220 | 2009-06-17 12:55:10 +0000 | [diff] [blame] | 713 | class GitChange(Change): |
| 714 | _AFFECTED_FILES = GitAffectedFile |
| 715 | |
thestig@chromium.org | da8cddd | 2009-08-13 00:25:55 +0000 | [diff] [blame] | 716 | def __init__(self, *args, **kwargs): |
| 717 | Change.__init__(self, *args, **kwargs) |
| 718 | self.scm = 'git' |
| 719 | |
maruel@chromium.org | c70a220 | 2009-06-17 12:55:10 +0000 | [diff] [blame] | 720 | |
maruel@chromium.org | 4661e0c | 2009-06-04 00:45:26 +0000 | [diff] [blame] | 721 | def ListRelevantPresubmitFiles(files, root): |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 722 | """Finds all presubmit files that apply to a given set of source files. |
| 723 | |
| 724 | Args: |
| 725 | files: An iterable container containing file paths. |
maruel@chromium.org | 4661e0c | 2009-06-04 00:45:26 +0000 | [diff] [blame] | 726 | root: Path where to stop searching. |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 727 | |
| 728 | Return: |
maruel@chromium.org | 4661e0c | 2009-06-04 00:45:26 +0000 | [diff] [blame] | 729 | List of absolute paths of the existing PRESUBMIT.py scripts. |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 730 | """ |
maruel@chromium.org | 4661e0c | 2009-06-04 00:45:26 +0000 | [diff] [blame] | 731 | entries = [] |
| 732 | for f in files: |
| 733 | f = normpath(os.path.join(root, f)) |
| 734 | while f: |
| 735 | f = os.path.dirname(f) |
| 736 | if f in entries: |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 737 | break |
maruel@chromium.org | 4661e0c | 2009-06-04 00:45:26 +0000 | [diff] [blame] | 738 | entries.append(f) |
| 739 | if f == root: |
| 740 | break |
| 741 | entries.sort() |
| 742 | entries = map(lambda x: os.path.join(x, 'PRESUBMIT.py'), entries) |
| 743 | return filter(lambda x: os.path.isfile(x), entries) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 744 | |
| 745 | |
| 746 | class PresubmitExecuter(object): |
maruel@chromium.org | 4ff922a | 2009-06-12 20:20:19 +0000 | [diff] [blame] | 747 | def __init__(self, change, committing): |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 748 | """ |
| 749 | Args: |
maruel@chromium.org | 4ff922a | 2009-06-12 20:20:19 +0000 | [diff] [blame] | 750 | change: The Change object. |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 751 | committing: True if 'gcl commit' is running, False if 'gcl upload' is. |
| 752 | """ |
maruel@chromium.org | 4ff922a | 2009-06-12 20:20:19 +0000 | [diff] [blame] | 753 | self.change = change |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 754 | self.committing = committing |
| 755 | |
| 756 | def ExecPresubmitScript(self, script_text, presubmit_path): |
| 757 | """Executes a single presubmit script. |
| 758 | |
| 759 | Args: |
| 760 | script_text: The text of the presubmit script. |
| 761 | presubmit_path: The path to the presubmit file (this will be reported via |
| 762 | input_api.PresubmitLocalPath()). |
| 763 | |
| 764 | Return: |
| 765 | A list of result objects, empty if no problems. |
| 766 | """ |
maruel@chromium.org | d7dccf5 | 2009-06-06 18:51:58 +0000 | [diff] [blame] | 767 | input_api = InputApi(self.change, presubmit_path, self.committing) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 768 | context = {} |
| 769 | exec script_text in context |
| 770 | |
| 771 | # These function names must change if we make substantial changes to |
| 772 | # the presubmit API that are not backwards compatible. |
| 773 | if self.committing: |
| 774 | function_name = 'CheckChangeOnCommit' |
| 775 | else: |
| 776 | function_name = 'CheckChangeOnUpload' |
| 777 | if function_name in context: |
| 778 | context['__args'] = (input_api, OutputApi()) |
| 779 | result = eval(function_name + '(*__args)', context) |
| 780 | if not (isinstance(result, types.TupleType) or |
| 781 | isinstance(result, types.ListType)): |
| 782 | raise exceptions.RuntimeError( |
| 783 | 'Presubmit functions must return a tuple or list') |
| 784 | for item in result: |
| 785 | if not isinstance(item, OutputApi.PresubmitResult): |
| 786 | raise exceptions.RuntimeError( |
| 787 | 'All presubmit results must be of types derived from ' |
| 788 | 'output_api.PresubmitResult') |
| 789 | else: |
| 790 | result = () # no error since the script doesn't care about current event. |
| 791 | |
| 792 | return result |
| 793 | |
| 794 | |
maruel@chromium.org | 4ff922a | 2009-06-12 20:20:19 +0000 | [diff] [blame] | 795 | def DoPresubmitChecks(change, |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 796 | committing, |
| 797 | verbose, |
| 798 | output_stream, |
maruel@chromium.org | 0ff1fab | 2009-05-22 13:08:15 +0000 | [diff] [blame] | 799 | input_stream, |
maruel@chromium.org | b0dfd35 | 2009-06-10 14:12:54 +0000 | [diff] [blame] | 800 | default_presubmit, |
| 801 | may_prompt): |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 802 | """Runs all presubmit checks that apply to the files in the change. |
| 803 | |
| 804 | This finds all PRESUBMIT.py files in directories enclosing the files in the |
| 805 | change (up to the repository root) and calls the relevant entrypoint function |
| 806 | depending on whether the change is being committed or uploaded. |
| 807 | |
| 808 | Prints errors, warnings and notifications. Prompts the user for warnings |
| 809 | when needed. |
| 810 | |
| 811 | Args: |
maruel@chromium.org | 4ff922a | 2009-06-12 20:20:19 +0000 | [diff] [blame] | 812 | change: The Change object. |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 813 | committing: True if 'gcl commit' is running, False if 'gcl upload' is. |
| 814 | verbose: Prints debug info. |
| 815 | output_stream: A stream to write output from presubmit tests to. |
| 816 | input_stream: A stream to read input from the user. |
maruel@chromium.org | 0ff1fab | 2009-05-22 13:08:15 +0000 | [diff] [blame] | 817 | default_presubmit: A default presubmit script to execute in any case. |
maruel@chromium.org | b0dfd35 | 2009-06-10 14:12:54 +0000 | [diff] [blame] | 818 | may_prompt: Enable (y/n) questions on warning or error. |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 819 | |
maruel@chromium.org | ce8e46b | 2009-06-26 22:31:51 +0000 | [diff] [blame] | 820 | Warning: |
| 821 | If may_prompt is true, output_stream SHOULD be sys.stdout and input_stream |
| 822 | SHOULD be sys.stdin. |
| 823 | |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 824 | Return: |
| 825 | True if execution can continue, False if not. |
| 826 | """ |
jam@chromium.org | 2a891dc | 2009-08-20 20:33:37 +0000 | [diff] [blame] | 827 | start_time = time.time() |
maruel@chromium.org | 4ff922a | 2009-06-12 20:20:19 +0000 | [diff] [blame] | 828 | presubmit_files = ListRelevantPresubmitFiles(change.AbsoluteLocalPaths(True), |
| 829 | change.RepositoryRoot()) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 830 | if not presubmit_files and verbose: |
maruel@chromium.org | f3eee56 | 2009-05-27 00:51:10 +0000 | [diff] [blame] | 831 | output_stream.write("Warning, no presubmit.py found.\n") |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 832 | results = [] |
maruel@chromium.org | 4ff922a | 2009-06-12 20:20:19 +0000 | [diff] [blame] | 833 | executer = PresubmitExecuter(change, committing) |
maruel@chromium.org | 0ff1fab | 2009-05-22 13:08:15 +0000 | [diff] [blame] | 834 | if default_presubmit: |
| 835 | if verbose: |
maruel@chromium.org | f3eee56 | 2009-05-27 00:51:10 +0000 | [diff] [blame] | 836 | output_stream.write("Running default presubmit script.\n") |
maruel@chromium.org | 4ff922a | 2009-06-12 20:20:19 +0000 | [diff] [blame] | 837 | fake_path = os.path.join(change.RepositoryRoot(), 'PRESUBMIT.py') |
maruel@chromium.org | 4661e0c | 2009-06-04 00:45:26 +0000 | [diff] [blame] | 838 | results += executer.ExecPresubmitScript(default_presubmit, fake_path) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 839 | for filename in presubmit_files: |
maruel@chromium.org | 3d23524 | 2009-05-15 12:40:48 +0000 | [diff] [blame] | 840 | filename = os.path.abspath(filename) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 841 | if verbose: |
maruel@chromium.org | f3eee56 | 2009-05-27 00:51:10 +0000 | [diff] [blame] | 842 | output_stream.write("Running %s\n" % filename) |
maruel@chromium.org | c1675e2 | 2009-04-27 20:30:48 +0000 | [diff] [blame] | 843 | # Accept CRLF presubmit script. |
maruel@chromium.org | 277003e | 2009-05-01 12:51:43 +0000 | [diff] [blame] | 844 | presubmit_script = gcl.ReadFile(filename, 'rU') |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 845 | results += executer.ExecPresubmitScript(presubmit_script, filename) |
| 846 | |
| 847 | errors = [] |
| 848 | notifications = [] |
| 849 | warnings = [] |
| 850 | for result in results: |
| 851 | if not result.IsFatal() and not result.ShouldPrompt(): |
| 852 | notifications.append(result) |
| 853 | elif result.ShouldPrompt(): |
| 854 | warnings.append(result) |
| 855 | else: |
| 856 | errors.append(result) |
| 857 | |
| 858 | error_count = 0 |
| 859 | for name, items in (('Messages', notifications), |
| 860 | ('Warnings', warnings), |
| 861 | ('ERRORS', errors)): |
| 862 | if items: |
maruel@chromium.org | b0dfd35 | 2009-06-10 14:12:54 +0000 | [diff] [blame] | 863 | output_stream.write('** Presubmit %s **\n' % name) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 864 | for item in items: |
| 865 | if not item._Handle(output_stream, input_stream, |
| 866 | may_prompt=False): |
| 867 | error_count += 1 |
| 868 | output_stream.write('\n') |
maruel@chromium.org | 07bbc21 | 2009-06-11 02:08:41 +0000 | [diff] [blame] | 869 | if not errors and warnings and may_prompt: |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 870 | output_stream.write( |
| 871 | 'There were presubmit warnings. Sure you want to continue? (y/N): ') |
| 872 | response = input_stream.readline() |
| 873 | if response.strip().lower() != 'y': |
| 874 | error_count += 1 |
maruel@chromium.org | ce8e46b | 2009-06-26 22:31:51 +0000 | [diff] [blame] | 875 | |
jam@chromium.org | 2a891dc | 2009-08-20 20:33:37 +0000 | [diff] [blame] | 876 | total_time = time.time() - start_time |
| 877 | if total_time > 1.0: |
| 878 | print "Presubmit checks took %.1fs to calculate." % total_time |
maruel@chromium.org | ce8e46b | 2009-06-26 22:31:51 +0000 | [diff] [blame] | 879 | global _ASKED_FOR_FEEDBACK |
| 880 | # Ask for feedback one time out of 5. |
| 881 | if (len(results) and random.randint(0, 4) == 0 and not _ASKED_FOR_FEEDBACK): |
| 882 | output_stream.write("Was the presubmit check useful? Please send feedback " |
| 883 | "& hate mail to maruel@chromium.org!\n") |
| 884 | _ASKED_FOR_FEEDBACK = True |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 885 | return (error_count == 0) |
| 886 | |
| 887 | |
| 888 | def ScanSubDirs(mask, recursive): |
| 889 | if not recursive: |
maruel@chromium.org | c70a220 | 2009-06-17 12:55:10 +0000 | [diff] [blame] | 890 | return [x for x in glob.glob(mask) if '.svn' not in x and '.git' not in x] |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 891 | else: |
| 892 | results = [] |
| 893 | for root, dirs, files in os.walk('.'): |
| 894 | if '.svn' in dirs: |
| 895 | dirs.remove('.svn') |
maruel@chromium.org | c70a220 | 2009-06-17 12:55:10 +0000 | [diff] [blame] | 896 | if '.git' in dirs: |
| 897 | dirs.remove('.git') |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 898 | for name in files: |
| 899 | if fnmatch.fnmatch(name, mask): |
| 900 | results.append(os.path.join(root, name)) |
| 901 | return results |
| 902 | |
| 903 | |
| 904 | def ParseFiles(args, recursive): |
| 905 | files = [] |
| 906 | for arg in args: |
| 907 | files.extend([('M', file) for file in ScanSubDirs(arg, recursive)]) |
| 908 | return files |
| 909 | |
| 910 | |
| 911 | def Main(argv): |
| 912 | parser = optparse.OptionParser(usage="%prog [options]", |
| 913 | version="%prog " + str(__version__)) |
maruel@chromium.org | c70a220 | 2009-06-17 12:55:10 +0000 | [diff] [blame] | 914 | parser.add_option("-c", "--commit", action="store_true", default=False, |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 915 | help="Use commit instead of upload checks") |
maruel@chromium.org | c70a220 | 2009-06-17 12:55:10 +0000 | [diff] [blame] | 916 | parser.add_option("-u", "--upload", action="store_false", dest='commit', |
| 917 | help="Use upload instead of commit checks") |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 918 | parser.add_option("-r", "--recursive", action="store_true", |
| 919 | help="Act recursively") |
maruel@chromium.org | c70a220 | 2009-06-17 12:55:10 +0000 | [diff] [blame] | 920 | parser.add_option("-v", "--verbose", action="store_true", default=False, |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 921 | help="Verbose output") |
maruel@chromium.org | c70a220 | 2009-06-17 12:55:10 +0000 | [diff] [blame] | 922 | parser.add_option("--files") |
maruel@chromium.org | 4ff922a | 2009-06-12 20:20:19 +0000 | [diff] [blame] | 923 | parser.add_option("--name", default='no name') |
| 924 | parser.add_option("--description", default='') |
| 925 | parser.add_option("--issue", type='int', default=0) |
| 926 | parser.add_option("--patchset", type='int', default=0) |
maruel@chromium.org | c70a220 | 2009-06-17 12:55:10 +0000 | [diff] [blame] | 927 | parser.add_option("--root", default='') |
| 928 | parser.add_option("--default_presubmit") |
| 929 | parser.add_option("--may_prompt", action='store_true', default=False) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 930 | options, args = parser.parse_args(argv[1:]) |
maruel@chromium.org | 4ff922a | 2009-06-12 20:20:19 +0000 | [diff] [blame] | 931 | if not options.root: |
maruel@chromium.org | c70a220 | 2009-06-17 12:55:10 +0000 | [diff] [blame] | 932 | options.root = os.getcwd() |
| 933 | if os.path.isdir(os.path.join(options.root, '.git')): |
| 934 | change_class = GitChange |
| 935 | if not options.files: |
| 936 | if args: |
| 937 | options.files = ParseFiles(args, options.recursive) |
| 938 | else: |
| 939 | # Grab modified files. |
| 940 | raise NotImplementedException() # TODO(maruel) Implement. |
| 941 | elif os.path.isdir(os.path.join(options.root, '.svn')): |
| 942 | change_class = SvnChange |
| 943 | if not options.files: |
| 944 | if args: |
| 945 | options.files = ParseFiles(args, options.recursive) |
| 946 | else: |
| 947 | # Grab modified files. |
| 948 | files = gclient.CaptureSVNStatus([options.root]) |
| 949 | else: |
| 950 | # Doesn't seem under source control. |
| 951 | change_class = Change |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 952 | if options.verbose: |
maruel@chromium.org | c70a220 | 2009-06-17 12:55:10 +0000 | [diff] [blame] | 953 | print "Found %d files." % len(options.files) |
| 954 | return not DoPresubmitChecks(change_class(options.name, |
| 955 | options.description, |
| 956 | options.root, |
| 957 | options.files, |
| 958 | options.issue, |
| 959 | options.patchset), |
maruel@chromium.org | 0ff1fab | 2009-05-22 13:08:15 +0000 | [diff] [blame] | 960 | options.commit, |
| 961 | options.verbose, |
| 962 | sys.stdout, |
| 963 | sys.stdin, |
maruel@chromium.org | 4ff922a | 2009-06-12 20:20:19 +0000 | [diff] [blame] | 964 | options.default_presubmit, |
| 965 | options.may_prompt) |
maruel@google.com | fb2b8eb | 2009-04-23 21:03:42 +0000 | [diff] [blame] | 966 | |
| 967 | |
| 968 | if __name__ == '__main__': |
| 969 | sys.exit(Main(sys.argv)) |