blob: 419ac1985c628cd08e74a0cf74d1eb12eea0bff7 [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 Lemurd2a5a4c2019-10-23 22:55:26 +000036import types
Edward Lemurde9e3ca2019-10-24 21:13:31 +000037import traceback
maruel@chromium.org1487d532009-06-06 00:22:57 +000038import unittest # Exposed through the API.
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +000039from warnings import warn
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000040
41# Local imports.
maruel@chromium.org35625c72011-03-23 17:34:02 +000042import fix_encoding
Yoshisato Yanagisawa04600b42019-03-15 03:03:41 +000043import gclient_paths # Exposed through the API
44import gclient_utils
Aaron Gableb584c4f2017-04-26 16:28:08 -070045import git_footers
tandrii@chromium.org015ebae2016-04-25 19:37:22 +000046import gerrit_util
dpranke@chromium.org2a009622011-03-01 02:43:31 +000047import owners
Jochen Eisinger76f5fc62017-04-07 16:27:46 +020048import owners_finder
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000049import presubmit_canned_checks
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +000050import scm
maruel@chromium.org84f4fe32011-04-06 13:26:45 +000051import subprocess2 as subprocess # Exposed through the API.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000052
Edward Lemur16af3562019-10-17 22:11:33 +000053if sys.version_info.major == 2:
54 # TODO(1009814): Expose urllib2 only through urllib_request and urllib_error
55 import urllib2 # Exposed through the API.
56 import urlparse
57 import urllib2 as urllib_request
58 import urllib2 as urllib_error
59else:
60 import urllib.parse as urlparse
61 import urllib.request as urllib_request
62 import urllib.error as urllib_error
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000063
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +000064# Ask for feedback only once in program lifetime.
65_ASKED_FOR_FEEDBACK = False
66
67
maruel@chromium.org899e1c12011-04-07 17:03:18 +000068class PresubmitFailure(Exception):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000069 pass
70
71
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +000072class CommandData(object):
Edward Lemur940c2822019-08-23 00:34:25 +000073 def __init__(self, name, cmd, kwargs, message, python3=False):
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +000074 self.name = name
75 self.cmd = cmd
Edward Lesmes8e282792018-04-03 18:50:29 -040076 self.stdin = kwargs.get('stdin', None)
Edward Lemur2d6b67c2019-08-23 22:25:41 +000077 self.kwargs = kwargs.copy()
Edward Lesmes8e282792018-04-03 18:50:29 -040078 self.kwargs['stdout'] = subprocess.PIPE
79 self.kwargs['stderr'] = subprocess.STDOUT
80 self.kwargs['stdin'] = subprocess.PIPE
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +000081 self.message = message
82 self.info = None
Edward Lemur940c2822019-08-23 00:34:25 +000083 self.python3 = python3
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +000084
ilevy@chromium.orgbc117312013-04-20 03:57:56 +000085
Edward Lesmes8e282792018-04-03 18:50:29 -040086# Adapted from
87# https://github.com/google/gtest-parallel/blob/master/gtest_parallel.py#L37
88#
89# An object that catches SIGINT sent to the Python process and notices
90# if processes passed to wait() die by SIGINT (we need to look for
91# both of those cases, because pressing Ctrl+C can result in either
92# the main process or one of the subprocesses getting the signal).
93#
94# Before a SIGINT is seen, wait(p) will simply call p.wait() and
95# return the result. Once a SIGINT has been seen (in the main process
96# or a subprocess, including the one the current call is waiting for),
Edward Lemur9a5bb612019-09-26 02:01:52 +000097# wait(p) will call p.terminate().
Edward Lesmes8e282792018-04-03 18:50:29 -040098class SigintHandler(object):
Edward Lesmes8e282792018-04-03 18:50:29 -040099 sigint_returncodes = {-signal.SIGINT, # Unix
100 -1073741510, # Windows
101 }
102 def __init__(self):
103 self.__lock = threading.Lock()
104 self.__processes = set()
105 self.__got_sigint = False
Edward Lemur9a5bb612019-09-26 02:01:52 +0000106 self.__previous_signal = signal.signal(signal.SIGINT, self.interrupt)
Edward Lesmes8e282792018-04-03 18:50:29 -0400107
108 def __on_sigint(self):
109 self.__got_sigint = True
110 while self.__processes:
111 try:
112 self.__processes.pop().terminate()
113 except OSError:
114 pass
115
Edward Lemur9a5bb612019-09-26 02:01:52 +0000116 def interrupt(self, signal_num, frame):
Edward Lesmes8e282792018-04-03 18:50:29 -0400117 with self.__lock:
118 self.__on_sigint()
Edward Lemur9a5bb612019-09-26 02:01:52 +0000119 self.__previous_signal(signal_num, frame)
Edward Lesmes8e282792018-04-03 18:50:29 -0400120
121 def got_sigint(self):
122 with self.__lock:
123 return self.__got_sigint
124
125 def wait(self, p, stdin):
126 with self.__lock:
127 if self.__got_sigint:
128 p.terminate()
129 self.__processes.add(p)
130 stdout, stderr = p.communicate(stdin)
131 code = p.returncode
132 with self.__lock:
133 self.__processes.discard(p)
134 if code in self.sigint_returncodes:
135 self.__on_sigint()
Edward Lesmes8e282792018-04-03 18:50:29 -0400136 return stdout, stderr
137
138sigint_handler = SigintHandler()
139
140
141class ThreadPool(object):
142 def __init__(self, pool_size=None):
143 self._pool_size = pool_size or multiprocessing.cpu_count()
144 self._messages = []
145 self._messages_lock = threading.Lock()
146 self._tests = []
147 self._tests_lock = threading.Lock()
148 self._nonparallel_tests = []
149
150 def CallCommand(self, test):
151 """Runs an external program.
152
153 This function converts invocation of .py files and invocations of "python"
154 to vpython invocations.
155 """
Edward Lemur940c2822019-08-23 00:34:25 +0000156 vpython = 'vpython'
157 if test.python3:
158 vpython += '3'
159 if sys.platform == 'win32':
160 vpython += '.bat'
Edward Lesmes8e282792018-04-03 18:50:29 -0400161
162 cmd = test.cmd
163 if cmd[0] == 'python':
164 cmd = list(cmd)
165 cmd[0] = vpython
166 elif cmd[0].endswith('.py'):
167 cmd = [vpython] + cmd
168
169 try:
170 start = time.time()
171 p = subprocess.Popen(cmd, **test.kwargs)
172 stdout, _ = sigint_handler.wait(p, test.stdin)
173 duration = time.time() - start
174 except OSError as e:
175 duration = time.time() - start
176 return test.message(
177 '%s exec failure (%4.2fs)\n %s' % (test.name, duration, e))
Edward Lemurde9e3ca2019-10-24 21:13:31 +0000178 except Exception as e:
179 duration = time.time() - start
180 return test.message(
181 '%s exec failure (%4.2fs)\n%s' % (
182 test.name, duration, traceback.format_exc()))
183
Edward Lesmes8e282792018-04-03 18:50:29 -0400184 if p.returncode != 0:
185 return test.message(
186 '%s (%4.2fs) failed\n%s' % (test.name, duration, stdout))
187 if test.info:
188 return test.info('%s (%4.2fs)' % (test.name, duration))
189
190 def AddTests(self, tests, parallel=True):
191 if parallel:
192 self._tests.extend(tests)
193 else:
194 self._nonparallel_tests.extend(tests)
195
196 def RunAsync(self):
197 self._messages = []
198
199 def _WorkerFn():
200 while True:
201 test = None
202 with self._tests_lock:
203 if not self._tests:
204 break
205 test = self._tests.pop()
206 result = self.CallCommand(test)
207 if result:
208 with self._messages_lock:
209 self._messages.append(result)
210
211 def _StartDaemon():
212 t = threading.Thread(target=_WorkerFn)
213 t.daemon = True
214 t.start()
215 return t
216
217 while self._nonparallel_tests:
218 test = self._nonparallel_tests.pop()
219 result = self.CallCommand(test)
220 if result:
221 self._messages.append(result)
222
223 if self._tests:
224 threads = [_StartDaemon() for _ in range(self._pool_size)]
225 for worker in threads:
226 worker.join()
227
228 return self._messages
229
230
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000231def normpath(path):
232 '''Version of os.path.normpath that also changes backward slashes to
233 forward slashes when not running on Windows.
234 '''
235 # This is safe to always do because the Windows version of os.path.normpath
236 # will replace forward slashes with backward slashes.
237 path = path.replace(os.sep, '/')
238 return os.path.normpath(path)
239
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000240
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000241def _RightHandSideLinesImpl(affected_files):
242 """Implements RightHandSideLines for InputApi and GclChange."""
243 for af in affected_files:
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000244 lines = af.ChangedContents()
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000245 for line in lines:
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000246 yield (af, line[0], line[1])
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000247
248
dpranke@chromium.org5ac21012011-03-16 02:58:25 +0000249class PresubmitOutput(object):
250 def __init__(self, input_stream=None, output_stream=None):
251 self.input_stream = input_stream
252 self.output_stream = output_stream
253 self.reviewers = []
Daniel Cheng7227d212017-11-17 08:12:37 -0800254 self.more_cc = []
dpranke@chromium.org5ac21012011-03-16 02:58:25 +0000255 self.written_output = []
256 self.error_count = 0
257
258 def prompt_yes_no(self, prompt_string):
259 self.write(prompt_string)
260 if self.input_stream:
261 response = self.input_stream.readline().strip().lower()
262 if response not in ('y', 'yes'):
263 self.fail()
264 else:
265 self.fail()
266
267 def fail(self):
268 self.error_count += 1
269
270 def should_continue(self):
271 return not self.error_count
272
273 def write(self, s):
274 self.written_output.append(s)
275 if self.output_stream:
276 self.output_stream.write(s)
277
278 def getvalue(self):
279 return ''.join(self.written_output)
280
281
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000282# Top level object so multiprocessing can pickle
283# Public access through OutputApi object.
284class _PresubmitResult(object):
285 """Base class for result objects."""
286 fatal = False
287 should_prompt = False
288
289 def __init__(self, message, items=None, long_text=''):
290 """
291 message: A short one-line message to indicate errors.
292 items: A list of short strings to indicate where errors occurred.
293 long_text: multi-line text output, e.g. from another tool
294 """
295 self._message = message
296 self._items = items or []
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000297 self._long_text = long_text.rstrip()
298
299 def handle(self, output):
300 output.write(self._message)
301 output.write('\n')
302 for index, item in enumerate(self._items):
303 output.write(' ')
304 # Write separately in case it's unicode.
305 output.write(str(item))
306 if index < len(self._items) - 1:
307 output.write(' \\')
308 output.write('\n')
309 if self._long_text:
310 output.write('\n***************\n')
311 # Write separately in case it's unicode.
312 output.write(self._long_text)
313 output.write('\n***************\n')
314 if self.fatal:
315 output.fail()
316
Debrian Figueroadd2737e2019-06-21 23:50:13 +0000317 def json_format(self):
318 return {
319 'message': self._message,
Debrian Figueroa6095d402019-06-28 18:47:18 +0000320 'items': [str(item) for item in self._items],
Debrian Figueroadd2737e2019-06-21 23:50:13 +0000321 'long_text': self._long_text,
322 'fatal': self.fatal
323 }
324
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000325
326# Top level object so multiprocessing can pickle
327# Public access through OutputApi object.
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000328class _PresubmitError(_PresubmitResult):
329 """A hard presubmit error."""
330 fatal = True
331
332
333# Top level object so multiprocessing can pickle
334# Public access through OutputApi object.
335class _PresubmitPromptWarning(_PresubmitResult):
336 """An warning that prompts the user if they want to continue."""
337 should_prompt = True
338
339
340# Top level object so multiprocessing can pickle
341# Public access through OutputApi object.
342class _PresubmitNotifyResult(_PresubmitResult):
343 """Just print something to the screen -- but it's not even a warning."""
344 pass
345
346
347# Top level object so multiprocessing can pickle
348# Public access through OutputApi object.
349class _MailTextResult(_PresubmitResult):
350 """A warning that should be included in the review request email."""
351 def __init__(self, *args, **kwargs):
352 super(_MailTextResult, self).__init__()
353 raise NotImplementedError()
354
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000355class GerritAccessor(object):
356 """Limited Gerrit functionality for canned presubmit checks to work.
357
358 To avoid excessive Gerrit calls, caches the results.
359 """
360
361 def __init__(self, host):
362 self.host = host
363 self.cache = {}
364
365 def _FetchChangeDetail(self, issue):
366 # Separate function to be easily mocked in tests.
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +0100367 try:
368 return gerrit_util.GetChangeDetail(
369 self.host, str(issue),
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700370 ['ALL_REVISIONS', 'DETAILED_LABELS', 'ALL_COMMITS'])
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +0100371 except gerrit_util.GerritError as e:
372 if e.http_status == 404:
373 raise Exception('Either Gerrit issue %s doesn\'t exist, or '
374 'no credentials to fetch issue details' % issue)
375 raise
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000376
377 def GetChangeInfo(self, issue):
378 """Returns labels and all revisions (patchsets) for this issue.
379
380 The result is a dictionary according to Gerrit REST Api.
381 https://gerrit-review.googlesource.com/Documentation/rest-api.html
382
383 However, API isn't very clear what's inside, so see tests for example.
384 """
385 assert issue
386 cache_key = int(issue)
387 if cache_key not in self.cache:
388 self.cache[cache_key] = self._FetchChangeDetail(issue)
389 return self.cache[cache_key]
390
391 def GetChangeDescription(self, issue, patchset=None):
392 """If patchset is none, fetches current patchset."""
393 info = self.GetChangeInfo(issue)
394 # info is a reference to cache. We'll modify it here adding description to
395 # it to the right patchset, if it is not yet there.
396
397 # Find revision info for the patchset we want.
398 if patchset is not None:
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000399 for rev, rev_info in info['revisions'].items():
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000400 if str(rev_info['_number']) == str(patchset):
401 break
402 else:
403 raise Exception('patchset %s doesn\'t exist in issue %s' % (
404 patchset, issue))
405 else:
406 rev = info['current_revision']
407 rev_info = info['revisions'][rev]
408
Andrii Shyshkalov9c3a4642017-01-24 17:41:22 +0100409 return rev_info['commit']['message']
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000410
Mun Yong Jang603d01e2017-12-19 16:38:30 -0800411 def GetDestRef(self, issue):
412 ref = self.GetChangeInfo(issue)['branch']
413 if not ref.startswith('refs/'):
414 # NOTE: it is possible to create 'refs/x' branch,
415 # aka 'refs/heads/refs/x'. However, this is ill-advised.
416 ref = 'refs/heads/%s' % ref
417 return ref
418
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000419 def GetChangeOwner(self, issue):
420 return self.GetChangeInfo(issue)['owner']['email']
421
422 def GetChangeReviewers(self, issue, approving_only=True):
Aaron Gable8b478f02017-07-31 15:33:19 -0700423 changeinfo = self.GetChangeInfo(issue)
424 if approving_only:
425 labelinfo = changeinfo.get('labels', {}).get('Code-Review', {})
426 values = labelinfo.get('values', {}).keys()
427 try:
428 max_value = max(int(v) for v in values)
429 reviewers = [r for r in labelinfo.get('all', [])
430 if r.get('value', 0) == max_value]
431 except ValueError: # values is the empty list
432 reviewers = []
433 else:
434 reviewers = changeinfo.get('reviewers', {}).get('REVIEWER', [])
435 return [r.get('email') for r in reviewers]
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000436
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000437
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000438class OutputApi(object):
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000439 """An instance of OutputApi gets passed to presubmit scripts so that they
440 can output various types of results.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000441 """
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000442 PresubmitResult = _PresubmitResult
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000443 PresubmitError = _PresubmitError
444 PresubmitPromptWarning = _PresubmitPromptWarning
445 PresubmitNotifyResult = _PresubmitNotifyResult
446 MailTextResult = _MailTextResult
447
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000448 def __init__(self, is_committing):
449 self.is_committing = is_committing
Daniel Cheng7227d212017-11-17 08:12:37 -0800450 self.more_cc = []
451
452 def AppendCC(self, cc):
453 """Appends a user to cc for this change."""
454 self.more_cc.append(cc)
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000455
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000456 def PresubmitPromptOrNotify(self, *args, **kwargs):
457 """Warn the user when uploading, but only notify if committing."""
458 if self.is_committing:
459 return self.PresubmitNotifyResult(*args, **kwargs)
460 return self.PresubmitPromptWarning(*args, **kwargs)
461
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000462
463class InputApi(object):
464 """An instance of this object is passed to presubmit scripts so they can
465 know stuff about the change they're looking at.
466 """
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000467 # Method could be a function
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800468 # pylint: disable=no-self-use
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000469
maruel@chromium.org3410d912009-06-09 20:56:16 +0000470 # File extensions that are considered source files from a style guide
471 # perspective. Don't modify this list from a presubmit script!
maruel@chromium.orgc33455a2011-06-24 19:14:18 +0000472 #
473 # Files without an extension aren't included in the list. If you want to
474 # filter them as source files, add r"(^|.*?[\\\/])[^.]+$" to the white list.
475 # Note that ALL CAPS files are black listed in DEFAULT_BLACK_LIST below.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000476 DEFAULT_WHITE_LIST = (
477 # C++ and friends
maruel@chromium.orgfe1211a2011-05-28 18:54:17 +0000478 r".+\.c$", r".+\.cc$", r".+\.cpp$", r".+\.h$", r".+\.m$", r".+\.mm$",
479 r".+\.inl$", r".+\.asm$", r".+\.hxx$", r".+\.hpp$", r".+\.s$", r".+\.S$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000480 # Scripts
maruel@chromium.orgfe1211a2011-05-28 18:54:17 +0000481 r".+\.js$", r".+\.py$", r".+\.sh$", r".+\.rb$", r".+\.pl$", r".+\.pm$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000482 # Other
Sergey Ulanov166bc4c2018-04-30 17:03:38 -0700483 r".+\.java$", r".+\.mk$", r".+\.am$", r".+\.css$", r".+\.mojom$",
484 r".+\.fidl$"
maruel@chromium.org3410d912009-06-09 20:56:16 +0000485 )
486
487 # Path regexp that should be excluded from being considered containing source
488 # files. Don't modify this list from a presubmit script!
489 DEFAULT_BLACK_LIST = (
gavinp@chromium.org656326d2012-08-13 00:43:57 +0000490 r"testing_support[\\\/]google_appengine[\\\/].*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000491 r".*\bexperimental[\\\/].*",
Kent Tamura179dd1e2018-04-26 15:07:41 +0900492 # Exclude third_party/.* but NOT third_party/{WebKit,blink}
493 # (crbug.com/539768 and crbug.com/836555).
494 r".*\bthird_party[\\\/](?!(WebKit|blink)[\\\/]).*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000495 # Output directories (just in case)
496 r".*\bDebug[\\\/].*",
497 r".*\bRelease[\\\/].*",
498 r".*\bxcodebuild[\\\/].*",
thakis@chromium.orgc1c96352013-10-09 19:50:27 +0000499 r".*\bout[\\\/].*",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000500 # All caps files like README and LICENCE.
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000501 r".*\b[A-Z0-9_]{2,}$",
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000502 # SCM (can happen in dual SCM configuration). (Slightly over aggressive)
maruel@chromium.org5d0dc432011-01-03 02:40:37 +0000503 r"(|.*[\\\/])\.git[\\\/].*",
504 r"(|.*[\\\/])\.svn[\\\/].*",
maruel@chromium.org7ccb4bb2011-11-07 20:26:20 +0000505 # There is no point in processing a patch file.
506 r".+\.diff$",
507 r".+\.patch$",
maruel@chromium.org3410d912009-06-09 20:56:16 +0000508 )
509
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000510 def __init__(self, change, presubmit_path, is_committing,
Edward Lesmes8e282792018-04-03 18:50:29 -0400511 verbose, gerrit_obj, dry_run=None, thread_pool=None, parallel=False):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000512 """Builds an InputApi object.
513
514 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000515 change: A presubmit.Change object.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000516 presubmit_path: The path to the presubmit script being processed.
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000517 is_committing: True if the change is about to be committed.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000518 gerrit_obj: provides basic Gerrit codereview functionality.
519 dry_run: if true, some Checks will be skipped.
Edward Lesmes8e282792018-04-03 18:50:29 -0400520 parallel: if true, all tests reported via input_api.RunTests for all
521 PRESUBMIT files will be run in parallel.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000522 """
maruel@chromium.org9711bba2009-05-22 23:51:39 +0000523 # Version number of the presubmit_support script.
524 self.version = [int(x) for x in __version__.split('.')]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000525 self.change = change
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000526 self.is_committing = is_committing
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000527 self.gerrit = gerrit_obj
tandrii@chromium.org57bafac2016-04-28 05:09:03 +0000528 self.dry_run = dry_run
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000529
Edward Lesmes8e282792018-04-03 18:50:29 -0400530 self.parallel = parallel
531 self.thread_pool = thread_pool or ThreadPool()
532
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000533 # We expose various modules and functions as attributes of the input_api
534 # so that presubmit scripts don't have to import them.
Takeshi Yoshino07a6bea2017-08-02 02:44:06 +0900535 self.ast = ast
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000536 self.basename = os.path.basename
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000537 self.cpplint = cpplint
dcheng091b7db2016-06-16 01:27:51 -0700538 self.fnmatch = fnmatch
Yoshisato Yanagisawa04600b42019-03-15 03:03:41 +0000539 self.gclient_paths = gclient_paths
Yoshisato Yanagisawa57dd17b2019-03-22 09:10:29 +0000540 # TODO(yyanagisawa): stop exposing this when python3 become default.
541 # Since python3's tempfile has TemporaryDirectory, we do not need this.
542 self.temporary_directory = gclient_utils.temporary_directory
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000543 self.glob = glob.glob
maruel@chromium.orgfb11c7b2010-03-18 18:22:14 +0000544 self.json = json
maruel@chromium.org6fba34d2011-06-02 13:45:12 +0000545 self.logging = logging.getLogger('PRESUBMIT')
maruel@chromium.org2b5ce562011-03-31 16:15:44 +0000546 self.os_listdir = os.listdir
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000547 self.os_path = os.path
pgervais@chromium.orgbd0cace2014-10-02 23:23:46 +0000548 self.os_stat = os.stat
Yoshisato Yanagisawa406de132018-06-29 05:43:25 +0000549 self.os_walk = os.walk
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000550 self.re = re
551 self.subprocess = subprocess
552 self.tempfile = tempfile
dpranke@chromium.org0d1bdea2011-03-24 22:54:38 +0000553 self.time = time
maruel@chromium.org1487d532009-06-06 00:22:57 +0000554 self.unittest = unittest
Edward Lemurd2a5a4c2019-10-23 22:55:26 +0000555 self.urllib2 = urllib2
Edward Lemur16af3562019-10-17 22:11:33 +0000556 self.urllib_request = urllib_request
557 self.urllib_error = urllib_error
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000558
Robert Iannucci50258932018-03-19 10:30:59 -0700559 self.is_windows = sys.platform == 'win32'
560
Edward Lemurb9646622019-10-25 20:57:35 +0000561 # Set python_executable to 'vpython' in order to allow scripts in other
562 # repos (e.g. src.git) to automatically pick up that repo's .vpython file,
563 # instead of inheriting the one in depot_tools.
564 self.python_executable = 'vpython'
maruel@chromium.orgc0b22972009-06-25 16:19:14 +0000565 self.environ = os.environ
566
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000567 # InputApi.platform is the platform you're currently running on.
568 self.platform = sys.platform
569
iannucci@chromium.org0af3bb32015-06-12 20:44:35 +0000570 self.cpu_count = multiprocessing.cpu_count()
571
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000572 # The local path of the currently-being-processed presubmit script.
maruel@chromium.org3d235242009-05-15 12:40:48 +0000573 self._current_presubmit_path = os.path.dirname(presubmit_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000574
575 # We carry the canned checks so presubmit scripts can easily use them.
576 self.canned_checks = presubmit_canned_checks
577
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +0100578 # Temporary files we must manually remove at the end of a run.
579 self._named_temporary_files = []
Jochen Eisinger72606f82017-04-04 10:44:18 +0200580
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000581 # TODO(dpranke): figure out a list of all approved owners for a repo
582 # in order to be able to handle wildcard OWNERS files?
583 self.owners_db = owners.Database(change.RepositoryRoot(),
Edward Lemurd2a5a4c2019-10-23 22:55:26 +0000584 fopen=file, os_path=self.os_path)
Jochen Eisinger76f5fc62017-04-07 16:27:46 +0200585 self.owners_finder = owners_finder.OwnersFinder
maruel@chromium.org899e1c12011-04-07 17:03:18 +0000586 self.verbose = verbose
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000587 self.Command = CommandData
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000588
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000589 # Replace <hash_map> and <hash_set> as headers that need to be included
danakj@chromium.org18278522013-06-11 22:42:32 +0000590 # with "base/containers/hash_tables.h" instead.
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000591 # Access to a protected member _XX of a client class
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800592 # pylint: disable=protected-access
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000593 self.cpplint._re_pattern_templates = [
danakj@chromium.org18278522013-06-11 22:42:32 +0000594 (a, b, 'base/containers/hash_tables.h')
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000595 if header in ('<hash_map>', '<hash_set>') else (a, b, header)
596 for (a, b, header) in cpplint._re_pattern_templates
597 ]
598
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000599 def PresubmitLocalPath(self):
600 """Returns the local path of the presubmit script currently being run.
601
602 This is useful if you don't want to hard-code absolute paths in the
603 presubmit script. For example, It can be used to find another file
604 relative to the PRESUBMIT.py script, so the whole tree can be branched and
605 the presubmit script still works, without editing its content.
606 """
maruel@chromium.org3d235242009-05-15 12:40:48 +0000607 return self._current_presubmit_path
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000608
agable0b65e732016-11-22 09:25:46 -0800609 def AffectedFiles(self, include_deletes=True, file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000610 """Same as input_api.change.AffectedFiles() except only lists files
611 (and optionally directories) in the same directory as the current presubmit
612 script, or subdirectories thereof.
613 """
maruel@chromium.org3d235242009-05-15 12:40:48 +0000614 dir_with_slash = normpath("%s/" % self.PresubmitLocalPath())
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000615 if len(dir_with_slash) == 1:
616 dir_with_slash = ''
sail@chromium.org5538e022011-05-12 17:53:16 +0000617
Edward Lemurd2a5a4c2019-10-23 22:55:26 +0000618 return filter(
maruel@chromium.org4661e0c2009-06-04 00:45:26 +0000619 lambda x: normpath(x.AbsoluteLocalPath()).startswith(dir_with_slash),
Edward Lemurd2a5a4c2019-10-23 22:55:26 +0000620 self.change.AffectedFiles(include_deletes, file_filter))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000621
agable0b65e732016-11-22 09:25:46 -0800622 def LocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000623 """Returns local paths of input_api.AffectedFiles()."""
agable0b65e732016-11-22 09:25:46 -0800624 paths = [af.LocalPath() for af in self.AffectedFiles()]
pgervais@chromium.org2f64f782014-04-25 00:12:33 +0000625 logging.debug("LocalPaths: %s", paths)
626 return paths
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000627
agable0b65e732016-11-22 09:25:46 -0800628 def AbsoluteLocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000629 """Returns absolute local paths of input_api.AffectedFiles()."""
agable0b65e732016-11-22 09:25:46 -0800630 return [af.AbsoluteLocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000631
John Budorick16162372018-04-18 10:39:53 -0700632 def AffectedTestableFiles(self, include_deletes=None, **kwargs):
agable0b65e732016-11-22 09:25:46 -0800633 """Same as input_api.change.AffectedTestableFiles() except only lists files
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000634 in the same directory as the current presubmit script, or subdirectories
635 thereof.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000636 """
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000637 if include_deletes is not None:
agable0b65e732016-11-22 09:25:46 -0800638 warn("AffectedTestableFiles(include_deletes=%s)"
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000639 " is deprecated and ignored" % str(include_deletes),
640 category=DeprecationWarning,
641 stacklevel=2)
Edward Lemurd2a5a4c2019-10-23 22:55:26 +0000642 return filter(lambda x: x.IsTestableFile(),
643 self.AffectedFiles(include_deletes=False, **kwargs))
agable0b65e732016-11-22 09:25:46 -0800644
645 def AffectedTextFiles(self, include_deletes=None):
646 """An alias to AffectedTestableFiles for backwards compatibility."""
647 return self.AffectedTestableFiles(include_deletes=include_deletes)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000648
maruel@chromium.org3410d912009-06-09 20:56:16 +0000649 def FilterSourceFile(self, affected_file, white_list=None, black_list=None):
650 """Filters out files that aren't considered "source file".
651
652 If white_list or black_list is None, InputApi.DEFAULT_WHITE_LIST
653 and InputApi.DEFAULT_BLACK_LIST is used respectively.
654
655 The lists will be compiled as regular expression and
656 AffectedFile.LocalPath() needs to pass both list.
657
658 Note: Copy-paste this function to suit your needs or use a lambda function.
659 """
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000660 def Find(affected_file, items):
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000661 local_path = affected_file.LocalPath()
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000662 for item in items:
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000663 if self.re.match(item, local_path):
maruel@chromium.org3410d912009-06-09 20:56:16 +0000664 return True
665 return False
666 return (Find(affected_file, white_list or self.DEFAULT_WHITE_LIST) and
667 not Find(affected_file, black_list or self.DEFAULT_BLACK_LIST))
668
669 def AffectedSourceFiles(self, source_file):
agable0b65e732016-11-22 09:25:46 -0800670 """Filter the list of AffectedTestableFiles by the function source_file.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000671
672 If source_file is None, InputApi.FilterSourceFile() is used.
673 """
674 if not source_file:
675 source_file = self.FilterSourceFile
Edward Lemurd2a5a4c2019-10-23 22:55:26 +0000676 return filter(source_file, self.AffectedTestableFiles())
maruel@chromium.org3410d912009-06-09 20:56:16 +0000677
678 def RightHandSideLines(self, source_file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000679 """An iterator over all text lines in "new" version of changed files.
680
681 Only lists lines from new or modified text files in the change that are
682 contained by the directory of the currently executing presubmit script.
683
684 This is useful for doing line-by-line regex checks, like checking for
685 trailing whitespace.
686
687 Yields:
688 a 3 tuple:
689 the AffectedFile instance of the current file;
690 integer line number (1-based); and
691 the contents of the line as a string.
maruel@chromium.org1487d532009-06-06 00:22:57 +0000692
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000693 Note: The carriage return (LF or CR) is stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000694 """
maruel@chromium.org3410d912009-06-09 20:56:16 +0000695 files = self.AffectedSourceFiles(source_file_filter)
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000696 return _RightHandSideLinesImpl(files)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000697
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000698 def ReadFile(self, file_item, mode='r'):
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000699 """Reads an arbitrary file.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000700
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000701 Deny reading anything outside the repository.
702 """
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000703 if isinstance(file_item, AffectedFile):
704 file_item = file_item.AbsoluteLocalPath()
705 if not file_item.startswith(self.change.RepositoryRoot()):
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000706 raise IOError('Access outside the repository root is denied.')
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000707 return gclient_utils.FileRead(file_item, mode)
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000708
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +0100709 def CreateTemporaryFile(self, **kwargs):
710 """Returns a named temporary file that must be removed with a call to
711 RemoveTemporaryFiles().
712
713 All keyword arguments are forwarded to tempfile.NamedTemporaryFile(),
714 except for |delete|, which is always set to False.
715
716 Presubmit checks that need to create a temporary file and pass it for
717 reading should use this function instead of NamedTemporaryFile(), as
718 Windows fails to open a file that is already open for writing.
719
720 with input_api.CreateTemporaryFile() as f:
721 f.write('xyz')
722 f.close()
723 input_api.subprocess.check_output(['script-that', '--reads-from',
724 f.name])
725
726
727 Note that callers of CreateTemporaryFile() should not worry about removing
728 any temporary file; this is done transparently by the presubmit handling
729 code.
730 """
731 if 'delete' in kwargs:
732 # Prevent users from passing |delete|; we take care of file deletion
733 # ourselves and this prevents unintuitive error messages when we pass
734 # delete=False and 'delete' is also in kwargs.
735 raise TypeError('CreateTemporaryFile() does not take a "delete" '
736 'argument, file deletion is handled automatically by '
737 'the same presubmit_support code that creates InputApi '
738 'objects.')
739 temp_file = self.tempfile.NamedTemporaryFile(delete=False, **kwargs)
740 self._named_temporary_files.append(temp_file.name)
741 return temp_file
742
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000743 @property
744 def tbr(self):
745 """Returns if a change is TBR'ed."""
Jeremy Romandce22502017-06-20 15:37:29 -0400746 return 'TBR' in self.change.tags or self.change.TBRsFromDescription()
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000747
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +0000748 def RunTests(self, tests_mix, parallel=True):
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000749 tests = []
750 msgs = []
751 for t in tests_mix:
Edward Lesmes8e282792018-04-03 18:50:29 -0400752 if isinstance(t, OutputApi.PresubmitResult) and t:
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000753 msgs.append(t)
754 else:
755 assert issubclass(t.message, _PresubmitResult)
756 tests.append(t)
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +0000757 if self.verbose:
758 t.info = _PresubmitNotifyResult
Edward Lemur1037c742018-05-01 18:56:04 -0400759 if not t.kwargs.get('cwd'):
760 t.kwargs['cwd'] = self.PresubmitLocalPath()
Edward Lesmes8e282792018-04-03 18:50:29 -0400761 self.thread_pool.AddTests(tests, parallel)
Edward Lemur21000eb2019-05-24 23:25:58 +0000762 # When self.parallel is True (i.e. --parallel is passed as an option)
763 # RunTests doesn't actually run tests. It adds them to a ThreadPool that
764 # will run all tests once all PRESUBMIT files are processed.
765 # Otherwise, it will run them and return the results.
766 if not self.parallel:
Edward Lesmes8e282792018-04-03 18:50:29 -0400767 msgs.extend(self.thread_pool.RunAsync())
768 return msgs
scottmg86099d72016-09-01 09:16:51 -0700769
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000770
nick@chromium.orgff526192013-06-10 19:30:26 +0000771class _DiffCache(object):
772 """Caches diffs retrieved from a particular SCM."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000773 def __init__(self, upstream=None):
774 """Stores the upstream revision against which all diffs will be computed."""
775 self._upstream = upstream
nick@chromium.orgff526192013-06-10 19:30:26 +0000776
777 def GetDiff(self, path, local_root):
778 """Get the diff for a particular path."""
779 raise NotImplementedError()
780
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700781 def GetOldContents(self, path, local_root):
782 """Get the old version for a particular path."""
783 raise NotImplementedError()
784
nick@chromium.orgff526192013-06-10 19:30:26 +0000785
nick@chromium.orgff526192013-06-10 19:30:26 +0000786class _GitDiffCache(_DiffCache):
787 """DiffCache implementation for git; gets all file diffs at once."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000788 def __init__(self, upstream):
789 super(_GitDiffCache, self).__init__(upstream=upstream)
nick@chromium.orgff526192013-06-10 19:30:26 +0000790 self._diffs_by_file = None
791
792 def GetDiff(self, path, local_root):
793 if not self._diffs_by_file:
794 # Compute a single diff for all files and parse the output; should
795 # with git this is much faster than computing one diff for each file.
796 diffs = {}
797
798 # Don't specify any filenames below, because there are command line length
799 # limits on some platforms and GenerateDiff would fail.
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000800 unified_diff = scm.GIT.GenerateDiff(local_root, files=[], full_move=True,
801 branch=self._upstream)
nick@chromium.orgff526192013-06-10 19:30:26 +0000802
803 # This regex matches the path twice, separated by a space. Note that
804 # filename itself may contain spaces.
805 file_marker = re.compile('^diff --git (?P<filename>.*) (?P=filename)$')
806 current_diff = []
807 keep_line_endings = True
808 for x in unified_diff.splitlines(keep_line_endings):
809 match = file_marker.match(x)
810 if match:
811 # Marks the start of a new per-file section.
812 diffs[match.group('filename')] = current_diff = [x]
813 elif x.startswith('diff --git'):
814 raise PresubmitFailure('Unexpected diff line: %s' % x)
815 else:
816 current_diff.append(x)
817
818 self._diffs_by_file = dict(
819 (normpath(path), ''.join(diff)) for path, diff in diffs.items())
820
821 if path not in self._diffs_by_file:
822 raise PresubmitFailure(
823 'Unified diff did not contain entry for file %s' % path)
824
825 return self._diffs_by_file[path]
826
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700827 def GetOldContents(self, path, local_root):
828 return scm.GIT.GetOldContents(local_root, path, branch=self._upstream)
829
nick@chromium.orgff526192013-06-10 19:30:26 +0000830
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000831class AffectedFile(object):
832 """Representation of a file in a change."""
nick@chromium.orgff526192013-06-10 19:30:26 +0000833
834 DIFF_CACHE = _DiffCache
835
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000836 # Method could be a function
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800837 # pylint: disable=no-self-use
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000838 def __init__(self, path, action, repository_root, diff_cache):
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000839 self._path = path
840 self._action = action
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000841 self._local_root = repository_root
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000842 self._is_directory = None
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000843 self._cached_changed_contents = None
844 self._cached_new_contents = None
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000845 self._diff_cache = diff_cache
tobiasjs2836bcf2016-08-16 04:08:16 -0700846 logging.debug('%s(%s)', self.__class__.__name__, self._path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000847
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000848 def LocalPath(self):
849 """Returns the path of this file on the local disk relative to client root.
Andrew Grieve92b8b992017-11-02 09:42:24 -0400850
851 This should be used for error messages but not for accessing files,
852 because presubmit checks are run with CWD=PresubmitLocalPath() (which is
853 often != client root).
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000854 """
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000855 return normpath(self._path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000856
857 def AbsoluteLocalPath(self):
858 """Returns the absolute path of this file on the local disk.
859 """
chase@chromium.org8e416c82009-10-06 04:30:44 +0000860 return os.path.abspath(os.path.join(self._local_root, self.LocalPath()))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000861
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000862 def Action(self):
863 """Returns the action on this opened file, e.g. A, M, D, etc."""
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000864 return self._action
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000865
agable0b65e732016-11-22 09:25:46 -0800866 def IsTestableFile(self):
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000867 """Returns True if the file is a text file and not a binary file.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000868
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000869 Deleted files are not text file."""
maruel@chromium.org1e08c002009-05-28 19:09:33 +0000870 raise NotImplementedError() # Implement when needed
871
agable0b65e732016-11-22 09:25:46 -0800872 def IsTextFile(self):
873 """An alias to IsTestableFile for backwards compatibility."""
874 return self.IsTestableFile()
875
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700876 def OldContents(self):
877 """Returns an iterator over the lines in the old version of file.
878
Daniel Cheng2da34fe2017-03-21 20:42:12 -0700879 The old version is the file before any modifications in the user's
880 workspace, i.e. the "left hand side".
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700881
882 Contents will be empty if the file is a directory or does not exist.
883 Note: The carriage returns (LF or CR) are stripped off.
884 """
885 return self._diff_cache.GetOldContents(self.LocalPath(),
886 self._local_root).splitlines()
887
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000888 def NewContents(self):
889 """Returns an iterator over the lines in the new version of file.
890
891 The new version is the file in the user's workspace, i.e. the "right hand
892 side".
893
894 Contents will be empty if the file is a directory or does not exist.
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000895 Note: The carriage returns (LF or CR) are stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000896 """
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000897 if self._cached_new_contents is None:
898 self._cached_new_contents = []
agable0b65e732016-11-22 09:25:46 -0800899 try:
900 self._cached_new_contents = gclient_utils.FileRead(
901 self.AbsoluteLocalPath(), 'rU').splitlines()
902 except IOError:
903 pass # File not found? That's fine; maybe it was deleted.
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000904 return self._cached_new_contents[:]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000905
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000906 def ChangedContents(self):
907 """Returns a list of tuples (line number, line text) of all new lines.
908
909 This relies on the scm diff output describing each changed code section
910 with a line of the form
911
912 ^@@ <old line num>,<old size> <new line num>,<new size> @@$
913 """
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000914 if self._cached_changed_contents is not None:
915 return self._cached_changed_contents[:]
916 self._cached_changed_contents = []
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000917 line_num = 0
918
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000919 for line in self.GenerateScmDiff().splitlines():
920 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
921 if m:
922 line_num = int(m.groups(1)[0])
923 continue
924 if line.startswith('+') and not line.startswith('++'):
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000925 self._cached_changed_contents.append((line_num, line[1:]))
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000926 if not line.startswith('-'):
927 line_num += 1
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000928 return self._cached_changed_contents[:]
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000929
maruel@chromium.org5de13972009-06-10 18:16:06 +0000930 def __str__(self):
931 return self.LocalPath()
932
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000933 def GenerateScmDiff(self):
nick@chromium.orgff526192013-06-10 19:30:26 +0000934 return self._diff_cache.GetDiff(self.LocalPath(), self._local_root)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000935
maruel@chromium.org58407af2011-04-12 23:15:57 +0000936
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000937class GitAffectedFile(AffectedFile):
938 """Representation of a file in a change out of a git checkout."""
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000939 # Method 'NNN' is abstract in class 'NNN' but is not overridden
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800940 # pylint: disable=abstract-method
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000941
nick@chromium.orgff526192013-06-10 19:30:26 +0000942 DIFF_CACHE = _GitDiffCache
943
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000944 def __init__(self, *args, **kwargs):
945 AffectedFile.__init__(self, *args, **kwargs)
946 self._server_path = None
agable0b65e732016-11-22 09:25:46 -0800947 self._is_testable_file = None
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000948
agable0b65e732016-11-22 09:25:46 -0800949 def IsTestableFile(self):
950 if self._is_testable_file is None:
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000951 if self.Action() == 'D':
agable0b65e732016-11-22 09:25:46 -0800952 # A deleted file is not testable.
953 self._is_testable_file = False
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000954 else:
agable0b65e732016-11-22 09:25:46 -0800955 self._is_testable_file = os.path.isfile(self.AbsoluteLocalPath())
956 return self._is_testable_file
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000957
maruel@chromium.orgc1938752011-04-12 23:11:13 +0000958
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000959class Change(object):
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000960 """Describe a change.
961
962 Used directly by the presubmit scripts to query the current change being
963 tested.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000964
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000965 Instance members:
nick@chromium.orgff526192013-06-10 19:30:26 +0000966 tags: Dictionary of KEY=VALUE pairs found in the change description.
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000967 self.KEY: equivalent to tags['KEY']
968 """
969
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000970 _AFFECTED_FILES = AffectedFile
971
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000972 # Matches key/value (or "tag") lines in changelist descriptions.
maruel@chromium.org428342a2011-11-10 15:46:33 +0000973 TAG_LINE_RE = re.compile(
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +0000974 '^[ \t]*(?P<key>[A-Z][A-Z_0-9]*)[ \t]*=[ \t]*(?P<value>.*?)[ \t]*$')
maruel@chromium.orgc1938752011-04-12 23:11:13 +0000975 scm = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000976
maruel@chromium.org58407af2011-04-12 23:15:57 +0000977 def __init__(
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000978 self, name, description, local_root, files, issue, patchset, author,
979 upstream=None):
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000980 if files is None:
981 files = []
982 self._name = name
chase@chromium.org8e416c82009-10-06 04:30:44 +0000983 # Convert root into an absolute path.
984 self._local_root = os.path.abspath(local_root)
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000985 self._upstream = upstream
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000986 self.issue = issue
987 self.patchset = patchset
maruel@chromium.org58407af2011-04-12 23:15:57 +0000988 self.author_email = author
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000989
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000990 self._full_description = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000991 self.tags = {}
isherman@chromium.orgb5cded62014-03-25 17:47:57 +0000992 self._description_without_tags = ''
993 self.SetDescriptionText(description)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000994
maruel@chromium.orge085d812011-10-10 19:49:15 +0000995 assert all(
996 (isinstance(f, (list, tuple)) and len(f) == 2) for f in files), files
997
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000998 diff_cache = self._AFFECTED_FILES.DIFF_CACHE(self._upstream)
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +0000999 self._affected_files = [
nick@chromium.orgff526192013-06-10 19:30:26 +00001000 self._AFFECTED_FILES(path, action.strip(), self._local_root, diff_cache)
1001 for action, path in files
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +00001002 ]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001003
maruel@chromium.org92022ec2009-06-11 01:59:28 +00001004 def Name(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001005 """Returns the change name."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001006 return self._name
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001007
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001008 def DescriptionText(self):
1009 """Returns the user-entered changelist description, minus tags.
1010
1011 Any line in the user-provided description starting with e.g. "FOO="
1012 (whitespace permitted before and around) is considered a tag line. Such
1013 lines are stripped out of the description this function returns.
1014 """
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001015 return self._description_without_tags
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001016
1017 def FullDescriptionText(self):
1018 """Returns the complete changelist description including tags."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001019 return self._full_description
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001020
isherman@chromium.orgb5cded62014-03-25 17:47:57 +00001021 def SetDescriptionText(self, description):
1022 """Sets the full description text (including tags) to |description|.
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001023
isherman@chromium.orgb5cded62014-03-25 17:47:57 +00001024 Also updates the list of tags."""
1025 self._full_description = description
1026
1027 # From the description text, build up a dictionary of key/value pairs
1028 # plus the description minus all key/value or "tag" lines.
1029 description_without_tags = []
1030 self.tags = {}
1031 for line in self._full_description.splitlines():
1032 m = self.TAG_LINE_RE.match(line)
1033 if m:
1034 self.tags[m.group('key')] = m.group('value')
1035 else:
1036 description_without_tags.append(line)
1037
1038 # Change back to text and remove whitespace at end.
1039 self._description_without_tags = (
1040 '\n'.join(description_without_tags).rstrip())
1041
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001042 def RepositoryRoot(self):
maruel@chromium.org92022ec2009-06-11 01:59:28 +00001043 """Returns the repository (checkout) root directory for this change,
1044 as an absolute path.
1045 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001046 return self._local_root
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001047
1048 def __getattr__(self, attr):
maruel@chromium.org92022ec2009-06-11 01:59:28 +00001049 """Return tags directly as attributes on the object."""
1050 if not re.match(r"^[A-Z_]*$", attr):
1051 raise AttributeError(self, attr)
maruel@chromium.orge1a524f2009-05-27 14:43:46 +00001052 return self.tags.get(attr)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001053
Aaron Gablefc03e672017-05-15 14:09:42 -07001054 def BugsFromDescription(self):
1055 """Returns all bugs referenced in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -07001056 tags = [b.strip() for b in self.tags.get('BUG', '').split(',') if b.strip()]
Caleb Rouleauc0546b92019-02-22 06:12:57 +00001057 footers = []
Dan Beam62954042019-10-03 21:20:33 +00001058 parsed = git_footers.parse_footers(self._full_description)
1059 unsplit_footers = parsed.get('Bug', []) + parsed.get('Fixed', [])
Caleb Rouleauc0546b92019-02-22 06:12:57 +00001060 for unsplit_footer in unsplit_footers:
1061 footers += [b.strip() for b in unsplit_footer.split(',')]
Aaron Gable12ef5012017-05-15 14:29:00 -07001062 return sorted(set(tags + footers))
Aaron Gablefc03e672017-05-15 14:09:42 -07001063
1064 def ReviewersFromDescription(self):
1065 """Returns all reviewers listed in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -07001066 # We don't support a "R:" git-footer for reviewers; that is in metadata.
1067 tags = [r.strip() for r in self.tags.get('R', '').split(',') if r.strip()]
1068 return sorted(set(tags))
Aaron Gablefc03e672017-05-15 14:09:42 -07001069
1070 def TBRsFromDescription(self):
1071 """Returns all TBR reviewers listed in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -07001072 tags = [r.strip() for r in self.tags.get('TBR', '').split(',') if r.strip()]
1073 # TODO(agable): Remove support for 'Tbr:' when TBRs are programmatically
1074 # determined by self-CR+1s.
1075 footers = git_footers.parse_footers(self._full_description).get('Tbr', [])
1076 return sorted(set(tags + footers))
Aaron Gablefc03e672017-05-15 14:09:42 -07001077
1078 # TODO(agable): Delete these once we're sure they're unused.
1079 @property
1080 def BUG(self):
1081 return ','.join(self.BugsFromDescription())
1082 @property
1083 def R(self):
1084 return ','.join(self.ReviewersFromDescription())
1085 @property
1086 def TBR(self):
1087 return ','.join(self.TBRsFromDescription())
1088
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001089 def AllFiles(self, root=None):
1090 """List all files under source control in the repo."""
1091 raise NotImplementedError()
1092
agable0b65e732016-11-22 09:25:46 -08001093 def AffectedFiles(self, include_deletes=True, file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001094 """Returns a list of AffectedFile instances for all files in the change.
1095
1096 Args:
1097 include_deletes: If false, deleted files will be filtered out.
sail@chromium.org5538e022011-05-12 17:53:16 +00001098 file_filter: An additional filter to apply.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001099
1100 Returns:
1101 [AffectedFile(path, action), AffectedFile(path, action)]
1102 """
Edward Lemurd2a5a4c2019-10-23 22:55:26 +00001103 affected = filter(file_filter, self._affected_files)
sail@chromium.org5538e022011-05-12 17:53:16 +00001104
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001105 if include_deletes:
1106 return affected
Edward Lemurd2a5a4c2019-10-23 22:55:26 +00001107 return filter(lambda x: x.Action() != 'D', affected)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001108
John Budorick16162372018-04-18 10:39:53 -07001109 def AffectedTestableFiles(self, include_deletes=None, **kwargs):
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +00001110 """Return a list of the existing text files in a change."""
1111 if include_deletes is not None:
agable0b65e732016-11-22 09:25:46 -08001112 warn("AffectedTeestableFiles(include_deletes=%s)"
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +00001113 " is deprecated and ignored" % str(include_deletes),
1114 category=DeprecationWarning,
1115 stacklevel=2)
Edward Lemurd2a5a4c2019-10-23 22:55:26 +00001116 return filter(lambda x: x.IsTestableFile(),
1117 self.AffectedFiles(include_deletes=False, **kwargs))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001118
agable0b65e732016-11-22 09:25:46 -08001119 def AffectedTextFiles(self, include_deletes=None):
1120 """An alias to AffectedTestableFiles for backwards compatibility."""
1121 return self.AffectedTestableFiles(include_deletes=include_deletes)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001122
agable0b65e732016-11-22 09:25:46 -08001123 def LocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001124 """Convenience function."""
agable0b65e732016-11-22 09:25:46 -08001125 return [af.LocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001126
agable0b65e732016-11-22 09:25:46 -08001127 def AbsoluteLocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001128 """Convenience function."""
agable0b65e732016-11-22 09:25:46 -08001129 return [af.AbsoluteLocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001130
1131 def RightHandSideLines(self):
1132 """An iterator over all text lines in "new" version of changed files.
1133
1134 Lists lines from new or modified text files in the change.
1135
1136 This is useful for doing line-by-line regex checks, like checking for
1137 trailing whitespace.
1138
1139 Yields:
1140 a 3 tuple:
1141 the AffectedFile instance of the current file;
1142 integer line number (1-based); and
1143 the contents of the line as a string.
1144 """
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +00001145 return _RightHandSideLinesImpl(
1146 x for x in self.AffectedFiles(include_deletes=False)
agable0b65e732016-11-22 09:25:46 -08001147 if x.IsTestableFile())
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001148
Jochen Eisingerd0573ec2017-04-13 10:55:06 +02001149 def OriginalOwnersFiles(self):
1150 """A map from path names of affected OWNERS files to their old content."""
1151 def owners_file_filter(f):
1152 return 'OWNERS' in os.path.split(f.LocalPath())[1]
1153 files = self.AffectedFiles(file_filter=owners_file_filter)
1154 return dict([(f.LocalPath(), f.OldContents()) for f in files])
1155
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001156
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001157class GitChange(Change):
1158 _AFFECTED_FILES = GitAffectedFile
maruel@chromium.orgc1938752011-04-12 23:11:13 +00001159 scm = 'git'
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +00001160
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001161 def AllFiles(self, root=None):
1162 """List all files under source control in the repo."""
1163 root = root or self.RepositoryRoot()
1164 return subprocess.check_output(
Aaron Gable7817f022017-12-12 09:43:17 -08001165 ['git', '-c', 'core.quotePath=false', 'ls-files', '--', '.'],
1166 cwd=root).splitlines()
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001167
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001168
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001169def ListRelevantPresubmitFiles(files, root):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001170 """Finds all presubmit files that apply to a given set of source files.
1171
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001172 If inherit-review-settings-ok is present right under root, looks for
1173 PRESUBMIT.py in directories enclosing root.
1174
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001175 Args:
1176 files: An iterable container containing file paths.
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001177 root: Path where to stop searching.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001178
1179 Return:
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001180 List of absolute paths of the existing PRESUBMIT.py scripts.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001181 """
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001182 files = [normpath(os.path.join(root, f)) for f in files]
1183
1184 # List all the individual directories containing files.
1185 directories = set([os.path.dirname(f) for f in files])
1186
1187 # Ignore root if inherit-review-settings-ok is present.
1188 if os.path.isfile(os.path.join(root, 'inherit-review-settings-ok')):
1189 root = None
1190
1191 # Collect all unique directories that may contain PRESUBMIT.py.
1192 candidates = set()
1193 for directory in directories:
1194 while True:
1195 if directory in candidates:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001196 break
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001197 candidates.add(directory)
1198 if directory == root:
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001199 break
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001200 parent_dir = os.path.dirname(directory)
1201 if parent_dir == directory:
1202 # We hit the system root directory.
1203 break
1204 directory = parent_dir
1205
1206 # Look for PRESUBMIT.py in all candidate directories.
1207 results = []
1208 for directory in sorted(list(candidates)):
tobiasjsff061c02016-08-17 03:23:57 -07001209 try:
1210 for f in os.listdir(directory):
1211 p = os.path.join(directory, f)
1212 if os.path.isfile(p) and re.match(
1213 r'PRESUBMIT.*\.py$', f) and not f.startswith('PRESUBMIT_test'):
1214 results.append(p)
1215 except OSError:
1216 pass
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001217
tobiasjs2836bcf2016-08-16 04:08:16 -07001218 logging.debug('Presubmit files: %s', ','.join(results))
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001219 return results
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001220
1221
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001222class GetTryMastersExecuter(object):
1223 @staticmethod
1224 def ExecPresubmitScript(script_text, presubmit_path, project, change):
1225 """Executes GetPreferredTryMasters() from a single presubmit script.
1226
1227 Args:
1228 script_text: The text of the presubmit script.
1229 presubmit_path: Project script to run.
1230 project: Project name to pass to presubmit script for bot selection.
1231
1232 Return:
1233 A map of try masters to map of builders to set of tests.
1234 """
1235 context = {}
1236 try:
Raul Tambre09e64b42019-05-14 01:57:22 +00001237 exec(compile(script_text, 'PRESUBMIT.py', 'exec', dont_inherit=True),
1238 context)
Raul Tambre7c938462019-05-24 16:35:35 +00001239 except Exception as e:
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001240 raise PresubmitFailure('"%s" had an exception.\n%s'
1241 % (presubmit_path, e))
1242
1243 function_name = 'GetPreferredTryMasters'
1244 if function_name not in context:
1245 return {}
1246 get_preferred_try_masters = context[function_name]
1247 if not len(inspect.getargspec(get_preferred_try_masters)[0]) == 2:
1248 raise PresubmitFailure(
1249 'Expected function "GetPreferredTryMasters" to take two arguments.')
1250 return get_preferred_try_masters(project, change)
1251
1252
rmistry@google.com5626a922015-02-26 14:03:30 +00001253class GetPostUploadExecuter(object):
1254 @staticmethod
1255 def ExecPresubmitScript(script_text, presubmit_path, cl, change):
1256 """Executes PostUploadHook() from a single presubmit script.
1257
1258 Args:
1259 script_text: The text of the presubmit script.
1260 presubmit_path: Project script to run.
1261 cl: The Changelist object.
1262 change: The Change object.
1263
1264 Return:
1265 A list of results objects.
1266 """
1267 context = {}
1268 try:
Raul Tambre09e64b42019-05-14 01:57:22 +00001269 exec(compile(script_text, 'PRESUBMIT.py', 'exec', dont_inherit=True),
1270 context)
Raul Tambre7c938462019-05-24 16:35:35 +00001271 except Exception as e:
rmistry@google.com5626a922015-02-26 14:03:30 +00001272 raise PresubmitFailure('"%s" had an exception.\n%s'
1273 % (presubmit_path, e))
1274
1275 function_name = 'PostUploadHook'
1276 if function_name not in context:
1277 return {}
1278 post_upload_hook = context[function_name]
1279 if not len(inspect.getargspec(post_upload_hook)[0]) == 3:
1280 raise PresubmitFailure(
1281 'Expected function "PostUploadHook" to take three arguments.')
1282 return post_upload_hook(cl, change, OutputApi(False))
1283
1284
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001285def _MergeMasters(masters1, masters2):
1286 """Merges two master maps. Merges also the tests of each builder."""
1287 result = {}
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00001288 for (master, builders) in itertools.chain(masters1.items(),
1289 masters2.items()):
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001290 new_builders = result.setdefault(master, {})
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00001291 for (builder, tests) in builders.items():
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001292 new_builders.setdefault(builder, set([])).update(tests)
1293 return result
1294
1295
1296def DoGetTryMasters(change,
1297 changed_files,
1298 repository_root,
1299 default_presubmit,
1300 project,
1301 verbose,
1302 output_stream):
1303 """Get the list of try masters from the presubmit scripts.
1304
1305 Args:
1306 changed_files: List of modified files.
1307 repository_root: The repository root.
1308 default_presubmit: A default presubmit script to execute in any case.
1309 project: Optional name of a project used in selecting trybots.
1310 verbose: Prints debug info.
1311 output_stream: A stream to write debug output to.
1312
1313 Return:
1314 Map of try masters to map of builders to set of tests.
1315 """
1316 presubmit_files = ListRelevantPresubmitFiles(changed_files, repository_root)
1317 if not presubmit_files and verbose:
1318 output_stream.write("Warning, no PRESUBMIT.py found.\n")
1319 results = {}
1320 executer = GetTryMastersExecuter()
1321
1322 if default_presubmit:
1323 if verbose:
1324 output_stream.write("Running default presubmit script.\n")
1325 fake_path = os.path.join(repository_root, 'PRESUBMIT.py')
1326 results = _MergeMasters(results, executer.ExecPresubmitScript(
1327 default_presubmit, fake_path, project, change))
1328 for filename in presubmit_files:
1329 filename = os.path.abspath(filename)
1330 if verbose:
1331 output_stream.write("Running %s\n" % filename)
1332 # Accept CRLF presubmit script.
1333 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1334 results = _MergeMasters(results, executer.ExecPresubmitScript(
1335 presubmit_script, filename, project, change))
1336
1337 # Make sets to lists again for later JSON serialization.
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00001338 for builders in results.values():
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001339 for builder in builders:
1340 builders[builder] = list(builders[builder])
1341
1342 if results and verbose:
1343 output_stream.write('%s\n' % str(results))
1344 return results
1345
1346
rmistry@google.com5626a922015-02-26 14:03:30 +00001347def DoPostUploadExecuter(change,
1348 cl,
1349 repository_root,
1350 verbose,
1351 output_stream):
1352 """Execute the post upload hook.
1353
1354 Args:
1355 change: The Change object.
1356 cl: The Changelist object.
1357 repository_root: The repository root.
1358 verbose: Prints debug info.
1359 output_stream: A stream to write debug output to.
1360 """
1361 presubmit_files = ListRelevantPresubmitFiles(
1362 change.LocalPaths(), repository_root)
1363 if not presubmit_files and verbose:
1364 output_stream.write("Warning, no PRESUBMIT.py found.\n")
1365 results = []
1366 executer = GetPostUploadExecuter()
1367 # The root presubmit file should be executed after the ones in subdirectories.
1368 # i.e. the specific post upload hooks should run before the general ones.
1369 # Thus, reverse the order provided by ListRelevantPresubmitFiles.
1370 presubmit_files.reverse()
1371
1372 for filename in presubmit_files:
1373 filename = os.path.abspath(filename)
1374 if verbose:
1375 output_stream.write("Running %s\n" % filename)
1376 # Accept CRLF presubmit script.
1377 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1378 results.extend(executer.ExecPresubmitScript(
1379 presubmit_script, filename, cl, change))
1380 output_stream.write('\n')
1381 if results:
1382 output_stream.write('** Post Upload Hook Messages **\n')
1383 for result in results:
1384 result.handle(output_stream)
1385 output_stream.write('\n')
1386
1387 return results
1388
1389
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001390class PresubmitExecuter(object):
Aaron Gable668c1d82018-04-03 10:19:16 -07001391 def __init__(self, change, committing, verbose,
Edward Lesmes8e282792018-04-03 18:50:29 -04001392 gerrit_obj, dry_run=None, thread_pool=None, parallel=False):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001393 """
1394 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001395 change: The Change object.
agable92bec4f2016-08-24 09:27:27 -07001396 committing: True if 'git cl land' is running, False if 'git cl upload' is.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001397 gerrit_obj: provides basic Gerrit codereview functionality.
1398 dry_run: if true, some Checks will be skipped.
Edward Lesmes8e282792018-04-03 18:50:29 -04001399 parallel: if true, all tests reported via input_api.RunTests for all
1400 PRESUBMIT files will be run in parallel.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001401 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001402 self.change = change
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001403 self.committing = committing
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001404 self.gerrit = gerrit_obj
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001405 self.verbose = verbose
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001406 self.dry_run = dry_run
Daniel Cheng7227d212017-11-17 08:12:37 -08001407 self.more_cc = []
Edward Lesmes8e282792018-04-03 18:50:29 -04001408 self.thread_pool = thread_pool
1409 self.parallel = parallel
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001410
1411 def ExecPresubmitScript(self, script_text, presubmit_path):
1412 """Executes a single presubmit script.
1413
1414 Args:
1415 script_text: The text of the presubmit script.
1416 presubmit_path: The path to the presubmit file (this will be reported via
1417 input_api.PresubmitLocalPath()).
1418
1419 Return:
1420 A list of result objects, empty if no problems.
1421 """
thakis@chromium.orgc6ef53a2014-11-04 00:13:54 +00001422
chase@chromium.org8e416c82009-10-06 04:30:44 +00001423 # Change to the presubmit file's directory to support local imports.
1424 main_path = os.getcwd()
1425 os.chdir(os.path.dirname(presubmit_path))
1426
1427 # Load the presubmit script into context.
dpranke@chromium.org970c5222011-03-12 00:32:24 +00001428 input_api = InputApi(self.change, presubmit_path, self.committing,
Aaron Gable668c1d82018-04-03 10:19:16 -07001429 self.verbose, gerrit_obj=self.gerrit,
Edward Lesmes8e282792018-04-03 18:50:29 -04001430 dry_run=self.dry_run, thread_pool=self.thread_pool,
1431 parallel=self.parallel)
Daniel Cheng7227d212017-11-17 08:12:37 -08001432 output_api = OutputApi(self.committing)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001433 context = {}
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001434 try:
Raul Tambre09e64b42019-05-14 01:57:22 +00001435 exec(compile(script_text, 'PRESUBMIT.py', 'exec', dont_inherit=True),
1436 context)
Raul Tambre7c938462019-05-24 16:35:35 +00001437 except Exception as e:
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001438 raise PresubmitFailure('"%s" had an exception.\n%s' % (presubmit_path, e))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001439
1440 # These function names must change if we make substantial changes to
1441 # the presubmit API that are not backwards compatible.
1442 if self.committing:
1443 function_name = 'CheckChangeOnCommit'
1444 else:
1445 function_name = 'CheckChangeOnUpload'
1446 if function_name in context:
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +01001447 try:
Daniel Cheng7227d212017-11-17 08:12:37 -08001448 context['__args'] = (input_api, output_api)
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +01001449 logging.debug('Running %s in %s', function_name, presubmit_path)
1450 result = eval(function_name + '(*__args)', context)
1451 logging.debug('Running %s done.', function_name)
Daniel Chengd36fce42017-11-21 21:52:52 -08001452 self.more_cc.extend(output_api.more_cc)
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +01001453 finally:
Edward Lemurd2a5a4c2019-10-23 22:55:26 +00001454 map(os.remove, input_api._named_temporary_files)
1455 if not (isinstance(result, types.TupleType) or
1456 isinstance(result, types.ListType)):
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001457 raise PresubmitFailure(
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001458 'Presubmit functions must return a tuple or list')
1459 for item in result:
1460 if not isinstance(item, OutputApi.PresubmitResult):
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001461 raise PresubmitFailure(
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001462 'All presubmit results must be of types derived from '
1463 'output_api.PresubmitResult')
1464 else:
1465 result = () # no error since the script doesn't care about current event.
1466
chase@chromium.org8e416c82009-10-06 04:30:44 +00001467 # Return the process to the original working directory.
1468 os.chdir(main_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001469 return result
1470
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001471def DoPresubmitChecks(change,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001472 committing,
1473 verbose,
1474 output_stream,
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +00001475 input_stream,
maruel@chromium.orgb0dfd352009-06-10 14:12:54 +00001476 default_presubmit,
dpranke@chromium.org970c5222011-03-12 00:32:24 +00001477 may_prompt,
Aaron Gable668c1d82018-04-03 10:19:16 -07001478 gerrit_obj,
Edward Lesmes8e282792018-04-03 18:50:29 -04001479 dry_run=None,
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001480 parallel=False,
1481 json_output=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001482 """Runs all presubmit checks that apply to the files in the change.
1483
1484 This finds all PRESUBMIT.py files in directories enclosing the files in the
1485 change (up to the repository root) and calls the relevant entrypoint function
1486 depending on whether the change is being committed or uploaded.
1487
1488 Prints errors, warnings and notifications. Prompts the user for warnings
1489 when needed.
1490
1491 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001492 change: The Change object.
agable92bec4f2016-08-24 09:27:27 -07001493 committing: True if 'git cl land' is running, False if 'git cl upload' is.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001494 verbose: Prints debug info.
1495 output_stream: A stream to write output from presubmit tests to.
1496 input_stream: A stream to read input from the user.
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +00001497 default_presubmit: A default presubmit script to execute in any case.
Quinten Yearsley516fe7f2016-12-14 11:50:18 -08001498 may_prompt: Enable (y/n) questions on warning or error. If False,
1499 any questions are answered with yes by default.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001500 gerrit_obj: provides basic Gerrit codereview functionality.
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001501 dry_run: if true, some Checks will be skipped.
Edward Lesmes8e282792018-04-03 18:50:29 -04001502 parallel: if true, all tests specified by input_api.RunTests in all
1503 PRESUBMIT files will be run in parallel.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001504
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +00001505 Warning:
1506 If may_prompt is true, output_stream SHOULD be sys.stdout and input_stream
1507 SHOULD be sys.stdin.
1508
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001509 Return:
dpranke@chromium.org5ac21012011-03-16 02:58:25 +00001510 A PresubmitOutput object. Use output.should_continue() to figure out
1511 if there were errors or warnings and the caller should abort.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001512 """
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001513 old_environ = os.environ
1514 try:
1515 # Make sure python subprocesses won't generate .pyc files.
Edward Lesmes401b25c2019-10-23 03:34:12 +00001516 # We convert to str, since on Windows on Python 2 only strings are allowed
1517 # as environment variables, but literals are unicode since we're importing
1518 # unicode_literals from __future__.
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001519 os.environ = os.environ.copy()
Edward Lesmes401b25c2019-10-23 03:34:12 +00001520 os.environ[str('PYTHONDONTWRITEBYTECODE')] = str('1')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001521
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001522 output = PresubmitOutput(input_stream, output_stream)
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001523
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001524 if committing:
1525 output.write("Running presubmit commit checks ...\n")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001526 else:
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001527 output.write("Running presubmit upload checks ...\n")
1528 start_time = time.time()
1529 presubmit_files = ListRelevantPresubmitFiles(
agable0b65e732016-11-22 09:25:46 -08001530 change.AbsoluteLocalPaths(), change.RepositoryRoot())
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001531 if not presubmit_files and verbose:
maruel@chromium.orgfae707b2011-09-15 18:57:58 +00001532 output.write("Warning, no PRESUBMIT.py found.\n")
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001533 results = []
Edward Lesmes8e282792018-04-03 18:50:29 -04001534 thread_pool = ThreadPool()
Edward Lemur7e3c67f2018-07-20 20:52:49 +00001535 executer = PresubmitExecuter(change, committing, verbose, gerrit_obj,
1536 dry_run, thread_pool, parallel)
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001537 if default_presubmit:
1538 if verbose:
1539 output.write("Running default presubmit script.\n")
1540 fake_path = os.path.join(change.RepositoryRoot(), 'PRESUBMIT.py')
1541 results += executer.ExecPresubmitScript(default_presubmit, fake_path)
1542 for filename in presubmit_files:
1543 filename = os.path.abspath(filename)
1544 if verbose:
1545 output.write("Running %s\n" % filename)
1546 # Accept CRLF presubmit script.
1547 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1548 results += executer.ExecPresubmitScript(presubmit_script, filename)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001549
Edward Lesmes8e282792018-04-03 18:50:29 -04001550 results += thread_pool.RunAsync()
1551
Daniel Cheng7227d212017-11-17 08:12:37 -08001552 output.more_cc.extend(executer.more_cc)
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001553 errors = []
1554 notifications = []
1555 warnings = []
1556 for result in results:
1557 if result.fatal:
1558 errors.append(result)
1559 elif result.should_prompt:
1560 warnings.append(result)
1561 else:
1562 notifications.append(result)
pam@chromium.orged9a0832009-09-09 22:48:55 +00001563
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001564 if json_output:
1565 # Write the presubmit results to json output
1566 presubmit_results = {
1567 'errors': [
1568 error.json_format() for error in errors
1569 ],
1570 'notifications': [
1571 notification.json_format() for notification in notifications
1572 ],
1573 'warnings': [
1574 warning.json_format() for warning in warnings
1575 ]
1576 }
1577
Edward Lemurd2a5a4c2019-10-23 22:55:26 +00001578 gclient_utils.FileWrite(json_output, json.dumps(presubmit_results))
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001579
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001580 output.write('\n')
1581 for name, items in (('Messages', notifications),
1582 ('Warnings', warnings),
1583 ('ERRORS', errors)):
1584 if items:
1585 output.write('** Presubmit %s **\n' % name)
1586 for item in items:
1587 item.handle(output)
1588 output.write('\n')
pam@chromium.orged9a0832009-09-09 22:48:55 +00001589
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001590 total_time = time.time() - start_time
1591 if total_time > 1.0:
1592 output.write("Presubmit checks took %.1fs to calculate.\n\n" % total_time)
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +00001593
Quinten Yearsley516fe7f2016-12-14 11:50:18 -08001594 if errors:
1595 output.fail()
1596 elif warnings:
1597 output.write('There were presubmit warnings. ')
1598 if may_prompt:
1599 output.prompt_yes_no('Are you sure you wish to continue? (y/N): ')
1600 else:
1601 output.write('Presubmit checks passed.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001602
1603 global _ASKED_FOR_FEEDBACK
1604 # Ask for feedback one time out of 5.
1605 if (len(results) and random.randint(0, 4) == 0 and not _ASKED_FOR_FEEDBACK):
maruel@chromium.org1ce8e662014-01-14 15:23:00 +00001606 output.write(
1607 'Was the presubmit check useful? If not, run "git cl presubmit -v"\n'
1608 'to figure out which PRESUBMIT.py was run, then run git blame\n'
1609 'on the file to figure out who to ask for help.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001610 _ASKED_FOR_FEEDBACK = True
1611 return output
1612 finally:
1613 os.environ = old_environ
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001614
1615
1616def ScanSubDirs(mask, recursive):
1617 if not recursive:
pgervais@chromium.orge57b09d2014-05-07 00:58:13 +00001618 return [x for x in glob.glob(mask) if x not in ('.svn', '.git')]
Lei Zhang9611c4c2017-04-04 01:41:56 -07001619
1620 results = []
1621 for root, dirs, files in os.walk('.'):
1622 if '.svn' in dirs:
1623 dirs.remove('.svn')
1624 if '.git' in dirs:
1625 dirs.remove('.git')
1626 for name in files:
1627 if fnmatch.fnmatch(name, mask):
1628 results.append(os.path.join(root, name))
1629 return results
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001630
1631
1632def ParseFiles(args, recursive):
tobiasjs2836bcf2016-08-16 04:08:16 -07001633 logging.debug('Searching for %s', args)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001634 files = []
1635 for arg in args:
maruel@chromium.orge3608df2009-11-10 20:22:57 +00001636 files.extend([('M', f) for f in ScanSubDirs(arg, recursive)])
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001637 return files
1638
1639
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001640def load_files(options, args):
1641 """Tries to determine the SCM."""
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001642 files = []
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001643 if args:
1644 files = ParseFiles(args, options.recursive)
agable0b65e732016-11-22 09:25:46 -08001645 change_scm = scm.determine_scm(options.root)
1646 if change_scm == 'git':
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001647 change_class = GitChange
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001648 upstream = options.upstream or None
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001649 if not files:
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001650 files = scm.GIT.CaptureStatus([], options.root, upstream)
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001651 else:
tobiasjs2836bcf2016-08-16 04:08:16 -07001652 logging.info('Doesn\'t seem under source control. Got %d files', len(args))
maruel@chromium.org9b31f162012-01-26 19:02:31 +00001653 if not files:
1654 return None, None
1655 change_class = Change
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001656 return change_class, files
1657
1658
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001659@contextlib.contextmanager
1660def canned_check_filter(method_names):
1661 filtered = {}
1662 try:
1663 for method_name in method_names:
1664 if not hasattr(presubmit_canned_checks, method_name):
Aaron Gableecee74c2018-04-02 15:13:08 -07001665 logging.warn('Skipping unknown "canned" check %s' % method_name)
1666 continue
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001667 filtered[method_name] = getattr(presubmit_canned_checks, method_name)
1668 setattr(presubmit_canned_checks, method_name, lambda *_a, **_kw: [])
1669 yield
1670 finally:
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00001671 for name, method in filtered.items():
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001672 setattr(presubmit_canned_checks, name, method)
1673
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001674
sbc@chromium.org013731e2015-02-26 18:28:43 +00001675def main(argv=None):
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001676 parser = optparse.OptionParser(usage="%prog [options] <files...>",
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001677 version="%prog " + str(__version__))
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001678 parser.add_option("-c", "--commit", action="store_true", default=False,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001679 help="Use commit instead of upload checks")
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001680 parser.add_option("-u", "--upload", action="store_false", dest='commit',
1681 help="Use upload instead of commit checks")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001682 parser.add_option("-r", "--recursive", action="store_true",
1683 help="Act recursively")
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001684 parser.add_option("-v", "--verbose", action="count", default=0,
1685 help="Use 2 times for more debug info")
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001686 parser.add_option("--name", default='no name')
maruel@chromium.org58407af2011-04-12 23:15:57 +00001687 parser.add_option("--author")
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001688 parser.add_option("--description", default='')
1689 parser.add_option("--issue", type='int', default=0)
1690 parser.add_option("--patchset", type='int', default=0)
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001691 parser.add_option("--root", default=os.getcwd(),
1692 help="Search for PRESUBMIT.py up to this directory. "
1693 "If inherit-review-settings-ok is present in this "
1694 "directory, parent directories up to the root file "
1695 "system directories will also be searched.")
agable@chromium.org2da1ade2014-04-30 17:40:45 +00001696 parser.add_option("--upstream",
1697 help="Git only: the base ref or upstream branch against "
1698 "which the diff should be computed.")
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001699 parser.add_option("--default_presubmit")
1700 parser.add_option("--may_prompt", action='store_true', default=False)
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001701 parser.add_option("--skip_canned", action='append', default=[],
1702 help="A list of checks to skip which appear in "
1703 "presubmit_canned_checks. Can be provided multiple times "
1704 "to skip multiple canned checks.")
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001705 parser.add_option("--dry_run", action='store_true',
1706 help=optparse.SUPPRESS_HELP)
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001707 parser.add_option("--gerrit_url", help=optparse.SUPPRESS_HELP)
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001708 parser.add_option("--gerrit_fetch", action='store_true',
1709 help=optparse.SUPPRESS_HELP)
Edward Lesmes8e282792018-04-03 18:50:29 -04001710 parser.add_option('--parallel', action='store_true',
1711 help='Run all tests specified by input_api.RunTests in all '
1712 'PRESUBMIT files in parallel.')
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001713 parser.add_option('--json_output',
1714 help='Write presubmit errors to json output.')
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001715
maruel@chromium.org82e5f282011-03-17 14:08:55 +00001716 options, args = parser.parse_args(argv)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001717
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001718 if options.verbose >= 2:
maruel@chromium.org7444c502011-02-09 14:02:11 +00001719 logging.basicConfig(level=logging.DEBUG)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001720 elif options.verbose:
1721 logging.basicConfig(level=logging.INFO)
1722 else:
1723 logging.basicConfig(level=logging.ERROR)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001724
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001725 change_class, files = load_files(options, args)
1726 if not change_class:
1727 parser.error('For unversioned directory, <files> is not optional.')
tobiasjs2836bcf2016-08-16 04:08:16 -07001728 logging.info('Found %d file(s).', len(files))
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001729
Aaron Gable668c1d82018-04-03 10:19:16 -07001730 gerrit_obj = None
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001731 if options.gerrit_url and options.gerrit_fetch:
tandrii@chromium.org83b1b232016-04-29 16:33:19 +00001732 assert options.issue and options.patchset
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001733 gerrit_obj = GerritAccessor(urlparse.urlparse(options.gerrit_url).netloc)
1734 options.author = gerrit_obj.GetChangeOwner(options.issue)
1735 options.description = gerrit_obj.GetChangeDescription(options.issue,
1736 options.patchset)
tandrii@chromium.org015ebae2016-04-25 19:37:22 +00001737 logging.info('Got author: "%s"', options.author)
1738 logging.info('Got description: """\n%s\n"""', options.description)
1739
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001740 try:
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001741 with canned_check_filter(options.skip_canned):
1742 results = DoPresubmitChecks(
1743 change_class(options.name,
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001744 options.description,
1745 options.root,
1746 files,
1747 options.issue,
1748 options.patchset,
1749 options.author,
1750 upstream=options.upstream),
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001751 options.commit,
1752 options.verbose,
1753 sys.stdout,
1754 sys.stdin,
1755 options.default_presubmit,
1756 options.may_prompt,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001757 gerrit_obj,
Edward Lesmes8e282792018-04-03 18:50:29 -04001758 options.dry_run,
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001759 options.parallel,
1760 options.json_output)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001761 return not results.should_continue()
Raul Tambre7c938462019-05-24 16:35:35 +00001762 except PresubmitFailure as e:
Raul Tambre80ee78e2019-05-06 22:41:05 +00001763 print(e, file=sys.stderr)
1764 print('Maybe your depot_tools is out of date?', file=sys.stderr)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001765 return 2
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001766
1767
1768if __name__ == '__main__':
maruel@chromium.org35625c72011-03-23 17:34:02 +00001769 fix_encoding.fix_encoding()
sbc@chromium.org013731e2015-02-26 18:28:43 +00001770 try:
1771 sys.exit(main())
1772 except KeyboardInterrupt:
1773 sys.stderr.write('interrupted\n')
sergiybf8a3b382016-07-05 11:21:30 -07001774 sys.exit(2)