blob: d2734edea54b80110c7bffe286b4f34f18c6a286 [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
Edward Lemura834f392019-10-22 22:23:00 +000010from __future__ import unicode_literals
Raul Tambre80ee78e2019-05-06 22:41:05 +000011
stip@chromium.orgf7d31f52014-01-03 20:14:46 +000012__version__ = '1.8.0'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000013
14# TODO(joi) Add caching where appropriate/needed. The API is designed to allow
15# caching (between all different invocations of presubmit scripts for a given
16# change). We should add it as our presubmit scripts start feeling slow.
17
Takeshi Yoshino07a6bea2017-08-02 02:44:06 +090018import ast # Exposed through the API.
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +000019import contextlib
Yoshisato Yanagisawa406de132018-06-29 05:43:25 +000020import cpplint
dcheng091b7db2016-06-16 01:27:51 -070021import fnmatch # Exposed through the API.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000022import glob
asvitkine@chromium.org15169952011-09-27 14:30:53 +000023import inspect
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +000024import itertools
maruel@chromium.org4f6852c2012-04-20 20:39:20 +000025import json # Exposed through the API.
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +000026import logging
ilevy@chromium.orgbc117312013-04-20 03:57:56 +000027import multiprocessing
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000028import optparse
29import os # Somewhat exposed through the API.
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +000030import random
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000031import re # Exposed through the API.
Edward Lesmes8e282792018-04-03 18:50:29 -040032import signal
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000033import sys # Parts exposed through API.
34import tempfile # Exposed through the API.
Edward Lesmes8e282792018-04-03 18:50:29 -040035import threading
jam@chromium.org2a891dc2009-08-20 20:33:37 +000036import time
maruel@chromium.org1487d532009-06-06 00:22:57 +000037import unittest # Exposed through the API.
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +000038from warnings import warn
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000039
40# Local imports.
maruel@chromium.org35625c72011-03-23 17:34:02 +000041import fix_encoding
Yoshisato Yanagisawa04600b42019-03-15 03:03:41 +000042import gclient_paths # Exposed through the API
43import gclient_utils
Aaron Gableb584c4f2017-04-26 16:28:08 -070044import git_footers
tandrii@chromium.org015ebae2016-04-25 19:37:22 +000045import gerrit_util
dpranke@chromium.org2a009622011-03-01 02:43:31 +000046import owners
Jochen Eisinger76f5fc62017-04-07 16:27:46 +020047import owners_finder
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000048import presubmit_canned_checks
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +000049import scm
maruel@chromium.org84f4fe32011-04-06 13:26:45 +000050import subprocess2 as subprocess # Exposed through the API.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000051
Edward Lemur16af3562019-10-17 22:11:33 +000052if sys.version_info.major == 2:
53 # TODO(1009814): Expose urllib2 only through urllib_request and urllib_error
54 import urllib2 # Exposed through the API.
55 import urlparse
56 import urllib2 as urllib_request
57 import urllib2 as urllib_error
58else:
59 import urllib.parse as urlparse
60 import urllib.request as urllib_request
61 import urllib.error as urllib_error
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000062
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +000063# Ask for feedback only once in program lifetime.
64_ASKED_FOR_FEEDBACK = False
65
66
maruel@chromium.org899e1c12011-04-07 17:03:18 +000067class PresubmitFailure(Exception):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000068 pass
69
70
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +000071class CommandData(object):
Edward Lemur940c2822019-08-23 00:34:25 +000072 def __init__(self, name, cmd, kwargs, message, python3=False):
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +000073 self.name = name
74 self.cmd = cmd
Edward Lesmes8e282792018-04-03 18:50:29 -040075 self.stdin = kwargs.get('stdin', None)
Edward Lemur2d6b67c2019-08-23 22:25:41 +000076 self.kwargs = kwargs.copy()
Edward Lesmes8e282792018-04-03 18:50:29 -040077 self.kwargs['stdout'] = subprocess.PIPE
78 self.kwargs['stderr'] = subprocess.STDOUT
79 self.kwargs['stdin'] = subprocess.PIPE
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +000080 self.message = message
81 self.info = None
Edward Lemur940c2822019-08-23 00:34:25 +000082 self.python3 = python3
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +000083
ilevy@chromium.orgbc117312013-04-20 03:57:56 +000084
Edward Lesmes8e282792018-04-03 18:50:29 -040085# Adapted from
86# https://github.com/google/gtest-parallel/blob/master/gtest_parallel.py#L37
87#
88# An object that catches SIGINT sent to the Python process and notices
89# if processes passed to wait() die by SIGINT (we need to look for
90# both of those cases, because pressing Ctrl+C can result in either
91# the main process or one of the subprocesses getting the signal).
92#
93# Before a SIGINT is seen, wait(p) will simply call p.wait() and
94# return the result. Once a SIGINT has been seen (in the main process
95# or a subprocess, including the one the current call is waiting for),
Edward Lemur9a5bb612019-09-26 02:01:52 +000096# wait(p) will call p.terminate().
Edward Lesmes8e282792018-04-03 18:50:29 -040097class SigintHandler(object):
Edward Lesmes8e282792018-04-03 18:50:29 -040098 sigint_returncodes = {-signal.SIGINT, # Unix
99 -1073741510, # Windows
100 }
101 def __init__(self):
102 self.__lock = threading.Lock()
103 self.__processes = set()
104 self.__got_sigint = False
Edward Lemur9a5bb612019-09-26 02:01:52 +0000105 self.__previous_signal = signal.signal(signal.SIGINT, self.interrupt)
Edward Lesmes8e282792018-04-03 18:50:29 -0400106
107 def __on_sigint(self):
108 self.__got_sigint = True
109 while self.__processes:
110 try:
111 self.__processes.pop().terminate()
112 except OSError:
113 pass
114
Edward Lemur9a5bb612019-09-26 02:01:52 +0000115 def interrupt(self, signal_num, frame):
Edward Lesmes8e282792018-04-03 18:50:29 -0400116 with self.__lock:
117 self.__on_sigint()
Edward Lemur9a5bb612019-09-26 02:01:52 +0000118 self.__previous_signal(signal_num, frame)
Edward Lesmes8e282792018-04-03 18:50:29 -0400119
120 def got_sigint(self):
121 with self.__lock:
122 return self.__got_sigint
123
124 def wait(self, p, stdin):
125 with self.__lock:
126 if self.__got_sigint:
127 p.terminate()
128 self.__processes.add(p)
129 stdout, stderr = p.communicate(stdin)
130 code = p.returncode
131 with self.__lock:
132 self.__processes.discard(p)
133 if code in self.sigint_returncodes:
134 self.__on_sigint()
Edward Lesmes8e282792018-04-03 18:50:29 -0400135 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 """
Edward Lemur940c2822019-08-23 00:34:25 +0000155 vpython = 'vpython'
156 if test.python3:
157 vpython += '3'
158 if sys.platform == 'win32':
159 vpython += '.bat'
Edward Lesmes8e282792018-04-03 18:50:29 -0400160
161 cmd = test.cmd
162 if cmd[0] == 'python':
163 cmd = list(cmd)
164 cmd[0] = vpython
165 elif cmd[0].endswith('.py'):
166 cmd = [vpython] + cmd
167
168 try:
169 start = time.time()
170 p = subprocess.Popen(cmd, **test.kwargs)
171 stdout, _ = sigint_handler.wait(p, test.stdin)
172 duration = time.time() - start
173 except OSError as e:
174 duration = time.time() - start
175 return test.message(
176 '%s exec failure (%4.2fs)\n %s' % (test.name, duration, e))
177 if p.returncode != 0:
178 return test.message(
179 '%s (%4.2fs) failed\n%s' % (test.name, duration, stdout))
180 if test.info:
181 return test.info('%s (%4.2fs)' % (test.name, duration))
182
183 def AddTests(self, tests, parallel=True):
184 if parallel:
185 self._tests.extend(tests)
186 else:
187 self._nonparallel_tests.extend(tests)
188
189 def RunAsync(self):
190 self._messages = []
191
192 def _WorkerFn():
193 while True:
194 test = None
195 with self._tests_lock:
196 if not self._tests:
197 break
198 test = self._tests.pop()
199 result = self.CallCommand(test)
200 if result:
201 with self._messages_lock:
202 self._messages.append(result)
203
204 def _StartDaemon():
205 t = threading.Thread(target=_WorkerFn)
206 t.daemon = True
207 t.start()
208 return t
209
210 while self._nonparallel_tests:
211 test = self._nonparallel_tests.pop()
212 result = self.CallCommand(test)
213 if result:
214 self._messages.append(result)
215
216 if self._tests:
217 threads = [_StartDaemon() for _ in range(self._pool_size)]
218 for worker in threads:
219 worker.join()
220
221 return self._messages
222
223
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000224def normpath(path):
225 '''Version of os.path.normpath that also changes backward slashes to
226 forward slashes when not running on Windows.
227 '''
228 # This is safe to always do because the Windows version of os.path.normpath
229 # will replace forward slashes with backward slashes.
230 path = path.replace(os.sep, '/')
231 return os.path.normpath(path)
232
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000233
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000234def _RightHandSideLinesImpl(affected_files):
235 """Implements RightHandSideLines for InputApi and GclChange."""
236 for af in affected_files:
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000237 lines = af.ChangedContents()
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000238 for line in lines:
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000239 yield (af, line[0], line[1])
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000240
241
dpranke@chromium.org5ac21012011-03-16 02:58:25 +0000242class PresubmitOutput(object):
243 def __init__(self, input_stream=None, output_stream=None):
244 self.input_stream = input_stream
245 self.output_stream = output_stream
246 self.reviewers = []
Daniel Cheng7227d212017-11-17 08:12:37 -0800247 self.more_cc = []
dpranke@chromium.org5ac21012011-03-16 02:58:25 +0000248 self.written_output = []
249 self.error_count = 0
250
251 def prompt_yes_no(self, prompt_string):
252 self.write(prompt_string)
253 if self.input_stream:
254 response = self.input_stream.readline().strip().lower()
255 if response not in ('y', 'yes'):
256 self.fail()
257 else:
258 self.fail()
259
260 def fail(self):
261 self.error_count += 1
262
263 def should_continue(self):
264 return not self.error_count
265
266 def write(self, s):
267 self.written_output.append(s)
268 if self.output_stream:
269 self.output_stream.write(s)
270
271 def getvalue(self):
272 return ''.join(self.written_output)
273
274
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000275# Top level object so multiprocessing can pickle
276# Public access through OutputApi object.
277class _PresubmitResult(object):
278 """Base class for result objects."""
279 fatal = False
280 should_prompt = False
281
282 def __init__(self, message, items=None, long_text=''):
283 """
284 message: A short one-line message to indicate errors.
285 items: A list of short strings to indicate where errors occurred.
286 long_text: multi-line text output, e.g. from another tool
287 """
288 self._message = message
289 self._items = items or []
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000290 self._long_text = long_text.rstrip()
291
292 def handle(self, output):
293 output.write(self._message)
294 output.write('\n')
295 for index, item in enumerate(self._items):
296 output.write(' ')
297 # Write separately in case it's unicode.
298 output.write(str(item))
299 if index < len(self._items) - 1:
300 output.write(' \\')
301 output.write('\n')
302 if self._long_text:
303 output.write('\n***************\n')
304 # Write separately in case it's unicode.
305 output.write(self._long_text)
306 output.write('\n***************\n')
307 if self.fatal:
308 output.fail()
309
Debrian Figueroadd2737e2019-06-21 23:50:13 +0000310 def json_format(self):
311 return {
312 'message': self._message,
Debrian Figueroa6095d402019-06-28 18:47:18 +0000313 'items': [str(item) for item in self._items],
Debrian Figueroadd2737e2019-06-21 23:50:13 +0000314 'long_text': self._long_text,
315 'fatal': self.fatal
316 }
317
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000318
319# Top level object so multiprocessing can pickle
320# Public access through OutputApi object.
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000321class _PresubmitError(_PresubmitResult):
322 """A hard presubmit error."""
323 fatal = True
324
325
326# Top level object so multiprocessing can pickle
327# Public access through OutputApi object.
328class _PresubmitPromptWarning(_PresubmitResult):
329 """An warning that prompts the user if they want to continue."""
330 should_prompt = True
331
332
333# Top level object so multiprocessing can pickle
334# Public access through OutputApi object.
335class _PresubmitNotifyResult(_PresubmitResult):
336 """Just print something to the screen -- but it's not even a warning."""
337 pass
338
339
340# Top level object so multiprocessing can pickle
341# Public access through OutputApi object.
342class _MailTextResult(_PresubmitResult):
343 """A warning that should be included in the review request email."""
344 def __init__(self, *args, **kwargs):
345 super(_MailTextResult, self).__init__()
346 raise NotImplementedError()
347
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000348class GerritAccessor(object):
349 """Limited Gerrit functionality for canned presubmit checks to work.
350
351 To avoid excessive Gerrit calls, caches the results.
352 """
353
354 def __init__(self, host):
355 self.host = host
356 self.cache = {}
357
358 def _FetchChangeDetail(self, issue):
359 # Separate function to be easily mocked in tests.
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +0100360 try:
361 return gerrit_util.GetChangeDetail(
362 self.host, str(issue),
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700363 ['ALL_REVISIONS', 'DETAILED_LABELS', 'ALL_COMMITS'])
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +0100364 except gerrit_util.GerritError as e:
365 if e.http_status == 404:
366 raise Exception('Either Gerrit issue %s doesn\'t exist, or '
367 'no credentials to fetch issue details' % issue)
368 raise
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000369
370 def GetChangeInfo(self, issue):
371 """Returns labels and all revisions (patchsets) for this issue.
372
373 The result is a dictionary according to Gerrit REST Api.
374 https://gerrit-review.googlesource.com/Documentation/rest-api.html
375
376 However, API isn't very clear what's inside, so see tests for example.
377 """
378 assert issue
379 cache_key = int(issue)
380 if cache_key not in self.cache:
381 self.cache[cache_key] = self._FetchChangeDetail(issue)
382 return self.cache[cache_key]
383
384 def GetChangeDescription(self, issue, patchset=None):
385 """If patchset is none, fetches current patchset."""
386 info = self.GetChangeInfo(issue)
387 # info is a reference to cache. We'll modify it here adding description to
388 # it to the right patchset, if it is not yet there.
389
390 # Find revision info for the patchset we want.
391 if patchset is not None:
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000392 for rev, rev_info in info['revisions'].items():
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000393 if str(rev_info['_number']) == str(patchset):
394 break
395 else:
396 raise Exception('patchset %s doesn\'t exist in issue %s' % (
397 patchset, issue))
398 else:
399 rev = info['current_revision']
400 rev_info = info['revisions'][rev]
401
Andrii Shyshkalov9c3a4642017-01-24 17:41:22 +0100402 return rev_info['commit']['message']
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000403
Mun Yong Jang603d01e2017-12-19 16:38:30 -0800404 def GetDestRef(self, issue):
405 ref = self.GetChangeInfo(issue)['branch']
406 if not ref.startswith('refs/'):
407 # NOTE: it is possible to create 'refs/x' branch,
408 # aka 'refs/heads/refs/x'. However, this is ill-advised.
409 ref = 'refs/heads/%s' % ref
410 return ref
411
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000412 def GetChangeOwner(self, issue):
413 return self.GetChangeInfo(issue)['owner']['email']
414
415 def GetChangeReviewers(self, issue, approving_only=True):
Aaron Gable8b478f02017-07-31 15:33:19 -0700416 changeinfo = self.GetChangeInfo(issue)
417 if approving_only:
418 labelinfo = changeinfo.get('labels', {}).get('Code-Review', {})
419 values = labelinfo.get('values', {}).keys()
420 try:
421 max_value = max(int(v) for v in values)
422 reviewers = [r for r in labelinfo.get('all', [])
423 if r.get('value', 0) == max_value]
424 except ValueError: # values is the empty list
425 reviewers = []
426 else:
427 reviewers = changeinfo.get('reviewers', {}).get('REVIEWER', [])
428 return [r.get('email') for r in reviewers]
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000429
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000430
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000431class OutputApi(object):
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000432 """An instance of OutputApi gets passed to presubmit scripts so that they
433 can output various types of results.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000434 """
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000435 PresubmitResult = _PresubmitResult
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000436 PresubmitError = _PresubmitError
437 PresubmitPromptWarning = _PresubmitPromptWarning
438 PresubmitNotifyResult = _PresubmitNotifyResult
439 MailTextResult = _MailTextResult
440
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000441 def __init__(self, is_committing):
442 self.is_committing = is_committing
Daniel Cheng7227d212017-11-17 08:12:37 -0800443 self.more_cc = []
444
445 def AppendCC(self, cc):
446 """Appends a user to cc for this change."""
447 self.more_cc.append(cc)
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000448
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000449 def PresubmitPromptOrNotify(self, *args, **kwargs):
450 """Warn the user when uploading, but only notify if committing."""
451 if self.is_committing:
452 return self.PresubmitNotifyResult(*args, **kwargs)
453 return self.PresubmitPromptWarning(*args, **kwargs)
454
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000455
456class InputApi(object):
457 """An instance of this object is passed to presubmit scripts so they can
458 know stuff about the change they're looking at.
459 """
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000460 # Method could be a function
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800461 # pylint: disable=no-self-use
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000462
maruel@chromium.org3410d912009-06-09 20:56:16 +0000463 # File extensions that are considered source files from a style guide
464 # perspective. Don't modify this list from a presubmit script!
maruel@chromium.orgc33455a2011-06-24 19:14:18 +0000465 #
466 # Files without an extension aren't included in the list. If you want to
467 # filter them as source files, add r"(^|.*?[\\\/])[^.]+$" to the white list.
468 # Note that ALL CAPS files are black listed in DEFAULT_BLACK_LIST below.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000469 DEFAULT_WHITE_LIST = (
470 # C++ and friends
maruel@chromium.orgfe1211a2011-05-28 18:54:17 +0000471 r".+\.c$", r".+\.cc$", r".+\.cpp$", r".+\.h$", r".+\.m$", r".+\.mm$",
472 r".+\.inl$", r".+\.asm$", r".+\.hxx$", r".+\.hpp$", r".+\.s$", r".+\.S$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000473 # Scripts
maruel@chromium.orgfe1211a2011-05-28 18:54:17 +0000474 r".+\.js$", r".+\.py$", r".+\.sh$", r".+\.rb$", r".+\.pl$", r".+\.pm$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000475 # Other
Sergey Ulanov166bc4c2018-04-30 17:03:38 -0700476 r".+\.java$", r".+\.mk$", r".+\.am$", r".+\.css$", r".+\.mojom$",
477 r".+\.fidl$"
maruel@chromium.org3410d912009-06-09 20:56:16 +0000478 )
479
480 # Path regexp that should be excluded from being considered containing source
481 # files. Don't modify this list from a presubmit script!
482 DEFAULT_BLACK_LIST = (
gavinp@chromium.org656326d2012-08-13 00:43:57 +0000483 r"testing_support[\\\/]google_appengine[\\\/].*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000484 r".*\bexperimental[\\\/].*",
Kent Tamura179dd1e2018-04-26 15:07:41 +0900485 # Exclude third_party/.* but NOT third_party/{WebKit,blink}
486 # (crbug.com/539768 and crbug.com/836555).
487 r".*\bthird_party[\\\/](?!(WebKit|blink)[\\\/]).*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000488 # Output directories (just in case)
489 r".*\bDebug[\\\/].*",
490 r".*\bRelease[\\\/].*",
491 r".*\bxcodebuild[\\\/].*",
thakis@chromium.orgc1c96352013-10-09 19:50:27 +0000492 r".*\bout[\\\/].*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000493 # All caps files like README and LICENCE.
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000494 r".*\b[A-Z0-9_]{2,}$",
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000495 # SCM (can happen in dual SCM configuration). (Slightly over aggressive)
maruel@chromium.org5d0dc432011-01-03 02:40:37 +0000496 r"(|.*[\\\/])\.git[\\\/].*",
497 r"(|.*[\\\/])\.svn[\\\/].*",
maruel@chromium.org7ccb4bb2011-11-07 20:26:20 +0000498 # There is no point in processing a patch file.
499 r".+\.diff$",
500 r".+\.patch$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000501 )
502
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000503 def __init__(self, change, presubmit_path, is_committing,
Edward Lesmes8e282792018-04-03 18:50:29 -0400504 verbose, gerrit_obj, dry_run=None, thread_pool=None, parallel=False):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000505 """Builds an InputApi object.
506
507 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000508 change: A presubmit.Change object.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000509 presubmit_path: The path to the presubmit script being processed.
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000510 is_committing: True if the change is about to be committed.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000511 gerrit_obj: provides basic Gerrit codereview functionality.
512 dry_run: if true, some Checks will be skipped.
Edward Lesmes8e282792018-04-03 18:50:29 -0400513 parallel: if true, all tests reported via input_api.RunTests for all
514 PRESUBMIT files will be run in parallel.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000515 """
maruel@chromium.org9711bba2009-05-22 23:51:39 +0000516 # Version number of the presubmit_support script.
517 self.version = [int(x) for x in __version__.split('.')]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000518 self.change = change
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000519 self.is_committing = is_committing
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000520 self.gerrit = gerrit_obj
tandrii@chromium.org57bafac2016-04-28 05:09:03 +0000521 self.dry_run = dry_run
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000522
Edward Lesmes8e282792018-04-03 18:50:29 -0400523 self.parallel = parallel
524 self.thread_pool = thread_pool or ThreadPool()
525
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000526 # We expose various modules and functions as attributes of the input_api
527 # so that presubmit scripts don't have to import them.
Takeshi Yoshino07a6bea2017-08-02 02:44:06 +0900528 self.ast = ast
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000529 self.basename = os.path.basename
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000530 self.cpplint = cpplint
dcheng091b7db2016-06-16 01:27:51 -0700531 self.fnmatch = fnmatch
Yoshisato Yanagisawa04600b42019-03-15 03:03:41 +0000532 self.gclient_paths = gclient_paths
Yoshisato Yanagisawa57dd17b2019-03-22 09:10:29 +0000533 # TODO(yyanagisawa): stop exposing this when python3 become default.
534 # Since python3's tempfile has TemporaryDirectory, we do not need this.
535 self.temporary_directory = gclient_utils.temporary_directory
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000536 self.glob = glob.glob
maruel@chromium.orgfb11c7b2010-03-18 18:22:14 +0000537 self.json = json
maruel@chromium.org6fba34d2011-06-02 13:45:12 +0000538 self.logging = logging.getLogger('PRESUBMIT')
maruel@chromium.org2b5ce562011-03-31 16:15:44 +0000539 self.os_listdir = os.listdir
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000540 self.os_path = os.path
pgervais@chromium.orgbd0cace2014-10-02 23:23:46 +0000541 self.os_stat = os.stat
Yoshisato Yanagisawa406de132018-06-29 05:43:25 +0000542 self.os_walk = os.walk
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000543 self.re = re
544 self.subprocess = subprocess
Edward Lemura834f392019-10-22 22:23:00 +0000545 self.sys = sys
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000546 self.tempfile = tempfile
dpranke@chromium.org0d1bdea2011-03-24 22:54:38 +0000547 self.time = time
maruel@chromium.org1487d532009-06-06 00:22:57 +0000548 self.unittest = unittest
Edward Lemura834f392019-10-22 22:23:00 +0000549 if sys.version_info.major == 2:
550 self.urllib2 = urllib2
Edward Lemur16af3562019-10-17 22:11:33 +0000551 self.urllib_request = urllib_request
552 self.urllib_error = urllib_error
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000553
Robert Iannucci50258932018-03-19 10:30:59 -0700554 self.is_windows = sys.platform == 'win32'
555
556 # Set python_executable to 'python'. This is interpreted in CallCommand to
557 # convert to vpython in order to allow scripts in other repos (e.g. src.git)
558 # to automatically pick up that repo's .vpython file, instead of inheriting
559 # the one in depot_tools.
560 self.python_executable = 'python'
maruel@chromium.orgc0b22972009-06-25 16:19:14 +0000561 self.environ = os.environ
562
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000563 # InputApi.platform is the platform you're currently running on.
564 self.platform = sys.platform
565
iannucci@chromium.org0af3bb32015-06-12 20:44:35 +0000566 self.cpu_count = multiprocessing.cpu_count()
567
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000568 # The local path of the currently-being-processed presubmit script.
maruel@chromium.org3d235242009-05-15 12:40:48 +0000569 self._current_presubmit_path = os.path.dirname(presubmit_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000570
571 # We carry the canned checks so presubmit scripts can easily use them.
572 self.canned_checks = presubmit_canned_checks
573
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +0100574 # Temporary files we must manually remove at the end of a run.
575 self._named_temporary_files = []
Jochen Eisinger72606f82017-04-04 10:44:18 +0200576
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000577 # TODO(dpranke): figure out a list of all approved owners for a repo
578 # in order to be able to handle wildcard OWNERS files?
579 self.owners_db = owners.Database(change.RepositoryRoot(),
Edward Lemura834f392019-10-22 22:23:00 +0000580 fopen=open, os_path=self.os_path)
Jochen Eisinger76f5fc62017-04-07 16:27:46 +0200581 self.owners_finder = owners_finder.OwnersFinder
maruel@chromium.org899e1c12011-04-07 17:03:18 +0000582 self.verbose = verbose
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000583 self.Command = CommandData
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000584
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000585 # Replace <hash_map> and <hash_set> as headers that need to be included
danakj@chromium.org18278522013-06-11 22:42:32 +0000586 # with "base/containers/hash_tables.h" instead.
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000587 # Access to a protected member _XX of a client class
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800588 # pylint: disable=protected-access
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000589 self.cpplint._re_pattern_templates = [
danakj@chromium.org18278522013-06-11 22:42:32 +0000590 (a, b, 'base/containers/hash_tables.h')
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000591 if header in ('<hash_map>', '<hash_set>') else (a, b, header)
592 for (a, b, header) in cpplint._re_pattern_templates
593 ]
594
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000595 def PresubmitLocalPath(self):
596 """Returns the local path of the presubmit script currently being run.
597
598 This is useful if you don't want to hard-code absolute paths in the
599 presubmit script. For example, It can be used to find another file
600 relative to the PRESUBMIT.py script, so the whole tree can be branched and
601 the presubmit script still works, without editing its content.
602 """
maruel@chromium.org3d235242009-05-15 12:40:48 +0000603 return self._current_presubmit_path
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000604
agable0b65e732016-11-22 09:25:46 -0800605 def AffectedFiles(self, include_deletes=True, file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000606 """Same as input_api.change.AffectedFiles() except only lists files
607 (and optionally directories) in the same directory as the current presubmit
608 script, or subdirectories thereof.
609 """
maruel@chromium.org3d235242009-05-15 12:40:48 +0000610 dir_with_slash = normpath("%s/" % self.PresubmitLocalPath())
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000611 if len(dir_with_slash) == 1:
612 dir_with_slash = ''
sail@chromium.org5538e022011-05-12 17:53:16 +0000613
Edward Lemura834f392019-10-22 22:23:00 +0000614 return list(filter(
maruel@chromium.org4661e0c2009-06-04 00:45:26 +0000615 lambda x: normpath(x.AbsoluteLocalPath()).startswith(dir_with_slash),
Edward Lemura834f392019-10-22 22:23:00 +0000616 self.change.AffectedFiles(include_deletes, file_filter)))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000617
agable0b65e732016-11-22 09:25:46 -0800618 def LocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000619 """Returns local paths of input_api.AffectedFiles()."""
agable0b65e732016-11-22 09:25:46 -0800620 paths = [af.LocalPath() for af in self.AffectedFiles()]
pgervais@chromium.org2f64f782014-04-25 00:12:33 +0000621 logging.debug("LocalPaths: %s", paths)
622 return paths
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000623
agable0b65e732016-11-22 09:25:46 -0800624 def AbsoluteLocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000625 """Returns absolute local paths of input_api.AffectedFiles()."""
agable0b65e732016-11-22 09:25:46 -0800626 return [af.AbsoluteLocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000627
John Budorick16162372018-04-18 10:39:53 -0700628 def AffectedTestableFiles(self, include_deletes=None, **kwargs):
agable0b65e732016-11-22 09:25:46 -0800629 """Same as input_api.change.AffectedTestableFiles() except only lists files
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000630 in the same directory as the current presubmit script, or subdirectories
631 thereof.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000632 """
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000633 if include_deletes is not None:
agable0b65e732016-11-22 09:25:46 -0800634 warn("AffectedTestableFiles(include_deletes=%s)"
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000635 " is deprecated and ignored" % str(include_deletes),
636 category=DeprecationWarning,
637 stacklevel=2)
Edward Lemura834f392019-10-22 22:23:00 +0000638 return list(filter(
639 lambda x: x.IsTestableFile(),
640 self.AffectedFiles(include_deletes=False, **kwargs)))
agable0b65e732016-11-22 09:25:46 -0800641
642 def AffectedTextFiles(self, include_deletes=None):
643 """An alias to AffectedTestableFiles for backwards compatibility."""
644 return self.AffectedTestableFiles(include_deletes=include_deletes)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000645
maruel@chromium.org3410d912009-06-09 20:56:16 +0000646 def FilterSourceFile(self, affected_file, white_list=None, black_list=None):
647 """Filters out files that aren't considered "source file".
648
649 If white_list or black_list is None, InputApi.DEFAULT_WHITE_LIST
650 and InputApi.DEFAULT_BLACK_LIST is used respectively.
651
652 The lists will be compiled as regular expression and
653 AffectedFile.LocalPath() needs to pass both list.
654
655 Note: Copy-paste this function to suit your needs or use a lambda function.
656 """
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000657 def Find(affected_file, items):
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000658 local_path = affected_file.LocalPath()
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000659 for item in items:
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000660 if self.re.match(item, local_path):
maruel@chromium.org3410d912009-06-09 20:56:16 +0000661 return True
662 return False
663 return (Find(affected_file, white_list or self.DEFAULT_WHITE_LIST) and
664 not Find(affected_file, black_list or self.DEFAULT_BLACK_LIST))
665
666 def AffectedSourceFiles(self, source_file):
agable0b65e732016-11-22 09:25:46 -0800667 """Filter the list of AffectedTestableFiles by the function source_file.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000668
669 If source_file is None, InputApi.FilterSourceFile() is used.
670 """
671 if not source_file:
672 source_file = self.FilterSourceFile
Edward Lemura834f392019-10-22 22:23:00 +0000673 return list(filter(source_file, self.AffectedTestableFiles()))
maruel@chromium.org3410d912009-06-09 20:56:16 +0000674
675 def RightHandSideLines(self, source_file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000676 """An iterator over all text lines in "new" version of changed files.
677
678 Only lists lines from new or modified text files in the change that are
679 contained by the directory of the currently executing presubmit script.
680
681 This is useful for doing line-by-line regex checks, like checking for
682 trailing whitespace.
683
684 Yields:
685 a 3 tuple:
686 the AffectedFile instance of the current file;
687 integer line number (1-based); and
688 the contents of the line as a string.
maruel@chromium.org1487d532009-06-06 00:22:57 +0000689
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000690 Note: The carriage return (LF or CR) is stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000691 """
maruel@chromium.org3410d912009-06-09 20:56:16 +0000692 files = self.AffectedSourceFiles(source_file_filter)
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000693 return _RightHandSideLinesImpl(files)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000694
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000695 def ReadFile(self, file_item, mode='r'):
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000696 """Reads an arbitrary file.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000697
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000698 Deny reading anything outside the repository.
699 """
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000700 if isinstance(file_item, AffectedFile):
701 file_item = file_item.AbsoluteLocalPath()
702 if not file_item.startswith(self.change.RepositoryRoot()):
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000703 raise IOError('Access outside the repository root is denied.')
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000704 return gclient_utils.FileRead(file_item, mode)
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000705
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +0100706 def CreateTemporaryFile(self, **kwargs):
707 """Returns a named temporary file that must be removed with a call to
708 RemoveTemporaryFiles().
709
710 All keyword arguments are forwarded to tempfile.NamedTemporaryFile(),
711 except for |delete|, which is always set to False.
712
713 Presubmit checks that need to create a temporary file and pass it for
714 reading should use this function instead of NamedTemporaryFile(), as
715 Windows fails to open a file that is already open for writing.
716
717 with input_api.CreateTemporaryFile() as f:
718 f.write('xyz')
719 f.close()
720 input_api.subprocess.check_output(['script-that', '--reads-from',
721 f.name])
722
723
724 Note that callers of CreateTemporaryFile() should not worry about removing
725 any temporary file; this is done transparently by the presubmit handling
726 code.
727 """
728 if 'delete' in kwargs:
729 # Prevent users from passing |delete|; we take care of file deletion
730 # ourselves and this prevents unintuitive error messages when we pass
731 # delete=False and 'delete' is also in kwargs.
732 raise TypeError('CreateTemporaryFile() does not take a "delete" '
733 'argument, file deletion is handled automatically by '
734 'the same presubmit_support code that creates InputApi '
735 'objects.')
736 temp_file = self.tempfile.NamedTemporaryFile(delete=False, **kwargs)
737 self._named_temporary_files.append(temp_file.name)
738 return temp_file
739
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000740 @property
741 def tbr(self):
742 """Returns if a change is TBR'ed."""
Jeremy Romandce22502017-06-20 15:37:29 -0400743 return 'TBR' in self.change.tags or self.change.TBRsFromDescription()
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000744
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +0000745 def RunTests(self, tests_mix, parallel=True):
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000746 tests = []
747 msgs = []
748 for t in tests_mix:
Edward Lesmes8e282792018-04-03 18:50:29 -0400749 if isinstance(t, OutputApi.PresubmitResult) and t:
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000750 msgs.append(t)
751 else:
752 assert issubclass(t.message, _PresubmitResult)
753 tests.append(t)
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +0000754 if self.verbose:
755 t.info = _PresubmitNotifyResult
Edward Lemur1037c742018-05-01 18:56:04 -0400756 if not t.kwargs.get('cwd'):
757 t.kwargs['cwd'] = self.PresubmitLocalPath()
Edward Lesmes8e282792018-04-03 18:50:29 -0400758 self.thread_pool.AddTests(tests, parallel)
Edward Lemur21000eb2019-05-24 23:25:58 +0000759 # When self.parallel is True (i.e. --parallel is passed as an option)
760 # RunTests doesn't actually run tests. It adds them to a ThreadPool that
761 # will run all tests once all PRESUBMIT files are processed.
762 # Otherwise, it will run them and return the results.
763 if not self.parallel:
Edward Lesmes8e282792018-04-03 18:50:29 -0400764 msgs.extend(self.thread_pool.RunAsync())
765 return msgs
scottmg86099d72016-09-01 09:16:51 -0700766
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000767
nick@chromium.orgff526192013-06-10 19:30:26 +0000768class _DiffCache(object):
769 """Caches diffs retrieved from a particular SCM."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000770 def __init__(self, upstream=None):
771 """Stores the upstream revision against which all diffs will be computed."""
772 self._upstream = upstream
nick@chromium.orgff526192013-06-10 19:30:26 +0000773
774 def GetDiff(self, path, local_root):
775 """Get the diff for a particular path."""
776 raise NotImplementedError()
777
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700778 def GetOldContents(self, path, local_root):
779 """Get the old version for a particular path."""
780 raise NotImplementedError()
781
nick@chromium.orgff526192013-06-10 19:30:26 +0000782
nick@chromium.orgff526192013-06-10 19:30:26 +0000783class _GitDiffCache(_DiffCache):
784 """DiffCache implementation for git; gets all file diffs at once."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000785 def __init__(self, upstream):
786 super(_GitDiffCache, self).__init__(upstream=upstream)
nick@chromium.orgff526192013-06-10 19:30:26 +0000787 self._diffs_by_file = None
788
789 def GetDiff(self, path, local_root):
790 if not self._diffs_by_file:
791 # Compute a single diff for all files and parse the output; should
792 # with git this is much faster than computing one diff for each file.
793 diffs = {}
794
795 # Don't specify any filenames below, because there are command line length
796 # limits on some platforms and GenerateDiff would fail.
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000797 unified_diff = scm.GIT.GenerateDiff(local_root, files=[], full_move=True,
798 branch=self._upstream)
nick@chromium.orgff526192013-06-10 19:30:26 +0000799
800 # This regex matches the path twice, separated by a space. Note that
801 # filename itself may contain spaces.
802 file_marker = re.compile('^diff --git (?P<filename>.*) (?P=filename)$')
803 current_diff = []
804 keep_line_endings = True
805 for x in unified_diff.splitlines(keep_line_endings):
806 match = file_marker.match(x)
807 if match:
808 # Marks the start of a new per-file section.
809 diffs[match.group('filename')] = current_diff = [x]
810 elif x.startswith('diff --git'):
811 raise PresubmitFailure('Unexpected diff line: %s' % x)
812 else:
813 current_diff.append(x)
814
815 self._diffs_by_file = dict(
816 (normpath(path), ''.join(diff)) for path, diff in diffs.items())
817
818 if path not in self._diffs_by_file:
819 raise PresubmitFailure(
820 'Unified diff did not contain entry for file %s' % path)
821
822 return self._diffs_by_file[path]
823
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700824 def GetOldContents(self, path, local_root):
825 return scm.GIT.GetOldContents(local_root, path, branch=self._upstream)
826
nick@chromium.orgff526192013-06-10 19:30:26 +0000827
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000828class AffectedFile(object):
829 """Representation of a file in a change."""
nick@chromium.orgff526192013-06-10 19:30:26 +0000830
831 DIFF_CACHE = _DiffCache
832
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000833 # Method could be a function
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800834 # pylint: disable=no-self-use
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000835 def __init__(self, path, action, repository_root, diff_cache):
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000836 self._path = path
837 self._action = action
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000838 self._local_root = repository_root
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000839 self._is_directory = None
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000840 self._cached_changed_contents = None
841 self._cached_new_contents = None
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000842 self._diff_cache = diff_cache
tobiasjs2836bcf2016-08-16 04:08:16 -0700843 logging.debug('%s(%s)', self.__class__.__name__, self._path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000844
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000845 def LocalPath(self):
846 """Returns the path of this file on the local disk relative to client root.
Andrew Grieve92b8b992017-11-02 09:42:24 -0400847
848 This should be used for error messages but not for accessing files,
849 because presubmit checks are run with CWD=PresubmitLocalPath() (which is
850 often != client root).
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000851 """
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000852 return normpath(self._path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000853
854 def AbsoluteLocalPath(self):
855 """Returns the absolute path of this file on the local disk.
856 """
chase@chromium.org8e416c82009-10-06 04:30:44 +0000857 return os.path.abspath(os.path.join(self._local_root, self.LocalPath()))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000858
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000859 def Action(self):
860 """Returns the action on this opened file, e.g. A, M, D, etc."""
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000861 return self._action
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000862
agable0b65e732016-11-22 09:25:46 -0800863 def IsTestableFile(self):
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000864 """Returns True if the file is a text file and not a binary file.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000865
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000866 Deleted files are not text file."""
maruel@chromium.org1e08c002009-05-28 19:09:33 +0000867 raise NotImplementedError() # Implement when needed
868
agable0b65e732016-11-22 09:25:46 -0800869 def IsTextFile(self):
870 """An alias to IsTestableFile for backwards compatibility."""
871 return self.IsTestableFile()
872
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700873 def OldContents(self):
874 """Returns an iterator over the lines in the old version of file.
875
Daniel Cheng2da34fe2017-03-21 20:42:12 -0700876 The old version is the file before any modifications in the user's
877 workspace, i.e. the "left hand side".
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700878
879 Contents will be empty if the file is a directory or does not exist.
880 Note: The carriage returns (LF or CR) are stripped off.
881 """
882 return self._diff_cache.GetOldContents(self.LocalPath(),
883 self._local_root).splitlines()
884
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000885 def NewContents(self):
886 """Returns an iterator over the lines in the new version of file.
887
888 The new version is the file in the user's workspace, i.e. the "right hand
889 side".
890
891 Contents will be empty if the file is a directory or does not exist.
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000892 Note: The carriage returns (LF or CR) are stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000893 """
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000894 if self._cached_new_contents is None:
895 self._cached_new_contents = []
agable0b65e732016-11-22 09:25:46 -0800896 try:
897 self._cached_new_contents = gclient_utils.FileRead(
898 self.AbsoluteLocalPath(), 'rU').splitlines()
899 except IOError:
900 pass # File not found? That's fine; maybe it was deleted.
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000901 return self._cached_new_contents[:]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000902
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000903 def ChangedContents(self):
904 """Returns a list of tuples (line number, line text) of all new lines.
905
906 This relies on the scm diff output describing each changed code section
907 with a line of the form
908
909 ^@@ <old line num>,<old size> <new line num>,<new size> @@$
910 """
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000911 if self._cached_changed_contents is not None:
912 return self._cached_changed_contents[:]
913 self._cached_changed_contents = []
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000914 line_num = 0
915
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000916 for line in self.GenerateScmDiff().splitlines():
917 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
918 if m:
919 line_num = int(m.groups(1)[0])
920 continue
921 if line.startswith('+') and not line.startswith('++'):
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000922 self._cached_changed_contents.append((line_num, line[1:]))
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000923 if not line.startswith('-'):
924 line_num += 1
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000925 return self._cached_changed_contents[:]
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000926
maruel@chromium.org5de13972009-06-10 18:16:06 +0000927 def __str__(self):
928 return self.LocalPath()
929
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000930 def GenerateScmDiff(self):
nick@chromium.orgff526192013-06-10 19:30:26 +0000931 return self._diff_cache.GetDiff(self.LocalPath(), self._local_root)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000932
maruel@chromium.org58407af2011-04-12 23:15:57 +0000933
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000934class GitAffectedFile(AffectedFile):
935 """Representation of a file in a change out of a git checkout."""
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000936 # Method 'NNN' is abstract in class 'NNN' but is not overridden
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800937 # pylint: disable=abstract-method
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000938
nick@chromium.orgff526192013-06-10 19:30:26 +0000939 DIFF_CACHE = _GitDiffCache
940
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000941 def __init__(self, *args, **kwargs):
942 AffectedFile.__init__(self, *args, **kwargs)
943 self._server_path = None
agable0b65e732016-11-22 09:25:46 -0800944 self._is_testable_file = None
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000945
agable0b65e732016-11-22 09:25:46 -0800946 def IsTestableFile(self):
947 if self._is_testable_file is None:
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000948 if self.Action() == 'D':
agable0b65e732016-11-22 09:25:46 -0800949 # A deleted file is not testable.
950 self._is_testable_file = False
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000951 else:
agable0b65e732016-11-22 09:25:46 -0800952 self._is_testable_file = os.path.isfile(self.AbsoluteLocalPath())
953 return self._is_testable_file
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000954
maruel@chromium.orgc1938752011-04-12 23:11:13 +0000955
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000956class Change(object):
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000957 """Describe a change.
958
959 Used directly by the presubmit scripts to query the current change being
960 tested.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000961
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000962 Instance members:
nick@chromium.orgff526192013-06-10 19:30:26 +0000963 tags: Dictionary of KEY=VALUE pairs found in the change description.
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000964 self.KEY: equivalent to tags['KEY']
965 """
966
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000967 _AFFECTED_FILES = AffectedFile
968
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000969 # Matches key/value (or "tag") lines in changelist descriptions.
maruel@chromium.org428342a2011-11-10 15:46:33 +0000970 TAG_LINE_RE = re.compile(
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +0000971 '^[ \t]*(?P<key>[A-Z][A-Z_0-9]*)[ \t]*=[ \t]*(?P<value>.*?)[ \t]*$')
maruel@chromium.orgc1938752011-04-12 23:11:13 +0000972 scm = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000973
maruel@chromium.org58407af2011-04-12 23:15:57 +0000974 def __init__(
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000975 self, name, description, local_root, files, issue, patchset, author,
976 upstream=None):
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000977 if files is None:
978 files = []
979 self._name = name
chase@chromium.org8e416c82009-10-06 04:30:44 +0000980 # Convert root into an absolute path.
981 self._local_root = os.path.abspath(local_root)
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000982 self._upstream = upstream
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000983 self.issue = issue
984 self.patchset = patchset
maruel@chromium.org58407af2011-04-12 23:15:57 +0000985 self.author_email = author
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000986
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000987 self._full_description = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000988 self.tags = {}
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000989 self._description_without_tags = ''
990 self.SetDescriptionText(description)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000991
maruel@chromium.orge085d812011-10-10 19:49:15 +0000992 assert all(
993 (isinstance(f, (list, tuple)) and len(f) == 2) for f in files), files
994
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000995 diff_cache = self._AFFECTED_FILES.DIFF_CACHE(self._upstream)
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000996 self._affected_files = [
nick@chromium.orgff526192013-06-10 19:30:26 +0000997 self._AFFECTED_FILES(path, action.strip(), self._local_root, diff_cache)
998 for action, path in files
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +0000999 ]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001000
maruel@chromium.org92022ec2009-06-11 01:59:28 +00001001 def Name(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001002 """Returns the change name."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001003 return self._name
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001004
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001005 def DescriptionText(self):
1006 """Returns the user-entered changelist description, minus tags.
1007
1008 Any line in the user-provided description starting with e.g. "FOO="
1009 (whitespace permitted before and around) is considered a tag line. Such
1010 lines are stripped out of the description this function returns.
1011 """
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001012 return self._description_without_tags
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001013
1014 def FullDescriptionText(self):
1015 """Returns the complete changelist description including tags."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001016 return self._full_description
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001017
isherman@chromium.orgb5cded62014-03-25 17:47:57 +00001018 def SetDescriptionText(self, description):
1019 """Sets the full description text (including tags) to |description|.
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001020
isherman@chromium.orgb5cded62014-03-25 17:47:57 +00001021 Also updates the list of tags."""
1022 self._full_description = description
1023
1024 # From the description text, build up a dictionary of key/value pairs
1025 # plus the description minus all key/value or "tag" lines.
1026 description_without_tags = []
1027 self.tags = {}
1028 for line in self._full_description.splitlines():
1029 m = self.TAG_LINE_RE.match(line)
1030 if m:
1031 self.tags[m.group('key')] = m.group('value')
1032 else:
1033 description_without_tags.append(line)
1034
1035 # Change back to text and remove whitespace at end.
1036 self._description_without_tags = (
1037 '\n'.join(description_without_tags).rstrip())
1038
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001039 def RepositoryRoot(self):
maruel@chromium.org92022ec2009-06-11 01:59:28 +00001040 """Returns the repository (checkout) root directory for this change,
1041 as an absolute path.
1042 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001043 return self._local_root
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001044
1045 def __getattr__(self, attr):
maruel@chromium.org92022ec2009-06-11 01:59:28 +00001046 """Return tags directly as attributes on the object."""
1047 if not re.match(r"^[A-Z_]*$", attr):
1048 raise AttributeError(self, attr)
maruel@chromium.orge1a524f2009-05-27 14:43:46 +00001049 return self.tags.get(attr)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001050
Aaron Gablefc03e672017-05-15 14:09:42 -07001051 def BugsFromDescription(self):
1052 """Returns all bugs referenced in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -07001053 tags = [b.strip() for b in self.tags.get('BUG', '').split(',') if b.strip()]
Caleb Rouleauc0546b92019-02-22 06:12:57 +00001054 footers = []
Dan Beam62954042019-10-03 21:20:33 +00001055 parsed = git_footers.parse_footers(self._full_description)
1056 unsplit_footers = parsed.get('Bug', []) + parsed.get('Fixed', [])
Caleb Rouleauc0546b92019-02-22 06:12:57 +00001057 for unsplit_footer in unsplit_footers:
1058 footers += [b.strip() for b in unsplit_footer.split(',')]
Aaron Gable12ef5012017-05-15 14:29:00 -07001059 return sorted(set(tags + footers))
Aaron Gablefc03e672017-05-15 14:09:42 -07001060
1061 def ReviewersFromDescription(self):
1062 """Returns all reviewers listed in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -07001063 # We don't support a "R:" git-footer for reviewers; that is in metadata.
1064 tags = [r.strip() for r in self.tags.get('R', '').split(',') if r.strip()]
1065 return sorted(set(tags))
Aaron Gablefc03e672017-05-15 14:09:42 -07001066
1067 def TBRsFromDescription(self):
1068 """Returns all TBR reviewers listed in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -07001069 tags = [r.strip() for r in self.tags.get('TBR', '').split(',') if r.strip()]
1070 # TODO(agable): Remove support for 'Tbr:' when TBRs are programmatically
1071 # determined by self-CR+1s.
1072 footers = git_footers.parse_footers(self._full_description).get('Tbr', [])
1073 return sorted(set(tags + footers))
Aaron Gablefc03e672017-05-15 14:09:42 -07001074
1075 # TODO(agable): Delete these once we're sure they're unused.
1076 @property
1077 def BUG(self):
1078 return ','.join(self.BugsFromDescription())
1079 @property
1080 def R(self):
1081 return ','.join(self.ReviewersFromDescription())
1082 @property
1083 def TBR(self):
1084 return ','.join(self.TBRsFromDescription())
1085
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001086 def AllFiles(self, root=None):
1087 """List all files under source control in the repo."""
1088 raise NotImplementedError()
1089
agable0b65e732016-11-22 09:25:46 -08001090 def AffectedFiles(self, include_deletes=True, file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001091 """Returns a list of AffectedFile instances for all files in the change.
1092
1093 Args:
1094 include_deletes: If false, deleted files will be filtered out.
sail@chromium.org5538e022011-05-12 17:53:16 +00001095 file_filter: An additional filter to apply.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001096
1097 Returns:
1098 [AffectedFile(path, action), AffectedFile(path, action)]
1099 """
Edward Lemura834f392019-10-22 22:23:00 +00001100 affected = list(filter(file_filter, self._affected_files))
sail@chromium.org5538e022011-05-12 17:53:16 +00001101
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001102 if include_deletes:
1103 return affected
Edward Lemura834f392019-10-22 22:23:00 +00001104 return list(filter(lambda x: x.Action() != 'D', affected))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001105
John Budorick16162372018-04-18 10:39:53 -07001106 def AffectedTestableFiles(self, include_deletes=None, **kwargs):
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +00001107 """Return a list of the existing text files in a change."""
1108 if include_deletes is not None:
agable0b65e732016-11-22 09:25:46 -08001109 warn("AffectedTeestableFiles(include_deletes=%s)"
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +00001110 " is deprecated and ignored" % str(include_deletes),
1111 category=DeprecationWarning,
1112 stacklevel=2)
Edward Lemura834f392019-10-22 22:23:00 +00001113 return list(filter(
1114 lambda x: x.IsTestableFile(),
1115 self.AffectedFiles(include_deletes=False, **kwargs)))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001116
agable0b65e732016-11-22 09:25:46 -08001117 def AffectedTextFiles(self, include_deletes=None):
1118 """An alias to AffectedTestableFiles for backwards compatibility."""
1119 return self.AffectedTestableFiles(include_deletes=include_deletes)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001120
agable0b65e732016-11-22 09:25:46 -08001121 def LocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001122 """Convenience function."""
agable0b65e732016-11-22 09:25:46 -08001123 return [af.LocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001124
agable0b65e732016-11-22 09:25:46 -08001125 def AbsoluteLocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001126 """Convenience function."""
agable0b65e732016-11-22 09:25:46 -08001127 return [af.AbsoluteLocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001128
1129 def RightHandSideLines(self):
1130 """An iterator over all text lines in "new" version of changed files.
1131
1132 Lists lines from new or modified text files in the change.
1133
1134 This is useful for doing line-by-line regex checks, like checking for
1135 trailing whitespace.
1136
1137 Yields:
1138 a 3 tuple:
1139 the AffectedFile instance of the current file;
1140 integer line number (1-based); and
1141 the contents of the line as a string.
1142 """
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +00001143 return _RightHandSideLinesImpl(
1144 x for x in self.AffectedFiles(include_deletes=False)
agable0b65e732016-11-22 09:25:46 -08001145 if x.IsTestableFile())
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001146
Jochen Eisingerd0573ec2017-04-13 10:55:06 +02001147 def OriginalOwnersFiles(self):
1148 """A map from path names of affected OWNERS files to their old content."""
1149 def owners_file_filter(f):
1150 return 'OWNERS' in os.path.split(f.LocalPath())[1]
1151 files = self.AffectedFiles(file_filter=owners_file_filter)
1152 return dict([(f.LocalPath(), f.OldContents()) for f in files])
1153
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001154
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001155class GitChange(Change):
1156 _AFFECTED_FILES = GitAffectedFile
maruel@chromium.orgc1938752011-04-12 23:11:13 +00001157 scm = 'git'
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +00001158
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001159 def AllFiles(self, root=None):
1160 """List all files under source control in the repo."""
1161 root = root or self.RepositoryRoot()
1162 return subprocess.check_output(
Aaron Gable7817f022017-12-12 09:43:17 -08001163 ['git', '-c', 'core.quotePath=false', 'ls-files', '--', '.'],
1164 cwd=root).splitlines()
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001165
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001166
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001167def ListRelevantPresubmitFiles(files, root):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001168 """Finds all presubmit files that apply to a given set of source files.
1169
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001170 If inherit-review-settings-ok is present right under root, looks for
1171 PRESUBMIT.py in directories enclosing root.
1172
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001173 Args:
1174 files: An iterable container containing file paths.
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001175 root: Path where to stop searching.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001176
1177 Return:
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001178 List of absolute paths of the existing PRESUBMIT.py scripts.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001179 """
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001180 files = [normpath(os.path.join(root, f)) for f in files]
1181
1182 # List all the individual directories containing files.
1183 directories = set([os.path.dirname(f) for f in files])
1184
1185 # Ignore root if inherit-review-settings-ok is present.
1186 if os.path.isfile(os.path.join(root, 'inherit-review-settings-ok')):
1187 root = None
1188
1189 # Collect all unique directories that may contain PRESUBMIT.py.
1190 candidates = set()
1191 for directory in directories:
1192 while True:
1193 if directory in candidates:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001194 break
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001195 candidates.add(directory)
1196 if directory == root:
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001197 break
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001198 parent_dir = os.path.dirname(directory)
1199 if parent_dir == directory:
1200 # We hit the system root directory.
1201 break
1202 directory = parent_dir
1203
1204 # Look for PRESUBMIT.py in all candidate directories.
1205 results = []
1206 for directory in sorted(list(candidates)):
tobiasjsff061c02016-08-17 03:23:57 -07001207 try:
1208 for f in os.listdir(directory):
1209 p = os.path.join(directory, f)
1210 if os.path.isfile(p) and re.match(
1211 r'PRESUBMIT.*\.py$', f) and not f.startswith('PRESUBMIT_test'):
1212 results.append(p)
1213 except OSError:
1214 pass
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001215
tobiasjs2836bcf2016-08-16 04:08:16 -07001216 logging.debug('Presubmit files: %s', ','.join(results))
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001217 return results
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001218
1219
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001220class GetTryMastersExecuter(object):
1221 @staticmethod
1222 def ExecPresubmitScript(script_text, presubmit_path, project, change):
1223 """Executes GetPreferredTryMasters() from a single presubmit script.
1224
1225 Args:
1226 script_text: The text of the presubmit script.
1227 presubmit_path: Project script to run.
1228 project: Project name to pass to presubmit script for bot selection.
1229
1230 Return:
1231 A map of try masters to map of builders to set of tests.
1232 """
1233 context = {}
1234 try:
Raul Tambre09e64b42019-05-14 01:57:22 +00001235 exec(compile(script_text, 'PRESUBMIT.py', 'exec', dont_inherit=True),
1236 context)
Raul Tambre7c938462019-05-24 16:35:35 +00001237 except Exception as e:
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001238 raise PresubmitFailure('"%s" had an exception.\n%s'
1239 % (presubmit_path, e))
1240
1241 function_name = 'GetPreferredTryMasters'
1242 if function_name not in context:
1243 return {}
1244 get_preferred_try_masters = context[function_name]
1245 if not len(inspect.getargspec(get_preferred_try_masters)[0]) == 2:
1246 raise PresubmitFailure(
1247 'Expected function "GetPreferredTryMasters" to take two arguments.')
1248 return get_preferred_try_masters(project, change)
1249
1250
rmistry@google.com5626a922015-02-26 14:03:30 +00001251class GetPostUploadExecuter(object):
1252 @staticmethod
1253 def ExecPresubmitScript(script_text, presubmit_path, cl, change):
1254 """Executes PostUploadHook() from a single presubmit script.
1255
1256 Args:
1257 script_text: The text of the presubmit script.
1258 presubmit_path: Project script to run.
1259 cl: The Changelist object.
1260 change: The Change object.
1261
1262 Return:
1263 A list of results objects.
1264 """
1265 context = {}
1266 try:
Raul Tambre09e64b42019-05-14 01:57:22 +00001267 exec(compile(script_text, 'PRESUBMIT.py', 'exec', dont_inherit=True),
1268 context)
Raul Tambre7c938462019-05-24 16:35:35 +00001269 except Exception as e:
rmistry@google.com5626a922015-02-26 14:03:30 +00001270 raise PresubmitFailure('"%s" had an exception.\n%s'
1271 % (presubmit_path, e))
1272
1273 function_name = 'PostUploadHook'
1274 if function_name not in context:
1275 return {}
1276 post_upload_hook = context[function_name]
1277 if not len(inspect.getargspec(post_upload_hook)[0]) == 3:
1278 raise PresubmitFailure(
1279 'Expected function "PostUploadHook" to take three arguments.')
1280 return post_upload_hook(cl, change, OutputApi(False))
1281
1282
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001283def _MergeMasters(masters1, masters2):
1284 """Merges two master maps. Merges also the tests of each builder."""
1285 result = {}
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00001286 for (master, builders) in itertools.chain(masters1.items(),
1287 masters2.items()):
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001288 new_builders = result.setdefault(master, {})
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00001289 for (builder, tests) in builders.items():
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001290 new_builders.setdefault(builder, set([])).update(tests)
1291 return result
1292
1293
1294def DoGetTryMasters(change,
1295 changed_files,
1296 repository_root,
1297 default_presubmit,
1298 project,
1299 verbose,
1300 output_stream):
1301 """Get the list of try masters from the presubmit scripts.
1302
1303 Args:
1304 changed_files: List of modified files.
1305 repository_root: The repository root.
1306 default_presubmit: A default presubmit script to execute in any case.
1307 project: Optional name of a project used in selecting trybots.
1308 verbose: Prints debug info.
1309 output_stream: A stream to write debug output to.
1310
1311 Return:
1312 Map of try masters to map of builders to set of tests.
1313 """
1314 presubmit_files = ListRelevantPresubmitFiles(changed_files, repository_root)
1315 if not presubmit_files and verbose:
1316 output_stream.write("Warning, no PRESUBMIT.py found.\n")
1317 results = {}
1318 executer = GetTryMastersExecuter()
1319
1320 if default_presubmit:
1321 if verbose:
1322 output_stream.write("Running default presubmit script.\n")
1323 fake_path = os.path.join(repository_root, 'PRESUBMIT.py')
1324 results = _MergeMasters(results, executer.ExecPresubmitScript(
1325 default_presubmit, fake_path, project, change))
1326 for filename in presubmit_files:
1327 filename = os.path.abspath(filename)
1328 if verbose:
1329 output_stream.write("Running %s\n" % filename)
1330 # Accept CRLF presubmit script.
1331 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1332 results = _MergeMasters(results, executer.ExecPresubmitScript(
1333 presubmit_script, filename, project, change))
1334
1335 # Make sets to lists again for later JSON serialization.
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00001336 for builders in results.values():
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001337 for builder in builders:
1338 builders[builder] = list(builders[builder])
1339
1340 if results and verbose:
1341 output_stream.write('%s\n' % str(results))
1342 return results
1343
1344
rmistry@google.com5626a922015-02-26 14:03:30 +00001345def DoPostUploadExecuter(change,
1346 cl,
1347 repository_root,
1348 verbose,
1349 output_stream):
1350 """Execute the post upload hook.
1351
1352 Args:
1353 change: The Change object.
1354 cl: The Changelist object.
1355 repository_root: The repository root.
1356 verbose: Prints debug info.
1357 output_stream: A stream to write debug output to.
1358 """
1359 presubmit_files = ListRelevantPresubmitFiles(
1360 change.LocalPaths(), repository_root)
1361 if not presubmit_files and verbose:
1362 output_stream.write("Warning, no PRESUBMIT.py found.\n")
1363 results = []
1364 executer = GetPostUploadExecuter()
1365 # The root presubmit file should be executed after the ones in subdirectories.
1366 # i.e. the specific post upload hooks should run before the general ones.
1367 # Thus, reverse the order provided by ListRelevantPresubmitFiles.
1368 presubmit_files.reverse()
1369
1370 for filename in presubmit_files:
1371 filename = os.path.abspath(filename)
1372 if verbose:
1373 output_stream.write("Running %s\n" % filename)
1374 # Accept CRLF presubmit script.
1375 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1376 results.extend(executer.ExecPresubmitScript(
1377 presubmit_script, filename, cl, change))
1378 output_stream.write('\n')
1379 if results:
1380 output_stream.write('** Post Upload Hook Messages **\n')
1381 for result in results:
1382 result.handle(output_stream)
1383 output_stream.write('\n')
1384
1385 return results
1386
1387
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001388class PresubmitExecuter(object):
Aaron Gable668c1d82018-04-03 10:19:16 -07001389 def __init__(self, change, committing, verbose,
Edward Lesmes8e282792018-04-03 18:50:29 -04001390 gerrit_obj, dry_run=None, thread_pool=None, parallel=False):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001391 """
1392 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001393 change: The Change object.
agable92bec4f2016-08-24 09:27:27 -07001394 committing: True if 'git cl land' is running, False if 'git cl upload' is.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001395 gerrit_obj: provides basic Gerrit codereview functionality.
1396 dry_run: if true, some Checks will be skipped.
Edward Lesmes8e282792018-04-03 18:50:29 -04001397 parallel: if true, all tests reported via input_api.RunTests for all
1398 PRESUBMIT files will be run in parallel.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001399 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001400 self.change = change
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001401 self.committing = committing
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001402 self.gerrit = gerrit_obj
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001403 self.verbose = verbose
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001404 self.dry_run = dry_run
Daniel Cheng7227d212017-11-17 08:12:37 -08001405 self.more_cc = []
Edward Lesmes8e282792018-04-03 18:50:29 -04001406 self.thread_pool = thread_pool
1407 self.parallel = parallel
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001408
1409 def ExecPresubmitScript(self, script_text, presubmit_path):
1410 """Executes a single presubmit script.
1411
1412 Args:
1413 script_text: The text of the presubmit script.
1414 presubmit_path: The path to the presubmit file (this will be reported via
1415 input_api.PresubmitLocalPath()).
1416
1417 Return:
1418 A list of result objects, empty if no problems.
1419 """
thakis@chromium.orgc6ef53a2014-11-04 00:13:54 +00001420
chase@chromium.org8e416c82009-10-06 04:30:44 +00001421 # Change to the presubmit file's directory to support local imports.
1422 main_path = os.getcwd()
1423 os.chdir(os.path.dirname(presubmit_path))
1424
1425 # Load the presubmit script into context.
dpranke@chromium.org970c5222011-03-12 00:32:24 +00001426 input_api = InputApi(self.change, presubmit_path, self.committing,
Aaron Gable668c1d82018-04-03 10:19:16 -07001427 self.verbose, gerrit_obj=self.gerrit,
Edward Lesmes8e282792018-04-03 18:50:29 -04001428 dry_run=self.dry_run, thread_pool=self.thread_pool,
1429 parallel=self.parallel)
Daniel Cheng7227d212017-11-17 08:12:37 -08001430 output_api = OutputApi(self.committing)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001431 context = {}
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001432 try:
Raul Tambre09e64b42019-05-14 01:57:22 +00001433 exec(compile(script_text, 'PRESUBMIT.py', 'exec', dont_inherit=True),
1434 context)
Raul Tambre7c938462019-05-24 16:35:35 +00001435 except Exception as e:
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001436 raise PresubmitFailure('"%s" had an exception.\n%s' % (presubmit_path, e))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001437
1438 # These function names must change if we make substantial changes to
1439 # the presubmit API that are not backwards compatible.
1440 if self.committing:
1441 function_name = 'CheckChangeOnCommit'
1442 else:
1443 function_name = 'CheckChangeOnUpload'
1444 if function_name in context:
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +01001445 try:
Daniel Cheng7227d212017-11-17 08:12:37 -08001446 context['__args'] = (input_api, output_api)
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +01001447 logging.debug('Running %s in %s', function_name, presubmit_path)
1448 result = eval(function_name + '(*__args)', context)
1449 logging.debug('Running %s done.', function_name)
Daniel Chengd36fce42017-11-21 21:52:52 -08001450 self.more_cc.extend(output_api.more_cc)
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +01001451 finally:
Edward Lemura834f392019-10-22 22:23:00 +00001452 for f in input_api._named_temporary_files:
1453 os.remove(f)
1454 if not isinstance(result, (tuple, list)):
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001455 raise PresubmitFailure(
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001456 'Presubmit functions must return a tuple or list')
1457 for item in result:
1458 if not isinstance(item, OutputApi.PresubmitResult):
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001459 raise PresubmitFailure(
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001460 'All presubmit results must be of types derived from '
1461 'output_api.PresubmitResult')
1462 else:
1463 result = () # no error since the script doesn't care about current event.
1464
chase@chromium.org8e416c82009-10-06 04:30:44 +00001465 # Return the process to the original working directory.
1466 os.chdir(main_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001467 return result
1468
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001469def DoPresubmitChecks(change,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001470 committing,
1471 verbose,
1472 output_stream,
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +00001473 input_stream,
maruel@chromium.orgb0dfd352009-06-10 14:12:54 +00001474 default_presubmit,
dpranke@chromium.org970c5222011-03-12 00:32:24 +00001475 may_prompt,
Aaron Gable668c1d82018-04-03 10:19:16 -07001476 gerrit_obj,
Edward Lesmes8e282792018-04-03 18:50:29 -04001477 dry_run=None,
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001478 parallel=False,
1479 json_output=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001480 """Runs all presubmit checks that apply to the files in the change.
1481
1482 This finds all PRESUBMIT.py files in directories enclosing the files in the
1483 change (up to the repository root) and calls the relevant entrypoint function
1484 depending on whether the change is being committed or uploaded.
1485
1486 Prints errors, warnings and notifications. Prompts the user for warnings
1487 when needed.
1488
1489 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001490 change: The Change object.
agable92bec4f2016-08-24 09:27:27 -07001491 committing: True if 'git cl land' is running, False if 'git cl upload' is.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001492 verbose: Prints debug info.
1493 output_stream: A stream to write output from presubmit tests to.
1494 input_stream: A stream to read input from the user.
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +00001495 default_presubmit: A default presubmit script to execute in any case.
Quinten Yearsley516fe7f2016-12-14 11:50:18 -08001496 may_prompt: Enable (y/n) questions on warning or error. If False,
1497 any questions are answered with yes by default.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001498 gerrit_obj: provides basic Gerrit codereview functionality.
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001499 dry_run: if true, some Checks will be skipped.
Edward Lesmes8e282792018-04-03 18:50:29 -04001500 parallel: if true, all tests specified by input_api.RunTests in all
1501 PRESUBMIT files will be run in parallel.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001502
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +00001503 Warning:
1504 If may_prompt is true, output_stream SHOULD be sys.stdout and input_stream
1505 SHOULD be sys.stdin.
1506
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001507 Return:
dpranke@chromium.org5ac21012011-03-16 02:58:25 +00001508 A PresubmitOutput object. Use output.should_continue() to figure out
1509 if there were errors or warnings and the caller should abort.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001510 """
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001511 old_environ = os.environ
1512 try:
1513 # Make sure python subprocesses won't generate .pyc files.
1514 os.environ = os.environ.copy()
1515 os.environ['PYTHONDONTWRITEBYTECODE'] = '1'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001516
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001517 output = PresubmitOutput(input_stream, output_stream)
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001518
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001519 if committing:
1520 output.write("Running presubmit commit checks ...\n")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001521 else:
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001522 output.write("Running presubmit upload checks ...\n")
1523 start_time = time.time()
1524 presubmit_files = ListRelevantPresubmitFiles(
agable0b65e732016-11-22 09:25:46 -08001525 change.AbsoluteLocalPaths(), change.RepositoryRoot())
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001526 if not presubmit_files and verbose:
maruel@chromium.orgfae707b2011-09-15 18:57:58 +00001527 output.write("Warning, no PRESUBMIT.py found.\n")
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001528 results = []
Edward Lesmes8e282792018-04-03 18:50:29 -04001529 thread_pool = ThreadPool()
Edward Lemur7e3c67f2018-07-20 20:52:49 +00001530 executer = PresubmitExecuter(change, committing, verbose, gerrit_obj,
1531 dry_run, thread_pool, parallel)
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001532 if default_presubmit:
1533 if verbose:
1534 output.write("Running default presubmit script.\n")
1535 fake_path = os.path.join(change.RepositoryRoot(), 'PRESUBMIT.py')
1536 results += executer.ExecPresubmitScript(default_presubmit, fake_path)
1537 for filename in presubmit_files:
1538 filename = os.path.abspath(filename)
1539 if verbose:
1540 output.write("Running %s\n" % filename)
1541 # Accept CRLF presubmit script.
1542 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1543 results += executer.ExecPresubmitScript(presubmit_script, filename)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001544
Edward Lesmes8e282792018-04-03 18:50:29 -04001545 results += thread_pool.RunAsync()
1546
Daniel Cheng7227d212017-11-17 08:12:37 -08001547 output.more_cc.extend(executer.more_cc)
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001548 errors = []
1549 notifications = []
1550 warnings = []
1551 for result in results:
1552 if result.fatal:
1553 errors.append(result)
1554 elif result.should_prompt:
1555 warnings.append(result)
1556 else:
1557 notifications.append(result)
pam@chromium.orged9a0832009-09-09 22:48:55 +00001558
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001559 if json_output:
1560 # Write the presubmit results to json output
1561 presubmit_results = {
1562 'errors': [
1563 error.json_format() for error in errors
1564 ],
1565 'notifications': [
1566 notification.json_format() for notification in notifications
1567 ],
1568 'warnings': [
1569 warning.json_format() for warning in warnings
1570 ]
1571 }
1572
Edward Lemura834f392019-10-22 22:23:00 +00001573 gclient_utils.FileWrite(
1574 json_output, json.dumps(presubmit_results, sort_keys=True))
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001575
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001576 output.write('\n')
1577 for name, items in (('Messages', notifications),
1578 ('Warnings', warnings),
1579 ('ERRORS', errors)):
1580 if items:
1581 output.write('** Presubmit %s **\n' % name)
1582 for item in items:
1583 item.handle(output)
1584 output.write('\n')
pam@chromium.orged9a0832009-09-09 22:48:55 +00001585
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001586 total_time = time.time() - start_time
1587 if total_time > 1.0:
1588 output.write("Presubmit checks took %.1fs to calculate.\n\n" % total_time)
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +00001589
Quinten Yearsley516fe7f2016-12-14 11:50:18 -08001590 if errors:
1591 output.fail()
1592 elif warnings:
1593 output.write('There were presubmit warnings. ')
1594 if may_prompt:
1595 output.prompt_yes_no('Are you sure you wish to continue? (y/N): ')
1596 else:
1597 output.write('Presubmit checks passed.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001598
1599 global _ASKED_FOR_FEEDBACK
1600 # Ask for feedback one time out of 5.
1601 if (len(results) and random.randint(0, 4) == 0 and not _ASKED_FOR_FEEDBACK):
maruel@chromium.org1ce8e662014-01-14 15:23:00 +00001602 output.write(
1603 'Was the presubmit check useful? If not, run "git cl presubmit -v"\n'
1604 'to figure out which PRESUBMIT.py was run, then run git blame\n'
1605 'on the file to figure out who to ask for help.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001606 _ASKED_FOR_FEEDBACK = True
1607 return output
1608 finally:
1609 os.environ = old_environ
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001610
1611
1612def ScanSubDirs(mask, recursive):
1613 if not recursive:
pgervais@chromium.orge57b09d2014-05-07 00:58:13 +00001614 return [x for x in glob.glob(mask) if x not in ('.svn', '.git')]
Lei Zhang9611c4c2017-04-04 01:41:56 -07001615
1616 results = []
1617 for root, dirs, files in os.walk('.'):
1618 if '.svn' in dirs:
1619 dirs.remove('.svn')
1620 if '.git' in dirs:
1621 dirs.remove('.git')
1622 for name in files:
1623 if fnmatch.fnmatch(name, mask):
1624 results.append(os.path.join(root, name))
1625 return results
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001626
1627
1628def ParseFiles(args, recursive):
tobiasjs2836bcf2016-08-16 04:08:16 -07001629 logging.debug('Searching for %s', args)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001630 files = []
1631 for arg in args:
maruel@chromium.orge3608df2009-11-10 20:22:57 +00001632 files.extend([('M', f) for f in ScanSubDirs(arg, recursive)])
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001633 return files
1634
1635
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001636def load_files(options, args):
1637 """Tries to determine the SCM."""
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001638 files = []
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001639 if args:
1640 files = ParseFiles(args, options.recursive)
agable0b65e732016-11-22 09:25:46 -08001641 change_scm = scm.determine_scm(options.root)
1642 if change_scm == 'git':
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001643 change_class = GitChange
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001644 upstream = options.upstream or None
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001645 if not files:
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001646 files = scm.GIT.CaptureStatus([], options.root, upstream)
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001647 else:
tobiasjs2836bcf2016-08-16 04:08:16 -07001648 logging.info('Doesn\'t seem under source control. Got %d files', len(args))
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001649 if not files:
1650 return None, None
1651 change_class = Change
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001652 return change_class, files
1653
1654
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001655@contextlib.contextmanager
1656def canned_check_filter(method_names):
1657 filtered = {}
1658 try:
1659 for method_name in method_names:
1660 if not hasattr(presubmit_canned_checks, method_name):
Aaron Gableecee74c2018-04-02 15:13:08 -07001661 logging.warn('Skipping unknown "canned" check %s' % method_name)
1662 continue
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001663 filtered[method_name] = getattr(presubmit_canned_checks, method_name)
1664 setattr(presubmit_canned_checks, method_name, lambda *_a, **_kw: [])
1665 yield
1666 finally:
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00001667 for name, method in filtered.items():
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001668 setattr(presubmit_canned_checks, name, method)
1669
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001670
sbc@chromium.org013731e2015-02-26 18:28:43 +00001671def main(argv=None):
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001672 parser = optparse.OptionParser(usage="%prog [options] <files...>",
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001673 version="%prog " + str(__version__))
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001674 parser.add_option("-c", "--commit", action="store_true", default=False,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001675 help="Use commit instead of upload checks")
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001676 parser.add_option("-u", "--upload", action="store_false", dest='commit',
1677 help="Use upload instead of commit checks")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001678 parser.add_option("-r", "--recursive", action="store_true",
1679 help="Act recursively")
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001680 parser.add_option("-v", "--verbose", action="count", default=0,
1681 help="Use 2 times for more debug info")
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001682 parser.add_option("--name", default='no name')
maruel@chromium.org58407af2011-04-12 23:15:57 +00001683 parser.add_option("--author")
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001684 parser.add_option("--description", default='')
1685 parser.add_option("--issue", type='int', default=0)
1686 parser.add_option("--patchset", type='int', default=0)
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001687 parser.add_option("--root", default=os.getcwd(),
1688 help="Search for PRESUBMIT.py up to this directory. "
1689 "If inherit-review-settings-ok is present in this "
1690 "directory, parent directories up to the root file "
1691 "system directories will also be searched.")
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001692 parser.add_option("--upstream",
1693 help="Git only: the base ref or upstream branch against "
1694 "which the diff should be computed.")
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001695 parser.add_option("--default_presubmit")
1696 parser.add_option("--may_prompt", action='store_true', default=False)
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001697 parser.add_option("--skip_canned", action='append', default=[],
1698 help="A list of checks to skip which appear in "
1699 "presubmit_canned_checks. Can be provided multiple times "
1700 "to skip multiple canned checks.")
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001701 parser.add_option("--dry_run", action='store_true',
1702 help=optparse.SUPPRESS_HELP)
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001703 parser.add_option("--gerrit_url", help=optparse.SUPPRESS_HELP)
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001704 parser.add_option("--gerrit_fetch", action='store_true',
1705 help=optparse.SUPPRESS_HELP)
Edward Lesmes8e282792018-04-03 18:50:29 -04001706 parser.add_option('--parallel', action='store_true',
1707 help='Run all tests specified by input_api.RunTests in all '
1708 'PRESUBMIT files in parallel.')
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001709 parser.add_option('--json_output',
1710 help='Write presubmit errors to json output.')
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001711
maruel@chromium.org82e5f282011-03-17 14:08:55 +00001712 options, args = parser.parse_args(argv)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001713
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001714 if options.verbose >= 2:
maruel@chromium.org7444c502011-02-09 14:02:11 +00001715 logging.basicConfig(level=logging.DEBUG)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001716 elif options.verbose:
1717 logging.basicConfig(level=logging.INFO)
1718 else:
1719 logging.basicConfig(level=logging.ERROR)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001720
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001721 change_class, files = load_files(options, args)
1722 if not change_class:
1723 parser.error('For unversioned directory, <files> is not optional.')
tobiasjs2836bcf2016-08-16 04:08:16 -07001724 logging.info('Found %d file(s).', len(files))
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001725
Aaron Gable668c1d82018-04-03 10:19:16 -07001726 gerrit_obj = None
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001727 if options.gerrit_url and options.gerrit_fetch:
tandrii@chromium.org83b1b232016-04-29 16:33:19 +00001728 assert options.issue and options.patchset
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001729 gerrit_obj = GerritAccessor(urlparse.urlparse(options.gerrit_url).netloc)
1730 options.author = gerrit_obj.GetChangeOwner(options.issue)
1731 options.description = gerrit_obj.GetChangeDescription(options.issue,
1732 options.patchset)
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001733 logging.info('Got author: "%s"', options.author)
1734 logging.info('Got description: """\n%s\n"""', options.description)
1735
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001736 try:
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001737 with canned_check_filter(options.skip_canned):
1738 results = DoPresubmitChecks(
1739 change_class(options.name,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001740 options.description,
1741 options.root,
1742 files,
1743 options.issue,
1744 options.patchset,
1745 options.author,
1746 upstream=options.upstream),
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001747 options.commit,
1748 options.verbose,
1749 sys.stdout,
1750 sys.stdin,
1751 options.default_presubmit,
1752 options.may_prompt,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001753 gerrit_obj,
Edward Lesmes8e282792018-04-03 18:50:29 -04001754 options.dry_run,
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001755 options.parallel,
1756 options.json_output)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001757 return not results.should_continue()
Raul Tambre7c938462019-05-24 16:35:35 +00001758 except PresubmitFailure as e:
Raul Tambre80ee78e2019-05-06 22:41:05 +00001759 print(e, file=sys.stderr)
1760 print('Maybe your depot_tools is out of date?', file=sys.stderr)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001761 return 2
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001762
1763
1764if __name__ == '__main__':
maruel@chromium.org35625c72011-03-23 17:34:02 +00001765 fix_encoding.fix_encoding()
sbc@chromium.org013731e2015-02-26 18:28:43 +00001766 try:
1767 sys.exit(main())
1768 except KeyboardInterrupt:
1769 sys.stderr.write('interrupted\n')
sergiybf8a3b382016-07-05 11:21:30 -07001770 sys.exit(2)