blob: 8ab05c133bd52a6e63fb8d4d99c10250c77cc563 [file] [log] [blame]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001#!/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.orgb7d46902009-06-10 14:12:10 +00009__version__ = '1.3.2'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000010
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
15import cPickle # Exposed through the API.
16import cStringIO # Exposed through the API.
17import exceptions
18import fnmatch
19import glob
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +000020import logging
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000021import marshal # Exposed through the API.
22import optparse
23import os # Somewhat exposed through the API.
24import pickle # Exposed through the API.
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +000025import random
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000026import re # Exposed through the API.
27import subprocess # Exposed through the API.
28import sys # Parts exposed through API.
29import tempfile # Exposed through the API.
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +000030import traceback # Exposed through the API.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000031import types
maruel@chromium.org1487d532009-06-06 00:22:57 +000032import unittest # Exposed through the API.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000033import urllib2 # Exposed through the API.
maruel@chromium.org1e08c002009-05-28 19:09:33 +000034import warnings
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000035
36# Local imports.
37# TODO(joi) Would be cleaner to factor out utils in gcl to separate module, but
38# for now it would only be a couple of functions so hardly worth it.
39import gcl
maruel@chromium.org46a94102009-05-12 20:32:43 +000040import gclient
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000041import presubmit_canned_checks
42
43
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +000044# Ask for feedback only once in program lifetime.
45_ASKED_FOR_FEEDBACK = False
46
47
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000048class NotImplementedException(Exception):
49 """We're leaving placeholders in a bunch of places to remind us of the
50 design of the API, but we have not implemented all of it yet. Implement as
51 the need arises.
52 """
53 pass
54
55
56def normpath(path):
57 '''Version of os.path.normpath that also changes backward slashes to
58 forward slashes when not running on Windows.
59 '''
60 # This is safe to always do because the Windows version of os.path.normpath
61 # will replace forward slashes with backward slashes.
62 path = path.replace(os.sep, '/')
63 return os.path.normpath(path)
64
65
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000066class OutputApi(object):
67 """This class (more like a module) gets passed to presubmit scripts so that
68 they can specify various types of results.
69 """
70
71 class PresubmitResult(object):
72 """Base class for result objects."""
73
74 def __init__(self, message, items=None, long_text=''):
75 """
76 message: A short one-line message to indicate errors.
77 items: A list of short strings to indicate where errors occurred.
78 long_text: multi-line text output, e.g. from another tool
79 """
80 self._message = message
81 self._items = []
82 if items:
83 self._items = items
84 self._long_text = long_text.rstrip()
85
86 def _Handle(self, output_stream, input_stream, may_prompt=True):
87 """Writes this result to the output stream.
88
89 Args:
90 output_stream: Where to write
91
92 Returns:
93 True if execution may continue, False otherwise.
94 """
95 output_stream.write(self._message)
96 output_stream.write('\n')
97 for item in self._items:
maruel@chromium.org5de13972009-06-10 18:16:06 +000098 output_stream.write(' %s\n' % str(item))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000099 if self._long_text:
maruel@chromium.orgb0dfd352009-06-10 14:12:54 +0000100 output_stream.write('\n***************\n%s\n***************\n' %
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000101 self._long_text)
102
103 if self.ShouldPrompt() and may_prompt:
104 output_stream.write('Are you sure you want to continue? (y/N): ')
105 response = input_stream.readline()
106 if response.strip().lower() != 'y':
107 return False
108
109 return not self.IsFatal()
110
111 def IsFatal(self):
112 """An error that is fatal stops g4 mail/submit immediately, i.e. before
113 other presubmit scripts are run.
114 """
115 return False
116
117 def ShouldPrompt(self):
118 """Whether this presubmit result should result in a prompt warning."""
119 return False
120
121 class PresubmitError(PresubmitResult):
122 """A hard presubmit error."""
123 def IsFatal(self):
124 return True
125
126 class PresubmitPromptWarning(PresubmitResult):
127 """An warning that prompts the user if they want to continue."""
128 def ShouldPrompt(self):
129 return True
130
131 class PresubmitNotifyResult(PresubmitResult):
132 """Just print something to the screen -- but it's not even a warning."""
133 pass
134
135 class MailTextResult(PresubmitResult):
136 """A warning that should be included in the review request email."""
137 def __init__(self, *args, **kwargs):
138 raise NotImplementedException() # TODO(joi) Implement.
139
140
141class InputApi(object):
142 """An instance of this object is passed to presubmit scripts so they can
143 know stuff about the change they're looking at.
144 """
145
maruel@chromium.org3410d912009-06-09 20:56:16 +0000146 # File extensions that are considered source files from a style guide
147 # perspective. Don't modify this list from a presubmit script!
148 DEFAULT_WHITE_LIST = (
149 # C++ and friends
150 r".*\.c", r".*\.cc", r".*\.cpp", r".*\.h", r".*\.m", r".*\.mm",
151 r".*\.inl", r".*\.asm", r".*\.hxx", r".*\.hpp",
152 # Scripts
153 r".*\.js", r".*\.py", r".*\.json", r".*\.sh", r".*\.rb",
154 # No extension at all
155 r"(^|.*[\\\/])[^.]+$",
156 # Other
157 r".*\.java", r".*\.mk", r".*\.am",
158 )
159
160 # Path regexp that should be excluded from being considered containing source
161 # files. Don't modify this list from a presubmit script!
162 DEFAULT_BLACK_LIST = (
163 r".*\bexperimental[\\\/].*",
164 r".*\bthird_party[\\\/].*",
165 # Output directories (just in case)
166 r".*\bDebug[\\\/].*",
167 r".*\bRelease[\\\/].*",
168 r".*\bxcodebuild[\\\/].*",
169 r".*\bsconsbuild[\\\/].*",
170 # All caps files like README and LICENCE.
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000171 r".*\b[A-Z0-9_]+$",
172 # SCM (can happen in dual SCM configuration). (Slightly over aggressive)
173 r".*\.git[\\\/].*",
174 r".*\.svn[\\\/].*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000175 )
176
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000177 def __init__(self, change, presubmit_path, is_committing):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000178 """Builds an InputApi object.
179
180 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000181 change: A presubmit.Change object.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000182 presubmit_path: The path to the presubmit script being processed.
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000183 is_committing: True if the change is about to be committed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000184 """
maruel@chromium.org9711bba2009-05-22 23:51:39 +0000185 # Version number of the presubmit_support script.
186 self.version = [int(x) for x in __version__.split('.')]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000187 self.change = change
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000188 self.is_committing = is_committing
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000189
190 # We expose various modules and functions as attributes of the input_api
191 # so that presubmit scripts don't have to import them.
192 self.basename = os.path.basename
193 self.cPickle = cPickle
194 self.cStringIO = cStringIO
195 self.os_path = os.path
196 self.pickle = pickle
197 self.marshal = marshal
198 self.re = re
199 self.subprocess = subprocess
200 self.tempfile = tempfile
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000201 self.traceback = traceback
maruel@chromium.org1487d532009-06-06 00:22:57 +0000202 self.unittest = unittest
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000203 self.urllib2 = urllib2
204
maruel@chromium.orgc0b22972009-06-25 16:19:14 +0000205 # To easily fork python.
206 self.python_executable = sys.executable
207 self.environ = os.environ
208
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000209 # InputApi.platform is the platform you're currently running on.
210 self.platform = sys.platform
211
212 # The local path of the currently-being-processed presubmit script.
maruel@chromium.org3d235242009-05-15 12:40:48 +0000213 self._current_presubmit_path = os.path.dirname(presubmit_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000214
215 # We carry the canned checks so presubmit scripts can easily use them.
216 self.canned_checks = presubmit_canned_checks
217
218 def PresubmitLocalPath(self):
219 """Returns the local path of the presubmit script currently being run.
220
221 This is useful if you don't want to hard-code absolute paths in the
222 presubmit script. For example, It can be used to find another file
223 relative to the PRESUBMIT.py script, so the whole tree can be branched and
224 the presubmit script still works, without editing its content.
225 """
maruel@chromium.org3d235242009-05-15 12:40:48 +0000226 return self._current_presubmit_path
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000227
maruel@chromium.org1e08c002009-05-28 19:09:33 +0000228 def DepotToLocalPath(self, depot_path):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000229 """Translate a depot path to a local path (relative to client root).
230
231 Args:
232 Depot path as a string.
233
234 Returns:
235 The local path of the depot path under the user's current client, or None
236 if the file is not mapped.
237
238 Remember to check for the None case and show an appropriate error!
239 """
maruel@chromium.org46a94102009-05-12 20:32:43 +0000240 local_path = gclient.CaptureSVNInfo(depot_path).get('Path')
maruel@chromium.org1e08c002009-05-28 19:09:33 +0000241 if local_path:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000242 return local_path
243
maruel@chromium.org1e08c002009-05-28 19:09:33 +0000244 def LocalToDepotPath(self, local_path):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000245 """Translate a local path to a depot path.
246
247 Args:
248 Local path (relative to current directory, or absolute) as a string.
249
250 Returns:
251 The depot path (SVN URL) of the file if mapped, otherwise None.
252 """
maruel@chromium.org46a94102009-05-12 20:32:43 +0000253 depot_path = gclient.CaptureSVNInfo(local_path).get('URL')
maruel@chromium.org1e08c002009-05-28 19:09:33 +0000254 if depot_path:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000255 return depot_path
256
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000257 def AffectedFiles(self, include_dirs=False, include_deletes=True):
258 """Same as input_api.change.AffectedFiles() except only lists files
259 (and optionally directories) in the same directory as the current presubmit
260 script, or subdirectories thereof.
261 """
maruel@chromium.org3d235242009-05-15 12:40:48 +0000262 dir_with_slash = normpath("%s/" % self.PresubmitLocalPath())
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000263 if len(dir_with_slash) == 1:
264 dir_with_slash = ''
maruel@chromium.org4661e0c2009-06-04 00:45:26 +0000265 return filter(
266 lambda x: normpath(x.AbsoluteLocalPath()).startswith(dir_with_slash),
267 self.change.AffectedFiles(include_dirs, include_deletes))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000268
269 def LocalPaths(self, include_dirs=False):
270 """Returns local paths of input_api.AffectedFiles()."""
271 return [af.LocalPath() for af in self.AffectedFiles(include_dirs)]
272
273 def AbsoluteLocalPaths(self, include_dirs=False):
274 """Returns absolute local paths of input_api.AffectedFiles()."""
275 return [af.AbsoluteLocalPath() for af in self.AffectedFiles(include_dirs)]
276
277 def ServerPaths(self, include_dirs=False):
278 """Returns server paths of input_api.AffectedFiles()."""
279 return [af.ServerPath() for af in self.AffectedFiles(include_dirs)]
280
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000281 def AffectedTextFiles(self, include_deletes=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000282 """Same as input_api.change.AffectedTextFiles() except only lists files
283 in the same directory as the current presubmit script, or subdirectories
284 thereof.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000285 """
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000286 if include_deletes is not None:
287 warnings.warn("AffectedTextFiles(include_deletes=%s)"
288 " is deprecated and ignored" % str(include_deletes),
289 category=DeprecationWarning,
290 stacklevel=2)
291 return filter(lambda x: x.IsTextFile(),
292 self.AffectedFiles(include_dirs=False, include_deletes=False))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000293
maruel@chromium.org3410d912009-06-09 20:56:16 +0000294 def FilterSourceFile(self, affected_file, white_list=None, black_list=None):
295 """Filters out files that aren't considered "source file".
296
297 If white_list or black_list is None, InputApi.DEFAULT_WHITE_LIST
298 and InputApi.DEFAULT_BLACK_LIST is used respectively.
299
300 The lists will be compiled as regular expression and
301 AffectedFile.LocalPath() needs to pass both list.
302
303 Note: Copy-paste this function to suit your needs or use a lambda function.
304 """
305 def Find(affected_file, list):
306 for item in list:
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000307 local_path = affected_file.LocalPath()
308 if self.re.match(item, local_path):
309 logging.debug("%s matched %s" % (item, local_path))
maruel@chromium.org3410d912009-06-09 20:56:16 +0000310 return True
311 return False
312 return (Find(affected_file, white_list or self.DEFAULT_WHITE_LIST) and
313 not Find(affected_file, black_list or self.DEFAULT_BLACK_LIST))
314
315 def AffectedSourceFiles(self, source_file):
316 """Filter the list of AffectedTextFiles by the function source_file.
317
318 If source_file is None, InputApi.FilterSourceFile() is used.
319 """
320 if not source_file:
321 source_file = self.FilterSourceFile
322 return filter(source_file, self.AffectedTextFiles())
323
324 def RightHandSideLines(self, source_file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000325 """An iterator over all text lines in "new" version of changed files.
326
327 Only lists lines from new or modified text files in the change that are
328 contained by the directory of the currently executing presubmit script.
329
330 This is useful for doing line-by-line regex checks, like checking for
331 trailing whitespace.
332
333 Yields:
334 a 3 tuple:
335 the AffectedFile instance of the current file;
336 integer line number (1-based); and
337 the contents of the line as a string.
maruel@chromium.org1487d532009-06-06 00:22:57 +0000338
339 Note: The cariage return (LF or CR) is stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000340 """
maruel@chromium.org3410d912009-06-09 20:56:16 +0000341 files = self.AffectedSourceFiles(source_file_filter)
342 return InputApi._RightHandSideLinesImpl(files)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000343
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000344 def ReadFile(self, file, mode='r'):
345 """Reads an arbitrary file.
346
347 Deny reading anything outside the repository.
348 """
349 if isinstance(file, AffectedFile):
350 file = file.AbsoluteLocalPath()
351 if not file.startswith(self.change.RepositoryRoot()):
352 raise IOError('Access outside the repository root is denied.')
353 return gcl.ReadFile(file, mode)
354
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000355 @staticmethod
356 def _RightHandSideLinesImpl(affected_files):
357 """Implements RightHandSideLines for InputApi and GclChange."""
358 for af in affected_files:
359 lines = af.NewContents()
360 line_number = 0
361 for line in lines:
362 line_number += 1
363 yield (af, line_number, line)
364
365
366class AffectedFile(object):
367 """Representation of a file in a change."""
368
369 def __init__(self, path, action, repository_root=''):
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000370 self._path = path
371 self._action = action
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000372 self._local_root = repository_root
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000373 self._is_directory = None
374 self._properties = {}
maruel@chromium.orgb7d46902009-06-10 14:12:10 +0000375 self.scm = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000376
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.orgdbbeedc2009-05-22 20:26:17 +0000382 return ""
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000383
384 def LocalPath(self):
385 """Returns the path of this file on the local disk relative to client root.
386 """
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000387 return normpath(self._path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000388
389 def AbsoluteLocalPath(self):
390 """Returns the absolute path of this file on the local disk.
391 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000392 return normpath(os.path.join(self._local_root, self.LocalPath()))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000393
394 def IsDirectory(self):
395 """Returns true if this object is a directory."""
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000396 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.comfb2b8eb2009-04-23 21:03:42 +0000401
402 def Action(self):
403 """Returns the action on this opened file, e.g. A, M, D, etc."""
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000404 # TODO(maruel): Somewhat crappy, Could be "A" or "A +" for svn but
405 # different for other SCM.
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000406 return self._action
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000407
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000408 def Property(self, property_name):
409 """Returns the specified SCM property of this file, or None if no such
410 property.
411 """
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000412 return self._properties.get(property_name, None)
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000413
maruel@chromium.org1e08c002009-05-28 19:09:33 +0000414 def IsTextFile(self):
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000415 """Returns True if the file is a text file and not a binary file.
416
417 Deleted files are not text file."""
maruel@chromium.org1e08c002009-05-28 19:09:33 +0000418 raise NotImplementedError() # Implement when needed
419
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000420 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.org1487d532009-06-06 00:22:57 +0000427 Note: The cariage returns (LF or CR) are stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000428 """
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.org5de13972009-06-10 18:16:06 +0000450 def __str__(self):
451 return self.LocalPath()
452
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000453
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000454class SvnAffectedFile(AffectedFile):
455 """Representation of a file in a change out of a Subversion checkout."""
456
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000457 def __init__(self, *args, **kwargs):
458 AffectedFile.__init__(self, *args, **kwargs)
459 self._server_path = None
460 self._is_text_file = None
maruel@chromium.orgb7d46902009-06-10 14:12:10 +0000461 self.scm = 'svn'
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000462
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000463 def ServerPath(self):
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000464 if self._server_path is None:
465 self._server_path = gclient.CaptureSVNInfo(
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000466 self.AbsoluteLocalPath()).get('URL', '')
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000467 return self._server_path
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000468
469 def IsDirectory(self):
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000470 if self._is_directory is None:
471 path = self.AbsoluteLocalPath()
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000472 if os.path.exists(path):
473 # Retrieve directly from the file system; it is much faster than
474 # querying subversion, especially on Windows.
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000475 self._is_directory = os.path.isdir(path)
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000476 else:
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000477 self._is_directory = gclient.CaptureSVNInfo(
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000478 path).get('Node Kind') in ('dir', 'directory')
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000479 return self._is_directory
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000480
481 def Property(self, property_name):
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000482 if not property_name in self._properties:
483 self._properties[property_name] = gcl.GetSVNFileProperty(
maruel@chromium.org196f8cb2009-06-11 00:32:06 +0000484 self.AbsoluteLocalPath(), property_name).rstrip()
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000485 return self._properties[property_name]
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000486
maruel@chromium.org1e08c002009-05-28 19:09:33 +0000487 def IsTextFile(self):
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000488 if self._is_text_file is None:
489 if self.Action() == 'D':
490 # A deleted file is not a text file.
491 self._is_text_file = False
492 elif self.IsDirectory():
493 self._is_text_file = False
494 else:
495 mime_type = gcl.GetSVNFileProperty(self.AbsoluteLocalPath(),
496 'svn:mime-type')
497 self._is_text_file = (not mime_type or mime_type.startswith('text/'))
498 return self._is_text_file
maruel@chromium.org1e08c002009-05-28 19:09:33 +0000499
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000500
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000501class GitAffectedFile(AffectedFile):
502 """Representation of a file in a change out of a git checkout."""
503
504 def __init__(self, *args, **kwargs):
505 AffectedFile.__init__(self, *args, **kwargs)
506 self._server_path = None
507 self._is_text_file = None
508 self.scm = 'git'
509
510 def ServerPath(self):
511 if self._server_path is None:
512 raise NotImplementedException() # TODO(maruel) Implement.
513 return self._server_path
514
515 def IsDirectory(self):
516 if self._is_directory is None:
517 path = self.AbsoluteLocalPath()
518 if os.path.exists(path):
519 # Retrieve directly from the file system; it is much faster than
520 # querying subversion, especially on Windows.
521 self._is_directory = os.path.isdir(path)
522 else:
523 # raise NotImplementedException() # TODO(maruel) Implement.
524 self._is_directory = False
525 return self._is_directory
526
527 def Property(self, property_name):
528 if not property_name in self._properties:
529 raise NotImplementedException() # TODO(maruel) Implement.
530 return self._properties[property_name]
531
532 def IsTextFile(self):
533 if self._is_text_file is None:
534 if self.Action() == 'D':
535 # A deleted file is not a text file.
536 self._is_text_file = False
537 elif self.IsDirectory():
538 self._is_text_file = False
539 else:
540 # raise NotImplementedException() # TODO(maruel) Implement.
541 self._is_text_file = os.path.isfile(self.AbsoluteLocalPath())
542 return self._is_text_file
543
544
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000545class Change(object):
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000546 """Describe a change.
547
548 Used directly by the presubmit scripts to query the current change being
549 tested.
550
551 Instance members:
552 tags: Dictionnary of KEY=VALUE pairs found in the change description.
553 self.KEY: equivalent to tags['KEY']
554 """
555
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000556 _AFFECTED_FILES = AffectedFile
557
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000558 # Matches key/value (or "tag") lines in changelist descriptions.
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000559 _TAG_LINE_RE = re.compile(
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000560 '^\s*(?P<key>[A-Z][A-Z_0-9]*)\s*=\s*(?P<value>.*?)\s*$')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000561
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000562 def __init__(self, name, description, local_root, files, issue, patchset):
563 if files is None:
564 files = []
565 self._name = name
566 self._full_description = description
567 self._local_root = local_root
568 self.issue = issue
569 self.patchset = patchset
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000570
571 # From the description text, build up a dictionary of key/value pairs
572 # plus the description minus all key/value or "tag" lines.
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000573 self._description_without_tags = []
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000574 self.tags = {}
maruel@chromium.org8d5c9a52009-06-12 15:59:08 +0000575 for line in self._full_description.splitlines():
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000576 m = self._TAG_LINE_RE.match(line)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000577 if m:
578 self.tags[m.group('key')] = m.group('value')
579 else:
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000580 self._description_without_tags.append(line)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000581
582 # Change back to text and remove whitespace at end.
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000583 self._description_without_tags = '\n'.join(self._description_without_tags)
584 self._description_without_tags = self._description_without_tags.rstrip()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000585
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000586 self._affected_files = [
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000587 self._AFFECTED_FILES(info[1], info[0].strip(), self._local_root)
588 for info in files
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000589 ]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000590
maruel@chromium.org92022ec2009-06-11 01:59:28 +0000591 def Name(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000592 """Returns the change name."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000593 return self._name
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000594
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000595 def DescriptionText(self):
596 """Returns the user-entered changelist description, minus tags.
597
598 Any line in the user-provided description starting with e.g. "FOO="
599 (whitespace permitted before and around) is considered a tag line. Such
600 lines are stripped out of the description this function returns.
601 """
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000602 return self._description_without_tags
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000603
604 def FullDescriptionText(self):
605 """Returns the complete changelist description including tags."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000606 return self._full_description
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000607
608 def RepositoryRoot(self):
maruel@chromium.org92022ec2009-06-11 01:59:28 +0000609 """Returns the repository (checkout) root directory for this change,
610 as an absolute path.
611 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000612 return self._local_root
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000613
614 def __getattr__(self, attr):
maruel@chromium.org92022ec2009-06-11 01:59:28 +0000615 """Return tags directly as attributes on the object."""
616 if not re.match(r"^[A-Z_]*$", attr):
617 raise AttributeError(self, attr)
maruel@chromium.orge1a524f2009-05-27 14:43:46 +0000618 return self.tags.get(attr)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000619
620 def AffectedFiles(self, include_dirs=False, include_deletes=True):
621 """Returns a list of AffectedFile instances for all files in the change.
622
623 Args:
624 include_deletes: If false, deleted files will be filtered out.
625 include_dirs: True to include directories in the list
626
627 Returns:
628 [AffectedFile(path, action), AffectedFile(path, action)]
629 """
630 if include_dirs:
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000631 affected = self._affected_files
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000632 else:
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000633 affected = filter(lambda x: not x.IsDirectory(), self._affected_files)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000634
635 if include_deletes:
636 return affected
637 else:
638 return filter(lambda x: x.Action() != 'D', affected)
639
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000640 def AffectedTextFiles(self, include_deletes=None):
641 """Return a list of the existing text files in a change."""
642 if include_deletes is not None:
643 warnings.warn("AffectedTextFiles(include_deletes=%s)"
644 " is deprecated and ignored" % str(include_deletes),
645 category=DeprecationWarning,
646 stacklevel=2)
647 return filter(lambda x: x.IsTextFile(),
648 self.AffectedFiles(include_dirs=False, include_deletes=False))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000649
650 def LocalPaths(self, include_dirs=False):
651 """Convenience function."""
652 return [af.LocalPath() for af in self.AffectedFiles(include_dirs)]
653
654 def AbsoluteLocalPaths(self, include_dirs=False):
655 """Convenience function."""
656 return [af.AbsoluteLocalPath() for af in self.AffectedFiles(include_dirs)]
657
658 def ServerPaths(self, include_dirs=False):
659 """Convenience function."""
660 return [af.ServerPath() for af in self.AffectedFiles(include_dirs)]
661
662 def RightHandSideLines(self):
663 """An iterator over all text lines in "new" version of changed files.
664
665 Lists lines from new or modified text files in the change.
666
667 This is useful for doing line-by-line regex checks, like checking for
668 trailing whitespace.
669
670 Yields:
671 a 3 tuple:
672 the AffectedFile instance of the current file;
673 integer line number (1-based); and
674 the contents of the line as a string.
675 """
676 return InputApi._RightHandSideLinesImpl(
maruel@chromium.org1e08c002009-05-28 19:09:33 +0000677 filter(lambda x: x.IsTextFile(),
678 self.AffectedFiles(include_deletes=False)))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000679
680
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000681class SvnChange(Change):
682 _AFFECTED_FILES = SvnAffectedFile
683
684
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000685class GitChange(Change):
686 _AFFECTED_FILES = GitAffectedFile
687
688
maruel@chromium.org4661e0c2009-06-04 00:45:26 +0000689def ListRelevantPresubmitFiles(files, root):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000690 """Finds all presubmit files that apply to a given set of source files.
691
692 Args:
693 files: An iterable container containing file paths.
maruel@chromium.org4661e0c2009-06-04 00:45:26 +0000694 root: Path where to stop searching.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000695
696 Return:
maruel@chromium.org4661e0c2009-06-04 00:45:26 +0000697 List of absolute paths of the existing PRESUBMIT.py scripts.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000698 """
maruel@chromium.org4661e0c2009-06-04 00:45:26 +0000699 entries = []
700 for f in files:
701 f = normpath(os.path.join(root, f))
702 while f:
703 f = os.path.dirname(f)
704 if f in entries:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000705 break
maruel@chromium.org4661e0c2009-06-04 00:45:26 +0000706 entries.append(f)
707 if f == root:
708 break
709 entries.sort()
710 entries = map(lambda x: os.path.join(x, 'PRESUBMIT.py'), entries)
711 return filter(lambda x: os.path.isfile(x), entries)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000712
713
714class PresubmitExecuter(object):
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000715 def __init__(self, change, committing):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000716 """
717 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000718 change: The Change object.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000719 committing: True if 'gcl commit' is running, False if 'gcl upload' is.
720 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000721 self.change = change
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000722 self.committing = committing
723
724 def ExecPresubmitScript(self, script_text, presubmit_path):
725 """Executes a single presubmit script.
726
727 Args:
728 script_text: The text of the presubmit script.
729 presubmit_path: The path to the presubmit file (this will be reported via
730 input_api.PresubmitLocalPath()).
731
732 Return:
733 A list of result objects, empty if no problems.
734 """
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000735 input_api = InputApi(self.change, presubmit_path, self.committing)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000736 context = {}
737 exec script_text in context
738
739 # These function names must change if we make substantial changes to
740 # the presubmit API that are not backwards compatible.
741 if self.committing:
742 function_name = 'CheckChangeOnCommit'
743 else:
744 function_name = 'CheckChangeOnUpload'
745 if function_name in context:
746 context['__args'] = (input_api, OutputApi())
747 result = eval(function_name + '(*__args)', context)
748 if not (isinstance(result, types.TupleType) or
749 isinstance(result, types.ListType)):
750 raise exceptions.RuntimeError(
751 'Presubmit functions must return a tuple or list')
752 for item in result:
753 if not isinstance(item, OutputApi.PresubmitResult):
754 raise exceptions.RuntimeError(
755 'All presubmit results must be of types derived from '
756 'output_api.PresubmitResult')
757 else:
758 result = () # no error since the script doesn't care about current event.
759
760 return result
761
762
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000763def DoPresubmitChecks(change,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000764 committing,
765 verbose,
766 output_stream,
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +0000767 input_stream,
maruel@chromium.orgb0dfd352009-06-10 14:12:54 +0000768 default_presubmit,
769 may_prompt):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000770 """Runs all presubmit checks that apply to the files in the change.
771
772 This finds all PRESUBMIT.py files in directories enclosing the files in the
773 change (up to the repository root) and calls the relevant entrypoint function
774 depending on whether the change is being committed or uploaded.
775
776 Prints errors, warnings and notifications. Prompts the user for warnings
777 when needed.
778
779 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000780 change: The Change object.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000781 committing: True if 'gcl commit' is running, False if 'gcl upload' is.
782 verbose: Prints debug info.
783 output_stream: A stream to write output from presubmit tests to.
784 input_stream: A stream to read input from the user.
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +0000785 default_presubmit: A default presubmit script to execute in any case.
maruel@chromium.orgb0dfd352009-06-10 14:12:54 +0000786 may_prompt: Enable (y/n) questions on warning or error.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000787
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +0000788 Warning:
789 If may_prompt is true, output_stream SHOULD be sys.stdout and input_stream
790 SHOULD be sys.stdin.
791
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000792 Return:
793 True if execution can continue, False if not.
794 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000795 presubmit_files = ListRelevantPresubmitFiles(change.AbsoluteLocalPaths(True),
796 change.RepositoryRoot())
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000797 if not presubmit_files and verbose:
maruel@chromium.orgf3eee562009-05-27 00:51:10 +0000798 output_stream.write("Warning, no presubmit.py found.\n")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000799 results = []
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000800 executer = PresubmitExecuter(change, committing)
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +0000801 if default_presubmit:
802 if verbose:
maruel@chromium.orgf3eee562009-05-27 00:51:10 +0000803 output_stream.write("Running default presubmit script.\n")
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000804 fake_path = os.path.join(change.RepositoryRoot(), 'PRESUBMIT.py')
maruel@chromium.org4661e0c2009-06-04 00:45:26 +0000805 results += executer.ExecPresubmitScript(default_presubmit, fake_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000806 for filename in presubmit_files:
maruel@chromium.org3d235242009-05-15 12:40:48 +0000807 filename = os.path.abspath(filename)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000808 if verbose:
maruel@chromium.orgf3eee562009-05-27 00:51:10 +0000809 output_stream.write("Running %s\n" % filename)
maruel@chromium.orgc1675e22009-04-27 20:30:48 +0000810 # Accept CRLF presubmit script.
maruel@chromium.org277003e2009-05-01 12:51:43 +0000811 presubmit_script = gcl.ReadFile(filename, 'rU')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000812 results += executer.ExecPresubmitScript(presubmit_script, filename)
813
814 errors = []
815 notifications = []
816 warnings = []
817 for result in results:
818 if not result.IsFatal() and not result.ShouldPrompt():
819 notifications.append(result)
820 elif result.ShouldPrompt():
821 warnings.append(result)
822 else:
823 errors.append(result)
824
825 error_count = 0
826 for name, items in (('Messages', notifications),
827 ('Warnings', warnings),
828 ('ERRORS', errors)):
829 if items:
maruel@chromium.orgb0dfd352009-06-10 14:12:54 +0000830 output_stream.write('** Presubmit %s **\n' % name)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000831 for item in items:
832 if not item._Handle(output_stream, input_stream,
833 may_prompt=False):
834 error_count += 1
835 output_stream.write('\n')
maruel@chromium.org07bbc212009-06-11 02:08:41 +0000836 if not errors and warnings and may_prompt:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000837 output_stream.write(
838 'There were presubmit warnings. Sure you want to continue? (y/N): ')
839 response = input_stream.readline()
840 if response.strip().lower() != 'y':
841 error_count += 1
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +0000842
843 global _ASKED_FOR_FEEDBACK
844 # Ask for feedback one time out of 5.
845 if (len(results) and random.randint(0, 4) == 0 and not _ASKED_FOR_FEEDBACK):
846 output_stream.write("Was the presubmit check useful? Please send feedback "
847 "& hate mail to maruel@chromium.org!\n")
848 _ASKED_FOR_FEEDBACK = True
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000849 return (error_count == 0)
850
851
852def ScanSubDirs(mask, recursive):
853 if not recursive:
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000854 return [x for x in glob.glob(mask) if '.svn' not in x and '.git' not in x]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000855 else:
856 results = []
857 for root, dirs, files in os.walk('.'):
858 if '.svn' in dirs:
859 dirs.remove('.svn')
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000860 if '.git' in dirs:
861 dirs.remove('.git')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000862 for name in files:
863 if fnmatch.fnmatch(name, mask):
864 results.append(os.path.join(root, name))
865 return results
866
867
868def ParseFiles(args, recursive):
869 files = []
870 for arg in args:
871 files.extend([('M', file) for file in ScanSubDirs(arg, recursive)])
872 return files
873
874
875def Main(argv):
876 parser = optparse.OptionParser(usage="%prog [options]",
877 version="%prog " + str(__version__))
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000878 parser.add_option("-c", "--commit", action="store_true", default=False,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000879 help="Use commit instead of upload checks")
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000880 parser.add_option("-u", "--upload", action="store_false", dest='commit',
881 help="Use upload instead of commit checks")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000882 parser.add_option("-r", "--recursive", action="store_true",
883 help="Act recursively")
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000884 parser.add_option("-v", "--verbose", action="store_true", default=False,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000885 help="Verbose output")
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000886 parser.add_option("--files")
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000887 parser.add_option("--name", default='no name')
888 parser.add_option("--description", default='')
889 parser.add_option("--issue", type='int', default=0)
890 parser.add_option("--patchset", type='int', default=0)
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000891 parser.add_option("--root", default='')
892 parser.add_option("--default_presubmit")
893 parser.add_option("--may_prompt", action='store_true', default=False)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000894 options, args = parser.parse_args(argv[1:])
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000895 if not options.root:
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000896 options.root = os.getcwd()
897 if os.path.isdir(os.path.join(options.root, '.git')):
898 change_class = GitChange
899 if not options.files:
900 if args:
901 options.files = ParseFiles(args, options.recursive)
902 else:
903 # Grab modified files.
904 raise NotImplementedException() # TODO(maruel) Implement.
905 elif os.path.isdir(os.path.join(options.root, '.svn')):
906 change_class = SvnChange
907 if not options.files:
908 if args:
909 options.files = ParseFiles(args, options.recursive)
910 else:
911 # Grab modified files.
912 files = gclient.CaptureSVNStatus([options.root])
913 else:
914 # Doesn't seem under source control.
915 change_class = Change
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000916 if options.verbose:
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000917 print "Found %d files." % len(options.files)
918 return not DoPresubmitChecks(change_class(options.name,
919 options.description,
920 options.root,
921 options.files,
922 options.issue,
923 options.patchset),
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +0000924 options.commit,
925 options.verbose,
926 sys.stdout,
927 sys.stdin,
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000928 options.default_presubmit,
929 options.may_prompt)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000930
931
932if __name__ == '__main__':
933 sys.exit(Main(sys.argv))