blob: f945d718dc46939e4cf476dd6c1713c2c87097fc [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
Debrian Figueroadd2737e2019-06-21 23:50:13 +0000306 def json_format(self):
307 return {
308 'message': self._message,
Debrian Figueroa6095d402019-06-28 18:47:18 +0000309 'items': [str(item) for item in self._items],
Debrian Figueroadd2737e2019-06-21 23:50:13 +0000310 'long_text': self._long_text,
311 'fatal': self.fatal
312 }
313
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000314
315# Top level object so multiprocessing can pickle
316# Public access through OutputApi object.
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000317class _PresubmitError(_PresubmitResult):
318 """A hard presubmit error."""
319 fatal = True
320
321
322# Top level object so multiprocessing can pickle
323# Public access through OutputApi object.
324class _PresubmitPromptWarning(_PresubmitResult):
325 """An warning that prompts the user if they want to continue."""
326 should_prompt = True
327
328
329# Top level object so multiprocessing can pickle
330# Public access through OutputApi object.
331class _PresubmitNotifyResult(_PresubmitResult):
332 """Just print something to the screen -- but it's not even a warning."""
333 pass
334
335
336# Top level object so multiprocessing can pickle
337# Public access through OutputApi object.
338class _MailTextResult(_PresubmitResult):
339 """A warning that should be included in the review request email."""
340 def __init__(self, *args, **kwargs):
341 super(_MailTextResult, self).__init__()
342 raise NotImplementedError()
343
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000344class GerritAccessor(object):
345 """Limited Gerrit functionality for canned presubmit checks to work.
346
347 To avoid excessive Gerrit calls, caches the results.
348 """
349
350 def __init__(self, host):
351 self.host = host
352 self.cache = {}
353
354 def _FetchChangeDetail(self, issue):
355 # Separate function to be easily mocked in tests.
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +0100356 try:
357 return gerrit_util.GetChangeDetail(
358 self.host, str(issue),
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700359 ['ALL_REVISIONS', 'DETAILED_LABELS', 'ALL_COMMITS'])
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +0100360 except gerrit_util.GerritError as e:
361 if e.http_status == 404:
362 raise Exception('Either Gerrit issue %s doesn\'t exist, or '
363 'no credentials to fetch issue details' % issue)
364 raise
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000365
366 def GetChangeInfo(self, issue):
367 """Returns labels and all revisions (patchsets) for this issue.
368
369 The result is a dictionary according to Gerrit REST Api.
370 https://gerrit-review.googlesource.com/Documentation/rest-api.html
371
372 However, API isn't very clear what's inside, so see tests for example.
373 """
374 assert issue
375 cache_key = int(issue)
376 if cache_key not in self.cache:
377 self.cache[cache_key] = self._FetchChangeDetail(issue)
378 return self.cache[cache_key]
379
380 def GetChangeDescription(self, issue, patchset=None):
381 """If patchset is none, fetches current patchset."""
382 info = self.GetChangeInfo(issue)
383 # info is a reference to cache. We'll modify it here adding description to
384 # it to the right patchset, if it is not yet there.
385
386 # Find revision info for the patchset we want.
387 if patchset is not None:
388 for rev, rev_info in info['revisions'].iteritems():
389 if str(rev_info['_number']) == str(patchset):
390 break
391 else:
392 raise Exception('patchset %s doesn\'t exist in issue %s' % (
393 patchset, issue))
394 else:
395 rev = info['current_revision']
396 rev_info = info['revisions'][rev]
397
Andrii Shyshkalov9c3a4642017-01-24 17:41:22 +0100398 return rev_info['commit']['message']
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000399
Mun Yong Jang603d01e2017-12-19 16:38:30 -0800400 def GetDestRef(self, issue):
401 ref = self.GetChangeInfo(issue)['branch']
402 if not ref.startswith('refs/'):
403 # NOTE: it is possible to create 'refs/x' branch,
404 # aka 'refs/heads/refs/x'. However, this is ill-advised.
405 ref = 'refs/heads/%s' % ref
406 return ref
407
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000408 def GetChangeOwner(self, issue):
409 return self.GetChangeInfo(issue)['owner']['email']
410
411 def GetChangeReviewers(self, issue, approving_only=True):
Aaron Gable8b478f02017-07-31 15:33:19 -0700412 changeinfo = self.GetChangeInfo(issue)
413 if approving_only:
414 labelinfo = changeinfo.get('labels', {}).get('Code-Review', {})
415 values = labelinfo.get('values', {}).keys()
416 try:
417 max_value = max(int(v) for v in values)
418 reviewers = [r for r in labelinfo.get('all', [])
419 if r.get('value', 0) == max_value]
420 except ValueError: # values is the empty list
421 reviewers = []
422 else:
423 reviewers = changeinfo.get('reviewers', {}).get('REVIEWER', [])
424 return [r.get('email') for r in reviewers]
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000425
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000426
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000427class OutputApi(object):
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000428 """An instance of OutputApi gets passed to presubmit scripts so that they
429 can output various types of results.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000430 """
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000431 PresubmitResult = _PresubmitResult
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000432 PresubmitError = _PresubmitError
433 PresubmitPromptWarning = _PresubmitPromptWarning
434 PresubmitNotifyResult = _PresubmitNotifyResult
435 MailTextResult = _MailTextResult
436
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000437 def __init__(self, is_committing):
438 self.is_committing = is_committing
Daniel Cheng7227d212017-11-17 08:12:37 -0800439 self.more_cc = []
440
441 def AppendCC(self, cc):
442 """Appends a user to cc for this change."""
443 self.more_cc.append(cc)
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000444
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000445 def PresubmitPromptOrNotify(self, *args, **kwargs):
446 """Warn the user when uploading, but only notify if committing."""
447 if self.is_committing:
448 return self.PresubmitNotifyResult(*args, **kwargs)
449 return self.PresubmitPromptWarning(*args, **kwargs)
450
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000451
452class InputApi(object):
453 """An instance of this object is passed to presubmit scripts so they can
454 know stuff about the change they're looking at.
455 """
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000456 # Method could be a function
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800457 # pylint: disable=no-self-use
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000458
maruel@chromium.org3410d912009-06-09 20:56:16 +0000459 # File extensions that are considered source files from a style guide
460 # perspective. Don't modify this list from a presubmit script!
maruel@chromium.orgc33455a2011-06-24 19:14:18 +0000461 #
462 # Files without an extension aren't included in the list. If you want to
463 # filter them as source files, add r"(^|.*?[\\\/])[^.]+$" to the white list.
464 # Note that ALL CAPS files are black listed in DEFAULT_BLACK_LIST below.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000465 DEFAULT_WHITE_LIST = (
466 # C++ and friends
maruel@chromium.orgfe1211a2011-05-28 18:54:17 +0000467 r".+\.c$", r".+\.cc$", r".+\.cpp$", r".+\.h$", r".+\.m$", r".+\.mm$",
468 r".+\.inl$", r".+\.asm$", r".+\.hxx$", r".+\.hpp$", r".+\.s$", r".+\.S$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000469 # Scripts
maruel@chromium.orgfe1211a2011-05-28 18:54:17 +0000470 r".+\.js$", r".+\.py$", r".+\.sh$", r".+\.rb$", r".+\.pl$", r".+\.pm$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000471 # Other
Sergey Ulanov166bc4c2018-04-30 17:03:38 -0700472 r".+\.java$", r".+\.mk$", r".+\.am$", r".+\.css$", r".+\.mojom$",
473 r".+\.fidl$"
maruel@chromium.org3410d912009-06-09 20:56:16 +0000474 )
475
476 # Path regexp that should be excluded from being considered containing source
477 # files. Don't modify this list from a presubmit script!
478 DEFAULT_BLACK_LIST = (
gavinp@chromium.org656326d2012-08-13 00:43:57 +0000479 r"testing_support[\\\/]google_appengine[\\\/].*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000480 r".*\bexperimental[\\\/].*",
Kent Tamura179dd1e2018-04-26 15:07:41 +0900481 # Exclude third_party/.* but NOT third_party/{WebKit,blink}
482 # (crbug.com/539768 and crbug.com/836555).
483 r".*\bthird_party[\\\/](?!(WebKit|blink)[\\\/]).*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000484 # Output directories (just in case)
485 r".*\bDebug[\\\/].*",
486 r".*\bRelease[\\\/].*",
487 r".*\bxcodebuild[\\\/].*",
thakis@chromium.orgc1c96352013-10-09 19:50:27 +0000488 r".*\bout[\\\/].*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000489 # All caps files like README and LICENCE.
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000490 r".*\b[A-Z0-9_]{2,}$",
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000491 # SCM (can happen in dual SCM configuration). (Slightly over aggressive)
maruel@chromium.org5d0dc432011-01-03 02:40:37 +0000492 r"(|.*[\\\/])\.git[\\\/].*",
493 r"(|.*[\\\/])\.svn[\\\/].*",
maruel@chromium.org7ccb4bb2011-11-07 20:26:20 +0000494 # There is no point in processing a patch file.
495 r".+\.diff$",
496 r".+\.patch$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000497 )
498
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000499 def __init__(self, change, presubmit_path, is_committing,
Edward Lesmes8e282792018-04-03 18:50:29 -0400500 verbose, gerrit_obj, dry_run=None, thread_pool=None, parallel=False):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000501 """Builds an InputApi object.
502
503 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000504 change: A presubmit.Change object.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000505 presubmit_path: The path to the presubmit script being processed.
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000506 is_committing: True if the change is about to be committed.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000507 gerrit_obj: provides basic Gerrit codereview functionality.
508 dry_run: if true, some Checks will be skipped.
Edward Lesmes8e282792018-04-03 18:50:29 -0400509 parallel: if true, all tests reported via input_api.RunTests for all
510 PRESUBMIT files will be run in parallel.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000511 """
maruel@chromium.org9711bba2009-05-22 23:51:39 +0000512 # Version number of the presubmit_support script.
513 self.version = [int(x) for x in __version__.split('.')]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000514 self.change = change
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000515 self.is_committing = is_committing
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000516 self.gerrit = gerrit_obj
tandrii@chromium.org57bafac2016-04-28 05:09:03 +0000517 self.dry_run = dry_run
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000518
Edward Lesmes8e282792018-04-03 18:50:29 -0400519 self.parallel = parallel
520 self.thread_pool = thread_pool or ThreadPool()
521
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000522 # We expose various modules and functions as attributes of the input_api
523 # so that presubmit scripts don't have to import them.
Takeshi Yoshino07a6bea2017-08-02 02:44:06 +0900524 self.ast = ast
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000525 self.basename = os.path.basename
526 self.cPickle = cPickle
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000527 self.cpplint = cpplint
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000528 self.cStringIO = cStringIO
dcheng091b7db2016-06-16 01:27:51 -0700529 self.fnmatch = fnmatch
Yoshisato Yanagisawa04600b42019-03-15 03:03:41 +0000530 self.gclient_paths = gclient_paths
Yoshisato Yanagisawa57dd17b2019-03-22 09:10:29 +0000531 # TODO(yyanagisawa): stop exposing this when python3 become default.
532 # Since python3's tempfile has TemporaryDirectory, we do not need this.
533 self.temporary_directory = gclient_utils.temporary_directory
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000534 self.glob = glob.glob
maruel@chromium.orgfb11c7b2010-03-18 18:22:14 +0000535 self.json = json
maruel@chromium.org6fba34d2011-06-02 13:45:12 +0000536 self.logging = logging.getLogger('PRESUBMIT')
Yoshisato Yanagisawa406de132018-06-29 05:43:25 +0000537 self.marshal = marshal
maruel@chromium.org2b5ce562011-03-31 16:15:44 +0000538 self.os_listdir = os.listdir
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000539 self.os_path = os.path
pgervais@chromium.orgbd0cace2014-10-02 23:23:46 +0000540 self.os_stat = os.stat
Yoshisato Yanagisawa406de132018-06-29 05:43:25 +0000541 self.os_walk = os.walk
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000542 self.pickle = pickle
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000543 self.re = re
544 self.subprocess = subprocess
545 self.tempfile = tempfile
dpranke@chromium.org0d1bdea2011-03-24 22:54:38 +0000546 self.time = time
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000547 self.traceback = traceback
maruel@chromium.org1487d532009-06-06 00:22:57 +0000548 self.unittest = unittest
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000549 self.urllib2 = urllib2
550
Robert Iannucci50258932018-03-19 10:30:59 -0700551 self.is_windows = sys.platform == 'win32'
552
553 # Set python_executable to 'python'. This is interpreted in CallCommand to
554 # convert to vpython in order to allow scripts in other repos (e.g. src.git)
555 # to automatically pick up that repo's .vpython file, instead of inheriting
556 # the one in depot_tools.
557 self.python_executable = 'python'
maruel@chromium.orgc0b22972009-06-25 16:19:14 +0000558 self.environ = os.environ
559
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000560 # InputApi.platform is the platform you're currently running on.
561 self.platform = sys.platform
562
iannucci@chromium.org0af3bb32015-06-12 20:44:35 +0000563 self.cpu_count = multiprocessing.cpu_count()
564
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000565 # The local path of the currently-being-processed presubmit script.
maruel@chromium.org3d235242009-05-15 12:40:48 +0000566 self._current_presubmit_path = os.path.dirname(presubmit_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000567
568 # We carry the canned checks so presubmit scripts can easily use them.
569 self.canned_checks = presubmit_canned_checks
570
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +0100571 # Temporary files we must manually remove at the end of a run.
572 self._named_temporary_files = []
Jochen Eisinger72606f82017-04-04 10:44:18 +0200573
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000574 # TODO(dpranke): figure out a list of all approved owners for a repo
575 # in order to be able to handle wildcard OWNERS files?
576 self.owners_db = owners.Database(change.RepositoryRoot(),
Jochen Eisinger72606f82017-04-04 10:44:18 +0200577 fopen=file, os_path=self.os_path)
Jochen Eisinger76f5fc62017-04-07 16:27:46 +0200578 self.owners_finder = owners_finder.OwnersFinder
maruel@chromium.org899e1c12011-04-07 17:03:18 +0000579 self.verbose = verbose
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000580 self.Command = CommandData
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000581
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000582 # Replace <hash_map> and <hash_set> as headers that need to be included
danakj@chromium.org18278522013-06-11 22:42:32 +0000583 # with "base/containers/hash_tables.h" instead.
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000584 # Access to a protected member _XX of a client class
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800585 # pylint: disable=protected-access
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000586 self.cpplint._re_pattern_templates = [
danakj@chromium.org18278522013-06-11 22:42:32 +0000587 (a, b, 'base/containers/hash_tables.h')
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000588 if header in ('<hash_map>', '<hash_set>') else (a, b, header)
589 for (a, b, header) in cpplint._re_pattern_templates
590 ]
591
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000592 def PresubmitLocalPath(self):
593 """Returns the local path of the presubmit script currently being run.
594
595 This is useful if you don't want to hard-code absolute paths in the
596 presubmit script. For example, It can be used to find another file
597 relative to the PRESUBMIT.py script, so the whole tree can be branched and
598 the presubmit script still works, without editing its content.
599 """
maruel@chromium.org3d235242009-05-15 12:40:48 +0000600 return self._current_presubmit_path
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000601
agable0b65e732016-11-22 09:25:46 -0800602 def AffectedFiles(self, include_deletes=True, file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000603 """Same as input_api.change.AffectedFiles() except only lists files
604 (and optionally directories) in the same directory as the current presubmit
605 script, or subdirectories thereof.
606 """
maruel@chromium.org3d235242009-05-15 12:40:48 +0000607 dir_with_slash = normpath("%s/" % self.PresubmitLocalPath())
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000608 if len(dir_with_slash) == 1:
609 dir_with_slash = ''
sail@chromium.org5538e022011-05-12 17:53:16 +0000610
maruel@chromium.org4661e0c2009-06-04 00:45:26 +0000611 return filter(
612 lambda x: normpath(x.AbsoluteLocalPath()).startswith(dir_with_slash),
agable0b65e732016-11-22 09:25:46 -0800613 self.change.AffectedFiles(include_deletes, file_filter))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000614
agable0b65e732016-11-22 09:25:46 -0800615 def LocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000616 """Returns local paths of input_api.AffectedFiles()."""
agable0b65e732016-11-22 09:25:46 -0800617 paths = [af.LocalPath() for af in self.AffectedFiles()]
pgervais@chromium.org2f64f782014-04-25 00:12:33 +0000618 logging.debug("LocalPaths: %s", paths)
619 return paths
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000620
agable0b65e732016-11-22 09:25:46 -0800621 def AbsoluteLocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000622 """Returns absolute local paths of input_api.AffectedFiles()."""
agable0b65e732016-11-22 09:25:46 -0800623 return [af.AbsoluteLocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000624
John Budorick16162372018-04-18 10:39:53 -0700625 def AffectedTestableFiles(self, include_deletes=None, **kwargs):
agable0b65e732016-11-22 09:25:46 -0800626 """Same as input_api.change.AffectedTestableFiles() except only lists files
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000627 in the same directory as the current presubmit script, or subdirectories
628 thereof.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000629 """
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000630 if include_deletes is not None:
agable0b65e732016-11-22 09:25:46 -0800631 warn("AffectedTestableFiles(include_deletes=%s)"
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000632 " is deprecated and ignored" % str(include_deletes),
633 category=DeprecationWarning,
634 stacklevel=2)
agable0b65e732016-11-22 09:25:46 -0800635 return filter(lambda x: x.IsTestableFile(),
John Budorick16162372018-04-18 10:39:53 -0700636 self.AffectedFiles(include_deletes=False, **kwargs))
agable0b65e732016-11-22 09:25:46 -0800637
638 def AffectedTextFiles(self, include_deletes=None):
639 """An alias to AffectedTestableFiles for backwards compatibility."""
640 return self.AffectedTestableFiles(include_deletes=include_deletes)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000641
maruel@chromium.org3410d912009-06-09 20:56:16 +0000642 def FilterSourceFile(self, affected_file, white_list=None, black_list=None):
643 """Filters out files that aren't considered "source file".
644
645 If white_list or black_list is None, InputApi.DEFAULT_WHITE_LIST
646 and InputApi.DEFAULT_BLACK_LIST is used respectively.
647
648 The lists will be compiled as regular expression and
649 AffectedFile.LocalPath() needs to pass both list.
650
651 Note: Copy-paste this function to suit your needs or use a lambda function.
652 """
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000653 def Find(affected_file, items):
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000654 local_path = affected_file.LocalPath()
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000655 for item in items:
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000656 if self.re.match(item, local_path):
maruel@chromium.org3410d912009-06-09 20:56:16 +0000657 return True
658 return False
659 return (Find(affected_file, white_list or self.DEFAULT_WHITE_LIST) and
660 not Find(affected_file, black_list or self.DEFAULT_BLACK_LIST))
661
662 def AffectedSourceFiles(self, source_file):
agable0b65e732016-11-22 09:25:46 -0800663 """Filter the list of AffectedTestableFiles by the function source_file.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000664
665 If source_file is None, InputApi.FilterSourceFile() is used.
666 """
667 if not source_file:
668 source_file = self.FilterSourceFile
agable0b65e732016-11-22 09:25:46 -0800669 return filter(source_file, self.AffectedTestableFiles())
maruel@chromium.org3410d912009-06-09 20:56:16 +0000670
671 def RightHandSideLines(self, source_file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000672 """An iterator over all text lines in "new" version of changed files.
673
674 Only lists lines from new or modified text files in the change that are
675 contained by the directory of the currently executing presubmit script.
676
677 This is useful for doing line-by-line regex checks, like checking for
678 trailing whitespace.
679
680 Yields:
681 a 3 tuple:
682 the AffectedFile instance of the current file;
683 integer line number (1-based); and
684 the contents of the line as a string.
maruel@chromium.org1487d532009-06-06 00:22:57 +0000685
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000686 Note: The carriage return (LF or CR) is stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000687 """
maruel@chromium.org3410d912009-06-09 20:56:16 +0000688 files = self.AffectedSourceFiles(source_file_filter)
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000689 return _RightHandSideLinesImpl(files)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000690
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000691 def ReadFile(self, file_item, mode='r'):
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000692 """Reads an arbitrary file.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000693
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000694 Deny reading anything outside the repository.
695 """
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000696 if isinstance(file_item, AffectedFile):
697 file_item = file_item.AbsoluteLocalPath()
698 if not file_item.startswith(self.change.RepositoryRoot()):
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000699 raise IOError('Access outside the repository root is denied.')
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000700 return gclient_utils.FileRead(file_item, mode)
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000701
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +0100702 def CreateTemporaryFile(self, **kwargs):
703 """Returns a named temporary file that must be removed with a call to
704 RemoveTemporaryFiles().
705
706 All keyword arguments are forwarded to tempfile.NamedTemporaryFile(),
707 except for |delete|, which is always set to False.
708
709 Presubmit checks that need to create a temporary file and pass it for
710 reading should use this function instead of NamedTemporaryFile(), as
711 Windows fails to open a file that is already open for writing.
712
713 with input_api.CreateTemporaryFile() as f:
714 f.write('xyz')
715 f.close()
716 input_api.subprocess.check_output(['script-that', '--reads-from',
717 f.name])
718
719
720 Note that callers of CreateTemporaryFile() should not worry about removing
721 any temporary file; this is done transparently by the presubmit handling
722 code.
723 """
724 if 'delete' in kwargs:
725 # Prevent users from passing |delete|; we take care of file deletion
726 # ourselves and this prevents unintuitive error messages when we pass
727 # delete=False and 'delete' is also in kwargs.
728 raise TypeError('CreateTemporaryFile() does not take a "delete" '
729 'argument, file deletion is handled automatically by '
730 'the same presubmit_support code that creates InputApi '
731 'objects.')
732 temp_file = self.tempfile.NamedTemporaryFile(delete=False, **kwargs)
733 self._named_temporary_files.append(temp_file.name)
734 return temp_file
735
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000736 @property
737 def tbr(self):
738 """Returns if a change is TBR'ed."""
Jeremy Romandce22502017-06-20 15:37:29 -0400739 return 'TBR' in self.change.tags or self.change.TBRsFromDescription()
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000740
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +0000741 def RunTests(self, tests_mix, parallel=True):
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000742 tests = []
743 msgs = []
744 for t in tests_mix:
Edward Lesmes8e282792018-04-03 18:50:29 -0400745 if isinstance(t, OutputApi.PresubmitResult) and t:
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000746 msgs.append(t)
747 else:
748 assert issubclass(t.message, _PresubmitResult)
749 tests.append(t)
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +0000750 if self.verbose:
751 t.info = _PresubmitNotifyResult
Edward Lemur1037c742018-05-01 18:56:04 -0400752 if not t.kwargs.get('cwd'):
753 t.kwargs['cwd'] = self.PresubmitLocalPath()
Edward Lesmes8e282792018-04-03 18:50:29 -0400754 self.thread_pool.AddTests(tests, parallel)
Edward Lemur21000eb2019-05-24 23:25:58 +0000755 # When self.parallel is True (i.e. --parallel is passed as an option)
756 # RunTests doesn't actually run tests. It adds them to a ThreadPool that
757 # will run all tests once all PRESUBMIT files are processed.
758 # Otherwise, it will run them and return the results.
759 if not self.parallel:
Edward Lesmes8e282792018-04-03 18:50:29 -0400760 msgs.extend(self.thread_pool.RunAsync())
761 return msgs
scottmg86099d72016-09-01 09:16:51 -0700762
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000763
nick@chromium.orgff526192013-06-10 19:30:26 +0000764class _DiffCache(object):
765 """Caches diffs retrieved from a particular SCM."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000766 def __init__(self, upstream=None):
767 """Stores the upstream revision against which all diffs will be computed."""
768 self._upstream = upstream
nick@chromium.orgff526192013-06-10 19:30:26 +0000769
770 def GetDiff(self, path, local_root):
771 """Get the diff for a particular path."""
772 raise NotImplementedError()
773
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700774 def GetOldContents(self, path, local_root):
775 """Get the old version for a particular path."""
776 raise NotImplementedError()
777
nick@chromium.orgff526192013-06-10 19:30:26 +0000778
nick@chromium.orgff526192013-06-10 19:30:26 +0000779class _GitDiffCache(_DiffCache):
780 """DiffCache implementation for git; gets all file diffs at once."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000781 def __init__(self, upstream):
782 super(_GitDiffCache, self).__init__(upstream=upstream)
nick@chromium.orgff526192013-06-10 19:30:26 +0000783 self._diffs_by_file = None
784
785 def GetDiff(self, path, local_root):
786 if not self._diffs_by_file:
787 # Compute a single diff for all files and parse the output; should
788 # with git this is much faster than computing one diff for each file.
789 diffs = {}
790
791 # Don't specify any filenames below, because there are command line length
792 # limits on some platforms and GenerateDiff would fail.
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000793 unified_diff = scm.GIT.GenerateDiff(local_root, files=[], full_move=True,
794 branch=self._upstream)
nick@chromium.orgff526192013-06-10 19:30:26 +0000795
796 # This regex matches the path twice, separated by a space. Note that
797 # filename itself may contain spaces.
798 file_marker = re.compile('^diff --git (?P<filename>.*) (?P=filename)$')
799 current_diff = []
800 keep_line_endings = True
801 for x in unified_diff.splitlines(keep_line_endings):
802 match = file_marker.match(x)
803 if match:
804 # Marks the start of a new per-file section.
805 diffs[match.group('filename')] = current_diff = [x]
806 elif x.startswith('diff --git'):
807 raise PresubmitFailure('Unexpected diff line: %s' % x)
808 else:
809 current_diff.append(x)
810
811 self._diffs_by_file = dict(
812 (normpath(path), ''.join(diff)) for path, diff in diffs.items())
813
814 if path not in self._diffs_by_file:
815 raise PresubmitFailure(
816 'Unified diff did not contain entry for file %s' % path)
817
818 return self._diffs_by_file[path]
819
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700820 def GetOldContents(self, path, local_root):
821 return scm.GIT.GetOldContents(local_root, path, branch=self._upstream)
822
nick@chromium.orgff526192013-06-10 19:30:26 +0000823
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000824class AffectedFile(object):
825 """Representation of a file in a change."""
nick@chromium.orgff526192013-06-10 19:30:26 +0000826
827 DIFF_CACHE = _DiffCache
828
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000829 # Method could be a function
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800830 # pylint: disable=no-self-use
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000831 def __init__(self, path, action, repository_root, diff_cache):
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000832 self._path = path
833 self._action = action
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000834 self._local_root = repository_root
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000835 self._is_directory = None
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000836 self._cached_changed_contents = None
837 self._cached_new_contents = None
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000838 self._diff_cache = diff_cache
tobiasjs2836bcf2016-08-16 04:08:16 -0700839 logging.debug('%s(%s)', self.__class__.__name__, self._path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000840
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000841 def LocalPath(self):
842 """Returns the path of this file on the local disk relative to client root.
Andrew Grieve92b8b992017-11-02 09:42:24 -0400843
844 This should be used for error messages but not for accessing files,
845 because presubmit checks are run with CWD=PresubmitLocalPath() (which is
846 often != client root).
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000847 """
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000848 return normpath(self._path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000849
850 def AbsoluteLocalPath(self):
851 """Returns the absolute path of this file on the local disk.
852 """
chase@chromium.org8e416c82009-10-06 04:30:44 +0000853 return os.path.abspath(os.path.join(self._local_root, self.LocalPath()))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000854
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000855 def Action(self):
856 """Returns the action on this opened file, e.g. A, M, D, etc."""
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000857 return self._action
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000858
agable0b65e732016-11-22 09:25:46 -0800859 def IsTestableFile(self):
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000860 """Returns True if the file is a text file and not a binary file.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000861
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000862 Deleted files are not text file."""
maruel@chromium.org1e08c002009-05-28 19:09:33 +0000863 raise NotImplementedError() # Implement when needed
864
agable0b65e732016-11-22 09:25:46 -0800865 def IsTextFile(self):
866 """An alias to IsTestableFile for backwards compatibility."""
867 return self.IsTestableFile()
868
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700869 def OldContents(self):
870 """Returns an iterator over the lines in the old version of file.
871
Daniel Cheng2da34fe2017-03-21 20:42:12 -0700872 The old version is the file before any modifications in the user's
873 workspace, i.e. the "left hand side".
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700874
875 Contents will be empty if the file is a directory or does not exist.
876 Note: The carriage returns (LF or CR) are stripped off.
877 """
878 return self._diff_cache.GetOldContents(self.LocalPath(),
879 self._local_root).splitlines()
880
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000881 def NewContents(self):
882 """Returns an iterator over the lines in the new version of file.
883
884 The new version is the file in the user's workspace, i.e. the "right hand
885 side".
886
887 Contents will be empty if the file is a directory or does not exist.
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000888 Note: The carriage returns (LF or CR) are stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000889 """
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000890 if self._cached_new_contents is None:
891 self._cached_new_contents = []
agable0b65e732016-11-22 09:25:46 -0800892 try:
893 self._cached_new_contents = gclient_utils.FileRead(
894 self.AbsoluteLocalPath(), 'rU').splitlines()
895 except IOError:
896 pass # File not found? That's fine; maybe it was deleted.
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000897 return self._cached_new_contents[:]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000898
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000899 def ChangedContents(self):
900 """Returns a list of tuples (line number, line text) of all new lines.
901
902 This relies on the scm diff output describing each changed code section
903 with a line of the form
904
905 ^@@ <old line num>,<old size> <new line num>,<new size> @@$
906 """
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000907 if self._cached_changed_contents is not None:
908 return self._cached_changed_contents[:]
909 self._cached_changed_contents = []
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000910 line_num = 0
911
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000912 for line in self.GenerateScmDiff().splitlines():
913 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
914 if m:
915 line_num = int(m.groups(1)[0])
916 continue
917 if line.startswith('+') and not line.startswith('++'):
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000918 self._cached_changed_contents.append((line_num, line[1:]))
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000919 if not line.startswith('-'):
920 line_num += 1
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000921 return self._cached_changed_contents[:]
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000922
maruel@chromium.org5de13972009-06-10 18:16:06 +0000923 def __str__(self):
924 return self.LocalPath()
925
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000926 def GenerateScmDiff(self):
nick@chromium.orgff526192013-06-10 19:30:26 +0000927 return self._diff_cache.GetDiff(self.LocalPath(), self._local_root)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000928
maruel@chromium.org58407af2011-04-12 23:15:57 +0000929
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000930class GitAffectedFile(AffectedFile):
931 """Representation of a file in a change out of a git checkout."""
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000932 # Method 'NNN' is abstract in class 'NNN' but is not overridden
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800933 # pylint: disable=abstract-method
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000934
nick@chromium.orgff526192013-06-10 19:30:26 +0000935 DIFF_CACHE = _GitDiffCache
936
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000937 def __init__(self, *args, **kwargs):
938 AffectedFile.__init__(self, *args, **kwargs)
939 self._server_path = None
agable0b65e732016-11-22 09:25:46 -0800940 self._is_testable_file = None
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000941
agable0b65e732016-11-22 09:25:46 -0800942 def IsTestableFile(self):
943 if self._is_testable_file is None:
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000944 if self.Action() == 'D':
agable0b65e732016-11-22 09:25:46 -0800945 # A deleted file is not testable.
946 self._is_testable_file = False
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000947 else:
agable0b65e732016-11-22 09:25:46 -0800948 self._is_testable_file = os.path.isfile(self.AbsoluteLocalPath())
949 return self._is_testable_file
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000950
maruel@chromium.orgc1938752011-04-12 23:11:13 +0000951
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000952class Change(object):
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000953 """Describe a change.
954
955 Used directly by the presubmit scripts to query the current change being
956 tested.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000957
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000958 Instance members:
nick@chromium.orgff526192013-06-10 19:30:26 +0000959 tags: Dictionary of KEY=VALUE pairs found in the change description.
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000960 self.KEY: equivalent to tags['KEY']
961 """
962
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000963 _AFFECTED_FILES = AffectedFile
964
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000965 # Matches key/value (or "tag") lines in changelist descriptions.
maruel@chromium.org428342a2011-11-10 15:46:33 +0000966 TAG_LINE_RE = re.compile(
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +0000967 '^[ \t]*(?P<key>[A-Z][A-Z_0-9]*)[ \t]*=[ \t]*(?P<value>.*?)[ \t]*$')
maruel@chromium.orgc1938752011-04-12 23:11:13 +0000968 scm = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000969
maruel@chromium.org58407af2011-04-12 23:15:57 +0000970 def __init__(
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000971 self, name, description, local_root, files, issue, patchset, author,
972 upstream=None):
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000973 if files is None:
974 files = []
975 self._name = name
chase@chromium.org8e416c82009-10-06 04:30:44 +0000976 # Convert root into an absolute path.
977 self._local_root = os.path.abspath(local_root)
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000978 self._upstream = upstream
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000979 self.issue = issue
980 self.patchset = patchset
maruel@chromium.org58407af2011-04-12 23:15:57 +0000981 self.author_email = author
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000982
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000983 self._full_description = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000984 self.tags = {}
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000985 self._description_without_tags = ''
986 self.SetDescriptionText(description)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000987
maruel@chromium.orge085d812011-10-10 19:49:15 +0000988 assert all(
989 (isinstance(f, (list, tuple)) and len(f) == 2) for f in files), files
990
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000991 diff_cache = self._AFFECTED_FILES.DIFF_CACHE(self._upstream)
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000992 self._affected_files = [
nick@chromium.orgff526192013-06-10 19:30:26 +0000993 self._AFFECTED_FILES(path, action.strip(), self._local_root, diff_cache)
994 for action, path in files
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000995 ]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000996
maruel@chromium.org92022ec2009-06-11 01:59:28 +0000997 def Name(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000998 """Returns the change name."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000999 return self._name
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001000
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001001 def DescriptionText(self):
1002 """Returns the user-entered changelist description, minus tags.
1003
1004 Any line in the user-provided description starting with e.g. "FOO="
1005 (whitespace permitted before and around) is considered a tag line. Such
1006 lines are stripped out of the description this function returns.
1007 """
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001008 return self._description_without_tags
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001009
1010 def FullDescriptionText(self):
1011 """Returns the complete changelist description including tags."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001012 return self._full_description
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001013
isherman@chromium.orgb5cded62014-03-25 17:47:57 +00001014 def SetDescriptionText(self, description):
1015 """Sets the full description text (including tags) to |description|.
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001016
isherman@chromium.orgb5cded62014-03-25 17:47:57 +00001017 Also updates the list of tags."""
1018 self._full_description = description
1019
1020 # From the description text, build up a dictionary of key/value pairs
1021 # plus the description minus all key/value or "tag" lines.
1022 description_without_tags = []
1023 self.tags = {}
1024 for line in self._full_description.splitlines():
1025 m = self.TAG_LINE_RE.match(line)
1026 if m:
1027 self.tags[m.group('key')] = m.group('value')
1028 else:
1029 description_without_tags.append(line)
1030
1031 # Change back to text and remove whitespace at end.
1032 self._description_without_tags = (
1033 '\n'.join(description_without_tags).rstrip())
1034
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001035 def RepositoryRoot(self):
maruel@chromium.org92022ec2009-06-11 01:59:28 +00001036 """Returns the repository (checkout) root directory for this change,
1037 as an absolute path.
1038 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001039 return self._local_root
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001040
1041 def __getattr__(self, attr):
maruel@chromium.org92022ec2009-06-11 01:59:28 +00001042 """Return tags directly as attributes on the object."""
1043 if not re.match(r"^[A-Z_]*$", attr):
1044 raise AttributeError(self, attr)
maruel@chromium.orge1a524f2009-05-27 14:43:46 +00001045 return self.tags.get(attr)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001046
Aaron Gablefc03e672017-05-15 14:09:42 -07001047 def BugsFromDescription(self):
1048 """Returns all bugs referenced in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -07001049 tags = [b.strip() for b in self.tags.get('BUG', '').split(',') if b.strip()]
Caleb Rouleauc0546b92019-02-22 06:12:57 +00001050 footers = []
1051 unsplit_footers = git_footers.parse_footers(self._full_description).get(
1052 'Bug', [])
1053 for unsplit_footer in unsplit_footers:
1054 footers += [b.strip() for b in unsplit_footer.split(',')]
Aaron Gable12ef5012017-05-15 14:29:00 -07001055 return sorted(set(tags + footers))
Aaron Gablefc03e672017-05-15 14:09:42 -07001056
1057 def ReviewersFromDescription(self):
1058 """Returns all reviewers listed in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -07001059 # We don't support a "R:" git-footer for reviewers; that is in metadata.
1060 tags = [r.strip() for r in self.tags.get('R', '').split(',') if r.strip()]
1061 return sorted(set(tags))
Aaron Gablefc03e672017-05-15 14:09:42 -07001062
1063 def TBRsFromDescription(self):
1064 """Returns all TBR reviewers listed in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -07001065 tags = [r.strip() for r in self.tags.get('TBR', '').split(',') if r.strip()]
1066 # TODO(agable): Remove support for 'Tbr:' when TBRs are programmatically
1067 # determined by self-CR+1s.
1068 footers = git_footers.parse_footers(self._full_description).get('Tbr', [])
1069 return sorted(set(tags + footers))
Aaron Gablefc03e672017-05-15 14:09:42 -07001070
1071 # TODO(agable): Delete these once we're sure they're unused.
1072 @property
1073 def BUG(self):
1074 return ','.join(self.BugsFromDescription())
1075 @property
1076 def R(self):
1077 return ','.join(self.ReviewersFromDescription())
1078 @property
1079 def TBR(self):
1080 return ','.join(self.TBRsFromDescription())
1081
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001082 def AllFiles(self, root=None):
1083 """List all files under source control in the repo."""
1084 raise NotImplementedError()
1085
agable0b65e732016-11-22 09:25:46 -08001086 def AffectedFiles(self, include_deletes=True, file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001087 """Returns a list of AffectedFile instances for all files in the change.
1088
1089 Args:
1090 include_deletes: If false, deleted files will be filtered out.
sail@chromium.org5538e022011-05-12 17:53:16 +00001091 file_filter: An additional filter to apply.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001092
1093 Returns:
1094 [AffectedFile(path, action), AffectedFile(path, action)]
1095 """
agable0b65e732016-11-22 09:25:46 -08001096 affected = filter(file_filter, self._affected_files)
sail@chromium.org5538e022011-05-12 17:53:16 +00001097
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001098 if include_deletes:
1099 return affected
Lei Zhang9611c4c2017-04-04 01:41:56 -07001100 return filter(lambda x: x.Action() != 'D', affected)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001101
John Budorick16162372018-04-18 10:39:53 -07001102 def AffectedTestableFiles(self, include_deletes=None, **kwargs):
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +00001103 """Return a list of the existing text files in a change."""
1104 if include_deletes is not None:
agable0b65e732016-11-22 09:25:46 -08001105 warn("AffectedTeestableFiles(include_deletes=%s)"
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +00001106 " is deprecated and ignored" % str(include_deletes),
1107 category=DeprecationWarning,
1108 stacklevel=2)
agable0b65e732016-11-22 09:25:46 -08001109 return filter(lambda x: x.IsTestableFile(),
John Budorick16162372018-04-18 10:39:53 -07001110 self.AffectedFiles(include_deletes=False, **kwargs))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001111
agable0b65e732016-11-22 09:25:46 -08001112 def AffectedTextFiles(self, include_deletes=None):
1113 """An alias to AffectedTestableFiles for backwards compatibility."""
1114 return self.AffectedTestableFiles(include_deletes=include_deletes)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001115
agable0b65e732016-11-22 09:25:46 -08001116 def LocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001117 """Convenience function."""
agable0b65e732016-11-22 09:25:46 -08001118 return [af.LocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001119
agable0b65e732016-11-22 09:25:46 -08001120 def AbsoluteLocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001121 """Convenience function."""
agable0b65e732016-11-22 09:25:46 -08001122 return [af.AbsoluteLocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001123
1124 def RightHandSideLines(self):
1125 """An iterator over all text lines in "new" version of changed files.
1126
1127 Lists lines from new or modified text files in the change.
1128
1129 This is useful for doing line-by-line regex checks, like checking for
1130 trailing whitespace.
1131
1132 Yields:
1133 a 3 tuple:
1134 the AffectedFile instance of the current file;
1135 integer line number (1-based); and
1136 the contents of the line as a string.
1137 """
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +00001138 return _RightHandSideLinesImpl(
1139 x for x in self.AffectedFiles(include_deletes=False)
agable0b65e732016-11-22 09:25:46 -08001140 if x.IsTestableFile())
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001141
Jochen Eisingerd0573ec2017-04-13 10:55:06 +02001142 def OriginalOwnersFiles(self):
1143 """A map from path names of affected OWNERS files to their old content."""
1144 def owners_file_filter(f):
1145 return 'OWNERS' in os.path.split(f.LocalPath())[1]
1146 files = self.AffectedFiles(file_filter=owners_file_filter)
1147 return dict([(f.LocalPath(), f.OldContents()) for f in files])
1148
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001149
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001150class GitChange(Change):
1151 _AFFECTED_FILES = GitAffectedFile
maruel@chromium.orgc1938752011-04-12 23:11:13 +00001152 scm = 'git'
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +00001153
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001154 def AllFiles(self, root=None):
1155 """List all files under source control in the repo."""
1156 root = root or self.RepositoryRoot()
1157 return subprocess.check_output(
Aaron Gable7817f022017-12-12 09:43:17 -08001158 ['git', '-c', 'core.quotePath=false', 'ls-files', '--', '.'],
1159 cwd=root).splitlines()
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001160
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001161
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001162def ListRelevantPresubmitFiles(files, root):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001163 """Finds all presubmit files that apply to a given set of source files.
1164
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001165 If inherit-review-settings-ok is present right under root, looks for
1166 PRESUBMIT.py in directories enclosing root.
1167
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001168 Args:
1169 files: An iterable container containing file paths.
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001170 root: Path where to stop searching.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001171
1172 Return:
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001173 List of absolute paths of the existing PRESUBMIT.py scripts.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001174 """
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001175 files = [normpath(os.path.join(root, f)) for f in files]
1176
1177 # List all the individual directories containing files.
1178 directories = set([os.path.dirname(f) for f in files])
1179
1180 # Ignore root if inherit-review-settings-ok is present.
1181 if os.path.isfile(os.path.join(root, 'inherit-review-settings-ok')):
1182 root = None
1183
1184 # Collect all unique directories that may contain PRESUBMIT.py.
1185 candidates = set()
1186 for directory in directories:
1187 while True:
1188 if directory in candidates:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001189 break
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001190 candidates.add(directory)
1191 if directory == root:
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001192 break
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001193 parent_dir = os.path.dirname(directory)
1194 if parent_dir == directory:
1195 # We hit the system root directory.
1196 break
1197 directory = parent_dir
1198
1199 # Look for PRESUBMIT.py in all candidate directories.
1200 results = []
1201 for directory in sorted(list(candidates)):
tobiasjsff061c02016-08-17 03:23:57 -07001202 try:
1203 for f in os.listdir(directory):
1204 p = os.path.join(directory, f)
1205 if os.path.isfile(p) and re.match(
1206 r'PRESUBMIT.*\.py$', f) and not f.startswith('PRESUBMIT_test'):
1207 results.append(p)
1208 except OSError:
1209 pass
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001210
tobiasjs2836bcf2016-08-16 04:08:16 -07001211 logging.debug('Presubmit files: %s', ','.join(results))
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001212 return results
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001213
1214
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001215class GetTryMastersExecuter(object):
1216 @staticmethod
1217 def ExecPresubmitScript(script_text, presubmit_path, project, change):
1218 """Executes GetPreferredTryMasters() from a single presubmit script.
1219
1220 Args:
1221 script_text: The text of the presubmit script.
1222 presubmit_path: Project script to run.
1223 project: Project name to pass to presubmit script for bot selection.
1224
1225 Return:
1226 A map of try masters to map of builders to set of tests.
1227 """
1228 context = {}
1229 try:
Raul Tambre09e64b42019-05-14 01:57:22 +00001230 exec(compile(script_text, 'PRESUBMIT.py', 'exec', dont_inherit=True),
1231 context)
Raul Tambre7c938462019-05-24 16:35:35 +00001232 except Exception as e:
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001233 raise PresubmitFailure('"%s" had an exception.\n%s'
1234 % (presubmit_path, e))
1235
1236 function_name = 'GetPreferredTryMasters'
1237 if function_name not in context:
1238 return {}
1239 get_preferred_try_masters = context[function_name]
1240 if not len(inspect.getargspec(get_preferred_try_masters)[0]) == 2:
1241 raise PresubmitFailure(
1242 'Expected function "GetPreferredTryMasters" to take two arguments.')
1243 return get_preferred_try_masters(project, change)
1244
1245
rmistry@google.com5626a922015-02-26 14:03:30 +00001246class GetPostUploadExecuter(object):
1247 @staticmethod
1248 def ExecPresubmitScript(script_text, presubmit_path, cl, change):
1249 """Executes PostUploadHook() from a single presubmit script.
1250
1251 Args:
1252 script_text: The text of the presubmit script.
1253 presubmit_path: Project script to run.
1254 cl: The Changelist object.
1255 change: The Change object.
1256
1257 Return:
1258 A list of results objects.
1259 """
1260 context = {}
1261 try:
Raul Tambre09e64b42019-05-14 01:57:22 +00001262 exec(compile(script_text, 'PRESUBMIT.py', 'exec', dont_inherit=True),
1263 context)
Raul Tambre7c938462019-05-24 16:35:35 +00001264 except Exception as e:
rmistry@google.com5626a922015-02-26 14:03:30 +00001265 raise PresubmitFailure('"%s" had an exception.\n%s'
1266 % (presubmit_path, e))
1267
1268 function_name = 'PostUploadHook'
1269 if function_name not in context:
1270 return {}
1271 post_upload_hook = context[function_name]
1272 if not len(inspect.getargspec(post_upload_hook)[0]) == 3:
1273 raise PresubmitFailure(
1274 'Expected function "PostUploadHook" to take three arguments.')
1275 return post_upload_hook(cl, change, OutputApi(False))
1276
1277
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001278def _MergeMasters(masters1, masters2):
1279 """Merges two master maps. Merges also the tests of each builder."""
1280 result = {}
1281 for (master, builders) in itertools.chain(masters1.iteritems(),
1282 masters2.iteritems()):
1283 new_builders = result.setdefault(master, {})
1284 for (builder, tests) in builders.iteritems():
1285 new_builders.setdefault(builder, set([])).update(tests)
1286 return result
1287
1288
1289def DoGetTryMasters(change,
1290 changed_files,
1291 repository_root,
1292 default_presubmit,
1293 project,
1294 verbose,
1295 output_stream):
1296 """Get the list of try masters from the presubmit scripts.
1297
1298 Args:
1299 changed_files: List of modified files.
1300 repository_root: The repository root.
1301 default_presubmit: A default presubmit script to execute in any case.
1302 project: Optional name of a project used in selecting trybots.
1303 verbose: Prints debug info.
1304 output_stream: A stream to write debug output to.
1305
1306 Return:
1307 Map of try masters to map of builders to set of tests.
1308 """
1309 presubmit_files = ListRelevantPresubmitFiles(changed_files, repository_root)
1310 if not presubmit_files and verbose:
1311 output_stream.write("Warning, no PRESUBMIT.py found.\n")
1312 results = {}
1313 executer = GetTryMastersExecuter()
1314
1315 if default_presubmit:
1316 if verbose:
1317 output_stream.write("Running default presubmit script.\n")
1318 fake_path = os.path.join(repository_root, 'PRESUBMIT.py')
1319 results = _MergeMasters(results, executer.ExecPresubmitScript(
1320 default_presubmit, fake_path, project, change))
1321 for filename in presubmit_files:
1322 filename = os.path.abspath(filename)
1323 if verbose:
1324 output_stream.write("Running %s\n" % filename)
1325 # Accept CRLF presubmit script.
1326 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1327 results = _MergeMasters(results, executer.ExecPresubmitScript(
1328 presubmit_script, filename, project, change))
1329
1330 # Make sets to lists again for later JSON serialization.
1331 for builders in results.itervalues():
1332 for builder in builders:
1333 builders[builder] = list(builders[builder])
1334
1335 if results and verbose:
1336 output_stream.write('%s\n' % str(results))
1337 return results
1338
1339
rmistry@google.com5626a922015-02-26 14:03:30 +00001340def DoPostUploadExecuter(change,
1341 cl,
1342 repository_root,
1343 verbose,
1344 output_stream):
1345 """Execute the post upload hook.
1346
1347 Args:
1348 change: The Change object.
1349 cl: The Changelist object.
1350 repository_root: The repository root.
1351 verbose: Prints debug info.
1352 output_stream: A stream to write debug output to.
1353 """
1354 presubmit_files = ListRelevantPresubmitFiles(
1355 change.LocalPaths(), repository_root)
1356 if not presubmit_files and verbose:
1357 output_stream.write("Warning, no PRESUBMIT.py found.\n")
1358 results = []
1359 executer = GetPostUploadExecuter()
1360 # The root presubmit file should be executed after the ones in subdirectories.
1361 # i.e. the specific post upload hooks should run before the general ones.
1362 # Thus, reverse the order provided by ListRelevantPresubmitFiles.
1363 presubmit_files.reverse()
1364
1365 for filename in presubmit_files:
1366 filename = os.path.abspath(filename)
1367 if verbose:
1368 output_stream.write("Running %s\n" % filename)
1369 # Accept CRLF presubmit script.
1370 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1371 results.extend(executer.ExecPresubmitScript(
1372 presubmit_script, filename, cl, change))
1373 output_stream.write('\n')
1374 if results:
1375 output_stream.write('** Post Upload Hook Messages **\n')
1376 for result in results:
1377 result.handle(output_stream)
1378 output_stream.write('\n')
1379
1380 return results
1381
1382
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001383class PresubmitExecuter(object):
Aaron Gable668c1d82018-04-03 10:19:16 -07001384 def __init__(self, change, committing, verbose,
Edward Lesmes8e282792018-04-03 18:50:29 -04001385 gerrit_obj, dry_run=None, thread_pool=None, parallel=False):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001386 """
1387 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001388 change: The Change object.
agable92bec4f2016-08-24 09:27:27 -07001389 committing: True if 'git cl land' is running, False if 'git cl upload' is.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001390 gerrit_obj: provides basic Gerrit codereview functionality.
1391 dry_run: if true, some Checks will be skipped.
Edward Lesmes8e282792018-04-03 18:50:29 -04001392 parallel: if true, all tests reported via input_api.RunTests for all
1393 PRESUBMIT files will be run in parallel.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001394 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001395 self.change = change
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001396 self.committing = committing
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001397 self.gerrit = gerrit_obj
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001398 self.verbose = verbose
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001399 self.dry_run = dry_run
Daniel Cheng7227d212017-11-17 08:12:37 -08001400 self.more_cc = []
Edward Lesmes8e282792018-04-03 18:50:29 -04001401 self.thread_pool = thread_pool
1402 self.parallel = parallel
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001403
1404 def ExecPresubmitScript(self, script_text, presubmit_path):
1405 """Executes a single presubmit script.
1406
1407 Args:
1408 script_text: The text of the presubmit script.
1409 presubmit_path: The path to the presubmit file (this will be reported via
1410 input_api.PresubmitLocalPath()).
1411
1412 Return:
1413 A list of result objects, empty if no problems.
1414 """
thakis@chromium.orgc6ef53a2014-11-04 00:13:54 +00001415
chase@chromium.org8e416c82009-10-06 04:30:44 +00001416 # Change to the presubmit file's directory to support local imports.
1417 main_path = os.getcwd()
1418 os.chdir(os.path.dirname(presubmit_path))
1419
1420 # Load the presubmit script into context.
dpranke@chromium.org970c5222011-03-12 00:32:24 +00001421 input_api = InputApi(self.change, presubmit_path, self.committing,
Aaron Gable668c1d82018-04-03 10:19:16 -07001422 self.verbose, gerrit_obj=self.gerrit,
Edward Lesmes8e282792018-04-03 18:50:29 -04001423 dry_run=self.dry_run, thread_pool=self.thread_pool,
1424 parallel=self.parallel)
Daniel Cheng7227d212017-11-17 08:12:37 -08001425 output_api = OutputApi(self.committing)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001426 context = {}
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001427 try:
Raul Tambre09e64b42019-05-14 01:57:22 +00001428 exec(compile(script_text, 'PRESUBMIT.py', 'exec', dont_inherit=True),
1429 context)
Raul Tambre7c938462019-05-24 16:35:35 +00001430 except Exception as e:
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001431 raise PresubmitFailure('"%s" had an exception.\n%s' % (presubmit_path, e))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001432
1433 # These function names must change if we make substantial changes to
1434 # the presubmit API that are not backwards compatible.
1435 if self.committing:
1436 function_name = 'CheckChangeOnCommit'
1437 else:
1438 function_name = 'CheckChangeOnUpload'
1439 if function_name in context:
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +01001440 try:
Daniel Cheng7227d212017-11-17 08:12:37 -08001441 context['__args'] = (input_api, output_api)
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +01001442 logging.debug('Running %s in %s', function_name, presubmit_path)
1443 result = eval(function_name + '(*__args)', context)
1444 logging.debug('Running %s done.', function_name)
Daniel Chengd36fce42017-11-21 21:52:52 -08001445 self.more_cc.extend(output_api.more_cc)
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +01001446 finally:
1447 map(os.remove, input_api._named_temporary_files)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001448 if not (isinstance(result, types.TupleType) or
1449 isinstance(result, types.ListType)):
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001450 raise PresubmitFailure(
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001451 'Presubmit functions must return a tuple or list')
1452 for item in result:
1453 if not isinstance(item, OutputApi.PresubmitResult):
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001454 raise PresubmitFailure(
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001455 'All presubmit results must be of types derived from '
1456 'output_api.PresubmitResult')
1457 else:
1458 result = () # no error since the script doesn't care about current event.
1459
chase@chromium.org8e416c82009-10-06 04:30:44 +00001460 # Return the process to the original working directory.
1461 os.chdir(main_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001462 return result
1463
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001464def DoPresubmitChecks(change,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001465 committing,
1466 verbose,
1467 output_stream,
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +00001468 input_stream,
maruel@chromium.orgb0dfd352009-06-10 14:12:54 +00001469 default_presubmit,
dpranke@chromium.org970c5222011-03-12 00:32:24 +00001470 may_prompt,
Aaron Gable668c1d82018-04-03 10:19:16 -07001471 gerrit_obj,
Edward Lesmes8e282792018-04-03 18:50:29 -04001472 dry_run=None,
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001473 parallel=False,
1474 json_output=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001475 """Runs all presubmit checks that apply to the files in the change.
1476
1477 This finds all PRESUBMIT.py files in directories enclosing the files in the
1478 change (up to the repository root) and calls the relevant entrypoint function
1479 depending on whether the change is being committed or uploaded.
1480
1481 Prints errors, warnings and notifications. Prompts the user for warnings
1482 when needed.
1483
1484 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001485 change: The Change object.
agable92bec4f2016-08-24 09:27:27 -07001486 committing: True if 'git cl land' is running, False if 'git cl upload' is.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001487 verbose: Prints debug info.
1488 output_stream: A stream to write output from presubmit tests to.
1489 input_stream: A stream to read input from the user.
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +00001490 default_presubmit: A default presubmit script to execute in any case.
Quinten Yearsley516fe7f2016-12-14 11:50:18 -08001491 may_prompt: Enable (y/n) questions on warning or error. If False,
1492 any questions are answered with yes by default.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001493 gerrit_obj: provides basic Gerrit codereview functionality.
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001494 dry_run: if true, some Checks will be skipped.
Edward Lesmes8e282792018-04-03 18:50:29 -04001495 parallel: if true, all tests specified by input_api.RunTests in all
1496 PRESUBMIT files will be run in parallel.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001497
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +00001498 Warning:
1499 If may_prompt is true, output_stream SHOULD be sys.stdout and input_stream
1500 SHOULD be sys.stdin.
1501
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001502 Return:
dpranke@chromium.org5ac21012011-03-16 02:58:25 +00001503 A PresubmitOutput object. Use output.should_continue() to figure out
1504 if there were errors or warnings and the caller should abort.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001505 """
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001506 old_environ = os.environ
1507 try:
1508 # Make sure python subprocesses won't generate .pyc files.
1509 os.environ = os.environ.copy()
1510 os.environ['PYTHONDONTWRITEBYTECODE'] = '1'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001511
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001512 output = PresubmitOutput(input_stream, output_stream)
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001513
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001514 if committing:
1515 output.write("Running presubmit commit checks ...\n")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001516 else:
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001517 output.write("Running presubmit upload checks ...\n")
1518 start_time = time.time()
1519 presubmit_files = ListRelevantPresubmitFiles(
agable0b65e732016-11-22 09:25:46 -08001520 change.AbsoluteLocalPaths(), change.RepositoryRoot())
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001521 if not presubmit_files and verbose:
maruel@chromium.orgfae707b2011-09-15 18:57:58 +00001522 output.write("Warning, no PRESUBMIT.py found.\n")
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001523 results = []
Edward Lesmes8e282792018-04-03 18:50:29 -04001524 thread_pool = ThreadPool()
Edward Lemur7e3c67f2018-07-20 20:52:49 +00001525 executer = PresubmitExecuter(change, committing, verbose, gerrit_obj,
1526 dry_run, thread_pool, parallel)
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001527 if default_presubmit:
1528 if verbose:
1529 output.write("Running default presubmit script.\n")
1530 fake_path = os.path.join(change.RepositoryRoot(), 'PRESUBMIT.py')
1531 results += executer.ExecPresubmitScript(default_presubmit, fake_path)
1532 for filename in presubmit_files:
1533 filename = os.path.abspath(filename)
1534 if verbose:
1535 output.write("Running %s\n" % filename)
1536 # Accept CRLF presubmit script.
1537 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1538 results += executer.ExecPresubmitScript(presubmit_script, filename)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001539
Edward Lesmes8e282792018-04-03 18:50:29 -04001540 results += thread_pool.RunAsync()
1541
Daniel Cheng7227d212017-11-17 08:12:37 -08001542 output.more_cc.extend(executer.more_cc)
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001543 errors = []
1544 notifications = []
1545 warnings = []
1546 for result in results:
1547 if result.fatal:
1548 errors.append(result)
1549 elif result.should_prompt:
1550 warnings.append(result)
1551 else:
1552 notifications.append(result)
pam@chromium.orged9a0832009-09-09 22:48:55 +00001553
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001554 if json_output:
1555 # Write the presubmit results to json output
1556 presubmit_results = {
1557 'errors': [
1558 error.json_format() for error in errors
1559 ],
1560 'notifications': [
1561 notification.json_format() for notification in notifications
1562 ],
1563 'warnings': [
1564 warning.json_format() for warning in warnings
1565 ]
1566 }
1567
1568 gclient_utils.FileWrite(json_output, json.dumps(presubmit_results))
1569
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001570 output.write('\n')
1571 for name, items in (('Messages', notifications),
1572 ('Warnings', warnings),
1573 ('ERRORS', errors)):
1574 if items:
1575 output.write('** Presubmit %s **\n' % name)
1576 for item in items:
1577 item.handle(output)
1578 output.write('\n')
pam@chromium.orged9a0832009-09-09 22:48:55 +00001579
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001580 total_time = time.time() - start_time
1581 if total_time > 1.0:
1582 output.write("Presubmit checks took %.1fs to calculate.\n\n" % total_time)
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +00001583
Quinten Yearsley516fe7f2016-12-14 11:50:18 -08001584 if errors:
1585 output.fail()
1586 elif warnings:
1587 output.write('There were presubmit warnings. ')
1588 if may_prompt:
1589 output.prompt_yes_no('Are you sure you wish to continue? (y/N): ')
1590 else:
1591 output.write('Presubmit checks passed.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001592
1593 global _ASKED_FOR_FEEDBACK
1594 # Ask for feedback one time out of 5.
1595 if (len(results) and random.randint(0, 4) == 0 and not _ASKED_FOR_FEEDBACK):
maruel@chromium.org1ce8e662014-01-14 15:23:00 +00001596 output.write(
1597 'Was the presubmit check useful? If not, run "git cl presubmit -v"\n'
1598 'to figure out which PRESUBMIT.py was run, then run git blame\n'
1599 'on the file to figure out who to ask for help.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001600 _ASKED_FOR_FEEDBACK = True
1601 return output
1602 finally:
1603 os.environ = old_environ
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001604
1605
1606def ScanSubDirs(mask, recursive):
1607 if not recursive:
pgervais@chromium.orge57b09d2014-05-07 00:58:13 +00001608 return [x for x in glob.glob(mask) if x not in ('.svn', '.git')]
Lei Zhang9611c4c2017-04-04 01:41:56 -07001609
1610 results = []
1611 for root, dirs, files in os.walk('.'):
1612 if '.svn' in dirs:
1613 dirs.remove('.svn')
1614 if '.git' in dirs:
1615 dirs.remove('.git')
1616 for name in files:
1617 if fnmatch.fnmatch(name, mask):
1618 results.append(os.path.join(root, name))
1619 return results
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001620
1621
1622def ParseFiles(args, recursive):
tobiasjs2836bcf2016-08-16 04:08:16 -07001623 logging.debug('Searching for %s', args)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001624 files = []
1625 for arg in args:
maruel@chromium.orge3608df2009-11-10 20:22:57 +00001626 files.extend([('M', f) for f in ScanSubDirs(arg, recursive)])
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001627 return files
1628
1629
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001630def load_files(options, args):
1631 """Tries to determine the SCM."""
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001632 files = []
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001633 if args:
1634 files = ParseFiles(args, options.recursive)
agable0b65e732016-11-22 09:25:46 -08001635 change_scm = scm.determine_scm(options.root)
1636 if change_scm == 'git':
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001637 change_class = GitChange
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001638 upstream = options.upstream or None
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001639 if not files:
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001640 files = scm.GIT.CaptureStatus([], options.root, upstream)
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001641 else:
tobiasjs2836bcf2016-08-16 04:08:16 -07001642 logging.info('Doesn\'t seem under source control. Got %d files', len(args))
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001643 if not files:
1644 return None, None
1645 change_class = Change
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001646 return change_class, files
1647
1648
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001649@contextlib.contextmanager
1650def canned_check_filter(method_names):
1651 filtered = {}
1652 try:
1653 for method_name in method_names:
1654 if not hasattr(presubmit_canned_checks, method_name):
Aaron Gableecee74c2018-04-02 15:13:08 -07001655 logging.warn('Skipping unknown "canned" check %s' % method_name)
1656 continue
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001657 filtered[method_name] = getattr(presubmit_canned_checks, method_name)
1658 setattr(presubmit_canned_checks, method_name, lambda *_a, **_kw: [])
1659 yield
1660 finally:
1661 for name, method in filtered.iteritems():
1662 setattr(presubmit_canned_checks, name, method)
1663
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001664
sbc@chromium.org013731e2015-02-26 18:28:43 +00001665def main(argv=None):
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001666 parser = optparse.OptionParser(usage="%prog [options] <files...>",
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001667 version="%prog " + str(__version__))
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001668 parser.add_option("-c", "--commit", action="store_true", default=False,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001669 help="Use commit instead of upload checks")
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001670 parser.add_option("-u", "--upload", action="store_false", dest='commit',
1671 help="Use upload instead of commit checks")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001672 parser.add_option("-r", "--recursive", action="store_true",
1673 help="Act recursively")
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001674 parser.add_option("-v", "--verbose", action="count", default=0,
1675 help="Use 2 times for more debug info")
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001676 parser.add_option("--name", default='no name')
maruel@chromium.org58407af2011-04-12 23:15:57 +00001677 parser.add_option("--author")
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001678 parser.add_option("--description", default='')
1679 parser.add_option("--issue", type='int', default=0)
1680 parser.add_option("--patchset", type='int', default=0)
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001681 parser.add_option("--root", default=os.getcwd(),
1682 help="Search for PRESUBMIT.py up to this directory. "
1683 "If inherit-review-settings-ok is present in this "
1684 "directory, parent directories up to the root file "
1685 "system directories will also be searched.")
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001686 parser.add_option("--upstream",
1687 help="Git only: the base ref or upstream branch against "
1688 "which the diff should be computed.")
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001689 parser.add_option("--default_presubmit")
1690 parser.add_option("--may_prompt", action='store_true', default=False)
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001691 parser.add_option("--skip_canned", action='append', default=[],
1692 help="A list of checks to skip which appear in "
1693 "presubmit_canned_checks. Can be provided multiple times "
1694 "to skip multiple canned checks.")
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001695 parser.add_option("--dry_run", action='store_true',
1696 help=optparse.SUPPRESS_HELP)
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001697 parser.add_option("--gerrit_url", help=optparse.SUPPRESS_HELP)
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001698 parser.add_option("--gerrit_fetch", action='store_true',
1699 help=optparse.SUPPRESS_HELP)
Edward Lesmes8e282792018-04-03 18:50:29 -04001700 parser.add_option('--parallel', action='store_true',
1701 help='Run all tests specified by input_api.RunTests in all '
1702 'PRESUBMIT files in parallel.')
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001703 parser.add_option('--json_output',
1704 help='Write presubmit errors to json output.')
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001705
maruel@chromium.org82e5f282011-03-17 14:08:55 +00001706 options, args = parser.parse_args(argv)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001707
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001708 if options.verbose >= 2:
maruel@chromium.org7444c502011-02-09 14:02:11 +00001709 logging.basicConfig(level=logging.DEBUG)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001710 elif options.verbose:
1711 logging.basicConfig(level=logging.INFO)
1712 else:
1713 logging.basicConfig(level=logging.ERROR)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001714
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001715 change_class, files = load_files(options, args)
1716 if not change_class:
1717 parser.error('For unversioned directory, <files> is not optional.')
tobiasjs2836bcf2016-08-16 04:08:16 -07001718 logging.info('Found %d file(s).', len(files))
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001719
Aaron Gable668c1d82018-04-03 10:19:16 -07001720 gerrit_obj = None
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001721 if options.gerrit_url and options.gerrit_fetch:
tandrii@chromium.org83b1b232016-04-29 16:33:19 +00001722 assert options.issue and options.patchset
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001723 gerrit_obj = GerritAccessor(urlparse.urlparse(options.gerrit_url).netloc)
1724 options.author = gerrit_obj.GetChangeOwner(options.issue)
1725 options.description = gerrit_obj.GetChangeDescription(options.issue,
1726 options.patchset)
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001727 logging.info('Got author: "%s"', options.author)
1728 logging.info('Got description: """\n%s\n"""', options.description)
1729
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001730 try:
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001731 with canned_check_filter(options.skip_canned):
1732 results = DoPresubmitChecks(
1733 change_class(options.name,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001734 options.description,
1735 options.root,
1736 files,
1737 options.issue,
1738 options.patchset,
1739 options.author,
1740 upstream=options.upstream),
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001741 options.commit,
1742 options.verbose,
1743 sys.stdout,
1744 sys.stdin,
1745 options.default_presubmit,
1746 options.may_prompt,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001747 gerrit_obj,
Edward Lesmes8e282792018-04-03 18:50:29 -04001748 options.dry_run,
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001749 options.parallel,
1750 options.json_output)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001751 return not results.should_continue()
Raul Tambre7c938462019-05-24 16:35:35 +00001752 except PresubmitFailure as e:
Raul Tambre80ee78e2019-05-06 22:41:05 +00001753 print(e, file=sys.stderr)
1754 print('Maybe your depot_tools is out of date?', file=sys.stderr)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001755 return 2
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001756
1757
1758if __name__ == '__main__':
maruel@chromium.org35625c72011-03-23 17:34:02 +00001759 fix_encoding.fix_encoding()
sbc@chromium.org013731e2015-02-26 18:28:43 +00001760 try:
1761 sys.exit(main())
1762 except KeyboardInterrupt:
1763 sys.stderr.write('interrupted\n')
sergiybf8a3b382016-07-05 11:21:30 -07001764 sys.exit(2)