blob: 62d6db0e3a9fa4125916e3c4d8b2076ef11952d2 [file] [log] [blame]
maruel@chromium.org725f1c32011-04-01 20:24:54 +00001#!/usr/bin/env python
maruel@chromium.org3bbf2942012-01-10 16:52:06 +00002# Copyright (c) 2012 The Chromium Authors. All rights reserved.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Enables directory-specific presubmit checks to run at upload and/or commit.
7"""
8
Raul Tambre80ee78e2019-05-06 22:41:05 +00009from __future__ import print_function
10
stip@chromium.orgf7d31f52014-01-03 20:14:46 +000011__version__ = '1.8.0'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000012
13# TODO(joi) Add caching where appropriate/needed. The API is designed to allow
14# caching (between all different invocations of presubmit scripts for a given
15# change). We should add it as our presubmit scripts start feeling slow.
16
Takeshi Yoshino07a6bea2017-08-02 02:44:06 +090017import ast # Exposed through the API.
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +000018import contextlib
Yoshisato Yanagisawa406de132018-06-29 05:43:25 +000019import cpplint
dcheng091b7db2016-06-16 01:27:51 -070020import fnmatch # Exposed through the API.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000021import glob
asvitkine@chromium.org15169952011-09-27 14:30:53 +000022import inspect
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +000023import itertools
maruel@chromium.org4f6852c2012-04-20 20:39:20 +000024import json # Exposed through the API.
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +000025import logging
ilevy@chromium.orgbc117312013-04-20 03:57:56 +000026import multiprocessing
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000027import optparse
28import os # Somewhat exposed through the API.
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +000029import random
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000030import re # Exposed through the API.
Edward Lesmes8e282792018-04-03 18:50:29 -040031import signal
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000032import sys # Parts exposed through API.
33import tempfile # Exposed through the API.
Edward Lesmes8e282792018-04-03 18:50:29 -040034import threading
jam@chromium.org2a891dc2009-08-20 20:33:37 +000035import time
Edward Lemurde9e3ca2019-10-24 21:13:31 +000036import traceback
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))
Edward Lemurde9e3ca2019-10-24 21:13:31 +0000177 except Exception as e:
178 duration = time.time() - start
179 return test.message(
180 '%s exec failure (%4.2fs)\n%s' % (
181 test.name, duration, traceback.format_exc()))
182
Edward Lesmes8e282792018-04-03 18:50:29 -0400183 if p.returncode != 0:
184 return test.message(
185 '%s (%4.2fs) failed\n%s' % (test.name, duration, stdout))
186 if test.info:
187 return test.info('%s (%4.2fs)' % (test.name, duration))
188
189 def AddTests(self, tests, parallel=True):
190 if parallel:
191 self._tests.extend(tests)
192 else:
193 self._nonparallel_tests.extend(tests)
194
195 def RunAsync(self):
196 self._messages = []
197
198 def _WorkerFn():
199 while True:
200 test = None
201 with self._tests_lock:
202 if not self._tests:
203 break
204 test = self._tests.pop()
205 result = self.CallCommand(test)
206 if result:
207 with self._messages_lock:
208 self._messages.append(result)
209
210 def _StartDaemon():
211 t = threading.Thread(target=_WorkerFn)
212 t.daemon = True
213 t.start()
214 return t
215
216 while self._nonparallel_tests:
217 test = self._nonparallel_tests.pop()
218 result = self.CallCommand(test)
219 if result:
220 self._messages.append(result)
221
222 if self._tests:
223 threads = [_StartDaemon() for _ in range(self._pool_size)]
224 for worker in threads:
225 worker.join()
226
227 return self._messages
228
229
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000230def normpath(path):
231 '''Version of os.path.normpath that also changes backward slashes to
232 forward slashes when not running on Windows.
233 '''
234 # This is safe to always do because the Windows version of os.path.normpath
235 # will replace forward slashes with backward slashes.
236 path = path.replace(os.sep, '/')
237 return os.path.normpath(path)
238
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000239
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000240def _RightHandSideLinesImpl(affected_files):
241 """Implements RightHandSideLines for InputApi and GclChange."""
242 for af in affected_files:
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000243 lines = af.ChangedContents()
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000244 for line in lines:
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000245 yield (af, line[0], line[1])
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000246
247
dpranke@chromium.org5ac21012011-03-16 02:58:25 +0000248class PresubmitOutput(object):
249 def __init__(self, input_stream=None, output_stream=None):
250 self.input_stream = input_stream
251 self.output_stream = output_stream
252 self.reviewers = []
Daniel Cheng7227d212017-11-17 08:12:37 -0800253 self.more_cc = []
dpranke@chromium.org5ac21012011-03-16 02:58:25 +0000254 self.written_output = []
255 self.error_count = 0
256
257 def prompt_yes_no(self, prompt_string):
258 self.write(prompt_string)
259 if self.input_stream:
260 response = self.input_stream.readline().strip().lower()
261 if response not in ('y', 'yes'):
262 self.fail()
263 else:
264 self.fail()
265
266 def fail(self):
267 self.error_count += 1
268
269 def should_continue(self):
270 return not self.error_count
271
272 def write(self, s):
273 self.written_output.append(s)
274 if self.output_stream:
275 self.output_stream.write(s)
276
277 def getvalue(self):
278 return ''.join(self.written_output)
279
280
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000281# Top level object so multiprocessing can pickle
282# Public access through OutputApi object.
283class _PresubmitResult(object):
284 """Base class for result objects."""
285 fatal = False
286 should_prompt = False
287
288 def __init__(self, message, items=None, long_text=''):
289 """
290 message: A short one-line message to indicate errors.
291 items: A list of short strings to indicate where errors occurred.
292 long_text: multi-line text output, e.g. from another tool
293 """
294 self._message = message
295 self._items = items or []
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000296 self._long_text = long_text.rstrip()
297
298 def handle(self, output):
299 output.write(self._message)
300 output.write('\n')
301 for index, item in enumerate(self._items):
302 output.write(' ')
303 # Write separately in case it's unicode.
304 output.write(str(item))
305 if index < len(self._items) - 1:
306 output.write(' \\')
307 output.write('\n')
308 if self._long_text:
309 output.write('\n***************\n')
310 # Write separately in case it's unicode.
311 output.write(self._long_text)
312 output.write('\n***************\n')
313 if self.fatal:
314 output.fail()
315
Debrian Figueroadd2737e2019-06-21 23:50:13 +0000316 def json_format(self):
317 return {
318 'message': self._message,
Debrian Figueroa6095d402019-06-28 18:47:18 +0000319 'items': [str(item) for item in self._items],
Debrian Figueroadd2737e2019-06-21 23:50:13 +0000320 'long_text': self._long_text,
321 'fatal': self.fatal
322 }
323
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000324
325# Top level object so multiprocessing can pickle
326# Public access through OutputApi object.
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000327class _PresubmitError(_PresubmitResult):
328 """A hard presubmit error."""
329 fatal = True
330
331
332# Top level object so multiprocessing can pickle
333# Public access through OutputApi object.
334class _PresubmitPromptWarning(_PresubmitResult):
335 """An warning that prompts the user if they want to continue."""
336 should_prompt = True
337
338
339# Top level object so multiprocessing can pickle
340# Public access through OutputApi object.
341class _PresubmitNotifyResult(_PresubmitResult):
342 """Just print something to the screen -- but it's not even a warning."""
343 pass
344
345
346# Top level object so multiprocessing can pickle
347# Public access through OutputApi object.
348class _MailTextResult(_PresubmitResult):
349 """A warning that should be included in the review request email."""
350 def __init__(self, *args, **kwargs):
351 super(_MailTextResult, self).__init__()
352 raise NotImplementedError()
353
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000354class GerritAccessor(object):
355 """Limited Gerrit functionality for canned presubmit checks to work.
356
357 To avoid excessive Gerrit calls, caches the results.
358 """
359
360 def __init__(self, host):
361 self.host = host
362 self.cache = {}
363
364 def _FetchChangeDetail(self, issue):
365 # Separate function to be easily mocked in tests.
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +0100366 try:
367 return gerrit_util.GetChangeDetail(
368 self.host, str(issue),
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700369 ['ALL_REVISIONS', 'DETAILED_LABELS', 'ALL_COMMITS'])
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +0100370 except gerrit_util.GerritError as e:
371 if e.http_status == 404:
372 raise Exception('Either Gerrit issue %s doesn\'t exist, or '
373 'no credentials to fetch issue details' % issue)
374 raise
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000375
376 def GetChangeInfo(self, issue):
377 """Returns labels and all revisions (patchsets) for this issue.
378
379 The result is a dictionary according to Gerrit REST Api.
380 https://gerrit-review.googlesource.com/Documentation/rest-api.html
381
382 However, API isn't very clear what's inside, so see tests for example.
383 """
384 assert issue
385 cache_key = int(issue)
386 if cache_key not in self.cache:
387 self.cache[cache_key] = self._FetchChangeDetail(issue)
388 return self.cache[cache_key]
389
390 def GetChangeDescription(self, issue, patchset=None):
391 """If patchset is none, fetches current patchset."""
392 info = self.GetChangeInfo(issue)
393 # info is a reference to cache. We'll modify it here adding description to
394 # it to the right patchset, if it is not yet there.
395
396 # Find revision info for the patchset we want.
397 if patchset is not None:
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000398 for rev, rev_info in info['revisions'].items():
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000399 if str(rev_info['_number']) == str(patchset):
400 break
401 else:
402 raise Exception('patchset %s doesn\'t exist in issue %s' % (
403 patchset, issue))
404 else:
405 rev = info['current_revision']
406 rev_info = info['revisions'][rev]
407
Andrii Shyshkalov9c3a4642017-01-24 17:41:22 +0100408 return rev_info['commit']['message']
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000409
Mun Yong Jang603d01e2017-12-19 16:38:30 -0800410 def GetDestRef(self, issue):
411 ref = self.GetChangeInfo(issue)['branch']
412 if not ref.startswith('refs/'):
413 # NOTE: it is possible to create 'refs/x' branch,
414 # aka 'refs/heads/refs/x'. However, this is ill-advised.
415 ref = 'refs/heads/%s' % ref
416 return ref
417
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000418 def GetChangeOwner(self, issue):
419 return self.GetChangeInfo(issue)['owner']['email']
420
421 def GetChangeReviewers(self, issue, approving_only=True):
Aaron Gable8b478f02017-07-31 15:33:19 -0700422 changeinfo = self.GetChangeInfo(issue)
423 if approving_only:
424 labelinfo = changeinfo.get('labels', {}).get('Code-Review', {})
425 values = labelinfo.get('values', {}).keys()
426 try:
427 max_value = max(int(v) for v in values)
428 reviewers = [r for r in labelinfo.get('all', [])
429 if r.get('value', 0) == max_value]
430 except ValueError: # values is the empty list
431 reviewers = []
432 else:
433 reviewers = changeinfo.get('reviewers', {}).get('REVIEWER', [])
434 return [r.get('email') for r in reviewers]
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000435
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000436
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000437class OutputApi(object):
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000438 """An instance of OutputApi gets passed to presubmit scripts so that they
439 can output various types of results.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000440 """
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000441 PresubmitResult = _PresubmitResult
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000442 PresubmitError = _PresubmitError
443 PresubmitPromptWarning = _PresubmitPromptWarning
444 PresubmitNotifyResult = _PresubmitNotifyResult
445 MailTextResult = _MailTextResult
446
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000447 def __init__(self, is_committing):
448 self.is_committing = is_committing
Daniel Cheng7227d212017-11-17 08:12:37 -0800449 self.more_cc = []
450
451 def AppendCC(self, cc):
452 """Appends a user to cc for this change."""
453 self.more_cc.append(cc)
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000454
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000455 def PresubmitPromptOrNotify(self, *args, **kwargs):
456 """Warn the user when uploading, but only notify if committing."""
457 if self.is_committing:
458 return self.PresubmitNotifyResult(*args, **kwargs)
459 return self.PresubmitPromptWarning(*args, **kwargs)
460
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000461
462class InputApi(object):
463 """An instance of this object is passed to presubmit scripts so they can
464 know stuff about the change they're looking at.
465 """
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000466 # Method could be a function
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800467 # pylint: disable=no-self-use
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000468
maruel@chromium.org3410d912009-06-09 20:56:16 +0000469 # File extensions that are considered source files from a style guide
470 # perspective. Don't modify this list from a presubmit script!
maruel@chromium.orgc33455a2011-06-24 19:14:18 +0000471 #
472 # Files without an extension aren't included in the list. If you want to
473 # filter them as source files, add r"(^|.*?[\\\/])[^.]+$" to the white list.
474 # Note that ALL CAPS files are black listed in DEFAULT_BLACK_LIST below.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000475 DEFAULT_WHITE_LIST = (
476 # C++ and friends
maruel@chromium.orgfe1211a2011-05-28 18:54:17 +0000477 r".+\.c$", r".+\.cc$", r".+\.cpp$", r".+\.h$", r".+\.m$", r".+\.mm$",
478 r".+\.inl$", r".+\.asm$", r".+\.hxx$", r".+\.hpp$", r".+\.s$", r".+\.S$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000479 # Scripts
maruel@chromium.orgfe1211a2011-05-28 18:54:17 +0000480 r".+\.js$", r".+\.py$", r".+\.sh$", r".+\.rb$", r".+\.pl$", r".+\.pm$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000481 # Other
Sergey Ulanov166bc4c2018-04-30 17:03:38 -0700482 r".+\.java$", r".+\.mk$", r".+\.am$", r".+\.css$", r".+\.mojom$",
483 r".+\.fidl$"
maruel@chromium.org3410d912009-06-09 20:56:16 +0000484 )
485
486 # Path regexp that should be excluded from being considered containing source
487 # files. Don't modify this list from a presubmit script!
488 DEFAULT_BLACK_LIST = (
gavinp@chromium.org656326d2012-08-13 00:43:57 +0000489 r"testing_support[\\\/]google_appengine[\\\/].*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000490 r".*\bexperimental[\\\/].*",
Kent Tamura179dd1e2018-04-26 15:07:41 +0900491 # Exclude third_party/.* but NOT third_party/{WebKit,blink}
492 # (crbug.com/539768 and crbug.com/836555).
493 r".*\bthird_party[\\\/](?!(WebKit|blink)[\\\/]).*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000494 # Output directories (just in case)
495 r".*\bDebug[\\\/].*",
496 r".*\bRelease[\\\/].*",
497 r".*\bxcodebuild[\\\/].*",
thakis@chromium.orgc1c96352013-10-09 19:50:27 +0000498 r".*\bout[\\\/].*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000499 # All caps files like README and LICENCE.
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000500 r".*\b[A-Z0-9_]{2,}$",
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000501 # SCM (can happen in dual SCM configuration). (Slightly over aggressive)
maruel@chromium.org5d0dc432011-01-03 02:40:37 +0000502 r"(|.*[\\\/])\.git[\\\/].*",
503 r"(|.*[\\\/])\.svn[\\\/].*",
maruel@chromium.org7ccb4bb2011-11-07 20:26:20 +0000504 # There is no point in processing a patch file.
505 r".+\.diff$",
506 r".+\.patch$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000507 )
508
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000509 def __init__(self, change, presubmit_path, is_committing,
Edward Lesmes8e282792018-04-03 18:50:29 -0400510 verbose, gerrit_obj, dry_run=None, thread_pool=None, parallel=False):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000511 """Builds an InputApi object.
512
513 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000514 change: A presubmit.Change object.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000515 presubmit_path: The path to the presubmit script being processed.
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000516 is_committing: True if the change is about to be committed.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000517 gerrit_obj: provides basic Gerrit codereview functionality.
518 dry_run: if true, some Checks will be skipped.
Edward Lesmes8e282792018-04-03 18:50:29 -0400519 parallel: if true, all tests reported via input_api.RunTests for all
520 PRESUBMIT files will be run in parallel.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000521 """
maruel@chromium.org9711bba2009-05-22 23:51:39 +0000522 # Version number of the presubmit_support script.
523 self.version = [int(x) for x in __version__.split('.')]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000524 self.change = change
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000525 self.is_committing = is_committing
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000526 self.gerrit = gerrit_obj
tandrii@chromium.org57bafac2016-04-28 05:09:03 +0000527 self.dry_run = dry_run
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000528
Edward Lesmes8e282792018-04-03 18:50:29 -0400529 self.parallel = parallel
530 self.thread_pool = thread_pool or ThreadPool()
531
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000532 # We expose various modules and functions as attributes of the input_api
533 # so that presubmit scripts don't have to import them.
Takeshi Yoshino07a6bea2017-08-02 02:44:06 +0900534 self.ast = ast
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000535 self.basename = os.path.basename
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000536 self.cpplint = cpplint
dcheng091b7db2016-06-16 01:27:51 -0700537 self.fnmatch = fnmatch
Yoshisato Yanagisawa04600b42019-03-15 03:03:41 +0000538 self.gclient_paths = gclient_paths
Yoshisato Yanagisawa57dd17b2019-03-22 09:10:29 +0000539 # TODO(yyanagisawa): stop exposing this when python3 become default.
540 # Since python3's tempfile has TemporaryDirectory, we do not need this.
541 self.temporary_directory = gclient_utils.temporary_directory
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000542 self.glob = glob.glob
maruel@chromium.orgfb11c7b2010-03-18 18:22:14 +0000543 self.json = json
maruel@chromium.org6fba34d2011-06-02 13:45:12 +0000544 self.logging = logging.getLogger('PRESUBMIT')
maruel@chromium.org2b5ce562011-03-31 16:15:44 +0000545 self.os_listdir = os.listdir
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000546 self.os_path = os.path
pgervais@chromium.orgbd0cace2014-10-02 23:23:46 +0000547 self.os_stat = os.stat
Yoshisato Yanagisawa406de132018-06-29 05:43:25 +0000548 self.os_walk = os.walk
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000549 self.re = re
550 self.subprocess = subprocess
Edward Lemurb9830242019-10-30 22:19:20 +0000551 self.sys = sys
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000552 self.tempfile = tempfile
dpranke@chromium.org0d1bdea2011-03-24 22:54:38 +0000553 self.time = time
maruel@chromium.org1487d532009-06-06 00:22:57 +0000554 self.unittest = unittest
Edward Lemurb9830242019-10-30 22:19:20 +0000555 if sys.version_info.major == 2:
556 self.urllib2 = urllib2
Edward Lemur16af3562019-10-17 22:11:33 +0000557 self.urllib_request = urllib_request
558 self.urllib_error = urllib_error
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000559
Robert Iannucci50258932018-03-19 10:30:59 -0700560 self.is_windows = sys.platform == 'win32'
561
Edward Lemurb9646622019-10-25 20:57:35 +0000562 # Set python_executable to 'vpython' in order to allow scripts in other
563 # repos (e.g. src.git) to automatically pick up that repo's .vpython file,
564 # instead of inheriting the one in depot_tools.
565 self.python_executable = 'vpython'
maruel@chromium.orgc0b22972009-06-25 16:19:14 +0000566 self.environ = os.environ
567
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000568 # InputApi.platform is the platform you're currently running on.
569 self.platform = sys.platform
570
iannucci@chromium.org0af3bb32015-06-12 20:44:35 +0000571 self.cpu_count = multiprocessing.cpu_count()
572
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000573 # The local path of the currently-being-processed presubmit script.
maruel@chromium.org3d235242009-05-15 12:40:48 +0000574 self._current_presubmit_path = os.path.dirname(presubmit_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000575
576 # We carry the canned checks so presubmit scripts can easily use them.
577 self.canned_checks = presubmit_canned_checks
578
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +0100579 # Temporary files we must manually remove at the end of a run.
580 self._named_temporary_files = []
Jochen Eisinger72606f82017-04-04 10:44:18 +0200581
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000582 # TODO(dpranke): figure out a list of all approved owners for a repo
583 # in order to be able to handle wildcard OWNERS files?
584 self.owners_db = owners.Database(change.RepositoryRoot(),
Edward Lemurb9830242019-10-30 22:19:20 +0000585 fopen=open, os_path=self.os_path)
Jochen Eisinger76f5fc62017-04-07 16:27:46 +0200586 self.owners_finder = owners_finder.OwnersFinder
maruel@chromium.org899e1c12011-04-07 17:03:18 +0000587 self.verbose = verbose
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000588 self.Command = CommandData
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000589
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000590 # Replace <hash_map> and <hash_set> as headers that need to be included
danakj@chromium.org18278522013-06-11 22:42:32 +0000591 # with "base/containers/hash_tables.h" instead.
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000592 # Access to a protected member _XX of a client class
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800593 # pylint: disable=protected-access
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000594 self.cpplint._re_pattern_templates = [
danakj@chromium.org18278522013-06-11 22:42:32 +0000595 (a, b, 'base/containers/hash_tables.h')
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000596 if header in ('<hash_map>', '<hash_set>') else (a, b, header)
597 for (a, b, header) in cpplint._re_pattern_templates
598 ]
599
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000600 def PresubmitLocalPath(self):
601 """Returns the local path of the presubmit script currently being run.
602
603 This is useful if you don't want to hard-code absolute paths in the
604 presubmit script. For example, It can be used to find another file
605 relative to the PRESUBMIT.py script, so the whole tree can be branched and
606 the presubmit script still works, without editing its content.
607 """
maruel@chromium.org3d235242009-05-15 12:40:48 +0000608 return self._current_presubmit_path
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000609
agable0b65e732016-11-22 09:25:46 -0800610 def AffectedFiles(self, include_deletes=True, file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000611 """Same as input_api.change.AffectedFiles() except only lists files
612 (and optionally directories) in the same directory as the current presubmit
613 script, or subdirectories thereof.
614 """
maruel@chromium.org3d235242009-05-15 12:40:48 +0000615 dir_with_slash = normpath("%s/" % self.PresubmitLocalPath())
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000616 if len(dir_with_slash) == 1:
617 dir_with_slash = ''
sail@chromium.org5538e022011-05-12 17:53:16 +0000618
Edward Lemurb9830242019-10-30 22:19:20 +0000619 return list(filter(
maruel@chromium.org4661e0c2009-06-04 00:45:26 +0000620 lambda x: normpath(x.AbsoluteLocalPath()).startswith(dir_with_slash),
Edward Lemurb9830242019-10-30 22:19:20 +0000621 self.change.AffectedFiles(include_deletes, file_filter)))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000622
agable0b65e732016-11-22 09:25:46 -0800623 def LocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000624 """Returns local paths of input_api.AffectedFiles()."""
agable0b65e732016-11-22 09:25:46 -0800625 paths = [af.LocalPath() for af in self.AffectedFiles()]
pgervais@chromium.org2f64f782014-04-25 00:12:33 +0000626 logging.debug("LocalPaths: %s", paths)
627 return paths
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000628
agable0b65e732016-11-22 09:25:46 -0800629 def AbsoluteLocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000630 """Returns absolute local paths of input_api.AffectedFiles()."""
agable0b65e732016-11-22 09:25:46 -0800631 return [af.AbsoluteLocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000632
John Budorick16162372018-04-18 10:39:53 -0700633 def AffectedTestableFiles(self, include_deletes=None, **kwargs):
agable0b65e732016-11-22 09:25:46 -0800634 """Same as input_api.change.AffectedTestableFiles() except only lists files
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000635 in the same directory as the current presubmit script, or subdirectories
636 thereof.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000637 """
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000638 if include_deletes is not None:
agable0b65e732016-11-22 09:25:46 -0800639 warn("AffectedTestableFiles(include_deletes=%s)"
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000640 " is deprecated and ignored" % str(include_deletes),
641 category=DeprecationWarning,
642 stacklevel=2)
Edward Lemurb9830242019-10-30 22:19:20 +0000643 return list(filter(
644 lambda x: x.IsTestableFile(),
645 self.AffectedFiles(include_deletes=False, **kwargs)))
agable0b65e732016-11-22 09:25:46 -0800646
647 def AffectedTextFiles(self, include_deletes=None):
648 """An alias to AffectedTestableFiles for backwards compatibility."""
649 return self.AffectedTestableFiles(include_deletes=include_deletes)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000650
maruel@chromium.org3410d912009-06-09 20:56:16 +0000651 def FilterSourceFile(self, affected_file, white_list=None, black_list=None):
652 """Filters out files that aren't considered "source file".
653
654 If white_list or black_list is None, InputApi.DEFAULT_WHITE_LIST
655 and InputApi.DEFAULT_BLACK_LIST is used respectively.
656
657 The lists will be compiled as regular expression and
658 AffectedFile.LocalPath() needs to pass both list.
659
660 Note: Copy-paste this function to suit your needs or use a lambda function.
661 """
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000662 def Find(affected_file, items):
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000663 local_path = affected_file.LocalPath()
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000664 for item in items:
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000665 if self.re.match(item, local_path):
maruel@chromium.org3410d912009-06-09 20:56:16 +0000666 return True
667 return False
668 return (Find(affected_file, white_list or self.DEFAULT_WHITE_LIST) and
669 not Find(affected_file, black_list or self.DEFAULT_BLACK_LIST))
670
671 def AffectedSourceFiles(self, source_file):
agable0b65e732016-11-22 09:25:46 -0800672 """Filter the list of AffectedTestableFiles by the function source_file.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000673
674 If source_file is None, InputApi.FilterSourceFile() is used.
675 """
676 if not source_file:
677 source_file = self.FilterSourceFile
Edward Lemurb9830242019-10-30 22:19:20 +0000678 return list(filter(source_file, self.AffectedTestableFiles()))
maruel@chromium.org3410d912009-06-09 20:56:16 +0000679
680 def RightHandSideLines(self, source_file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000681 """An iterator over all text lines in "new" version of changed files.
682
683 Only lists lines from new or modified text files in the change that are
684 contained by the directory of the currently executing presubmit script.
685
686 This is useful for doing line-by-line regex checks, like checking for
687 trailing whitespace.
688
689 Yields:
690 a 3 tuple:
691 the AffectedFile instance of the current file;
692 integer line number (1-based); and
693 the contents of the line as a string.
maruel@chromium.org1487d532009-06-06 00:22:57 +0000694
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000695 Note: The carriage return (LF or CR) is stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000696 """
maruel@chromium.org3410d912009-06-09 20:56:16 +0000697 files = self.AffectedSourceFiles(source_file_filter)
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000698 return _RightHandSideLinesImpl(files)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000699
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000700 def ReadFile(self, file_item, mode='r'):
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000701 """Reads an arbitrary file.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000702
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000703 Deny reading anything outside the repository.
704 """
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000705 if isinstance(file_item, AffectedFile):
706 file_item = file_item.AbsoluteLocalPath()
707 if not file_item.startswith(self.change.RepositoryRoot()):
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000708 raise IOError('Access outside the repository root is denied.')
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000709 return gclient_utils.FileRead(file_item, mode)
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000710
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +0100711 def CreateTemporaryFile(self, **kwargs):
712 """Returns a named temporary file that must be removed with a call to
713 RemoveTemporaryFiles().
714
715 All keyword arguments are forwarded to tempfile.NamedTemporaryFile(),
716 except for |delete|, which is always set to False.
717
718 Presubmit checks that need to create a temporary file and pass it for
719 reading should use this function instead of NamedTemporaryFile(), as
720 Windows fails to open a file that is already open for writing.
721
722 with input_api.CreateTemporaryFile() as f:
723 f.write('xyz')
724 f.close()
725 input_api.subprocess.check_output(['script-that', '--reads-from',
726 f.name])
727
728
729 Note that callers of CreateTemporaryFile() should not worry about removing
730 any temporary file; this is done transparently by the presubmit handling
731 code.
732 """
733 if 'delete' in kwargs:
734 # Prevent users from passing |delete|; we take care of file deletion
735 # ourselves and this prevents unintuitive error messages when we pass
736 # delete=False and 'delete' is also in kwargs.
737 raise TypeError('CreateTemporaryFile() does not take a "delete" '
738 'argument, file deletion is handled automatically by '
739 'the same presubmit_support code that creates InputApi '
740 'objects.')
741 temp_file = self.tempfile.NamedTemporaryFile(delete=False, **kwargs)
742 self._named_temporary_files.append(temp_file.name)
743 return temp_file
744
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000745 @property
746 def tbr(self):
747 """Returns if a change is TBR'ed."""
Jeremy Romandce22502017-06-20 15:37:29 -0400748 return 'TBR' in self.change.tags or self.change.TBRsFromDescription()
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000749
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +0000750 def RunTests(self, tests_mix, parallel=True):
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000751 tests = []
752 msgs = []
753 for t in tests_mix:
Edward Lesmes8e282792018-04-03 18:50:29 -0400754 if isinstance(t, OutputApi.PresubmitResult) and t:
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000755 msgs.append(t)
756 else:
757 assert issubclass(t.message, _PresubmitResult)
758 tests.append(t)
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +0000759 if self.verbose:
760 t.info = _PresubmitNotifyResult
Edward Lemur1037c742018-05-01 18:56:04 -0400761 if not t.kwargs.get('cwd'):
762 t.kwargs['cwd'] = self.PresubmitLocalPath()
Edward Lesmes8e282792018-04-03 18:50:29 -0400763 self.thread_pool.AddTests(tests, parallel)
Edward Lemur21000eb2019-05-24 23:25:58 +0000764 # When self.parallel is True (i.e. --parallel is passed as an option)
765 # RunTests doesn't actually run tests. It adds them to a ThreadPool that
766 # will run all tests once all PRESUBMIT files are processed.
767 # Otherwise, it will run them and return the results.
768 if not self.parallel:
Edward Lesmes8e282792018-04-03 18:50:29 -0400769 msgs.extend(self.thread_pool.RunAsync())
770 return msgs
scottmg86099d72016-09-01 09:16:51 -0700771
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000772
nick@chromium.orgff526192013-06-10 19:30:26 +0000773class _DiffCache(object):
774 """Caches diffs retrieved from a particular SCM."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000775 def __init__(self, upstream=None):
776 """Stores the upstream revision against which all diffs will be computed."""
777 self._upstream = upstream
nick@chromium.orgff526192013-06-10 19:30:26 +0000778
779 def GetDiff(self, path, local_root):
780 """Get the diff for a particular path."""
781 raise NotImplementedError()
782
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700783 def GetOldContents(self, path, local_root):
784 """Get the old version for a particular path."""
785 raise NotImplementedError()
786
nick@chromium.orgff526192013-06-10 19:30:26 +0000787
nick@chromium.orgff526192013-06-10 19:30:26 +0000788class _GitDiffCache(_DiffCache):
789 """DiffCache implementation for git; gets all file diffs at once."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000790 def __init__(self, upstream):
791 super(_GitDiffCache, self).__init__(upstream=upstream)
nick@chromium.orgff526192013-06-10 19:30:26 +0000792 self._diffs_by_file = None
793
794 def GetDiff(self, path, local_root):
795 if not self._diffs_by_file:
796 # Compute a single diff for all files and parse the output; should
797 # with git this is much faster than computing one diff for each file.
798 diffs = {}
799
800 # Don't specify any filenames below, because there are command line length
801 # limits on some platforms and GenerateDiff would fail.
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000802 unified_diff = scm.GIT.GenerateDiff(local_root, files=[], full_move=True,
803 branch=self._upstream)
nick@chromium.orgff526192013-06-10 19:30:26 +0000804
805 # This regex matches the path twice, separated by a space. Note that
806 # filename itself may contain spaces.
807 file_marker = re.compile('^diff --git (?P<filename>.*) (?P=filename)$')
808 current_diff = []
809 keep_line_endings = True
810 for x in unified_diff.splitlines(keep_line_endings):
811 match = file_marker.match(x)
812 if match:
813 # Marks the start of a new per-file section.
814 diffs[match.group('filename')] = current_diff = [x]
815 elif x.startswith('diff --git'):
816 raise PresubmitFailure('Unexpected diff line: %s' % x)
817 else:
818 current_diff.append(x)
819
820 self._diffs_by_file = dict(
821 (normpath(path), ''.join(diff)) for path, diff in diffs.items())
822
823 if path not in self._diffs_by_file:
824 raise PresubmitFailure(
825 'Unified diff did not contain entry for file %s' % path)
826
827 return self._diffs_by_file[path]
828
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700829 def GetOldContents(self, path, local_root):
830 return scm.GIT.GetOldContents(local_root, path, branch=self._upstream)
831
nick@chromium.orgff526192013-06-10 19:30:26 +0000832
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000833class AffectedFile(object):
834 """Representation of a file in a change."""
nick@chromium.orgff526192013-06-10 19:30:26 +0000835
836 DIFF_CACHE = _DiffCache
837
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000838 # Method could be a function
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800839 # pylint: disable=no-self-use
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000840 def __init__(self, path, action, repository_root, diff_cache):
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000841 self._path = path
842 self._action = action
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000843 self._local_root = repository_root
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000844 self._is_directory = None
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000845 self._cached_changed_contents = None
846 self._cached_new_contents = None
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000847 self._diff_cache = diff_cache
tobiasjs2836bcf2016-08-16 04:08:16 -0700848 logging.debug('%s(%s)', self.__class__.__name__, self._path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000849
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000850 def LocalPath(self):
851 """Returns the path of this file on the local disk relative to client root.
Andrew Grieve92b8b992017-11-02 09:42:24 -0400852
853 This should be used for error messages but not for accessing files,
854 because presubmit checks are run with CWD=PresubmitLocalPath() (which is
855 often != client root).
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000856 """
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000857 return normpath(self._path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000858
859 def AbsoluteLocalPath(self):
860 """Returns the absolute path of this file on the local disk.
861 """
chase@chromium.org8e416c82009-10-06 04:30:44 +0000862 return os.path.abspath(os.path.join(self._local_root, self.LocalPath()))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000863
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000864 def Action(self):
865 """Returns the action on this opened file, e.g. A, M, D, etc."""
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000866 return self._action
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000867
agable0b65e732016-11-22 09:25:46 -0800868 def IsTestableFile(self):
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000869 """Returns True if the file is a text file and not a binary file.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000870
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000871 Deleted files are not text file."""
maruel@chromium.org1e08c002009-05-28 19:09:33 +0000872 raise NotImplementedError() # Implement when needed
873
agable0b65e732016-11-22 09:25:46 -0800874 def IsTextFile(self):
875 """An alias to IsTestableFile for backwards compatibility."""
876 return self.IsTestableFile()
877
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700878 def OldContents(self):
879 """Returns an iterator over the lines in the old version of file.
880
Daniel Cheng2da34fe2017-03-21 20:42:12 -0700881 The old version is the file before any modifications in the user's
882 workspace, i.e. the "left hand side".
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700883
884 Contents will be empty if the file is a directory or does not exist.
885 Note: The carriage returns (LF or CR) are stripped off.
886 """
887 return self._diff_cache.GetOldContents(self.LocalPath(),
888 self._local_root).splitlines()
889
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000890 def NewContents(self):
891 """Returns an iterator over the lines in the new version of file.
892
893 The new version is the file in the user's workspace, i.e. the "right hand
894 side".
895
896 Contents will be empty if the file is a directory or does not exist.
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000897 Note: The carriage returns (LF or CR) are stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000898 """
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000899 if self._cached_new_contents is None:
900 self._cached_new_contents = []
agable0b65e732016-11-22 09:25:46 -0800901 try:
902 self._cached_new_contents = gclient_utils.FileRead(
903 self.AbsoluteLocalPath(), 'rU').splitlines()
904 except IOError:
905 pass # File not found? That's fine; maybe it was deleted.
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000906 return self._cached_new_contents[:]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000907
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000908 def ChangedContents(self):
909 """Returns a list of tuples (line number, line text) of all new lines.
910
911 This relies on the scm diff output describing each changed code section
912 with a line of the form
913
914 ^@@ <old line num>,<old size> <new line num>,<new size> @@$
915 """
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000916 if self._cached_changed_contents is not None:
917 return self._cached_changed_contents[:]
918 self._cached_changed_contents = []
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000919 line_num = 0
920
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000921 for line in self.GenerateScmDiff().splitlines():
922 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
923 if m:
924 line_num = int(m.groups(1)[0])
925 continue
926 if line.startswith('+') and not line.startswith('++'):
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000927 self._cached_changed_contents.append((line_num, line[1:]))
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000928 if not line.startswith('-'):
929 line_num += 1
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000930 return self._cached_changed_contents[:]
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000931
maruel@chromium.org5de13972009-06-10 18:16:06 +0000932 def __str__(self):
933 return self.LocalPath()
934
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000935 def GenerateScmDiff(self):
nick@chromium.orgff526192013-06-10 19:30:26 +0000936 return self._diff_cache.GetDiff(self.LocalPath(), self._local_root)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000937
maruel@chromium.org58407af2011-04-12 23:15:57 +0000938
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000939class GitAffectedFile(AffectedFile):
940 """Representation of a file in a change out of a git checkout."""
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000941 # Method 'NNN' is abstract in class 'NNN' but is not overridden
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800942 # pylint: disable=abstract-method
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000943
nick@chromium.orgff526192013-06-10 19:30:26 +0000944 DIFF_CACHE = _GitDiffCache
945
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000946 def __init__(self, *args, **kwargs):
947 AffectedFile.__init__(self, *args, **kwargs)
948 self._server_path = None
agable0b65e732016-11-22 09:25:46 -0800949 self._is_testable_file = None
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000950
agable0b65e732016-11-22 09:25:46 -0800951 def IsTestableFile(self):
952 if self._is_testable_file is None:
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000953 if self.Action() == 'D':
agable0b65e732016-11-22 09:25:46 -0800954 # A deleted file is not testable.
955 self._is_testable_file = False
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000956 else:
agable0b65e732016-11-22 09:25:46 -0800957 self._is_testable_file = os.path.isfile(self.AbsoluteLocalPath())
958 return self._is_testable_file
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000959
maruel@chromium.orgc1938752011-04-12 23:11:13 +0000960
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000961class Change(object):
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000962 """Describe a change.
963
964 Used directly by the presubmit scripts to query the current change being
965 tested.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000966
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000967 Instance members:
nick@chromium.orgff526192013-06-10 19:30:26 +0000968 tags: Dictionary of KEY=VALUE pairs found in the change description.
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000969 self.KEY: equivalent to tags['KEY']
970 """
971
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000972 _AFFECTED_FILES = AffectedFile
973
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000974 # Matches key/value (or "tag") lines in changelist descriptions.
maruel@chromium.org428342a2011-11-10 15:46:33 +0000975 TAG_LINE_RE = re.compile(
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +0000976 '^[ \t]*(?P<key>[A-Z][A-Z_0-9]*)[ \t]*=[ \t]*(?P<value>.*?)[ \t]*$')
maruel@chromium.orgc1938752011-04-12 23:11:13 +0000977 scm = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000978
maruel@chromium.org58407af2011-04-12 23:15:57 +0000979 def __init__(
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000980 self, name, description, local_root, files, issue, patchset, author,
981 upstream=None):
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000982 if files is None:
983 files = []
984 self._name = name
chase@chromium.org8e416c82009-10-06 04:30:44 +0000985 # Convert root into an absolute path.
986 self._local_root = os.path.abspath(local_root)
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000987 self._upstream = upstream
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000988 self.issue = issue
989 self.patchset = patchset
maruel@chromium.org58407af2011-04-12 23:15:57 +0000990 self.author_email = author
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000991
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000992 self._full_description = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000993 self.tags = {}
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000994 self._description_without_tags = ''
995 self.SetDescriptionText(description)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000996
maruel@chromium.orge085d812011-10-10 19:49:15 +0000997 assert all(
998 (isinstance(f, (list, tuple)) and len(f) == 2) for f in files), files
999
agable@chromium.orgea84ef12014-04-30 19:55:12 +00001000 diff_cache = self._AFFECTED_FILES.DIFF_CACHE(self._upstream)
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001001 self._affected_files = [
nick@chromium.orgff526192013-06-10 19:30:26 +00001002 self._AFFECTED_FILES(path, action.strip(), self._local_root, diff_cache)
1003 for action, path in files
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +00001004 ]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001005
maruel@chromium.org92022ec2009-06-11 01:59:28 +00001006 def Name(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001007 """Returns the change name."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001008 return self._name
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001009
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001010 def DescriptionText(self):
1011 """Returns the user-entered changelist description, minus tags.
1012
1013 Any line in the user-provided description starting with e.g. "FOO="
1014 (whitespace permitted before and around) is considered a tag line. Such
1015 lines are stripped out of the description this function returns.
1016 """
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001017 return self._description_without_tags
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001018
1019 def FullDescriptionText(self):
1020 """Returns the complete changelist description including tags."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001021 return self._full_description
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001022
isherman@chromium.orgb5cded62014-03-25 17:47:57 +00001023 def SetDescriptionText(self, description):
1024 """Sets the full description text (including tags) to |description|.
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001025
isherman@chromium.orgb5cded62014-03-25 17:47:57 +00001026 Also updates the list of tags."""
1027 self._full_description = description
1028
1029 # From the description text, build up a dictionary of key/value pairs
1030 # plus the description minus all key/value or "tag" lines.
1031 description_without_tags = []
1032 self.tags = {}
1033 for line in self._full_description.splitlines():
1034 m = self.TAG_LINE_RE.match(line)
1035 if m:
1036 self.tags[m.group('key')] = m.group('value')
1037 else:
1038 description_without_tags.append(line)
1039
1040 # Change back to text and remove whitespace at end.
1041 self._description_without_tags = (
1042 '\n'.join(description_without_tags).rstrip())
1043
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001044 def RepositoryRoot(self):
maruel@chromium.org92022ec2009-06-11 01:59:28 +00001045 """Returns the repository (checkout) root directory for this change,
1046 as an absolute path.
1047 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001048 return self._local_root
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001049
1050 def __getattr__(self, attr):
maruel@chromium.org92022ec2009-06-11 01:59:28 +00001051 """Return tags directly as attributes on the object."""
1052 if not re.match(r"^[A-Z_]*$", attr):
1053 raise AttributeError(self, attr)
maruel@chromium.orge1a524f2009-05-27 14:43:46 +00001054 return self.tags.get(attr)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001055
Aaron Gablefc03e672017-05-15 14:09:42 -07001056 def BugsFromDescription(self):
1057 """Returns all bugs referenced in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -07001058 tags = [b.strip() for b in self.tags.get('BUG', '').split(',') if b.strip()]
Caleb Rouleauc0546b92019-02-22 06:12:57 +00001059 footers = []
Dan Beam62954042019-10-03 21:20:33 +00001060 parsed = git_footers.parse_footers(self._full_description)
1061 unsplit_footers = parsed.get('Bug', []) + parsed.get('Fixed', [])
Caleb Rouleauc0546b92019-02-22 06:12:57 +00001062 for unsplit_footer in unsplit_footers:
1063 footers += [b.strip() for b in unsplit_footer.split(',')]
Aaron Gable12ef5012017-05-15 14:29:00 -07001064 return sorted(set(tags + footers))
Aaron Gablefc03e672017-05-15 14:09:42 -07001065
1066 def ReviewersFromDescription(self):
1067 """Returns all reviewers listed in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -07001068 # We don't support a "R:" git-footer for reviewers; that is in metadata.
1069 tags = [r.strip() for r in self.tags.get('R', '').split(',') if r.strip()]
1070 return sorted(set(tags))
Aaron Gablefc03e672017-05-15 14:09:42 -07001071
1072 def TBRsFromDescription(self):
1073 """Returns all TBR reviewers listed in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -07001074 tags = [r.strip() for r in self.tags.get('TBR', '').split(',') if r.strip()]
1075 # TODO(agable): Remove support for 'Tbr:' when TBRs are programmatically
1076 # determined by self-CR+1s.
1077 footers = git_footers.parse_footers(self._full_description).get('Tbr', [])
1078 return sorted(set(tags + footers))
Aaron Gablefc03e672017-05-15 14:09:42 -07001079
1080 # TODO(agable): Delete these once we're sure they're unused.
1081 @property
1082 def BUG(self):
1083 return ','.join(self.BugsFromDescription())
1084 @property
1085 def R(self):
1086 return ','.join(self.ReviewersFromDescription())
1087 @property
1088 def TBR(self):
1089 return ','.join(self.TBRsFromDescription())
1090
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001091 def AllFiles(self, root=None):
1092 """List all files under source control in the repo."""
1093 raise NotImplementedError()
1094
agable0b65e732016-11-22 09:25:46 -08001095 def AffectedFiles(self, include_deletes=True, file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001096 """Returns a list of AffectedFile instances for all files in the change.
1097
1098 Args:
1099 include_deletes: If false, deleted files will be filtered out.
sail@chromium.org5538e022011-05-12 17:53:16 +00001100 file_filter: An additional filter to apply.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001101
1102 Returns:
1103 [AffectedFile(path, action), AffectedFile(path, action)]
1104 """
Edward Lemurb9830242019-10-30 22:19:20 +00001105 affected = list(filter(file_filter, self._affected_files))
sail@chromium.org5538e022011-05-12 17:53:16 +00001106
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001107 if include_deletes:
1108 return affected
Edward Lemurb9830242019-10-30 22:19:20 +00001109 return list(filter(lambda x: x.Action() != 'D', affected))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001110
John Budorick16162372018-04-18 10:39:53 -07001111 def AffectedTestableFiles(self, include_deletes=None, **kwargs):
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +00001112 """Return a list of the existing text files in a change."""
1113 if include_deletes is not None:
agable0b65e732016-11-22 09:25:46 -08001114 warn("AffectedTeestableFiles(include_deletes=%s)"
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +00001115 " is deprecated and ignored" % str(include_deletes),
1116 category=DeprecationWarning,
1117 stacklevel=2)
Edward Lemurb9830242019-10-30 22:19:20 +00001118 return list(filter(
1119 lambda x: x.IsTestableFile(),
1120 self.AffectedFiles(include_deletes=False, **kwargs)))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001121
agable0b65e732016-11-22 09:25:46 -08001122 def AffectedTextFiles(self, include_deletes=None):
1123 """An alias to AffectedTestableFiles for backwards compatibility."""
1124 return self.AffectedTestableFiles(include_deletes=include_deletes)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001125
agable0b65e732016-11-22 09:25:46 -08001126 def LocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001127 """Convenience function."""
agable0b65e732016-11-22 09:25:46 -08001128 return [af.LocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001129
agable0b65e732016-11-22 09:25:46 -08001130 def AbsoluteLocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001131 """Convenience function."""
agable0b65e732016-11-22 09:25:46 -08001132 return [af.AbsoluteLocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001133
1134 def RightHandSideLines(self):
1135 """An iterator over all text lines in "new" version of changed files.
1136
1137 Lists lines from new or modified text files in the change.
1138
1139 This is useful for doing line-by-line regex checks, like checking for
1140 trailing whitespace.
1141
1142 Yields:
1143 a 3 tuple:
1144 the AffectedFile instance of the current file;
1145 integer line number (1-based); and
1146 the contents of the line as a string.
1147 """
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +00001148 return _RightHandSideLinesImpl(
1149 x for x in self.AffectedFiles(include_deletes=False)
agable0b65e732016-11-22 09:25:46 -08001150 if x.IsTestableFile())
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001151
Jochen Eisingerd0573ec2017-04-13 10:55:06 +02001152 def OriginalOwnersFiles(self):
1153 """A map from path names of affected OWNERS files to their old content."""
1154 def owners_file_filter(f):
1155 return 'OWNERS' in os.path.split(f.LocalPath())[1]
1156 files = self.AffectedFiles(file_filter=owners_file_filter)
1157 return dict([(f.LocalPath(), f.OldContents()) for f in files])
1158
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001159
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001160class GitChange(Change):
1161 _AFFECTED_FILES = GitAffectedFile
maruel@chromium.orgc1938752011-04-12 23:11:13 +00001162 scm = 'git'
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +00001163
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001164 def AllFiles(self, root=None):
1165 """List all files under source control in the repo."""
1166 root = root or self.RepositoryRoot()
1167 return subprocess.check_output(
Aaron Gable7817f022017-12-12 09:43:17 -08001168 ['git', '-c', 'core.quotePath=false', 'ls-files', '--', '.'],
1169 cwd=root).splitlines()
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001170
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001171
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001172def ListRelevantPresubmitFiles(files, root):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001173 """Finds all presubmit files that apply to a given set of source files.
1174
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001175 If inherit-review-settings-ok is present right under root, looks for
1176 PRESUBMIT.py in directories enclosing root.
1177
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001178 Args:
1179 files: An iterable container containing file paths.
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001180 root: Path where to stop searching.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001181
1182 Return:
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001183 List of absolute paths of the existing PRESUBMIT.py scripts.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001184 """
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001185 files = [normpath(os.path.join(root, f)) for f in files]
1186
1187 # List all the individual directories containing files.
1188 directories = set([os.path.dirname(f) for f in files])
1189
1190 # Ignore root if inherit-review-settings-ok is present.
1191 if os.path.isfile(os.path.join(root, 'inherit-review-settings-ok')):
1192 root = None
1193
1194 # Collect all unique directories that may contain PRESUBMIT.py.
1195 candidates = set()
1196 for directory in directories:
1197 while True:
1198 if directory in candidates:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001199 break
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001200 candidates.add(directory)
1201 if directory == root:
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001202 break
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001203 parent_dir = os.path.dirname(directory)
1204 if parent_dir == directory:
1205 # We hit the system root directory.
1206 break
1207 directory = parent_dir
1208
1209 # Look for PRESUBMIT.py in all candidate directories.
1210 results = []
1211 for directory in sorted(list(candidates)):
tobiasjsff061c02016-08-17 03:23:57 -07001212 try:
1213 for f in os.listdir(directory):
1214 p = os.path.join(directory, f)
1215 if os.path.isfile(p) and re.match(
1216 r'PRESUBMIT.*\.py$', f) and not f.startswith('PRESUBMIT_test'):
1217 results.append(p)
1218 except OSError:
1219 pass
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001220
tobiasjs2836bcf2016-08-16 04:08:16 -07001221 logging.debug('Presubmit files: %s', ','.join(results))
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001222 return results
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001223
1224
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001225class GetTryMastersExecuter(object):
1226 @staticmethod
1227 def ExecPresubmitScript(script_text, presubmit_path, project, change):
1228 """Executes GetPreferredTryMasters() from a single presubmit script.
1229
1230 Args:
1231 script_text: The text of the presubmit script.
1232 presubmit_path: Project script to run.
1233 project: Project name to pass to presubmit script for bot selection.
1234
1235 Return:
1236 A map of try masters to map of builders to set of tests.
1237 """
1238 context = {}
1239 try:
Raul Tambre09e64b42019-05-14 01:57:22 +00001240 exec(compile(script_text, 'PRESUBMIT.py', 'exec', dont_inherit=True),
1241 context)
Raul Tambre7c938462019-05-24 16:35:35 +00001242 except Exception as e:
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001243 raise PresubmitFailure('"%s" had an exception.\n%s'
1244 % (presubmit_path, e))
1245
1246 function_name = 'GetPreferredTryMasters'
1247 if function_name not in context:
1248 return {}
1249 get_preferred_try_masters = context[function_name]
1250 if not len(inspect.getargspec(get_preferred_try_masters)[0]) == 2:
1251 raise PresubmitFailure(
1252 'Expected function "GetPreferredTryMasters" to take two arguments.')
1253 return get_preferred_try_masters(project, change)
1254
1255
rmistry@google.com5626a922015-02-26 14:03:30 +00001256class GetPostUploadExecuter(object):
1257 @staticmethod
1258 def ExecPresubmitScript(script_text, presubmit_path, cl, change):
1259 """Executes PostUploadHook() from a single presubmit script.
1260
1261 Args:
1262 script_text: The text of the presubmit script.
1263 presubmit_path: Project script to run.
1264 cl: The Changelist object.
1265 change: The Change object.
1266
1267 Return:
1268 A list of results objects.
1269 """
1270 context = {}
1271 try:
Raul Tambre09e64b42019-05-14 01:57:22 +00001272 exec(compile(script_text, 'PRESUBMIT.py', 'exec', dont_inherit=True),
1273 context)
Raul Tambre7c938462019-05-24 16:35:35 +00001274 except Exception as e:
rmistry@google.com5626a922015-02-26 14:03:30 +00001275 raise PresubmitFailure('"%s" had an exception.\n%s'
1276 % (presubmit_path, e))
1277
1278 function_name = 'PostUploadHook'
1279 if function_name not in context:
1280 return {}
1281 post_upload_hook = context[function_name]
1282 if not len(inspect.getargspec(post_upload_hook)[0]) == 3:
1283 raise PresubmitFailure(
1284 'Expected function "PostUploadHook" to take three arguments.')
1285 return post_upload_hook(cl, change, OutputApi(False))
1286
1287
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001288def _MergeMasters(masters1, masters2):
1289 """Merges two master maps. Merges also the tests of each builder."""
1290 result = {}
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00001291 for (master, builders) in itertools.chain(masters1.items(),
1292 masters2.items()):
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001293 new_builders = result.setdefault(master, {})
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00001294 for (builder, tests) in builders.items():
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001295 new_builders.setdefault(builder, set([])).update(tests)
1296 return result
1297
1298
1299def DoGetTryMasters(change,
1300 changed_files,
1301 repository_root,
1302 default_presubmit,
1303 project,
1304 verbose,
1305 output_stream):
1306 """Get the list of try masters from the presubmit scripts.
1307
1308 Args:
1309 changed_files: List of modified files.
1310 repository_root: The repository root.
1311 default_presubmit: A default presubmit script to execute in any case.
1312 project: Optional name of a project used in selecting trybots.
1313 verbose: Prints debug info.
1314 output_stream: A stream to write debug output to.
1315
1316 Return:
1317 Map of try masters to map of builders to set of tests.
1318 """
1319 presubmit_files = ListRelevantPresubmitFiles(changed_files, repository_root)
1320 if not presubmit_files and verbose:
1321 output_stream.write("Warning, no PRESUBMIT.py found.\n")
1322 results = {}
1323 executer = GetTryMastersExecuter()
1324
1325 if default_presubmit:
1326 if verbose:
1327 output_stream.write("Running default presubmit script.\n")
1328 fake_path = os.path.join(repository_root, 'PRESUBMIT.py')
1329 results = _MergeMasters(results, executer.ExecPresubmitScript(
1330 default_presubmit, fake_path, project, change))
1331 for filename in presubmit_files:
1332 filename = os.path.abspath(filename)
1333 if verbose:
1334 output_stream.write("Running %s\n" % filename)
1335 # Accept CRLF presubmit script.
1336 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1337 results = _MergeMasters(results, executer.ExecPresubmitScript(
1338 presubmit_script, filename, project, change))
1339
1340 # Make sets to lists again for later JSON serialization.
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00001341 for builders in results.values():
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001342 for builder in builders:
1343 builders[builder] = list(builders[builder])
1344
1345 if results and verbose:
1346 output_stream.write('%s\n' % str(results))
1347 return results
1348
1349
rmistry@google.com5626a922015-02-26 14:03:30 +00001350def DoPostUploadExecuter(change,
1351 cl,
1352 repository_root,
1353 verbose,
1354 output_stream):
1355 """Execute the post upload hook.
1356
1357 Args:
1358 change: The Change object.
1359 cl: The Changelist object.
1360 repository_root: The repository root.
1361 verbose: Prints debug info.
1362 output_stream: A stream to write debug output to.
1363 """
1364 presubmit_files = ListRelevantPresubmitFiles(
1365 change.LocalPaths(), repository_root)
1366 if not presubmit_files and verbose:
1367 output_stream.write("Warning, no PRESUBMIT.py found.\n")
1368 results = []
1369 executer = GetPostUploadExecuter()
1370 # The root presubmit file should be executed after the ones in subdirectories.
1371 # i.e. the specific post upload hooks should run before the general ones.
1372 # Thus, reverse the order provided by ListRelevantPresubmitFiles.
1373 presubmit_files.reverse()
1374
1375 for filename in presubmit_files:
1376 filename = os.path.abspath(filename)
1377 if verbose:
1378 output_stream.write("Running %s\n" % filename)
1379 # Accept CRLF presubmit script.
1380 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1381 results.extend(executer.ExecPresubmitScript(
1382 presubmit_script, filename, cl, change))
1383 output_stream.write('\n')
1384 if results:
1385 output_stream.write('** Post Upload Hook Messages **\n')
1386 for result in results:
1387 result.handle(output_stream)
1388 output_stream.write('\n')
1389
1390 return results
1391
1392
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001393class PresubmitExecuter(object):
Aaron Gable668c1d82018-04-03 10:19:16 -07001394 def __init__(self, change, committing, verbose,
Edward Lesmes8e282792018-04-03 18:50:29 -04001395 gerrit_obj, dry_run=None, thread_pool=None, parallel=False):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001396 """
1397 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001398 change: The Change object.
agable92bec4f2016-08-24 09:27:27 -07001399 committing: True if 'git cl land' is running, False if 'git cl upload' is.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001400 gerrit_obj: provides basic Gerrit codereview functionality.
1401 dry_run: if true, some Checks will be skipped.
Edward Lesmes8e282792018-04-03 18:50:29 -04001402 parallel: if true, all tests reported via input_api.RunTests for all
1403 PRESUBMIT files will be run in parallel.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001404 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001405 self.change = change
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001406 self.committing = committing
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001407 self.gerrit = gerrit_obj
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001408 self.verbose = verbose
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001409 self.dry_run = dry_run
Daniel Cheng7227d212017-11-17 08:12:37 -08001410 self.more_cc = []
Edward Lesmes8e282792018-04-03 18:50:29 -04001411 self.thread_pool = thread_pool
1412 self.parallel = parallel
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001413
1414 def ExecPresubmitScript(self, script_text, presubmit_path):
1415 """Executes a single presubmit script.
1416
1417 Args:
1418 script_text: The text of the presubmit script.
1419 presubmit_path: The path to the presubmit file (this will be reported via
1420 input_api.PresubmitLocalPath()).
1421
1422 Return:
1423 A list of result objects, empty if no problems.
1424 """
thakis@chromium.orgc6ef53a2014-11-04 00:13:54 +00001425
chase@chromium.org8e416c82009-10-06 04:30:44 +00001426 # Change to the presubmit file's directory to support local imports.
1427 main_path = os.getcwd()
1428 os.chdir(os.path.dirname(presubmit_path))
1429
1430 # Load the presubmit script into context.
dpranke@chromium.org970c5222011-03-12 00:32:24 +00001431 input_api = InputApi(self.change, presubmit_path, self.committing,
Aaron Gable668c1d82018-04-03 10:19:16 -07001432 self.verbose, gerrit_obj=self.gerrit,
Edward Lesmes8e282792018-04-03 18:50:29 -04001433 dry_run=self.dry_run, thread_pool=self.thread_pool,
1434 parallel=self.parallel)
Daniel Cheng7227d212017-11-17 08:12:37 -08001435 output_api = OutputApi(self.committing)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001436 context = {}
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001437 try:
Raul Tambre09e64b42019-05-14 01:57:22 +00001438 exec(compile(script_text, 'PRESUBMIT.py', 'exec', dont_inherit=True),
1439 context)
Raul Tambre7c938462019-05-24 16:35:35 +00001440 except Exception as e:
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001441 raise PresubmitFailure('"%s" had an exception.\n%s' % (presubmit_path, e))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001442
1443 # These function names must change if we make substantial changes to
1444 # the presubmit API that are not backwards compatible.
1445 if self.committing:
1446 function_name = 'CheckChangeOnCommit'
1447 else:
1448 function_name = 'CheckChangeOnUpload'
1449 if function_name in context:
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +01001450 try:
Daniel Cheng7227d212017-11-17 08:12:37 -08001451 context['__args'] = (input_api, output_api)
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +01001452 logging.debug('Running %s in %s', function_name, presubmit_path)
1453 result = eval(function_name + '(*__args)', context)
1454 logging.debug('Running %s done.', function_name)
Daniel Chengd36fce42017-11-21 21:52:52 -08001455 self.more_cc.extend(output_api.more_cc)
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +01001456 finally:
Edward Lemurb9830242019-10-30 22:19:20 +00001457 for f in input_api._named_temporary_files:
1458 os.remove(f)
1459 if not isinstance(result, (tuple, list)):
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001460 raise PresubmitFailure(
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001461 'Presubmit functions must return a tuple or list')
1462 for item in result:
1463 if not isinstance(item, OutputApi.PresubmitResult):
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001464 raise PresubmitFailure(
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001465 'All presubmit results must be of types derived from '
1466 'output_api.PresubmitResult')
1467 else:
1468 result = () # no error since the script doesn't care about current event.
1469
chase@chromium.org8e416c82009-10-06 04:30:44 +00001470 # Return the process to the original working directory.
1471 os.chdir(main_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001472 return result
1473
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001474def DoPresubmitChecks(change,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001475 committing,
1476 verbose,
1477 output_stream,
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +00001478 input_stream,
maruel@chromium.orgb0dfd352009-06-10 14:12:54 +00001479 default_presubmit,
dpranke@chromium.org970c5222011-03-12 00:32:24 +00001480 may_prompt,
Aaron Gable668c1d82018-04-03 10:19:16 -07001481 gerrit_obj,
Edward Lesmes8e282792018-04-03 18:50:29 -04001482 dry_run=None,
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001483 parallel=False,
1484 json_output=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001485 """Runs all presubmit checks that apply to the files in the change.
1486
1487 This finds all PRESUBMIT.py files in directories enclosing the files in the
1488 change (up to the repository root) and calls the relevant entrypoint function
1489 depending on whether the change is being committed or uploaded.
1490
1491 Prints errors, warnings and notifications. Prompts the user for warnings
1492 when needed.
1493
1494 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001495 change: The Change object.
agable92bec4f2016-08-24 09:27:27 -07001496 committing: True if 'git cl land' is running, False if 'git cl upload' is.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001497 verbose: Prints debug info.
1498 output_stream: A stream to write output from presubmit tests to.
1499 input_stream: A stream to read input from the user.
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +00001500 default_presubmit: A default presubmit script to execute in any case.
Quinten Yearsley516fe7f2016-12-14 11:50:18 -08001501 may_prompt: Enable (y/n) questions on warning or error. If False,
1502 any questions are answered with yes by default.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001503 gerrit_obj: provides basic Gerrit codereview functionality.
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001504 dry_run: if true, some Checks will be skipped.
Edward Lesmes8e282792018-04-03 18:50:29 -04001505 parallel: if true, all tests specified by input_api.RunTests in all
1506 PRESUBMIT files will be run in parallel.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001507
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +00001508 Warning:
1509 If may_prompt is true, output_stream SHOULD be sys.stdout and input_stream
1510 SHOULD be sys.stdin.
1511
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001512 Return:
dpranke@chromium.org5ac21012011-03-16 02:58:25 +00001513 A PresubmitOutput object. Use output.should_continue() to figure out
1514 if there were errors or warnings and the caller should abort.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001515 """
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001516 old_environ = os.environ
1517 try:
1518 # Make sure python subprocesses won't generate .pyc files.
1519 os.environ = os.environ.copy()
Edward Lemurb9830242019-10-30 22:19:20 +00001520 os.environ['PYTHONDONTWRITEBYTECODE'] = '1'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001521
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001522 output = PresubmitOutput(input_stream, output_stream)
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001523
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001524 if committing:
1525 output.write("Running presubmit commit checks ...\n")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001526 else:
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001527 output.write("Running presubmit upload checks ...\n")
1528 start_time = time.time()
1529 presubmit_files = ListRelevantPresubmitFiles(
agable0b65e732016-11-22 09:25:46 -08001530 change.AbsoluteLocalPaths(), change.RepositoryRoot())
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001531 if not presubmit_files and verbose:
maruel@chromium.orgfae707b2011-09-15 18:57:58 +00001532 output.write("Warning, no PRESUBMIT.py found.\n")
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001533 results = []
Edward Lesmes8e282792018-04-03 18:50:29 -04001534 thread_pool = ThreadPool()
Edward Lemur7e3c67f2018-07-20 20:52:49 +00001535 executer = PresubmitExecuter(change, committing, verbose, gerrit_obj,
1536 dry_run, thread_pool, parallel)
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001537 if default_presubmit:
1538 if verbose:
1539 output.write("Running default presubmit script.\n")
1540 fake_path = os.path.join(change.RepositoryRoot(), 'PRESUBMIT.py')
1541 results += executer.ExecPresubmitScript(default_presubmit, fake_path)
1542 for filename in presubmit_files:
1543 filename = os.path.abspath(filename)
1544 if verbose:
1545 output.write("Running %s\n" % filename)
1546 # Accept CRLF presubmit script.
1547 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1548 results += executer.ExecPresubmitScript(presubmit_script, filename)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001549
Edward Lesmes8e282792018-04-03 18:50:29 -04001550 results += thread_pool.RunAsync()
1551
Daniel Cheng7227d212017-11-17 08:12:37 -08001552 output.more_cc.extend(executer.more_cc)
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001553 errors = []
1554 notifications = []
1555 warnings = []
1556 for result in results:
1557 if result.fatal:
1558 errors.append(result)
1559 elif result.should_prompt:
1560 warnings.append(result)
1561 else:
1562 notifications.append(result)
pam@chromium.orged9a0832009-09-09 22:48:55 +00001563
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001564 if json_output:
1565 # Write the presubmit results to json output
1566 presubmit_results = {
1567 'errors': [
1568 error.json_format() for error in errors
1569 ],
1570 'notifications': [
1571 notification.json_format() for notification in notifications
1572 ],
1573 'warnings': [
1574 warning.json_format() for warning in warnings
1575 ]
1576 }
1577
Edward Lemurb9830242019-10-30 22:19:20 +00001578 gclient_utils.FileWrite(
1579 json_output, json.dumps(presubmit_results, sort_keys=True))
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001580
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001581 output.write('\n')
1582 for name, items in (('Messages', notifications),
1583 ('Warnings', warnings),
1584 ('ERRORS', errors)):
1585 if items:
1586 output.write('** Presubmit %s **\n' % name)
1587 for item in items:
1588 item.handle(output)
1589 output.write('\n')
pam@chromium.orged9a0832009-09-09 22:48:55 +00001590
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001591 total_time = time.time() - start_time
1592 if total_time > 1.0:
1593 output.write("Presubmit checks took %.1fs to calculate.\n\n" % total_time)
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +00001594
Quinten Yearsley516fe7f2016-12-14 11:50:18 -08001595 if errors:
1596 output.fail()
1597 elif warnings:
1598 output.write('There were presubmit warnings. ')
1599 if may_prompt:
1600 output.prompt_yes_no('Are you sure you wish to continue? (y/N): ')
1601 else:
1602 output.write('Presubmit checks passed.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001603
1604 global _ASKED_FOR_FEEDBACK
1605 # Ask for feedback one time out of 5.
1606 if (len(results) and random.randint(0, 4) == 0 and not _ASKED_FOR_FEEDBACK):
maruel@chromium.org1ce8e662014-01-14 15:23:00 +00001607 output.write(
1608 'Was the presubmit check useful? If not, run "git cl presubmit -v"\n'
1609 'to figure out which PRESUBMIT.py was run, then run git blame\n'
1610 'on the file to figure out who to ask for help.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001611 _ASKED_FOR_FEEDBACK = True
1612 return output
1613 finally:
1614 os.environ = old_environ
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001615
1616
1617def ScanSubDirs(mask, recursive):
1618 if not recursive:
pgervais@chromium.orge57b09d2014-05-07 00:58:13 +00001619 return [x for x in glob.glob(mask) if x not in ('.svn', '.git')]
Lei Zhang9611c4c2017-04-04 01:41:56 -07001620
1621 results = []
1622 for root, dirs, files in os.walk('.'):
1623 if '.svn' in dirs:
1624 dirs.remove('.svn')
1625 if '.git' in dirs:
1626 dirs.remove('.git')
1627 for name in files:
1628 if fnmatch.fnmatch(name, mask):
1629 results.append(os.path.join(root, name))
1630 return results
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001631
1632
1633def ParseFiles(args, recursive):
tobiasjs2836bcf2016-08-16 04:08:16 -07001634 logging.debug('Searching for %s', args)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001635 files = []
1636 for arg in args:
maruel@chromium.orge3608df2009-11-10 20:22:57 +00001637 files.extend([('M', f) for f in ScanSubDirs(arg, recursive)])
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001638 return files
1639
1640
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001641def load_files(options, args):
1642 """Tries to determine the SCM."""
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001643 files = []
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001644 if args:
1645 files = ParseFiles(args, options.recursive)
agable0b65e732016-11-22 09:25:46 -08001646 change_scm = scm.determine_scm(options.root)
1647 if change_scm == 'git':
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001648 change_class = GitChange
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001649 upstream = options.upstream or None
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001650 if not files:
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001651 files = scm.GIT.CaptureStatus([], options.root, upstream)
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001652 else:
tobiasjs2836bcf2016-08-16 04:08:16 -07001653 logging.info('Doesn\'t seem under source control. Got %d files', len(args))
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001654 if not files:
1655 return None, None
1656 change_class = Change
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001657 return change_class, files
1658
1659
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001660@contextlib.contextmanager
1661def canned_check_filter(method_names):
1662 filtered = {}
1663 try:
1664 for method_name in method_names:
1665 if not hasattr(presubmit_canned_checks, method_name):
Aaron Gableecee74c2018-04-02 15:13:08 -07001666 logging.warn('Skipping unknown "canned" check %s' % method_name)
1667 continue
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001668 filtered[method_name] = getattr(presubmit_canned_checks, method_name)
1669 setattr(presubmit_canned_checks, method_name, lambda *_a, **_kw: [])
1670 yield
1671 finally:
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00001672 for name, method in filtered.items():
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001673 setattr(presubmit_canned_checks, name, method)
1674
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001675
sbc@chromium.org013731e2015-02-26 18:28:43 +00001676def main(argv=None):
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001677 parser = optparse.OptionParser(usage="%prog [options] <files...>",
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001678 version="%prog " + str(__version__))
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001679 parser.add_option("-c", "--commit", action="store_true", default=False,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001680 help="Use commit instead of upload checks")
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001681 parser.add_option("-u", "--upload", action="store_false", dest='commit',
1682 help="Use upload instead of commit checks")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001683 parser.add_option("-r", "--recursive", action="store_true",
1684 help="Act recursively")
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001685 parser.add_option("-v", "--verbose", action="count", default=0,
1686 help="Use 2 times for more debug info")
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001687 parser.add_option("--name", default='no name')
maruel@chromium.org58407af2011-04-12 23:15:57 +00001688 parser.add_option("--author")
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001689 parser.add_option("--description", default='')
1690 parser.add_option("--issue", type='int', default=0)
1691 parser.add_option("--patchset", type='int', default=0)
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001692 parser.add_option("--root", default=os.getcwd(),
1693 help="Search for PRESUBMIT.py up to this directory. "
1694 "If inherit-review-settings-ok is present in this "
1695 "directory, parent directories up to the root file "
1696 "system directories will also be searched.")
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001697 parser.add_option("--upstream",
1698 help="Git only: the base ref or upstream branch against "
1699 "which the diff should be computed.")
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001700 parser.add_option("--default_presubmit")
1701 parser.add_option("--may_prompt", action='store_true', default=False)
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001702 parser.add_option("--skip_canned", action='append', default=[],
1703 help="A list of checks to skip which appear in "
1704 "presubmit_canned_checks. Can be provided multiple times "
1705 "to skip multiple canned checks.")
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001706 parser.add_option("--dry_run", action='store_true',
1707 help=optparse.SUPPRESS_HELP)
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001708 parser.add_option("--gerrit_url", help=optparse.SUPPRESS_HELP)
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001709 parser.add_option("--gerrit_fetch", action='store_true',
1710 help=optparse.SUPPRESS_HELP)
Edward Lesmes8e282792018-04-03 18:50:29 -04001711 parser.add_option('--parallel', action='store_true',
1712 help='Run all tests specified by input_api.RunTests in all '
1713 'PRESUBMIT files in parallel.')
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001714 parser.add_option('--json_output',
1715 help='Write presubmit errors to json output.')
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001716
maruel@chromium.org82e5f282011-03-17 14:08:55 +00001717 options, args = parser.parse_args(argv)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001718
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001719 if options.verbose >= 2:
maruel@chromium.org7444c502011-02-09 14:02:11 +00001720 logging.basicConfig(level=logging.DEBUG)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001721 elif options.verbose:
1722 logging.basicConfig(level=logging.INFO)
1723 else:
1724 logging.basicConfig(level=logging.ERROR)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001725
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001726 change_class, files = load_files(options, args)
1727 if not change_class:
1728 parser.error('For unversioned directory, <files> is not optional.')
tobiasjs2836bcf2016-08-16 04:08:16 -07001729 logging.info('Found %d file(s).', len(files))
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001730
Aaron Gable668c1d82018-04-03 10:19:16 -07001731 gerrit_obj = None
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001732 if options.gerrit_url and options.gerrit_fetch:
tandrii@chromium.org83b1b232016-04-29 16:33:19 +00001733 assert options.issue and options.patchset
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001734 gerrit_obj = GerritAccessor(urlparse.urlparse(options.gerrit_url).netloc)
1735 options.author = gerrit_obj.GetChangeOwner(options.issue)
1736 options.description = gerrit_obj.GetChangeDescription(options.issue,
1737 options.patchset)
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001738 logging.info('Got author: "%s"', options.author)
1739 logging.info('Got description: """\n%s\n"""', options.description)
1740
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001741 try:
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001742 with canned_check_filter(options.skip_canned):
1743 results = DoPresubmitChecks(
1744 change_class(options.name,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001745 options.description,
1746 options.root,
1747 files,
1748 options.issue,
1749 options.patchset,
1750 options.author,
1751 upstream=options.upstream),
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001752 options.commit,
1753 options.verbose,
1754 sys.stdout,
1755 sys.stdin,
1756 options.default_presubmit,
1757 options.may_prompt,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001758 gerrit_obj,
Edward Lesmes8e282792018-04-03 18:50:29 -04001759 options.dry_run,
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001760 options.parallel,
1761 options.json_output)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001762 return not results.should_continue()
Raul Tambre7c938462019-05-24 16:35:35 +00001763 except PresubmitFailure as e:
Raul Tambre80ee78e2019-05-06 22:41:05 +00001764 print(e, file=sys.stderr)
1765 print('Maybe your depot_tools is out of date?', file=sys.stderr)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001766 return 2
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001767
1768
1769if __name__ == '__main__':
maruel@chromium.org35625c72011-03-23 17:34:02 +00001770 fix_encoding.fix_encoding()
sbc@chromium.org013731e2015-02-26 18:28:43 +00001771 try:
1772 sys.exit(main())
1773 except KeyboardInterrupt:
1774 sys.stderr.write('interrupted\n')
sergiybf8a3b382016-07-05 11:21:30 -07001775 sys.exit(2)