blob: 111db588aec44be481b084bc40db8aa819f9ed3a [file] [log] [blame]
maruel@chromium.org725f1c32011-04-01 20:24:54 +00001#!/usr/bin/env python
maruel@chromium.org3bbf2942012-01-10 16:52:06 +00002# Copyright (c) 2012 The Chromium Authors. All rights reserved.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Enables directory-specific presubmit checks to run at upload and/or commit.
7"""
8
stip@chromium.orgf7d31f52014-01-03 20:14:46 +00009__version__ = '1.8.0'
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
enne@chromium.orge72c5f52013-04-16 00:36:40 +000015import cpplint
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000016import cPickle # Exposed through the API.
17import cStringIO # Exposed through the API.
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +000018import contextlib
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000019import fnmatch
20import glob
asvitkine@chromium.org15169952011-09-27 14:30:53 +000021import inspect
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +000022import itertools
maruel@chromium.org4f6852c2012-04-20 20:39:20 +000023import json # Exposed through the API.
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +000024import logging
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000025import marshal # Exposed through the API.
ilevy@chromium.orgbc117312013-04-20 03:57:56 +000026import multiprocessing
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000027import optparse
28import os # Somewhat exposed through the API.
29import pickle # Exposed through the API.
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +000030import random
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000031import re # Exposed through the API.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000032import sys # Parts exposed through API.
33import tempfile # Exposed through the API.
jam@chromium.org2a891dc2009-08-20 20:33:37 +000034import time
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +000035import traceback # Exposed through the API.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000036import types
maruel@chromium.org1487d532009-06-06 00:22:57 +000037import unittest # Exposed through the API.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000038import urllib2 # Exposed through the API.
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +000039from warnings import warn
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000040
41# Local imports.
maruel@chromium.org35625c72011-03-23 17:34:02 +000042import fix_encoding
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +000043import gclient_utils
dpranke@chromium.org2a009622011-03-01 02:43:31 +000044import owners
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000045import presubmit_canned_checks
maruel@chromium.org239f4112011-06-03 20:08:23 +000046import rietveld
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +000047import scm
maruel@chromium.org84f4fe32011-04-06 13:26:45 +000048import subprocess2 as subprocess # Exposed through the API.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000049
50
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +000051# Ask for feedback only once in program lifetime.
52_ASKED_FOR_FEEDBACK = False
53
54
maruel@chromium.org899e1c12011-04-07 17:03:18 +000055class PresubmitFailure(Exception):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000056 pass
57
58
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +000059class CommandData(object):
60 def __init__(self, name, cmd, kwargs, message):
61 self.name = name
62 self.cmd = cmd
63 self.kwargs = kwargs
64 self.message = message
65 self.info = None
66
ilevy@chromium.orgbc117312013-04-20 03:57:56 +000067
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000068def normpath(path):
69 '''Version of os.path.normpath that also changes backward slashes to
70 forward slashes when not running on Windows.
71 '''
72 # This is safe to always do because the Windows version of os.path.normpath
73 # will replace forward slashes with backward slashes.
74 path = path.replace(os.sep, '/')
75 return os.path.normpath(path)
76
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +000077
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +000078def _RightHandSideLinesImpl(affected_files):
79 """Implements RightHandSideLines for InputApi and GclChange."""
80 for af in affected_files:
maruel@chromium.orgab05d582011-02-09 23:41:22 +000081 lines = af.ChangedContents()
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +000082 for line in lines:
maruel@chromium.orgab05d582011-02-09 23:41:22 +000083 yield (af, line[0], line[1])
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +000084
85
dpranke@chromium.org5ac21012011-03-16 02:58:25 +000086class PresubmitOutput(object):
87 def __init__(self, input_stream=None, output_stream=None):
88 self.input_stream = input_stream
89 self.output_stream = output_stream
90 self.reviewers = []
91 self.written_output = []
92 self.error_count = 0
93
94 def prompt_yes_no(self, prompt_string):
95 self.write(prompt_string)
96 if self.input_stream:
97 response = self.input_stream.readline().strip().lower()
98 if response not in ('y', 'yes'):
99 self.fail()
100 else:
101 self.fail()
102
103 def fail(self):
104 self.error_count += 1
105
106 def should_continue(self):
107 return not self.error_count
108
109 def write(self, s):
110 self.written_output.append(s)
111 if self.output_stream:
112 self.output_stream.write(s)
113
114 def getvalue(self):
115 return ''.join(self.written_output)
116
117
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000118# Top level object so multiprocessing can pickle
119# Public access through OutputApi object.
120class _PresubmitResult(object):
121 """Base class for result objects."""
122 fatal = False
123 should_prompt = False
124
125 def __init__(self, message, items=None, long_text=''):
126 """
127 message: A short one-line message to indicate errors.
128 items: A list of short strings to indicate where errors occurred.
129 long_text: multi-line text output, e.g. from another tool
130 """
131 self._message = message
132 self._items = items or []
133 if items:
134 self._items = items
135 self._long_text = long_text.rstrip()
136
137 def handle(self, output):
138 output.write(self._message)
139 output.write('\n')
140 for index, item in enumerate(self._items):
141 output.write(' ')
142 # Write separately in case it's unicode.
143 output.write(str(item))
144 if index < len(self._items) - 1:
145 output.write(' \\')
146 output.write('\n')
147 if self._long_text:
148 output.write('\n***************\n')
149 # Write separately in case it's unicode.
150 output.write(self._long_text)
151 output.write('\n***************\n')
152 if self.fatal:
153 output.fail()
154
155
156# Top level object so multiprocessing can pickle
157# Public access through OutputApi object.
158class _PresubmitAddReviewers(_PresubmitResult):
159 """Add some suggested reviewers to the change."""
160 def __init__(self, reviewers):
161 super(_PresubmitAddReviewers, self).__init__('')
162 self.reviewers = reviewers
163
164 def handle(self, output):
165 output.reviewers.extend(self.reviewers)
166
167
168# Top level object so multiprocessing can pickle
169# Public access through OutputApi object.
170class _PresubmitError(_PresubmitResult):
171 """A hard presubmit error."""
172 fatal = True
173
174
175# Top level object so multiprocessing can pickle
176# Public access through OutputApi object.
177class _PresubmitPromptWarning(_PresubmitResult):
178 """An warning that prompts the user if they want to continue."""
179 should_prompt = True
180
181
182# Top level object so multiprocessing can pickle
183# Public access through OutputApi object.
184class _PresubmitNotifyResult(_PresubmitResult):
185 """Just print something to the screen -- but it's not even a warning."""
186 pass
187
188
189# Top level object so multiprocessing can pickle
190# Public access through OutputApi object.
191class _MailTextResult(_PresubmitResult):
192 """A warning that should be included in the review request email."""
193 def __init__(self, *args, **kwargs):
194 super(_MailTextResult, self).__init__()
195 raise NotImplementedError()
196
197
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000198class OutputApi(object):
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000199 """An instance of OutputApi gets passed to presubmit scripts so that they
200 can output various types of results.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000201 """
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000202 PresubmitResult = _PresubmitResult
203 PresubmitAddReviewers = _PresubmitAddReviewers
204 PresubmitError = _PresubmitError
205 PresubmitPromptWarning = _PresubmitPromptWarning
206 PresubmitNotifyResult = _PresubmitNotifyResult
207 MailTextResult = _MailTextResult
208
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000209 def __init__(self, is_committing):
210 self.is_committing = is_committing
211
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000212 def PresubmitPromptOrNotify(self, *args, **kwargs):
213 """Warn the user when uploading, but only notify if committing."""
214 if self.is_committing:
215 return self.PresubmitNotifyResult(*args, **kwargs)
216 return self.PresubmitPromptWarning(*args, **kwargs)
217
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000218
219class InputApi(object):
220 """An instance of this object is passed to presubmit scripts so they can
221 know stuff about the change they're looking at.
222 """
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000223 # Method could be a function
224 # pylint: disable=R0201
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000225
maruel@chromium.org3410d912009-06-09 20:56:16 +0000226 # File extensions that are considered source files from a style guide
227 # perspective. Don't modify this list from a presubmit script!
maruel@chromium.orgc33455a2011-06-24 19:14:18 +0000228 #
229 # Files without an extension aren't included in the list. If you want to
230 # filter them as source files, add r"(^|.*?[\\\/])[^.]+$" to the white list.
231 # Note that ALL CAPS files are black listed in DEFAULT_BLACK_LIST below.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000232 DEFAULT_WHITE_LIST = (
233 # C++ and friends
maruel@chromium.orgfe1211a2011-05-28 18:54:17 +0000234 r".+\.c$", r".+\.cc$", r".+\.cpp$", r".+\.h$", r".+\.m$", r".+\.mm$",
235 r".+\.inl$", r".+\.asm$", r".+\.hxx$", r".+\.hpp$", r".+\.s$", r".+\.S$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000236 # Scripts
maruel@chromium.orgfe1211a2011-05-28 18:54:17 +0000237 r".+\.js$", r".+\.py$", r".+\.sh$", r".+\.rb$", r".+\.pl$", r".+\.pm$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000238 # Other
estade@chromium.orgae7af922012-01-27 14:51:13 +0000239 r".+\.java$", r".+\.mk$", r".+\.am$", r".+\.css$"
maruel@chromium.org3410d912009-06-09 20:56:16 +0000240 )
241
242 # Path regexp that should be excluded from being considered containing source
243 # files. Don't modify this list from a presubmit script!
244 DEFAULT_BLACK_LIST = (
gavinp@chromium.org656326d2012-08-13 00:43:57 +0000245 r"testing_support[\\\/]google_appengine[\\\/].*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000246 r".*\bexperimental[\\\/].*",
247 r".*\bthird_party[\\\/].*",
248 # Output directories (just in case)
249 r".*\bDebug[\\\/].*",
250 r".*\bRelease[\\\/].*",
251 r".*\bxcodebuild[\\\/].*",
thakis@chromium.orgc1c96352013-10-09 19:50:27 +0000252 r".*\bout[\\\/].*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000253 # All caps files like README and LICENCE.
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000254 r".*\b[A-Z0-9_]{2,}$",
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000255 # SCM (can happen in dual SCM configuration). (Slightly over aggressive)
maruel@chromium.org5d0dc432011-01-03 02:40:37 +0000256 r"(|.*[\\\/])\.git[\\\/].*",
257 r"(|.*[\\\/])\.svn[\\\/].*",
maruel@chromium.org7ccb4bb2011-11-07 20:26:20 +0000258 # There is no point in processing a patch file.
259 r".+\.diff$",
260 r".+\.patch$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000261 )
262
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000263 def __init__(self, change, presubmit_path, is_committing,
maruel@chromium.org239f4112011-06-03 20:08:23 +0000264 rietveld_obj, verbose):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000265 """Builds an InputApi object.
266
267 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000268 change: A presubmit.Change object.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000269 presubmit_path: The path to the presubmit script being processed.
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000270 is_committing: True if the change is about to be committed.
maruel@chromium.org239f4112011-06-03 20:08:23 +0000271 rietveld_obj: rietveld.Rietveld client object
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000272 """
maruel@chromium.org9711bba2009-05-22 23:51:39 +0000273 # Version number of the presubmit_support script.
274 self.version = [int(x) for x in __version__.split('.')]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000275 self.change = change
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000276 self.is_committing = is_committing
maruel@chromium.org239f4112011-06-03 20:08:23 +0000277 self.rietveld = rietveld_obj
maruel@chromium.orgcab38e92011-04-09 00:30:51 +0000278 # TBD
279 self.host_url = 'http://codereview.chromium.org'
280 if self.rietveld:
maruel@chromium.org239f4112011-06-03 20:08:23 +0000281 self.host_url = self.rietveld.url
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000282
283 # We expose various modules and functions as attributes of the input_api
284 # so that presubmit scripts don't have to import them.
285 self.basename = os.path.basename
286 self.cPickle = cPickle
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000287 self.cpplint = cpplint
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000288 self.cStringIO = cStringIO
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000289 self.glob = glob.glob
maruel@chromium.orgfb11c7b2010-03-18 18:22:14 +0000290 self.json = json
maruel@chromium.org6fba34d2011-06-02 13:45:12 +0000291 self.logging = logging.getLogger('PRESUBMIT')
maruel@chromium.org2b5ce562011-03-31 16:15:44 +0000292 self.os_listdir = os.listdir
293 self.os_walk = os.walk
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000294 self.os_path = os.path
295 self.pickle = pickle
296 self.marshal = marshal
297 self.re = re
298 self.subprocess = subprocess
299 self.tempfile = tempfile
dpranke@chromium.org0d1bdea2011-03-24 22:54:38 +0000300 self.time = time
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000301 self.traceback = traceback
maruel@chromium.org1487d532009-06-06 00:22:57 +0000302 self.unittest = unittest
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000303 self.urllib2 = urllib2
304
maruel@chromium.orgc0b22972009-06-25 16:19:14 +0000305 # To easily fork python.
306 self.python_executable = sys.executable
307 self.environ = os.environ
308
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000309 # InputApi.platform is the platform you're currently running on.
310 self.platform = sys.platform
311
312 # The local path of the currently-being-processed presubmit script.
maruel@chromium.org3d235242009-05-15 12:40:48 +0000313 self._current_presubmit_path = os.path.dirname(presubmit_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000314
315 # We carry the canned checks so presubmit scripts can easily use them.
316 self.canned_checks = presubmit_canned_checks
317
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000318 # TODO(dpranke): figure out a list of all approved owners for a repo
319 # in order to be able to handle wildcard OWNERS files?
320 self.owners_db = owners.Database(change.RepositoryRoot(),
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000321 fopen=file, os_path=self.os_path, glob=self.glob)
maruel@chromium.org899e1c12011-04-07 17:03:18 +0000322 self.verbose = verbose
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000323 self.Command = CommandData
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000324
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000325 # Replace <hash_map> and <hash_set> as headers that need to be included
danakj@chromium.org18278522013-06-11 22:42:32 +0000326 # with "base/containers/hash_tables.h" instead.
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000327 # Access to a protected member _XX of a client class
328 # pylint: disable=W0212
329 self.cpplint._re_pattern_templates = [
danakj@chromium.org18278522013-06-11 22:42:32 +0000330 (a, b, 'base/containers/hash_tables.h')
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000331 if header in ('<hash_map>', '<hash_set>') else (a, b, header)
332 for (a, b, header) in cpplint._re_pattern_templates
333 ]
334
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000335 def PresubmitLocalPath(self):
336 """Returns the local path of the presubmit script currently being run.
337
338 This is useful if you don't want to hard-code absolute paths in the
339 presubmit script. For example, It can be used to find another file
340 relative to the PRESUBMIT.py script, so the whole tree can be branched and
341 the presubmit script still works, without editing its content.
342 """
maruel@chromium.org3d235242009-05-15 12:40:48 +0000343 return self._current_presubmit_path
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000344
maruel@chromium.org1e08c002009-05-28 19:09:33 +0000345 def DepotToLocalPath(self, depot_path):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000346 """Translate a depot path to a local path (relative to client root).
347
348 Args:
349 Depot path as a string.
350
351 Returns:
352 The local path of the depot path under the user's current client, or None
353 if the file is not mapped.
354
355 Remember to check for the None case and show an appropriate error!
356 """
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000357 return scm.SVN.CaptureLocalInfo([depot_path], self.change.RepositoryRoot()
358 ).get('Path')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000359
maruel@chromium.org1e08c002009-05-28 19:09:33 +0000360 def LocalToDepotPath(self, local_path):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000361 """Translate a local path to a depot path.
362
363 Args:
364 Local path (relative to current directory, or absolute) as a string.
365
366 Returns:
367 The depot path (SVN URL) of the file if mapped, otherwise None.
368 """
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000369 return scm.SVN.CaptureLocalInfo([local_path], self.change.RepositoryRoot()
370 ).get('URL')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000371
sail@chromium.org5538e022011-05-12 17:53:16 +0000372 def AffectedFiles(self, include_dirs=False, include_deletes=True,
373 file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000374 """Same as input_api.change.AffectedFiles() except only lists files
375 (and optionally directories) in the same directory as the current presubmit
376 script, or subdirectories thereof.
377 """
maruel@chromium.org3d235242009-05-15 12:40:48 +0000378 dir_with_slash = normpath("%s/" % self.PresubmitLocalPath())
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000379 if len(dir_with_slash) == 1:
380 dir_with_slash = ''
sail@chromium.org5538e022011-05-12 17:53:16 +0000381
maruel@chromium.org4661e0c2009-06-04 00:45:26 +0000382 return filter(
383 lambda x: normpath(x.AbsoluteLocalPath()).startswith(dir_with_slash),
sail@chromium.org5538e022011-05-12 17:53:16 +0000384 self.change.AffectedFiles(include_dirs, include_deletes, file_filter))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000385
386 def LocalPaths(self, include_dirs=False):
387 """Returns local paths of input_api.AffectedFiles()."""
pgervais@chromium.org2f64f782014-04-25 00:12:33 +0000388 paths = [af.LocalPath() for af in self.AffectedFiles(include_dirs)]
389 logging.debug("LocalPaths: %s", paths)
390 return paths
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000391
392 def AbsoluteLocalPaths(self, include_dirs=False):
393 """Returns absolute local paths of input_api.AffectedFiles()."""
394 return [af.AbsoluteLocalPath() for af in self.AffectedFiles(include_dirs)]
395
396 def ServerPaths(self, include_dirs=False):
397 """Returns server paths of input_api.AffectedFiles()."""
398 return [af.ServerPath() for af in self.AffectedFiles(include_dirs)]
399
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000400 def AffectedTextFiles(self, include_deletes=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000401 """Same as input_api.change.AffectedTextFiles() except only lists files
402 in the same directory as the current presubmit script, or subdirectories
403 thereof.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000404 """
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000405 if include_deletes is not None:
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000406 warn("AffectedTextFiles(include_deletes=%s)"
407 " is deprecated and ignored" % str(include_deletes),
408 category=DeprecationWarning,
409 stacklevel=2)
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000410 return filter(lambda x: x.IsTextFile(),
411 self.AffectedFiles(include_dirs=False, include_deletes=False))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000412
maruel@chromium.org3410d912009-06-09 20:56:16 +0000413 def FilterSourceFile(self, affected_file, white_list=None, black_list=None):
414 """Filters out files that aren't considered "source file".
415
416 If white_list or black_list is None, InputApi.DEFAULT_WHITE_LIST
417 and InputApi.DEFAULT_BLACK_LIST is used respectively.
418
419 The lists will be compiled as regular expression and
420 AffectedFile.LocalPath() needs to pass both list.
421
422 Note: Copy-paste this function to suit your needs or use a lambda function.
423 """
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000424 def Find(affected_file, items):
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000425 local_path = affected_file.LocalPath()
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000426 for item in items:
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000427 if self.re.match(item, local_path):
428 logging.debug("%s matched %s" % (item, local_path))
maruel@chromium.org3410d912009-06-09 20:56:16 +0000429 return True
430 return False
431 return (Find(affected_file, white_list or self.DEFAULT_WHITE_LIST) and
432 not Find(affected_file, black_list or self.DEFAULT_BLACK_LIST))
433
434 def AffectedSourceFiles(self, source_file):
435 """Filter the list of AffectedTextFiles by the function source_file.
436
437 If source_file is None, InputApi.FilterSourceFile() is used.
438 """
439 if not source_file:
440 source_file = self.FilterSourceFile
441 return filter(source_file, self.AffectedTextFiles())
442
443 def RightHandSideLines(self, source_file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000444 """An iterator over all text lines in "new" version of changed files.
445
446 Only lists lines from new or modified text files in the change that are
447 contained by the directory of the currently executing presubmit script.
448
449 This is useful for doing line-by-line regex checks, like checking for
450 trailing whitespace.
451
452 Yields:
453 a 3 tuple:
454 the AffectedFile instance of the current file;
455 integer line number (1-based); and
456 the contents of the line as a string.
maruel@chromium.org1487d532009-06-06 00:22:57 +0000457
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000458 Note: The carriage return (LF or CR) is stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000459 """
maruel@chromium.org3410d912009-06-09 20:56:16 +0000460 files = self.AffectedSourceFiles(source_file_filter)
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000461 return _RightHandSideLinesImpl(files)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000462
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000463 def ReadFile(self, file_item, mode='r'):
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000464 """Reads an arbitrary file.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000465
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000466 Deny reading anything outside the repository.
467 """
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000468 if isinstance(file_item, AffectedFile):
469 file_item = file_item.AbsoluteLocalPath()
470 if not file_item.startswith(self.change.RepositoryRoot()):
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000471 raise IOError('Access outside the repository root is denied.')
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000472 return gclient_utils.FileRead(file_item, mode)
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000473
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000474 @property
475 def tbr(self):
476 """Returns if a change is TBR'ed."""
477 return 'TBR' in self.change.tags
478
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +0000479 def RunTests(self, tests_mix, parallel=True):
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000480 tests = []
481 msgs = []
482 for t in tests_mix:
483 if isinstance(t, OutputApi.PresubmitResult):
484 msgs.append(t)
485 else:
486 assert issubclass(t.message, _PresubmitResult)
487 tests.append(t)
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +0000488 if self.verbose:
489 t.info = _PresubmitNotifyResult
ilevy@chromium.org5678d332013-05-18 01:34:14 +0000490 if len(tests) > 1 and parallel:
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000491 pool = multiprocessing.Pool()
492 # async recipe works around multiprocessing bug handling Ctrl-C
493 msgs.extend(pool.map_async(CallCommand, tests).get(99999))
494 pool.close()
495 pool.join()
496 else:
497 msgs.extend(map(CallCommand, tests))
498 return [m for m in msgs if m]
499
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000500
nick@chromium.orgff526192013-06-10 19:30:26 +0000501class _DiffCache(object):
502 """Caches diffs retrieved from a particular SCM."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000503 def __init__(self, upstream=None):
504 """Stores the upstream revision against which all diffs will be computed."""
505 self._upstream = upstream
nick@chromium.orgff526192013-06-10 19:30:26 +0000506
507 def GetDiff(self, path, local_root):
508 """Get the diff for a particular path."""
509 raise NotImplementedError()
510
511
512class _SvnDiffCache(_DiffCache):
513 """DiffCache implementation for subversion."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000514 def __init__(self, *args, **kwargs):
515 super(_SvnDiffCache, self).__init__(*args, **kwargs)
nick@chromium.orgff526192013-06-10 19:30:26 +0000516 self._diffs_by_file = {}
517
518 def GetDiff(self, path, local_root):
519 if path not in self._diffs_by_file:
520 self._diffs_by_file[path] = scm.SVN.GenerateDiff([path], local_root,
521 False, None)
522 return self._diffs_by_file[path]
523
524
525class _GitDiffCache(_DiffCache):
526 """DiffCache implementation for git; gets all file diffs at once."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000527 def __init__(self, upstream):
528 super(_GitDiffCache, self).__init__(upstream=upstream)
nick@chromium.orgff526192013-06-10 19:30:26 +0000529 self._diffs_by_file = None
530
531 def GetDiff(self, path, local_root):
532 if not self._diffs_by_file:
533 # Compute a single diff for all files and parse the output; should
534 # with git this is much faster than computing one diff for each file.
535 diffs = {}
536
537 # Don't specify any filenames below, because there are command line length
538 # limits on some platforms and GenerateDiff would fail.
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000539 unified_diff = scm.GIT.GenerateDiff(local_root, files=[], full_move=True,
540 branch=self._upstream)
nick@chromium.orgff526192013-06-10 19:30:26 +0000541
542 # This regex matches the path twice, separated by a space. Note that
543 # filename itself may contain spaces.
544 file_marker = re.compile('^diff --git (?P<filename>.*) (?P=filename)$')
545 current_diff = []
546 keep_line_endings = True
547 for x in unified_diff.splitlines(keep_line_endings):
548 match = file_marker.match(x)
549 if match:
550 # Marks the start of a new per-file section.
551 diffs[match.group('filename')] = current_diff = [x]
552 elif x.startswith('diff --git'):
553 raise PresubmitFailure('Unexpected diff line: %s' % x)
554 else:
555 current_diff.append(x)
556
557 self._diffs_by_file = dict(
558 (normpath(path), ''.join(diff)) for path, diff in diffs.items())
559
560 if path not in self._diffs_by_file:
561 raise PresubmitFailure(
562 'Unified diff did not contain entry for file %s' % path)
563
564 return self._diffs_by_file[path]
565
566
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000567class AffectedFile(object):
568 """Representation of a file in a change."""
nick@chromium.orgff526192013-06-10 19:30:26 +0000569
570 DIFF_CACHE = _DiffCache
571
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000572 # Method could be a function
573 # pylint: disable=R0201
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000574 def __init__(self, path, action, repository_root, diff_cache):
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000575 self._path = path
576 self._action = action
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000577 self._local_root = repository_root
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000578 self._is_directory = None
579 self._properties = {}
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000580 self._cached_changed_contents = None
581 self._cached_new_contents = None
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000582 self._diff_cache = diff_cache
maruel@chromium.org5d0dc432011-01-03 02:40:37 +0000583 logging.debug('%s(%s)' % (self.__class__.__name__, self._path))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000584
585 def ServerPath(self):
586 """Returns a path string that identifies the file in the SCM system.
587
588 Returns the empty string if the file does not exist in SCM.
589 """
nick@chromium.orgff526192013-06-10 19:30:26 +0000590 return ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000591
592 def LocalPath(self):
593 """Returns the path of this file on the local disk relative to client root.
594 """
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000595 return normpath(self._path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000596
597 def AbsoluteLocalPath(self):
598 """Returns the absolute path of this file on the local disk.
599 """
chase@chromium.org8e416c82009-10-06 04:30:44 +0000600 return os.path.abspath(os.path.join(self._local_root, self.LocalPath()))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000601
602 def IsDirectory(self):
603 """Returns true if this object is a directory."""
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000604 if self._is_directory is None:
605 path = self.AbsoluteLocalPath()
606 self._is_directory = (os.path.exists(path) and
607 os.path.isdir(path))
608 return self._is_directory
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000609
610 def Action(self):
611 """Returns the action on this opened file, e.g. A, M, D, etc."""
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000612 # TODO(maruel): Somewhat crappy, Could be "A" or "A +" for svn but
613 # different for other SCM.
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000614 return self._action
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000615
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000616 def Property(self, property_name):
617 """Returns the specified SCM property of this file, or None if no such
618 property.
619 """
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000620 return self._properties.get(property_name, None)
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000621
maruel@chromium.org1e08c002009-05-28 19:09:33 +0000622 def IsTextFile(self):
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000623 """Returns True if the file is a text file and not a binary file.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000624
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000625 Deleted files are not text file."""
maruel@chromium.org1e08c002009-05-28 19:09:33 +0000626 raise NotImplementedError() # Implement when needed
627
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000628 def NewContents(self):
629 """Returns an iterator over the lines in the new version of file.
630
631 The new version is the file in the user's workspace, i.e. the "right hand
632 side".
633
634 Contents will be empty if the file is a directory or does not exist.
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000635 Note: The carriage returns (LF or CR) are stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000636 """
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000637 if self._cached_new_contents is None:
638 self._cached_new_contents = []
639 if not self.IsDirectory():
640 try:
641 self._cached_new_contents = gclient_utils.FileRead(
642 self.AbsoluteLocalPath(), 'rU').splitlines()
643 except IOError:
644 pass # File not found? That's fine; maybe it was deleted.
645 return self._cached_new_contents[:]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000646
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000647 def ChangedContents(self):
648 """Returns a list of tuples (line number, line text) of all new lines.
649
650 This relies on the scm diff output describing each changed code section
651 with a line of the form
652
653 ^@@ <old line num>,<old size> <new line num>,<new size> @@$
654 """
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000655 if self._cached_changed_contents is not None:
656 return self._cached_changed_contents[:]
657 self._cached_changed_contents = []
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000658 line_num = 0
659
660 if self.IsDirectory():
661 return []
662
663 for line in self.GenerateScmDiff().splitlines():
664 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
665 if m:
666 line_num = int(m.groups(1)[0])
667 continue
668 if line.startswith('+') and not line.startswith('++'):
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000669 self._cached_changed_contents.append((line_num, line[1:]))
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000670 if not line.startswith('-'):
671 line_num += 1
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000672 return self._cached_changed_contents[:]
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000673
maruel@chromium.org5de13972009-06-10 18:16:06 +0000674 def __str__(self):
675 return self.LocalPath()
676
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000677 def GenerateScmDiff(self):
nick@chromium.orgff526192013-06-10 19:30:26 +0000678 return self._diff_cache.GetDiff(self.LocalPath(), self._local_root)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000679
maruel@chromium.org58407af2011-04-12 23:15:57 +0000680
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000681class SvnAffectedFile(AffectedFile):
682 """Representation of a file in a change out of a Subversion checkout."""
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000683 # Method 'NNN' is abstract in class 'NNN' but is not overridden
684 # pylint: disable=W0223
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000685
nick@chromium.orgff526192013-06-10 19:30:26 +0000686 DIFF_CACHE = _SvnDiffCache
687
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000688 def __init__(self, *args, **kwargs):
689 AffectedFile.__init__(self, *args, **kwargs)
690 self._server_path = None
691 self._is_text_file = None
692
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000693 def ServerPath(self):
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000694 if self._server_path is None:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000695 self._server_path = scm.SVN.CaptureLocalInfo(
696 [self.LocalPath()], self._local_root).get('URL', '')
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000697 return self._server_path
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000698
699 def IsDirectory(self):
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000700 if self._is_directory is None:
701 path = self.AbsoluteLocalPath()
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000702 if os.path.exists(path):
703 # Retrieve directly from the file system; it is much faster than
704 # querying subversion, especially on Windows.
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000705 self._is_directory = os.path.isdir(path)
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000706 else:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000707 self._is_directory = scm.SVN.CaptureLocalInfo(
708 [self.LocalPath()], self._local_root
709 ).get('Node Kind') in ('dir', 'directory')
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000710 return self._is_directory
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000711
712 def Property(self, property_name):
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000713 if not property_name in self._properties:
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000714 self._properties[property_name] = scm.SVN.GetFileProperty(
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000715 self.LocalPath(), property_name, self._local_root).rstrip()
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000716 return self._properties[property_name]
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000717
maruel@chromium.org1e08c002009-05-28 19:09:33 +0000718 def IsTextFile(self):
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000719 if self._is_text_file is None:
720 if self.Action() == 'D':
721 # A deleted file is not a text file.
722 self._is_text_file = False
723 elif self.IsDirectory():
724 self._is_text_file = False
725 else:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000726 mime_type = scm.SVN.GetFileProperty(
727 self.LocalPath(), 'svn:mime-type', self._local_root)
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000728 self._is_text_file = (not mime_type or mime_type.startswith('text/'))
729 return self._is_text_file
maruel@chromium.org1e08c002009-05-28 19:09:33 +0000730
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000731
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000732class GitAffectedFile(AffectedFile):
733 """Representation of a file in a change out of a git checkout."""
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000734 # Method 'NNN' is abstract in class 'NNN' but is not overridden
735 # pylint: disable=W0223
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000736
nick@chromium.orgff526192013-06-10 19:30:26 +0000737 DIFF_CACHE = _GitDiffCache
738
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000739 def __init__(self, *args, **kwargs):
740 AffectedFile.__init__(self, *args, **kwargs)
741 self._server_path = None
742 self._is_text_file = None
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000743
744 def ServerPath(self):
745 if self._server_path is None:
maruel@chromium.org899e1c12011-04-07 17:03:18 +0000746 raise NotImplementedError('TODO(maruel) Implement.')
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000747 return self._server_path
748
749 def IsDirectory(self):
750 if self._is_directory is None:
751 path = self.AbsoluteLocalPath()
752 if os.path.exists(path):
753 # Retrieve directly from the file system; it is much faster than
754 # querying subversion, especially on Windows.
755 self._is_directory = os.path.isdir(path)
756 else:
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000757 self._is_directory = False
758 return self._is_directory
759
760 def Property(self, property_name):
761 if not property_name in self._properties:
maruel@chromium.org899e1c12011-04-07 17:03:18 +0000762 raise NotImplementedError('TODO(maruel) Implement.')
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000763 return self._properties[property_name]
764
765 def IsTextFile(self):
766 if self._is_text_file is None:
767 if self.Action() == 'D':
768 # A deleted file is not a text file.
769 self._is_text_file = False
770 elif self.IsDirectory():
771 self._is_text_file = False
772 else:
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000773 self._is_text_file = os.path.isfile(self.AbsoluteLocalPath())
774 return self._is_text_file
775
maruel@chromium.orgc1938752011-04-12 23:11:13 +0000776
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000777class Change(object):
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000778 """Describe a change.
779
780 Used directly by the presubmit scripts to query the current change being
781 tested.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000782
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000783 Instance members:
nick@chromium.orgff526192013-06-10 19:30:26 +0000784 tags: Dictionary of KEY=VALUE pairs found in the change description.
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000785 self.KEY: equivalent to tags['KEY']
786 """
787
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000788 _AFFECTED_FILES = AffectedFile
789
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000790 # Matches key/value (or "tag") lines in changelist descriptions.
maruel@chromium.org428342a2011-11-10 15:46:33 +0000791 TAG_LINE_RE = re.compile(
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +0000792 '^[ \t]*(?P<key>[A-Z][A-Z_0-9]*)[ \t]*=[ \t]*(?P<value>.*?)[ \t]*$')
maruel@chromium.orgc1938752011-04-12 23:11:13 +0000793 scm = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000794
maruel@chromium.org58407af2011-04-12 23:15:57 +0000795 def __init__(
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000796 self, name, description, local_root, files, issue, patchset, author,
797 upstream=None):
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000798 if files is None:
799 files = []
800 self._name = name
chase@chromium.org8e416c82009-10-06 04:30:44 +0000801 # Convert root into an absolute path.
802 self._local_root = os.path.abspath(local_root)
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000803 self._upstream = upstream
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000804 self.issue = issue
805 self.patchset = patchset
maruel@chromium.org58407af2011-04-12 23:15:57 +0000806 self.author_email = author
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000807
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000808 self._full_description = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000809 self.tags = {}
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000810 self._description_without_tags = ''
811 self.SetDescriptionText(description)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000812
maruel@chromium.orge085d812011-10-10 19:49:15 +0000813 assert all(
814 (isinstance(f, (list, tuple)) and len(f) == 2) for f in files), files
815
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000816 diff_cache = self._AFFECTED_FILES.DIFF_CACHE(self._upstream)
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000817 self._affected_files = [
nick@chromium.orgff526192013-06-10 19:30:26 +0000818 self._AFFECTED_FILES(path, action.strip(), self._local_root, diff_cache)
819 for action, path in files
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000820 ]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000821
maruel@chromium.org92022ec2009-06-11 01:59:28 +0000822 def Name(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000823 """Returns the change name."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000824 return self._name
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000825
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000826 def DescriptionText(self):
827 """Returns the user-entered changelist description, minus tags.
828
829 Any line in the user-provided description starting with e.g. "FOO="
830 (whitespace permitted before and around) is considered a tag line. Such
831 lines are stripped out of the description this function returns.
832 """
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000833 return self._description_without_tags
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000834
835 def FullDescriptionText(self):
836 """Returns the complete changelist description including tags."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000837 return self._full_description
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000838
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000839 def SetDescriptionText(self, description):
840 """Sets the full description text (including tags) to |description|.
pgervais@chromium.org92c30092014-04-15 00:30:37 +0000841
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000842 Also updates the list of tags."""
843 self._full_description = description
844
845 # From the description text, build up a dictionary of key/value pairs
846 # plus the description minus all key/value or "tag" lines.
847 description_without_tags = []
848 self.tags = {}
849 for line in self._full_description.splitlines():
850 m = self.TAG_LINE_RE.match(line)
851 if m:
852 self.tags[m.group('key')] = m.group('value')
853 else:
854 description_without_tags.append(line)
855
856 # Change back to text and remove whitespace at end.
857 self._description_without_tags = (
858 '\n'.join(description_without_tags).rstrip())
859
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000860 def RepositoryRoot(self):
maruel@chromium.org92022ec2009-06-11 01:59:28 +0000861 """Returns the repository (checkout) root directory for this change,
862 as an absolute path.
863 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000864 return self._local_root
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000865
866 def __getattr__(self, attr):
maruel@chromium.org92022ec2009-06-11 01:59:28 +0000867 """Return tags directly as attributes on the object."""
868 if not re.match(r"^[A-Z_]*$", attr):
869 raise AttributeError(self, attr)
maruel@chromium.orge1a524f2009-05-27 14:43:46 +0000870 return self.tags.get(attr)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000871
sail@chromium.org5538e022011-05-12 17:53:16 +0000872 def AffectedFiles(self, include_dirs=False, include_deletes=True,
873 file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000874 """Returns a list of AffectedFile instances for all files in the change.
875
876 Args:
877 include_deletes: If false, deleted files will be filtered out.
878 include_dirs: True to include directories in the list
sail@chromium.org5538e022011-05-12 17:53:16 +0000879 file_filter: An additional filter to apply.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000880
881 Returns:
882 [AffectedFile(path, action), AffectedFile(path, action)]
883 """
884 if include_dirs:
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000885 affected = self._affected_files
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000886 else:
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000887 affected = filter(lambda x: not x.IsDirectory(), self._affected_files)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000888
sail@chromium.org5538e022011-05-12 17:53:16 +0000889 affected = filter(file_filter, affected)
890
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000891 if include_deletes:
892 return affected
893 else:
894 return filter(lambda x: x.Action() != 'D', affected)
895
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000896 def AffectedTextFiles(self, include_deletes=None):
897 """Return a list of the existing text files in a change."""
898 if include_deletes is not None:
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000899 warn("AffectedTextFiles(include_deletes=%s)"
900 " is deprecated and ignored" % str(include_deletes),
901 category=DeprecationWarning,
902 stacklevel=2)
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000903 return filter(lambda x: x.IsTextFile(),
904 self.AffectedFiles(include_dirs=False, include_deletes=False))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000905
906 def LocalPaths(self, include_dirs=False):
907 """Convenience function."""
908 return [af.LocalPath() for af in self.AffectedFiles(include_dirs)]
909
910 def AbsoluteLocalPaths(self, include_dirs=False):
911 """Convenience function."""
912 return [af.AbsoluteLocalPath() for af in self.AffectedFiles(include_dirs)]
913
914 def ServerPaths(self, include_dirs=False):
915 """Convenience function."""
916 return [af.ServerPath() for af in self.AffectedFiles(include_dirs)]
917
918 def RightHandSideLines(self):
919 """An iterator over all text lines in "new" version of changed files.
920
921 Lists lines from new or modified text files in the change.
922
923 This is useful for doing line-by-line regex checks, like checking for
924 trailing whitespace.
925
926 Yields:
927 a 3 tuple:
928 the AffectedFile instance of the current file;
929 integer line number (1-based); and
930 the contents of the line as a string.
931 """
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000932 return _RightHandSideLinesImpl(
933 x for x in self.AffectedFiles(include_deletes=False)
934 if x.IsTextFile())
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000935
936
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000937class SvnChange(Change):
938 _AFFECTED_FILES = SvnAffectedFile
maruel@chromium.orgc1938752011-04-12 23:11:13 +0000939 scm = 'svn'
940 _changelists = None
thestig@chromium.org6bd31702009-09-02 23:29:07 +0000941
942 def _GetChangeLists(self):
943 """Get all change lists."""
944 if self._changelists == None:
945 previous_cwd = os.getcwd()
946 os.chdir(self.RepositoryRoot())
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000947 # Need to import here to avoid circular dependency.
948 import gcl
thestig@chromium.org6bd31702009-09-02 23:29:07 +0000949 self._changelists = gcl.GetModifiedFiles()
950 os.chdir(previous_cwd)
951 return self._changelists
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000952
953 def GetAllModifiedFiles(self):
954 """Get all modified files."""
thestig@chromium.org6bd31702009-09-02 23:29:07 +0000955 changelists = self._GetChangeLists()
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000956 all_modified_files = []
957 for cl in changelists.values():
thestig@chromium.org6bd31702009-09-02 23:29:07 +0000958 all_modified_files.extend(
959 [os.path.join(self.RepositoryRoot(), f[1]) for f in cl])
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000960 return all_modified_files
961
962 def GetModifiedFiles(self):
963 """Get modified files in the current CL."""
thestig@chromium.org6bd31702009-09-02 23:29:07 +0000964 changelists = self._GetChangeLists()
965 return [os.path.join(self.RepositoryRoot(), f[1])
966 for f in changelists[self.Name()]]
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000967
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000968
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000969class GitChange(Change):
970 _AFFECTED_FILES = GitAffectedFile
maruel@chromium.orgc1938752011-04-12 23:11:13 +0000971 scm = 'git'
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000972
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000973
maruel@chromium.org4661e0c2009-06-04 00:45:26 +0000974def ListRelevantPresubmitFiles(files, root):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000975 """Finds all presubmit files that apply to a given set of source files.
976
maruel@chromium.orgb1901a62010-06-16 00:18:47 +0000977 If inherit-review-settings-ok is present right under root, looks for
978 PRESUBMIT.py in directories enclosing root.
979
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000980 Args:
981 files: An iterable container containing file paths.
maruel@chromium.org4661e0c2009-06-04 00:45:26 +0000982 root: Path where to stop searching.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000983
984 Return:
maruel@chromium.org4661e0c2009-06-04 00:45:26 +0000985 List of absolute paths of the existing PRESUBMIT.py scripts.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000986 """
maruel@chromium.orgb1901a62010-06-16 00:18:47 +0000987 files = [normpath(os.path.join(root, f)) for f in files]
988
989 # List all the individual directories containing files.
990 directories = set([os.path.dirname(f) for f in files])
991
992 # Ignore root if inherit-review-settings-ok is present.
993 if os.path.isfile(os.path.join(root, 'inherit-review-settings-ok')):
994 root = None
995
996 # Collect all unique directories that may contain PRESUBMIT.py.
997 candidates = set()
998 for directory in directories:
999 while True:
1000 if directory in candidates:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001001 break
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001002 candidates.add(directory)
1003 if directory == root:
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001004 break
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001005 parent_dir = os.path.dirname(directory)
1006 if parent_dir == directory:
1007 # We hit the system root directory.
1008 break
1009 directory = parent_dir
1010
1011 # Look for PRESUBMIT.py in all candidate directories.
1012 results = []
1013 for directory in sorted(list(candidates)):
1014 p = os.path.join(directory, 'PRESUBMIT.py')
1015 if os.path.isfile(p):
1016 results.append(p)
1017
maruel@chromium.org5d0dc432011-01-03 02:40:37 +00001018 logging.debug('Presubmit files: %s' % ','.join(results))
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001019 return results
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001020
1021
thestig@chromium.orgde243452009-10-06 21:02:56 +00001022class GetTrySlavesExecuter(object):
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +00001023 @staticmethod
asvitkine@chromium.org15169952011-09-27 14:30:53 +00001024 def ExecPresubmitScript(script_text, presubmit_path, project, change):
thestig@chromium.orgde243452009-10-06 21:02:56 +00001025 """Executes GetPreferredTrySlaves() from a single presubmit script.
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001026
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001027 This will soon be deprecated and replaced by GetPreferredTryMasters().
thestig@chromium.orgde243452009-10-06 21:02:56 +00001028
1029 Args:
1030 script_text: The text of the presubmit script.
bradnelson@google.com78230022011-05-24 18:55:19 +00001031 presubmit_path: Project script to run.
1032 project: Project name to pass to presubmit script for bot selection.
thestig@chromium.orgde243452009-10-06 21:02:56 +00001033
1034 Return:
1035 A list of try slaves.
1036 """
1037 context = {}
alokp@chromium.orgf6349642014-03-04 00:52:18 +00001038 main_path = os.getcwd()
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001039 try:
alokp@chromium.orgf6349642014-03-04 00:52:18 +00001040 os.chdir(os.path.dirname(presubmit_path))
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001041 exec script_text in context
1042 except Exception, e:
1043 raise PresubmitFailure('"%s" had an exception.\n%s' % (presubmit_path, e))
alokp@chromium.orgf6349642014-03-04 00:52:18 +00001044 finally:
1045 os.chdir(main_path)
thestig@chromium.orgde243452009-10-06 21:02:56 +00001046
1047 function_name = 'GetPreferredTrySlaves'
1048 if function_name in context:
asvitkine@chromium.org15169952011-09-27 14:30:53 +00001049 get_preferred_try_slaves = context[function_name]
1050 function_info = inspect.getargspec(get_preferred_try_slaves)
1051 if len(function_info[0]) == 1:
1052 result = get_preferred_try_slaves(project)
1053 elif len(function_info[0]) == 2:
1054 result = get_preferred_try_slaves(project, change)
1055 else:
1056 result = get_preferred_try_slaves()
thestig@chromium.orgde243452009-10-06 21:02:56 +00001057 if not isinstance(result, types.ListType):
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001058 raise PresubmitFailure(
thestig@chromium.orgde243452009-10-06 21:02:56 +00001059 'Presubmit functions must return a list, got a %s instead: %s' %
1060 (type(result), str(result)))
1061 for item in result:
stip@chromium.org68e04192013-11-04 22:14:38 +00001062 if isinstance(item, basestring):
1063 # Old-style ['bot'] format.
1064 botname = item
1065 elif isinstance(item, tuple):
1066 # New-style [('bot', set(['tests']))] format.
1067 botname = item[0]
1068 else:
1069 raise PresubmitFailure('PRESUBMIT.py returned invalid tryslave/test'
1070 ' format.')
1071
1072 if botname != botname.strip():
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001073 raise PresubmitFailure(
1074 'Try slave names cannot start/end with whitespace')
stip@chromium.org68e04192013-11-04 22:14:38 +00001075 if ',' in botname:
maruel@chromium.org3ecc8ea2012-03-10 01:47:46 +00001076 raise PresubmitFailure(
stip@chromium.org68e04192013-11-04 22:14:38 +00001077 'Do not use \',\' separated builder or test names: %s' % botname)
thestig@chromium.orgde243452009-10-06 21:02:56 +00001078 else:
1079 result = []
stip@chromium.org5ca27622013-12-18 17:44:58 +00001080
1081 def valid_oldstyle(result):
1082 return all(isinstance(i, basestring) for i in result)
1083
1084 def valid_newstyle(result):
1085 return (all(isinstance(i, tuple) for i in result) and
1086 all(len(i) == 2 for i in result) and
1087 all(isinstance(i[0], basestring) for i in result) and
1088 all(isinstance(i[1], set) for i in result)
1089 )
1090
1091 # Ensure it's either all old-style or all new-style.
1092 if not valid_oldstyle(result) and not valid_newstyle(result):
1093 raise PresubmitFailure(
1094 'PRESUBMIT.py returned invalid trybot specification!')
1095
thestig@chromium.orgde243452009-10-06 21:02:56 +00001096 return result
1097
1098
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001099class GetTryMastersExecuter(object):
1100 @staticmethod
1101 def ExecPresubmitScript(script_text, presubmit_path, project, change):
1102 """Executes GetPreferredTryMasters() from a single presubmit script.
1103
1104 Args:
1105 script_text: The text of the presubmit script.
1106 presubmit_path: Project script to run.
1107 project: Project name to pass to presubmit script for bot selection.
1108
1109 Return:
1110 A map of try masters to map of builders to set of tests.
1111 """
1112 context = {}
1113 try:
1114 exec script_text in context
1115 except Exception, e:
1116 raise PresubmitFailure('"%s" had an exception.\n%s'
1117 % (presubmit_path, e))
1118
1119 function_name = 'GetPreferredTryMasters'
1120 if function_name not in context:
1121 return {}
1122 get_preferred_try_masters = context[function_name]
1123 if not len(inspect.getargspec(get_preferred_try_masters)[0]) == 2:
1124 raise PresubmitFailure(
1125 'Expected function "GetPreferredTryMasters" to take two arguments.')
1126 return get_preferred_try_masters(project, change)
1127
1128
asvitkine@chromium.org15169952011-09-27 14:30:53 +00001129def DoGetTrySlaves(change,
1130 changed_files,
thestig@chromium.orgde243452009-10-06 21:02:56 +00001131 repository_root,
1132 default_presubmit,
bradnelson@google.com78230022011-05-24 18:55:19 +00001133 project,
thestig@chromium.orgde243452009-10-06 21:02:56 +00001134 verbose,
1135 output_stream):
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001136 """Get the list of try servers from the presubmit scripts (deprecated).
thestig@chromium.orgde243452009-10-06 21:02:56 +00001137
1138 Args:
1139 changed_files: List of modified files.
1140 repository_root: The repository root.
1141 default_presubmit: A default presubmit script to execute in any case.
bradnelson@google.com78230022011-05-24 18:55:19 +00001142 project: Optional name of a project used in selecting trybots.
thestig@chromium.orgde243452009-10-06 21:02:56 +00001143 verbose: Prints debug info.
1144 output_stream: A stream to write debug output to.
1145
1146 Return:
1147 List of try slaves
1148 """
1149 presubmit_files = ListRelevantPresubmitFiles(changed_files, repository_root)
1150 if not presubmit_files and verbose:
mdempsky@chromium.orgd59e7612014-03-05 19:55:56 +00001151 output_stream.write("Warning, no PRESUBMIT.py found.\n")
thestig@chromium.orgde243452009-10-06 21:02:56 +00001152 results = []
1153 executer = GetTrySlavesExecuter()
stip@chromium.org5ca27622013-12-18 17:44:58 +00001154
thestig@chromium.orgde243452009-10-06 21:02:56 +00001155 if default_presubmit:
1156 if verbose:
1157 output_stream.write("Running default presubmit script.\n")
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001158 fake_path = os.path.join(repository_root, 'PRESUBMIT.py')
stip@chromium.org5ca27622013-12-18 17:44:58 +00001159 results.extend(executer.ExecPresubmitScript(
1160 default_presubmit, fake_path, project, change))
thestig@chromium.orgde243452009-10-06 21:02:56 +00001161 for filename in presubmit_files:
1162 filename = os.path.abspath(filename)
1163 if verbose:
1164 output_stream.write("Running %s\n" % filename)
1165 # Accept CRLF presubmit script.
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +00001166 presubmit_script = gclient_utils.FileRead(filename, 'rU')
stip@chromium.org5ca27622013-12-18 17:44:58 +00001167 results.extend(executer.ExecPresubmitScript(
1168 presubmit_script, filename, project, change))
thestig@chromium.orgde243452009-10-06 21:02:56 +00001169
stip@chromium.org5ca27622013-12-18 17:44:58 +00001170
1171 slave_dict = {}
1172 old_style = filter(lambda x: isinstance(x, basestring), results)
1173 new_style = filter(lambda x: isinstance(x, tuple), results)
1174
1175 for result in new_style:
1176 slave_dict.setdefault(result[0], set()).update(result[1])
1177 slaves = list(slave_dict.items())
1178
1179 slaves.extend(set(old_style))
stip@chromium.org68e04192013-11-04 22:14:38 +00001180
thestig@chromium.orgde243452009-10-06 21:02:56 +00001181 if slaves and verbose:
stip@chromium.org5ca27622013-12-18 17:44:58 +00001182 output_stream.write(', '.join((str(x) for x in slaves)))
thestig@chromium.orgde243452009-10-06 21:02:56 +00001183 output_stream.write('\n')
1184 return slaves
1185
1186
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001187def _MergeMasters(masters1, masters2):
1188 """Merges two master maps. Merges also the tests of each builder."""
1189 result = {}
1190 for (master, builders) in itertools.chain(masters1.iteritems(),
1191 masters2.iteritems()):
1192 new_builders = result.setdefault(master, {})
1193 for (builder, tests) in builders.iteritems():
1194 new_builders.setdefault(builder, set([])).update(tests)
1195 return result
1196
1197
1198def DoGetTryMasters(change,
1199 changed_files,
1200 repository_root,
1201 default_presubmit,
1202 project,
1203 verbose,
1204 output_stream):
1205 """Get the list of try masters from the presubmit scripts.
1206
1207 Args:
1208 changed_files: List of modified files.
1209 repository_root: The repository root.
1210 default_presubmit: A default presubmit script to execute in any case.
1211 project: Optional name of a project used in selecting trybots.
1212 verbose: Prints debug info.
1213 output_stream: A stream to write debug output to.
1214
1215 Return:
1216 Map of try masters to map of builders to set of tests.
1217 """
1218 presubmit_files = ListRelevantPresubmitFiles(changed_files, repository_root)
1219 if not presubmit_files and verbose:
1220 output_stream.write("Warning, no PRESUBMIT.py found.\n")
1221 results = {}
1222 executer = GetTryMastersExecuter()
1223
1224 if default_presubmit:
1225 if verbose:
1226 output_stream.write("Running default presubmit script.\n")
1227 fake_path = os.path.join(repository_root, 'PRESUBMIT.py')
1228 results = _MergeMasters(results, executer.ExecPresubmitScript(
1229 default_presubmit, fake_path, project, change))
1230 for filename in presubmit_files:
1231 filename = os.path.abspath(filename)
1232 if verbose:
1233 output_stream.write("Running %s\n" % filename)
1234 # Accept CRLF presubmit script.
1235 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1236 results = _MergeMasters(results, executer.ExecPresubmitScript(
1237 presubmit_script, filename, project, change))
1238
1239 # Make sets to lists again for later JSON serialization.
1240 for builders in results.itervalues():
1241 for builder in builders:
1242 builders[builder] = list(builders[builder])
1243
1244 if results and verbose:
1245 output_stream.write('%s\n' % str(results))
1246 return results
1247
1248
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001249class PresubmitExecuter(object):
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +00001250 def __init__(self, change, committing, rietveld_obj, verbose):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001251 """
1252 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001253 change: The Change object.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001254 committing: True if 'gcl commit' is running, False if 'gcl upload' is.
maruel@chromium.org239f4112011-06-03 20:08:23 +00001255 rietveld_obj: rietveld.Rietveld client object.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001256 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001257 self.change = change
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001258 self.committing = committing
maruel@chromium.org239f4112011-06-03 20:08:23 +00001259 self.rietveld = rietveld_obj
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001260 self.verbose = verbose
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001261
1262 def ExecPresubmitScript(self, script_text, presubmit_path):
1263 """Executes a single presubmit script.
1264
1265 Args:
1266 script_text: The text of the presubmit script.
1267 presubmit_path: The path to the presubmit file (this will be reported via
1268 input_api.PresubmitLocalPath()).
1269
1270 Return:
1271 A list of result objects, empty if no problems.
1272 """
chase@chromium.org8e416c82009-10-06 04:30:44 +00001273
1274 # Change to the presubmit file's directory to support local imports.
1275 main_path = os.getcwd()
1276 os.chdir(os.path.dirname(presubmit_path))
1277
1278 # Load the presubmit script into context.
dpranke@chromium.org970c5222011-03-12 00:32:24 +00001279 input_api = InputApi(self.change, presubmit_path, self.committing,
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +00001280 self.rietveld, self.verbose)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001281 context = {}
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001282 try:
1283 exec script_text in context
1284 except Exception, e:
1285 raise PresubmitFailure('"%s" had an exception.\n%s' % (presubmit_path, e))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001286
1287 # These function names must change if we make substantial changes to
1288 # the presubmit API that are not backwards compatible.
1289 if self.committing:
1290 function_name = 'CheckChangeOnCommit'
1291 else:
1292 function_name = 'CheckChangeOnUpload'
1293 if function_name in context:
wez@chromium.orga6d011e2013-03-26 17:31:49 +00001294 context['__args'] = (input_api, OutputApi(self.committing))
maruel@chromium.org5d0dc432011-01-03 02:40:37 +00001295 logging.debug('Running %s in %s' % (function_name, presubmit_path))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001296 result = eval(function_name + '(*__args)', context)
maruel@chromium.org5d0dc432011-01-03 02:40:37 +00001297 logging.debug('Running %s done.' % function_name)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001298 if not (isinstance(result, types.TupleType) or
1299 isinstance(result, types.ListType)):
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001300 raise PresubmitFailure(
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001301 'Presubmit functions must return a tuple or list')
1302 for item in result:
1303 if not isinstance(item, OutputApi.PresubmitResult):
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001304 raise PresubmitFailure(
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001305 'All presubmit results must be of types derived from '
1306 'output_api.PresubmitResult')
1307 else:
1308 result = () # no error since the script doesn't care about current event.
1309
chase@chromium.org8e416c82009-10-06 04:30:44 +00001310 # Return the process to the original working directory.
1311 os.chdir(main_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001312 return result
1313
dpranke@chromium.org5ac21012011-03-16 02:58:25 +00001314
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001315def DoPresubmitChecks(change,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001316 committing,
1317 verbose,
1318 output_stream,
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +00001319 input_stream,
maruel@chromium.orgb0dfd352009-06-10 14:12:54 +00001320 default_presubmit,
dpranke@chromium.org970c5222011-03-12 00:32:24 +00001321 may_prompt,
maruel@chromium.org239f4112011-06-03 20:08:23 +00001322 rietveld_obj):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001323 """Runs all presubmit checks that apply to the files in the change.
1324
1325 This finds all PRESUBMIT.py files in directories enclosing the files in the
1326 change (up to the repository root) and calls the relevant entrypoint function
1327 depending on whether the change is being committed or uploaded.
1328
1329 Prints errors, warnings and notifications. Prompts the user for warnings
1330 when needed.
1331
1332 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001333 change: The Change object.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001334 committing: True if 'gcl commit' is running, False if 'gcl upload' is.
1335 verbose: Prints debug info.
1336 output_stream: A stream to write output from presubmit tests to.
1337 input_stream: A stream to read input from the user.
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +00001338 default_presubmit: A default presubmit script to execute in any case.
maruel@chromium.orgb0dfd352009-06-10 14:12:54 +00001339 may_prompt: Enable (y/n) questions on warning or error.
maruel@chromium.org239f4112011-06-03 20:08:23 +00001340 rietveld_obj: rietveld.Rietveld object.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001341
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +00001342 Warning:
1343 If may_prompt is true, output_stream SHOULD be sys.stdout and input_stream
1344 SHOULD be sys.stdin.
1345
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001346 Return:
dpranke@chromium.org5ac21012011-03-16 02:58:25 +00001347 A PresubmitOutput object. Use output.should_continue() to figure out
1348 if there were errors or warnings and the caller should abort.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001349 """
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001350 old_environ = os.environ
1351 try:
1352 # Make sure python subprocesses won't generate .pyc files.
1353 os.environ = os.environ.copy()
1354 os.environ['PYTHONDONTWRITEBYTECODE'] = '1'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001355
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001356 output = PresubmitOutput(input_stream, output_stream)
1357 if committing:
1358 output.write("Running presubmit commit checks ...\n")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001359 else:
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001360 output.write("Running presubmit upload checks ...\n")
1361 start_time = time.time()
1362 presubmit_files = ListRelevantPresubmitFiles(
1363 change.AbsoluteLocalPaths(True), change.RepositoryRoot())
1364 if not presubmit_files and verbose:
maruel@chromium.orgfae707b2011-09-15 18:57:58 +00001365 output.write("Warning, no PRESUBMIT.py found.\n")
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001366 results = []
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +00001367 executer = PresubmitExecuter(change, committing, rietveld_obj, verbose)
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001368 if default_presubmit:
1369 if verbose:
1370 output.write("Running default presubmit script.\n")
1371 fake_path = os.path.join(change.RepositoryRoot(), 'PRESUBMIT.py')
1372 results += executer.ExecPresubmitScript(default_presubmit, fake_path)
1373 for filename in presubmit_files:
1374 filename = os.path.abspath(filename)
1375 if verbose:
1376 output.write("Running %s\n" % filename)
1377 # Accept CRLF presubmit script.
1378 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1379 results += executer.ExecPresubmitScript(presubmit_script, filename)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001380
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001381 errors = []
1382 notifications = []
1383 warnings = []
1384 for result in results:
1385 if result.fatal:
1386 errors.append(result)
1387 elif result.should_prompt:
1388 warnings.append(result)
1389 else:
1390 notifications.append(result)
pam@chromium.orged9a0832009-09-09 22:48:55 +00001391
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001392 output.write('\n')
1393 for name, items in (('Messages', notifications),
1394 ('Warnings', warnings),
1395 ('ERRORS', errors)):
1396 if items:
1397 output.write('** Presubmit %s **\n' % name)
1398 for item in items:
1399 item.handle(output)
1400 output.write('\n')
pam@chromium.orged9a0832009-09-09 22:48:55 +00001401
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001402 total_time = time.time() - start_time
1403 if total_time > 1.0:
1404 output.write("Presubmit checks took %.1fs to calculate.\n\n" % total_time)
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +00001405
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001406 if not errors:
1407 if not warnings:
1408 output.write('Presubmit checks passed.\n')
1409 elif may_prompt:
1410 output.prompt_yes_no('There were presubmit warnings. '
1411 'Are you sure you wish to continue? (y/N): ')
1412 else:
1413 output.fail()
1414
1415 global _ASKED_FOR_FEEDBACK
1416 # Ask for feedback one time out of 5.
1417 if (len(results) and random.randint(0, 4) == 0 and not _ASKED_FOR_FEEDBACK):
maruel@chromium.org1ce8e662014-01-14 15:23:00 +00001418 output.write(
1419 'Was the presubmit check useful? If not, run "git cl presubmit -v"\n'
1420 'to figure out which PRESUBMIT.py was run, then run git blame\n'
1421 'on the file to figure out who to ask for help.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001422 _ASKED_FOR_FEEDBACK = True
1423 return output
1424 finally:
1425 os.environ = old_environ
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001426
1427
1428def ScanSubDirs(mask, recursive):
1429 if not recursive:
pgervais@chromium.orge57b09d2014-05-07 00:58:13 +00001430 return [x for x in glob.glob(mask) if x not in ('.svn', '.git')]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001431 else:
1432 results = []
1433 for root, dirs, files in os.walk('.'):
1434 if '.svn' in dirs:
1435 dirs.remove('.svn')
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001436 if '.git' in dirs:
1437 dirs.remove('.git')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001438 for name in files:
1439 if fnmatch.fnmatch(name, mask):
1440 results.append(os.path.join(root, name))
1441 return results
1442
1443
1444def ParseFiles(args, recursive):
maruel@chromium.org7444c502011-02-09 14:02:11 +00001445 logging.debug('Searching for %s' % args)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001446 files = []
1447 for arg in args:
maruel@chromium.orge3608df2009-11-10 20:22:57 +00001448 files.extend([('M', f) for f in ScanSubDirs(arg, recursive)])
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001449 return files
1450
1451
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001452def load_files(options, args):
1453 """Tries to determine the SCM."""
1454 change_scm = scm.determine_scm(options.root)
1455 files = []
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001456 if args:
1457 files = ParseFiles(args, options.recursive)
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001458 if change_scm == 'svn':
1459 change_class = SvnChange
1460 if not files:
1461 files = scm.SVN.CaptureStatus([], options.root)
1462 elif change_scm == 'git':
1463 change_class = GitChange
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001464 upstream = options.upstream or None
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001465 if not files:
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001466 files = scm.GIT.CaptureStatus([], options.root, upstream)
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001467 else:
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001468 logging.info('Doesn\'t seem under source control. Got %d files' % len(args))
1469 if not files:
1470 return None, None
1471 change_class = Change
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001472 return change_class, files
1473
1474
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001475class NonexistantCannedCheckFilter(Exception):
1476 pass
1477
1478
1479@contextlib.contextmanager
1480def canned_check_filter(method_names):
1481 filtered = {}
1482 try:
1483 for method_name in method_names:
1484 if not hasattr(presubmit_canned_checks, method_name):
1485 raise NonexistantCannedCheckFilter(method_name)
1486 filtered[method_name] = getattr(presubmit_canned_checks, method_name)
1487 setattr(presubmit_canned_checks, method_name, lambda *_a, **_kw: [])
1488 yield
1489 finally:
1490 for name, method in filtered.iteritems():
1491 setattr(presubmit_canned_checks, name, method)
1492
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001493
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001494def CallCommand(cmd_data):
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001495 """Runs an external program, potentially from a child process created by the
1496 multiprocessing module.
1497
1498 multiprocessing needs a top level function with a single argument.
1499 """
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001500 cmd_data.kwargs['stdout'] = subprocess.PIPE
1501 cmd_data.kwargs['stderr'] = subprocess.STDOUT
1502 try:
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001503 start = time.time()
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001504 (out, _), code = subprocess.communicate(cmd_data.cmd, **cmd_data.kwargs)
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001505 duration = time.time() - start
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001506 except OSError as e:
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001507 duration = time.time() - start
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001508 return cmd_data.message(
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001509 '%s exec failure (%4.2fs)\n %s' % (cmd_data.name, duration, e))
1510 if code != 0:
1511 return cmd_data.message(
1512 '%s (%4.2fs) failed\n%s' % (cmd_data.name, duration, out))
1513 if cmd_data.info:
1514 return cmd_data.info('%s (%4.2fs)' % (cmd_data.name, duration))
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001515
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001516
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001517def Main(argv):
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001518 parser = optparse.OptionParser(usage="%prog [options] <files...>",
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001519 version="%prog " + str(__version__))
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001520 parser.add_option("-c", "--commit", action="store_true", default=False,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001521 help="Use commit instead of upload checks")
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001522 parser.add_option("-u", "--upload", action="store_false", dest='commit',
1523 help="Use upload instead of commit checks")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001524 parser.add_option("-r", "--recursive", action="store_true",
1525 help="Act recursively")
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001526 parser.add_option("-v", "--verbose", action="count", default=0,
1527 help="Use 2 times for more debug info")
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001528 parser.add_option("--name", default='no name')
maruel@chromium.org58407af2011-04-12 23:15:57 +00001529 parser.add_option("--author")
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001530 parser.add_option("--description", default='')
1531 parser.add_option("--issue", type='int', default=0)
1532 parser.add_option("--patchset", type='int', default=0)
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001533 parser.add_option("--root", default=os.getcwd(),
1534 help="Search for PRESUBMIT.py up to this directory. "
1535 "If inherit-review-settings-ok is present in this "
1536 "directory, parent directories up to the root file "
1537 "system directories will also be searched.")
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001538 parser.add_option("--upstream",
1539 help="Git only: the base ref or upstream branch against "
1540 "which the diff should be computed.")
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001541 parser.add_option("--default_presubmit")
1542 parser.add_option("--may_prompt", action='store_true', default=False)
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001543 parser.add_option("--skip_canned", action='append', default=[],
1544 help="A list of checks to skip which appear in "
1545 "presubmit_canned_checks. Can be provided multiple times "
1546 "to skip multiple canned checks.")
maruel@chromium.org239f4112011-06-03 20:08:23 +00001547 parser.add_option("--rietveld_url", help=optparse.SUPPRESS_HELP)
1548 parser.add_option("--rietveld_email", help=optparse.SUPPRESS_HELP)
1549 parser.add_option("--rietveld_password", help=optparse.SUPPRESS_HELP)
iannucci@chromium.org720fd7a2013-04-24 04:13:50 +00001550 parser.add_option("--rietveld_fetch", action='store_true', default=False,
1551 help=optparse.SUPPRESS_HELP)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001552 # These are for OAuth2 authentication for bots. See also apply_issue.py
1553 parser.add_option("--rietveld_email_file", help=optparse.SUPPRESS_HELP)
1554 parser.add_option("--rietveld_private_key_file", help=optparse.SUPPRESS_HELP)
1555
stip@chromium.orgf7d31f52014-01-03 20:14:46 +00001556 parser.add_option("--trybot-json",
1557 help="Output trybot information to the file specified.")
maruel@chromium.org82e5f282011-03-17 14:08:55 +00001558 options, args = parser.parse_args(argv)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001559
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001560 if options.verbose >= 2:
maruel@chromium.org7444c502011-02-09 14:02:11 +00001561 logging.basicConfig(level=logging.DEBUG)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001562 elif options.verbose:
1563 logging.basicConfig(level=logging.INFO)
1564 else:
1565 logging.basicConfig(level=logging.ERROR)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001566
1567 if options.rietveld_email and options.rietveld_email_file:
1568 parser.error("Only one of --rietveld_email or --rietveld_email_file "
1569 "can be passed to this program.")
1570 if options.rietveld_private_key_file and options.rietveld_password:
1571 parser.error("Only one of --rietveld_private_key_file or "
1572 "--rietveld_password can be passed to this program.")
djacques@chromium.org7b654f52014-04-15 04:02:32 +00001573
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001574 if options.rietveld_email_file:
1575 with open(options.rietveld_email_file, "rb") as f:
1576 options.rietveld_email = f.read().strip()
1577
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001578 change_class, files = load_files(options, args)
1579 if not change_class:
1580 parser.error('For unversioned directory, <files> is not optional.')
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001581 logging.info('Found %d file(s).' % len(files))
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001582
maruel@chromium.org239f4112011-06-03 20:08:23 +00001583 rietveld_obj = None
1584 if options.rietveld_url:
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001585 # The empty password is permitted: '' is not None.
djacques@chromium.org7b654f52014-04-15 04:02:32 +00001586 if options.rietveld_private_key_file:
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001587 rietveld_obj = rietveld.JwtOAuth2Rietveld(
1588 options.rietveld_url,
1589 options.rietveld_email,
1590 options.rietveld_private_key_file)
1591 else:
djacques@chromium.org7b654f52014-04-15 04:02:32 +00001592 rietveld_obj = rietveld.CachingRietveld(
1593 options.rietveld_url,
1594 options.rietveld_email,
1595 options.rietveld_password)
iannucci@chromium.org720fd7a2013-04-24 04:13:50 +00001596 if options.rietveld_fetch:
1597 assert options.issue
1598 props = rietveld_obj.get_issue_properties(options.issue, False)
1599 options.author = props['owner_email']
1600 options.description = props['description']
1601 logging.info('Got author: "%s"', options.author)
1602 logging.info('Got description: """\n%s\n"""', options.description)
stip@chromium.orgf7d31f52014-01-03 20:14:46 +00001603 if options.trybot_json:
1604 with open(options.trybot_json, 'w') as f:
1605 # Python's sets aren't JSON-encodable, so we convert them to lists here.
1606 class SetEncoder(json.JSONEncoder):
1607 # pylint: disable=E0202
1608 def default(self, obj):
1609 if isinstance(obj, set):
1610 return sorted(obj)
1611 return json.JSONEncoder.default(self, obj)
1612 change = change_class(options.name,
1613 options.description,
1614 options.root,
1615 files,
1616 options.issue,
1617 options.patchset,
agable@chromium.orgea84ef12014-04-30 19:55:12 +00001618 options.author,
1619 upstream=options.upstream)
stip@chromium.orgf7d31f52014-01-03 20:14:46 +00001620 trybots = DoGetTrySlaves(
1621 change,
1622 change.LocalPaths(),
1623 change.RepositoryRoot(),
1624 None,
1625 None,
1626 options.verbose,
1627 sys.stdout)
1628 json.dump(trybots, f, cls=SetEncoder)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001629 try:
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001630 with canned_check_filter(options.skip_canned):
1631 results = DoPresubmitChecks(
1632 change_class(options.name,
1633 options.description,
1634 options.root,
1635 files,
1636 options.issue,
1637 options.patchset,
agable@chromium.orgea84ef12014-04-30 19:55:12 +00001638 options.author,
1639 upstream=options.upstream),
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001640 options.commit,
1641 options.verbose,
1642 sys.stdout,
1643 sys.stdin,
1644 options.default_presubmit,
1645 options.may_prompt,
1646 rietveld_obj)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001647 return not results.should_continue()
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001648 except NonexistantCannedCheckFilter, e:
1649 print >> sys.stderr, (
1650 'Attempted to skip nonexistent canned presubmit check: %s' % e.message)
1651 return 2
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001652 except PresubmitFailure, e:
1653 print >> sys.stderr, e
1654 print >> sys.stderr, 'Maybe your depot_tools is out of date?'
1655 print >> sys.stderr, 'If all fails, contact maruel@'
1656 return 2
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001657
1658
1659if __name__ == '__main__':
maruel@chromium.org35625c72011-03-23 17:34:02 +00001660 fix_encoding.fix_encoding()
maruel@chromium.org82e5f282011-03-17 14:08:55 +00001661 sys.exit(Main(None))