blob: c9ac9ca4b4a065cfefacc4747f177555521bb974 [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
Edward Lemur336e51f2019-11-14 21:42:04 +0000168 # On Windows, scripts on the current directory take precedence over PATH, so
169 # that when testing depot_tools on Windows, calling `vpython.bat` will
170 # execute the copy of vpython of the depot_tools under test instead of the
171 # one in the bot.
172 # As a workaround, we run the tests from the parent directory instead.
173 if (cmd[0] == vpython and
174 'cwd' in test.kwargs and
175 os.path.basename(test.kwargs['cwd']) == 'depot_tools'):
176 test.kwargs['cwd'] = os.path.dirname(test.kwargs['cwd'])
177 cmd[1] = os.path.join('depot_tools', cmd[1])
178
Edward Lesmes8e282792018-04-03 18:50:29 -0400179 try:
180 start = time.time()
181 p = subprocess.Popen(cmd, **test.kwargs)
182 stdout, _ = sigint_handler.wait(p, test.stdin)
183 duration = time.time() - start
Edward Lemur7cf94382019-11-15 22:36:41 +0000184 except Exception:
Edward Lesmes8e282792018-04-03 18:50:29 -0400185 duration = time.time() - start
186 return test.message(
Edward Lemur7cf94382019-11-15 22:36:41 +0000187 '%s\n%s exec failure (%4.2fs)\n%s' % (
188 test.name, ' '.join(cmd), duration, traceback.format_exc()))
Edward Lemurde9e3ca2019-10-24 21:13:31 +0000189
Edward Lesmes8e282792018-04-03 18:50:29 -0400190 if p.returncode != 0:
191 return test.message(
Edward Lemur7cf94382019-11-15 22:36:41 +0000192 '%s\n%s (%4.2fs) failed\n%s' % (
193 test.name, ' '.join(cmd), duration, stdout))
Edward Lesmes8e282792018-04-03 18:50:29 -0400194 if test.info:
Edward Lemur7cf94382019-11-15 22:36:41 +0000195 return test.info('%s\n%s (%4.2fs)' % (test.name, ' '.join(cmd), duration))
Edward Lesmes8e282792018-04-03 18:50:29 -0400196
197 def AddTests(self, tests, parallel=True):
198 if parallel:
199 self._tests.extend(tests)
200 else:
201 self._nonparallel_tests.extend(tests)
202
203 def RunAsync(self):
204 self._messages = []
205
206 def _WorkerFn():
207 while True:
208 test = None
209 with self._tests_lock:
210 if not self._tests:
211 break
212 test = self._tests.pop()
213 result = self.CallCommand(test)
214 if result:
215 with self._messages_lock:
216 self._messages.append(result)
217
218 def _StartDaemon():
219 t = threading.Thread(target=_WorkerFn)
220 t.daemon = True
221 t.start()
222 return t
223
224 while self._nonparallel_tests:
225 test = self._nonparallel_tests.pop()
226 result = self.CallCommand(test)
227 if result:
228 self._messages.append(result)
229
230 if self._tests:
231 threads = [_StartDaemon() for _ in range(self._pool_size)]
232 for worker in threads:
233 worker.join()
234
235 return self._messages
236
237
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000238def normpath(path):
239 '''Version of os.path.normpath that also changes backward slashes to
240 forward slashes when not running on Windows.
241 '''
242 # This is safe to always do because the Windows version of os.path.normpath
243 # will replace forward slashes with backward slashes.
244 path = path.replace(os.sep, '/')
245 return os.path.normpath(path)
246
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000247
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000248def _RightHandSideLinesImpl(affected_files):
249 """Implements RightHandSideLines for InputApi and GclChange."""
250 for af in affected_files:
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000251 lines = af.ChangedContents()
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000252 for line in lines:
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000253 yield (af, line[0], line[1])
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000254
255
dpranke@chromium.org5ac21012011-03-16 02:58:25 +0000256class PresubmitOutput(object):
257 def __init__(self, input_stream=None, output_stream=None):
258 self.input_stream = input_stream
259 self.output_stream = output_stream
260 self.reviewers = []
Daniel Cheng7227d212017-11-17 08:12:37 -0800261 self.more_cc = []
dpranke@chromium.org5ac21012011-03-16 02:58:25 +0000262 self.written_output = []
263 self.error_count = 0
264
265 def prompt_yes_no(self, prompt_string):
266 self.write(prompt_string)
267 if self.input_stream:
268 response = self.input_stream.readline().strip().lower()
269 if response not in ('y', 'yes'):
270 self.fail()
271 else:
272 self.fail()
273
274 def fail(self):
275 self.error_count += 1
276
277 def should_continue(self):
278 return not self.error_count
279
280 def write(self, s):
281 self.written_output.append(s)
282 if self.output_stream:
283 self.output_stream.write(s)
284
285 def getvalue(self):
286 return ''.join(self.written_output)
287
288
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000289# Top level object so multiprocessing can pickle
290# Public access through OutputApi object.
291class _PresubmitResult(object):
292 """Base class for result objects."""
293 fatal = False
294 should_prompt = False
295
296 def __init__(self, message, items=None, long_text=''):
297 """
298 message: A short one-line message to indicate errors.
299 items: A list of short strings to indicate where errors occurred.
300 long_text: multi-line text output, e.g. from another tool
301 """
302 self._message = message
303 self._items = items or []
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000304 self._long_text = long_text.rstrip()
305
306 def handle(self, output):
307 output.write(self._message)
308 output.write('\n')
309 for index, item in enumerate(self._items):
310 output.write(' ')
311 # Write separately in case it's unicode.
312 output.write(str(item))
313 if index < len(self._items) - 1:
314 output.write(' \\')
315 output.write('\n')
316 if self._long_text:
317 output.write('\n***************\n')
318 # Write separately in case it's unicode.
319 output.write(self._long_text)
320 output.write('\n***************\n')
321 if self.fatal:
322 output.fail()
323
Debrian Figueroadd2737e2019-06-21 23:50:13 +0000324 def json_format(self):
325 return {
326 'message': self._message,
Debrian Figueroa6095d402019-06-28 18:47:18 +0000327 'items': [str(item) for item in self._items],
Debrian Figueroadd2737e2019-06-21 23:50:13 +0000328 'long_text': self._long_text,
329 'fatal': self.fatal
330 }
331
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000332
333# Top level object so multiprocessing can pickle
334# Public access through OutputApi object.
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000335class _PresubmitError(_PresubmitResult):
336 """A hard presubmit error."""
337 fatal = True
338
339
340# Top level object so multiprocessing can pickle
341# Public access through OutputApi object.
342class _PresubmitPromptWarning(_PresubmitResult):
343 """An warning that prompts the user if they want to continue."""
344 should_prompt = True
345
346
347# Top level object so multiprocessing can pickle
348# Public access through OutputApi object.
349class _PresubmitNotifyResult(_PresubmitResult):
350 """Just print something to the screen -- but it's not even a warning."""
351 pass
352
353
354# Top level object so multiprocessing can pickle
355# Public access through OutputApi object.
356class _MailTextResult(_PresubmitResult):
357 """A warning that should be included in the review request email."""
358 def __init__(self, *args, **kwargs):
359 super(_MailTextResult, self).__init__()
360 raise NotImplementedError()
361
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000362class GerritAccessor(object):
363 """Limited Gerrit functionality for canned presubmit checks to work.
364
365 To avoid excessive Gerrit calls, caches the results.
366 """
367
368 def __init__(self, host):
369 self.host = host
370 self.cache = {}
371
372 def _FetchChangeDetail(self, issue):
373 # Separate function to be easily mocked in tests.
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +0100374 try:
375 return gerrit_util.GetChangeDetail(
376 self.host, str(issue),
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700377 ['ALL_REVISIONS', 'DETAILED_LABELS', 'ALL_COMMITS'])
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +0100378 except gerrit_util.GerritError as e:
379 if e.http_status == 404:
380 raise Exception('Either Gerrit issue %s doesn\'t exist, or '
381 'no credentials to fetch issue details' % issue)
382 raise
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000383
384 def GetChangeInfo(self, issue):
385 """Returns labels and all revisions (patchsets) for this issue.
386
387 The result is a dictionary according to Gerrit REST Api.
388 https://gerrit-review.googlesource.com/Documentation/rest-api.html
389
390 However, API isn't very clear what's inside, so see tests for example.
391 """
392 assert issue
393 cache_key = int(issue)
394 if cache_key not in self.cache:
395 self.cache[cache_key] = self._FetchChangeDetail(issue)
396 return self.cache[cache_key]
397
398 def GetChangeDescription(self, issue, patchset=None):
399 """If patchset is none, fetches current patchset."""
400 info = self.GetChangeInfo(issue)
401 # info is a reference to cache. We'll modify it here adding description to
402 # it to the right patchset, if it is not yet there.
403
404 # Find revision info for the patchset we want.
405 if patchset is not None:
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000406 for rev, rev_info in info['revisions'].items():
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000407 if str(rev_info['_number']) == str(patchset):
408 break
409 else:
410 raise Exception('patchset %s doesn\'t exist in issue %s' % (
411 patchset, issue))
412 else:
413 rev = info['current_revision']
414 rev_info = info['revisions'][rev]
415
Andrii Shyshkalov9c3a4642017-01-24 17:41:22 +0100416 return rev_info['commit']['message']
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000417
Mun Yong Jang603d01e2017-12-19 16:38:30 -0800418 def GetDestRef(self, issue):
419 ref = self.GetChangeInfo(issue)['branch']
420 if not ref.startswith('refs/'):
421 # NOTE: it is possible to create 'refs/x' branch,
422 # aka 'refs/heads/refs/x'. However, this is ill-advised.
423 ref = 'refs/heads/%s' % ref
424 return ref
425
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000426 def GetChangeOwner(self, issue):
427 return self.GetChangeInfo(issue)['owner']['email']
428
429 def GetChangeReviewers(self, issue, approving_only=True):
Aaron Gable8b478f02017-07-31 15:33:19 -0700430 changeinfo = self.GetChangeInfo(issue)
431 if approving_only:
432 labelinfo = changeinfo.get('labels', {}).get('Code-Review', {})
433 values = labelinfo.get('values', {}).keys()
434 try:
435 max_value = max(int(v) for v in values)
436 reviewers = [r for r in labelinfo.get('all', [])
437 if r.get('value', 0) == max_value]
438 except ValueError: # values is the empty list
439 reviewers = []
440 else:
441 reviewers = changeinfo.get('reviewers', {}).get('REVIEWER', [])
442 return [r.get('email') for r in reviewers]
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000443
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000444
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000445class OutputApi(object):
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000446 """An instance of OutputApi gets passed to presubmit scripts so that they
447 can output various types of results.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000448 """
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000449 PresubmitResult = _PresubmitResult
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000450 PresubmitError = _PresubmitError
451 PresubmitPromptWarning = _PresubmitPromptWarning
452 PresubmitNotifyResult = _PresubmitNotifyResult
453 MailTextResult = _MailTextResult
454
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000455 def __init__(self, is_committing):
456 self.is_committing = is_committing
Daniel Cheng7227d212017-11-17 08:12:37 -0800457 self.more_cc = []
458
459 def AppendCC(self, cc):
460 """Appends a user to cc for this change."""
461 self.more_cc.append(cc)
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000462
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000463 def PresubmitPromptOrNotify(self, *args, **kwargs):
464 """Warn the user when uploading, but only notify if committing."""
465 if self.is_committing:
466 return self.PresubmitNotifyResult(*args, **kwargs)
467 return self.PresubmitPromptWarning(*args, **kwargs)
468
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000469
470class InputApi(object):
471 """An instance of this object is passed to presubmit scripts so they can
472 know stuff about the change they're looking at.
473 """
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000474 # Method could be a function
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800475 # pylint: disable=no-self-use
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000476
maruel@chromium.org3410d912009-06-09 20:56:16 +0000477 # File extensions that are considered source files from a style guide
478 # perspective. Don't modify this list from a presubmit script!
maruel@chromium.orgc33455a2011-06-24 19:14:18 +0000479 #
480 # Files without an extension aren't included in the list. If you want to
481 # filter them as source files, add r"(^|.*?[\\\/])[^.]+$" to the white list.
482 # Note that ALL CAPS files are black listed in DEFAULT_BLACK_LIST below.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000483 DEFAULT_WHITE_LIST = (
484 # C++ and friends
maruel@chromium.orgfe1211a2011-05-28 18:54:17 +0000485 r".+\.c$", r".+\.cc$", r".+\.cpp$", r".+\.h$", r".+\.m$", r".+\.mm$",
486 r".+\.inl$", r".+\.asm$", r".+\.hxx$", r".+\.hpp$", r".+\.s$", r".+\.S$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000487 # Scripts
maruel@chromium.orgfe1211a2011-05-28 18:54:17 +0000488 r".+\.js$", r".+\.py$", r".+\.sh$", r".+\.rb$", r".+\.pl$", r".+\.pm$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000489 # Other
Sergey Ulanov166bc4c2018-04-30 17:03:38 -0700490 r".+\.java$", r".+\.mk$", r".+\.am$", r".+\.css$", r".+\.mojom$",
491 r".+\.fidl$"
maruel@chromium.org3410d912009-06-09 20:56:16 +0000492 )
493
494 # Path regexp that should be excluded from being considered containing source
495 # files. Don't modify this list from a presubmit script!
496 DEFAULT_BLACK_LIST = (
gavinp@chromium.org656326d2012-08-13 00:43:57 +0000497 r"testing_support[\\\/]google_appengine[\\\/].*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000498 r".*\bexperimental[\\\/].*",
Kent Tamura179dd1e2018-04-26 15:07:41 +0900499 # Exclude third_party/.* but NOT third_party/{WebKit,blink}
500 # (crbug.com/539768 and crbug.com/836555).
501 r".*\bthird_party[\\\/](?!(WebKit|blink)[\\\/]).*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000502 # Output directories (just in case)
503 r".*\bDebug[\\\/].*",
504 r".*\bRelease[\\\/].*",
505 r".*\bxcodebuild[\\\/].*",
thakis@chromium.orgc1c96352013-10-09 19:50:27 +0000506 r".*\bout[\\\/].*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000507 # All caps files like README and LICENCE.
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000508 r".*\b[A-Z0-9_]{2,}$",
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000509 # SCM (can happen in dual SCM configuration). (Slightly over aggressive)
maruel@chromium.org5d0dc432011-01-03 02:40:37 +0000510 r"(|.*[\\\/])\.git[\\\/].*",
511 r"(|.*[\\\/])\.svn[\\\/].*",
maruel@chromium.org7ccb4bb2011-11-07 20:26:20 +0000512 # There is no point in processing a patch file.
513 r".+\.diff$",
514 r".+\.patch$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000515 )
516
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000517 def __init__(self, change, presubmit_path, is_committing,
Edward Lesmes8e282792018-04-03 18:50:29 -0400518 verbose, gerrit_obj, dry_run=None, thread_pool=None, parallel=False):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000519 """Builds an InputApi object.
520
521 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000522 change: A presubmit.Change object.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000523 presubmit_path: The path to the presubmit script being processed.
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000524 is_committing: True if the change is about to be committed.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000525 gerrit_obj: provides basic Gerrit codereview functionality.
526 dry_run: if true, some Checks will be skipped.
Edward Lesmes8e282792018-04-03 18:50:29 -0400527 parallel: if true, all tests reported via input_api.RunTests for all
528 PRESUBMIT files will be run in parallel.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000529 """
maruel@chromium.org9711bba2009-05-22 23:51:39 +0000530 # Version number of the presubmit_support script.
531 self.version = [int(x) for x in __version__.split('.')]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000532 self.change = change
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000533 self.is_committing = is_committing
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000534 self.gerrit = gerrit_obj
tandrii@chromium.org57bafac2016-04-28 05:09:03 +0000535 self.dry_run = dry_run
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000536
Edward Lesmes8e282792018-04-03 18:50:29 -0400537 self.parallel = parallel
538 self.thread_pool = thread_pool or ThreadPool()
539
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000540 # We expose various modules and functions as attributes of the input_api
541 # so that presubmit scripts don't have to import them.
Takeshi Yoshino07a6bea2017-08-02 02:44:06 +0900542 self.ast = ast
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000543 self.basename = os.path.basename
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000544 self.cpplint = cpplint
dcheng091b7db2016-06-16 01:27:51 -0700545 self.fnmatch = fnmatch
Yoshisato Yanagisawa04600b42019-03-15 03:03:41 +0000546 self.gclient_paths = gclient_paths
Yoshisato Yanagisawa57dd17b2019-03-22 09:10:29 +0000547 # TODO(yyanagisawa): stop exposing this when python3 become default.
548 # Since python3's tempfile has TemporaryDirectory, we do not need this.
549 self.temporary_directory = gclient_utils.temporary_directory
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000550 self.glob = glob.glob
maruel@chromium.orgfb11c7b2010-03-18 18:22:14 +0000551 self.json = json
maruel@chromium.org6fba34d2011-06-02 13:45:12 +0000552 self.logging = logging.getLogger('PRESUBMIT')
maruel@chromium.org2b5ce562011-03-31 16:15:44 +0000553 self.os_listdir = os.listdir
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000554 self.os_path = os.path
pgervais@chromium.orgbd0cace2014-10-02 23:23:46 +0000555 self.os_stat = os.stat
Yoshisato Yanagisawa406de132018-06-29 05:43:25 +0000556 self.os_walk = os.walk
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000557 self.re = re
558 self.subprocess = subprocess
Edward Lemurb9830242019-10-30 22:19:20 +0000559 self.sys = sys
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000560 self.tempfile = tempfile
dpranke@chromium.org0d1bdea2011-03-24 22:54:38 +0000561 self.time = time
maruel@chromium.org1487d532009-06-06 00:22:57 +0000562 self.unittest = unittest
Edward Lemurb9830242019-10-30 22:19:20 +0000563 if sys.version_info.major == 2:
564 self.urllib2 = urllib2
Edward Lemur16af3562019-10-17 22:11:33 +0000565 self.urllib_request = urllib_request
566 self.urllib_error = urllib_error
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000567
Robert Iannucci50258932018-03-19 10:30:59 -0700568 self.is_windows = sys.platform == 'win32'
569
Edward Lemurb9646622019-10-25 20:57:35 +0000570 # Set python_executable to 'vpython' in order to allow scripts in other
571 # repos (e.g. src.git) to automatically pick up that repo's .vpython file,
572 # instead of inheriting the one in depot_tools.
573 self.python_executable = 'vpython'
maruel@chromium.orgc0b22972009-06-25 16:19:14 +0000574 self.environ = os.environ
575
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000576 # InputApi.platform is the platform you're currently running on.
577 self.platform = sys.platform
578
iannucci@chromium.org0af3bb32015-06-12 20:44:35 +0000579 self.cpu_count = multiprocessing.cpu_count()
580
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000581 # The local path of the currently-being-processed presubmit script.
maruel@chromium.org3d235242009-05-15 12:40:48 +0000582 self._current_presubmit_path = os.path.dirname(presubmit_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000583
584 # We carry the canned checks so presubmit scripts can easily use them.
585 self.canned_checks = presubmit_canned_checks
586
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +0100587 # Temporary files we must manually remove at the end of a run.
588 self._named_temporary_files = []
Jochen Eisinger72606f82017-04-04 10:44:18 +0200589
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000590 # TODO(dpranke): figure out a list of all approved owners for a repo
591 # in order to be able to handle wildcard OWNERS files?
592 self.owners_db = owners.Database(change.RepositoryRoot(),
Edward Lemurb9830242019-10-30 22:19:20 +0000593 fopen=open, os_path=self.os_path)
Jochen Eisinger76f5fc62017-04-07 16:27:46 +0200594 self.owners_finder = owners_finder.OwnersFinder
maruel@chromium.org899e1c12011-04-07 17:03:18 +0000595 self.verbose = verbose
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000596 self.Command = CommandData
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000597
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000598 # Replace <hash_map> and <hash_set> as headers that need to be included
danakj@chromium.org18278522013-06-11 22:42:32 +0000599 # with "base/containers/hash_tables.h" instead.
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000600 # Access to a protected member _XX of a client class
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800601 # pylint: disable=protected-access
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000602 self.cpplint._re_pattern_templates = [
danakj@chromium.org18278522013-06-11 22:42:32 +0000603 (a, b, 'base/containers/hash_tables.h')
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000604 if header in ('<hash_map>', '<hash_set>') else (a, b, header)
605 for (a, b, header) in cpplint._re_pattern_templates
606 ]
607
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000608 def PresubmitLocalPath(self):
609 """Returns the local path of the presubmit script currently being run.
610
611 This is useful if you don't want to hard-code absolute paths in the
612 presubmit script. For example, It can be used to find another file
613 relative to the PRESUBMIT.py script, so the whole tree can be branched and
614 the presubmit script still works, without editing its content.
615 """
maruel@chromium.org3d235242009-05-15 12:40:48 +0000616 return self._current_presubmit_path
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000617
agable0b65e732016-11-22 09:25:46 -0800618 def AffectedFiles(self, include_deletes=True, file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000619 """Same as input_api.change.AffectedFiles() except only lists files
620 (and optionally directories) in the same directory as the current presubmit
621 script, or subdirectories thereof.
622 """
maruel@chromium.org3d235242009-05-15 12:40:48 +0000623 dir_with_slash = normpath("%s/" % self.PresubmitLocalPath())
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000624 if len(dir_with_slash) == 1:
625 dir_with_slash = ''
sail@chromium.org5538e022011-05-12 17:53:16 +0000626
Edward Lemurb9830242019-10-30 22:19:20 +0000627 return list(filter(
maruel@chromium.org4661e0c2009-06-04 00:45:26 +0000628 lambda x: normpath(x.AbsoluteLocalPath()).startswith(dir_with_slash),
Edward Lemurb9830242019-10-30 22:19:20 +0000629 self.change.AffectedFiles(include_deletes, file_filter)))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000630
agable0b65e732016-11-22 09:25:46 -0800631 def LocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000632 """Returns local paths of input_api.AffectedFiles()."""
agable0b65e732016-11-22 09:25:46 -0800633 paths = [af.LocalPath() for af in self.AffectedFiles()]
pgervais@chromium.org2f64f782014-04-25 00:12:33 +0000634 logging.debug("LocalPaths: %s", paths)
635 return paths
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000636
agable0b65e732016-11-22 09:25:46 -0800637 def AbsoluteLocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000638 """Returns absolute local paths of input_api.AffectedFiles()."""
agable0b65e732016-11-22 09:25:46 -0800639 return [af.AbsoluteLocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000640
John Budorick16162372018-04-18 10:39:53 -0700641 def AffectedTestableFiles(self, include_deletes=None, **kwargs):
agable0b65e732016-11-22 09:25:46 -0800642 """Same as input_api.change.AffectedTestableFiles() except only lists files
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000643 in the same directory as the current presubmit script, or subdirectories
644 thereof.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000645 """
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000646 if include_deletes is not None:
agable0b65e732016-11-22 09:25:46 -0800647 warn("AffectedTestableFiles(include_deletes=%s)"
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000648 " is deprecated and ignored" % str(include_deletes),
649 category=DeprecationWarning,
650 stacklevel=2)
Edward Lemurb9830242019-10-30 22:19:20 +0000651 return list(filter(
652 lambda x: x.IsTestableFile(),
653 self.AffectedFiles(include_deletes=False, **kwargs)))
agable0b65e732016-11-22 09:25:46 -0800654
655 def AffectedTextFiles(self, include_deletes=None):
656 """An alias to AffectedTestableFiles for backwards compatibility."""
657 return self.AffectedTestableFiles(include_deletes=include_deletes)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000658
maruel@chromium.org3410d912009-06-09 20:56:16 +0000659 def FilterSourceFile(self, affected_file, white_list=None, black_list=None):
660 """Filters out files that aren't considered "source file".
661
662 If white_list or black_list is None, InputApi.DEFAULT_WHITE_LIST
663 and InputApi.DEFAULT_BLACK_LIST is used respectively.
664
665 The lists will be compiled as regular expression and
666 AffectedFile.LocalPath() needs to pass both list.
667
668 Note: Copy-paste this function to suit your needs or use a lambda function.
669 """
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000670 def Find(affected_file, items):
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000671 local_path = affected_file.LocalPath()
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000672 for item in items:
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000673 if self.re.match(item, local_path):
maruel@chromium.org3410d912009-06-09 20:56:16 +0000674 return True
675 return False
676 return (Find(affected_file, white_list or self.DEFAULT_WHITE_LIST) and
677 not Find(affected_file, black_list or self.DEFAULT_BLACK_LIST))
678
679 def AffectedSourceFiles(self, source_file):
agable0b65e732016-11-22 09:25:46 -0800680 """Filter the list of AffectedTestableFiles by the function source_file.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000681
682 If source_file is None, InputApi.FilterSourceFile() is used.
683 """
684 if not source_file:
685 source_file = self.FilterSourceFile
Edward Lemurb9830242019-10-30 22:19:20 +0000686 return list(filter(source_file, self.AffectedTestableFiles()))
maruel@chromium.org3410d912009-06-09 20:56:16 +0000687
688 def RightHandSideLines(self, source_file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000689 """An iterator over all text lines in "new" version of changed files.
690
691 Only lists lines from new or modified text files in the change that are
692 contained by the directory of the currently executing presubmit script.
693
694 This is useful for doing line-by-line regex checks, like checking for
695 trailing whitespace.
696
697 Yields:
698 a 3 tuple:
699 the AffectedFile instance of the current file;
700 integer line number (1-based); and
701 the contents of the line as a string.
maruel@chromium.org1487d532009-06-06 00:22:57 +0000702
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000703 Note: The carriage return (LF or CR) is stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000704 """
maruel@chromium.org3410d912009-06-09 20:56:16 +0000705 files = self.AffectedSourceFiles(source_file_filter)
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000706 return _RightHandSideLinesImpl(files)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000707
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000708 def ReadFile(self, file_item, mode='r'):
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000709 """Reads an arbitrary file.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000710
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000711 Deny reading anything outside the repository.
712 """
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000713 if isinstance(file_item, AffectedFile):
714 file_item = file_item.AbsoluteLocalPath()
715 if not file_item.startswith(self.change.RepositoryRoot()):
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000716 raise IOError('Access outside the repository root is denied.')
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000717 return gclient_utils.FileRead(file_item, mode)
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000718
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +0100719 def CreateTemporaryFile(self, **kwargs):
720 """Returns a named temporary file that must be removed with a call to
721 RemoveTemporaryFiles().
722
723 All keyword arguments are forwarded to tempfile.NamedTemporaryFile(),
724 except for |delete|, which is always set to False.
725
726 Presubmit checks that need to create a temporary file and pass it for
727 reading should use this function instead of NamedTemporaryFile(), as
728 Windows fails to open a file that is already open for writing.
729
730 with input_api.CreateTemporaryFile() as f:
731 f.write('xyz')
732 f.close()
733 input_api.subprocess.check_output(['script-that', '--reads-from',
734 f.name])
735
736
737 Note that callers of CreateTemporaryFile() should not worry about removing
738 any temporary file; this is done transparently by the presubmit handling
739 code.
740 """
741 if 'delete' in kwargs:
742 # Prevent users from passing |delete|; we take care of file deletion
743 # ourselves and this prevents unintuitive error messages when we pass
744 # delete=False and 'delete' is also in kwargs.
745 raise TypeError('CreateTemporaryFile() does not take a "delete" '
746 'argument, file deletion is handled automatically by '
747 'the same presubmit_support code that creates InputApi '
748 'objects.')
749 temp_file = self.tempfile.NamedTemporaryFile(delete=False, **kwargs)
750 self._named_temporary_files.append(temp_file.name)
751 return temp_file
752
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000753 @property
754 def tbr(self):
755 """Returns if a change is TBR'ed."""
Jeremy Romandce22502017-06-20 15:37:29 -0400756 return 'TBR' in self.change.tags or self.change.TBRsFromDescription()
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000757
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +0000758 def RunTests(self, tests_mix, parallel=True):
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000759 tests = []
760 msgs = []
761 for t in tests_mix:
Edward Lesmes8e282792018-04-03 18:50:29 -0400762 if isinstance(t, OutputApi.PresubmitResult) and t:
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000763 msgs.append(t)
764 else:
765 assert issubclass(t.message, _PresubmitResult)
766 tests.append(t)
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +0000767 if self.verbose:
768 t.info = _PresubmitNotifyResult
Edward Lemur1037c742018-05-01 18:56:04 -0400769 if not t.kwargs.get('cwd'):
770 t.kwargs['cwd'] = self.PresubmitLocalPath()
Edward Lesmes8e282792018-04-03 18:50:29 -0400771 self.thread_pool.AddTests(tests, parallel)
Edward Lemur21000eb2019-05-24 23:25:58 +0000772 # When self.parallel is True (i.e. --parallel is passed as an option)
773 # RunTests doesn't actually run tests. It adds them to a ThreadPool that
774 # will run all tests once all PRESUBMIT files are processed.
775 # Otherwise, it will run them and return the results.
776 if not self.parallel:
Edward Lesmes8e282792018-04-03 18:50:29 -0400777 msgs.extend(self.thread_pool.RunAsync())
778 return msgs
scottmg86099d72016-09-01 09:16:51 -0700779
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000780
nick@chromium.orgff526192013-06-10 19:30:26 +0000781class _DiffCache(object):
782 """Caches diffs retrieved from a particular SCM."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000783 def __init__(self, upstream=None):
784 """Stores the upstream revision against which all diffs will be computed."""
785 self._upstream = upstream
nick@chromium.orgff526192013-06-10 19:30:26 +0000786
787 def GetDiff(self, path, local_root):
788 """Get the diff for a particular path."""
789 raise NotImplementedError()
790
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700791 def GetOldContents(self, path, local_root):
792 """Get the old version for a particular path."""
793 raise NotImplementedError()
794
nick@chromium.orgff526192013-06-10 19:30:26 +0000795
nick@chromium.orgff526192013-06-10 19:30:26 +0000796class _GitDiffCache(_DiffCache):
797 """DiffCache implementation for git; gets all file diffs at once."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000798 def __init__(self, upstream):
799 super(_GitDiffCache, self).__init__(upstream=upstream)
nick@chromium.orgff526192013-06-10 19:30:26 +0000800 self._diffs_by_file = None
801
802 def GetDiff(self, path, local_root):
803 if not self._diffs_by_file:
804 # Compute a single diff for all files and parse the output; should
805 # with git this is much faster than computing one diff for each file.
806 diffs = {}
807
808 # Don't specify any filenames below, because there are command line length
809 # limits on some platforms and GenerateDiff would fail.
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000810 unified_diff = scm.GIT.GenerateDiff(local_root, files=[], full_move=True,
811 branch=self._upstream)
nick@chromium.orgff526192013-06-10 19:30:26 +0000812
813 # This regex matches the path twice, separated by a space. Note that
814 # filename itself may contain spaces.
815 file_marker = re.compile('^diff --git (?P<filename>.*) (?P=filename)$')
816 current_diff = []
817 keep_line_endings = True
818 for x in unified_diff.splitlines(keep_line_endings):
819 match = file_marker.match(x)
820 if match:
821 # Marks the start of a new per-file section.
822 diffs[match.group('filename')] = current_diff = [x]
823 elif x.startswith('diff --git'):
824 raise PresubmitFailure('Unexpected diff line: %s' % x)
825 else:
826 current_diff.append(x)
827
828 self._diffs_by_file = dict(
829 (normpath(path), ''.join(diff)) for path, diff in diffs.items())
830
831 if path not in self._diffs_by_file:
832 raise PresubmitFailure(
833 'Unified diff did not contain entry for file %s' % path)
834
835 return self._diffs_by_file[path]
836
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700837 def GetOldContents(self, path, local_root):
838 return scm.GIT.GetOldContents(local_root, path, branch=self._upstream)
839
nick@chromium.orgff526192013-06-10 19:30:26 +0000840
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000841class AffectedFile(object):
842 """Representation of a file in a change."""
nick@chromium.orgff526192013-06-10 19:30:26 +0000843
844 DIFF_CACHE = _DiffCache
845
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000846 # Method could be a function
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800847 # pylint: disable=no-self-use
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000848 def __init__(self, path, action, repository_root, diff_cache):
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000849 self._path = path
850 self._action = action
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000851 self._local_root = repository_root
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000852 self._is_directory = None
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000853 self._cached_changed_contents = None
854 self._cached_new_contents = None
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000855 self._diff_cache = diff_cache
tobiasjs2836bcf2016-08-16 04:08:16 -0700856 logging.debug('%s(%s)', self.__class__.__name__, self._path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000857
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000858 def LocalPath(self):
859 """Returns the path of this file on the local disk relative to client root.
Andrew Grieve92b8b992017-11-02 09:42:24 -0400860
861 This should be used for error messages but not for accessing files,
862 because presubmit checks are run with CWD=PresubmitLocalPath() (which is
863 often != client root).
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000864 """
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000865 return normpath(self._path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000866
867 def AbsoluteLocalPath(self):
868 """Returns the absolute path of this file on the local disk.
869 """
chase@chromium.org8e416c82009-10-06 04:30:44 +0000870 return os.path.abspath(os.path.join(self._local_root, self.LocalPath()))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000871
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000872 def Action(self):
873 """Returns the action on this opened file, e.g. A, M, D, etc."""
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000874 return self._action
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000875
agable0b65e732016-11-22 09:25:46 -0800876 def IsTestableFile(self):
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000877 """Returns True if the file is a text file and not a binary file.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000878
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000879 Deleted files are not text file."""
maruel@chromium.org1e08c002009-05-28 19:09:33 +0000880 raise NotImplementedError() # Implement when needed
881
agable0b65e732016-11-22 09:25:46 -0800882 def IsTextFile(self):
883 """An alias to IsTestableFile for backwards compatibility."""
884 return self.IsTestableFile()
885
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700886 def OldContents(self):
887 """Returns an iterator over the lines in the old version of file.
888
Daniel Cheng2da34fe2017-03-21 20:42:12 -0700889 The old version is the file before any modifications in the user's
890 workspace, i.e. the "left hand side".
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700891
892 Contents will be empty if the file is a directory or does not exist.
893 Note: The carriage returns (LF or CR) are stripped off.
894 """
895 return self._diff_cache.GetOldContents(self.LocalPath(),
896 self._local_root).splitlines()
897
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000898 def NewContents(self):
899 """Returns an iterator over the lines in the new version of file.
900
901 The new version is the file in the user's workspace, i.e. the "right hand
902 side".
903
904 Contents will be empty if the file is a directory or does not exist.
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000905 Note: The carriage returns (LF or CR) are stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000906 """
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000907 if self._cached_new_contents is None:
908 self._cached_new_contents = []
agable0b65e732016-11-22 09:25:46 -0800909 try:
910 self._cached_new_contents = gclient_utils.FileRead(
911 self.AbsoluteLocalPath(), 'rU').splitlines()
912 except IOError:
913 pass # File not found? That's fine; maybe it was deleted.
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000914 return self._cached_new_contents[:]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000915
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000916 def ChangedContents(self):
917 """Returns a list of tuples (line number, line text) of all new lines.
918
919 This relies on the scm diff output describing each changed code section
920 with a line of the form
921
922 ^@@ <old line num>,<old size> <new line num>,<new size> @@$
923 """
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000924 if self._cached_changed_contents is not None:
925 return self._cached_changed_contents[:]
926 self._cached_changed_contents = []
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000927 line_num = 0
928
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000929 for line in self.GenerateScmDiff().splitlines():
930 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
931 if m:
932 line_num = int(m.groups(1)[0])
933 continue
934 if line.startswith('+') and not line.startswith('++'):
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000935 self._cached_changed_contents.append((line_num, line[1:]))
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000936 if not line.startswith('-'):
937 line_num += 1
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000938 return self._cached_changed_contents[:]
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000939
maruel@chromium.org5de13972009-06-10 18:16:06 +0000940 def __str__(self):
941 return self.LocalPath()
942
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000943 def GenerateScmDiff(self):
nick@chromium.orgff526192013-06-10 19:30:26 +0000944 return self._diff_cache.GetDiff(self.LocalPath(), self._local_root)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000945
maruel@chromium.org58407af2011-04-12 23:15:57 +0000946
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000947class GitAffectedFile(AffectedFile):
948 """Representation of a file in a change out of a git checkout."""
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000949 # Method 'NNN' is abstract in class 'NNN' but is not overridden
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800950 # pylint: disable=abstract-method
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000951
nick@chromium.orgff526192013-06-10 19:30:26 +0000952 DIFF_CACHE = _GitDiffCache
953
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000954 def __init__(self, *args, **kwargs):
955 AffectedFile.__init__(self, *args, **kwargs)
956 self._server_path = None
agable0b65e732016-11-22 09:25:46 -0800957 self._is_testable_file = None
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000958
agable0b65e732016-11-22 09:25:46 -0800959 def IsTestableFile(self):
960 if self._is_testable_file is None:
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000961 if self.Action() == 'D':
agable0b65e732016-11-22 09:25:46 -0800962 # A deleted file is not testable.
963 self._is_testable_file = False
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000964 else:
agable0b65e732016-11-22 09:25:46 -0800965 self._is_testable_file = os.path.isfile(self.AbsoluteLocalPath())
966 return self._is_testable_file
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000967
maruel@chromium.orgc1938752011-04-12 23:11:13 +0000968
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000969class Change(object):
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000970 """Describe a change.
971
972 Used directly by the presubmit scripts to query the current change being
973 tested.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000974
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000975 Instance members:
nick@chromium.orgff526192013-06-10 19:30:26 +0000976 tags: Dictionary of KEY=VALUE pairs found in the change description.
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000977 self.KEY: equivalent to tags['KEY']
978 """
979
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000980 _AFFECTED_FILES = AffectedFile
981
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000982 # Matches key/value (or "tag") lines in changelist descriptions.
maruel@chromium.org428342a2011-11-10 15:46:33 +0000983 TAG_LINE_RE = re.compile(
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +0000984 '^[ \t]*(?P<key>[A-Z][A-Z_0-9]*)[ \t]*=[ \t]*(?P<value>.*?)[ \t]*$')
maruel@chromium.orgc1938752011-04-12 23:11:13 +0000985 scm = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000986
maruel@chromium.org58407af2011-04-12 23:15:57 +0000987 def __init__(
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000988 self, name, description, local_root, files, issue, patchset, author,
989 upstream=None):
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000990 if files is None:
991 files = []
992 self._name = name
chase@chromium.org8e416c82009-10-06 04:30:44 +0000993 # Convert root into an absolute path.
994 self._local_root = os.path.abspath(local_root)
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000995 self._upstream = upstream
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000996 self.issue = issue
997 self.patchset = patchset
maruel@chromium.org58407af2011-04-12 23:15:57 +0000998 self.author_email = author
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000999
isherman@chromium.orgb5cded62014-03-25 17:47:57 +00001000 self._full_description = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001001 self.tags = {}
isherman@chromium.orgb5cded62014-03-25 17:47:57 +00001002 self._description_without_tags = ''
1003 self.SetDescriptionText(description)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001004
maruel@chromium.orge085d812011-10-10 19:49:15 +00001005 assert all(
1006 (isinstance(f, (list, tuple)) and len(f) == 2) for f in files), files
1007
agable@chromium.orgea84ef12014-04-30 19:55:12 +00001008 diff_cache = self._AFFECTED_FILES.DIFF_CACHE(self._upstream)
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001009 self._affected_files = [
nick@chromium.orgff526192013-06-10 19:30:26 +00001010 self._AFFECTED_FILES(path, action.strip(), self._local_root, diff_cache)
1011 for action, path in files
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +00001012 ]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001013
maruel@chromium.org92022ec2009-06-11 01:59:28 +00001014 def Name(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001015 """Returns the change name."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001016 return self._name
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001017
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001018 def DescriptionText(self):
1019 """Returns the user-entered changelist description, minus tags.
1020
1021 Any line in the user-provided description starting with e.g. "FOO="
1022 (whitespace permitted before and around) is considered a tag line. Such
1023 lines are stripped out of the description this function returns.
1024 """
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001025 return self._description_without_tags
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001026
1027 def FullDescriptionText(self):
1028 """Returns the complete changelist description including tags."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001029 return self._full_description
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001030
isherman@chromium.orgb5cded62014-03-25 17:47:57 +00001031 def SetDescriptionText(self, description):
1032 """Sets the full description text (including tags) to |description|.
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001033
isherman@chromium.orgb5cded62014-03-25 17:47:57 +00001034 Also updates the list of tags."""
1035 self._full_description = description
1036
1037 # From the description text, build up a dictionary of key/value pairs
1038 # plus the description minus all key/value or "tag" lines.
1039 description_without_tags = []
1040 self.tags = {}
1041 for line in self._full_description.splitlines():
1042 m = self.TAG_LINE_RE.match(line)
1043 if m:
1044 self.tags[m.group('key')] = m.group('value')
1045 else:
1046 description_without_tags.append(line)
1047
1048 # Change back to text and remove whitespace at end.
1049 self._description_without_tags = (
1050 '\n'.join(description_without_tags).rstrip())
1051
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001052 def RepositoryRoot(self):
maruel@chromium.org92022ec2009-06-11 01:59:28 +00001053 """Returns the repository (checkout) root directory for this change,
1054 as an absolute path.
1055 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001056 return self._local_root
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001057
1058 def __getattr__(self, attr):
maruel@chromium.org92022ec2009-06-11 01:59:28 +00001059 """Return tags directly as attributes on the object."""
1060 if not re.match(r"^[A-Z_]*$", attr):
1061 raise AttributeError(self, attr)
maruel@chromium.orge1a524f2009-05-27 14:43:46 +00001062 return self.tags.get(attr)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001063
Aaron Gablefc03e672017-05-15 14:09:42 -07001064 def BugsFromDescription(self):
1065 """Returns all bugs referenced in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -07001066 tags = [b.strip() for b in self.tags.get('BUG', '').split(',') if b.strip()]
Caleb Rouleauc0546b92019-02-22 06:12:57 +00001067 footers = []
Dan Beam62954042019-10-03 21:20:33 +00001068 parsed = git_footers.parse_footers(self._full_description)
1069 unsplit_footers = parsed.get('Bug', []) + parsed.get('Fixed', [])
Caleb Rouleauc0546b92019-02-22 06:12:57 +00001070 for unsplit_footer in unsplit_footers:
1071 footers += [b.strip() for b in unsplit_footer.split(',')]
Aaron Gable12ef5012017-05-15 14:29:00 -07001072 return sorted(set(tags + footers))
Aaron Gablefc03e672017-05-15 14:09:42 -07001073
1074 def ReviewersFromDescription(self):
1075 """Returns all reviewers listed in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -07001076 # We don't support a "R:" git-footer for reviewers; that is in metadata.
1077 tags = [r.strip() for r in self.tags.get('R', '').split(',') if r.strip()]
1078 return sorted(set(tags))
Aaron Gablefc03e672017-05-15 14:09:42 -07001079
1080 def TBRsFromDescription(self):
1081 """Returns all TBR reviewers listed in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -07001082 tags = [r.strip() for r in self.tags.get('TBR', '').split(',') if r.strip()]
1083 # TODO(agable): Remove support for 'Tbr:' when TBRs are programmatically
1084 # determined by self-CR+1s.
1085 footers = git_footers.parse_footers(self._full_description).get('Tbr', [])
1086 return sorted(set(tags + footers))
Aaron Gablefc03e672017-05-15 14:09:42 -07001087
1088 # TODO(agable): Delete these once we're sure they're unused.
1089 @property
1090 def BUG(self):
1091 return ','.join(self.BugsFromDescription())
1092 @property
1093 def R(self):
1094 return ','.join(self.ReviewersFromDescription())
1095 @property
1096 def TBR(self):
1097 return ','.join(self.TBRsFromDescription())
1098
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001099 def AllFiles(self, root=None):
1100 """List all files under source control in the repo."""
1101 raise NotImplementedError()
1102
agable0b65e732016-11-22 09:25:46 -08001103 def AffectedFiles(self, include_deletes=True, file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001104 """Returns a list of AffectedFile instances for all files in the change.
1105
1106 Args:
1107 include_deletes: If false, deleted files will be filtered out.
sail@chromium.org5538e022011-05-12 17:53:16 +00001108 file_filter: An additional filter to apply.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001109
1110 Returns:
1111 [AffectedFile(path, action), AffectedFile(path, action)]
1112 """
Edward Lemurb9830242019-10-30 22:19:20 +00001113 affected = list(filter(file_filter, self._affected_files))
sail@chromium.org5538e022011-05-12 17:53:16 +00001114
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001115 if include_deletes:
1116 return affected
Edward Lemurb9830242019-10-30 22:19:20 +00001117 return list(filter(lambda x: x.Action() != 'D', affected))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001118
John Budorick16162372018-04-18 10:39:53 -07001119 def AffectedTestableFiles(self, include_deletes=None, **kwargs):
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +00001120 """Return a list of the existing text files in a change."""
1121 if include_deletes is not None:
agable0b65e732016-11-22 09:25:46 -08001122 warn("AffectedTeestableFiles(include_deletes=%s)"
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +00001123 " is deprecated and ignored" % str(include_deletes),
1124 category=DeprecationWarning,
1125 stacklevel=2)
Edward Lemurb9830242019-10-30 22:19:20 +00001126 return list(filter(
1127 lambda x: x.IsTestableFile(),
1128 self.AffectedFiles(include_deletes=False, **kwargs)))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001129
agable0b65e732016-11-22 09:25:46 -08001130 def AffectedTextFiles(self, include_deletes=None):
1131 """An alias to AffectedTestableFiles for backwards compatibility."""
1132 return self.AffectedTestableFiles(include_deletes=include_deletes)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001133
agable0b65e732016-11-22 09:25:46 -08001134 def LocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001135 """Convenience function."""
agable0b65e732016-11-22 09:25:46 -08001136 return [af.LocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001137
agable0b65e732016-11-22 09:25:46 -08001138 def AbsoluteLocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001139 """Convenience function."""
agable0b65e732016-11-22 09:25:46 -08001140 return [af.AbsoluteLocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001141
1142 def RightHandSideLines(self):
1143 """An iterator over all text lines in "new" version of changed files.
1144
1145 Lists lines from new or modified text files in the change.
1146
1147 This is useful for doing line-by-line regex checks, like checking for
1148 trailing whitespace.
1149
1150 Yields:
1151 a 3 tuple:
1152 the AffectedFile instance of the current file;
1153 integer line number (1-based); and
1154 the contents of the line as a string.
1155 """
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +00001156 return _RightHandSideLinesImpl(
1157 x for x in self.AffectedFiles(include_deletes=False)
agable0b65e732016-11-22 09:25:46 -08001158 if x.IsTestableFile())
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001159
Jochen Eisingerd0573ec2017-04-13 10:55:06 +02001160 def OriginalOwnersFiles(self):
1161 """A map from path names of affected OWNERS files to their old content."""
1162 def owners_file_filter(f):
1163 return 'OWNERS' in os.path.split(f.LocalPath())[1]
1164 files = self.AffectedFiles(file_filter=owners_file_filter)
1165 return dict([(f.LocalPath(), f.OldContents()) for f in files])
1166
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001167
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001168class GitChange(Change):
1169 _AFFECTED_FILES = GitAffectedFile
maruel@chromium.orgc1938752011-04-12 23:11:13 +00001170 scm = 'git'
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +00001171
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001172 def AllFiles(self, root=None):
1173 """List all files under source control in the repo."""
1174 root = root or self.RepositoryRoot()
1175 return subprocess.check_output(
Aaron Gable7817f022017-12-12 09:43:17 -08001176 ['git', '-c', 'core.quotePath=false', 'ls-files', '--', '.'],
1177 cwd=root).splitlines()
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001178
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001179
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001180def ListRelevantPresubmitFiles(files, root):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001181 """Finds all presubmit files that apply to a given set of source files.
1182
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001183 If inherit-review-settings-ok is present right under root, looks for
1184 PRESUBMIT.py in directories enclosing root.
1185
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001186 Args:
1187 files: An iterable container containing file paths.
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001188 root: Path where to stop searching.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001189
1190 Return:
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001191 List of absolute paths of the existing PRESUBMIT.py scripts.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001192 """
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001193 files = [normpath(os.path.join(root, f)) for f in files]
1194
1195 # List all the individual directories containing files.
1196 directories = set([os.path.dirname(f) for f in files])
1197
1198 # Ignore root if inherit-review-settings-ok is present.
1199 if os.path.isfile(os.path.join(root, 'inherit-review-settings-ok')):
1200 root = None
1201
1202 # Collect all unique directories that may contain PRESUBMIT.py.
1203 candidates = set()
1204 for directory in directories:
1205 while True:
1206 if directory in candidates:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001207 break
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001208 candidates.add(directory)
1209 if directory == root:
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001210 break
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001211 parent_dir = os.path.dirname(directory)
1212 if parent_dir == directory:
1213 # We hit the system root directory.
1214 break
1215 directory = parent_dir
1216
1217 # Look for PRESUBMIT.py in all candidate directories.
1218 results = []
1219 for directory in sorted(list(candidates)):
tobiasjsff061c02016-08-17 03:23:57 -07001220 try:
1221 for f in os.listdir(directory):
1222 p = os.path.join(directory, f)
1223 if os.path.isfile(p) and re.match(
1224 r'PRESUBMIT.*\.py$', f) and not f.startswith('PRESUBMIT_test'):
1225 results.append(p)
1226 except OSError:
1227 pass
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001228
tobiasjs2836bcf2016-08-16 04:08:16 -07001229 logging.debug('Presubmit files: %s', ','.join(results))
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001230 return results
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001231
1232
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001233class GetTryMastersExecuter(object):
1234 @staticmethod
1235 def ExecPresubmitScript(script_text, presubmit_path, project, change):
1236 """Executes GetPreferredTryMasters() from a single presubmit script.
1237
1238 Args:
1239 script_text: The text of the presubmit script.
1240 presubmit_path: Project script to run.
1241 project: Project name to pass to presubmit script for bot selection.
1242
1243 Return:
1244 A map of try masters to map of builders to set of tests.
1245 """
1246 context = {}
1247 try:
Raul Tambre09e64b42019-05-14 01:57:22 +00001248 exec(compile(script_text, 'PRESUBMIT.py', 'exec', dont_inherit=True),
1249 context)
Raul Tambre7c938462019-05-24 16:35:35 +00001250 except Exception as e:
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001251 raise PresubmitFailure('"%s" had an exception.\n%s'
1252 % (presubmit_path, e))
1253
1254 function_name = 'GetPreferredTryMasters'
1255 if function_name not in context:
1256 return {}
1257 get_preferred_try_masters = context[function_name]
1258 if not len(inspect.getargspec(get_preferred_try_masters)[0]) == 2:
1259 raise PresubmitFailure(
1260 'Expected function "GetPreferredTryMasters" to take two arguments.')
1261 return get_preferred_try_masters(project, change)
1262
1263
rmistry@google.com5626a922015-02-26 14:03:30 +00001264class GetPostUploadExecuter(object):
1265 @staticmethod
1266 def ExecPresubmitScript(script_text, presubmit_path, cl, change):
1267 """Executes PostUploadHook() from a single presubmit script.
1268
1269 Args:
1270 script_text: The text of the presubmit script.
1271 presubmit_path: Project script to run.
1272 cl: The Changelist object.
1273 change: The Change object.
1274
1275 Return:
1276 A list of results objects.
1277 """
1278 context = {}
1279 try:
Raul Tambre09e64b42019-05-14 01:57:22 +00001280 exec(compile(script_text, 'PRESUBMIT.py', 'exec', dont_inherit=True),
1281 context)
Raul Tambre7c938462019-05-24 16:35:35 +00001282 except Exception as e:
rmistry@google.com5626a922015-02-26 14:03:30 +00001283 raise PresubmitFailure('"%s" had an exception.\n%s'
1284 % (presubmit_path, e))
1285
1286 function_name = 'PostUploadHook'
1287 if function_name not in context:
1288 return {}
1289 post_upload_hook = context[function_name]
1290 if not len(inspect.getargspec(post_upload_hook)[0]) == 3:
1291 raise PresubmitFailure(
1292 'Expected function "PostUploadHook" to take three arguments.')
1293 return post_upload_hook(cl, change, OutputApi(False))
1294
1295
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001296def _MergeMasters(masters1, masters2):
1297 """Merges two master maps. Merges also the tests of each builder."""
1298 result = {}
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00001299 for (master, builders) in itertools.chain(masters1.items(),
1300 masters2.items()):
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001301 new_builders = result.setdefault(master, {})
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00001302 for (builder, tests) in builders.items():
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001303 new_builders.setdefault(builder, set([])).update(tests)
1304 return result
1305
1306
1307def DoGetTryMasters(change,
1308 changed_files,
1309 repository_root,
1310 default_presubmit,
1311 project,
1312 verbose,
1313 output_stream):
1314 """Get the list of try masters from the presubmit scripts.
1315
1316 Args:
1317 changed_files: List of modified files.
1318 repository_root: The repository root.
1319 default_presubmit: A default presubmit script to execute in any case.
1320 project: Optional name of a project used in selecting trybots.
1321 verbose: Prints debug info.
1322 output_stream: A stream to write debug output to.
1323
1324 Return:
1325 Map of try masters to map of builders to set of tests.
1326 """
1327 presubmit_files = ListRelevantPresubmitFiles(changed_files, repository_root)
1328 if not presubmit_files and verbose:
1329 output_stream.write("Warning, no PRESUBMIT.py found.\n")
1330 results = {}
1331 executer = GetTryMastersExecuter()
1332
1333 if default_presubmit:
1334 if verbose:
1335 output_stream.write("Running default presubmit script.\n")
1336 fake_path = os.path.join(repository_root, 'PRESUBMIT.py')
1337 results = _MergeMasters(results, executer.ExecPresubmitScript(
1338 default_presubmit, fake_path, project, change))
1339 for filename in presubmit_files:
1340 filename = os.path.abspath(filename)
1341 if verbose:
1342 output_stream.write("Running %s\n" % filename)
1343 # Accept CRLF presubmit script.
1344 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1345 results = _MergeMasters(results, executer.ExecPresubmitScript(
1346 presubmit_script, filename, project, change))
1347
1348 # Make sets to lists again for later JSON serialization.
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00001349 for builders in results.values():
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001350 for builder in builders:
1351 builders[builder] = list(builders[builder])
1352
1353 if results and verbose:
1354 output_stream.write('%s\n' % str(results))
1355 return results
1356
1357
rmistry@google.com5626a922015-02-26 14:03:30 +00001358def DoPostUploadExecuter(change,
1359 cl,
1360 repository_root,
1361 verbose,
1362 output_stream):
1363 """Execute the post upload hook.
1364
1365 Args:
1366 change: The Change object.
1367 cl: The Changelist object.
1368 repository_root: The repository root.
1369 verbose: Prints debug info.
1370 output_stream: A stream to write debug output to.
1371 """
1372 presubmit_files = ListRelevantPresubmitFiles(
1373 change.LocalPaths(), repository_root)
1374 if not presubmit_files and verbose:
1375 output_stream.write("Warning, no PRESUBMIT.py found.\n")
1376 results = []
1377 executer = GetPostUploadExecuter()
1378 # The root presubmit file should be executed after the ones in subdirectories.
1379 # i.e. the specific post upload hooks should run before the general ones.
1380 # Thus, reverse the order provided by ListRelevantPresubmitFiles.
1381 presubmit_files.reverse()
1382
1383 for filename in presubmit_files:
1384 filename = os.path.abspath(filename)
1385 if verbose:
1386 output_stream.write("Running %s\n" % filename)
1387 # Accept CRLF presubmit script.
1388 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1389 results.extend(executer.ExecPresubmitScript(
1390 presubmit_script, filename, cl, change))
1391 output_stream.write('\n')
1392 if results:
1393 output_stream.write('** Post Upload Hook Messages **\n')
1394 for result in results:
1395 result.handle(output_stream)
1396 output_stream.write('\n')
1397
1398 return results
1399
1400
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001401class PresubmitExecuter(object):
Aaron Gable668c1d82018-04-03 10:19:16 -07001402 def __init__(self, change, committing, verbose,
Edward Lesmes8e282792018-04-03 18:50:29 -04001403 gerrit_obj, dry_run=None, thread_pool=None, parallel=False):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001404 """
1405 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001406 change: The Change object.
agable92bec4f2016-08-24 09:27:27 -07001407 committing: True if 'git cl land' is running, False if 'git cl upload' is.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001408 gerrit_obj: provides basic Gerrit codereview functionality.
1409 dry_run: if true, some Checks will be skipped.
Edward Lesmes8e282792018-04-03 18:50:29 -04001410 parallel: if true, all tests reported via input_api.RunTests for all
1411 PRESUBMIT files will be run in parallel.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001412 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001413 self.change = change
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001414 self.committing = committing
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001415 self.gerrit = gerrit_obj
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001416 self.verbose = verbose
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001417 self.dry_run = dry_run
Daniel Cheng7227d212017-11-17 08:12:37 -08001418 self.more_cc = []
Edward Lesmes8e282792018-04-03 18:50:29 -04001419 self.thread_pool = thread_pool
1420 self.parallel = parallel
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001421
1422 def ExecPresubmitScript(self, script_text, presubmit_path):
1423 """Executes a single presubmit script.
1424
1425 Args:
1426 script_text: The text of the presubmit script.
1427 presubmit_path: The path to the presubmit file (this will be reported via
1428 input_api.PresubmitLocalPath()).
1429
1430 Return:
1431 A list of result objects, empty if no problems.
1432 """
thakis@chromium.orgc6ef53a2014-11-04 00:13:54 +00001433
chase@chromium.org8e416c82009-10-06 04:30:44 +00001434 # Change to the presubmit file's directory to support local imports.
1435 main_path = os.getcwd()
1436 os.chdir(os.path.dirname(presubmit_path))
1437
1438 # Load the presubmit script into context.
dpranke@chromium.org970c5222011-03-12 00:32:24 +00001439 input_api = InputApi(self.change, presubmit_path, self.committing,
Aaron Gable668c1d82018-04-03 10:19:16 -07001440 self.verbose, gerrit_obj=self.gerrit,
Edward Lesmes8e282792018-04-03 18:50:29 -04001441 dry_run=self.dry_run, thread_pool=self.thread_pool,
1442 parallel=self.parallel)
Daniel Cheng7227d212017-11-17 08:12:37 -08001443 output_api = OutputApi(self.committing)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001444 context = {}
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001445 try:
Raul Tambre09e64b42019-05-14 01:57:22 +00001446 exec(compile(script_text, 'PRESUBMIT.py', 'exec', dont_inherit=True),
1447 context)
Raul Tambre7c938462019-05-24 16:35:35 +00001448 except Exception as e:
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001449 raise PresubmitFailure('"%s" had an exception.\n%s' % (presubmit_path, e))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001450
1451 # These function names must change if we make substantial changes to
1452 # the presubmit API that are not backwards compatible.
1453 if self.committing:
1454 function_name = 'CheckChangeOnCommit'
1455 else:
1456 function_name = 'CheckChangeOnUpload'
1457 if function_name in context:
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +01001458 try:
Daniel Cheng7227d212017-11-17 08:12:37 -08001459 context['__args'] = (input_api, output_api)
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +01001460 logging.debug('Running %s in %s', function_name, presubmit_path)
1461 result = eval(function_name + '(*__args)', context)
1462 logging.debug('Running %s done.', function_name)
Daniel Chengd36fce42017-11-21 21:52:52 -08001463 self.more_cc.extend(output_api.more_cc)
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +01001464 finally:
Edward Lemurb9830242019-10-30 22:19:20 +00001465 for f in input_api._named_temporary_files:
1466 os.remove(f)
1467 if not isinstance(result, (tuple, list)):
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001468 raise PresubmitFailure(
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001469 'Presubmit functions must return a tuple or list')
1470 for item in result:
1471 if not isinstance(item, OutputApi.PresubmitResult):
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001472 raise PresubmitFailure(
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001473 'All presubmit results must be of types derived from '
1474 'output_api.PresubmitResult')
1475 else:
1476 result = () # no error since the script doesn't care about current event.
1477
chase@chromium.org8e416c82009-10-06 04:30:44 +00001478 # Return the process to the original working directory.
1479 os.chdir(main_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001480 return result
1481
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001482def DoPresubmitChecks(change,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001483 committing,
1484 verbose,
1485 output_stream,
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +00001486 input_stream,
maruel@chromium.orgb0dfd352009-06-10 14:12:54 +00001487 default_presubmit,
dpranke@chromium.org970c5222011-03-12 00:32:24 +00001488 may_prompt,
Aaron Gable668c1d82018-04-03 10:19:16 -07001489 gerrit_obj,
Edward Lesmes8e282792018-04-03 18:50:29 -04001490 dry_run=None,
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001491 parallel=False,
1492 json_output=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001493 """Runs all presubmit checks that apply to the files in the change.
1494
1495 This finds all PRESUBMIT.py files in directories enclosing the files in the
1496 change (up to the repository root) and calls the relevant entrypoint function
1497 depending on whether the change is being committed or uploaded.
1498
1499 Prints errors, warnings and notifications. Prompts the user for warnings
1500 when needed.
1501
1502 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001503 change: The Change object.
agable92bec4f2016-08-24 09:27:27 -07001504 committing: True if 'git cl land' is running, False if 'git cl upload' is.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001505 verbose: Prints debug info.
1506 output_stream: A stream to write output from presubmit tests to.
1507 input_stream: A stream to read input from the user.
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +00001508 default_presubmit: A default presubmit script to execute in any case.
Quinten Yearsley516fe7f2016-12-14 11:50:18 -08001509 may_prompt: Enable (y/n) questions on warning or error. If False,
1510 any questions are answered with yes by default.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001511 gerrit_obj: provides basic Gerrit codereview functionality.
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001512 dry_run: if true, some Checks will be skipped.
Edward Lesmes8e282792018-04-03 18:50:29 -04001513 parallel: if true, all tests specified by input_api.RunTests in all
1514 PRESUBMIT files will be run in parallel.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001515
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +00001516 Warning:
1517 If may_prompt is true, output_stream SHOULD be sys.stdout and input_stream
1518 SHOULD be sys.stdin.
1519
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001520 Return:
dpranke@chromium.org5ac21012011-03-16 02:58:25 +00001521 A PresubmitOutput object. Use output.should_continue() to figure out
1522 if there were errors or warnings and the caller should abort.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001523 """
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001524 old_environ = os.environ
1525 try:
1526 # Make sure python subprocesses won't generate .pyc files.
1527 os.environ = os.environ.copy()
Edward Lemurb9830242019-10-30 22:19:20 +00001528 os.environ['PYTHONDONTWRITEBYTECODE'] = '1'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001529
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001530 output = PresubmitOutput(input_stream, output_stream)
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001531
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001532 if committing:
1533 output.write("Running presubmit commit checks ...\n")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001534 else:
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001535 output.write("Running presubmit upload checks ...\n")
1536 start_time = time.time()
1537 presubmit_files = ListRelevantPresubmitFiles(
agable0b65e732016-11-22 09:25:46 -08001538 change.AbsoluteLocalPaths(), change.RepositoryRoot())
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001539 if not presubmit_files and verbose:
maruel@chromium.orgfae707b2011-09-15 18:57:58 +00001540 output.write("Warning, no PRESUBMIT.py found.\n")
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001541 results = []
Edward Lesmes8e282792018-04-03 18:50:29 -04001542 thread_pool = ThreadPool()
Edward Lemur7e3c67f2018-07-20 20:52:49 +00001543 executer = PresubmitExecuter(change, committing, verbose, gerrit_obj,
1544 dry_run, thread_pool, parallel)
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001545 if default_presubmit:
1546 if verbose:
1547 output.write("Running default presubmit script.\n")
1548 fake_path = os.path.join(change.RepositoryRoot(), 'PRESUBMIT.py')
1549 results += executer.ExecPresubmitScript(default_presubmit, fake_path)
1550 for filename in presubmit_files:
1551 filename = os.path.abspath(filename)
1552 if verbose:
1553 output.write("Running %s\n" % filename)
1554 # Accept CRLF presubmit script.
1555 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1556 results += executer.ExecPresubmitScript(presubmit_script, filename)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001557
Edward Lesmes8e282792018-04-03 18:50:29 -04001558 results += thread_pool.RunAsync()
1559
Daniel Cheng7227d212017-11-17 08:12:37 -08001560 output.more_cc.extend(executer.more_cc)
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001561 errors = []
1562 notifications = []
1563 warnings = []
1564 for result in results:
1565 if result.fatal:
1566 errors.append(result)
1567 elif result.should_prompt:
1568 warnings.append(result)
1569 else:
1570 notifications.append(result)
pam@chromium.orged9a0832009-09-09 22:48:55 +00001571
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001572 if json_output:
1573 # Write the presubmit results to json output
1574 presubmit_results = {
1575 'errors': [
1576 error.json_format() for error in errors
1577 ],
1578 'notifications': [
1579 notification.json_format() for notification in notifications
1580 ],
1581 'warnings': [
1582 warning.json_format() for warning in warnings
1583 ]
1584 }
1585
Edward Lemurb9830242019-10-30 22:19:20 +00001586 gclient_utils.FileWrite(
1587 json_output, json.dumps(presubmit_results, sort_keys=True))
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001588
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001589 output.write('\n')
1590 for name, items in (('Messages', notifications),
1591 ('Warnings', warnings),
1592 ('ERRORS', errors)):
1593 if items:
1594 output.write('** Presubmit %s **\n' % name)
1595 for item in items:
1596 item.handle(output)
1597 output.write('\n')
pam@chromium.orged9a0832009-09-09 22:48:55 +00001598
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001599 total_time = time.time() - start_time
1600 if total_time > 1.0:
1601 output.write("Presubmit checks took %.1fs to calculate.\n\n" % total_time)
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +00001602
Quinten Yearsley516fe7f2016-12-14 11:50:18 -08001603 if errors:
1604 output.fail()
1605 elif warnings:
1606 output.write('There were presubmit warnings. ')
1607 if may_prompt:
1608 output.prompt_yes_no('Are you sure you wish to continue? (y/N): ')
1609 else:
1610 output.write('Presubmit checks passed.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001611
1612 global _ASKED_FOR_FEEDBACK
1613 # Ask for feedback one time out of 5.
1614 if (len(results) and random.randint(0, 4) == 0 and not _ASKED_FOR_FEEDBACK):
maruel@chromium.org1ce8e662014-01-14 15:23:00 +00001615 output.write(
1616 'Was the presubmit check useful? If not, run "git cl presubmit -v"\n'
1617 'to figure out which PRESUBMIT.py was run, then run git blame\n'
1618 'on the file to figure out who to ask for help.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001619 _ASKED_FOR_FEEDBACK = True
1620 return output
1621 finally:
1622 os.environ = old_environ
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001623
1624
1625def ScanSubDirs(mask, recursive):
1626 if not recursive:
pgervais@chromium.orge57b09d2014-05-07 00:58:13 +00001627 return [x for x in glob.glob(mask) if x not in ('.svn', '.git')]
Lei Zhang9611c4c2017-04-04 01:41:56 -07001628
1629 results = []
1630 for root, dirs, files in os.walk('.'):
1631 if '.svn' in dirs:
1632 dirs.remove('.svn')
1633 if '.git' in dirs:
1634 dirs.remove('.git')
1635 for name in files:
1636 if fnmatch.fnmatch(name, mask):
1637 results.append(os.path.join(root, name))
1638 return results
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001639
1640
1641def ParseFiles(args, recursive):
tobiasjs2836bcf2016-08-16 04:08:16 -07001642 logging.debug('Searching for %s', args)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001643 files = []
1644 for arg in args:
maruel@chromium.orge3608df2009-11-10 20:22:57 +00001645 files.extend([('M', f) for f in ScanSubDirs(arg, recursive)])
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001646 return files
1647
1648
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001649def load_files(options, args):
1650 """Tries to determine the SCM."""
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001651 files = []
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001652 if args:
1653 files = ParseFiles(args, options.recursive)
agable0b65e732016-11-22 09:25:46 -08001654 change_scm = scm.determine_scm(options.root)
1655 if change_scm == 'git':
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001656 change_class = GitChange
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001657 upstream = options.upstream or None
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001658 if not files:
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001659 files = scm.GIT.CaptureStatus([], options.root, upstream)
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001660 else:
tobiasjs2836bcf2016-08-16 04:08:16 -07001661 logging.info('Doesn\'t seem under source control. Got %d files', len(args))
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001662 if not files:
1663 return None, None
1664 change_class = Change
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001665 return change_class, files
1666
1667
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001668@contextlib.contextmanager
1669def canned_check_filter(method_names):
1670 filtered = {}
1671 try:
1672 for method_name in method_names:
1673 if not hasattr(presubmit_canned_checks, method_name):
Aaron Gableecee74c2018-04-02 15:13:08 -07001674 logging.warn('Skipping unknown "canned" check %s' % method_name)
1675 continue
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001676 filtered[method_name] = getattr(presubmit_canned_checks, method_name)
1677 setattr(presubmit_canned_checks, method_name, lambda *_a, **_kw: [])
1678 yield
1679 finally:
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00001680 for name, method in filtered.items():
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001681 setattr(presubmit_canned_checks, name, method)
1682
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001683
sbc@chromium.org013731e2015-02-26 18:28:43 +00001684def main(argv=None):
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001685 parser = optparse.OptionParser(usage="%prog [options] <files...>",
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001686 version="%prog " + str(__version__))
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001687 parser.add_option("-c", "--commit", action="store_true", default=False,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001688 help="Use commit instead of upload checks")
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001689 parser.add_option("-u", "--upload", action="store_false", dest='commit',
1690 help="Use upload instead of commit checks")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001691 parser.add_option("-r", "--recursive", action="store_true",
1692 help="Act recursively")
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001693 parser.add_option("-v", "--verbose", action="count", default=0,
1694 help="Use 2 times for more debug info")
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001695 parser.add_option("--name", default='no name')
maruel@chromium.org58407af2011-04-12 23:15:57 +00001696 parser.add_option("--author")
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001697 parser.add_option("--description", default='')
1698 parser.add_option("--issue", type='int', default=0)
1699 parser.add_option("--patchset", type='int', default=0)
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001700 parser.add_option("--root", default=os.getcwd(),
1701 help="Search for PRESUBMIT.py up to this directory. "
1702 "If inherit-review-settings-ok is present in this "
1703 "directory, parent directories up to the root file "
1704 "system directories will also be searched.")
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001705 parser.add_option("--upstream",
1706 help="Git only: the base ref or upstream branch against "
1707 "which the diff should be computed.")
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001708 parser.add_option("--default_presubmit")
1709 parser.add_option("--may_prompt", action='store_true', default=False)
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001710 parser.add_option("--skip_canned", action='append', default=[],
1711 help="A list of checks to skip which appear in "
1712 "presubmit_canned_checks. Can be provided multiple times "
1713 "to skip multiple canned checks.")
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001714 parser.add_option("--dry_run", action='store_true',
1715 help=optparse.SUPPRESS_HELP)
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001716 parser.add_option("--gerrit_url", help=optparse.SUPPRESS_HELP)
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001717 parser.add_option("--gerrit_fetch", action='store_true',
1718 help=optparse.SUPPRESS_HELP)
Edward Lesmes8e282792018-04-03 18:50:29 -04001719 parser.add_option('--parallel', action='store_true',
1720 help='Run all tests specified by input_api.RunTests in all '
1721 'PRESUBMIT files in parallel.')
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001722 parser.add_option('--json_output',
1723 help='Write presubmit errors to json output.')
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001724
maruel@chromium.org82e5f282011-03-17 14:08:55 +00001725 options, args = parser.parse_args(argv)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001726
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001727 if options.verbose >= 2:
maruel@chromium.org7444c502011-02-09 14:02:11 +00001728 logging.basicConfig(level=logging.DEBUG)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001729 elif options.verbose:
1730 logging.basicConfig(level=logging.INFO)
1731 else:
1732 logging.basicConfig(level=logging.ERROR)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001733
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001734 change_class, files = load_files(options, args)
1735 if not change_class:
1736 parser.error('For unversioned directory, <files> is not optional.')
tobiasjs2836bcf2016-08-16 04:08:16 -07001737 logging.info('Found %d file(s).', len(files))
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001738
Aaron Gable668c1d82018-04-03 10:19:16 -07001739 gerrit_obj = None
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001740 if options.gerrit_url and options.gerrit_fetch:
tandrii@chromium.org83b1b232016-04-29 16:33:19 +00001741 assert options.issue and options.patchset
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001742 gerrit_obj = GerritAccessor(urlparse.urlparse(options.gerrit_url).netloc)
1743 options.author = gerrit_obj.GetChangeOwner(options.issue)
1744 options.description = gerrit_obj.GetChangeDescription(options.issue,
1745 options.patchset)
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001746 logging.info('Got author: "%s"', options.author)
1747 logging.info('Got description: """\n%s\n"""', options.description)
1748
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001749 try:
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001750 with canned_check_filter(options.skip_canned):
1751 results = DoPresubmitChecks(
1752 change_class(options.name,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001753 options.description,
1754 options.root,
1755 files,
1756 options.issue,
1757 options.patchset,
1758 options.author,
1759 upstream=options.upstream),
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001760 options.commit,
1761 options.verbose,
1762 sys.stdout,
1763 sys.stdin,
1764 options.default_presubmit,
1765 options.may_prompt,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001766 gerrit_obj,
Edward Lesmes8e282792018-04-03 18:50:29 -04001767 options.dry_run,
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001768 options.parallel,
1769 options.json_output)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001770 return not results.should_continue()
Raul Tambre7c938462019-05-24 16:35:35 +00001771 except PresubmitFailure as e:
Raul Tambre80ee78e2019-05-06 22:41:05 +00001772 print(e, file=sys.stderr)
1773 print('Maybe your depot_tools is out of date?', file=sys.stderr)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001774 return 2
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001775
1776
1777if __name__ == '__main__':
maruel@chromium.org35625c72011-03-23 17:34:02 +00001778 fix_encoding.fix_encoding()
sbc@chromium.org013731e2015-02-26 18:28:43 +00001779 try:
1780 sys.exit(main())
1781 except KeyboardInterrupt:
1782 sys.stderr.write('interrupted\n')
sergiybf8a3b382016-07-05 11:21:30 -07001783 sys.exit(2)