blob: 9337674ad4fa0034516c2089e9a3190e3340850c [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.
tandrii@chromium.org015ebae2016-04-25 19:37:22 +000039import urlparse
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +000040from warnings import warn
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000041
42# Local imports.
vadimsh@chromium.orgcf6a5d22015-04-09 22:02:00 +000043import auth
maruel@chromium.org35625c72011-03-23 17:34:02 +000044import fix_encoding
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +000045import gclient_utils
tandrii@chromium.org015ebae2016-04-25 19:37:22 +000046import gerrit_util
dpranke@chromium.org2a009622011-03-01 02:43:31 +000047import owners
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000048import presubmit_canned_checks
maruel@chromium.org239f4112011-06-03 20:08:23 +000049import rietveld
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +000050import scm
maruel@chromium.org84f4fe32011-04-06 13:26:45 +000051import subprocess2 as subprocess # Exposed through the API.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000052
53
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +000054# Ask for feedback only once in program lifetime.
55_ASKED_FOR_FEEDBACK = False
56
57
maruel@chromium.org899e1c12011-04-07 17:03:18 +000058class PresubmitFailure(Exception):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000059 pass
60
61
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +000062class CommandData(object):
63 def __init__(self, name, cmd, kwargs, message):
64 self.name = name
65 self.cmd = cmd
66 self.kwargs = kwargs
67 self.message = message
68 self.info = None
69
ilevy@chromium.orgbc117312013-04-20 03:57:56 +000070
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000071def normpath(path):
72 '''Version of os.path.normpath that also changes backward slashes to
73 forward slashes when not running on Windows.
74 '''
75 # This is safe to always do because the Windows version of os.path.normpath
76 # will replace forward slashes with backward slashes.
77 path = path.replace(os.sep, '/')
78 return os.path.normpath(path)
79
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +000080
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +000081def _RightHandSideLinesImpl(affected_files):
82 """Implements RightHandSideLines for InputApi and GclChange."""
83 for af in affected_files:
maruel@chromium.orgab05d582011-02-09 23:41:22 +000084 lines = af.ChangedContents()
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +000085 for line in lines:
maruel@chromium.orgab05d582011-02-09 23:41:22 +000086 yield (af, line[0], line[1])
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +000087
88
dpranke@chromium.org5ac21012011-03-16 02:58:25 +000089class PresubmitOutput(object):
90 def __init__(self, input_stream=None, output_stream=None):
91 self.input_stream = input_stream
92 self.output_stream = output_stream
93 self.reviewers = []
94 self.written_output = []
95 self.error_count = 0
96
97 def prompt_yes_no(self, prompt_string):
98 self.write(prompt_string)
99 if self.input_stream:
100 response = self.input_stream.readline().strip().lower()
101 if response not in ('y', 'yes'):
102 self.fail()
103 else:
104 self.fail()
105
106 def fail(self):
107 self.error_count += 1
108
109 def should_continue(self):
110 return not self.error_count
111
112 def write(self, s):
113 self.written_output.append(s)
114 if self.output_stream:
115 self.output_stream.write(s)
116
117 def getvalue(self):
118 return ''.join(self.written_output)
119
120
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000121# Top level object so multiprocessing can pickle
122# Public access through OutputApi object.
123class _PresubmitResult(object):
124 """Base class for result objects."""
125 fatal = False
126 should_prompt = False
127
128 def __init__(self, message, items=None, long_text=''):
129 """
130 message: A short one-line message to indicate errors.
131 items: A list of short strings to indicate where errors occurred.
132 long_text: multi-line text output, e.g. from another tool
133 """
134 self._message = message
135 self._items = items or []
136 if items:
137 self._items = items
138 self._long_text = long_text.rstrip()
139
140 def handle(self, output):
141 output.write(self._message)
142 output.write('\n')
143 for index, item in enumerate(self._items):
144 output.write(' ')
145 # Write separately in case it's unicode.
146 output.write(str(item))
147 if index < len(self._items) - 1:
148 output.write(' \\')
149 output.write('\n')
150 if self._long_text:
151 output.write('\n***************\n')
152 # Write separately in case it's unicode.
153 output.write(self._long_text)
154 output.write('\n***************\n')
155 if self.fatal:
156 output.fail()
157
158
159# Top level object so multiprocessing can pickle
160# Public access through OutputApi object.
161class _PresubmitAddReviewers(_PresubmitResult):
162 """Add some suggested reviewers to the change."""
163 def __init__(self, reviewers):
164 super(_PresubmitAddReviewers, self).__init__('')
165 self.reviewers = reviewers
166
167 def handle(self, output):
168 output.reviewers.extend(self.reviewers)
169
170
171# Top level object so multiprocessing can pickle
172# Public access through OutputApi object.
173class _PresubmitError(_PresubmitResult):
174 """A hard presubmit error."""
175 fatal = True
176
177
178# Top level object so multiprocessing can pickle
179# Public access through OutputApi object.
180class _PresubmitPromptWarning(_PresubmitResult):
181 """An warning that prompts the user if they want to continue."""
182 should_prompt = True
183
184
185# Top level object so multiprocessing can pickle
186# Public access through OutputApi object.
187class _PresubmitNotifyResult(_PresubmitResult):
188 """Just print something to the screen -- but it's not even a warning."""
189 pass
190
191
192# Top level object so multiprocessing can pickle
193# Public access through OutputApi object.
194class _MailTextResult(_PresubmitResult):
195 """A warning that should be included in the review request email."""
196 def __init__(self, *args, **kwargs):
197 super(_MailTextResult, self).__init__()
198 raise NotImplementedError()
199
tandrii@chromium.orgb4cd1962016-04-29 16:04:11 +0000200class GerritAccessor(object):
201 """Limited Gerrit functionality for canned presubmit checks to work.
202
203 To avoid excessive Gerrit calls, caches the results.
204 """
205
206 def __init__(self, host):
207 self.host = host
208 self.cache = {}
209
210 def _FetchChangeDetail(self, issue):
211 # Separate function to be easily mocked in tests.
212 return gerrit_util.GetChangeDetail(
213 self.host, str(issue),
214 ['ALL_REVISIONS', 'DETAILED_LABELS'])
215
216 def GetChangeInfo(self, issue):
217 """Returns labels and all revisions (patchsets) for this issue.
218
219 The result is a dictionary according to Gerrit REST Api.
220 https://gerrit-review.googlesource.com/Documentation/rest-api.html
221
222 However, API isn't very clear what's inside, so see tests for example.
223 """
224 assert issue
225 cache_key = int(issue)
226 if cache_key not in self.cache:
227 self.cache[cache_key] = self._FetchChangeDetail(issue)
228 return self.cache[cache_key]
229
230 def GetChangeDescription(self, issue, patchset=None):
231 """If patchset is none, fetches current patchset."""
232 info = self.GetChangeInfo(issue)
233 # info is a reference to cache. We'll modify it here adding description to
234 # it to the right patchset, if it is not yet there.
235
236 # Find revision info for the patchset we want.
237 if patchset is not None:
238 for rev, rev_info in info['revisions'].iteritems():
239 if str(rev_info['_number']) == str(patchset):
240 break
241 else:
242 raise Exception('patchset %s doesn\'t exist in issue %s' % (
243 patchset, issue))
244 else:
245 rev = info['current_revision']
246 rev_info = info['revisions'][rev]
247
248 # Updates revision info, which is part of cached issue info.
249 if 'real_description' not in rev_info:
250 rev_info['real_description'] = (
251 gerrit_util.GetChangeDescriptionFromGitiles(
252 rev_info['fetch']['http']['url'], rev))
253 return rev_info['real_description']
254
255 def GetChangeOwner(self, issue):
256 return self.GetChangeInfo(issue)['owner']['email']
257
258 def GetChangeReviewers(self, issue, approving_only=True):
259 # Gerrit has 'approved' sub-section, but it only lists 1 approver.
260 # So, if we look only for approvers, we have to look at all anyway.
261 # Also, assume LGTM means Code-Review label == 2. Other configurations
262 # aren't supported.
263 return [r['email']
264 for r in self.GetChangeInfo(issue)['labels']['Code-Review']['all']
265 if not approving_only or '2' == str(r.get('value', 0))]
266
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000267
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000268class OutputApi(object):
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000269 """An instance of OutputApi gets passed to presubmit scripts so that they
270 can output various types of results.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000271 """
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000272 PresubmitResult = _PresubmitResult
273 PresubmitAddReviewers = _PresubmitAddReviewers
274 PresubmitError = _PresubmitError
275 PresubmitPromptWarning = _PresubmitPromptWarning
276 PresubmitNotifyResult = _PresubmitNotifyResult
277 MailTextResult = _MailTextResult
278
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000279 def __init__(self, is_committing):
280 self.is_committing = is_committing
281
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000282 def PresubmitPromptOrNotify(self, *args, **kwargs):
283 """Warn the user when uploading, but only notify if committing."""
284 if self.is_committing:
285 return self.PresubmitNotifyResult(*args, **kwargs)
286 return self.PresubmitPromptWarning(*args, **kwargs)
287
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000288
289class InputApi(object):
290 """An instance of this object is passed to presubmit scripts so they can
291 know stuff about the change they're looking at.
292 """
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000293 # Method could be a function
294 # pylint: disable=R0201
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000295
maruel@chromium.org3410d912009-06-09 20:56:16 +0000296 # File extensions that are considered source files from a style guide
297 # perspective. Don't modify this list from a presubmit script!
maruel@chromium.orgc33455a2011-06-24 19:14:18 +0000298 #
299 # Files without an extension aren't included in the list. If you want to
300 # filter them as source files, add r"(^|.*?[\\\/])[^.]+$" to the white list.
301 # Note that ALL CAPS files are black listed in DEFAULT_BLACK_LIST below.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000302 DEFAULT_WHITE_LIST = (
303 # C++ and friends
maruel@chromium.orgfe1211a2011-05-28 18:54:17 +0000304 r".+\.c$", r".+\.cc$", r".+\.cpp$", r".+\.h$", r".+\.m$", r".+\.mm$",
305 r".+\.inl$", r".+\.asm$", r".+\.hxx$", r".+\.hpp$", r".+\.s$", r".+\.S$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000306 # Scripts
maruel@chromium.orgfe1211a2011-05-28 18:54:17 +0000307 r".+\.js$", r".+\.py$", r".+\.sh$", r".+\.rb$", r".+\.pl$", r".+\.pm$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000308 # Other
estade@chromium.orgae7af922012-01-27 14:51:13 +0000309 r".+\.java$", r".+\.mk$", r".+\.am$", r".+\.css$"
maruel@chromium.org3410d912009-06-09 20:56:16 +0000310 )
311
312 # Path regexp that should be excluded from being considered containing source
313 # files. Don't modify this list from a presubmit script!
314 DEFAULT_BLACK_LIST = (
gavinp@chromium.org656326d2012-08-13 00:43:57 +0000315 r"testing_support[\\\/]google_appengine[\\\/].*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000316 r".*\bexperimental[\\\/].*",
primiano@chromium.orgb9658c32015-10-06 10:50:13 +0000317 # Exclude third_party/.* but NOT third_party/WebKit (crbug.com/539768).
318 r".*\bthird_party[\\\/](?!WebKit[\\\/]).*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000319 # Output directories (just in case)
320 r".*\bDebug[\\\/].*",
321 r".*\bRelease[\\\/].*",
322 r".*\bxcodebuild[\\\/].*",
thakis@chromium.orgc1c96352013-10-09 19:50:27 +0000323 r".*\bout[\\\/].*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000324 # All caps files like README and LICENCE.
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000325 r".*\b[A-Z0-9_]{2,}$",
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000326 # SCM (can happen in dual SCM configuration). (Slightly over aggressive)
maruel@chromium.org5d0dc432011-01-03 02:40:37 +0000327 r"(|.*[\\\/])\.git[\\\/].*",
328 r"(|.*[\\\/])\.svn[\\\/].*",
maruel@chromium.org7ccb4bb2011-11-07 20:26:20 +0000329 # There is no point in processing a patch file.
330 r".+\.diff$",
331 r".+\.patch$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000332 )
333
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000334 def __init__(self, change, presubmit_path, is_committing,
tandrii@chromium.orgb4cd1962016-04-29 16:04:11 +0000335 rietveld_obj, verbose, gerrit_obj=None, dry_run=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000336 """Builds an InputApi object.
337
338 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000339 change: A presubmit.Change object.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000340 presubmit_path: The path to the presubmit script being processed.
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000341 is_committing: True if the change is about to be committed.
maruel@chromium.org239f4112011-06-03 20:08:23 +0000342 rietveld_obj: rietveld.Rietveld client object
tandrii@chromium.orgb4cd1962016-04-29 16:04:11 +0000343 gerrit_obj: provides basic Gerrit codereview functionality.
344 dry_run: if true, some Checks will be skipped.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000345 """
maruel@chromium.org9711bba2009-05-22 23:51:39 +0000346 # Version number of the presubmit_support script.
347 self.version = [int(x) for x in __version__.split('.')]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000348 self.change = change
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000349 self.is_committing = is_committing
maruel@chromium.org239f4112011-06-03 20:08:23 +0000350 self.rietveld = rietveld_obj
tandrii@chromium.orgb4cd1962016-04-29 16:04:11 +0000351 self.gerrit = gerrit_obj
tandrii@chromium.org57bafac2016-04-28 05:09:03 +0000352 self.dry_run = dry_run
maruel@chromium.orgcab38e92011-04-09 00:30:51 +0000353 # TBD
354 self.host_url = 'http://codereview.chromium.org'
355 if self.rietveld:
maruel@chromium.org239f4112011-06-03 20:08:23 +0000356 self.host_url = self.rietveld.url
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000357
358 # We expose various modules and functions as attributes of the input_api
359 # so that presubmit scripts don't have to import them.
360 self.basename = os.path.basename
361 self.cPickle = cPickle
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000362 self.cpplint = cpplint
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000363 self.cStringIO = cStringIO
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000364 self.glob = glob.glob
maruel@chromium.orgfb11c7b2010-03-18 18:22:14 +0000365 self.json = json
maruel@chromium.org6fba34d2011-06-02 13:45:12 +0000366 self.logging = logging.getLogger('PRESUBMIT')
maruel@chromium.org2b5ce562011-03-31 16:15:44 +0000367 self.os_listdir = os.listdir
368 self.os_walk = os.walk
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000369 self.os_path = os.path
pgervais@chromium.orgbd0cace2014-10-02 23:23:46 +0000370 self.os_stat = os.stat
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000371 self.pickle = pickle
372 self.marshal = marshal
373 self.re = re
374 self.subprocess = subprocess
375 self.tempfile = tempfile
dpranke@chromium.org0d1bdea2011-03-24 22:54:38 +0000376 self.time = time
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000377 self.traceback = traceback
maruel@chromium.org1487d532009-06-06 00:22:57 +0000378 self.unittest = unittest
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000379 self.urllib2 = urllib2
380
maruel@chromium.orgc0b22972009-06-25 16:19:14 +0000381 # To easily fork python.
382 self.python_executable = sys.executable
383 self.environ = os.environ
384
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000385 # InputApi.platform is the platform you're currently running on.
386 self.platform = sys.platform
387
iannucci@chromium.org0af3bb32015-06-12 20:44:35 +0000388 self.cpu_count = multiprocessing.cpu_count()
389
iannucci@chromium.orgd61a4952015-07-01 23:21:26 +0000390 # this is done here because in RunTests, the current working directory has
391 # changed, which causes Pool() to explode fantastically when run on windows
392 # (because it tries to load the __main__ module, which imports lots of
393 # things relative to the current working directory).
394 self._run_tests_pool = multiprocessing.Pool(self.cpu_count)
395
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000396 # The local path of the currently-being-processed presubmit script.
maruel@chromium.org3d235242009-05-15 12:40:48 +0000397 self._current_presubmit_path = os.path.dirname(presubmit_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000398
399 # We carry the canned checks so presubmit scripts can easily use them.
400 self.canned_checks = presubmit_canned_checks
401
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000402 # TODO(dpranke): figure out a list of all approved owners for a repo
403 # in order to be able to handle wildcard OWNERS files?
404 self.owners_db = owners.Database(change.RepositoryRoot(),
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000405 fopen=file, os_path=self.os_path, glob=self.glob)
maruel@chromium.org899e1c12011-04-07 17:03:18 +0000406 self.verbose = verbose
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000407 self.Command = CommandData
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000408
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000409 # Replace <hash_map> and <hash_set> as headers that need to be included
danakj@chromium.org18278522013-06-11 22:42:32 +0000410 # with "base/containers/hash_tables.h" instead.
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000411 # Access to a protected member _XX of a client class
412 # pylint: disable=W0212
413 self.cpplint._re_pattern_templates = [
danakj@chromium.org18278522013-06-11 22:42:32 +0000414 (a, b, 'base/containers/hash_tables.h')
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000415 if header in ('<hash_map>', '<hash_set>') else (a, b, header)
416 for (a, b, header) in cpplint._re_pattern_templates
417 ]
418
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000419 def PresubmitLocalPath(self):
420 """Returns the local path of the presubmit script currently being run.
421
422 This is useful if you don't want to hard-code absolute paths in the
423 presubmit script. For example, It can be used to find another file
424 relative to the PRESUBMIT.py script, so the whole tree can be branched and
425 the presubmit script still works, without editing its content.
426 """
maruel@chromium.org3d235242009-05-15 12:40:48 +0000427 return self._current_presubmit_path
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000428
maruel@chromium.org1e08c002009-05-28 19:09:33 +0000429 def DepotToLocalPath(self, depot_path):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000430 """Translate a depot path to a local path (relative to client root).
431
432 Args:
433 Depot path as a string.
434
435 Returns:
436 The local path of the depot path under the user's current client, or None
437 if the file is not mapped.
438
439 Remember to check for the None case and show an appropriate error!
440 """
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000441 return scm.SVN.CaptureLocalInfo([depot_path], self.change.RepositoryRoot()
442 ).get('Path')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000443
maruel@chromium.org1e08c002009-05-28 19:09:33 +0000444 def LocalToDepotPath(self, local_path):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000445 """Translate a local path to a depot path.
446
447 Args:
448 Local path (relative to current directory, or absolute) as a string.
449
450 Returns:
451 The depot path (SVN URL) of the file if mapped, otherwise None.
452 """
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000453 return scm.SVN.CaptureLocalInfo([local_path], self.change.RepositoryRoot()
454 ).get('URL')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000455
sail@chromium.org5538e022011-05-12 17:53:16 +0000456 def AffectedFiles(self, include_dirs=False, include_deletes=True,
457 file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000458 """Same as input_api.change.AffectedFiles() except only lists files
459 (and optionally directories) in the same directory as the current presubmit
460 script, or subdirectories thereof.
461 """
maruel@chromium.org3d235242009-05-15 12:40:48 +0000462 dir_with_slash = normpath("%s/" % self.PresubmitLocalPath())
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000463 if len(dir_with_slash) == 1:
464 dir_with_slash = ''
sail@chromium.org5538e022011-05-12 17:53:16 +0000465
maruel@chromium.org4661e0c2009-06-04 00:45:26 +0000466 return filter(
467 lambda x: normpath(x.AbsoluteLocalPath()).startswith(dir_with_slash),
sail@chromium.org5538e022011-05-12 17:53:16 +0000468 self.change.AffectedFiles(include_dirs, include_deletes, file_filter))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000469
470 def LocalPaths(self, include_dirs=False):
471 """Returns local paths of input_api.AffectedFiles()."""
pgervais@chromium.org2f64f782014-04-25 00:12:33 +0000472 paths = [af.LocalPath() for af in self.AffectedFiles(include_dirs)]
473 logging.debug("LocalPaths: %s", paths)
474 return paths
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000475
476 def AbsoluteLocalPaths(self, include_dirs=False):
477 """Returns absolute local paths of input_api.AffectedFiles()."""
478 return [af.AbsoluteLocalPath() for af in self.AffectedFiles(include_dirs)]
479
480 def ServerPaths(self, include_dirs=False):
481 """Returns server paths of input_api.AffectedFiles()."""
482 return [af.ServerPath() for af in self.AffectedFiles(include_dirs)]
483
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000484 def AffectedTextFiles(self, include_deletes=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000485 """Same as input_api.change.AffectedTextFiles() except only lists files
486 in the same directory as the current presubmit script, or subdirectories
487 thereof.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000488 """
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000489 if include_deletes is not None:
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000490 warn("AffectedTextFiles(include_deletes=%s)"
491 " is deprecated and ignored" % str(include_deletes),
492 category=DeprecationWarning,
493 stacklevel=2)
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000494 return filter(lambda x: x.IsTextFile(),
495 self.AffectedFiles(include_dirs=False, include_deletes=False))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000496
maruel@chromium.org3410d912009-06-09 20:56:16 +0000497 def FilterSourceFile(self, affected_file, white_list=None, black_list=None):
498 """Filters out files that aren't considered "source file".
499
500 If white_list or black_list is None, InputApi.DEFAULT_WHITE_LIST
501 and InputApi.DEFAULT_BLACK_LIST is used respectively.
502
503 The lists will be compiled as regular expression and
504 AffectedFile.LocalPath() needs to pass both list.
505
506 Note: Copy-paste this function to suit your needs or use a lambda function.
507 """
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000508 def Find(affected_file, items):
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000509 local_path = affected_file.LocalPath()
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000510 for item in items:
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000511 if self.re.match(item, local_path):
512 logging.debug("%s matched %s" % (item, local_path))
maruel@chromium.org3410d912009-06-09 20:56:16 +0000513 return True
514 return False
515 return (Find(affected_file, white_list or self.DEFAULT_WHITE_LIST) and
516 not Find(affected_file, black_list or self.DEFAULT_BLACK_LIST))
517
518 def AffectedSourceFiles(self, source_file):
519 """Filter the list of AffectedTextFiles by the function source_file.
520
521 If source_file is None, InputApi.FilterSourceFile() is used.
522 """
523 if not source_file:
524 source_file = self.FilterSourceFile
525 return filter(source_file, self.AffectedTextFiles())
526
527 def RightHandSideLines(self, source_file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000528 """An iterator over all text lines in "new" version of changed files.
529
530 Only lists lines from new or modified text files in the change that are
531 contained by the directory of the currently executing presubmit script.
532
533 This is useful for doing line-by-line regex checks, like checking for
534 trailing whitespace.
535
536 Yields:
537 a 3 tuple:
538 the AffectedFile instance of the current file;
539 integer line number (1-based); and
540 the contents of the line as a string.
maruel@chromium.org1487d532009-06-06 00:22:57 +0000541
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000542 Note: The carriage return (LF or CR) is stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000543 """
maruel@chromium.org3410d912009-06-09 20:56:16 +0000544 files = self.AffectedSourceFiles(source_file_filter)
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000545 return _RightHandSideLinesImpl(files)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000546
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000547 def ReadFile(self, file_item, mode='r'):
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000548 """Reads an arbitrary file.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000549
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000550 Deny reading anything outside the repository.
551 """
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000552 if isinstance(file_item, AffectedFile):
553 file_item = file_item.AbsoluteLocalPath()
554 if not file_item.startswith(self.change.RepositoryRoot()):
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000555 raise IOError('Access outside the repository root is denied.')
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000556 return gclient_utils.FileRead(file_item, mode)
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000557
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000558 @property
559 def tbr(self):
560 """Returns if a change is TBR'ed."""
561 return 'TBR' in self.change.tags
562
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +0000563 def RunTests(self, tests_mix, parallel=True):
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000564 tests = []
565 msgs = []
566 for t in tests_mix:
567 if isinstance(t, OutputApi.PresubmitResult):
568 msgs.append(t)
569 else:
570 assert issubclass(t.message, _PresubmitResult)
571 tests.append(t)
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +0000572 if self.verbose:
573 t.info = _PresubmitNotifyResult
ilevy@chromium.org5678d332013-05-18 01:34:14 +0000574 if len(tests) > 1 and parallel:
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000575 # async recipe works around multiprocessing bug handling Ctrl-C
iannucci@chromium.orgd61a4952015-07-01 23:21:26 +0000576 msgs.extend(self._run_tests_pool.map_async(CallCommand, tests).get(99999))
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000577 else:
578 msgs.extend(map(CallCommand, tests))
579 return [m for m in msgs if m]
580
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000581
nick@chromium.orgff526192013-06-10 19:30:26 +0000582class _DiffCache(object):
583 """Caches diffs retrieved from a particular SCM."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000584 def __init__(self, upstream=None):
585 """Stores the upstream revision against which all diffs will be computed."""
586 self._upstream = upstream
nick@chromium.orgff526192013-06-10 19:30:26 +0000587
588 def GetDiff(self, path, local_root):
589 """Get the diff for a particular path."""
590 raise NotImplementedError()
591
592
593class _SvnDiffCache(_DiffCache):
594 """DiffCache implementation for subversion."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000595 def __init__(self, *args, **kwargs):
596 super(_SvnDiffCache, self).__init__(*args, **kwargs)
nick@chromium.orgff526192013-06-10 19:30:26 +0000597 self._diffs_by_file = {}
598
599 def GetDiff(self, path, local_root):
600 if path not in self._diffs_by_file:
601 self._diffs_by_file[path] = scm.SVN.GenerateDiff([path], local_root,
602 False, None)
603 return self._diffs_by_file[path]
604
605
606class _GitDiffCache(_DiffCache):
607 """DiffCache implementation for git; gets all file diffs at once."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000608 def __init__(self, upstream):
609 super(_GitDiffCache, self).__init__(upstream=upstream)
nick@chromium.orgff526192013-06-10 19:30:26 +0000610 self._diffs_by_file = None
611
612 def GetDiff(self, path, local_root):
613 if not self._diffs_by_file:
614 # Compute a single diff for all files and parse the output; should
615 # with git this is much faster than computing one diff for each file.
616 diffs = {}
617
618 # Don't specify any filenames below, because there are command line length
619 # limits on some platforms and GenerateDiff would fail.
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000620 unified_diff = scm.GIT.GenerateDiff(local_root, files=[], full_move=True,
621 branch=self._upstream)
nick@chromium.orgff526192013-06-10 19:30:26 +0000622
623 # This regex matches the path twice, separated by a space. Note that
624 # filename itself may contain spaces.
625 file_marker = re.compile('^diff --git (?P<filename>.*) (?P=filename)$')
626 current_diff = []
627 keep_line_endings = True
628 for x in unified_diff.splitlines(keep_line_endings):
629 match = file_marker.match(x)
630 if match:
631 # Marks the start of a new per-file section.
632 diffs[match.group('filename')] = current_diff = [x]
633 elif x.startswith('diff --git'):
634 raise PresubmitFailure('Unexpected diff line: %s' % x)
635 else:
636 current_diff.append(x)
637
638 self._diffs_by_file = dict(
639 (normpath(path), ''.join(diff)) for path, diff in diffs.items())
640
641 if path not in self._diffs_by_file:
642 raise PresubmitFailure(
643 'Unified diff did not contain entry for file %s' % path)
644
645 return self._diffs_by_file[path]
646
647
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000648class AffectedFile(object):
649 """Representation of a file in a change."""
nick@chromium.orgff526192013-06-10 19:30:26 +0000650
651 DIFF_CACHE = _DiffCache
652
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000653 # Method could be a function
654 # pylint: disable=R0201
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000655 def __init__(self, path, action, repository_root, diff_cache):
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000656 self._path = path
657 self._action = action
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000658 self._local_root = repository_root
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000659 self._is_directory = None
660 self._properties = {}
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000661 self._cached_changed_contents = None
662 self._cached_new_contents = None
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000663 self._diff_cache = diff_cache
maruel@chromium.org5d0dc432011-01-03 02:40:37 +0000664 logging.debug('%s(%s)' % (self.__class__.__name__, self._path))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000665
666 def ServerPath(self):
667 """Returns a path string that identifies the file in the SCM system.
668
669 Returns the empty string if the file does not exist in SCM.
670 """
nick@chromium.orgff526192013-06-10 19:30:26 +0000671 return ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000672
673 def LocalPath(self):
674 """Returns the path of this file on the local disk relative to client root.
675 """
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000676 return normpath(self._path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000677
678 def AbsoluteLocalPath(self):
679 """Returns the absolute path of this file on the local disk.
680 """
chase@chromium.org8e416c82009-10-06 04:30:44 +0000681 return os.path.abspath(os.path.join(self._local_root, self.LocalPath()))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000682
683 def IsDirectory(self):
684 """Returns true if this object is a directory."""
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000685 if self._is_directory is None:
686 path = self.AbsoluteLocalPath()
687 self._is_directory = (os.path.exists(path) and
688 os.path.isdir(path))
689 return self._is_directory
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000690
691 def Action(self):
692 """Returns the action on this opened file, e.g. A, M, D, etc."""
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000693 # TODO(maruel): Somewhat crappy, Could be "A" or "A +" for svn but
694 # different for other SCM.
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000695 return self._action
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000696
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000697 def Property(self, property_name):
698 """Returns the specified SCM property of this file, or None if no such
699 property.
700 """
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000701 return self._properties.get(property_name, None)
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000702
maruel@chromium.org1e08c002009-05-28 19:09:33 +0000703 def IsTextFile(self):
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000704 """Returns True if the file is a text file and not a binary file.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000705
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000706 Deleted files are not text file."""
maruel@chromium.org1e08c002009-05-28 19:09:33 +0000707 raise NotImplementedError() # Implement when needed
708
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000709 def NewContents(self):
710 """Returns an iterator over the lines in the new version of file.
711
712 The new version is the file in the user's workspace, i.e. the "right hand
713 side".
714
715 Contents will be empty if the file is a directory or does not exist.
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000716 Note: The carriage returns (LF or CR) are stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000717 """
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000718 if self._cached_new_contents is None:
719 self._cached_new_contents = []
720 if not self.IsDirectory():
721 try:
722 self._cached_new_contents = gclient_utils.FileRead(
723 self.AbsoluteLocalPath(), 'rU').splitlines()
724 except IOError:
725 pass # File not found? That's fine; maybe it was deleted.
726 return self._cached_new_contents[:]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000727
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000728 def ChangedContents(self):
729 """Returns a list of tuples (line number, line text) of all new lines.
730
731 This relies on the scm diff output describing each changed code section
732 with a line of the form
733
734 ^@@ <old line num>,<old size> <new line num>,<new size> @@$
735 """
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000736 if self._cached_changed_contents is not None:
737 return self._cached_changed_contents[:]
738 self._cached_changed_contents = []
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000739 line_num = 0
740
741 if self.IsDirectory():
742 return []
743
744 for line in self.GenerateScmDiff().splitlines():
745 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
746 if m:
747 line_num = int(m.groups(1)[0])
748 continue
749 if line.startswith('+') and not line.startswith('++'):
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000750 self._cached_changed_contents.append((line_num, line[1:]))
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000751 if not line.startswith('-'):
752 line_num += 1
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000753 return self._cached_changed_contents[:]
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000754
maruel@chromium.org5de13972009-06-10 18:16:06 +0000755 def __str__(self):
756 return self.LocalPath()
757
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000758 def GenerateScmDiff(self):
nick@chromium.orgff526192013-06-10 19:30:26 +0000759 return self._diff_cache.GetDiff(self.LocalPath(), self._local_root)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000760
maruel@chromium.org58407af2011-04-12 23:15:57 +0000761
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000762class SvnAffectedFile(AffectedFile):
763 """Representation of a file in a change out of a Subversion checkout."""
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000764 # Method 'NNN' is abstract in class 'NNN' but is not overridden
765 # pylint: disable=W0223
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000766
nick@chromium.orgff526192013-06-10 19:30:26 +0000767 DIFF_CACHE = _SvnDiffCache
768
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000769 def __init__(self, *args, **kwargs):
770 AffectedFile.__init__(self, *args, **kwargs)
771 self._server_path = None
772 self._is_text_file = None
773
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000774 def ServerPath(self):
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000775 if self._server_path is None:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000776 self._server_path = scm.SVN.CaptureLocalInfo(
777 [self.LocalPath()], self._local_root).get('URL', '')
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000778 return self._server_path
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000779
780 def IsDirectory(self):
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000781 if self._is_directory is None:
782 path = self.AbsoluteLocalPath()
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000783 if os.path.exists(path):
784 # Retrieve directly from the file system; it is much faster than
785 # querying subversion, especially on Windows.
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000786 self._is_directory = os.path.isdir(path)
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000787 else:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000788 self._is_directory = scm.SVN.CaptureLocalInfo(
789 [self.LocalPath()], self._local_root
790 ).get('Node Kind') in ('dir', 'directory')
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000791 return self._is_directory
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000792
793 def Property(self, property_name):
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000794 if not property_name in self._properties:
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000795 self._properties[property_name] = scm.SVN.GetFileProperty(
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000796 self.LocalPath(), property_name, self._local_root).rstrip()
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000797 return self._properties[property_name]
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000798
maruel@chromium.org1e08c002009-05-28 19:09:33 +0000799 def IsTextFile(self):
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000800 if self._is_text_file is None:
801 if self.Action() == 'D':
802 # A deleted file is not a text file.
803 self._is_text_file = False
804 elif self.IsDirectory():
805 self._is_text_file = False
806 else:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000807 mime_type = scm.SVN.GetFileProperty(
808 self.LocalPath(), 'svn:mime-type', self._local_root)
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000809 self._is_text_file = (not mime_type or mime_type.startswith('text/'))
810 return self._is_text_file
maruel@chromium.org1e08c002009-05-28 19:09:33 +0000811
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000812
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000813class GitAffectedFile(AffectedFile):
814 """Representation of a file in a change out of a git checkout."""
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000815 # Method 'NNN' is abstract in class 'NNN' but is not overridden
816 # pylint: disable=W0223
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000817
nick@chromium.orgff526192013-06-10 19:30:26 +0000818 DIFF_CACHE = _GitDiffCache
819
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000820 def __init__(self, *args, **kwargs):
821 AffectedFile.__init__(self, *args, **kwargs)
822 self._server_path = None
823 self._is_text_file = None
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000824
825 def ServerPath(self):
826 if self._server_path is None:
maruel@chromium.org899e1c12011-04-07 17:03:18 +0000827 raise NotImplementedError('TODO(maruel) Implement.')
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000828 return self._server_path
829
830 def IsDirectory(self):
831 if self._is_directory is None:
832 path = self.AbsoluteLocalPath()
833 if os.path.exists(path):
834 # Retrieve directly from the file system; it is much faster than
835 # querying subversion, especially on Windows.
836 self._is_directory = os.path.isdir(path)
837 else:
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000838 self._is_directory = False
839 return self._is_directory
840
841 def Property(self, property_name):
842 if not property_name in self._properties:
maruel@chromium.org899e1c12011-04-07 17:03:18 +0000843 raise NotImplementedError('TODO(maruel) Implement.')
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000844 return self._properties[property_name]
845
846 def IsTextFile(self):
847 if self._is_text_file is None:
848 if self.Action() == 'D':
849 # A deleted file is not a text file.
850 self._is_text_file = False
851 elif self.IsDirectory():
852 self._is_text_file = False
853 else:
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000854 self._is_text_file = os.path.isfile(self.AbsoluteLocalPath())
855 return self._is_text_file
856
maruel@chromium.orgc1938752011-04-12 23:11:13 +0000857
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000858class Change(object):
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000859 """Describe a change.
860
861 Used directly by the presubmit scripts to query the current change being
862 tested.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000863
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000864 Instance members:
nick@chromium.orgff526192013-06-10 19:30:26 +0000865 tags: Dictionary of KEY=VALUE pairs found in the change description.
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000866 self.KEY: equivalent to tags['KEY']
867 """
868
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000869 _AFFECTED_FILES = AffectedFile
870
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000871 # Matches key/value (or "tag") lines in changelist descriptions.
maruel@chromium.org428342a2011-11-10 15:46:33 +0000872 TAG_LINE_RE = re.compile(
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +0000873 '^[ \t]*(?P<key>[A-Z][A-Z_0-9]*)[ \t]*=[ \t]*(?P<value>.*?)[ \t]*$')
maruel@chromium.orgc1938752011-04-12 23:11:13 +0000874 scm = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000875
maruel@chromium.org58407af2011-04-12 23:15:57 +0000876 def __init__(
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000877 self, name, description, local_root, files, issue, patchset, author,
878 upstream=None):
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000879 if files is None:
880 files = []
881 self._name = name
chase@chromium.org8e416c82009-10-06 04:30:44 +0000882 # Convert root into an absolute path.
883 self._local_root = os.path.abspath(local_root)
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000884 self._upstream = upstream
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000885 self.issue = issue
886 self.patchset = patchset
maruel@chromium.org58407af2011-04-12 23:15:57 +0000887 self.author_email = author
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000888
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000889 self._full_description = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000890 self.tags = {}
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000891 self._description_without_tags = ''
892 self.SetDescriptionText(description)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000893
maruel@chromium.orge085d812011-10-10 19:49:15 +0000894 assert all(
895 (isinstance(f, (list, tuple)) and len(f) == 2) for f in files), files
896
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000897 diff_cache = self._AFFECTED_FILES.DIFF_CACHE(self._upstream)
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000898 self._affected_files = [
nick@chromium.orgff526192013-06-10 19:30:26 +0000899 self._AFFECTED_FILES(path, action.strip(), self._local_root, diff_cache)
900 for action, path in files
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000901 ]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000902
maruel@chromium.org92022ec2009-06-11 01:59:28 +0000903 def Name(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000904 """Returns the change name."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000905 return self._name
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000906
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000907 def DescriptionText(self):
908 """Returns the user-entered changelist description, minus tags.
909
910 Any line in the user-provided description starting with e.g. "FOO="
911 (whitespace permitted before and around) is considered a tag line. Such
912 lines are stripped out of the description this function returns.
913 """
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000914 return self._description_without_tags
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000915
916 def FullDescriptionText(self):
917 """Returns the complete changelist description including tags."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000918 return self._full_description
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000919
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000920 def SetDescriptionText(self, description):
921 """Sets the full description text (including tags) to |description|.
pgervais@chromium.org92c30092014-04-15 00:30:37 +0000922
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000923 Also updates the list of tags."""
924 self._full_description = description
925
926 # From the description text, build up a dictionary of key/value pairs
927 # plus the description minus all key/value or "tag" lines.
928 description_without_tags = []
929 self.tags = {}
930 for line in self._full_description.splitlines():
931 m = self.TAG_LINE_RE.match(line)
932 if m:
933 self.tags[m.group('key')] = m.group('value')
934 else:
935 description_without_tags.append(line)
936
937 # Change back to text and remove whitespace at end.
938 self._description_without_tags = (
939 '\n'.join(description_without_tags).rstrip())
940
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000941 def RepositoryRoot(self):
maruel@chromium.org92022ec2009-06-11 01:59:28 +0000942 """Returns the repository (checkout) root directory for this change,
943 as an absolute path.
944 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000945 return self._local_root
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000946
947 def __getattr__(self, attr):
maruel@chromium.org92022ec2009-06-11 01:59:28 +0000948 """Return tags directly as attributes on the object."""
949 if not re.match(r"^[A-Z_]*$", attr):
950 raise AttributeError(self, attr)
maruel@chromium.orge1a524f2009-05-27 14:43:46 +0000951 return self.tags.get(attr)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000952
agable@chromium.org40a3d0b2014-05-15 01:59:16 +0000953 def AllFiles(self, root=None):
954 """List all files under source control in the repo."""
955 raise NotImplementedError()
956
sail@chromium.org5538e022011-05-12 17:53:16 +0000957 def AffectedFiles(self, include_dirs=False, include_deletes=True,
958 file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000959 """Returns a list of AffectedFile instances for all files in the change.
960
961 Args:
962 include_deletes: If false, deleted files will be filtered out.
963 include_dirs: True to include directories in the list
sail@chromium.org5538e022011-05-12 17:53:16 +0000964 file_filter: An additional filter to apply.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000965
966 Returns:
967 [AffectedFile(path, action), AffectedFile(path, action)]
968 """
969 if include_dirs:
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000970 affected = self._affected_files
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000971 else:
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000972 affected = filter(lambda x: not x.IsDirectory(), self._affected_files)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000973
sail@chromium.org5538e022011-05-12 17:53:16 +0000974 affected = filter(file_filter, affected)
975
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000976 if include_deletes:
977 return affected
978 else:
979 return filter(lambda x: x.Action() != 'D', affected)
980
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000981 def AffectedTextFiles(self, include_deletes=None):
982 """Return a list of the existing text files in a change."""
983 if include_deletes is not None:
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000984 warn("AffectedTextFiles(include_deletes=%s)"
985 " is deprecated and ignored" % str(include_deletes),
986 category=DeprecationWarning,
987 stacklevel=2)
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000988 return filter(lambda x: x.IsTextFile(),
989 self.AffectedFiles(include_dirs=False, include_deletes=False))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000990
991 def LocalPaths(self, include_dirs=False):
992 """Convenience function."""
993 return [af.LocalPath() for af in self.AffectedFiles(include_dirs)]
994
995 def AbsoluteLocalPaths(self, include_dirs=False):
996 """Convenience function."""
997 return [af.AbsoluteLocalPath() for af in self.AffectedFiles(include_dirs)]
998
999 def ServerPaths(self, include_dirs=False):
1000 """Convenience function."""
1001 return [af.ServerPath() for af in self.AffectedFiles(include_dirs)]
1002
1003 def RightHandSideLines(self):
1004 """An iterator over all text lines in "new" version of changed files.
1005
1006 Lists lines from new or modified text files in the change.
1007
1008 This is useful for doing line-by-line regex checks, like checking for
1009 trailing whitespace.
1010
1011 Yields:
1012 a 3 tuple:
1013 the AffectedFile instance of the current file;
1014 integer line number (1-based); and
1015 the contents of the line as a string.
1016 """
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +00001017 return _RightHandSideLinesImpl(
1018 x for x in self.AffectedFiles(include_deletes=False)
1019 if x.IsTextFile())
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001020
1021
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001022class SvnChange(Change):
1023 _AFFECTED_FILES = SvnAffectedFile
maruel@chromium.orgc1938752011-04-12 23:11:13 +00001024 scm = 'svn'
1025 _changelists = None
thestig@chromium.org6bd31702009-09-02 23:29:07 +00001026
1027 def _GetChangeLists(self):
1028 """Get all change lists."""
1029 if self._changelists == None:
1030 previous_cwd = os.getcwd()
1031 os.chdir(self.RepositoryRoot())
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +00001032 # Need to import here to avoid circular dependency.
1033 import gcl
thestig@chromium.org6bd31702009-09-02 23:29:07 +00001034 self._changelists = gcl.GetModifiedFiles()
1035 os.chdir(previous_cwd)
1036 return self._changelists
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +00001037
1038 def GetAllModifiedFiles(self):
1039 """Get all modified files."""
thestig@chromium.org6bd31702009-09-02 23:29:07 +00001040 changelists = self._GetChangeLists()
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +00001041 all_modified_files = []
1042 for cl in changelists.values():
thestig@chromium.org6bd31702009-09-02 23:29:07 +00001043 all_modified_files.extend(
1044 [os.path.join(self.RepositoryRoot(), f[1]) for f in cl])
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +00001045 return all_modified_files
1046
1047 def GetModifiedFiles(self):
1048 """Get modified files in the current CL."""
thestig@chromium.org6bd31702009-09-02 23:29:07 +00001049 changelists = self._GetChangeLists()
1050 return [os.path.join(self.RepositoryRoot(), f[1])
1051 for f in changelists[self.Name()]]
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +00001052
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001053 def AllFiles(self, root=None):
1054 """List all files under source control in the repo."""
1055 root = root or self.RepositoryRoot()
1056 return subprocess.check_output(
1057 ['svn', 'ls', '-R', '.'], cwd=root).splitlines()
1058
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001059
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001060class GitChange(Change):
1061 _AFFECTED_FILES = GitAffectedFile
maruel@chromium.orgc1938752011-04-12 23:11:13 +00001062 scm = 'git'
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +00001063
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001064 def AllFiles(self, root=None):
1065 """List all files under source control in the repo."""
1066 root = root or self.RepositoryRoot()
1067 return subprocess.check_output(
1068 ['git', 'ls-files', '--', '.'], cwd=root).splitlines()
1069
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001070
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001071def ListRelevantPresubmitFiles(files, root):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001072 """Finds all presubmit files that apply to a given set of source files.
1073
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001074 If inherit-review-settings-ok is present right under root, looks for
1075 PRESUBMIT.py in directories enclosing root.
1076
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001077 Args:
1078 files: An iterable container containing file paths.
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001079 root: Path where to stop searching.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001080
1081 Return:
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001082 List of absolute paths of the existing PRESUBMIT.py scripts.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001083 """
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001084 files = [normpath(os.path.join(root, f)) for f in files]
1085
1086 # List all the individual directories containing files.
1087 directories = set([os.path.dirname(f) for f in files])
1088
1089 # Ignore root if inherit-review-settings-ok is present.
1090 if os.path.isfile(os.path.join(root, 'inherit-review-settings-ok')):
1091 root = None
1092
1093 # Collect all unique directories that may contain PRESUBMIT.py.
1094 candidates = set()
1095 for directory in directories:
1096 while True:
1097 if directory in candidates:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001098 break
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001099 candidates.add(directory)
1100 if directory == root:
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001101 break
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001102 parent_dir = os.path.dirname(directory)
1103 if parent_dir == directory:
1104 # We hit the system root directory.
1105 break
1106 directory = parent_dir
1107
1108 # Look for PRESUBMIT.py in all candidate directories.
1109 results = []
1110 for directory in sorted(list(candidates)):
1111 p = os.path.join(directory, 'PRESUBMIT.py')
1112 if os.path.isfile(p):
1113 results.append(p)
1114
maruel@chromium.org5d0dc432011-01-03 02:40:37 +00001115 logging.debug('Presubmit files: %s' % ','.join(results))
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001116 return results
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001117
1118
thestig@chromium.orgde243452009-10-06 21:02:56 +00001119class GetTrySlavesExecuter(object):
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +00001120 @staticmethod
asvitkine@chromium.org15169952011-09-27 14:30:53 +00001121 def ExecPresubmitScript(script_text, presubmit_path, project, change):
thestig@chromium.orgde243452009-10-06 21:02:56 +00001122 """Executes GetPreferredTrySlaves() from a single presubmit script.
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001123
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001124 This will soon be deprecated and replaced by GetPreferredTryMasters().
thestig@chromium.orgde243452009-10-06 21:02:56 +00001125
1126 Args:
1127 script_text: The text of the presubmit script.
bradnelson@google.com78230022011-05-24 18:55:19 +00001128 presubmit_path: Project script to run.
1129 project: Project name to pass to presubmit script for bot selection.
thestig@chromium.orgde243452009-10-06 21:02:56 +00001130
1131 Return:
1132 A list of try slaves.
1133 """
1134 context = {}
alokp@chromium.orgf6349642014-03-04 00:52:18 +00001135 main_path = os.getcwd()
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001136 try:
alokp@chromium.orgf6349642014-03-04 00:52:18 +00001137 os.chdir(os.path.dirname(presubmit_path))
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001138 exec script_text in context
1139 except Exception, e:
1140 raise PresubmitFailure('"%s" had an exception.\n%s' % (presubmit_path, e))
alokp@chromium.orgf6349642014-03-04 00:52:18 +00001141 finally:
1142 os.chdir(main_path)
thestig@chromium.orgde243452009-10-06 21:02:56 +00001143
1144 function_name = 'GetPreferredTrySlaves'
1145 if function_name in context:
asvitkine@chromium.org15169952011-09-27 14:30:53 +00001146 get_preferred_try_slaves = context[function_name]
1147 function_info = inspect.getargspec(get_preferred_try_slaves)
1148 if len(function_info[0]) == 1:
1149 result = get_preferred_try_slaves(project)
1150 elif len(function_info[0]) == 2:
1151 result = get_preferred_try_slaves(project, change)
1152 else:
1153 result = get_preferred_try_slaves()
thestig@chromium.orgde243452009-10-06 21:02:56 +00001154 if not isinstance(result, types.ListType):
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001155 raise PresubmitFailure(
thestig@chromium.orgde243452009-10-06 21:02:56 +00001156 'Presubmit functions must return a list, got a %s instead: %s' %
1157 (type(result), str(result)))
1158 for item in result:
stip@chromium.org68e04192013-11-04 22:14:38 +00001159 if isinstance(item, basestring):
1160 # Old-style ['bot'] format.
1161 botname = item
1162 elif isinstance(item, tuple):
1163 # New-style [('bot', set(['tests']))] format.
1164 botname = item[0]
1165 else:
1166 raise PresubmitFailure('PRESUBMIT.py returned invalid tryslave/test'
1167 ' format.')
1168
1169 if botname != botname.strip():
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001170 raise PresubmitFailure(
1171 'Try slave names cannot start/end with whitespace')
stip@chromium.org68e04192013-11-04 22:14:38 +00001172 if ',' in botname:
maruel@chromium.org3ecc8ea2012-03-10 01:47:46 +00001173 raise PresubmitFailure(
stip@chromium.org68e04192013-11-04 22:14:38 +00001174 'Do not use \',\' separated builder or test names: %s' % botname)
thestig@chromium.orgde243452009-10-06 21:02:56 +00001175 else:
1176 result = []
stip@chromium.org5ca27622013-12-18 17:44:58 +00001177
1178 def valid_oldstyle(result):
1179 return all(isinstance(i, basestring) for i in result)
1180
1181 def valid_newstyle(result):
1182 return (all(isinstance(i, tuple) for i in result) and
1183 all(len(i) == 2 for i in result) and
1184 all(isinstance(i[0], basestring) for i in result) and
1185 all(isinstance(i[1], set) for i in result)
1186 )
1187
1188 # Ensure it's either all old-style or all new-style.
1189 if not valid_oldstyle(result) and not valid_newstyle(result):
1190 raise PresubmitFailure(
1191 'PRESUBMIT.py returned invalid trybot specification!')
1192
thestig@chromium.orgde243452009-10-06 21:02:56 +00001193 return result
1194
1195
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001196class GetTryMastersExecuter(object):
1197 @staticmethod
1198 def ExecPresubmitScript(script_text, presubmit_path, project, change):
1199 """Executes GetPreferredTryMasters() from a single presubmit script.
1200
1201 Args:
1202 script_text: The text of the presubmit script.
1203 presubmit_path: Project script to run.
1204 project: Project name to pass to presubmit script for bot selection.
1205
1206 Return:
1207 A map of try masters to map of builders to set of tests.
1208 """
1209 context = {}
1210 try:
1211 exec script_text in context
1212 except Exception, e:
1213 raise PresubmitFailure('"%s" had an exception.\n%s'
1214 % (presubmit_path, e))
1215
1216 function_name = 'GetPreferredTryMasters'
1217 if function_name not in context:
1218 return {}
1219 get_preferred_try_masters = context[function_name]
1220 if not len(inspect.getargspec(get_preferred_try_masters)[0]) == 2:
1221 raise PresubmitFailure(
1222 'Expected function "GetPreferredTryMasters" to take two arguments.')
1223 return get_preferred_try_masters(project, change)
1224
1225
rmistry@google.com5626a922015-02-26 14:03:30 +00001226class GetPostUploadExecuter(object):
1227 @staticmethod
1228 def ExecPresubmitScript(script_text, presubmit_path, cl, change):
1229 """Executes PostUploadHook() from a single presubmit script.
1230
1231 Args:
1232 script_text: The text of the presubmit script.
1233 presubmit_path: Project script to run.
1234 cl: The Changelist object.
1235 change: The Change object.
1236
1237 Return:
1238 A list of results objects.
1239 """
1240 context = {}
1241 try:
1242 exec script_text in context
1243 except Exception, e:
1244 raise PresubmitFailure('"%s" had an exception.\n%s'
1245 % (presubmit_path, e))
1246
1247 function_name = 'PostUploadHook'
1248 if function_name not in context:
1249 return {}
1250 post_upload_hook = context[function_name]
1251 if not len(inspect.getargspec(post_upload_hook)[0]) == 3:
1252 raise PresubmitFailure(
1253 'Expected function "PostUploadHook" to take three arguments.')
1254 return post_upload_hook(cl, change, OutputApi(False))
1255
1256
asvitkine@chromium.org15169952011-09-27 14:30:53 +00001257def DoGetTrySlaves(change,
1258 changed_files,
thestig@chromium.orgde243452009-10-06 21:02:56 +00001259 repository_root,
1260 default_presubmit,
bradnelson@google.com78230022011-05-24 18:55:19 +00001261 project,
thestig@chromium.orgde243452009-10-06 21:02:56 +00001262 verbose,
1263 output_stream):
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001264 """Get the list of try servers from the presubmit scripts (deprecated).
thestig@chromium.orgde243452009-10-06 21:02:56 +00001265
1266 Args:
1267 changed_files: List of modified files.
1268 repository_root: The repository root.
1269 default_presubmit: A default presubmit script to execute in any case.
bradnelson@google.com78230022011-05-24 18:55:19 +00001270 project: Optional name of a project used in selecting trybots.
thestig@chromium.orgde243452009-10-06 21:02:56 +00001271 verbose: Prints debug info.
1272 output_stream: A stream to write debug output to.
1273
1274 Return:
1275 List of try slaves
1276 """
1277 presubmit_files = ListRelevantPresubmitFiles(changed_files, repository_root)
1278 if not presubmit_files and verbose:
mdempsky@chromium.orgd59e7612014-03-05 19:55:56 +00001279 output_stream.write("Warning, no PRESUBMIT.py found.\n")
thestig@chromium.orgde243452009-10-06 21:02:56 +00001280 results = []
1281 executer = GetTrySlavesExecuter()
stip@chromium.org5ca27622013-12-18 17:44:58 +00001282
thestig@chromium.orgde243452009-10-06 21:02:56 +00001283 if default_presubmit:
1284 if verbose:
1285 output_stream.write("Running default presubmit script.\n")
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001286 fake_path = os.path.join(repository_root, 'PRESUBMIT.py')
stip@chromium.org5ca27622013-12-18 17:44:58 +00001287 results.extend(executer.ExecPresubmitScript(
1288 default_presubmit, fake_path, project, change))
thestig@chromium.orgde243452009-10-06 21:02:56 +00001289 for filename in presubmit_files:
1290 filename = os.path.abspath(filename)
1291 if verbose:
1292 output_stream.write("Running %s\n" % filename)
1293 # Accept CRLF presubmit script.
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +00001294 presubmit_script = gclient_utils.FileRead(filename, 'rU')
stip@chromium.org5ca27622013-12-18 17:44:58 +00001295 results.extend(executer.ExecPresubmitScript(
1296 presubmit_script, filename, project, change))
thestig@chromium.orgde243452009-10-06 21:02:56 +00001297
stip@chromium.org5ca27622013-12-18 17:44:58 +00001298
1299 slave_dict = {}
1300 old_style = filter(lambda x: isinstance(x, basestring), results)
1301 new_style = filter(lambda x: isinstance(x, tuple), results)
1302
1303 for result in new_style:
1304 slave_dict.setdefault(result[0], set()).update(result[1])
1305 slaves = list(slave_dict.items())
1306
1307 slaves.extend(set(old_style))
stip@chromium.org68e04192013-11-04 22:14:38 +00001308
thestig@chromium.orgde243452009-10-06 21:02:56 +00001309 if slaves and verbose:
stip@chromium.org5ca27622013-12-18 17:44:58 +00001310 output_stream.write(', '.join((str(x) for x in slaves)))
thestig@chromium.orgde243452009-10-06 21:02:56 +00001311 output_stream.write('\n')
1312 return slaves
1313
1314
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001315def _MergeMasters(masters1, masters2):
1316 """Merges two master maps. Merges also the tests of each builder."""
1317 result = {}
1318 for (master, builders) in itertools.chain(masters1.iteritems(),
1319 masters2.iteritems()):
1320 new_builders = result.setdefault(master, {})
1321 for (builder, tests) in builders.iteritems():
1322 new_builders.setdefault(builder, set([])).update(tests)
1323 return result
1324
1325
1326def DoGetTryMasters(change,
1327 changed_files,
1328 repository_root,
1329 default_presubmit,
1330 project,
1331 verbose,
1332 output_stream):
1333 """Get the list of try masters from the presubmit scripts.
1334
1335 Args:
1336 changed_files: List of modified files.
1337 repository_root: The repository root.
1338 default_presubmit: A default presubmit script to execute in any case.
1339 project: Optional name of a project used in selecting trybots.
1340 verbose: Prints debug info.
1341 output_stream: A stream to write debug output to.
1342
1343 Return:
1344 Map of try masters to map of builders to set of tests.
1345 """
1346 presubmit_files = ListRelevantPresubmitFiles(changed_files, repository_root)
1347 if not presubmit_files and verbose:
1348 output_stream.write("Warning, no PRESUBMIT.py found.\n")
1349 results = {}
1350 executer = GetTryMastersExecuter()
1351
1352 if default_presubmit:
1353 if verbose:
1354 output_stream.write("Running default presubmit script.\n")
1355 fake_path = os.path.join(repository_root, 'PRESUBMIT.py')
1356 results = _MergeMasters(results, executer.ExecPresubmitScript(
1357 default_presubmit, fake_path, project, change))
1358 for filename in presubmit_files:
1359 filename = os.path.abspath(filename)
1360 if verbose:
1361 output_stream.write("Running %s\n" % filename)
1362 # Accept CRLF presubmit script.
1363 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1364 results = _MergeMasters(results, executer.ExecPresubmitScript(
1365 presubmit_script, filename, project, change))
1366
1367 # Make sets to lists again for later JSON serialization.
1368 for builders in results.itervalues():
1369 for builder in builders:
1370 builders[builder] = list(builders[builder])
1371
1372 if results and verbose:
1373 output_stream.write('%s\n' % str(results))
1374 return results
1375
1376
rmistry@google.com5626a922015-02-26 14:03:30 +00001377def DoPostUploadExecuter(change,
1378 cl,
1379 repository_root,
1380 verbose,
1381 output_stream):
1382 """Execute the post upload hook.
1383
1384 Args:
1385 change: The Change object.
1386 cl: The Changelist object.
1387 repository_root: The repository root.
1388 verbose: Prints debug info.
1389 output_stream: A stream to write debug output to.
1390 """
1391 presubmit_files = ListRelevantPresubmitFiles(
1392 change.LocalPaths(), repository_root)
1393 if not presubmit_files and verbose:
1394 output_stream.write("Warning, no PRESUBMIT.py found.\n")
1395 results = []
1396 executer = GetPostUploadExecuter()
1397 # The root presubmit file should be executed after the ones in subdirectories.
1398 # i.e. the specific post upload hooks should run before the general ones.
1399 # Thus, reverse the order provided by ListRelevantPresubmitFiles.
1400 presubmit_files.reverse()
1401
1402 for filename in presubmit_files:
1403 filename = os.path.abspath(filename)
1404 if verbose:
1405 output_stream.write("Running %s\n" % filename)
1406 # Accept CRLF presubmit script.
1407 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1408 results.extend(executer.ExecPresubmitScript(
1409 presubmit_script, filename, cl, change))
1410 output_stream.write('\n')
1411 if results:
1412 output_stream.write('** Post Upload Hook Messages **\n')
1413 for result in results:
1414 result.handle(output_stream)
1415 output_stream.write('\n')
1416
1417 return results
1418
1419
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001420class PresubmitExecuter(object):
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001421 def __init__(self, change, committing, rietveld_obj, verbose,
tandrii@chromium.orgb4cd1962016-04-29 16:04:11 +00001422 gerrit_obj=None, dry_run=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001423 """
1424 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001425 change: The Change object.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001426 committing: True if 'gcl commit' is running, False if 'gcl upload' is.
maruel@chromium.org239f4112011-06-03 20:08:23 +00001427 rietveld_obj: rietveld.Rietveld client object.
tandrii@chromium.orgb4cd1962016-04-29 16:04:11 +00001428 gerrit_obj: provides basic Gerrit codereview functionality.
1429 dry_run: if true, some Checks will be skipped.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001430 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001431 self.change = change
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001432 self.committing = committing
maruel@chromium.org239f4112011-06-03 20:08:23 +00001433 self.rietveld = rietveld_obj
tandrii@chromium.orgb4cd1962016-04-29 16:04:11 +00001434 self.gerrit = gerrit_obj
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001435 self.verbose = verbose
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001436 self.dry_run = dry_run
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001437
1438 def ExecPresubmitScript(self, script_text, presubmit_path):
1439 """Executes a single presubmit script.
1440
1441 Args:
1442 script_text: The text of the presubmit script.
1443 presubmit_path: The path to the presubmit file (this will be reported via
1444 input_api.PresubmitLocalPath()).
1445
1446 Return:
1447 A list of result objects, empty if no problems.
1448 """
thakis@chromium.orgc6ef53a2014-11-04 00:13:54 +00001449
chase@chromium.org8e416c82009-10-06 04:30:44 +00001450 # Change to the presubmit file's directory to support local imports.
1451 main_path = os.getcwd()
1452 os.chdir(os.path.dirname(presubmit_path))
1453
1454 # Load the presubmit script into context.
dpranke@chromium.org970c5222011-03-12 00:32:24 +00001455 input_api = InputApi(self.change, presubmit_path, self.committing,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001456 self.rietveld, self.verbose,
tandrii@chromium.orgb4cd1962016-04-29 16:04:11 +00001457 gerrit_obj=self.gerrit, dry_run=self.dry_run)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001458 context = {}
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001459 try:
1460 exec script_text in context
1461 except Exception, e:
1462 raise PresubmitFailure('"%s" had an exception.\n%s' % (presubmit_path, e))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001463
1464 # These function names must change if we make substantial changes to
1465 # the presubmit API that are not backwards compatible.
1466 if self.committing:
1467 function_name = 'CheckChangeOnCommit'
1468 else:
1469 function_name = 'CheckChangeOnUpload'
1470 if function_name in context:
wez@chromium.orga6d011e2013-03-26 17:31:49 +00001471 context['__args'] = (input_api, OutputApi(self.committing))
maruel@chromium.org5d0dc432011-01-03 02:40:37 +00001472 logging.debug('Running %s in %s' % (function_name, presubmit_path))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001473 result = eval(function_name + '(*__args)', context)
maruel@chromium.org5d0dc432011-01-03 02:40:37 +00001474 logging.debug('Running %s done.' % function_name)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001475 if not (isinstance(result, types.TupleType) or
1476 isinstance(result, types.ListType)):
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001477 raise PresubmitFailure(
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001478 'Presubmit functions must return a tuple or list')
1479 for item in result:
1480 if not isinstance(item, OutputApi.PresubmitResult):
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001481 raise PresubmitFailure(
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001482 'All presubmit results must be of types derived from '
1483 'output_api.PresubmitResult')
1484 else:
1485 result = () # no error since the script doesn't care about current event.
1486
chase@chromium.org8e416c82009-10-06 04:30:44 +00001487 # Return the process to the original working directory.
1488 os.chdir(main_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001489 return result
1490
dpranke@chromium.org5ac21012011-03-16 02:58:25 +00001491
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001492def DoPresubmitChecks(change,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001493 committing,
1494 verbose,
1495 output_stream,
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +00001496 input_stream,
maruel@chromium.orgb0dfd352009-06-10 14:12:54 +00001497 default_presubmit,
dpranke@chromium.org970c5222011-03-12 00:32:24 +00001498 may_prompt,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001499 rietveld_obj,
tandrii@chromium.orgb4cd1962016-04-29 16:04:11 +00001500 gerrit_obj=None,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001501 dry_run=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001502 """Runs all presubmit checks that apply to the files in the change.
1503
1504 This finds all PRESUBMIT.py files in directories enclosing the files in the
1505 change (up to the repository root) and calls the relevant entrypoint function
1506 depending on whether the change is being committed or uploaded.
1507
1508 Prints errors, warnings and notifications. Prompts the user for warnings
1509 when needed.
1510
1511 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001512 change: The Change object.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001513 committing: True if 'gcl commit' is running, False if 'gcl upload' is.
1514 verbose: Prints debug info.
1515 output_stream: A stream to write output from presubmit tests to.
1516 input_stream: A stream to read input from the user.
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +00001517 default_presubmit: A default presubmit script to execute in any case.
maruel@chromium.orgb0dfd352009-06-10 14:12:54 +00001518 may_prompt: Enable (y/n) questions on warning or error.
maruel@chromium.org239f4112011-06-03 20:08:23 +00001519 rietveld_obj: rietveld.Rietveld object.
tandrii@chromium.orgb4cd1962016-04-29 16:04:11 +00001520 gerrit_obj: provides basic Gerrit codereview functionality.
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001521 dry_run: if true, some Checks will be skipped.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001522
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +00001523 Warning:
1524 If may_prompt is true, output_stream SHOULD be sys.stdout and input_stream
1525 SHOULD be sys.stdin.
1526
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001527 Return:
dpranke@chromium.org5ac21012011-03-16 02:58:25 +00001528 A PresubmitOutput object. Use output.should_continue() to figure out
1529 if there were errors or warnings and the caller should abort.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001530 """
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001531 old_environ = os.environ
1532 try:
1533 # Make sure python subprocesses won't generate .pyc files.
1534 os.environ = os.environ.copy()
1535 os.environ['PYTHONDONTWRITEBYTECODE'] = '1'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001536
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001537 output = PresubmitOutput(input_stream, output_stream)
1538 if committing:
1539 output.write("Running presubmit commit checks ...\n")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001540 else:
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001541 output.write("Running presubmit upload checks ...\n")
1542 start_time = time.time()
1543 presubmit_files = ListRelevantPresubmitFiles(
1544 change.AbsoluteLocalPaths(True), change.RepositoryRoot())
1545 if not presubmit_files and verbose:
maruel@chromium.orgfae707b2011-09-15 18:57:58 +00001546 output.write("Warning, no PRESUBMIT.py found.\n")
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001547 results = []
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001548 executer = PresubmitExecuter(change, committing, rietveld_obj, verbose,
tandrii@chromium.orgb4cd1962016-04-29 16:04:11 +00001549 gerrit_obj, dry_run)
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001550 if default_presubmit:
1551 if verbose:
1552 output.write("Running default presubmit script.\n")
1553 fake_path = os.path.join(change.RepositoryRoot(), 'PRESUBMIT.py')
1554 results += executer.ExecPresubmitScript(default_presubmit, fake_path)
1555 for filename in presubmit_files:
1556 filename = os.path.abspath(filename)
1557 if verbose:
1558 output.write("Running %s\n" % filename)
1559 # Accept CRLF presubmit script.
1560 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1561 results += executer.ExecPresubmitScript(presubmit_script, filename)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001562
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001563 errors = []
1564 notifications = []
1565 warnings = []
1566 for result in results:
1567 if result.fatal:
1568 errors.append(result)
1569 elif result.should_prompt:
1570 warnings.append(result)
1571 else:
1572 notifications.append(result)
pam@chromium.orged9a0832009-09-09 22:48:55 +00001573
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001574 output.write('\n')
1575 for name, items in (('Messages', notifications),
1576 ('Warnings', warnings),
1577 ('ERRORS', errors)):
1578 if items:
1579 output.write('** Presubmit %s **\n' % name)
1580 for item in items:
1581 item.handle(output)
1582 output.write('\n')
pam@chromium.orged9a0832009-09-09 22:48:55 +00001583
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001584 total_time = time.time() - start_time
1585 if total_time > 1.0:
1586 output.write("Presubmit checks took %.1fs to calculate.\n\n" % total_time)
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +00001587
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001588 if not errors:
1589 if not warnings:
1590 output.write('Presubmit checks passed.\n')
1591 elif may_prompt:
1592 output.prompt_yes_no('There were presubmit warnings. '
1593 'Are you sure you wish to continue? (y/N): ')
1594 else:
1595 output.fail()
1596
1597 global _ASKED_FOR_FEEDBACK
1598 # Ask for feedback one time out of 5.
1599 if (len(results) and random.randint(0, 4) == 0 and not _ASKED_FOR_FEEDBACK):
maruel@chromium.org1ce8e662014-01-14 15:23:00 +00001600 output.write(
1601 'Was the presubmit check useful? If not, run "git cl presubmit -v"\n'
1602 'to figure out which PRESUBMIT.py was run, then run git blame\n'
1603 'on the file to figure out who to ask for help.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001604 _ASKED_FOR_FEEDBACK = True
1605 return output
1606 finally:
1607 os.environ = old_environ
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001608
1609
1610def ScanSubDirs(mask, recursive):
1611 if not recursive:
pgervais@chromium.orge57b09d2014-05-07 00:58:13 +00001612 return [x for x in glob.glob(mask) if x not in ('.svn', '.git')]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001613 else:
1614 results = []
1615 for root, dirs, files in os.walk('.'):
1616 if '.svn' in dirs:
1617 dirs.remove('.svn')
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001618 if '.git' in dirs:
1619 dirs.remove('.git')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001620 for name in files:
1621 if fnmatch.fnmatch(name, mask):
1622 results.append(os.path.join(root, name))
1623 return results
1624
1625
1626def ParseFiles(args, recursive):
maruel@chromium.org7444c502011-02-09 14:02:11 +00001627 logging.debug('Searching for %s' % args)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001628 files = []
1629 for arg in args:
maruel@chromium.orge3608df2009-11-10 20:22:57 +00001630 files.extend([('M', f) for f in ScanSubDirs(arg, recursive)])
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001631 return files
1632
1633
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001634def load_files(options, args):
1635 """Tries to determine the SCM."""
1636 change_scm = scm.determine_scm(options.root)
1637 files = []
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001638 if args:
1639 files = ParseFiles(args, options.recursive)
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001640 if change_scm == 'svn':
1641 change_class = SvnChange
1642 if not files:
1643 files = scm.SVN.CaptureStatus([], options.root)
1644 elif change_scm == 'git':
1645 change_class = GitChange
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001646 upstream = options.upstream or None
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001647 if not files:
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001648 files = scm.GIT.CaptureStatus([], options.root, upstream)
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001649 else:
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001650 logging.info('Doesn\'t seem under source control. Got %d files' % len(args))
1651 if not files:
1652 return None, None
1653 change_class = Change
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001654 return change_class, files
1655
1656
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001657class NonexistantCannedCheckFilter(Exception):
1658 pass
1659
1660
1661@contextlib.contextmanager
1662def canned_check_filter(method_names):
1663 filtered = {}
1664 try:
1665 for method_name in method_names:
1666 if not hasattr(presubmit_canned_checks, method_name):
1667 raise NonexistantCannedCheckFilter(method_name)
1668 filtered[method_name] = getattr(presubmit_canned_checks, method_name)
1669 setattr(presubmit_canned_checks, method_name, lambda *_a, **_kw: [])
1670 yield
1671 finally:
1672 for name, method in filtered.iteritems():
1673 setattr(presubmit_canned_checks, name, method)
1674
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001675
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001676def CallCommand(cmd_data):
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001677 """Runs an external program, potentially from a child process created by the
1678 multiprocessing module.
1679
1680 multiprocessing needs a top level function with a single argument.
1681 """
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001682 cmd_data.kwargs['stdout'] = subprocess.PIPE
1683 cmd_data.kwargs['stderr'] = subprocess.STDOUT
1684 try:
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001685 start = time.time()
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001686 (out, _), code = subprocess.communicate(cmd_data.cmd, **cmd_data.kwargs)
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001687 duration = time.time() - start
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001688 except OSError as e:
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001689 duration = time.time() - start
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001690 return cmd_data.message(
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001691 '%s exec failure (%4.2fs)\n %s' % (cmd_data.name, duration, e))
1692 if code != 0:
1693 return cmd_data.message(
1694 '%s (%4.2fs) failed\n%s' % (cmd_data.name, duration, out))
1695 if cmd_data.info:
1696 return cmd_data.info('%s (%4.2fs)' % (cmd_data.name, duration))
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001697
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001698
sbc@chromium.org013731e2015-02-26 18:28:43 +00001699def main(argv=None):
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001700 parser = optparse.OptionParser(usage="%prog [options] <files...>",
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001701 version="%prog " + str(__version__))
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001702 parser.add_option("-c", "--commit", action="store_true", default=False,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001703 help="Use commit instead of upload checks")
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001704 parser.add_option("-u", "--upload", action="store_false", dest='commit',
1705 help="Use upload instead of commit checks")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001706 parser.add_option("-r", "--recursive", action="store_true",
1707 help="Act recursively")
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001708 parser.add_option("-v", "--verbose", action="count", default=0,
1709 help="Use 2 times for more debug info")
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001710 parser.add_option("--name", default='no name')
maruel@chromium.org58407af2011-04-12 23:15:57 +00001711 parser.add_option("--author")
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001712 parser.add_option("--description", default='')
1713 parser.add_option("--issue", type='int', default=0)
1714 parser.add_option("--patchset", type='int', default=0)
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001715 parser.add_option("--root", default=os.getcwd(),
1716 help="Search for PRESUBMIT.py up to this directory. "
1717 "If inherit-review-settings-ok is present in this "
1718 "directory, parent directories up to the root file "
1719 "system directories will also be searched.")
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001720 parser.add_option("--upstream",
1721 help="Git only: the base ref or upstream branch against "
1722 "which the diff should be computed.")
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001723 parser.add_option("--default_presubmit")
1724 parser.add_option("--may_prompt", action='store_true', default=False)
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001725 parser.add_option("--skip_canned", action='append', default=[],
1726 help="A list of checks to skip which appear in "
1727 "presubmit_canned_checks. Can be provided multiple times "
1728 "to skip multiple canned checks.")
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001729 parser.add_option("--dry_run", action='store_true',
1730 help=optparse.SUPPRESS_HELP)
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001731 parser.add_option("--gerrit_url", help=optparse.SUPPRESS_HELP)
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001732 parser.add_option("--gerrit_fetch", action='store_true',
1733 help=optparse.SUPPRESS_HELP)
maruel@chromium.org239f4112011-06-03 20:08:23 +00001734 parser.add_option("--rietveld_url", help=optparse.SUPPRESS_HELP)
1735 parser.add_option("--rietveld_email", help=optparse.SUPPRESS_HELP)
iannucci@chromium.org720fd7a2013-04-24 04:13:50 +00001736 parser.add_option("--rietveld_fetch", action='store_true', default=False,
1737 help=optparse.SUPPRESS_HELP)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001738 # These are for OAuth2 authentication for bots. See also apply_issue.py
1739 parser.add_option("--rietveld_email_file", help=optparse.SUPPRESS_HELP)
1740 parser.add_option("--rietveld_private_key_file", help=optparse.SUPPRESS_HELP)
1741
phajdan.jr@chromium.org2ff30182016-03-23 09:52:51 +00001742 # TODO(phajdan.jr): Update callers and remove obsolete --trybot-json .
stip@chromium.orgf7d31f52014-01-03 20:14:46 +00001743 parser.add_option("--trybot-json",
1744 help="Output trybot information to the file specified.")
vadimsh@chromium.orgcf6a5d22015-04-09 22:02:00 +00001745 auth.add_auth_options(parser)
maruel@chromium.org82e5f282011-03-17 14:08:55 +00001746 options, args = parser.parse_args(argv)
vadimsh@chromium.orgcf6a5d22015-04-09 22:02:00 +00001747 auth_config = auth.extract_auth_config_from_options(options)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001748
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001749 if options.verbose >= 2:
maruel@chromium.org7444c502011-02-09 14:02:11 +00001750 logging.basicConfig(level=logging.DEBUG)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001751 elif options.verbose:
1752 logging.basicConfig(level=logging.INFO)
1753 else:
1754 logging.basicConfig(level=logging.ERROR)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001755
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001756 if (any((options.rietveld_url, options.rietveld_email_file,
1757 options.rietveld_fetch, options.rietveld_private_key_file))
1758 and any((options.gerrit_url, options.gerrit_fetch))):
1759 parser.error('Options for only codereview --rietveld_* or --gerrit_* '
1760 'allowed')
1761
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001762 if options.rietveld_email and options.rietveld_email_file:
1763 parser.error("Only one of --rietveld_email or --rietveld_email_file "
1764 "can be passed to this program.")
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001765 if options.rietveld_email_file:
1766 with open(options.rietveld_email_file, "rb") as f:
1767 options.rietveld_email = f.read().strip()
1768
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001769 change_class, files = load_files(options, args)
1770 if not change_class:
1771 parser.error('For unversioned directory, <files> is not optional.')
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001772 logging.info('Found %d file(s).' % len(files))
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001773
tandrii@chromium.orgb4cd1962016-04-29 16:04:11 +00001774 rietveld_obj, gerrit_obj = None, None
1775
maruel@chromium.org239f4112011-06-03 20:08:23 +00001776 if options.rietveld_url:
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001777 # The empty password is permitted: '' is not None.
djacques@chromium.org7b654f52014-04-15 04:02:32 +00001778 if options.rietveld_private_key_file:
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001779 rietveld_obj = rietveld.JwtOAuth2Rietveld(
1780 options.rietveld_url,
1781 options.rietveld_email,
1782 options.rietveld_private_key_file)
1783 else:
djacques@chromium.org7b654f52014-04-15 04:02:32 +00001784 rietveld_obj = rietveld.CachingRietveld(
1785 options.rietveld_url,
vadimsh@chromium.orgcf6a5d22015-04-09 22:02:00 +00001786 auth_config,
1787 options.rietveld_email)
iannucci@chromium.org720fd7a2013-04-24 04:13:50 +00001788 if options.rietveld_fetch:
1789 assert options.issue
1790 props = rietveld_obj.get_issue_properties(options.issue, False)
1791 options.author = props['owner_email']
1792 options.description = props['description']
1793 logging.info('Got author: "%s"', options.author)
1794 logging.info('Got description: """\n%s\n"""', options.description)
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001795
1796 if options.gerrit_url and options.gerrit_fetch:
machenbach@chromium.org6996a102016-04-29 10:32:47 +00001797 assert options.issue and options.patchset
tandrii@chromium.orgb4cd1962016-04-29 16:04:11 +00001798 rietveld_obj = None
1799 gerrit_obj = GerritAccessor(urlparse.urlparse(options.gerrit_url).netloc)
1800 options.author = gerrit_obj.GetChangeOwner(options.issue)
1801 options.description = gerrit_obj.GetChangeDescription(options.patchset)
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001802 logging.info('Got author: "%s"', options.author)
1803 logging.info('Got description: """\n%s\n"""', options.description)
1804
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001805 try:
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001806 with canned_check_filter(options.skip_canned):
1807 results = DoPresubmitChecks(
1808 change_class(options.name,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001809 options.description,
1810 options.root,
1811 files,
1812 options.issue,
1813 options.patchset,
1814 options.author,
1815 upstream=options.upstream),
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001816 options.commit,
1817 options.verbose,
1818 sys.stdout,
1819 sys.stdin,
1820 options.default_presubmit,
1821 options.may_prompt,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001822 rietveld_obj,
tandrii@chromium.orgb4cd1962016-04-29 16:04:11 +00001823 gerrit_obj,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001824 options.dry_run)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001825 return not results.should_continue()
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001826 except NonexistantCannedCheckFilter, e:
1827 print >> sys.stderr, (
1828 'Attempted to skip nonexistent canned presubmit check: %s' % e.message)
1829 return 2
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001830 except PresubmitFailure, e:
1831 print >> sys.stderr, e
1832 print >> sys.stderr, 'Maybe your depot_tools is out of date?'
1833 print >> sys.stderr, 'If all fails, contact maruel@'
1834 return 2
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001835
1836
1837if __name__ == '__main__':
maruel@chromium.org35625c72011-03-23 17:34:02 +00001838 fix_encoding.fix_encoding()
sbc@chromium.org013731e2015-02-26 18:28:43 +00001839 try:
1840 sys.exit(main())
1841 except KeyboardInterrupt:
1842 sys.stderr.write('interrupted\n')
1843 sys.exit(1)