blob: 4161e7bb3101c02e7f3ea8051fe021fc0d407c72 [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
dcheng091b7db2016-06-16 01:27:51 -070019import fnmatch # Exposed through the API.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000020import 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.
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000161class _PresubmitError(_PresubmitResult):
162 """A hard presubmit error."""
163 fatal = True
164
165
166# Top level object so multiprocessing can pickle
167# Public access through OutputApi object.
168class _PresubmitPromptWarning(_PresubmitResult):
169 """An warning that prompts the user if they want to continue."""
170 should_prompt = True
171
172
173# Top level object so multiprocessing can pickle
174# Public access through OutputApi object.
175class _PresubmitNotifyResult(_PresubmitResult):
176 """Just print something to the screen -- but it's not even a warning."""
177 pass
178
179
180# Top level object so multiprocessing can pickle
181# Public access through OutputApi object.
182class _MailTextResult(_PresubmitResult):
183 """A warning that should be included in the review request email."""
184 def __init__(self, *args, **kwargs):
185 super(_MailTextResult, self).__init__()
186 raise NotImplementedError()
187
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000188class GerritAccessor(object):
189 """Limited Gerrit functionality for canned presubmit checks to work.
190
191 To avoid excessive Gerrit calls, caches the results.
192 """
193
194 def __init__(self, host):
195 self.host = host
196 self.cache = {}
197
198 def _FetchChangeDetail(self, issue):
199 # Separate function to be easily mocked in tests.
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +0100200 try:
201 return gerrit_util.GetChangeDetail(
202 self.host, str(issue),
203 ['ALL_REVISIONS', 'DETAILED_LABELS'],
204 ignore_404=False)
205 except gerrit_util.GerritError as e:
206 if e.http_status == 404:
207 raise Exception('Either Gerrit issue %s doesn\'t exist, or '
208 'no credentials to fetch issue details' % issue)
209 raise
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000210
211 def GetChangeInfo(self, issue):
212 """Returns labels and all revisions (patchsets) for this issue.
213
214 The result is a dictionary according to Gerrit REST Api.
215 https://gerrit-review.googlesource.com/Documentation/rest-api.html
216
217 However, API isn't very clear what's inside, so see tests for example.
218 """
219 assert issue
220 cache_key = int(issue)
221 if cache_key not in self.cache:
222 self.cache[cache_key] = self._FetchChangeDetail(issue)
223 return self.cache[cache_key]
224
225 def GetChangeDescription(self, issue, patchset=None):
226 """If patchset is none, fetches current patchset."""
227 info = self.GetChangeInfo(issue)
228 # info is a reference to cache. We'll modify it here adding description to
229 # it to the right patchset, if it is not yet there.
230
231 # Find revision info for the patchset we want.
232 if patchset is not None:
233 for rev, rev_info in info['revisions'].iteritems():
234 if str(rev_info['_number']) == str(patchset):
235 break
236 else:
237 raise Exception('patchset %s doesn\'t exist in issue %s' % (
238 patchset, issue))
239 else:
240 rev = info['current_revision']
241 rev_info = info['revisions'][rev]
242
243 # Updates revision info, which is part of cached issue info.
244 if 'real_description' not in rev_info:
245 rev_info['real_description'] = (
246 gerrit_util.GetChangeDescriptionFromGitiles(
247 rev_info['fetch']['http']['url'], rev))
248 return rev_info['real_description']
249
250 def GetChangeOwner(self, issue):
251 return self.GetChangeInfo(issue)['owner']['email']
252
253 def GetChangeReviewers(self, issue, approving_only=True):
agable565adb52016-07-22 14:48:07 -0700254 cr = self.GetChangeInfo(issue)['labels']['Code-Review']
255 max_value = max(int(k) for k in cr['values'].keys())
Aaron Gablef5644a92016-12-02 15:31:58 -0800256 return [r.get('email') for r in cr.get('all', [])
agable565adb52016-07-22 14:48:07 -0700257 if not approving_only or r.get('value', 0) == max_value]
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000258
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000259
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000260class OutputApi(object):
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000261 """An instance of OutputApi gets passed to presubmit scripts so that they
262 can output various types of results.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000263 """
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000264 PresubmitResult = _PresubmitResult
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000265 PresubmitError = _PresubmitError
266 PresubmitPromptWarning = _PresubmitPromptWarning
267 PresubmitNotifyResult = _PresubmitNotifyResult
268 MailTextResult = _MailTextResult
269
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000270 def __init__(self, is_committing):
271 self.is_committing = is_committing
272
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000273 def PresubmitPromptOrNotify(self, *args, **kwargs):
274 """Warn the user when uploading, but only notify if committing."""
275 if self.is_committing:
276 return self.PresubmitNotifyResult(*args, **kwargs)
277 return self.PresubmitPromptWarning(*args, **kwargs)
278
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000279
280class InputApi(object):
281 """An instance of this object is passed to presubmit scripts so they can
282 know stuff about the change they're looking at.
283 """
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000284 # Method could be a function
285 # pylint: disable=R0201
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000286
maruel@chromium.org3410d912009-06-09 20:56:16 +0000287 # File extensions that are considered source files from a style guide
288 # perspective. Don't modify this list from a presubmit script!
maruel@chromium.orgc33455a2011-06-24 19:14:18 +0000289 #
290 # Files without an extension aren't included in the list. If you want to
291 # filter them as source files, add r"(^|.*?[\\\/])[^.]+$" to the white list.
292 # Note that ALL CAPS files are black listed in DEFAULT_BLACK_LIST below.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000293 DEFAULT_WHITE_LIST = (
294 # C++ and friends
maruel@chromium.orgfe1211a2011-05-28 18:54:17 +0000295 r".+\.c$", r".+\.cc$", r".+\.cpp$", r".+\.h$", r".+\.m$", r".+\.mm$",
296 r".+\.inl$", r".+\.asm$", r".+\.hxx$", r".+\.hpp$", r".+\.s$", r".+\.S$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000297 # Scripts
maruel@chromium.orgfe1211a2011-05-28 18:54:17 +0000298 r".+\.js$", r".+\.py$", r".+\.sh$", r".+\.rb$", r".+\.pl$", r".+\.pm$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000299 # Other
estade@chromium.orgae7af922012-01-27 14:51:13 +0000300 r".+\.java$", r".+\.mk$", r".+\.am$", r".+\.css$"
maruel@chromium.org3410d912009-06-09 20:56:16 +0000301 )
302
303 # Path regexp that should be excluded from being considered containing source
304 # files. Don't modify this list from a presubmit script!
305 DEFAULT_BLACK_LIST = (
gavinp@chromium.org656326d2012-08-13 00:43:57 +0000306 r"testing_support[\\\/]google_appengine[\\\/].*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000307 r".*\bexperimental[\\\/].*",
primiano@chromium.orgb9658c32015-10-06 10:50:13 +0000308 # Exclude third_party/.* but NOT third_party/WebKit (crbug.com/539768).
309 r".*\bthird_party[\\\/](?!WebKit[\\\/]).*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000310 # Output directories (just in case)
311 r".*\bDebug[\\\/].*",
312 r".*\bRelease[\\\/].*",
313 r".*\bxcodebuild[\\\/].*",
thakis@chromium.orgc1c96352013-10-09 19:50:27 +0000314 r".*\bout[\\\/].*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000315 # All caps files like README and LICENCE.
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000316 r".*\b[A-Z0-9_]{2,}$",
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000317 # SCM (can happen in dual SCM configuration). (Slightly over aggressive)
maruel@chromium.org5d0dc432011-01-03 02:40:37 +0000318 r"(|.*[\\\/])\.git[\\\/].*",
319 r"(|.*[\\\/])\.svn[\\\/].*",
maruel@chromium.org7ccb4bb2011-11-07 20:26:20 +0000320 # There is no point in processing a patch file.
321 r".+\.diff$",
322 r".+\.patch$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000323 )
324
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000325 def __init__(self, change, presubmit_path, is_committing,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000326 rietveld_obj, verbose, gerrit_obj=None, dry_run=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000327 """Builds an InputApi object.
328
329 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000330 change: A presubmit.Change object.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000331 presubmit_path: The path to the presubmit script being processed.
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000332 is_committing: True if the change is about to be committed.
maruel@chromium.org239f4112011-06-03 20:08:23 +0000333 rietveld_obj: rietveld.Rietveld client object
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000334 gerrit_obj: provides basic Gerrit codereview functionality.
335 dry_run: if true, some Checks will be skipped.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000336 """
maruel@chromium.org9711bba2009-05-22 23:51:39 +0000337 # Version number of the presubmit_support script.
338 self.version = [int(x) for x in __version__.split('.')]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000339 self.change = change
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000340 self.is_committing = is_committing
maruel@chromium.org239f4112011-06-03 20:08:23 +0000341 self.rietveld = rietveld_obj
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000342 self.gerrit = gerrit_obj
tandrii@chromium.org57bafac2016-04-28 05:09:03 +0000343 self.dry_run = dry_run
maruel@chromium.orgcab38e92011-04-09 00:30:51 +0000344 # TBD
345 self.host_url = 'http://codereview.chromium.org'
346 if self.rietveld:
maruel@chromium.org239f4112011-06-03 20:08:23 +0000347 self.host_url = self.rietveld.url
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000348
349 # We expose various modules and functions as attributes of the input_api
350 # so that presubmit scripts don't have to import them.
351 self.basename = os.path.basename
352 self.cPickle = cPickle
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000353 self.cpplint = cpplint
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000354 self.cStringIO = cStringIO
dcheng091b7db2016-06-16 01:27:51 -0700355 self.fnmatch = fnmatch
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000356 self.glob = glob.glob
maruel@chromium.orgfb11c7b2010-03-18 18:22:14 +0000357 self.json = json
maruel@chromium.org6fba34d2011-06-02 13:45:12 +0000358 self.logging = logging.getLogger('PRESUBMIT')
maruel@chromium.org2b5ce562011-03-31 16:15:44 +0000359 self.os_listdir = os.listdir
360 self.os_walk = os.walk
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000361 self.os_path = os.path
pgervais@chromium.orgbd0cace2014-10-02 23:23:46 +0000362 self.os_stat = os.stat
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000363 self.pickle = pickle
364 self.marshal = marshal
365 self.re = re
366 self.subprocess = subprocess
367 self.tempfile = tempfile
dpranke@chromium.org0d1bdea2011-03-24 22:54:38 +0000368 self.time = time
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000369 self.traceback = traceback
maruel@chromium.org1487d532009-06-06 00:22:57 +0000370 self.unittest = unittest
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000371 self.urllib2 = urllib2
372
maruel@chromium.orgc0b22972009-06-25 16:19:14 +0000373 # To easily fork python.
374 self.python_executable = sys.executable
375 self.environ = os.environ
376
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000377 # InputApi.platform is the platform you're currently running on.
378 self.platform = sys.platform
379
iannucci@chromium.org0af3bb32015-06-12 20:44:35 +0000380 self.cpu_count = multiprocessing.cpu_count()
381
iannucci@chromium.orgd61a4952015-07-01 23:21:26 +0000382 # this is done here because in RunTests, the current working directory has
383 # changed, which causes Pool() to explode fantastically when run on windows
384 # (because it tries to load the __main__ module, which imports lots of
385 # things relative to the current working directory).
386 self._run_tests_pool = multiprocessing.Pool(self.cpu_count)
387
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000388 # The local path of the currently-being-processed presubmit script.
maruel@chromium.org3d235242009-05-15 12:40:48 +0000389 self._current_presubmit_path = os.path.dirname(presubmit_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000390
391 # We carry the canned checks so presubmit scripts can easily use them.
392 self.canned_checks = presubmit_canned_checks
393
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000394 # TODO(dpranke): figure out a list of all approved owners for a repo
395 # in order to be able to handle wildcard OWNERS files?
396 self.owners_db = owners.Database(change.RepositoryRoot(),
dtu944b6052016-07-14 14:48:21 -0700397 fopen=file, os_path=self.os_path)
maruel@chromium.org899e1c12011-04-07 17:03:18 +0000398 self.verbose = verbose
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000399 self.Command = CommandData
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000400
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000401 # Replace <hash_map> and <hash_set> as headers that need to be included
danakj@chromium.org18278522013-06-11 22:42:32 +0000402 # with "base/containers/hash_tables.h" instead.
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000403 # Access to a protected member _XX of a client class
404 # pylint: disable=W0212
405 self.cpplint._re_pattern_templates = [
danakj@chromium.org18278522013-06-11 22:42:32 +0000406 (a, b, 'base/containers/hash_tables.h')
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000407 if header in ('<hash_map>', '<hash_set>') else (a, b, header)
408 for (a, b, header) in cpplint._re_pattern_templates
409 ]
410
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000411 def PresubmitLocalPath(self):
412 """Returns the local path of the presubmit script currently being run.
413
414 This is useful if you don't want to hard-code absolute paths in the
415 presubmit script. For example, It can be used to find another file
416 relative to the PRESUBMIT.py script, so the whole tree can be branched and
417 the presubmit script still works, without editing its content.
418 """
maruel@chromium.org3d235242009-05-15 12:40:48 +0000419 return self._current_presubmit_path
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000420
agable0b65e732016-11-22 09:25:46 -0800421 def AffectedFiles(self, include_deletes=True, file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000422 """Same as input_api.change.AffectedFiles() except only lists files
423 (and optionally directories) in the same directory as the current presubmit
424 script, or subdirectories thereof.
425 """
maruel@chromium.org3d235242009-05-15 12:40:48 +0000426 dir_with_slash = normpath("%s/" % self.PresubmitLocalPath())
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000427 if len(dir_with_slash) == 1:
428 dir_with_slash = ''
sail@chromium.org5538e022011-05-12 17:53:16 +0000429
maruel@chromium.org4661e0c2009-06-04 00:45:26 +0000430 return filter(
431 lambda x: normpath(x.AbsoluteLocalPath()).startswith(dir_with_slash),
agable0b65e732016-11-22 09:25:46 -0800432 self.change.AffectedFiles(include_deletes, file_filter))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000433
agable0b65e732016-11-22 09:25:46 -0800434 def LocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000435 """Returns local paths of input_api.AffectedFiles()."""
agable0b65e732016-11-22 09:25:46 -0800436 paths = [af.LocalPath() for af in self.AffectedFiles()]
pgervais@chromium.org2f64f782014-04-25 00:12:33 +0000437 logging.debug("LocalPaths: %s", paths)
438 return paths
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000439
agable0b65e732016-11-22 09:25:46 -0800440 def AbsoluteLocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000441 """Returns absolute local paths of input_api.AffectedFiles()."""
agable0b65e732016-11-22 09:25:46 -0800442 return [af.AbsoluteLocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000443
agable0b65e732016-11-22 09:25:46 -0800444 def AffectedTestableFiles(self, include_deletes=None):
445 """Same as input_api.change.AffectedTestableFiles() except only lists files
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000446 in the same directory as the current presubmit script, or subdirectories
447 thereof.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000448 """
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000449 if include_deletes is not None:
agable0b65e732016-11-22 09:25:46 -0800450 warn("AffectedTestableFiles(include_deletes=%s)"
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000451 " is deprecated and ignored" % str(include_deletes),
452 category=DeprecationWarning,
453 stacklevel=2)
agable0b65e732016-11-22 09:25:46 -0800454 return filter(lambda x: x.IsTestableFile(),
455 self.AffectedFiles(include_deletes=False))
456
457 def AffectedTextFiles(self, include_deletes=None):
458 """An alias to AffectedTestableFiles for backwards compatibility."""
459 return self.AffectedTestableFiles(include_deletes=include_deletes)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000460
maruel@chromium.org3410d912009-06-09 20:56:16 +0000461 def FilterSourceFile(self, affected_file, white_list=None, black_list=None):
462 """Filters out files that aren't considered "source file".
463
464 If white_list or black_list is None, InputApi.DEFAULT_WHITE_LIST
465 and InputApi.DEFAULT_BLACK_LIST is used respectively.
466
467 The lists will be compiled as regular expression and
468 AffectedFile.LocalPath() needs to pass both list.
469
470 Note: Copy-paste this function to suit your needs or use a lambda function.
471 """
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000472 def Find(affected_file, items):
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000473 local_path = affected_file.LocalPath()
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000474 for item in items:
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000475 if self.re.match(item, local_path):
maruel@chromium.org3410d912009-06-09 20:56:16 +0000476 return True
477 return False
478 return (Find(affected_file, white_list or self.DEFAULT_WHITE_LIST) and
479 not Find(affected_file, black_list or self.DEFAULT_BLACK_LIST))
480
481 def AffectedSourceFiles(self, source_file):
agable0b65e732016-11-22 09:25:46 -0800482 """Filter the list of AffectedTestableFiles by the function source_file.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000483
484 If source_file is None, InputApi.FilterSourceFile() is used.
485 """
486 if not source_file:
487 source_file = self.FilterSourceFile
agable0b65e732016-11-22 09:25:46 -0800488 return filter(source_file, self.AffectedTestableFiles())
maruel@chromium.org3410d912009-06-09 20:56:16 +0000489
490 def RightHandSideLines(self, source_file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000491 """An iterator over all text lines in "new" version of changed files.
492
493 Only lists lines from new or modified text files in the change that are
494 contained by the directory of the currently executing presubmit script.
495
496 This is useful for doing line-by-line regex checks, like checking for
497 trailing whitespace.
498
499 Yields:
500 a 3 tuple:
501 the AffectedFile instance of the current file;
502 integer line number (1-based); and
503 the contents of the line as a string.
maruel@chromium.org1487d532009-06-06 00:22:57 +0000504
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000505 Note: The carriage return (LF or CR) is stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000506 """
maruel@chromium.org3410d912009-06-09 20:56:16 +0000507 files = self.AffectedSourceFiles(source_file_filter)
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000508 return _RightHandSideLinesImpl(files)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000509
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000510 def ReadFile(self, file_item, mode='r'):
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000511 """Reads an arbitrary file.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000512
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000513 Deny reading anything outside the repository.
514 """
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000515 if isinstance(file_item, AffectedFile):
516 file_item = file_item.AbsoluteLocalPath()
517 if not file_item.startswith(self.change.RepositoryRoot()):
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000518 raise IOError('Access outside the repository root is denied.')
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000519 return gclient_utils.FileRead(file_item, mode)
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000520
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000521 @property
522 def tbr(self):
523 """Returns if a change is TBR'ed."""
524 return 'TBR' in self.change.tags
525
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +0000526 def RunTests(self, tests_mix, parallel=True):
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000527 tests = []
528 msgs = []
529 for t in tests_mix:
530 if isinstance(t, OutputApi.PresubmitResult):
531 msgs.append(t)
532 else:
533 assert issubclass(t.message, _PresubmitResult)
534 tests.append(t)
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +0000535 if self.verbose:
536 t.info = _PresubmitNotifyResult
ilevy@chromium.org5678d332013-05-18 01:34:14 +0000537 if len(tests) > 1 and parallel:
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000538 # async recipe works around multiprocessing bug handling Ctrl-C
iannucci@chromium.orgd61a4952015-07-01 23:21:26 +0000539 msgs.extend(self._run_tests_pool.map_async(CallCommand, tests).get(99999))
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000540 else:
541 msgs.extend(map(CallCommand, tests))
542 return [m for m in msgs if m]
543
scottmg86099d72016-09-01 09:16:51 -0700544 def ShutdownPool(self):
545 self._run_tests_pool.close()
546 self._run_tests_pool.join()
547 self._run_tests_pool = None
548
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000549
nick@chromium.orgff526192013-06-10 19:30:26 +0000550class _DiffCache(object):
551 """Caches diffs retrieved from a particular SCM."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000552 def __init__(self, upstream=None):
553 """Stores the upstream revision against which all diffs will be computed."""
554 self._upstream = upstream
nick@chromium.orgff526192013-06-10 19:30:26 +0000555
556 def GetDiff(self, path, local_root):
557 """Get the diff for a particular path."""
558 raise NotImplementedError()
559
560
nick@chromium.orgff526192013-06-10 19:30:26 +0000561class _GitDiffCache(_DiffCache):
562 """DiffCache implementation for git; gets all file diffs at once."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000563 def __init__(self, upstream):
564 super(_GitDiffCache, self).__init__(upstream=upstream)
nick@chromium.orgff526192013-06-10 19:30:26 +0000565 self._diffs_by_file = None
566
567 def GetDiff(self, path, local_root):
568 if not self._diffs_by_file:
569 # Compute a single diff for all files and parse the output; should
570 # with git this is much faster than computing one diff for each file.
571 diffs = {}
572
573 # Don't specify any filenames below, because there are command line length
574 # limits on some platforms and GenerateDiff would fail.
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000575 unified_diff = scm.GIT.GenerateDiff(local_root, files=[], full_move=True,
576 branch=self._upstream)
nick@chromium.orgff526192013-06-10 19:30:26 +0000577
578 # This regex matches the path twice, separated by a space. Note that
579 # filename itself may contain spaces.
580 file_marker = re.compile('^diff --git (?P<filename>.*) (?P=filename)$')
581 current_diff = []
582 keep_line_endings = True
583 for x in unified_diff.splitlines(keep_line_endings):
584 match = file_marker.match(x)
585 if match:
586 # Marks the start of a new per-file section.
587 diffs[match.group('filename')] = current_diff = [x]
588 elif x.startswith('diff --git'):
589 raise PresubmitFailure('Unexpected diff line: %s' % x)
590 else:
591 current_diff.append(x)
592
593 self._diffs_by_file = dict(
594 (normpath(path), ''.join(diff)) for path, diff in diffs.items())
595
596 if path not in self._diffs_by_file:
597 raise PresubmitFailure(
598 'Unified diff did not contain entry for file %s' % path)
599
600 return self._diffs_by_file[path]
601
602
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000603class AffectedFile(object):
604 """Representation of a file in a change."""
nick@chromium.orgff526192013-06-10 19:30:26 +0000605
606 DIFF_CACHE = _DiffCache
607
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000608 # Method could be a function
609 # pylint: disable=R0201
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000610 def __init__(self, path, action, repository_root, diff_cache):
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000611 self._path = path
612 self._action = action
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000613 self._local_root = repository_root
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000614 self._is_directory = None
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000615 self._cached_changed_contents = None
616 self._cached_new_contents = None
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000617 self._diff_cache = diff_cache
tobiasjs2836bcf2016-08-16 04:08:16 -0700618 logging.debug('%s(%s)', self.__class__.__name__, self._path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000619
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000620 def LocalPath(self):
621 """Returns the path of this file on the local disk relative to client root.
622 """
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000623 return normpath(self._path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000624
625 def AbsoluteLocalPath(self):
626 """Returns the absolute path of this file on the local disk.
627 """
chase@chromium.org8e416c82009-10-06 04:30:44 +0000628 return os.path.abspath(os.path.join(self._local_root, self.LocalPath()))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000629
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000630 def Action(self):
631 """Returns the action on this opened file, e.g. A, M, D, etc."""
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000632 # TODO(maruel): Somewhat crappy, Could be "A" or "A +" for svn but
633 # different for other SCM.
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000634 return self._action
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000635
agable0b65e732016-11-22 09:25:46 -0800636 def IsTestableFile(self):
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000637 """Returns True if the file is a text file and not a binary file.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000638
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000639 Deleted files are not text file."""
maruel@chromium.org1e08c002009-05-28 19:09:33 +0000640 raise NotImplementedError() # Implement when needed
641
agable0b65e732016-11-22 09:25:46 -0800642 def IsTextFile(self):
643 """An alias to IsTestableFile for backwards compatibility."""
644 return self.IsTestableFile()
645
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000646 def NewContents(self):
647 """Returns an iterator over the lines in the new version of file.
648
649 The new version is the file in the user's workspace, i.e. the "right hand
650 side".
651
652 Contents will be empty if the file is a directory or does not exist.
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000653 Note: The carriage returns (LF or CR) are stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000654 """
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000655 if self._cached_new_contents is None:
656 self._cached_new_contents = []
agable0b65e732016-11-22 09:25:46 -0800657 try:
658 self._cached_new_contents = gclient_utils.FileRead(
659 self.AbsoluteLocalPath(), 'rU').splitlines()
660 except IOError:
661 pass # File not found? That's fine; maybe it was deleted.
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000662 return self._cached_new_contents[:]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000663
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000664 def ChangedContents(self):
665 """Returns a list of tuples (line number, line text) of all new lines.
666
667 This relies on the scm diff output describing each changed code section
668 with a line of the form
669
670 ^@@ <old line num>,<old size> <new line num>,<new size> @@$
671 """
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000672 if self._cached_changed_contents is not None:
673 return self._cached_changed_contents[:]
674 self._cached_changed_contents = []
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000675 line_num = 0
676
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000677 for line in self.GenerateScmDiff().splitlines():
678 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
679 if m:
680 line_num = int(m.groups(1)[0])
681 continue
682 if line.startswith('+') and not line.startswith('++'):
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000683 self._cached_changed_contents.append((line_num, line[1:]))
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000684 if not line.startswith('-'):
685 line_num += 1
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000686 return self._cached_changed_contents[:]
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000687
maruel@chromium.org5de13972009-06-10 18:16:06 +0000688 def __str__(self):
689 return self.LocalPath()
690
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000691 def GenerateScmDiff(self):
nick@chromium.orgff526192013-06-10 19:30:26 +0000692 return self._diff_cache.GetDiff(self.LocalPath(), self._local_root)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000693
maruel@chromium.org58407af2011-04-12 23:15:57 +0000694
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000695class GitAffectedFile(AffectedFile):
696 """Representation of a file in a change out of a git checkout."""
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000697 # Method 'NNN' is abstract in class 'NNN' but is not overridden
698 # pylint: disable=W0223
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000699
nick@chromium.orgff526192013-06-10 19:30:26 +0000700 DIFF_CACHE = _GitDiffCache
701
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000702 def __init__(self, *args, **kwargs):
703 AffectedFile.__init__(self, *args, **kwargs)
704 self._server_path = None
agable0b65e732016-11-22 09:25:46 -0800705 self._is_testable_file = None
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000706
agable0b65e732016-11-22 09:25:46 -0800707 def IsTestableFile(self):
708 if self._is_testable_file is None:
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000709 if self.Action() == 'D':
agable0b65e732016-11-22 09:25:46 -0800710 # A deleted file is not testable.
711 self._is_testable_file = False
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000712 else:
agable0b65e732016-11-22 09:25:46 -0800713 self._is_testable_file = os.path.isfile(self.AbsoluteLocalPath())
714 return self._is_testable_file
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000715
maruel@chromium.orgc1938752011-04-12 23:11:13 +0000716
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000717class Change(object):
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000718 """Describe a change.
719
720 Used directly by the presubmit scripts to query the current change being
721 tested.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000722
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000723 Instance members:
nick@chromium.orgff526192013-06-10 19:30:26 +0000724 tags: Dictionary of KEY=VALUE pairs found in the change description.
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000725 self.KEY: equivalent to tags['KEY']
726 """
727
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000728 _AFFECTED_FILES = AffectedFile
729
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000730 # Matches key/value (or "tag") lines in changelist descriptions.
maruel@chromium.org428342a2011-11-10 15:46:33 +0000731 TAG_LINE_RE = re.compile(
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +0000732 '^[ \t]*(?P<key>[A-Z][A-Z_0-9]*)[ \t]*=[ \t]*(?P<value>.*?)[ \t]*$')
maruel@chromium.orgc1938752011-04-12 23:11:13 +0000733 scm = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000734
maruel@chromium.org58407af2011-04-12 23:15:57 +0000735 def __init__(
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000736 self, name, description, local_root, files, issue, patchset, author,
737 upstream=None):
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000738 if files is None:
739 files = []
740 self._name = name
chase@chromium.org8e416c82009-10-06 04:30:44 +0000741 # Convert root into an absolute path.
742 self._local_root = os.path.abspath(local_root)
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000743 self._upstream = upstream
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000744 self.issue = issue
745 self.patchset = patchset
maruel@chromium.org58407af2011-04-12 23:15:57 +0000746 self.author_email = author
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000747
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000748 self._full_description = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000749 self.tags = {}
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000750 self._description_without_tags = ''
751 self.SetDescriptionText(description)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000752
maruel@chromium.orge085d812011-10-10 19:49:15 +0000753 assert all(
754 (isinstance(f, (list, tuple)) and len(f) == 2) for f in files), files
755
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000756 diff_cache = self._AFFECTED_FILES.DIFF_CACHE(self._upstream)
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000757 self._affected_files = [
nick@chromium.orgff526192013-06-10 19:30:26 +0000758 self._AFFECTED_FILES(path, action.strip(), self._local_root, diff_cache)
759 for action, path in files
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000760 ]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000761
maruel@chromium.org92022ec2009-06-11 01:59:28 +0000762 def Name(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000763 """Returns the change name."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000764 return self._name
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000765
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000766 def DescriptionText(self):
767 """Returns the user-entered changelist description, minus tags.
768
769 Any line in the user-provided description starting with e.g. "FOO="
770 (whitespace permitted before and around) is considered a tag line. Such
771 lines are stripped out of the description this function returns.
772 """
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000773 return self._description_without_tags
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000774
775 def FullDescriptionText(self):
776 """Returns the complete changelist description including tags."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000777 return self._full_description
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000778
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000779 def SetDescriptionText(self, description):
780 """Sets the full description text (including tags) to |description|.
pgervais@chromium.org92c30092014-04-15 00:30:37 +0000781
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000782 Also updates the list of tags."""
783 self._full_description = description
784
785 # From the description text, build up a dictionary of key/value pairs
786 # plus the description minus all key/value or "tag" lines.
787 description_without_tags = []
788 self.tags = {}
789 for line in self._full_description.splitlines():
790 m = self.TAG_LINE_RE.match(line)
791 if m:
792 self.tags[m.group('key')] = m.group('value')
793 else:
794 description_without_tags.append(line)
795
796 # Change back to text and remove whitespace at end.
797 self._description_without_tags = (
798 '\n'.join(description_without_tags).rstrip())
799
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000800 def RepositoryRoot(self):
maruel@chromium.org92022ec2009-06-11 01:59:28 +0000801 """Returns the repository (checkout) root directory for this change,
802 as an absolute path.
803 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000804 return self._local_root
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000805
806 def __getattr__(self, attr):
maruel@chromium.org92022ec2009-06-11 01:59:28 +0000807 """Return tags directly as attributes on the object."""
808 if not re.match(r"^[A-Z_]*$", attr):
809 raise AttributeError(self, attr)
maruel@chromium.orge1a524f2009-05-27 14:43:46 +0000810 return self.tags.get(attr)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000811
agable@chromium.org40a3d0b2014-05-15 01:59:16 +0000812 def AllFiles(self, root=None):
813 """List all files under source control in the repo."""
814 raise NotImplementedError()
815
agable0b65e732016-11-22 09:25:46 -0800816 def AffectedFiles(self, include_deletes=True, file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000817 """Returns a list of AffectedFile instances for all files in the change.
818
819 Args:
820 include_deletes: If false, deleted files will be filtered out.
sail@chromium.org5538e022011-05-12 17:53:16 +0000821 file_filter: An additional filter to apply.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000822
823 Returns:
824 [AffectedFile(path, action), AffectedFile(path, action)]
825 """
agable0b65e732016-11-22 09:25:46 -0800826 affected = filter(file_filter, self._affected_files)
sail@chromium.org5538e022011-05-12 17:53:16 +0000827
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000828 if include_deletes:
829 return affected
830 else:
831 return filter(lambda x: x.Action() != 'D', affected)
832
agable0b65e732016-11-22 09:25:46 -0800833 def AffectedTestableFiles(self, include_deletes=None):
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000834 """Return a list of the existing text files in a change."""
835 if include_deletes is not None:
agable0b65e732016-11-22 09:25:46 -0800836 warn("AffectedTeestableFiles(include_deletes=%s)"
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000837 " is deprecated and ignored" % str(include_deletes),
838 category=DeprecationWarning,
839 stacklevel=2)
agable0b65e732016-11-22 09:25:46 -0800840 return filter(lambda x: x.IsTestableFile(),
841 self.AffectedFiles(include_deletes=False))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000842
agable0b65e732016-11-22 09:25:46 -0800843 def AffectedTextFiles(self, include_deletes=None):
844 """An alias to AffectedTestableFiles for backwards compatibility."""
845 return self.AffectedTestableFiles(include_deletes=include_deletes)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000846
agable0b65e732016-11-22 09:25:46 -0800847 def LocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000848 """Convenience function."""
agable0b65e732016-11-22 09:25:46 -0800849 return [af.LocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000850
agable0b65e732016-11-22 09:25:46 -0800851 def AbsoluteLocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000852 """Convenience function."""
agable0b65e732016-11-22 09:25:46 -0800853 return [af.AbsoluteLocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000854
855 def RightHandSideLines(self):
856 """An iterator over all text lines in "new" version of changed files.
857
858 Lists lines from new or modified text files in the change.
859
860 This is useful for doing line-by-line regex checks, like checking for
861 trailing whitespace.
862
863 Yields:
864 a 3 tuple:
865 the AffectedFile instance of the current file;
866 integer line number (1-based); and
867 the contents of the line as a string.
868 """
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000869 return _RightHandSideLinesImpl(
870 x for x in self.AffectedFiles(include_deletes=False)
agable0b65e732016-11-22 09:25:46 -0800871 if x.IsTestableFile())
agable@chromium.org40a3d0b2014-05-15 01:59:16 +0000872
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000873
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000874class GitChange(Change):
875 _AFFECTED_FILES = GitAffectedFile
maruel@chromium.orgc1938752011-04-12 23:11:13 +0000876 scm = 'git'
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000877
agable@chromium.org40a3d0b2014-05-15 01:59:16 +0000878 def AllFiles(self, root=None):
879 """List all files under source control in the repo."""
880 root = root or self.RepositoryRoot()
881 return subprocess.check_output(
882 ['git', 'ls-files', '--', '.'], cwd=root).splitlines()
883
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000884
maruel@chromium.org4661e0c2009-06-04 00:45:26 +0000885def ListRelevantPresubmitFiles(files, root):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000886 """Finds all presubmit files that apply to a given set of source files.
887
maruel@chromium.orgb1901a62010-06-16 00:18:47 +0000888 If inherit-review-settings-ok is present right under root, looks for
889 PRESUBMIT.py in directories enclosing root.
890
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000891 Args:
892 files: An iterable container containing file paths.
maruel@chromium.org4661e0c2009-06-04 00:45:26 +0000893 root: Path where to stop searching.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000894
895 Return:
maruel@chromium.org4661e0c2009-06-04 00:45:26 +0000896 List of absolute paths of the existing PRESUBMIT.py scripts.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000897 """
maruel@chromium.orgb1901a62010-06-16 00:18:47 +0000898 files = [normpath(os.path.join(root, f)) for f in files]
899
900 # List all the individual directories containing files.
901 directories = set([os.path.dirname(f) for f in files])
902
903 # Ignore root if inherit-review-settings-ok is present.
904 if os.path.isfile(os.path.join(root, 'inherit-review-settings-ok')):
905 root = None
906
907 # Collect all unique directories that may contain PRESUBMIT.py.
908 candidates = set()
909 for directory in directories:
910 while True:
911 if directory in candidates:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000912 break
maruel@chromium.orgb1901a62010-06-16 00:18:47 +0000913 candidates.add(directory)
914 if directory == root:
maruel@chromium.org4661e0c2009-06-04 00:45:26 +0000915 break
maruel@chromium.orgb1901a62010-06-16 00:18:47 +0000916 parent_dir = os.path.dirname(directory)
917 if parent_dir == directory:
918 # We hit the system root directory.
919 break
920 directory = parent_dir
921
922 # Look for PRESUBMIT.py in all candidate directories.
923 results = []
924 for directory in sorted(list(candidates)):
tobiasjsff061c02016-08-17 03:23:57 -0700925 try:
926 for f in os.listdir(directory):
927 p = os.path.join(directory, f)
928 if os.path.isfile(p) and re.match(
929 r'PRESUBMIT.*\.py$', f) and not f.startswith('PRESUBMIT_test'):
930 results.append(p)
931 except OSError:
932 pass
maruel@chromium.orgb1901a62010-06-16 00:18:47 +0000933
tobiasjs2836bcf2016-08-16 04:08:16 -0700934 logging.debug('Presubmit files: %s', ','.join(results))
maruel@chromium.orgb1901a62010-06-16 00:18:47 +0000935 return results
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000936
937
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +0000938class GetTryMastersExecuter(object):
939 @staticmethod
940 def ExecPresubmitScript(script_text, presubmit_path, project, change):
941 """Executes GetPreferredTryMasters() from a single presubmit script.
942
943 Args:
944 script_text: The text of the presubmit script.
945 presubmit_path: Project script to run.
946 project: Project name to pass to presubmit script for bot selection.
947
948 Return:
949 A map of try masters to map of builders to set of tests.
950 """
951 context = {}
952 try:
953 exec script_text in context
954 except Exception, e:
955 raise PresubmitFailure('"%s" had an exception.\n%s'
956 % (presubmit_path, e))
957
958 function_name = 'GetPreferredTryMasters'
959 if function_name not in context:
960 return {}
961 get_preferred_try_masters = context[function_name]
962 if not len(inspect.getargspec(get_preferred_try_masters)[0]) == 2:
963 raise PresubmitFailure(
964 'Expected function "GetPreferredTryMasters" to take two arguments.')
965 return get_preferred_try_masters(project, change)
966
967
rmistry@google.com5626a922015-02-26 14:03:30 +0000968class GetPostUploadExecuter(object):
969 @staticmethod
970 def ExecPresubmitScript(script_text, presubmit_path, cl, change):
971 """Executes PostUploadHook() from a single presubmit script.
972
973 Args:
974 script_text: The text of the presubmit script.
975 presubmit_path: Project script to run.
976 cl: The Changelist object.
977 change: The Change object.
978
979 Return:
980 A list of results objects.
981 """
982 context = {}
983 try:
984 exec script_text in context
985 except Exception, e:
986 raise PresubmitFailure('"%s" had an exception.\n%s'
987 % (presubmit_path, e))
988
989 function_name = 'PostUploadHook'
990 if function_name not in context:
991 return {}
992 post_upload_hook = context[function_name]
993 if not len(inspect.getargspec(post_upload_hook)[0]) == 3:
994 raise PresubmitFailure(
995 'Expected function "PostUploadHook" to take three arguments.')
996 return post_upload_hook(cl, change, OutputApi(False))
997
998
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +0000999def _MergeMasters(masters1, masters2):
1000 """Merges two master maps. Merges also the tests of each builder."""
1001 result = {}
1002 for (master, builders) in itertools.chain(masters1.iteritems(),
1003 masters2.iteritems()):
1004 new_builders = result.setdefault(master, {})
1005 for (builder, tests) in builders.iteritems():
1006 new_builders.setdefault(builder, set([])).update(tests)
1007 return result
1008
1009
1010def DoGetTryMasters(change,
1011 changed_files,
1012 repository_root,
1013 default_presubmit,
1014 project,
1015 verbose,
1016 output_stream):
1017 """Get the list of try masters from the presubmit scripts.
1018
1019 Args:
1020 changed_files: List of modified files.
1021 repository_root: The repository root.
1022 default_presubmit: A default presubmit script to execute in any case.
1023 project: Optional name of a project used in selecting trybots.
1024 verbose: Prints debug info.
1025 output_stream: A stream to write debug output to.
1026
1027 Return:
1028 Map of try masters to map of builders to set of tests.
1029 """
1030 presubmit_files = ListRelevantPresubmitFiles(changed_files, repository_root)
1031 if not presubmit_files and verbose:
1032 output_stream.write("Warning, no PRESUBMIT.py found.\n")
1033 results = {}
1034 executer = GetTryMastersExecuter()
1035
1036 if default_presubmit:
1037 if verbose:
1038 output_stream.write("Running default presubmit script.\n")
1039 fake_path = os.path.join(repository_root, 'PRESUBMIT.py')
1040 results = _MergeMasters(results, executer.ExecPresubmitScript(
1041 default_presubmit, fake_path, project, change))
1042 for filename in presubmit_files:
1043 filename = os.path.abspath(filename)
1044 if verbose:
1045 output_stream.write("Running %s\n" % filename)
1046 # Accept CRLF presubmit script.
1047 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1048 results = _MergeMasters(results, executer.ExecPresubmitScript(
1049 presubmit_script, filename, project, change))
1050
1051 # Make sets to lists again for later JSON serialization.
1052 for builders in results.itervalues():
1053 for builder in builders:
1054 builders[builder] = list(builders[builder])
1055
1056 if results and verbose:
1057 output_stream.write('%s\n' % str(results))
1058 return results
1059
1060
rmistry@google.com5626a922015-02-26 14:03:30 +00001061def DoPostUploadExecuter(change,
1062 cl,
1063 repository_root,
1064 verbose,
1065 output_stream):
1066 """Execute the post upload hook.
1067
1068 Args:
1069 change: The Change object.
1070 cl: The Changelist object.
1071 repository_root: The repository root.
1072 verbose: Prints debug info.
1073 output_stream: A stream to write debug output to.
1074 """
1075 presubmit_files = ListRelevantPresubmitFiles(
1076 change.LocalPaths(), repository_root)
1077 if not presubmit_files and verbose:
1078 output_stream.write("Warning, no PRESUBMIT.py found.\n")
1079 results = []
1080 executer = GetPostUploadExecuter()
1081 # The root presubmit file should be executed after the ones in subdirectories.
1082 # i.e. the specific post upload hooks should run before the general ones.
1083 # Thus, reverse the order provided by ListRelevantPresubmitFiles.
1084 presubmit_files.reverse()
1085
1086 for filename in presubmit_files:
1087 filename = os.path.abspath(filename)
1088 if verbose:
1089 output_stream.write("Running %s\n" % filename)
1090 # Accept CRLF presubmit script.
1091 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1092 results.extend(executer.ExecPresubmitScript(
1093 presubmit_script, filename, cl, change))
1094 output_stream.write('\n')
1095 if results:
1096 output_stream.write('** Post Upload Hook Messages **\n')
1097 for result in results:
1098 result.handle(output_stream)
1099 output_stream.write('\n')
1100
1101 return results
1102
1103
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001104class PresubmitExecuter(object):
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001105 def __init__(self, change, committing, rietveld_obj, verbose,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001106 gerrit_obj=None, dry_run=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001107 """
1108 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001109 change: The Change object.
agable92bec4f2016-08-24 09:27:27 -07001110 committing: True if 'git cl land' is running, False if 'git cl upload' is.
maruel@chromium.org239f4112011-06-03 20:08:23 +00001111 rietveld_obj: rietveld.Rietveld client object.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001112 gerrit_obj: provides basic Gerrit codereview functionality.
1113 dry_run: if true, some Checks will be skipped.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001114 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001115 self.change = change
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001116 self.committing = committing
maruel@chromium.org239f4112011-06-03 20:08:23 +00001117 self.rietveld = rietveld_obj
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001118 self.gerrit = gerrit_obj
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001119 self.verbose = verbose
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001120 self.dry_run = dry_run
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001121
1122 def ExecPresubmitScript(self, script_text, presubmit_path):
1123 """Executes a single presubmit script.
1124
1125 Args:
1126 script_text: The text of the presubmit script.
1127 presubmit_path: The path to the presubmit file (this will be reported via
1128 input_api.PresubmitLocalPath()).
1129
1130 Return:
1131 A list of result objects, empty if no problems.
1132 """
thakis@chromium.orgc6ef53a2014-11-04 00:13:54 +00001133
chase@chromium.org8e416c82009-10-06 04:30:44 +00001134 # Change to the presubmit file's directory to support local imports.
1135 main_path = os.getcwd()
1136 os.chdir(os.path.dirname(presubmit_path))
1137
1138 # Load the presubmit script into context.
dpranke@chromium.org970c5222011-03-12 00:32:24 +00001139 input_api = InputApi(self.change, presubmit_path, self.committing,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001140 self.rietveld, self.verbose,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001141 gerrit_obj=self.gerrit, dry_run=self.dry_run)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001142 context = {}
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001143 try:
1144 exec script_text in context
1145 except Exception, e:
1146 raise PresubmitFailure('"%s" had an exception.\n%s' % (presubmit_path, e))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001147
1148 # These function names must change if we make substantial changes to
1149 # the presubmit API that are not backwards compatible.
1150 if self.committing:
1151 function_name = 'CheckChangeOnCommit'
1152 else:
1153 function_name = 'CheckChangeOnUpload'
1154 if function_name in context:
wez@chromium.orga6d011e2013-03-26 17:31:49 +00001155 context['__args'] = (input_api, OutputApi(self.committing))
tobiasjs2836bcf2016-08-16 04:08:16 -07001156 logging.debug('Running %s in %s', function_name, presubmit_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001157 result = eval(function_name + '(*__args)', context)
tobiasjs2836bcf2016-08-16 04:08:16 -07001158 logging.debug('Running %s done.', function_name)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001159 if not (isinstance(result, types.TupleType) or
1160 isinstance(result, types.ListType)):
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001161 raise PresubmitFailure(
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001162 'Presubmit functions must return a tuple or list')
1163 for item in result:
1164 if not isinstance(item, OutputApi.PresubmitResult):
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001165 raise PresubmitFailure(
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001166 'All presubmit results must be of types derived from '
1167 'output_api.PresubmitResult')
1168 else:
1169 result = () # no error since the script doesn't care about current event.
1170
scottmg86099d72016-09-01 09:16:51 -07001171 input_api.ShutdownPool()
1172
chase@chromium.org8e416c82009-10-06 04:30:44 +00001173 # Return the process to the original working directory.
1174 os.chdir(main_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001175 return result
1176
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001177def DoPresubmitChecks(change,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001178 committing,
1179 verbose,
1180 output_stream,
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +00001181 input_stream,
maruel@chromium.orgb0dfd352009-06-10 14:12:54 +00001182 default_presubmit,
dpranke@chromium.org970c5222011-03-12 00:32:24 +00001183 may_prompt,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001184 rietveld_obj,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001185 gerrit_obj=None,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001186 dry_run=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001187 """Runs all presubmit checks that apply to the files in the change.
1188
1189 This finds all PRESUBMIT.py files in directories enclosing the files in the
1190 change (up to the repository root) and calls the relevant entrypoint function
1191 depending on whether the change is being committed or uploaded.
1192
1193 Prints errors, warnings and notifications. Prompts the user for warnings
1194 when needed.
1195
1196 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001197 change: The Change object.
agable92bec4f2016-08-24 09:27:27 -07001198 committing: True if 'git cl land' is running, False if 'git cl upload' is.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001199 verbose: Prints debug info.
1200 output_stream: A stream to write output from presubmit tests to.
1201 input_stream: A stream to read input from the user.
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +00001202 default_presubmit: A default presubmit script to execute in any case.
Quinten Yearsley516fe7f2016-12-14 11:50:18 -08001203 may_prompt: Enable (y/n) questions on warning or error. If False,
1204 any questions are answered with yes by default.
maruel@chromium.org239f4112011-06-03 20:08:23 +00001205 rietveld_obj: rietveld.Rietveld object.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001206 gerrit_obj: provides basic Gerrit codereview functionality.
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001207 dry_run: if true, some Checks will be skipped.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001208
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +00001209 Warning:
1210 If may_prompt is true, output_stream SHOULD be sys.stdout and input_stream
1211 SHOULD be sys.stdin.
1212
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001213 Return:
dpranke@chromium.org5ac21012011-03-16 02:58:25 +00001214 A PresubmitOutput object. Use output.should_continue() to figure out
1215 if there were errors or warnings and the caller should abort.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001216 """
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001217 old_environ = os.environ
1218 try:
1219 # Make sure python subprocesses won't generate .pyc files.
1220 os.environ = os.environ.copy()
1221 os.environ['PYTHONDONTWRITEBYTECODE'] = '1'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001222
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001223 output = PresubmitOutput(input_stream, output_stream)
1224 if committing:
1225 output.write("Running presubmit commit checks ...\n")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001226 else:
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001227 output.write("Running presubmit upload checks ...\n")
1228 start_time = time.time()
1229 presubmit_files = ListRelevantPresubmitFiles(
agable0b65e732016-11-22 09:25:46 -08001230 change.AbsoluteLocalPaths(), change.RepositoryRoot())
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001231 if not presubmit_files and verbose:
maruel@chromium.orgfae707b2011-09-15 18:57:58 +00001232 output.write("Warning, no PRESUBMIT.py found.\n")
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001233 results = []
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001234 executer = PresubmitExecuter(change, committing, rietveld_obj, verbose,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001235 gerrit_obj, dry_run)
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001236 if default_presubmit:
1237 if verbose:
1238 output.write("Running default presubmit script.\n")
1239 fake_path = os.path.join(change.RepositoryRoot(), 'PRESUBMIT.py')
1240 results += executer.ExecPresubmitScript(default_presubmit, fake_path)
1241 for filename in presubmit_files:
1242 filename = os.path.abspath(filename)
1243 if verbose:
1244 output.write("Running %s\n" % filename)
1245 # Accept CRLF presubmit script.
1246 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1247 results += executer.ExecPresubmitScript(presubmit_script, filename)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001248
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001249 errors = []
1250 notifications = []
1251 warnings = []
1252 for result in results:
1253 if result.fatal:
1254 errors.append(result)
1255 elif result.should_prompt:
1256 warnings.append(result)
1257 else:
1258 notifications.append(result)
pam@chromium.orged9a0832009-09-09 22:48:55 +00001259
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001260 output.write('\n')
1261 for name, items in (('Messages', notifications),
1262 ('Warnings', warnings),
1263 ('ERRORS', errors)):
1264 if items:
1265 output.write('** Presubmit %s **\n' % name)
1266 for item in items:
1267 item.handle(output)
1268 output.write('\n')
pam@chromium.orged9a0832009-09-09 22:48:55 +00001269
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001270 total_time = time.time() - start_time
1271 if total_time > 1.0:
1272 output.write("Presubmit checks took %.1fs to calculate.\n\n" % total_time)
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +00001273
Quinten Yearsley516fe7f2016-12-14 11:50:18 -08001274 if errors:
1275 output.fail()
1276 elif warnings:
1277 output.write('There were presubmit warnings. ')
1278 if may_prompt:
1279 output.prompt_yes_no('Are you sure you wish to continue? (y/N): ')
1280 else:
1281 output.write('Presubmit checks passed.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001282
1283 global _ASKED_FOR_FEEDBACK
1284 # Ask for feedback one time out of 5.
1285 if (len(results) and random.randint(0, 4) == 0 and not _ASKED_FOR_FEEDBACK):
maruel@chromium.org1ce8e662014-01-14 15:23:00 +00001286 output.write(
1287 'Was the presubmit check useful? If not, run "git cl presubmit -v"\n'
1288 'to figure out which PRESUBMIT.py was run, then run git blame\n'
1289 'on the file to figure out who to ask for help.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001290 _ASKED_FOR_FEEDBACK = True
1291 return output
1292 finally:
1293 os.environ = old_environ
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001294
1295
1296def ScanSubDirs(mask, recursive):
1297 if not recursive:
pgervais@chromium.orge57b09d2014-05-07 00:58:13 +00001298 return [x for x in glob.glob(mask) if x not in ('.svn', '.git')]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001299 else:
1300 results = []
1301 for root, dirs, files in os.walk('.'):
1302 if '.svn' in dirs:
1303 dirs.remove('.svn')
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001304 if '.git' in dirs:
1305 dirs.remove('.git')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001306 for name in files:
1307 if fnmatch.fnmatch(name, mask):
1308 results.append(os.path.join(root, name))
1309 return results
1310
1311
1312def ParseFiles(args, recursive):
tobiasjs2836bcf2016-08-16 04:08:16 -07001313 logging.debug('Searching for %s', args)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001314 files = []
1315 for arg in args:
maruel@chromium.orge3608df2009-11-10 20:22:57 +00001316 files.extend([('M', f) for f in ScanSubDirs(arg, recursive)])
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001317 return files
1318
1319
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001320def load_files(options, args):
1321 """Tries to determine the SCM."""
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001322 files = []
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001323 if args:
1324 files = ParseFiles(args, options.recursive)
agable0b65e732016-11-22 09:25:46 -08001325 change_scm = scm.determine_scm(options.root)
1326 if change_scm == 'git':
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001327 change_class = GitChange
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001328 upstream = options.upstream or None
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001329 if not files:
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001330 files = scm.GIT.CaptureStatus([], options.root, upstream)
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001331 else:
tobiasjs2836bcf2016-08-16 04:08:16 -07001332 logging.info('Doesn\'t seem under source control. Got %d files', len(args))
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001333 if not files:
1334 return None, None
1335 change_class = Change
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001336 return change_class, files
1337
1338
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001339class NonexistantCannedCheckFilter(Exception):
1340 pass
1341
1342
1343@contextlib.contextmanager
1344def canned_check_filter(method_names):
1345 filtered = {}
1346 try:
1347 for method_name in method_names:
1348 if not hasattr(presubmit_canned_checks, method_name):
1349 raise NonexistantCannedCheckFilter(method_name)
1350 filtered[method_name] = getattr(presubmit_canned_checks, method_name)
1351 setattr(presubmit_canned_checks, method_name, lambda *_a, **_kw: [])
1352 yield
1353 finally:
1354 for name, method in filtered.iteritems():
1355 setattr(presubmit_canned_checks, name, method)
1356
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001357
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001358def CallCommand(cmd_data):
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001359 """Runs an external program, potentially from a child process created by the
1360 multiprocessing module.
1361
1362 multiprocessing needs a top level function with a single argument.
1363 """
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001364 cmd_data.kwargs['stdout'] = subprocess.PIPE
1365 cmd_data.kwargs['stderr'] = subprocess.STDOUT
1366 try:
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001367 start = time.time()
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001368 (out, _), code = subprocess.communicate(cmd_data.cmd, **cmd_data.kwargs)
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001369 duration = time.time() - start
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001370 except OSError as e:
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001371 duration = time.time() - start
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001372 return cmd_data.message(
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001373 '%s exec failure (%4.2fs)\n %s' % (cmd_data.name, duration, e))
1374 if code != 0:
1375 return cmd_data.message(
1376 '%s (%4.2fs) failed\n%s' % (cmd_data.name, duration, out))
1377 if cmd_data.info:
1378 return cmd_data.info('%s (%4.2fs)' % (cmd_data.name, duration))
ilevy@chromium.orgbc117312013-04-20 03:57:56 +00001379
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001380
sbc@chromium.org013731e2015-02-26 18:28:43 +00001381def main(argv=None):
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001382 parser = optparse.OptionParser(usage="%prog [options] <files...>",
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001383 version="%prog " + str(__version__))
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001384 parser.add_option("-c", "--commit", action="store_true", default=False,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001385 help="Use commit instead of upload checks")
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001386 parser.add_option("-u", "--upload", action="store_false", dest='commit',
1387 help="Use upload instead of commit checks")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001388 parser.add_option("-r", "--recursive", action="store_true",
1389 help="Act recursively")
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001390 parser.add_option("-v", "--verbose", action="count", default=0,
1391 help="Use 2 times for more debug info")
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001392 parser.add_option("--name", default='no name')
maruel@chromium.org58407af2011-04-12 23:15:57 +00001393 parser.add_option("--author")
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001394 parser.add_option("--description", default='')
1395 parser.add_option("--issue", type='int', default=0)
1396 parser.add_option("--patchset", type='int', default=0)
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001397 parser.add_option("--root", default=os.getcwd(),
1398 help="Search for PRESUBMIT.py up to this directory. "
1399 "If inherit-review-settings-ok is present in this "
1400 "directory, parent directories up to the root file "
1401 "system directories will also be searched.")
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001402 parser.add_option("--upstream",
1403 help="Git only: the base ref or upstream branch against "
1404 "which the diff should be computed.")
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001405 parser.add_option("--default_presubmit")
1406 parser.add_option("--may_prompt", action='store_true', default=False)
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001407 parser.add_option("--skip_canned", action='append', default=[],
1408 help="A list of checks to skip which appear in "
1409 "presubmit_canned_checks. Can be provided multiple times "
1410 "to skip multiple canned checks.")
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001411 parser.add_option("--dry_run", action='store_true',
1412 help=optparse.SUPPRESS_HELP)
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001413 parser.add_option("--gerrit_url", help=optparse.SUPPRESS_HELP)
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001414 parser.add_option("--gerrit_fetch", action='store_true',
1415 help=optparse.SUPPRESS_HELP)
maruel@chromium.org239f4112011-06-03 20:08:23 +00001416 parser.add_option("--rietveld_url", help=optparse.SUPPRESS_HELP)
1417 parser.add_option("--rietveld_email", help=optparse.SUPPRESS_HELP)
iannucci@chromium.org720fd7a2013-04-24 04:13:50 +00001418 parser.add_option("--rietveld_fetch", action='store_true', default=False,
1419 help=optparse.SUPPRESS_HELP)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001420 # These are for OAuth2 authentication for bots. See also apply_issue.py
1421 parser.add_option("--rietveld_email_file", help=optparse.SUPPRESS_HELP)
1422 parser.add_option("--rietveld_private_key_file", help=optparse.SUPPRESS_HELP)
1423
phajdan.jr@chromium.org2ff30182016-03-23 09:52:51 +00001424 # TODO(phajdan.jr): Update callers and remove obsolete --trybot-json .
stip@chromium.orgf7d31f52014-01-03 20:14:46 +00001425 parser.add_option("--trybot-json",
1426 help="Output trybot information to the file specified.")
vadimsh@chromium.orgcf6a5d22015-04-09 22:02:00 +00001427 auth.add_auth_options(parser)
maruel@chromium.org82e5f282011-03-17 14:08:55 +00001428 options, args = parser.parse_args(argv)
vadimsh@chromium.orgcf6a5d22015-04-09 22:02:00 +00001429 auth_config = auth.extract_auth_config_from_options(options)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001430
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001431 if options.verbose >= 2:
maruel@chromium.org7444c502011-02-09 14:02:11 +00001432 logging.basicConfig(level=logging.DEBUG)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001433 elif options.verbose:
1434 logging.basicConfig(level=logging.INFO)
1435 else:
1436 logging.basicConfig(level=logging.ERROR)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001437
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001438 if (any((options.rietveld_url, options.rietveld_email_file,
1439 options.rietveld_fetch, options.rietveld_private_key_file))
1440 and any((options.gerrit_url, options.gerrit_fetch))):
1441 parser.error('Options for only codereview --rietveld_* or --gerrit_* '
1442 'allowed')
1443
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001444 if options.rietveld_email and options.rietveld_email_file:
1445 parser.error("Only one of --rietveld_email or --rietveld_email_file "
1446 "can be passed to this program.")
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001447 if options.rietveld_email_file:
1448 with open(options.rietveld_email_file, "rb") as f:
1449 options.rietveld_email = f.read().strip()
1450
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001451 change_class, files = load_files(options, args)
1452 if not change_class:
1453 parser.error('For unversioned directory, <files> is not optional.')
tobiasjs2836bcf2016-08-16 04:08:16 -07001454 logging.info('Found %d file(s).', len(files))
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001455
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001456 rietveld_obj, gerrit_obj = None, None
1457
maruel@chromium.org239f4112011-06-03 20:08:23 +00001458 if options.rietveld_url:
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001459 # The empty password is permitted: '' is not None.
djacques@chromium.org7b654f52014-04-15 04:02:32 +00001460 if options.rietveld_private_key_file:
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001461 rietveld_obj = rietveld.JwtOAuth2Rietveld(
1462 options.rietveld_url,
1463 options.rietveld_email,
1464 options.rietveld_private_key_file)
1465 else:
djacques@chromium.org7b654f52014-04-15 04:02:32 +00001466 rietveld_obj = rietveld.CachingRietveld(
1467 options.rietveld_url,
vadimsh@chromium.orgcf6a5d22015-04-09 22:02:00 +00001468 auth_config,
1469 options.rietveld_email)
iannucci@chromium.org720fd7a2013-04-24 04:13:50 +00001470 if options.rietveld_fetch:
1471 assert options.issue
1472 props = rietveld_obj.get_issue_properties(options.issue, False)
1473 options.author = props['owner_email']
1474 options.description = props['description']
1475 logging.info('Got author: "%s"', options.author)
1476 logging.info('Got description: """\n%s\n"""', options.description)
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001477
1478 if options.gerrit_url and options.gerrit_fetch:
tandrii@chromium.org83b1b232016-04-29 16:33:19 +00001479 assert options.issue and options.patchset
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001480 rietveld_obj = None
1481 gerrit_obj = GerritAccessor(urlparse.urlparse(options.gerrit_url).netloc)
1482 options.author = gerrit_obj.GetChangeOwner(options.issue)
1483 options.description = gerrit_obj.GetChangeDescription(options.issue,
1484 options.patchset)
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001485 logging.info('Got author: "%s"', options.author)
1486 logging.info('Got description: """\n%s\n"""', options.description)
1487
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001488 try:
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001489 with canned_check_filter(options.skip_canned):
1490 results = DoPresubmitChecks(
1491 change_class(options.name,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001492 options.description,
1493 options.root,
1494 files,
1495 options.issue,
1496 options.patchset,
1497 options.author,
1498 upstream=options.upstream),
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001499 options.commit,
1500 options.verbose,
1501 sys.stdout,
1502 sys.stdin,
1503 options.default_presubmit,
1504 options.may_prompt,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001505 rietveld_obj,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001506 gerrit_obj,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001507 options.dry_run)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001508 return not results.should_continue()
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001509 except NonexistantCannedCheckFilter, e:
1510 print >> sys.stderr, (
1511 'Attempted to skip nonexistent canned presubmit check: %s' % e.message)
1512 return 2
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001513 except PresubmitFailure, e:
1514 print >> sys.stderr, e
1515 print >> sys.stderr, 'Maybe your depot_tools is out of date?'
1516 print >> sys.stderr, 'If all fails, contact maruel@'
1517 return 2
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001518
1519
1520if __name__ == '__main__':
maruel@chromium.org35625c72011-03-23 17:34:02 +00001521 fix_encoding.fix_encoding()
sbc@chromium.org013731e2015-02-26 18:28:43 +00001522 try:
1523 sys.exit(main())
1524 except KeyboardInterrupt:
1525 sys.stderr.write('interrupted\n')
sergiybf8a3b382016-07-05 11:21:30 -07001526 sys.exit(2)