blob: f0f9ed910ee816df79e5b81bc478fbff5615379d [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
Raul Tambre80ee78e2019-05-06 22:41:05 +00009from __future__ import print_function
10
stip@chromium.orgf7d31f52014-01-03 20:14:46 +000011__version__ = '1.8.0'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000012
13# TODO(joi) Add caching where appropriate/needed. The API is designed to allow
14# caching (between all different invocations of presubmit scripts for a given
15# change). We should add it as our presubmit scripts start feeling slow.
16
Takeshi Yoshino07a6bea2017-08-02 02:44:06 +090017import ast # Exposed through the API.
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +000018import contextlib
Yoshisato Yanagisawa406de132018-06-29 05:43:25 +000019import cPickle # Exposed through the API.
20import cpplint
21import cStringIO # Exposed through the API.
dcheng091b7db2016-06-16 01:27:51 -070022import fnmatch # Exposed through the API.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000023import glob
asvitkine@chromium.org15169952011-09-27 14:30:53 +000024import inspect
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +000025import itertools
maruel@chromium.org4f6852c2012-04-20 20:39:20 +000026import json # Exposed through the API.
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +000027import logging
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000028import marshal # Exposed through the API.
ilevy@chromium.orgbc117312013-04-20 03:57:56 +000029import multiprocessing
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000030import optparse
31import os # Somewhat exposed through the API.
32import pickle # Exposed through the API.
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +000033import random
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000034import re # Exposed through the API.
Edward Lesmes8e282792018-04-03 18:50:29 -040035import signal
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000036import sys # Parts exposed through API.
37import tempfile # Exposed through the API.
Edward Lesmes8e282792018-04-03 18:50:29 -040038import threading
jam@chromium.org2a891dc2009-08-20 20:33:37 +000039import time
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +000040import traceback # Exposed through the API.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000041import types
maruel@chromium.org1487d532009-06-06 00:22:57 +000042import unittest # Exposed through the API.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000043import urllib2 # Exposed through the API.
tandrii@chromium.org015ebae2016-04-25 19:37:22 +000044import urlparse
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +000045from warnings import warn
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000046
47# Local imports.
maruel@chromium.org35625c72011-03-23 17:34:02 +000048import fix_encoding
Yoshisato Yanagisawa04600b42019-03-15 03:03:41 +000049import gclient_paths # Exposed through the API
50import gclient_utils
Aaron Gableb584c4f2017-04-26 16:28:08 -070051import git_footers
tandrii@chromium.org015ebae2016-04-25 19:37:22 +000052import gerrit_util
dpranke@chromium.org2a009622011-03-01 02:43:31 +000053import owners
Jochen Eisinger76f5fc62017-04-07 16:27:46 +020054import owners_finder
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000055import presubmit_canned_checks
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +000056import scm
maruel@chromium.org84f4fe32011-04-06 13:26:45 +000057import subprocess2 as subprocess # Exposed through the API.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000058
59
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +000060# Ask for feedback only once in program lifetime.
61_ASKED_FOR_FEEDBACK = False
62
63
maruel@chromium.org899e1c12011-04-07 17:03:18 +000064class PresubmitFailure(Exception):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000065 pass
66
67
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +000068class CommandData(object):
69 def __init__(self, name, cmd, kwargs, message):
70 self.name = name
71 self.cmd = cmd
Edward Lesmes8e282792018-04-03 18:50:29 -040072 self.stdin = kwargs.get('stdin', None)
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +000073 self.kwargs = kwargs
Edward Lesmes8e282792018-04-03 18:50:29 -040074 self.kwargs['stdout'] = subprocess.PIPE
75 self.kwargs['stderr'] = subprocess.STDOUT
76 self.kwargs['stdin'] = subprocess.PIPE
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +000077 self.message = message
78 self.info = None
79
ilevy@chromium.orgbc117312013-04-20 03:57:56 +000080
Edward Lesmes8e282792018-04-03 18:50:29 -040081# Adapted from
82# https://github.com/google/gtest-parallel/blob/master/gtest_parallel.py#L37
83#
84# An object that catches SIGINT sent to the Python process and notices
85# if processes passed to wait() die by SIGINT (we need to look for
86# both of those cases, because pressing Ctrl+C can result in either
87# the main process or one of the subprocesses getting the signal).
88#
89# Before a SIGINT is seen, wait(p) will simply call p.wait() and
90# return the result. Once a SIGINT has been seen (in the main process
91# or a subprocess, including the one the current call is waiting for),
92# wait(p) will call p.terminate() and raise ProcessWasInterrupted.
93class SigintHandler(object):
94 class ProcessWasInterrupted(Exception):
95 pass
96
97 sigint_returncodes = {-signal.SIGINT, # Unix
98 -1073741510, # Windows
99 }
100 def __init__(self):
101 self.__lock = threading.Lock()
102 self.__processes = set()
103 self.__got_sigint = False
104 signal.signal(signal.SIGINT, lambda signal_num, frame: self.interrupt())
105
106 def __on_sigint(self):
107 self.__got_sigint = True
108 while self.__processes:
109 try:
110 self.__processes.pop().terminate()
111 except OSError:
112 pass
113
114 def interrupt(self):
115 with self.__lock:
116 self.__on_sigint()
117
118 def got_sigint(self):
119 with self.__lock:
120 return self.__got_sigint
121
122 def wait(self, p, stdin):
123 with self.__lock:
124 if self.__got_sigint:
125 p.terminate()
126 self.__processes.add(p)
127 stdout, stderr = p.communicate(stdin)
128 code = p.returncode
129 with self.__lock:
130 self.__processes.discard(p)
131 if code in self.sigint_returncodes:
132 self.__on_sigint()
133 if self.__got_sigint:
134 raise self.ProcessWasInterrupted
135 return stdout, stderr
136
137sigint_handler = SigintHandler()
138
139
140class ThreadPool(object):
141 def __init__(self, pool_size=None):
142 self._pool_size = pool_size or multiprocessing.cpu_count()
143 self._messages = []
144 self._messages_lock = threading.Lock()
145 self._tests = []
146 self._tests_lock = threading.Lock()
147 self._nonparallel_tests = []
148
149 def CallCommand(self, test):
150 """Runs an external program.
151
152 This function converts invocation of .py files and invocations of "python"
153 to vpython invocations.
154 """
155 vpython = 'vpython.bat' if sys.platform == 'win32' else 'vpython'
156
157 cmd = test.cmd
158 if cmd[0] == 'python':
159 cmd = list(cmd)
160 cmd[0] = vpython
161 elif cmd[0].endswith('.py'):
162 cmd = [vpython] + cmd
163
164 try:
165 start = time.time()
166 p = subprocess.Popen(cmd, **test.kwargs)
167 stdout, _ = sigint_handler.wait(p, test.stdin)
168 duration = time.time() - start
169 except OSError as e:
170 duration = time.time() - start
171 return test.message(
172 '%s exec failure (%4.2fs)\n %s' % (test.name, duration, e))
173 if p.returncode != 0:
174 return test.message(
175 '%s (%4.2fs) failed\n%s' % (test.name, duration, stdout))
176 if test.info:
177 return test.info('%s (%4.2fs)' % (test.name, duration))
178
179 def AddTests(self, tests, parallel=True):
180 if parallel:
181 self._tests.extend(tests)
182 else:
183 self._nonparallel_tests.extend(tests)
184
185 def RunAsync(self):
186 self._messages = []
187
188 def _WorkerFn():
189 while True:
190 test = None
191 with self._tests_lock:
192 if not self._tests:
193 break
194 test = self._tests.pop()
195 result = self.CallCommand(test)
196 if result:
197 with self._messages_lock:
198 self._messages.append(result)
199
200 def _StartDaemon():
201 t = threading.Thread(target=_WorkerFn)
202 t.daemon = True
203 t.start()
204 return t
205
206 while self._nonparallel_tests:
207 test = self._nonparallel_tests.pop()
208 result = self.CallCommand(test)
209 if result:
210 self._messages.append(result)
211
212 if self._tests:
213 threads = [_StartDaemon() for _ in range(self._pool_size)]
214 for worker in threads:
215 worker.join()
216
217 return self._messages
218
219
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000220def normpath(path):
221 '''Version of os.path.normpath that also changes backward slashes to
222 forward slashes when not running on Windows.
223 '''
224 # This is safe to always do because the Windows version of os.path.normpath
225 # will replace forward slashes with backward slashes.
226 path = path.replace(os.sep, '/')
227 return os.path.normpath(path)
228
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000229
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000230def _RightHandSideLinesImpl(affected_files):
231 """Implements RightHandSideLines for InputApi and GclChange."""
232 for af in affected_files:
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000233 lines = af.ChangedContents()
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000234 for line in lines:
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000235 yield (af, line[0], line[1])
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000236
237
dpranke@chromium.org5ac21012011-03-16 02:58:25 +0000238class PresubmitOutput(object):
239 def __init__(self, input_stream=None, output_stream=None):
240 self.input_stream = input_stream
241 self.output_stream = output_stream
242 self.reviewers = []
Daniel Cheng7227d212017-11-17 08:12:37 -0800243 self.more_cc = []
dpranke@chromium.org5ac21012011-03-16 02:58:25 +0000244 self.written_output = []
245 self.error_count = 0
246
247 def prompt_yes_no(self, prompt_string):
248 self.write(prompt_string)
249 if self.input_stream:
250 response = self.input_stream.readline().strip().lower()
251 if response not in ('y', 'yes'):
252 self.fail()
253 else:
254 self.fail()
255
256 def fail(self):
257 self.error_count += 1
258
259 def should_continue(self):
260 return not self.error_count
261
262 def write(self, s):
263 self.written_output.append(s)
264 if self.output_stream:
265 self.output_stream.write(s)
266
267 def getvalue(self):
268 return ''.join(self.written_output)
269
270
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000271# Top level object so multiprocessing can pickle
272# Public access through OutputApi object.
273class _PresubmitResult(object):
274 """Base class for result objects."""
275 fatal = False
276 should_prompt = False
277
278 def __init__(self, message, items=None, long_text=''):
279 """
280 message: A short one-line message to indicate errors.
281 items: A list of short strings to indicate where errors occurred.
282 long_text: multi-line text output, e.g. from another tool
283 """
284 self._message = message
285 self._items = items or []
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000286 self._long_text = long_text.rstrip()
287
288 def handle(self, output):
289 output.write(self._message)
290 output.write('\n')
291 for index, item in enumerate(self._items):
292 output.write(' ')
293 # Write separately in case it's unicode.
294 output.write(str(item))
295 if index < len(self._items) - 1:
296 output.write(' \\')
297 output.write('\n')
298 if self._long_text:
299 output.write('\n***************\n')
300 # Write separately in case it's unicode.
301 output.write(self._long_text)
302 output.write('\n***************\n')
303 if self.fatal:
304 output.fail()
305
306
307# Top level object so multiprocessing can pickle
308# Public access through OutputApi object.
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000309class _PresubmitError(_PresubmitResult):
310 """A hard presubmit error."""
311 fatal = True
312
313
314# Top level object so multiprocessing can pickle
315# Public access through OutputApi object.
316class _PresubmitPromptWarning(_PresubmitResult):
317 """An warning that prompts the user if they want to continue."""
318 should_prompt = True
319
320
321# Top level object so multiprocessing can pickle
322# Public access through OutputApi object.
323class _PresubmitNotifyResult(_PresubmitResult):
324 """Just print something to the screen -- but it's not even a warning."""
325 pass
326
327
328# Top level object so multiprocessing can pickle
329# Public access through OutputApi object.
330class _MailTextResult(_PresubmitResult):
331 """A warning that should be included in the review request email."""
332 def __init__(self, *args, **kwargs):
333 super(_MailTextResult, self).__init__()
334 raise NotImplementedError()
335
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000336class GerritAccessor(object):
337 """Limited Gerrit functionality for canned presubmit checks to work.
338
339 To avoid excessive Gerrit calls, caches the results.
340 """
341
342 def __init__(self, host):
343 self.host = host
344 self.cache = {}
345
346 def _FetchChangeDetail(self, issue):
347 # Separate function to be easily mocked in tests.
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +0100348 try:
349 return gerrit_util.GetChangeDetail(
350 self.host, str(issue),
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700351 ['ALL_REVISIONS', 'DETAILED_LABELS', 'ALL_COMMITS'])
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +0100352 except gerrit_util.GerritError as e:
353 if e.http_status == 404:
354 raise Exception('Either Gerrit issue %s doesn\'t exist, or '
355 'no credentials to fetch issue details' % issue)
356 raise
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000357
358 def GetChangeInfo(self, issue):
359 """Returns labels and all revisions (patchsets) for this issue.
360
361 The result is a dictionary according to Gerrit REST Api.
362 https://gerrit-review.googlesource.com/Documentation/rest-api.html
363
364 However, API isn't very clear what's inside, so see tests for example.
365 """
366 assert issue
367 cache_key = int(issue)
368 if cache_key not in self.cache:
369 self.cache[cache_key] = self._FetchChangeDetail(issue)
370 return self.cache[cache_key]
371
372 def GetChangeDescription(self, issue, patchset=None):
373 """If patchset is none, fetches current patchset."""
374 info = self.GetChangeInfo(issue)
375 # info is a reference to cache. We'll modify it here adding description to
376 # it to the right patchset, if it is not yet there.
377
378 # Find revision info for the patchset we want.
379 if patchset is not None:
380 for rev, rev_info in info['revisions'].iteritems():
381 if str(rev_info['_number']) == str(patchset):
382 break
383 else:
384 raise Exception('patchset %s doesn\'t exist in issue %s' % (
385 patchset, issue))
386 else:
387 rev = info['current_revision']
388 rev_info = info['revisions'][rev]
389
Andrii Shyshkalov9c3a4642017-01-24 17:41:22 +0100390 return rev_info['commit']['message']
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000391
Mun Yong Jang603d01e2017-12-19 16:38:30 -0800392 def GetDestRef(self, issue):
393 ref = self.GetChangeInfo(issue)['branch']
394 if not ref.startswith('refs/'):
395 # NOTE: it is possible to create 'refs/x' branch,
396 # aka 'refs/heads/refs/x'. However, this is ill-advised.
397 ref = 'refs/heads/%s' % ref
398 return ref
399
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000400 def GetChangeOwner(self, issue):
401 return self.GetChangeInfo(issue)['owner']['email']
402
403 def GetChangeReviewers(self, issue, approving_only=True):
Aaron Gable8b478f02017-07-31 15:33:19 -0700404 changeinfo = self.GetChangeInfo(issue)
405 if approving_only:
406 labelinfo = changeinfo.get('labels', {}).get('Code-Review', {})
407 values = labelinfo.get('values', {}).keys()
408 try:
409 max_value = max(int(v) for v in values)
410 reviewers = [r for r in labelinfo.get('all', [])
411 if r.get('value', 0) == max_value]
412 except ValueError: # values is the empty list
413 reviewers = []
414 else:
415 reviewers = changeinfo.get('reviewers', {}).get('REVIEWER', [])
416 return [r.get('email') for r in reviewers]
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000417
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000418
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000419class OutputApi(object):
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000420 """An instance of OutputApi gets passed to presubmit scripts so that they
421 can output various types of results.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000422 """
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000423 PresubmitResult = _PresubmitResult
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000424 PresubmitError = _PresubmitError
425 PresubmitPromptWarning = _PresubmitPromptWarning
426 PresubmitNotifyResult = _PresubmitNotifyResult
427 MailTextResult = _MailTextResult
428
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000429 def __init__(self, is_committing):
430 self.is_committing = is_committing
Daniel Cheng7227d212017-11-17 08:12:37 -0800431 self.more_cc = []
432
433 def AppendCC(self, cc):
434 """Appends a user to cc for this change."""
435 self.more_cc.append(cc)
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000436
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000437 def PresubmitPromptOrNotify(self, *args, **kwargs):
438 """Warn the user when uploading, but only notify if committing."""
439 if self.is_committing:
440 return self.PresubmitNotifyResult(*args, **kwargs)
441 return self.PresubmitPromptWarning(*args, **kwargs)
442
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000443
444class InputApi(object):
445 """An instance of this object is passed to presubmit scripts so they can
446 know stuff about the change they're looking at.
447 """
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000448 # Method could be a function
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800449 # pylint: disable=no-self-use
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000450
maruel@chromium.org3410d912009-06-09 20:56:16 +0000451 # File extensions that are considered source files from a style guide
452 # perspective. Don't modify this list from a presubmit script!
maruel@chromium.orgc33455a2011-06-24 19:14:18 +0000453 #
454 # Files without an extension aren't included in the list. If you want to
455 # filter them as source files, add r"(^|.*?[\\\/])[^.]+$" to the white list.
456 # Note that ALL CAPS files are black listed in DEFAULT_BLACK_LIST below.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000457 DEFAULT_WHITE_LIST = (
458 # C++ and friends
maruel@chromium.orgfe1211a2011-05-28 18:54:17 +0000459 r".+\.c$", r".+\.cc$", r".+\.cpp$", r".+\.h$", r".+\.m$", r".+\.mm$",
460 r".+\.inl$", r".+\.asm$", r".+\.hxx$", r".+\.hpp$", r".+\.s$", r".+\.S$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000461 # Scripts
maruel@chromium.orgfe1211a2011-05-28 18:54:17 +0000462 r".+\.js$", r".+\.py$", r".+\.sh$", r".+\.rb$", r".+\.pl$", r".+\.pm$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000463 # Other
Sergey Ulanov166bc4c2018-04-30 17:03:38 -0700464 r".+\.java$", r".+\.mk$", r".+\.am$", r".+\.css$", r".+\.mojom$",
465 r".+\.fidl$"
maruel@chromium.org3410d912009-06-09 20:56:16 +0000466 )
467
468 # Path regexp that should be excluded from being considered containing source
469 # files. Don't modify this list from a presubmit script!
470 DEFAULT_BLACK_LIST = (
gavinp@chromium.org656326d2012-08-13 00:43:57 +0000471 r"testing_support[\\\/]google_appengine[\\\/].*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000472 r".*\bexperimental[\\\/].*",
Kent Tamura179dd1e2018-04-26 15:07:41 +0900473 # Exclude third_party/.* but NOT third_party/{WebKit,blink}
474 # (crbug.com/539768 and crbug.com/836555).
475 r".*\bthird_party[\\\/](?!(WebKit|blink)[\\\/]).*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000476 # Output directories (just in case)
477 r".*\bDebug[\\\/].*",
478 r".*\bRelease[\\\/].*",
479 r".*\bxcodebuild[\\\/].*",
thakis@chromium.orgc1c96352013-10-09 19:50:27 +0000480 r".*\bout[\\\/].*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000481 # All caps files like README and LICENCE.
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000482 r".*\b[A-Z0-9_]{2,}$",
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000483 # SCM (can happen in dual SCM configuration). (Slightly over aggressive)
maruel@chromium.org5d0dc432011-01-03 02:40:37 +0000484 r"(|.*[\\\/])\.git[\\\/].*",
485 r"(|.*[\\\/])\.svn[\\\/].*",
maruel@chromium.org7ccb4bb2011-11-07 20:26:20 +0000486 # There is no point in processing a patch file.
487 r".+\.diff$",
488 r".+\.patch$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000489 )
490
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000491 def __init__(self, change, presubmit_path, is_committing,
Edward Lesmes8e282792018-04-03 18:50:29 -0400492 verbose, gerrit_obj, dry_run=None, thread_pool=None, parallel=False):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000493 """Builds an InputApi object.
494
495 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000496 change: A presubmit.Change object.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000497 presubmit_path: The path to the presubmit script being processed.
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000498 is_committing: True if the change is about to be committed.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000499 gerrit_obj: provides basic Gerrit codereview functionality.
500 dry_run: if true, some Checks will be skipped.
Edward Lesmes8e282792018-04-03 18:50:29 -0400501 parallel: if true, all tests reported via input_api.RunTests for all
502 PRESUBMIT files will be run in parallel.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000503 """
maruel@chromium.org9711bba2009-05-22 23:51:39 +0000504 # Version number of the presubmit_support script.
505 self.version = [int(x) for x in __version__.split('.')]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000506 self.change = change
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000507 self.is_committing = is_committing
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000508 self.gerrit = gerrit_obj
tandrii@chromium.org57bafac2016-04-28 05:09:03 +0000509 self.dry_run = dry_run
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000510
Edward Lesmes8e282792018-04-03 18:50:29 -0400511 self.parallel = parallel
512 self.thread_pool = thread_pool or ThreadPool()
513
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000514 # We expose various modules and functions as attributes of the input_api
515 # so that presubmit scripts don't have to import them.
Takeshi Yoshino07a6bea2017-08-02 02:44:06 +0900516 self.ast = ast
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000517 self.basename = os.path.basename
518 self.cPickle = cPickle
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000519 self.cpplint = cpplint
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000520 self.cStringIO = cStringIO
dcheng091b7db2016-06-16 01:27:51 -0700521 self.fnmatch = fnmatch
Yoshisato Yanagisawa04600b42019-03-15 03:03:41 +0000522 self.gclient_paths = gclient_paths
Yoshisato Yanagisawa57dd17b2019-03-22 09:10:29 +0000523 # TODO(yyanagisawa): stop exposing this when python3 become default.
524 # Since python3's tempfile has TemporaryDirectory, we do not need this.
525 self.temporary_directory = gclient_utils.temporary_directory
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000526 self.glob = glob.glob
maruel@chromium.orgfb11c7b2010-03-18 18:22:14 +0000527 self.json = json
maruel@chromium.org6fba34d2011-06-02 13:45:12 +0000528 self.logging = logging.getLogger('PRESUBMIT')
Yoshisato Yanagisawa406de132018-06-29 05:43:25 +0000529 self.marshal = marshal
maruel@chromium.org2b5ce562011-03-31 16:15:44 +0000530 self.os_listdir = os.listdir
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000531 self.os_path = os.path
pgervais@chromium.orgbd0cace2014-10-02 23:23:46 +0000532 self.os_stat = os.stat
Yoshisato Yanagisawa406de132018-06-29 05:43:25 +0000533 self.os_walk = os.walk
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000534 self.pickle = pickle
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000535 self.re = re
536 self.subprocess = subprocess
537 self.tempfile = tempfile
dpranke@chromium.org0d1bdea2011-03-24 22:54:38 +0000538 self.time = time
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000539 self.traceback = traceback
maruel@chromium.org1487d532009-06-06 00:22:57 +0000540 self.unittest = unittest
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000541 self.urllib2 = urllib2
542
Robert Iannucci50258932018-03-19 10:30:59 -0700543 self.is_windows = sys.platform == 'win32'
544
545 # Set python_executable to 'python'. This is interpreted in CallCommand to
546 # convert to vpython in order to allow scripts in other repos (e.g. src.git)
547 # to automatically pick up that repo's .vpython file, instead of inheriting
548 # the one in depot_tools.
549 self.python_executable = 'python'
maruel@chromium.orgc0b22972009-06-25 16:19:14 +0000550 self.environ = os.environ
551
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000552 # InputApi.platform is the platform you're currently running on.
553 self.platform = sys.platform
554
iannucci@chromium.org0af3bb32015-06-12 20:44:35 +0000555 self.cpu_count = multiprocessing.cpu_count()
556
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000557 # The local path of the currently-being-processed presubmit script.
maruel@chromium.org3d235242009-05-15 12:40:48 +0000558 self._current_presubmit_path = os.path.dirname(presubmit_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000559
560 # We carry the canned checks so presubmit scripts can easily use them.
561 self.canned_checks = presubmit_canned_checks
562
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +0100563 # Temporary files we must manually remove at the end of a run.
564 self._named_temporary_files = []
Jochen Eisinger72606f82017-04-04 10:44:18 +0200565
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000566 # TODO(dpranke): figure out a list of all approved owners for a repo
567 # in order to be able to handle wildcard OWNERS files?
568 self.owners_db = owners.Database(change.RepositoryRoot(),
Jochen Eisinger72606f82017-04-04 10:44:18 +0200569 fopen=file, os_path=self.os_path)
Jochen Eisinger76f5fc62017-04-07 16:27:46 +0200570 self.owners_finder = owners_finder.OwnersFinder
maruel@chromium.org899e1c12011-04-07 17:03:18 +0000571 self.verbose = verbose
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000572 self.Command = CommandData
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000573
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000574 # Replace <hash_map> and <hash_set> as headers that need to be included
danakj@chromium.org18278522013-06-11 22:42:32 +0000575 # with "base/containers/hash_tables.h" instead.
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000576 # Access to a protected member _XX of a client class
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800577 # pylint: disable=protected-access
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000578 self.cpplint._re_pattern_templates = [
danakj@chromium.org18278522013-06-11 22:42:32 +0000579 (a, b, 'base/containers/hash_tables.h')
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000580 if header in ('<hash_map>', '<hash_set>') else (a, b, header)
581 for (a, b, header) in cpplint._re_pattern_templates
582 ]
583
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000584 def PresubmitLocalPath(self):
585 """Returns the local path of the presubmit script currently being run.
586
587 This is useful if you don't want to hard-code absolute paths in the
588 presubmit script. For example, It can be used to find another file
589 relative to the PRESUBMIT.py script, so the whole tree can be branched and
590 the presubmit script still works, without editing its content.
591 """
maruel@chromium.org3d235242009-05-15 12:40:48 +0000592 return self._current_presubmit_path
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000593
agable0b65e732016-11-22 09:25:46 -0800594 def AffectedFiles(self, include_deletes=True, file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000595 """Same as input_api.change.AffectedFiles() except only lists files
596 (and optionally directories) in the same directory as the current presubmit
597 script, or subdirectories thereof.
598 """
maruel@chromium.org3d235242009-05-15 12:40:48 +0000599 dir_with_slash = normpath("%s/" % self.PresubmitLocalPath())
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000600 if len(dir_with_slash) == 1:
601 dir_with_slash = ''
sail@chromium.org5538e022011-05-12 17:53:16 +0000602
maruel@chromium.org4661e0c2009-06-04 00:45:26 +0000603 return filter(
604 lambda x: normpath(x.AbsoluteLocalPath()).startswith(dir_with_slash),
agable0b65e732016-11-22 09:25:46 -0800605 self.change.AffectedFiles(include_deletes, file_filter))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000606
agable0b65e732016-11-22 09:25:46 -0800607 def LocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000608 """Returns local paths of input_api.AffectedFiles()."""
agable0b65e732016-11-22 09:25:46 -0800609 paths = [af.LocalPath() for af in self.AffectedFiles()]
pgervais@chromium.org2f64f782014-04-25 00:12:33 +0000610 logging.debug("LocalPaths: %s", paths)
611 return paths
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000612
agable0b65e732016-11-22 09:25:46 -0800613 def AbsoluteLocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000614 """Returns absolute local paths of input_api.AffectedFiles()."""
agable0b65e732016-11-22 09:25:46 -0800615 return [af.AbsoluteLocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000616
John Budorick16162372018-04-18 10:39:53 -0700617 def AffectedTestableFiles(self, include_deletes=None, **kwargs):
agable0b65e732016-11-22 09:25:46 -0800618 """Same as input_api.change.AffectedTestableFiles() except only lists files
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000619 in the same directory as the current presubmit script, or subdirectories
620 thereof.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000621 """
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000622 if include_deletes is not None:
agable0b65e732016-11-22 09:25:46 -0800623 warn("AffectedTestableFiles(include_deletes=%s)"
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000624 " is deprecated and ignored" % str(include_deletes),
625 category=DeprecationWarning,
626 stacklevel=2)
agable0b65e732016-11-22 09:25:46 -0800627 return filter(lambda x: x.IsTestableFile(),
John Budorick16162372018-04-18 10:39:53 -0700628 self.AffectedFiles(include_deletes=False, **kwargs))
agable0b65e732016-11-22 09:25:46 -0800629
630 def AffectedTextFiles(self, include_deletes=None):
631 """An alias to AffectedTestableFiles for backwards compatibility."""
632 return self.AffectedTestableFiles(include_deletes=include_deletes)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000633
maruel@chromium.org3410d912009-06-09 20:56:16 +0000634 def FilterSourceFile(self, affected_file, white_list=None, black_list=None):
635 """Filters out files that aren't considered "source file".
636
637 If white_list or black_list is None, InputApi.DEFAULT_WHITE_LIST
638 and InputApi.DEFAULT_BLACK_LIST is used respectively.
639
640 The lists will be compiled as regular expression and
641 AffectedFile.LocalPath() needs to pass both list.
642
643 Note: Copy-paste this function to suit your needs or use a lambda function.
644 """
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000645 def Find(affected_file, items):
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000646 local_path = affected_file.LocalPath()
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000647 for item in items:
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000648 if self.re.match(item, local_path):
maruel@chromium.org3410d912009-06-09 20:56:16 +0000649 return True
650 return False
651 return (Find(affected_file, white_list or self.DEFAULT_WHITE_LIST) and
652 not Find(affected_file, black_list or self.DEFAULT_BLACK_LIST))
653
654 def AffectedSourceFiles(self, source_file):
agable0b65e732016-11-22 09:25:46 -0800655 """Filter the list of AffectedTestableFiles by the function source_file.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000656
657 If source_file is None, InputApi.FilterSourceFile() is used.
658 """
659 if not source_file:
660 source_file = self.FilterSourceFile
agable0b65e732016-11-22 09:25:46 -0800661 return filter(source_file, self.AffectedTestableFiles())
maruel@chromium.org3410d912009-06-09 20:56:16 +0000662
663 def RightHandSideLines(self, source_file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000664 """An iterator over all text lines in "new" version of changed files.
665
666 Only lists lines from new or modified text files in the change that are
667 contained by the directory of the currently executing presubmit script.
668
669 This is useful for doing line-by-line regex checks, like checking for
670 trailing whitespace.
671
672 Yields:
673 a 3 tuple:
674 the AffectedFile instance of the current file;
675 integer line number (1-based); and
676 the contents of the line as a string.
maruel@chromium.org1487d532009-06-06 00:22:57 +0000677
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000678 Note: The carriage return (LF or CR) is stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000679 """
maruel@chromium.org3410d912009-06-09 20:56:16 +0000680 files = self.AffectedSourceFiles(source_file_filter)
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000681 return _RightHandSideLinesImpl(files)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000682
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000683 def ReadFile(self, file_item, mode='r'):
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000684 """Reads an arbitrary file.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000685
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000686 Deny reading anything outside the repository.
687 """
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000688 if isinstance(file_item, AffectedFile):
689 file_item = file_item.AbsoluteLocalPath()
690 if not file_item.startswith(self.change.RepositoryRoot()):
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000691 raise IOError('Access outside the repository root is denied.')
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000692 return gclient_utils.FileRead(file_item, mode)
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000693
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +0100694 def CreateTemporaryFile(self, **kwargs):
695 """Returns a named temporary file that must be removed with a call to
696 RemoveTemporaryFiles().
697
698 All keyword arguments are forwarded to tempfile.NamedTemporaryFile(),
699 except for |delete|, which is always set to False.
700
701 Presubmit checks that need to create a temporary file and pass it for
702 reading should use this function instead of NamedTemporaryFile(), as
703 Windows fails to open a file that is already open for writing.
704
705 with input_api.CreateTemporaryFile() as f:
706 f.write('xyz')
707 f.close()
708 input_api.subprocess.check_output(['script-that', '--reads-from',
709 f.name])
710
711
712 Note that callers of CreateTemporaryFile() should not worry about removing
713 any temporary file; this is done transparently by the presubmit handling
714 code.
715 """
716 if 'delete' in kwargs:
717 # Prevent users from passing |delete|; we take care of file deletion
718 # ourselves and this prevents unintuitive error messages when we pass
719 # delete=False and 'delete' is also in kwargs.
720 raise TypeError('CreateTemporaryFile() does not take a "delete" '
721 'argument, file deletion is handled automatically by '
722 'the same presubmit_support code that creates InputApi '
723 'objects.')
724 temp_file = self.tempfile.NamedTemporaryFile(delete=False, **kwargs)
725 self._named_temporary_files.append(temp_file.name)
726 return temp_file
727
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000728 @property
729 def tbr(self):
730 """Returns if a change is TBR'ed."""
Jeremy Romandce22502017-06-20 15:37:29 -0400731 return 'TBR' in self.change.tags or self.change.TBRsFromDescription()
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000732
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +0000733 def RunTests(self, tests_mix, parallel=True):
Edward Lesmes8e282792018-04-03 18:50:29 -0400734 # RunTests doesn't actually run tests. It adds them to a ThreadPool that
735 # will run all tests once all PRESUBMIT files are processed.
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000736 tests = []
737 msgs = []
Edward Lemur7e3c67f2018-07-20 20:52:49 +0000738 parallel = parallel and self.parallel
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000739 for t in tests_mix:
Edward Lesmes8e282792018-04-03 18:50:29 -0400740 if isinstance(t, OutputApi.PresubmitResult) and t:
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000741 msgs.append(t)
742 else:
743 assert issubclass(t.message, _PresubmitResult)
744 tests.append(t)
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +0000745 if self.verbose:
746 t.info = _PresubmitNotifyResult
Edward Lemur1037c742018-05-01 18:56:04 -0400747 if not t.kwargs.get('cwd'):
748 t.kwargs['cwd'] = self.PresubmitLocalPath()
Edward Lesmes8e282792018-04-03 18:50:29 -0400749 self.thread_pool.AddTests(tests, parallel)
Edward Lemur7e3c67f2018-07-20 20:52:49 +0000750 if not parallel:
Edward Lesmes8e282792018-04-03 18:50:29 -0400751 msgs.extend(self.thread_pool.RunAsync())
752 return msgs
scottmg86099d72016-09-01 09:16:51 -0700753
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000754
nick@chromium.orgff526192013-06-10 19:30:26 +0000755class _DiffCache(object):
756 """Caches diffs retrieved from a particular SCM."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000757 def __init__(self, upstream=None):
758 """Stores the upstream revision against which all diffs will be computed."""
759 self._upstream = upstream
nick@chromium.orgff526192013-06-10 19:30:26 +0000760
761 def GetDiff(self, path, local_root):
762 """Get the diff for a particular path."""
763 raise NotImplementedError()
764
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700765 def GetOldContents(self, path, local_root):
766 """Get the old version for a particular path."""
767 raise NotImplementedError()
768
nick@chromium.orgff526192013-06-10 19:30:26 +0000769
nick@chromium.orgff526192013-06-10 19:30:26 +0000770class _GitDiffCache(_DiffCache):
771 """DiffCache implementation for git; gets all file diffs at once."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000772 def __init__(self, upstream):
773 super(_GitDiffCache, self).__init__(upstream=upstream)
nick@chromium.orgff526192013-06-10 19:30:26 +0000774 self._diffs_by_file = None
775
776 def GetDiff(self, path, local_root):
777 if not self._diffs_by_file:
778 # Compute a single diff for all files and parse the output; should
779 # with git this is much faster than computing one diff for each file.
780 diffs = {}
781
782 # Don't specify any filenames below, because there are command line length
783 # limits on some platforms and GenerateDiff would fail.
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000784 unified_diff = scm.GIT.GenerateDiff(local_root, files=[], full_move=True,
785 branch=self._upstream)
nick@chromium.orgff526192013-06-10 19:30:26 +0000786
787 # This regex matches the path twice, separated by a space. Note that
788 # filename itself may contain spaces.
789 file_marker = re.compile('^diff --git (?P<filename>.*) (?P=filename)$')
790 current_diff = []
791 keep_line_endings = True
792 for x in unified_diff.splitlines(keep_line_endings):
793 match = file_marker.match(x)
794 if match:
795 # Marks the start of a new per-file section.
796 diffs[match.group('filename')] = current_diff = [x]
797 elif x.startswith('diff --git'):
798 raise PresubmitFailure('Unexpected diff line: %s' % x)
799 else:
800 current_diff.append(x)
801
802 self._diffs_by_file = dict(
803 (normpath(path), ''.join(diff)) for path, diff in diffs.items())
804
805 if path not in self._diffs_by_file:
806 raise PresubmitFailure(
807 'Unified diff did not contain entry for file %s' % path)
808
809 return self._diffs_by_file[path]
810
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700811 def GetOldContents(self, path, local_root):
812 return scm.GIT.GetOldContents(local_root, path, branch=self._upstream)
813
nick@chromium.orgff526192013-06-10 19:30:26 +0000814
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000815class AffectedFile(object):
816 """Representation of a file in a change."""
nick@chromium.orgff526192013-06-10 19:30:26 +0000817
818 DIFF_CACHE = _DiffCache
819
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000820 # Method could be a function
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800821 # pylint: disable=no-self-use
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000822 def __init__(self, path, action, repository_root, diff_cache):
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000823 self._path = path
824 self._action = action
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000825 self._local_root = repository_root
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000826 self._is_directory = None
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000827 self._cached_changed_contents = None
828 self._cached_new_contents = None
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000829 self._diff_cache = diff_cache
tobiasjs2836bcf2016-08-16 04:08:16 -0700830 logging.debug('%s(%s)', self.__class__.__name__, self._path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000831
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000832 def LocalPath(self):
833 """Returns the path of this file on the local disk relative to client root.
Andrew Grieve92b8b992017-11-02 09:42:24 -0400834
835 This should be used for error messages but not for accessing files,
836 because presubmit checks are run with CWD=PresubmitLocalPath() (which is
837 often != client root).
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000838 """
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000839 return normpath(self._path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000840
841 def AbsoluteLocalPath(self):
842 """Returns the absolute path of this file on the local disk.
843 """
chase@chromium.org8e416c82009-10-06 04:30:44 +0000844 return os.path.abspath(os.path.join(self._local_root, self.LocalPath()))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000845
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000846 def Action(self):
847 """Returns the action on this opened file, e.g. A, M, D, etc."""
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000848 return self._action
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000849
agable0b65e732016-11-22 09:25:46 -0800850 def IsTestableFile(self):
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000851 """Returns True if the file is a text file and not a binary file.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000852
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000853 Deleted files are not text file."""
maruel@chromium.org1e08c002009-05-28 19:09:33 +0000854 raise NotImplementedError() # Implement when needed
855
agable0b65e732016-11-22 09:25:46 -0800856 def IsTextFile(self):
857 """An alias to IsTestableFile for backwards compatibility."""
858 return self.IsTestableFile()
859
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700860 def OldContents(self):
861 """Returns an iterator over the lines in the old version of file.
862
Daniel Cheng2da34fe2017-03-21 20:42:12 -0700863 The old version is the file before any modifications in the user's
864 workspace, i.e. the "left hand side".
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700865
866 Contents will be empty if the file is a directory or does not exist.
867 Note: The carriage returns (LF or CR) are stripped off.
868 """
869 return self._diff_cache.GetOldContents(self.LocalPath(),
870 self._local_root).splitlines()
871
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000872 def NewContents(self):
873 """Returns an iterator over the lines in the new version of file.
874
875 The new version is the file in the user's workspace, i.e. the "right hand
876 side".
877
878 Contents will be empty if the file is a directory or does not exist.
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000879 Note: The carriage returns (LF or CR) are stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000880 """
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000881 if self._cached_new_contents is None:
882 self._cached_new_contents = []
agable0b65e732016-11-22 09:25:46 -0800883 try:
884 self._cached_new_contents = gclient_utils.FileRead(
885 self.AbsoluteLocalPath(), 'rU').splitlines()
886 except IOError:
887 pass # File not found? That's fine; maybe it was deleted.
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000888 return self._cached_new_contents[:]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000889
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000890 def ChangedContents(self):
891 """Returns a list of tuples (line number, line text) of all new lines.
892
893 This relies on the scm diff output describing each changed code section
894 with a line of the form
895
896 ^@@ <old line num>,<old size> <new line num>,<new size> @@$
897 """
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000898 if self._cached_changed_contents is not None:
899 return self._cached_changed_contents[:]
900 self._cached_changed_contents = []
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000901 line_num = 0
902
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000903 for line in self.GenerateScmDiff().splitlines():
904 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
905 if m:
906 line_num = int(m.groups(1)[0])
907 continue
908 if line.startswith('+') and not line.startswith('++'):
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000909 self._cached_changed_contents.append((line_num, line[1:]))
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000910 if not line.startswith('-'):
911 line_num += 1
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000912 return self._cached_changed_contents[:]
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000913
maruel@chromium.org5de13972009-06-10 18:16:06 +0000914 def __str__(self):
915 return self.LocalPath()
916
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000917 def GenerateScmDiff(self):
nick@chromium.orgff526192013-06-10 19:30:26 +0000918 return self._diff_cache.GetDiff(self.LocalPath(), self._local_root)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000919
maruel@chromium.org58407af2011-04-12 23:15:57 +0000920
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000921class GitAffectedFile(AffectedFile):
922 """Representation of a file in a change out of a git checkout."""
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000923 # Method 'NNN' is abstract in class 'NNN' but is not overridden
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800924 # pylint: disable=abstract-method
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000925
nick@chromium.orgff526192013-06-10 19:30:26 +0000926 DIFF_CACHE = _GitDiffCache
927
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000928 def __init__(self, *args, **kwargs):
929 AffectedFile.__init__(self, *args, **kwargs)
930 self._server_path = None
agable0b65e732016-11-22 09:25:46 -0800931 self._is_testable_file = None
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000932
agable0b65e732016-11-22 09:25:46 -0800933 def IsTestableFile(self):
934 if self._is_testable_file is None:
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000935 if self.Action() == 'D':
agable0b65e732016-11-22 09:25:46 -0800936 # A deleted file is not testable.
937 self._is_testable_file = False
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000938 else:
agable0b65e732016-11-22 09:25:46 -0800939 self._is_testable_file = os.path.isfile(self.AbsoluteLocalPath())
940 return self._is_testable_file
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000941
maruel@chromium.orgc1938752011-04-12 23:11:13 +0000942
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000943class Change(object):
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000944 """Describe a change.
945
946 Used directly by the presubmit scripts to query the current change being
947 tested.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000948
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000949 Instance members:
nick@chromium.orgff526192013-06-10 19:30:26 +0000950 tags: Dictionary of KEY=VALUE pairs found in the change description.
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000951 self.KEY: equivalent to tags['KEY']
952 """
953
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000954 _AFFECTED_FILES = AffectedFile
955
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000956 # Matches key/value (or "tag") lines in changelist descriptions.
maruel@chromium.org428342a2011-11-10 15:46:33 +0000957 TAG_LINE_RE = re.compile(
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +0000958 '^[ \t]*(?P<key>[A-Z][A-Z_0-9]*)[ \t]*=[ \t]*(?P<value>.*?)[ \t]*$')
maruel@chromium.orgc1938752011-04-12 23:11:13 +0000959 scm = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000960
maruel@chromium.org58407af2011-04-12 23:15:57 +0000961 def __init__(
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000962 self, name, description, local_root, files, issue, patchset, author,
963 upstream=None):
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000964 if files is None:
965 files = []
966 self._name = name
chase@chromium.org8e416c82009-10-06 04:30:44 +0000967 # Convert root into an absolute path.
968 self._local_root = os.path.abspath(local_root)
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000969 self._upstream = upstream
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000970 self.issue = issue
971 self.patchset = patchset
maruel@chromium.org58407af2011-04-12 23:15:57 +0000972 self.author_email = author
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000973
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000974 self._full_description = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000975 self.tags = {}
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000976 self._description_without_tags = ''
977 self.SetDescriptionText(description)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000978
maruel@chromium.orge085d812011-10-10 19:49:15 +0000979 assert all(
980 (isinstance(f, (list, tuple)) and len(f) == 2) for f in files), files
981
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000982 diff_cache = self._AFFECTED_FILES.DIFF_CACHE(self._upstream)
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000983 self._affected_files = [
nick@chromium.orgff526192013-06-10 19:30:26 +0000984 self._AFFECTED_FILES(path, action.strip(), self._local_root, diff_cache)
985 for action, path in files
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000986 ]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000987
maruel@chromium.org92022ec2009-06-11 01:59:28 +0000988 def Name(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000989 """Returns the change name."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000990 return self._name
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000991
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000992 def DescriptionText(self):
993 """Returns the user-entered changelist description, minus tags.
994
995 Any line in the user-provided description starting with e.g. "FOO="
996 (whitespace permitted before and around) is considered a tag line. Such
997 lines are stripped out of the description this function returns.
998 """
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000999 return self._description_without_tags
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001000
1001 def FullDescriptionText(self):
1002 """Returns the complete changelist description including tags."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001003 return self._full_description
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001004
isherman@chromium.orgb5cded62014-03-25 17:47:57 +00001005 def SetDescriptionText(self, description):
1006 """Sets the full description text (including tags) to |description|.
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001007
isherman@chromium.orgb5cded62014-03-25 17:47:57 +00001008 Also updates the list of tags."""
1009 self._full_description = description
1010
1011 # From the description text, build up a dictionary of key/value pairs
1012 # plus the description minus all key/value or "tag" lines.
1013 description_without_tags = []
1014 self.tags = {}
1015 for line in self._full_description.splitlines():
1016 m = self.TAG_LINE_RE.match(line)
1017 if m:
1018 self.tags[m.group('key')] = m.group('value')
1019 else:
1020 description_without_tags.append(line)
1021
1022 # Change back to text and remove whitespace at end.
1023 self._description_without_tags = (
1024 '\n'.join(description_without_tags).rstrip())
1025
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001026 def RepositoryRoot(self):
maruel@chromium.org92022ec2009-06-11 01:59:28 +00001027 """Returns the repository (checkout) root directory for this change,
1028 as an absolute path.
1029 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001030 return self._local_root
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001031
1032 def __getattr__(self, attr):
maruel@chromium.org92022ec2009-06-11 01:59:28 +00001033 """Return tags directly as attributes on the object."""
1034 if not re.match(r"^[A-Z_]*$", attr):
1035 raise AttributeError(self, attr)
maruel@chromium.orge1a524f2009-05-27 14:43:46 +00001036 return self.tags.get(attr)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001037
Aaron Gablefc03e672017-05-15 14:09:42 -07001038 def BugsFromDescription(self):
1039 """Returns all bugs referenced in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -07001040 tags = [b.strip() for b in self.tags.get('BUG', '').split(',') if b.strip()]
Caleb Rouleauc0546b92019-02-22 06:12:57 +00001041 footers = []
1042 unsplit_footers = git_footers.parse_footers(self._full_description).get(
1043 'Bug', [])
1044 for unsplit_footer in unsplit_footers:
1045 footers += [b.strip() for b in unsplit_footer.split(',')]
Aaron Gable12ef5012017-05-15 14:29:00 -07001046 return sorted(set(tags + footers))
Aaron Gablefc03e672017-05-15 14:09:42 -07001047
1048 def ReviewersFromDescription(self):
1049 """Returns all reviewers listed in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -07001050 # We don't support a "R:" git-footer for reviewers; that is in metadata.
1051 tags = [r.strip() for r in self.tags.get('R', '').split(',') if r.strip()]
1052 return sorted(set(tags))
Aaron Gablefc03e672017-05-15 14:09:42 -07001053
1054 def TBRsFromDescription(self):
1055 """Returns all TBR reviewers listed in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -07001056 tags = [r.strip() for r in self.tags.get('TBR', '').split(',') if r.strip()]
1057 # TODO(agable): Remove support for 'Tbr:' when TBRs are programmatically
1058 # determined by self-CR+1s.
1059 footers = git_footers.parse_footers(self._full_description).get('Tbr', [])
1060 return sorted(set(tags + footers))
Aaron Gablefc03e672017-05-15 14:09:42 -07001061
1062 # TODO(agable): Delete these once we're sure they're unused.
1063 @property
1064 def BUG(self):
1065 return ','.join(self.BugsFromDescription())
1066 @property
1067 def R(self):
1068 return ','.join(self.ReviewersFromDescription())
1069 @property
1070 def TBR(self):
1071 return ','.join(self.TBRsFromDescription())
1072
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001073 def AllFiles(self, root=None):
1074 """List all files under source control in the repo."""
1075 raise NotImplementedError()
1076
agable0b65e732016-11-22 09:25:46 -08001077 def AffectedFiles(self, include_deletes=True, file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001078 """Returns a list of AffectedFile instances for all files in the change.
1079
1080 Args:
1081 include_deletes: If false, deleted files will be filtered out.
sail@chromium.org5538e022011-05-12 17:53:16 +00001082 file_filter: An additional filter to apply.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001083
1084 Returns:
1085 [AffectedFile(path, action), AffectedFile(path, action)]
1086 """
agable0b65e732016-11-22 09:25:46 -08001087 affected = filter(file_filter, self._affected_files)
sail@chromium.org5538e022011-05-12 17:53:16 +00001088
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001089 if include_deletes:
1090 return affected
Lei Zhang9611c4c2017-04-04 01:41:56 -07001091 return filter(lambda x: x.Action() != 'D', affected)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001092
John Budorick16162372018-04-18 10:39:53 -07001093 def AffectedTestableFiles(self, include_deletes=None, **kwargs):
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +00001094 """Return a list of the existing text files in a change."""
1095 if include_deletes is not None:
agable0b65e732016-11-22 09:25:46 -08001096 warn("AffectedTeestableFiles(include_deletes=%s)"
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +00001097 " is deprecated and ignored" % str(include_deletes),
1098 category=DeprecationWarning,
1099 stacklevel=2)
agable0b65e732016-11-22 09:25:46 -08001100 return filter(lambda x: x.IsTestableFile(),
John Budorick16162372018-04-18 10:39:53 -07001101 self.AffectedFiles(include_deletes=False, **kwargs))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001102
agable0b65e732016-11-22 09:25:46 -08001103 def AffectedTextFiles(self, include_deletes=None):
1104 """An alias to AffectedTestableFiles for backwards compatibility."""
1105 return self.AffectedTestableFiles(include_deletes=include_deletes)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001106
agable0b65e732016-11-22 09:25:46 -08001107 def LocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001108 """Convenience function."""
agable0b65e732016-11-22 09:25:46 -08001109 return [af.LocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001110
agable0b65e732016-11-22 09:25:46 -08001111 def AbsoluteLocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001112 """Convenience function."""
agable0b65e732016-11-22 09:25:46 -08001113 return [af.AbsoluteLocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001114
1115 def RightHandSideLines(self):
1116 """An iterator over all text lines in "new" version of changed files.
1117
1118 Lists lines from new or modified text files in the change.
1119
1120 This is useful for doing line-by-line regex checks, like checking for
1121 trailing whitespace.
1122
1123 Yields:
1124 a 3 tuple:
1125 the AffectedFile instance of the current file;
1126 integer line number (1-based); and
1127 the contents of the line as a string.
1128 """
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +00001129 return _RightHandSideLinesImpl(
1130 x for x in self.AffectedFiles(include_deletes=False)
agable0b65e732016-11-22 09:25:46 -08001131 if x.IsTestableFile())
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001132
Jochen Eisingerd0573ec2017-04-13 10:55:06 +02001133 def OriginalOwnersFiles(self):
1134 """A map from path names of affected OWNERS files to their old content."""
1135 def owners_file_filter(f):
1136 return 'OWNERS' in os.path.split(f.LocalPath())[1]
1137 files = self.AffectedFiles(file_filter=owners_file_filter)
1138 return dict([(f.LocalPath(), f.OldContents()) for f in files])
1139
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001140
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001141class GitChange(Change):
1142 _AFFECTED_FILES = GitAffectedFile
maruel@chromium.orgc1938752011-04-12 23:11:13 +00001143 scm = 'git'
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +00001144
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001145 def AllFiles(self, root=None):
1146 """List all files under source control in the repo."""
1147 root = root or self.RepositoryRoot()
1148 return subprocess.check_output(
Aaron Gable7817f022017-12-12 09:43:17 -08001149 ['git', '-c', 'core.quotePath=false', 'ls-files', '--', '.'],
1150 cwd=root).splitlines()
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001151
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001152
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001153def ListRelevantPresubmitFiles(files, root):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001154 """Finds all presubmit files that apply to a given set of source files.
1155
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001156 If inherit-review-settings-ok is present right under root, looks for
1157 PRESUBMIT.py in directories enclosing root.
1158
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001159 Args:
1160 files: An iterable container containing file paths.
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001161 root: Path where to stop searching.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001162
1163 Return:
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001164 List of absolute paths of the existing PRESUBMIT.py scripts.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001165 """
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001166 files = [normpath(os.path.join(root, f)) for f in files]
1167
1168 # List all the individual directories containing files.
1169 directories = set([os.path.dirname(f) for f in files])
1170
1171 # Ignore root if inherit-review-settings-ok is present.
1172 if os.path.isfile(os.path.join(root, 'inherit-review-settings-ok')):
1173 root = None
1174
1175 # Collect all unique directories that may contain PRESUBMIT.py.
1176 candidates = set()
1177 for directory in directories:
1178 while True:
1179 if directory in candidates:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001180 break
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001181 candidates.add(directory)
1182 if directory == root:
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001183 break
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001184 parent_dir = os.path.dirname(directory)
1185 if parent_dir == directory:
1186 # We hit the system root directory.
1187 break
1188 directory = parent_dir
1189
1190 # Look for PRESUBMIT.py in all candidate directories.
1191 results = []
1192 for directory in sorted(list(candidates)):
tobiasjsff061c02016-08-17 03:23:57 -07001193 try:
1194 for f in os.listdir(directory):
1195 p = os.path.join(directory, f)
1196 if os.path.isfile(p) and re.match(
1197 r'PRESUBMIT.*\.py$', f) and not f.startswith('PRESUBMIT_test'):
1198 results.append(p)
1199 except OSError:
1200 pass
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001201
tobiasjs2836bcf2016-08-16 04:08:16 -07001202 logging.debug('Presubmit files: %s', ','.join(results))
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001203 return results
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001204
1205
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001206class GetTryMastersExecuter(object):
1207 @staticmethod
1208 def ExecPresubmitScript(script_text, presubmit_path, project, change):
1209 """Executes GetPreferredTryMasters() from a single presubmit script.
1210
1211 Args:
1212 script_text: The text of the presubmit script.
1213 presubmit_path: Project script to run.
1214 project: Project name to pass to presubmit script for bot selection.
1215
1216 Return:
1217 A map of try masters to map of builders to set of tests.
1218 """
1219 context = {}
1220 try:
1221 exec script_text in context
1222 except Exception, e:
1223 raise PresubmitFailure('"%s" had an exception.\n%s'
1224 % (presubmit_path, e))
1225
1226 function_name = 'GetPreferredTryMasters'
1227 if function_name not in context:
1228 return {}
1229 get_preferred_try_masters = context[function_name]
1230 if not len(inspect.getargspec(get_preferred_try_masters)[0]) == 2:
1231 raise PresubmitFailure(
1232 'Expected function "GetPreferredTryMasters" to take two arguments.')
1233 return get_preferred_try_masters(project, change)
1234
1235
rmistry@google.com5626a922015-02-26 14:03:30 +00001236class GetPostUploadExecuter(object):
1237 @staticmethod
1238 def ExecPresubmitScript(script_text, presubmit_path, cl, change):
1239 """Executes PostUploadHook() from a single presubmit script.
1240
1241 Args:
1242 script_text: The text of the presubmit script.
1243 presubmit_path: Project script to run.
1244 cl: The Changelist object.
1245 change: The Change object.
1246
1247 Return:
1248 A list of results objects.
1249 """
1250 context = {}
1251 try:
1252 exec script_text in context
1253 except Exception, e:
1254 raise PresubmitFailure('"%s" had an exception.\n%s'
1255 % (presubmit_path, e))
1256
1257 function_name = 'PostUploadHook'
1258 if function_name not in context:
1259 return {}
1260 post_upload_hook = context[function_name]
1261 if not len(inspect.getargspec(post_upload_hook)[0]) == 3:
1262 raise PresubmitFailure(
1263 'Expected function "PostUploadHook" to take three arguments.')
1264 return post_upload_hook(cl, change, OutputApi(False))
1265
1266
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001267def _MergeMasters(masters1, masters2):
1268 """Merges two master maps. Merges also the tests of each builder."""
1269 result = {}
1270 for (master, builders) in itertools.chain(masters1.iteritems(),
1271 masters2.iteritems()):
1272 new_builders = result.setdefault(master, {})
1273 for (builder, tests) in builders.iteritems():
1274 new_builders.setdefault(builder, set([])).update(tests)
1275 return result
1276
1277
1278def DoGetTryMasters(change,
1279 changed_files,
1280 repository_root,
1281 default_presubmit,
1282 project,
1283 verbose,
1284 output_stream):
1285 """Get the list of try masters from the presubmit scripts.
1286
1287 Args:
1288 changed_files: List of modified files.
1289 repository_root: The repository root.
1290 default_presubmit: A default presubmit script to execute in any case.
1291 project: Optional name of a project used in selecting trybots.
1292 verbose: Prints debug info.
1293 output_stream: A stream to write debug output to.
1294
1295 Return:
1296 Map of try masters to map of builders to set of tests.
1297 """
1298 presubmit_files = ListRelevantPresubmitFiles(changed_files, repository_root)
1299 if not presubmit_files and verbose:
1300 output_stream.write("Warning, no PRESUBMIT.py found.\n")
1301 results = {}
1302 executer = GetTryMastersExecuter()
1303
1304 if default_presubmit:
1305 if verbose:
1306 output_stream.write("Running default presubmit script.\n")
1307 fake_path = os.path.join(repository_root, 'PRESUBMIT.py')
1308 results = _MergeMasters(results, executer.ExecPresubmitScript(
1309 default_presubmit, fake_path, project, change))
1310 for filename in presubmit_files:
1311 filename = os.path.abspath(filename)
1312 if verbose:
1313 output_stream.write("Running %s\n" % filename)
1314 # Accept CRLF presubmit script.
1315 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1316 results = _MergeMasters(results, executer.ExecPresubmitScript(
1317 presubmit_script, filename, project, change))
1318
1319 # Make sets to lists again for later JSON serialization.
1320 for builders in results.itervalues():
1321 for builder in builders:
1322 builders[builder] = list(builders[builder])
1323
1324 if results and verbose:
1325 output_stream.write('%s\n' % str(results))
1326 return results
1327
1328
rmistry@google.com5626a922015-02-26 14:03:30 +00001329def DoPostUploadExecuter(change,
1330 cl,
1331 repository_root,
1332 verbose,
1333 output_stream):
1334 """Execute the post upload hook.
1335
1336 Args:
1337 change: The Change object.
1338 cl: The Changelist object.
1339 repository_root: The repository root.
1340 verbose: Prints debug info.
1341 output_stream: A stream to write debug output to.
1342 """
1343 presubmit_files = ListRelevantPresubmitFiles(
1344 change.LocalPaths(), repository_root)
1345 if not presubmit_files and verbose:
1346 output_stream.write("Warning, no PRESUBMIT.py found.\n")
1347 results = []
1348 executer = GetPostUploadExecuter()
1349 # The root presubmit file should be executed after the ones in subdirectories.
1350 # i.e. the specific post upload hooks should run before the general ones.
1351 # Thus, reverse the order provided by ListRelevantPresubmitFiles.
1352 presubmit_files.reverse()
1353
1354 for filename in presubmit_files:
1355 filename = os.path.abspath(filename)
1356 if verbose:
1357 output_stream.write("Running %s\n" % filename)
1358 # Accept CRLF presubmit script.
1359 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1360 results.extend(executer.ExecPresubmitScript(
1361 presubmit_script, filename, cl, change))
1362 output_stream.write('\n')
1363 if results:
1364 output_stream.write('** Post Upload Hook Messages **\n')
1365 for result in results:
1366 result.handle(output_stream)
1367 output_stream.write('\n')
1368
1369 return results
1370
1371
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001372class PresubmitExecuter(object):
Aaron Gable668c1d82018-04-03 10:19:16 -07001373 def __init__(self, change, committing, verbose,
Edward Lesmes8e282792018-04-03 18:50:29 -04001374 gerrit_obj, dry_run=None, thread_pool=None, parallel=False):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001375 """
1376 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001377 change: The Change object.
agable92bec4f2016-08-24 09:27:27 -07001378 committing: True if 'git cl land' is running, False if 'git cl upload' is.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001379 gerrit_obj: provides basic Gerrit codereview functionality.
1380 dry_run: if true, some Checks will be skipped.
Edward Lesmes8e282792018-04-03 18:50:29 -04001381 parallel: if true, all tests reported via input_api.RunTests for all
1382 PRESUBMIT files will be run in parallel.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001383 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001384 self.change = change
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001385 self.committing = committing
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001386 self.gerrit = gerrit_obj
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001387 self.verbose = verbose
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001388 self.dry_run = dry_run
Daniel Cheng7227d212017-11-17 08:12:37 -08001389 self.more_cc = []
Edward Lesmes8e282792018-04-03 18:50:29 -04001390 self.thread_pool = thread_pool
1391 self.parallel = parallel
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001392
1393 def ExecPresubmitScript(self, script_text, presubmit_path):
1394 """Executes a single presubmit script.
1395
1396 Args:
1397 script_text: The text of the presubmit script.
1398 presubmit_path: The path to the presubmit file (this will be reported via
1399 input_api.PresubmitLocalPath()).
1400
1401 Return:
1402 A list of result objects, empty if no problems.
1403 """
thakis@chromium.orgc6ef53a2014-11-04 00:13:54 +00001404
chase@chromium.org8e416c82009-10-06 04:30:44 +00001405 # Change to the presubmit file's directory to support local imports.
1406 main_path = os.getcwd()
1407 os.chdir(os.path.dirname(presubmit_path))
1408
1409 # Load the presubmit script into context.
dpranke@chromium.org970c5222011-03-12 00:32:24 +00001410 input_api = InputApi(self.change, presubmit_path, self.committing,
Aaron Gable668c1d82018-04-03 10:19:16 -07001411 self.verbose, gerrit_obj=self.gerrit,
Edward Lesmes8e282792018-04-03 18:50:29 -04001412 dry_run=self.dry_run, thread_pool=self.thread_pool,
1413 parallel=self.parallel)
Daniel Cheng7227d212017-11-17 08:12:37 -08001414 output_api = OutputApi(self.committing)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001415 context = {}
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001416 try:
1417 exec script_text in context
1418 except Exception, e:
1419 raise PresubmitFailure('"%s" had an exception.\n%s' % (presubmit_path, e))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001420
1421 # These function names must change if we make substantial changes to
1422 # the presubmit API that are not backwards compatible.
1423 if self.committing:
1424 function_name = 'CheckChangeOnCommit'
1425 else:
1426 function_name = 'CheckChangeOnUpload'
1427 if function_name in context:
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +01001428 try:
Daniel Cheng7227d212017-11-17 08:12:37 -08001429 context['__args'] = (input_api, output_api)
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +01001430 logging.debug('Running %s in %s', function_name, presubmit_path)
1431 result = eval(function_name + '(*__args)', context)
1432 logging.debug('Running %s done.', function_name)
Daniel Chengd36fce42017-11-21 21:52:52 -08001433 self.more_cc.extend(output_api.more_cc)
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +01001434 finally:
1435 map(os.remove, input_api._named_temporary_files)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001436 if not (isinstance(result, types.TupleType) or
1437 isinstance(result, types.ListType)):
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001438 raise PresubmitFailure(
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001439 'Presubmit functions must return a tuple or list')
1440 for item in result:
1441 if not isinstance(item, OutputApi.PresubmitResult):
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001442 raise PresubmitFailure(
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001443 'All presubmit results must be of types derived from '
1444 'output_api.PresubmitResult')
1445 else:
1446 result = () # no error since the script doesn't care about current event.
1447
chase@chromium.org8e416c82009-10-06 04:30:44 +00001448 # Return the process to the original working directory.
1449 os.chdir(main_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001450 return result
1451
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001452def DoPresubmitChecks(change,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001453 committing,
1454 verbose,
1455 output_stream,
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +00001456 input_stream,
maruel@chromium.orgb0dfd352009-06-10 14:12:54 +00001457 default_presubmit,
dpranke@chromium.org970c5222011-03-12 00:32:24 +00001458 may_prompt,
Aaron Gable668c1d82018-04-03 10:19:16 -07001459 gerrit_obj,
Edward Lesmes8e282792018-04-03 18:50:29 -04001460 dry_run=None,
1461 parallel=False):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001462 """Runs all presubmit checks that apply to the files in the change.
1463
1464 This finds all PRESUBMIT.py files in directories enclosing the files in the
1465 change (up to the repository root) and calls the relevant entrypoint function
1466 depending on whether the change is being committed or uploaded.
1467
1468 Prints errors, warnings and notifications. Prompts the user for warnings
1469 when needed.
1470
1471 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001472 change: The Change object.
agable92bec4f2016-08-24 09:27:27 -07001473 committing: True if 'git cl land' is running, False if 'git cl upload' is.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001474 verbose: Prints debug info.
1475 output_stream: A stream to write output from presubmit tests to.
1476 input_stream: A stream to read input from the user.
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +00001477 default_presubmit: A default presubmit script to execute in any case.
Quinten Yearsley516fe7f2016-12-14 11:50:18 -08001478 may_prompt: Enable (y/n) questions on warning or error. If False,
1479 any questions are answered with yes by default.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001480 gerrit_obj: provides basic Gerrit codereview functionality.
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001481 dry_run: if true, some Checks will be skipped.
Edward Lesmes8e282792018-04-03 18:50:29 -04001482 parallel: if true, all tests specified by input_api.RunTests in all
1483 PRESUBMIT files will be run in parallel.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001484
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +00001485 Warning:
1486 If may_prompt is true, output_stream SHOULD be sys.stdout and input_stream
1487 SHOULD be sys.stdin.
1488
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001489 Return:
dpranke@chromium.org5ac21012011-03-16 02:58:25 +00001490 A PresubmitOutput object. Use output.should_continue() to figure out
1491 if there were errors or warnings and the caller should abort.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001492 """
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001493 old_environ = os.environ
1494 try:
1495 # Make sure python subprocesses won't generate .pyc files.
1496 os.environ = os.environ.copy()
1497 os.environ['PYTHONDONTWRITEBYTECODE'] = '1'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001498
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001499 output = PresubmitOutput(input_stream, output_stream)
1500 if committing:
1501 output.write("Running presubmit commit checks ...\n")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001502 else:
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001503 output.write("Running presubmit upload checks ...\n")
1504 start_time = time.time()
1505 presubmit_files = ListRelevantPresubmitFiles(
agable0b65e732016-11-22 09:25:46 -08001506 change.AbsoluteLocalPaths(), change.RepositoryRoot())
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001507 if not presubmit_files and verbose:
maruel@chromium.orgfae707b2011-09-15 18:57:58 +00001508 output.write("Warning, no PRESUBMIT.py found.\n")
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001509 results = []
Edward Lesmes8e282792018-04-03 18:50:29 -04001510 thread_pool = ThreadPool()
Edward Lemur7e3c67f2018-07-20 20:52:49 +00001511 executer = PresubmitExecuter(change, committing, verbose, gerrit_obj,
1512 dry_run, thread_pool, parallel)
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001513 if default_presubmit:
1514 if verbose:
1515 output.write("Running default presubmit script.\n")
1516 fake_path = os.path.join(change.RepositoryRoot(), 'PRESUBMIT.py')
1517 results += executer.ExecPresubmitScript(default_presubmit, fake_path)
1518 for filename in presubmit_files:
1519 filename = os.path.abspath(filename)
1520 if verbose:
1521 output.write("Running %s\n" % filename)
1522 # Accept CRLF presubmit script.
1523 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1524 results += executer.ExecPresubmitScript(presubmit_script, filename)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001525
Edward Lesmes8e282792018-04-03 18:50:29 -04001526 results += thread_pool.RunAsync()
1527
Daniel Cheng7227d212017-11-17 08:12:37 -08001528 output.more_cc.extend(executer.more_cc)
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001529 errors = []
1530 notifications = []
1531 warnings = []
1532 for result in results:
1533 if result.fatal:
1534 errors.append(result)
1535 elif result.should_prompt:
1536 warnings.append(result)
1537 else:
1538 notifications.append(result)
pam@chromium.orged9a0832009-09-09 22:48:55 +00001539
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001540 output.write('\n')
1541 for name, items in (('Messages', notifications),
1542 ('Warnings', warnings),
1543 ('ERRORS', errors)):
1544 if items:
1545 output.write('** Presubmit %s **\n' % name)
1546 for item in items:
1547 item.handle(output)
1548 output.write('\n')
pam@chromium.orged9a0832009-09-09 22:48:55 +00001549
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001550 total_time = time.time() - start_time
1551 if total_time > 1.0:
1552 output.write("Presubmit checks took %.1fs to calculate.\n\n" % total_time)
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +00001553
Quinten Yearsley516fe7f2016-12-14 11:50:18 -08001554 if errors:
1555 output.fail()
1556 elif warnings:
1557 output.write('There were presubmit warnings. ')
1558 if may_prompt:
1559 output.prompt_yes_no('Are you sure you wish to continue? (y/N): ')
1560 else:
1561 output.write('Presubmit checks passed.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001562
1563 global _ASKED_FOR_FEEDBACK
1564 # Ask for feedback one time out of 5.
1565 if (len(results) and random.randint(0, 4) == 0 and not _ASKED_FOR_FEEDBACK):
maruel@chromium.org1ce8e662014-01-14 15:23:00 +00001566 output.write(
1567 'Was the presubmit check useful? If not, run "git cl presubmit -v"\n'
1568 'to figure out which PRESUBMIT.py was run, then run git blame\n'
1569 'on the file to figure out who to ask for help.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001570 _ASKED_FOR_FEEDBACK = True
1571 return output
1572 finally:
1573 os.environ = old_environ
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001574
1575
1576def ScanSubDirs(mask, recursive):
1577 if not recursive:
pgervais@chromium.orge57b09d2014-05-07 00:58:13 +00001578 return [x for x in glob.glob(mask) if x not in ('.svn', '.git')]
Lei Zhang9611c4c2017-04-04 01:41:56 -07001579
1580 results = []
1581 for root, dirs, files in os.walk('.'):
1582 if '.svn' in dirs:
1583 dirs.remove('.svn')
1584 if '.git' in dirs:
1585 dirs.remove('.git')
1586 for name in files:
1587 if fnmatch.fnmatch(name, mask):
1588 results.append(os.path.join(root, name))
1589 return results
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001590
1591
1592def ParseFiles(args, recursive):
tobiasjs2836bcf2016-08-16 04:08:16 -07001593 logging.debug('Searching for %s', args)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001594 files = []
1595 for arg in args:
maruel@chromium.orge3608df2009-11-10 20:22:57 +00001596 files.extend([('M', f) for f in ScanSubDirs(arg, recursive)])
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001597 return files
1598
1599
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001600def load_files(options, args):
1601 """Tries to determine the SCM."""
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001602 files = []
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001603 if args:
1604 files = ParseFiles(args, options.recursive)
agable0b65e732016-11-22 09:25:46 -08001605 change_scm = scm.determine_scm(options.root)
1606 if change_scm == 'git':
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001607 change_class = GitChange
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001608 upstream = options.upstream or None
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001609 if not files:
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001610 files = scm.GIT.CaptureStatus([], options.root, upstream)
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001611 else:
tobiasjs2836bcf2016-08-16 04:08:16 -07001612 logging.info('Doesn\'t seem under source control. Got %d files', len(args))
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001613 if not files:
1614 return None, None
1615 change_class = Change
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001616 return change_class, files
1617
1618
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001619@contextlib.contextmanager
1620def canned_check_filter(method_names):
1621 filtered = {}
1622 try:
1623 for method_name in method_names:
1624 if not hasattr(presubmit_canned_checks, method_name):
Aaron Gableecee74c2018-04-02 15:13:08 -07001625 logging.warn('Skipping unknown "canned" check %s' % method_name)
1626 continue
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001627 filtered[method_name] = getattr(presubmit_canned_checks, method_name)
1628 setattr(presubmit_canned_checks, method_name, lambda *_a, **_kw: [])
1629 yield
1630 finally:
1631 for name, method in filtered.iteritems():
1632 setattr(presubmit_canned_checks, name, method)
1633
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001634
sbc@chromium.org013731e2015-02-26 18:28:43 +00001635def main(argv=None):
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001636 parser = optparse.OptionParser(usage="%prog [options] <files...>",
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001637 version="%prog " + str(__version__))
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001638 parser.add_option("-c", "--commit", action="store_true", default=False,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001639 help="Use commit instead of upload checks")
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001640 parser.add_option("-u", "--upload", action="store_false", dest='commit',
1641 help="Use upload instead of commit checks")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001642 parser.add_option("-r", "--recursive", action="store_true",
1643 help="Act recursively")
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001644 parser.add_option("-v", "--verbose", action="count", default=0,
1645 help="Use 2 times for more debug info")
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001646 parser.add_option("--name", default='no name')
maruel@chromium.org58407af2011-04-12 23:15:57 +00001647 parser.add_option("--author")
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001648 parser.add_option("--description", default='')
1649 parser.add_option("--issue", type='int', default=0)
1650 parser.add_option("--patchset", type='int', default=0)
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001651 parser.add_option("--root", default=os.getcwd(),
1652 help="Search for PRESUBMIT.py up to this directory. "
1653 "If inherit-review-settings-ok is present in this "
1654 "directory, parent directories up to the root file "
1655 "system directories will also be searched.")
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001656 parser.add_option("--upstream",
1657 help="Git only: the base ref or upstream branch against "
1658 "which the diff should be computed.")
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001659 parser.add_option("--default_presubmit")
1660 parser.add_option("--may_prompt", action='store_true', default=False)
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001661 parser.add_option("--skip_canned", action='append', default=[],
1662 help="A list of checks to skip which appear in "
1663 "presubmit_canned_checks. Can be provided multiple times "
1664 "to skip multiple canned checks.")
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001665 parser.add_option("--dry_run", action='store_true',
1666 help=optparse.SUPPRESS_HELP)
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001667 parser.add_option("--gerrit_url", help=optparse.SUPPRESS_HELP)
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001668 parser.add_option("--gerrit_fetch", action='store_true',
1669 help=optparse.SUPPRESS_HELP)
Edward Lesmes8e282792018-04-03 18:50:29 -04001670 parser.add_option('--parallel', action='store_true',
1671 help='Run all tests specified by input_api.RunTests in all '
1672 'PRESUBMIT files in parallel.')
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001673
maruel@chromium.org82e5f282011-03-17 14:08:55 +00001674 options, args = parser.parse_args(argv)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001675
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001676 if options.verbose >= 2:
maruel@chromium.org7444c502011-02-09 14:02:11 +00001677 logging.basicConfig(level=logging.DEBUG)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001678 elif options.verbose:
1679 logging.basicConfig(level=logging.INFO)
1680 else:
1681 logging.basicConfig(level=logging.ERROR)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001682
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001683 change_class, files = load_files(options, args)
1684 if not change_class:
1685 parser.error('For unversioned directory, <files> is not optional.')
tobiasjs2836bcf2016-08-16 04:08:16 -07001686 logging.info('Found %d file(s).', len(files))
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001687
Aaron Gable668c1d82018-04-03 10:19:16 -07001688 gerrit_obj = None
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001689 if options.gerrit_url and options.gerrit_fetch:
tandrii@chromium.org83b1b232016-04-29 16:33:19 +00001690 assert options.issue and options.patchset
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001691 gerrit_obj = GerritAccessor(urlparse.urlparse(options.gerrit_url).netloc)
1692 options.author = gerrit_obj.GetChangeOwner(options.issue)
1693 options.description = gerrit_obj.GetChangeDescription(options.issue,
1694 options.patchset)
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001695 logging.info('Got author: "%s"', options.author)
1696 logging.info('Got description: """\n%s\n"""', options.description)
1697
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001698 try:
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001699 with canned_check_filter(options.skip_canned):
1700 results = DoPresubmitChecks(
1701 change_class(options.name,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001702 options.description,
1703 options.root,
1704 files,
1705 options.issue,
1706 options.patchset,
1707 options.author,
1708 upstream=options.upstream),
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001709 options.commit,
1710 options.verbose,
1711 sys.stdout,
1712 sys.stdin,
1713 options.default_presubmit,
1714 options.may_prompt,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001715 gerrit_obj,
Edward Lesmes8e282792018-04-03 18:50:29 -04001716 options.dry_run,
1717 options.parallel)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001718 return not results.should_continue()
1719 except PresubmitFailure, e:
Raul Tambre80ee78e2019-05-06 22:41:05 +00001720 print(e, file=sys.stderr)
1721 print('Maybe your depot_tools is out of date?', file=sys.stderr)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001722 return 2
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001723
1724
1725if __name__ == '__main__':
maruel@chromium.org35625c72011-03-23 17:34:02 +00001726 fix_encoding.fix_encoding()
sbc@chromium.org013731e2015-02-26 18:28:43 +00001727 try:
1728 sys.exit(main())
1729 except KeyboardInterrupt:
1730 sys.stderr.write('interrupted\n')
sergiybf8a3b382016-07-05 11:21:30 -07001731 sys.exit(2)