blob: 16dd377eec7c702e243910f08c64ed3c14b76ba0 [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
Edward Lemura5799e32020-01-17 19:26:51 +000017import argparse
Takeshi Yoshino07a6bea2017-08-02 02:44:06 +090018import ast # Exposed through the API.
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +000019import contextlib
Yoshisato Yanagisawa406de132018-06-29 05:43:25 +000020import cpplint
dcheng091b7db2016-06-16 01:27:51 -070021import fnmatch # Exposed through the API.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000022import glob
asvitkine@chromium.org15169952011-09-27 14:30:53 +000023import inspect
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +000024import itertools
maruel@chromium.org4f6852c2012-04-20 20:39:20 +000025import json # Exposed through the API.
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +000026import logging
ilevy@chromium.orgbc117312013-04-20 03:57:56 +000027import multiprocessing
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000028import os # Somewhat exposed through the API.
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +000029import random
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000030import re # Exposed through the API.
Edward Lesmes8e282792018-04-03 18:50:29 -040031import signal
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000032import sys # Parts exposed through API.
33import tempfile # Exposed through the API.
Edward Lesmes8e282792018-04-03 18:50:29 -040034import threading
jam@chromium.org2a891dc2009-08-20 20:33:37 +000035import time
Edward Lemurde9e3ca2019-10-24 21:13:31 +000036import traceback
maruel@chromium.org1487d532009-06-06 00:22:57 +000037import unittest # Exposed through the API.
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +000038from warnings import warn
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000039
40# Local imports.
maruel@chromium.org35625c72011-03-23 17:34:02 +000041import fix_encoding
Yoshisato Yanagisawa04600b42019-03-15 03:03:41 +000042import gclient_paths # Exposed through the API
43import gclient_utils
Aaron Gableb584c4f2017-04-26 16:28:08 -070044import git_footers
tandrii@chromium.org015ebae2016-04-25 19:37:22 +000045import gerrit_util
dpranke@chromium.org2a009622011-03-01 02:43:31 +000046import owners
Jochen Eisinger76f5fc62017-04-07 16:27:46 +020047import owners_finder
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000048import presubmit_canned_checks
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +000049import scm
maruel@chromium.org84f4fe32011-04-06 13:26:45 +000050import subprocess2 as subprocess # Exposed through the API.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000051
Edward Lemur16af3562019-10-17 22:11:33 +000052if sys.version_info.major == 2:
53 # TODO(1009814): Expose urllib2 only through urllib_request and urllib_error
54 import urllib2 # Exposed through the API.
55 import urlparse
56 import urllib2 as urllib_request
57 import urllib2 as urllib_error
58else:
59 import urllib.parse as urlparse
60 import urllib.request as urllib_request
61 import urllib.error as urllib_error
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000062
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +000063# Ask for feedback only once in program lifetime.
64_ASKED_FOR_FEEDBACK = False
65
66
Edward Lemurecc27072020-01-06 16:42:34 +000067def time_time():
68 # Use this so that it can be mocked in tests without interfering with python
69 # system machinery.
70 return time.time()
71
72
maruel@chromium.org899e1c12011-04-07 17:03:18 +000073class PresubmitFailure(Exception):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000074 pass
75
76
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +000077class CommandData(object):
Edward Lemur940c2822019-08-23 00:34:25 +000078 def __init__(self, name, cmd, kwargs, message, python3=False):
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +000079 self.name = name
80 self.cmd = cmd
Edward Lesmes8e282792018-04-03 18:50:29 -040081 self.stdin = kwargs.get('stdin', None)
Edward Lemur2d6b67c2019-08-23 22:25:41 +000082 self.kwargs = kwargs.copy()
Edward Lesmes8e282792018-04-03 18:50:29 -040083 self.kwargs['stdout'] = subprocess.PIPE
84 self.kwargs['stderr'] = subprocess.STDOUT
85 self.kwargs['stdin'] = subprocess.PIPE
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +000086 self.message = message
87 self.info = None
Edward Lemur940c2822019-08-23 00:34:25 +000088 self.python3 = python3
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +000089
ilevy@chromium.orgbc117312013-04-20 03:57:56 +000090
Edward Lesmes8e282792018-04-03 18:50:29 -040091# Adapted from
92# https://github.com/google/gtest-parallel/blob/master/gtest_parallel.py#L37
93#
94# An object that catches SIGINT sent to the Python process and notices
95# if processes passed to wait() die by SIGINT (we need to look for
96# both of those cases, because pressing Ctrl+C can result in either
97# the main process or one of the subprocesses getting the signal).
98#
99# Before a SIGINT is seen, wait(p) will simply call p.wait() and
100# return the result. Once a SIGINT has been seen (in the main process
101# or a subprocess, including the one the current call is waiting for),
Edward Lemur9a5bb612019-09-26 02:01:52 +0000102# wait(p) will call p.terminate().
Edward Lesmes8e282792018-04-03 18:50:29 -0400103class SigintHandler(object):
Edward Lesmes8e282792018-04-03 18:50:29 -0400104 sigint_returncodes = {-signal.SIGINT, # Unix
105 -1073741510, # Windows
106 }
107 def __init__(self):
108 self.__lock = threading.Lock()
109 self.__processes = set()
110 self.__got_sigint = False
Edward Lemur9a5bb612019-09-26 02:01:52 +0000111 self.__previous_signal = signal.signal(signal.SIGINT, self.interrupt)
Edward Lesmes8e282792018-04-03 18:50:29 -0400112
113 def __on_sigint(self):
114 self.__got_sigint = True
115 while self.__processes:
116 try:
117 self.__processes.pop().terminate()
118 except OSError:
119 pass
120
Edward Lemur9a5bb612019-09-26 02:01:52 +0000121 def interrupt(self, signal_num, frame):
Edward Lesmes8e282792018-04-03 18:50:29 -0400122 with self.__lock:
123 self.__on_sigint()
Edward Lemur9a5bb612019-09-26 02:01:52 +0000124 self.__previous_signal(signal_num, frame)
Edward Lesmes8e282792018-04-03 18:50:29 -0400125
126 def got_sigint(self):
127 with self.__lock:
128 return self.__got_sigint
129
130 def wait(self, p, stdin):
131 with self.__lock:
132 if self.__got_sigint:
133 p.terminate()
134 self.__processes.add(p)
135 stdout, stderr = p.communicate(stdin)
136 code = p.returncode
137 with self.__lock:
138 self.__processes.discard(p)
139 if code in self.sigint_returncodes:
140 self.__on_sigint()
Edward Lesmes8e282792018-04-03 18:50:29 -0400141 return stdout, stderr
142
143sigint_handler = SigintHandler()
144
145
Edward Lemurecc27072020-01-06 16:42:34 +0000146class Timer(object):
147 def __init__(self, timeout, fn):
148 self.completed = False
149 self._fn = fn
150 self._timer = threading.Timer(timeout, self._onTimer) if timeout else None
151
152 def __enter__(self):
153 if self._timer:
154 self._timer.start()
155 return self
156
157 def __exit__(self, _type, _value, _traceback):
158 if self._timer:
159 self._timer.cancel()
160
161 def _onTimer(self):
162 self._fn()
163 self.completed = True
164
165
Edward Lesmes8e282792018-04-03 18:50:29 -0400166class ThreadPool(object):
Edward Lemurecc27072020-01-06 16:42:34 +0000167 def __init__(self, pool_size=None, timeout=None):
168 self.timeout = timeout
Edward Lesmes8e282792018-04-03 18:50:29 -0400169 self._pool_size = pool_size or multiprocessing.cpu_count()
170 self._messages = []
171 self._messages_lock = threading.Lock()
172 self._tests = []
173 self._tests_lock = threading.Lock()
174 self._nonparallel_tests = []
175
Edward Lemurecc27072020-01-06 16:42:34 +0000176 def _GetCommand(self, test):
Edward Lemur940c2822019-08-23 00:34:25 +0000177 vpython = 'vpython'
178 if test.python3:
179 vpython += '3'
180 if sys.platform == 'win32':
181 vpython += '.bat'
Edward Lesmes8e282792018-04-03 18:50:29 -0400182
183 cmd = test.cmd
184 if cmd[0] == 'python':
185 cmd = list(cmd)
186 cmd[0] = vpython
187 elif cmd[0].endswith('.py'):
188 cmd = [vpython] + cmd
189
Edward Lemur336e51f2019-11-14 21:42:04 +0000190 # On Windows, scripts on the current directory take precedence over PATH, so
191 # that when testing depot_tools on Windows, calling `vpython.bat` will
192 # execute the copy of vpython of the depot_tools under test instead of the
193 # one in the bot.
194 # As a workaround, we run the tests from the parent directory instead.
195 if (cmd[0] == vpython and
196 'cwd' in test.kwargs and
197 os.path.basename(test.kwargs['cwd']) == 'depot_tools'):
198 test.kwargs['cwd'] = os.path.dirname(test.kwargs['cwd'])
199 cmd[1] = os.path.join('depot_tools', cmd[1])
200
Edward Lemurecc27072020-01-06 16:42:34 +0000201 return cmd
202
203 def _RunWithTimeout(self, cmd, stdin, kwargs):
204 p = subprocess.Popen(cmd, **kwargs)
205 with Timer(self.timeout, p.terminate) as timer:
206 stdout, _ = sigint_handler.wait(p, stdin)
207 if timer.completed:
208 stdout = 'Process timed out after %ss\n%s' % (self.timeout, stdout)
209 return p.returncode, stdout
210
211 def CallCommand(self, test):
212 """Runs an external program.
213
Edward Lemura5799e32020-01-17 19:26:51 +0000214 This function converts invocation of .py files and invocations of 'python'
Edward Lemurecc27072020-01-06 16:42:34 +0000215 to vpython invocations.
216 """
217 cmd = self._GetCommand(test)
Edward Lesmes8e282792018-04-03 18:50:29 -0400218 try:
Edward Lemurecc27072020-01-06 16:42:34 +0000219 start = time_time()
220 returncode, stdout = self._RunWithTimeout(cmd, test.stdin, test.kwargs)
221 duration = time_time() - start
Edward Lemur7cf94382019-11-15 22:36:41 +0000222 except Exception:
Edward Lemurecc27072020-01-06 16:42:34 +0000223 duration = time_time() - start
Edward Lesmes8e282792018-04-03 18:50:29 -0400224 return test.message(
Edward Lemur7cf94382019-11-15 22:36:41 +0000225 '%s\n%s exec failure (%4.2fs)\n%s' % (
226 test.name, ' '.join(cmd), duration, traceback.format_exc()))
Edward Lemurde9e3ca2019-10-24 21:13:31 +0000227
Edward Lemurecc27072020-01-06 16:42:34 +0000228 if returncode != 0:
Edward Lesmes8e282792018-04-03 18:50:29 -0400229 return test.message(
Edward Lemur7cf94382019-11-15 22:36:41 +0000230 '%s\n%s (%4.2fs) failed\n%s' % (
231 test.name, ' '.join(cmd), duration, stdout))
Edward Lemurecc27072020-01-06 16:42:34 +0000232
Edward Lesmes8e282792018-04-03 18:50:29 -0400233 if test.info:
Edward Lemur7cf94382019-11-15 22:36:41 +0000234 return test.info('%s\n%s (%4.2fs)' % (test.name, ' '.join(cmd), duration))
Edward Lesmes8e282792018-04-03 18:50:29 -0400235
236 def AddTests(self, tests, parallel=True):
237 if parallel:
238 self._tests.extend(tests)
239 else:
240 self._nonparallel_tests.extend(tests)
241
242 def RunAsync(self):
243 self._messages = []
244
245 def _WorkerFn():
246 while True:
247 test = None
248 with self._tests_lock:
249 if not self._tests:
250 break
251 test = self._tests.pop()
252 result = self.CallCommand(test)
253 if result:
254 with self._messages_lock:
255 self._messages.append(result)
256
257 def _StartDaemon():
258 t = threading.Thread(target=_WorkerFn)
259 t.daemon = True
260 t.start()
261 return t
262
263 while self._nonparallel_tests:
264 test = self._nonparallel_tests.pop()
265 result = self.CallCommand(test)
266 if result:
267 self._messages.append(result)
268
269 if self._tests:
270 threads = [_StartDaemon() for _ in range(self._pool_size)]
271 for worker in threads:
272 worker.join()
273
274 return self._messages
275
276
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000277def normpath(path):
278 '''Version of os.path.normpath that also changes backward slashes to
279 forward slashes when not running on Windows.
280 '''
281 # This is safe to always do because the Windows version of os.path.normpath
282 # will replace forward slashes with backward slashes.
283 path = path.replace(os.sep, '/')
284 return os.path.normpath(path)
285
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000286
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000287def _RightHandSideLinesImpl(affected_files):
288 """Implements RightHandSideLines for InputApi and GclChange."""
289 for af in affected_files:
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000290 lines = af.ChangedContents()
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000291 for line in lines:
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000292 yield (af, line[0], line[1])
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000293
294
dpranke@chromium.org5ac21012011-03-16 02:58:25 +0000295class PresubmitOutput(object):
296 def __init__(self, input_stream=None, output_stream=None):
297 self.input_stream = input_stream
298 self.output_stream = output_stream
299 self.reviewers = []
Daniel Cheng7227d212017-11-17 08:12:37 -0800300 self.more_cc = []
dpranke@chromium.org5ac21012011-03-16 02:58:25 +0000301 self.written_output = []
302 self.error_count = 0
303
304 def prompt_yes_no(self, prompt_string):
305 self.write(prompt_string)
306 if self.input_stream:
307 response = self.input_stream.readline().strip().lower()
308 if response not in ('y', 'yes'):
309 self.fail()
310 else:
311 self.fail()
312
313 def fail(self):
314 self.error_count += 1
315
316 def should_continue(self):
317 return not self.error_count
318
319 def write(self, s):
320 self.written_output.append(s)
321 if self.output_stream:
322 self.output_stream.write(s)
323
324 def getvalue(self):
325 return ''.join(self.written_output)
326
327
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000328# Top level object so multiprocessing can pickle
329# Public access through OutputApi object.
330class _PresubmitResult(object):
331 """Base class for result objects."""
332 fatal = False
333 should_prompt = False
334
335 def __init__(self, message, items=None, long_text=''):
336 """
337 message: A short one-line message to indicate errors.
338 items: A list of short strings to indicate where errors occurred.
339 long_text: multi-line text output, e.g. from another tool
340 """
341 self._message = message
342 self._items = items or []
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000343 self._long_text = long_text.rstrip()
344
345 def handle(self, output):
346 output.write(self._message)
347 output.write('\n')
348 for index, item in enumerate(self._items):
349 output.write(' ')
350 # Write separately in case it's unicode.
351 output.write(str(item))
352 if index < len(self._items) - 1:
353 output.write(' \\')
354 output.write('\n')
355 if self._long_text:
356 output.write('\n***************\n')
357 # Write separately in case it's unicode.
358 output.write(self._long_text)
359 output.write('\n***************\n')
360 if self.fatal:
361 output.fail()
362
Debrian Figueroadd2737e2019-06-21 23:50:13 +0000363 def json_format(self):
364 return {
365 'message': self._message,
Debrian Figueroa6095d402019-06-28 18:47:18 +0000366 'items': [str(item) for item in self._items],
Debrian Figueroadd2737e2019-06-21 23:50:13 +0000367 'long_text': self._long_text,
368 'fatal': self.fatal
369 }
370
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000371
372# Top level object so multiprocessing can pickle
373# Public access through OutputApi object.
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000374class _PresubmitError(_PresubmitResult):
375 """A hard presubmit error."""
376 fatal = True
377
378
379# Top level object so multiprocessing can pickle
380# Public access through OutputApi object.
381class _PresubmitPromptWarning(_PresubmitResult):
382 """An warning that prompts the user if they want to continue."""
383 should_prompt = True
384
385
386# Top level object so multiprocessing can pickle
387# Public access through OutputApi object.
388class _PresubmitNotifyResult(_PresubmitResult):
389 """Just print something to the screen -- but it's not even a warning."""
390 pass
391
392
393# Top level object so multiprocessing can pickle
394# Public access through OutputApi object.
395class _MailTextResult(_PresubmitResult):
396 """A warning that should be included in the review request email."""
397 def __init__(self, *args, **kwargs):
398 super(_MailTextResult, self).__init__()
399 raise NotImplementedError()
400
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000401class GerritAccessor(object):
402 """Limited Gerrit functionality for canned presubmit checks to work.
403
404 To avoid excessive Gerrit calls, caches the results.
405 """
406
407 def __init__(self, host):
408 self.host = host
409 self.cache = {}
410
411 def _FetchChangeDetail(self, issue):
412 # Separate function to be easily mocked in tests.
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +0100413 try:
414 return gerrit_util.GetChangeDetail(
415 self.host, str(issue),
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700416 ['ALL_REVISIONS', 'DETAILED_LABELS', 'ALL_COMMITS'])
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +0100417 except gerrit_util.GerritError as e:
418 if e.http_status == 404:
419 raise Exception('Either Gerrit issue %s doesn\'t exist, or '
420 'no credentials to fetch issue details' % issue)
421 raise
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000422
423 def GetChangeInfo(self, issue):
424 """Returns labels and all revisions (patchsets) for this issue.
425
426 The result is a dictionary according to Gerrit REST Api.
427 https://gerrit-review.googlesource.com/Documentation/rest-api.html
428
429 However, API isn't very clear what's inside, so see tests for example.
430 """
431 assert issue
432 cache_key = int(issue)
433 if cache_key not in self.cache:
434 self.cache[cache_key] = self._FetchChangeDetail(issue)
435 return self.cache[cache_key]
436
437 def GetChangeDescription(self, issue, patchset=None):
438 """If patchset is none, fetches current patchset."""
439 info = self.GetChangeInfo(issue)
440 # info is a reference to cache. We'll modify it here adding description to
441 # it to the right patchset, if it is not yet there.
442
443 # Find revision info for the patchset we want.
444 if patchset is not None:
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000445 for rev, rev_info in info['revisions'].items():
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000446 if str(rev_info['_number']) == str(patchset):
447 break
448 else:
449 raise Exception('patchset %s doesn\'t exist in issue %s' % (
450 patchset, issue))
451 else:
452 rev = info['current_revision']
453 rev_info = info['revisions'][rev]
454
Andrii Shyshkalov9c3a4642017-01-24 17:41:22 +0100455 return rev_info['commit']['message']
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000456
Mun Yong Jang603d01e2017-12-19 16:38:30 -0800457 def GetDestRef(self, issue):
458 ref = self.GetChangeInfo(issue)['branch']
459 if not ref.startswith('refs/'):
460 # NOTE: it is possible to create 'refs/x' branch,
461 # aka 'refs/heads/refs/x'. However, this is ill-advised.
462 ref = 'refs/heads/%s' % ref
463 return ref
464
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000465 def GetChangeOwner(self, issue):
466 return self.GetChangeInfo(issue)['owner']['email']
467
468 def GetChangeReviewers(self, issue, approving_only=True):
Aaron Gable8b478f02017-07-31 15:33:19 -0700469 changeinfo = self.GetChangeInfo(issue)
470 if approving_only:
471 labelinfo = changeinfo.get('labels', {}).get('Code-Review', {})
472 values = labelinfo.get('values', {}).keys()
473 try:
474 max_value = max(int(v) for v in values)
475 reviewers = [r for r in labelinfo.get('all', [])
476 if r.get('value', 0) == max_value]
477 except ValueError: # values is the empty list
478 reviewers = []
479 else:
480 reviewers = changeinfo.get('reviewers', {}).get('REVIEWER', [])
481 return [r.get('email') for r in reviewers]
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000482
Edward Lemure4d329c2020-02-03 20:41:18 +0000483 def UpdateDescription(self, description, issue):
484 gerrit_util.SetCommitMessage(self.host, issue, description, notify='NONE')
485
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000486
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000487class OutputApi(object):
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000488 """An instance of OutputApi gets passed to presubmit scripts so that they
489 can output various types of results.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000490 """
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000491 PresubmitResult = _PresubmitResult
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000492 PresubmitError = _PresubmitError
493 PresubmitPromptWarning = _PresubmitPromptWarning
494 PresubmitNotifyResult = _PresubmitNotifyResult
495 MailTextResult = _MailTextResult
496
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000497 def __init__(self, is_committing):
498 self.is_committing = is_committing
Daniel Cheng7227d212017-11-17 08:12:37 -0800499 self.more_cc = []
500
501 def AppendCC(self, cc):
502 """Appends a user to cc for this change."""
503 self.more_cc.append(cc)
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000504
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000505 def PresubmitPromptOrNotify(self, *args, **kwargs):
506 """Warn the user when uploading, but only notify if committing."""
507 if self.is_committing:
508 return self.PresubmitNotifyResult(*args, **kwargs)
509 return self.PresubmitPromptWarning(*args, **kwargs)
510
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000511
512class InputApi(object):
513 """An instance of this object is passed to presubmit scripts so they can
514 know stuff about the change they're looking at.
515 """
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000516 # Method could be a function
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800517 # pylint: disable=no-self-use
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000518
maruel@chromium.org3410d912009-06-09 20:56:16 +0000519 # File extensions that are considered source files from a style guide
520 # perspective. Don't modify this list from a presubmit script!
maruel@chromium.orgc33455a2011-06-24 19:14:18 +0000521 #
522 # Files without an extension aren't included in the list. If you want to
Edward Lemura5799e32020-01-17 19:26:51 +0000523 # filter them as source files, add r'(^|.*?[\\\/])[^.]+$' to the white list.
maruel@chromium.orgc33455a2011-06-24 19:14:18 +0000524 # Note that ALL CAPS files are black listed in DEFAULT_BLACK_LIST below.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000525 DEFAULT_WHITE_LIST = (
526 # C++ and friends
Edward Lemura5799e32020-01-17 19:26:51 +0000527 r'.+\.c$', r'.+\.cc$', r'.+\.cpp$', r'.+\.h$', r'.+\.m$', r'.+\.mm$',
528 r'.+\.inl$', r'.+\.asm$', r'.+\.hxx$', r'.+\.hpp$', r'.+\.s$', r'.+\.S$',
maruel@chromium.org3410d912009-06-09 20:56:16 +0000529 # Scripts
Edward Lemura5799e32020-01-17 19:26:51 +0000530 r'.+\.js$', r'.+\.py$', r'.+\.sh$', r'.+\.rb$', r'.+\.pl$', r'.+\.pm$',
maruel@chromium.org3410d912009-06-09 20:56:16 +0000531 # Other
Edward Lemura5799e32020-01-17 19:26:51 +0000532 r'.+\.java$', r'.+\.mk$', r'.+\.am$', r'.+\.css$', r'.+\.mojom$',
533 r'.+\.fidl$'
maruel@chromium.org3410d912009-06-09 20:56:16 +0000534 )
535
536 # Path regexp that should be excluded from being considered containing source
537 # files. Don't modify this list from a presubmit script!
538 DEFAULT_BLACK_LIST = (
Edward Lemura5799e32020-01-17 19:26:51 +0000539 r'testing_support[\\\/]google_appengine[\\\/].*',
540 r'.*\bexperimental[\\\/].*',
Kent Tamura179dd1e2018-04-26 15:07:41 +0900541 # Exclude third_party/.* but NOT third_party/{WebKit,blink}
542 # (crbug.com/539768 and crbug.com/836555).
Edward Lemura5799e32020-01-17 19:26:51 +0000543 r'.*\bthird_party[\\\/](?!(WebKit|blink)[\\\/]).*',
maruel@chromium.org3410d912009-06-09 20:56:16 +0000544 # Output directories (just in case)
Edward Lemura5799e32020-01-17 19:26:51 +0000545 r'.*\bDebug[\\\/].*',
546 r'.*\bRelease[\\\/].*',
547 r'.*\bxcodebuild[\\\/].*',
548 r'.*\bout[\\\/].*',
maruel@chromium.org3410d912009-06-09 20:56:16 +0000549 # All caps files like README and LICENCE.
Edward Lemura5799e32020-01-17 19:26:51 +0000550 r'.*\b[A-Z0-9_]{2,}$',
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000551 # SCM (can happen in dual SCM configuration). (Slightly over aggressive)
Edward Lemura5799e32020-01-17 19:26:51 +0000552 r'(|.*[\\\/])\.git[\\\/].*',
553 r'(|.*[\\\/])\.svn[\\\/].*',
maruel@chromium.org7ccb4bb2011-11-07 20:26:20 +0000554 # There is no point in processing a patch file.
Edward Lemura5799e32020-01-17 19:26:51 +0000555 r'.+\.diff$',
556 r'.+\.patch$',
maruel@chromium.org3410d912009-06-09 20:56:16 +0000557 )
558
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000559 def __init__(self, change, presubmit_path, is_committing,
Edward Lesmes8e282792018-04-03 18:50:29 -0400560 verbose, gerrit_obj, dry_run=None, thread_pool=None, parallel=False):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000561 """Builds an InputApi object.
562
563 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000564 change: A presubmit.Change object.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000565 presubmit_path: The path to the presubmit script being processed.
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000566 is_committing: True if the change is about to be committed.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000567 gerrit_obj: provides basic Gerrit codereview functionality.
568 dry_run: if true, some Checks will be skipped.
Edward Lesmes8e282792018-04-03 18:50:29 -0400569 parallel: if true, all tests reported via input_api.RunTests for all
570 PRESUBMIT files will be run in parallel.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000571 """
maruel@chromium.org9711bba2009-05-22 23:51:39 +0000572 # Version number of the presubmit_support script.
573 self.version = [int(x) for x in __version__.split('.')]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000574 self.change = change
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000575 self.is_committing = is_committing
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000576 self.gerrit = gerrit_obj
tandrii@chromium.org57bafac2016-04-28 05:09:03 +0000577 self.dry_run = dry_run
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000578
Edward Lesmes8e282792018-04-03 18:50:29 -0400579 self.parallel = parallel
580 self.thread_pool = thread_pool or ThreadPool()
581
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000582 # We expose various modules and functions as attributes of the input_api
583 # so that presubmit scripts don't have to import them.
Takeshi Yoshino07a6bea2017-08-02 02:44:06 +0900584 self.ast = ast
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000585 self.basename = os.path.basename
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000586 self.cpplint = cpplint
dcheng091b7db2016-06-16 01:27:51 -0700587 self.fnmatch = fnmatch
Yoshisato Yanagisawa04600b42019-03-15 03:03:41 +0000588 self.gclient_paths = gclient_paths
Yoshisato Yanagisawa57dd17b2019-03-22 09:10:29 +0000589 # TODO(yyanagisawa): stop exposing this when python3 become default.
590 # Since python3's tempfile has TemporaryDirectory, we do not need this.
591 self.temporary_directory = gclient_utils.temporary_directory
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000592 self.glob = glob.glob
maruel@chromium.orgfb11c7b2010-03-18 18:22:14 +0000593 self.json = json
maruel@chromium.org6fba34d2011-06-02 13:45:12 +0000594 self.logging = logging.getLogger('PRESUBMIT')
maruel@chromium.org2b5ce562011-03-31 16:15:44 +0000595 self.os_listdir = os.listdir
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000596 self.os_path = os.path
pgervais@chromium.orgbd0cace2014-10-02 23:23:46 +0000597 self.os_stat = os.stat
Yoshisato Yanagisawa406de132018-06-29 05:43:25 +0000598 self.os_walk = os.walk
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000599 self.re = re
600 self.subprocess = subprocess
Edward Lemurb9830242019-10-30 22:19:20 +0000601 self.sys = sys
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000602 self.tempfile = tempfile
dpranke@chromium.org0d1bdea2011-03-24 22:54:38 +0000603 self.time = time
maruel@chromium.org1487d532009-06-06 00:22:57 +0000604 self.unittest = unittest
Edward Lemurb9830242019-10-30 22:19:20 +0000605 if sys.version_info.major == 2:
606 self.urllib2 = urllib2
Edward Lemur16af3562019-10-17 22:11:33 +0000607 self.urllib_request = urllib_request
608 self.urllib_error = urllib_error
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000609
Robert Iannucci50258932018-03-19 10:30:59 -0700610 self.is_windows = sys.platform == 'win32'
611
Edward Lemurb9646622019-10-25 20:57:35 +0000612 # Set python_executable to 'vpython' in order to allow scripts in other
613 # repos (e.g. src.git) to automatically pick up that repo's .vpython file,
614 # instead of inheriting the one in depot_tools.
615 self.python_executable = 'vpython'
maruel@chromium.orgc0b22972009-06-25 16:19:14 +0000616 self.environ = os.environ
617
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000618 # InputApi.platform is the platform you're currently running on.
619 self.platform = sys.platform
620
iannucci@chromium.org0af3bb32015-06-12 20:44:35 +0000621 self.cpu_count = multiprocessing.cpu_count()
622
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000623 # The local path of the currently-being-processed presubmit script.
maruel@chromium.org3d235242009-05-15 12:40:48 +0000624 self._current_presubmit_path = os.path.dirname(presubmit_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000625
626 # We carry the canned checks so presubmit scripts can easily use them.
627 self.canned_checks = presubmit_canned_checks
628
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +0100629 # Temporary files we must manually remove at the end of a run.
630 self._named_temporary_files = []
Jochen Eisinger72606f82017-04-04 10:44:18 +0200631
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000632 # TODO(dpranke): figure out a list of all approved owners for a repo
633 # in order to be able to handle wildcard OWNERS files?
634 self.owners_db = owners.Database(change.RepositoryRoot(),
Edward Lemurb9830242019-10-30 22:19:20 +0000635 fopen=open, os_path=self.os_path)
Jochen Eisinger76f5fc62017-04-07 16:27:46 +0200636 self.owners_finder = owners_finder.OwnersFinder
maruel@chromium.org899e1c12011-04-07 17:03:18 +0000637 self.verbose = verbose
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000638 self.Command = CommandData
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000639
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000640 # Replace <hash_map> and <hash_set> as headers that need to be included
Edward Lemura5799e32020-01-17 19:26:51 +0000641 # with 'base/containers/hash_tables.h' instead.
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000642 # Access to a protected member _XX of a client class
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800643 # pylint: disable=protected-access
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000644 self.cpplint._re_pattern_templates = [
danakj@chromium.org18278522013-06-11 22:42:32 +0000645 (a, b, 'base/containers/hash_tables.h')
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000646 if header in ('<hash_map>', '<hash_set>') else (a, b, header)
647 for (a, b, header) in cpplint._re_pattern_templates
648 ]
649
Edward Lemurecc27072020-01-06 16:42:34 +0000650 def SetTimeout(self, timeout):
651 self.thread_pool.timeout = timeout
652
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000653 def PresubmitLocalPath(self):
654 """Returns the local path of the presubmit script currently being run.
655
656 This is useful if you don't want to hard-code absolute paths in the
657 presubmit script. For example, It can be used to find another file
658 relative to the PRESUBMIT.py script, so the whole tree can be branched and
659 the presubmit script still works, without editing its content.
660 """
maruel@chromium.org3d235242009-05-15 12:40:48 +0000661 return self._current_presubmit_path
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000662
agable0b65e732016-11-22 09:25:46 -0800663 def AffectedFiles(self, include_deletes=True, file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000664 """Same as input_api.change.AffectedFiles() except only lists files
665 (and optionally directories) in the same directory as the current presubmit
666 script, or subdirectories thereof.
667 """
Edward Lemura5799e32020-01-17 19:26:51 +0000668 dir_with_slash = normpath('%s/' % self.PresubmitLocalPath())
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000669 if len(dir_with_slash) == 1:
670 dir_with_slash = ''
sail@chromium.org5538e022011-05-12 17:53:16 +0000671
Edward Lemurb9830242019-10-30 22:19:20 +0000672 return list(filter(
maruel@chromium.org4661e0c2009-06-04 00:45:26 +0000673 lambda x: normpath(x.AbsoluteLocalPath()).startswith(dir_with_slash),
Edward Lemurb9830242019-10-30 22:19:20 +0000674 self.change.AffectedFiles(include_deletes, file_filter)))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000675
agable0b65e732016-11-22 09:25:46 -0800676 def LocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000677 """Returns local paths of input_api.AffectedFiles()."""
agable0b65e732016-11-22 09:25:46 -0800678 paths = [af.LocalPath() for af in self.AffectedFiles()]
Edward Lemura5799e32020-01-17 19:26:51 +0000679 logging.debug('LocalPaths: %s', paths)
pgervais@chromium.org2f64f782014-04-25 00:12:33 +0000680 return paths
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000681
agable0b65e732016-11-22 09:25:46 -0800682 def AbsoluteLocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000683 """Returns absolute local paths of input_api.AffectedFiles()."""
agable0b65e732016-11-22 09:25:46 -0800684 return [af.AbsoluteLocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000685
John Budorick16162372018-04-18 10:39:53 -0700686 def AffectedTestableFiles(self, include_deletes=None, **kwargs):
agable0b65e732016-11-22 09:25:46 -0800687 """Same as input_api.change.AffectedTestableFiles() except only lists files
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000688 in the same directory as the current presubmit script, or subdirectories
689 thereof.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000690 """
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000691 if include_deletes is not None:
Edward Lemura5799e32020-01-17 19:26:51 +0000692 warn('AffectedTestableFiles(include_deletes=%s)'
693 ' is deprecated and ignored' % str(include_deletes),
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000694 category=DeprecationWarning,
695 stacklevel=2)
Edward Lemurb9830242019-10-30 22:19:20 +0000696 return list(filter(
697 lambda x: x.IsTestableFile(),
698 self.AffectedFiles(include_deletes=False, **kwargs)))
agable0b65e732016-11-22 09:25:46 -0800699
700 def AffectedTextFiles(self, include_deletes=None):
701 """An alias to AffectedTestableFiles for backwards compatibility."""
702 return self.AffectedTestableFiles(include_deletes=include_deletes)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000703
maruel@chromium.org3410d912009-06-09 20:56:16 +0000704 def FilterSourceFile(self, affected_file, white_list=None, black_list=None):
Edward Lemura5799e32020-01-17 19:26:51 +0000705 """Filters out files that aren't considered 'source file'.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000706
707 If white_list or black_list is None, InputApi.DEFAULT_WHITE_LIST
708 and InputApi.DEFAULT_BLACK_LIST is used respectively.
709
710 The lists will be compiled as regular expression and
711 AffectedFile.LocalPath() needs to pass both list.
712
713 Note: Copy-paste this function to suit your needs or use a lambda function.
714 """
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000715 def Find(affected_file, items):
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000716 local_path = affected_file.LocalPath()
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000717 for item in items:
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000718 if self.re.match(item, local_path):
maruel@chromium.org3410d912009-06-09 20:56:16 +0000719 return True
720 return False
721 return (Find(affected_file, white_list or self.DEFAULT_WHITE_LIST) and
722 not Find(affected_file, black_list or self.DEFAULT_BLACK_LIST))
723
724 def AffectedSourceFiles(self, source_file):
agable0b65e732016-11-22 09:25:46 -0800725 """Filter the list of AffectedTestableFiles by the function source_file.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000726
727 If source_file is None, InputApi.FilterSourceFile() is used.
728 """
729 if not source_file:
730 source_file = self.FilterSourceFile
Edward Lemurb9830242019-10-30 22:19:20 +0000731 return list(filter(source_file, self.AffectedTestableFiles()))
maruel@chromium.org3410d912009-06-09 20:56:16 +0000732
733 def RightHandSideLines(self, source_file_filter=None):
Edward Lemura5799e32020-01-17 19:26:51 +0000734 """An iterator over all text lines in 'new' version of changed files.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000735
736 Only lists lines from new or modified text files in the change that are
737 contained by the directory of the currently executing presubmit script.
738
739 This is useful for doing line-by-line regex checks, like checking for
740 trailing whitespace.
741
742 Yields:
743 a 3 tuple:
744 the AffectedFile instance of the current file;
745 integer line number (1-based); and
746 the contents of the line as a string.
maruel@chromium.org1487d532009-06-06 00:22:57 +0000747
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000748 Note: The carriage return (LF or CR) is stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000749 """
maruel@chromium.org3410d912009-06-09 20:56:16 +0000750 files = self.AffectedSourceFiles(source_file_filter)
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000751 return _RightHandSideLinesImpl(files)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000752
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000753 def ReadFile(self, file_item, mode='r'):
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000754 """Reads an arbitrary file.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000755
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000756 Deny reading anything outside the repository.
757 """
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000758 if isinstance(file_item, AffectedFile):
759 file_item = file_item.AbsoluteLocalPath()
760 if not file_item.startswith(self.change.RepositoryRoot()):
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000761 raise IOError('Access outside the repository root is denied.')
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000762 return gclient_utils.FileRead(file_item, mode)
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000763
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +0100764 def CreateTemporaryFile(self, **kwargs):
765 """Returns a named temporary file that must be removed with a call to
766 RemoveTemporaryFiles().
767
768 All keyword arguments are forwarded to tempfile.NamedTemporaryFile(),
769 except for |delete|, which is always set to False.
770
771 Presubmit checks that need to create a temporary file and pass it for
772 reading should use this function instead of NamedTemporaryFile(), as
773 Windows fails to open a file that is already open for writing.
774
775 with input_api.CreateTemporaryFile() as f:
776 f.write('xyz')
777 f.close()
778 input_api.subprocess.check_output(['script-that', '--reads-from',
779 f.name])
780
781
782 Note that callers of CreateTemporaryFile() should not worry about removing
783 any temporary file; this is done transparently by the presubmit handling
784 code.
785 """
786 if 'delete' in kwargs:
787 # Prevent users from passing |delete|; we take care of file deletion
788 # ourselves and this prevents unintuitive error messages when we pass
789 # delete=False and 'delete' is also in kwargs.
790 raise TypeError('CreateTemporaryFile() does not take a "delete" '
791 'argument, file deletion is handled automatically by '
792 'the same presubmit_support code that creates InputApi '
793 'objects.')
794 temp_file = self.tempfile.NamedTemporaryFile(delete=False, **kwargs)
795 self._named_temporary_files.append(temp_file.name)
796 return temp_file
797
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000798 @property
799 def tbr(self):
800 """Returns if a change is TBR'ed."""
Jeremy Romandce22502017-06-20 15:37:29 -0400801 return 'TBR' in self.change.tags or self.change.TBRsFromDescription()
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000802
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +0000803 def RunTests(self, tests_mix, parallel=True):
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000804 tests = []
805 msgs = []
806 for t in tests_mix:
Edward Lesmes8e282792018-04-03 18:50:29 -0400807 if isinstance(t, OutputApi.PresubmitResult) and t:
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000808 msgs.append(t)
809 else:
810 assert issubclass(t.message, _PresubmitResult)
811 tests.append(t)
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +0000812 if self.verbose:
813 t.info = _PresubmitNotifyResult
Edward Lemur1037c742018-05-01 18:56:04 -0400814 if not t.kwargs.get('cwd'):
815 t.kwargs['cwd'] = self.PresubmitLocalPath()
Edward Lesmes8e282792018-04-03 18:50:29 -0400816 self.thread_pool.AddTests(tests, parallel)
Edward Lemur21000eb2019-05-24 23:25:58 +0000817 # When self.parallel is True (i.e. --parallel is passed as an option)
818 # RunTests doesn't actually run tests. It adds them to a ThreadPool that
819 # will run all tests once all PRESUBMIT files are processed.
820 # Otherwise, it will run them and return the results.
821 if not self.parallel:
Edward Lesmes8e282792018-04-03 18:50:29 -0400822 msgs.extend(self.thread_pool.RunAsync())
823 return msgs
scottmg86099d72016-09-01 09:16:51 -0700824
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000825
nick@chromium.orgff526192013-06-10 19:30:26 +0000826class _DiffCache(object):
827 """Caches diffs retrieved from a particular SCM."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000828 def __init__(self, upstream=None):
829 """Stores the upstream revision against which all diffs will be computed."""
830 self._upstream = upstream
nick@chromium.orgff526192013-06-10 19:30:26 +0000831
832 def GetDiff(self, path, local_root):
833 """Get the diff for a particular path."""
834 raise NotImplementedError()
835
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700836 def GetOldContents(self, path, local_root):
837 """Get the old version for a particular path."""
838 raise NotImplementedError()
839
nick@chromium.orgff526192013-06-10 19:30:26 +0000840
nick@chromium.orgff526192013-06-10 19:30:26 +0000841class _GitDiffCache(_DiffCache):
842 """DiffCache implementation for git; gets all file diffs at once."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000843 def __init__(self, upstream):
844 super(_GitDiffCache, self).__init__(upstream=upstream)
nick@chromium.orgff526192013-06-10 19:30:26 +0000845 self._diffs_by_file = None
846
847 def GetDiff(self, path, local_root):
848 if not self._diffs_by_file:
849 # Compute a single diff for all files and parse the output; should
850 # with git this is much faster than computing one diff for each file.
851 diffs = {}
852
853 # Don't specify any filenames below, because there are command line length
854 # limits on some platforms and GenerateDiff would fail.
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000855 unified_diff = scm.GIT.GenerateDiff(local_root, files=[], full_move=True,
856 branch=self._upstream)
nick@chromium.orgff526192013-06-10 19:30:26 +0000857
858 # This regex matches the path twice, separated by a space. Note that
859 # filename itself may contain spaces.
860 file_marker = re.compile('^diff --git (?P<filename>.*) (?P=filename)$')
861 current_diff = []
862 keep_line_endings = True
863 for x in unified_diff.splitlines(keep_line_endings):
864 match = file_marker.match(x)
865 if match:
866 # Marks the start of a new per-file section.
867 diffs[match.group('filename')] = current_diff = [x]
868 elif x.startswith('diff --git'):
869 raise PresubmitFailure('Unexpected diff line: %s' % x)
870 else:
871 current_diff.append(x)
872
873 self._diffs_by_file = dict(
874 (normpath(path), ''.join(diff)) for path, diff in diffs.items())
875
876 if path not in self._diffs_by_file:
877 raise PresubmitFailure(
878 'Unified diff did not contain entry for file %s' % path)
879
880 return self._diffs_by_file[path]
881
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700882 def GetOldContents(self, path, local_root):
883 return scm.GIT.GetOldContents(local_root, path, branch=self._upstream)
884
nick@chromium.orgff526192013-06-10 19:30:26 +0000885
Yannic Bonenberger68409632020-01-23 18:29:01 +0000886def _ParseDiffHeader(line):
887 """Searches |line| for diff headers and returns a tuple
888 (header, old_line, old_size, new_line, new_size), or None if line doesn't
889 contain a diff header.
890
891 This relies on the scm diff output describing each changed code section
892 with a line of the form
893
894 ^@@ <old line num>,<old size> <new line num>,<new size> @@$
895 """
896 m = re.match(r'^@@ \-([0-9]+)\,([0-9]+) \+([0-9]+)\,([0-9]+) @@', line)
897 if m:
898 return (m.group(0), int(m.group(1)), int(m.group(2)), int(m.group(3)),
899 int(m.group(4)))
900
901
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000902class AffectedFile(object):
903 """Representation of a file in a change."""
nick@chromium.orgff526192013-06-10 19:30:26 +0000904
905 DIFF_CACHE = _DiffCache
906
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000907 # Method could be a function
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800908 # pylint: disable=no-self-use
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000909 def __init__(self, path, action, repository_root, diff_cache):
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000910 self._path = path
911 self._action = action
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000912 self._local_root = repository_root
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000913 self._is_directory = None
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000914 self._cached_changed_contents = None
Yannic Bonenberger68409632020-01-23 18:29:01 +0000915 self._cached_change_size_in_bytes = None
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000916 self._cached_new_contents = None
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000917 self._diff_cache = diff_cache
tobiasjs2836bcf2016-08-16 04:08:16 -0700918 logging.debug('%s(%s)', self.__class__.__name__, self._path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000919
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000920 def LocalPath(self):
921 """Returns the path of this file on the local disk relative to client root.
Andrew Grieve92b8b992017-11-02 09:42:24 -0400922
923 This should be used for error messages but not for accessing files,
924 because presubmit checks are run with CWD=PresubmitLocalPath() (which is
925 often != client root).
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000926 """
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000927 return normpath(self._path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000928
929 def AbsoluteLocalPath(self):
930 """Returns the absolute path of this file on the local disk.
931 """
chase@chromium.org8e416c82009-10-06 04:30:44 +0000932 return os.path.abspath(os.path.join(self._local_root, self.LocalPath()))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000933
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000934 def Action(self):
935 """Returns the action on this opened file, e.g. A, M, D, etc."""
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000936 return self._action
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000937
agable0b65e732016-11-22 09:25:46 -0800938 def IsTestableFile(self):
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000939 """Returns True if the file is a text file and not a binary file.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000940
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000941 Deleted files are not text file."""
maruel@chromium.org1e08c002009-05-28 19:09:33 +0000942 raise NotImplementedError() # Implement when needed
943
agable0b65e732016-11-22 09:25:46 -0800944 def IsTextFile(self):
945 """An alias to IsTestableFile for backwards compatibility."""
946 return self.IsTestableFile()
947
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700948 def OldContents(self):
949 """Returns an iterator over the lines in the old version of file.
950
Daniel Cheng2da34fe2017-03-21 20:42:12 -0700951 The old version is the file before any modifications in the user's
Edward Lemura5799e32020-01-17 19:26:51 +0000952 workspace, i.e. the 'left hand side'.
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700953
954 Contents will be empty if the file is a directory or does not exist.
955 Note: The carriage returns (LF or CR) are stripped off.
956 """
957 return self._diff_cache.GetOldContents(self.LocalPath(),
958 self._local_root).splitlines()
959
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000960 def NewContents(self):
961 """Returns an iterator over the lines in the new version of file.
962
Edward Lemura5799e32020-01-17 19:26:51 +0000963 The new version is the file in the user's workspace, i.e. the 'right hand
964 side'.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000965
966 Contents will be empty if the file is a directory or does not exist.
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000967 Note: The carriage returns (LF or CR) are stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000968 """
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000969 if self._cached_new_contents is None:
970 self._cached_new_contents = []
agable0b65e732016-11-22 09:25:46 -0800971 try:
972 self._cached_new_contents = gclient_utils.FileRead(
973 self.AbsoluteLocalPath(), 'rU').splitlines()
974 except IOError:
975 pass # File not found? That's fine; maybe it was deleted.
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000976 return self._cached_new_contents[:]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000977
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000978 def ChangedContents(self):
979 """Returns a list of tuples (line number, line text) of all new lines.
980
981 This relies on the scm diff output describing each changed code section
982 with a line of the form
983
984 ^@@ <old line num>,<old size> <new line num>,<new size> @@$
985 """
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000986 if self._cached_changed_contents is not None:
987 return self._cached_changed_contents[:]
988 self._cached_changed_contents = []
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000989 line_num = 0
990
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000991 for line in self.GenerateScmDiff().splitlines():
Yannic Bonenberger68409632020-01-23 18:29:01 +0000992 h = _ParseDiffHeader(line)
993 if h:
994 line_num = h[3]
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000995 continue
996 if line.startswith('+') and not line.startswith('++'):
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000997 self._cached_changed_contents.append((line_num, line[1:]))
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000998 if not line.startswith('-'):
999 line_num += 1
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +00001000 return self._cached_changed_contents[:]
maruel@chromium.orgab05d582011-02-09 23:41:22 +00001001
Yannic Bonenberger68409632020-01-23 18:29:01 +00001002 def ChangeSizeInBytes(self):
1003 """Returns a list of tuples (deleted bytes, added bytes) of all changes
1004 in this file.
1005
1006 This relies on the scm diff output describing each changed code section
1007 with a line of the form
1008
1009 ^@@ <old line num>,<old size> <new line num>,<new size> @@$
1010 """
1011 if self._cached_change_size_in_bytes is not None:
1012 return self._cached_change_size_in_bytes[:]
1013 self._cached_change_size_in_bytes = []
1014
1015 for line in self.GenerateScmDiff().splitlines():
1016 h = _ParseDiffHeader(line)
1017 if h:
1018 self._cached_change_size_in_bytes.append((h[2], h[4]))
1019 return self._cached_change_size_in_bytes[:]
1020
maruel@chromium.org5de13972009-06-10 18:16:06 +00001021 def __str__(self):
1022 return self.LocalPath()
1023
maruel@chromium.orgab05d582011-02-09 23:41:22 +00001024 def GenerateScmDiff(self):
nick@chromium.orgff526192013-06-10 19:30:26 +00001025 return self._diff_cache.GetDiff(self.LocalPath(), self._local_root)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001026
maruel@chromium.org58407af2011-04-12 23:15:57 +00001027
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001028class GitAffectedFile(AffectedFile):
1029 """Representation of a file in a change out of a git checkout."""
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +00001030 # Method 'NNN' is abstract in class 'NNN' but is not overridden
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -08001031 # pylint: disable=abstract-method
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001032
nick@chromium.orgff526192013-06-10 19:30:26 +00001033 DIFF_CACHE = _GitDiffCache
1034
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001035 def __init__(self, *args, **kwargs):
1036 AffectedFile.__init__(self, *args, **kwargs)
1037 self._server_path = None
agable0b65e732016-11-22 09:25:46 -08001038 self._is_testable_file = None
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001039
agable0b65e732016-11-22 09:25:46 -08001040 def IsTestableFile(self):
1041 if self._is_testable_file is None:
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001042 if self.Action() == 'D':
agable0b65e732016-11-22 09:25:46 -08001043 # A deleted file is not testable.
1044 self._is_testable_file = False
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001045 else:
agable0b65e732016-11-22 09:25:46 -08001046 self._is_testable_file = os.path.isfile(self.AbsoluteLocalPath())
1047 return self._is_testable_file
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001048
maruel@chromium.orgc1938752011-04-12 23:11:13 +00001049
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001050class Change(object):
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001051 """Describe a change.
1052
1053 Used directly by the presubmit scripts to query the current change being
1054 tested.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +00001055
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001056 Instance members:
nick@chromium.orgff526192013-06-10 19:30:26 +00001057 tags: Dictionary of KEY=VALUE pairs found in the change description.
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001058 self.KEY: equivalent to tags['KEY']
1059 """
1060
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001061 _AFFECTED_FILES = AffectedFile
1062
Edward Lemura5799e32020-01-17 19:26:51 +00001063 # Matches key/value (or 'tag') lines in changelist descriptions.
maruel@chromium.org428342a2011-11-10 15:46:33 +00001064 TAG_LINE_RE = re.compile(
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001065 '^[ \t]*(?P<key>[A-Z][A-Z_0-9]*)[ \t]*=[ \t]*(?P<value>.*?)[ \t]*$')
maruel@chromium.orgc1938752011-04-12 23:11:13 +00001066 scm = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001067
maruel@chromium.org58407af2011-04-12 23:15:57 +00001068 def __init__(
agable@chromium.orgea84ef12014-04-30 19:55:12 +00001069 self, name, description, local_root, files, issue, patchset, author,
1070 upstream=None):
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001071 if files is None:
1072 files = []
1073 self._name = name
chase@chromium.org8e416c82009-10-06 04:30:44 +00001074 # Convert root into an absolute path.
1075 self._local_root = os.path.abspath(local_root)
agable@chromium.orgea84ef12014-04-30 19:55:12 +00001076 self._upstream = upstream
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001077 self.issue = issue
1078 self.patchset = patchset
maruel@chromium.org58407af2011-04-12 23:15:57 +00001079 self.author_email = author
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001080
isherman@chromium.orgb5cded62014-03-25 17:47:57 +00001081 self._full_description = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001082 self.tags = {}
isherman@chromium.orgb5cded62014-03-25 17:47:57 +00001083 self._description_without_tags = ''
1084 self.SetDescriptionText(description)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001085
maruel@chromium.orge085d812011-10-10 19:49:15 +00001086 assert all(
1087 (isinstance(f, (list, tuple)) and len(f) == 2) for f in files), files
1088
agable@chromium.orgea84ef12014-04-30 19:55:12 +00001089 diff_cache = self._AFFECTED_FILES.DIFF_CACHE(self._upstream)
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001090 self._affected_files = [
nick@chromium.orgff526192013-06-10 19:30:26 +00001091 self._AFFECTED_FILES(path, action.strip(), self._local_root, diff_cache)
1092 for action, path in files
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +00001093 ]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001094
maruel@chromium.org92022ec2009-06-11 01:59:28 +00001095 def Name(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001096 """Returns the change name."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001097 return self._name
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001098
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001099 def DescriptionText(self):
1100 """Returns the user-entered changelist description, minus tags.
1101
Edward Lemura5799e32020-01-17 19:26:51 +00001102 Any line in the user-provided description starting with e.g. 'FOO='
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001103 (whitespace permitted before and around) is considered a tag line. Such
1104 lines are stripped out of the description this function returns.
1105 """
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001106 return self._description_without_tags
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001107
1108 def FullDescriptionText(self):
1109 """Returns the complete changelist description including tags."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001110 return self._full_description
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001111
isherman@chromium.orgb5cded62014-03-25 17:47:57 +00001112 def SetDescriptionText(self, description):
1113 """Sets the full description text (including tags) to |description|.
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001114
isherman@chromium.orgb5cded62014-03-25 17:47:57 +00001115 Also updates the list of tags."""
1116 self._full_description = description
1117
1118 # From the description text, build up a dictionary of key/value pairs
Edward Lemura5799e32020-01-17 19:26:51 +00001119 # plus the description minus all key/value or 'tag' lines.
isherman@chromium.orgb5cded62014-03-25 17:47:57 +00001120 description_without_tags = []
1121 self.tags = {}
1122 for line in self._full_description.splitlines():
1123 m = self.TAG_LINE_RE.match(line)
1124 if m:
1125 self.tags[m.group('key')] = m.group('value')
1126 else:
1127 description_without_tags.append(line)
1128
1129 # Change back to text and remove whitespace at end.
1130 self._description_without_tags = (
1131 '\n'.join(description_without_tags).rstrip())
1132
Edward Lemur69bb8be2020-02-03 20:37:38 +00001133 def AddDescriptionFooter(self, key, value):
1134 """Adds the given footer to the change description.
1135
1136 Args:
1137 key: A string with the key for the git footer. It must conform to
1138 the git footers format (i.e. 'List-Of-Tokens') and will be case
1139 normalized so that each token is title-cased.
1140 value: A string with the value for the git footer.
1141 """
1142 description = git_footers.add_footer(
1143 self.FullDescriptionText(), git_footers.normalize_name(key), value)
1144 self.SetDescriptionText(description)
1145
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001146 def RepositoryRoot(self):
maruel@chromium.org92022ec2009-06-11 01:59:28 +00001147 """Returns the repository (checkout) root directory for this change,
1148 as an absolute path.
1149 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001150 return self._local_root
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001151
1152 def __getattr__(self, attr):
maruel@chromium.org92022ec2009-06-11 01:59:28 +00001153 """Return tags directly as attributes on the object."""
Edward Lemura5799e32020-01-17 19:26:51 +00001154 if not re.match(r'^[A-Z_]*$', attr):
maruel@chromium.org92022ec2009-06-11 01:59:28 +00001155 raise AttributeError(self, attr)
maruel@chromium.orge1a524f2009-05-27 14:43:46 +00001156 return self.tags.get(attr)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001157
Edward Lemur69bb8be2020-02-03 20:37:38 +00001158 def GitFootersFromDescription(self):
1159 """Return the git footers present in the description.
1160
1161 Returns:
1162 footers: A dict of {footer: [values]} containing a multimap of the footers
1163 in the change description.
1164 """
1165 return git_footers.parse_footers(self.FullDescriptionText())
1166
Aaron Gablefc03e672017-05-15 14:09:42 -07001167 def BugsFromDescription(self):
1168 """Returns all bugs referenced in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -07001169 tags = [b.strip() for b in self.tags.get('BUG', '').split(',') if b.strip()]
Caleb Rouleauc0546b92019-02-22 06:12:57 +00001170 footers = []
Edward Lemur69bb8be2020-02-03 20:37:38 +00001171 parsed = self.GitFootersFromDescription()
Dan Beam62954042019-10-03 21:20:33 +00001172 unsplit_footers = parsed.get('Bug', []) + parsed.get('Fixed', [])
Caleb Rouleauc0546b92019-02-22 06:12:57 +00001173 for unsplit_footer in unsplit_footers:
1174 footers += [b.strip() for b in unsplit_footer.split(',')]
Aaron Gable12ef5012017-05-15 14:29:00 -07001175 return sorted(set(tags + footers))
Aaron Gablefc03e672017-05-15 14:09:42 -07001176
1177 def ReviewersFromDescription(self):
1178 """Returns all reviewers listed in the commit description."""
Edward Lemura5799e32020-01-17 19:26:51 +00001179 # We don't support a 'R:' git-footer for reviewers; that is in metadata.
Aaron Gable12ef5012017-05-15 14:29:00 -07001180 tags = [r.strip() for r in self.tags.get('R', '').split(',') if r.strip()]
1181 return sorted(set(tags))
Aaron Gablefc03e672017-05-15 14:09:42 -07001182
1183 def TBRsFromDescription(self):
1184 """Returns all TBR reviewers listed in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -07001185 tags = [r.strip() for r in self.tags.get('TBR', '').split(',') if r.strip()]
1186 # TODO(agable): Remove support for 'Tbr:' when TBRs are programmatically
1187 # determined by self-CR+1s.
Edward Lemur69bb8be2020-02-03 20:37:38 +00001188 footers = self.GitFootersFromDescription().get('Tbr', [])
Aaron Gable12ef5012017-05-15 14:29:00 -07001189 return sorted(set(tags + footers))
Aaron Gablefc03e672017-05-15 14:09:42 -07001190
1191 # TODO(agable): Delete these once we're sure they're unused.
1192 @property
1193 def BUG(self):
1194 return ','.join(self.BugsFromDescription())
1195 @property
1196 def R(self):
1197 return ','.join(self.ReviewersFromDescription())
1198 @property
1199 def TBR(self):
1200 return ','.join(self.TBRsFromDescription())
1201
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001202 def AllFiles(self, root=None):
1203 """List all files under source control in the repo."""
1204 raise NotImplementedError()
1205
agable0b65e732016-11-22 09:25:46 -08001206 def AffectedFiles(self, include_deletes=True, file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001207 """Returns a list of AffectedFile instances for all files in the change.
1208
1209 Args:
1210 include_deletes: If false, deleted files will be filtered out.
sail@chromium.org5538e022011-05-12 17:53:16 +00001211 file_filter: An additional filter to apply.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001212
1213 Returns:
1214 [AffectedFile(path, action), AffectedFile(path, action)]
1215 """
Edward Lemurb9830242019-10-30 22:19:20 +00001216 affected = list(filter(file_filter, self._affected_files))
sail@chromium.org5538e022011-05-12 17:53:16 +00001217
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001218 if include_deletes:
1219 return affected
Edward Lemurb9830242019-10-30 22:19:20 +00001220 return list(filter(lambda x: x.Action() != 'D', affected))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001221
John Budorick16162372018-04-18 10:39:53 -07001222 def AffectedTestableFiles(self, include_deletes=None, **kwargs):
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +00001223 """Return a list of the existing text files in a change."""
1224 if include_deletes is not None:
Edward Lemura5799e32020-01-17 19:26:51 +00001225 warn('AffectedTeestableFiles(include_deletes=%s)'
1226 ' is deprecated and ignored' % str(include_deletes),
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +00001227 category=DeprecationWarning,
1228 stacklevel=2)
Edward Lemurb9830242019-10-30 22:19:20 +00001229 return list(filter(
1230 lambda x: x.IsTestableFile(),
1231 self.AffectedFiles(include_deletes=False, **kwargs)))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001232
agable0b65e732016-11-22 09:25:46 -08001233 def AffectedTextFiles(self, include_deletes=None):
1234 """An alias to AffectedTestableFiles for backwards compatibility."""
1235 return self.AffectedTestableFiles(include_deletes=include_deletes)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001236
agable0b65e732016-11-22 09:25:46 -08001237 def LocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001238 """Convenience function."""
agable0b65e732016-11-22 09:25:46 -08001239 return [af.LocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001240
agable0b65e732016-11-22 09:25:46 -08001241 def AbsoluteLocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001242 """Convenience function."""
agable0b65e732016-11-22 09:25:46 -08001243 return [af.AbsoluteLocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001244
1245 def RightHandSideLines(self):
Edward Lemura5799e32020-01-17 19:26:51 +00001246 """An iterator over all text lines in 'new' version of changed files.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001247
1248 Lists lines from new or modified text files in the change.
1249
1250 This is useful for doing line-by-line regex checks, like checking for
1251 trailing whitespace.
1252
1253 Yields:
1254 a 3 tuple:
1255 the AffectedFile instance of the current file;
1256 integer line number (1-based); and
1257 the contents of the line as a string.
1258 """
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +00001259 return _RightHandSideLinesImpl(
1260 x for x in self.AffectedFiles(include_deletes=False)
agable0b65e732016-11-22 09:25:46 -08001261 if x.IsTestableFile())
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001262
Jochen Eisingerd0573ec2017-04-13 10:55:06 +02001263 def OriginalOwnersFiles(self):
1264 """A map from path names of affected OWNERS files to their old content."""
1265 def owners_file_filter(f):
1266 return 'OWNERS' in os.path.split(f.LocalPath())[1]
1267 files = self.AffectedFiles(file_filter=owners_file_filter)
1268 return dict([(f.LocalPath(), f.OldContents()) for f in files])
1269
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001270
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001271class GitChange(Change):
1272 _AFFECTED_FILES = GitAffectedFile
maruel@chromium.orgc1938752011-04-12 23:11:13 +00001273 scm = 'git'
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +00001274
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001275 def AllFiles(self, root=None):
1276 """List all files under source control in the repo."""
1277 root = root or self.RepositoryRoot()
1278 return subprocess.check_output(
Aaron Gable7817f022017-12-12 09:43:17 -08001279 ['git', '-c', 'core.quotePath=false', 'ls-files', '--', '.'],
1280 cwd=root).splitlines()
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001281
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001282
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001283def ListRelevantPresubmitFiles(files, root):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001284 """Finds all presubmit files that apply to a given set of source files.
1285
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001286 If inherit-review-settings-ok is present right under root, looks for
1287 PRESUBMIT.py in directories enclosing root.
1288
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001289 Args:
1290 files: An iterable container containing file paths.
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001291 root: Path where to stop searching.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001292
1293 Return:
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001294 List of absolute paths of the existing PRESUBMIT.py scripts.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001295 """
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001296 files = [normpath(os.path.join(root, f)) for f in files]
1297
1298 # List all the individual directories containing files.
1299 directories = set([os.path.dirname(f) for f in files])
1300
1301 # Ignore root if inherit-review-settings-ok is present.
1302 if os.path.isfile(os.path.join(root, 'inherit-review-settings-ok')):
1303 root = None
1304
1305 # Collect all unique directories that may contain PRESUBMIT.py.
1306 candidates = set()
1307 for directory in directories:
1308 while True:
1309 if directory in candidates:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001310 break
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001311 candidates.add(directory)
1312 if directory == root:
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001313 break
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001314 parent_dir = os.path.dirname(directory)
1315 if parent_dir == directory:
1316 # We hit the system root directory.
1317 break
1318 directory = parent_dir
1319
1320 # Look for PRESUBMIT.py in all candidate directories.
1321 results = []
1322 for directory in sorted(list(candidates)):
tobiasjsff061c02016-08-17 03:23:57 -07001323 try:
1324 for f in os.listdir(directory):
1325 p = os.path.join(directory, f)
1326 if os.path.isfile(p) and re.match(
1327 r'PRESUBMIT.*\.py$', f) and not f.startswith('PRESUBMIT_test'):
1328 results.append(p)
1329 except OSError:
1330 pass
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001331
tobiasjs2836bcf2016-08-16 04:08:16 -07001332 logging.debug('Presubmit files: %s', ','.join(results))
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001333 return results
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001334
1335
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001336class GetTryMastersExecuter(object):
1337 @staticmethod
1338 def ExecPresubmitScript(script_text, presubmit_path, project, change):
1339 """Executes GetPreferredTryMasters() from a single presubmit script.
1340
1341 Args:
1342 script_text: The text of the presubmit script.
1343 presubmit_path: Project script to run.
1344 project: Project name to pass to presubmit script for bot selection.
1345
1346 Return:
1347 A map of try masters to map of builders to set of tests.
1348 """
1349 context = {}
1350 try:
Raul Tambre09e64b42019-05-14 01:57:22 +00001351 exec(compile(script_text, 'PRESUBMIT.py', 'exec', dont_inherit=True),
1352 context)
Raul Tambre7c938462019-05-24 16:35:35 +00001353 except Exception as e:
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001354 raise PresubmitFailure('"%s" had an exception.\n%s'
1355 % (presubmit_path, e))
1356
1357 function_name = 'GetPreferredTryMasters'
1358 if function_name not in context:
1359 return {}
1360 get_preferred_try_masters = context[function_name]
1361 if not len(inspect.getargspec(get_preferred_try_masters)[0]) == 2:
1362 raise PresubmitFailure(
1363 'Expected function "GetPreferredTryMasters" to take two arguments.')
1364 return get_preferred_try_masters(project, change)
1365
1366
rmistry@google.com5626a922015-02-26 14:03:30 +00001367class GetPostUploadExecuter(object):
1368 @staticmethod
1369 def ExecPresubmitScript(script_text, presubmit_path, cl, change):
1370 """Executes PostUploadHook() from a single presubmit script.
1371
1372 Args:
1373 script_text: The text of the presubmit script.
1374 presubmit_path: Project script to run.
1375 cl: The Changelist object.
1376 change: The Change object.
1377
1378 Return:
1379 A list of results objects.
1380 """
1381 context = {}
1382 try:
Raul Tambre09e64b42019-05-14 01:57:22 +00001383 exec(compile(script_text, 'PRESUBMIT.py', 'exec', dont_inherit=True),
1384 context)
Raul Tambre7c938462019-05-24 16:35:35 +00001385 except Exception as e:
rmistry@google.com5626a922015-02-26 14:03:30 +00001386 raise PresubmitFailure('"%s" had an exception.\n%s'
1387 % (presubmit_path, e))
1388
1389 function_name = 'PostUploadHook'
1390 if function_name not in context:
1391 return {}
1392 post_upload_hook = context[function_name]
1393 if not len(inspect.getargspec(post_upload_hook)[0]) == 3:
1394 raise PresubmitFailure(
1395 'Expected function "PostUploadHook" to take three arguments.')
1396 return post_upload_hook(cl, change, OutputApi(False))
1397
1398
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001399def _MergeMasters(masters1, masters2):
1400 """Merges two master maps. Merges also the tests of each builder."""
1401 result = {}
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00001402 for (master, builders) in itertools.chain(masters1.items(),
1403 masters2.items()):
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001404 new_builders = result.setdefault(master, {})
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00001405 for (builder, tests) in builders.items():
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001406 new_builders.setdefault(builder, set([])).update(tests)
1407 return result
1408
1409
1410def DoGetTryMasters(change,
1411 changed_files,
1412 repository_root,
1413 default_presubmit,
1414 project,
1415 verbose,
1416 output_stream):
1417 """Get the list of try masters from the presubmit scripts.
1418
1419 Args:
1420 changed_files: List of modified files.
1421 repository_root: The repository root.
1422 default_presubmit: A default presubmit script to execute in any case.
1423 project: Optional name of a project used in selecting trybots.
1424 verbose: Prints debug info.
1425 output_stream: A stream to write debug output to.
1426
1427 Return:
1428 Map of try masters to map of builders to set of tests.
1429 """
1430 presubmit_files = ListRelevantPresubmitFiles(changed_files, repository_root)
1431 if not presubmit_files and verbose:
Edward Lemura5799e32020-01-17 19:26:51 +00001432 output_stream.write('Warning, no PRESUBMIT.py found.\n')
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001433 results = {}
1434 executer = GetTryMastersExecuter()
1435
1436 if default_presubmit:
1437 if verbose:
Edward Lemura5799e32020-01-17 19:26:51 +00001438 output_stream.write('Running default presubmit script.\n')
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001439 fake_path = os.path.join(repository_root, 'PRESUBMIT.py')
1440 results = _MergeMasters(results, executer.ExecPresubmitScript(
1441 default_presubmit, fake_path, project, change))
1442 for filename in presubmit_files:
1443 filename = os.path.abspath(filename)
1444 if verbose:
Edward Lemura5799e32020-01-17 19:26:51 +00001445 output_stream.write('Running %s\n' % filename)
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001446 # Accept CRLF presubmit script.
1447 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1448 results = _MergeMasters(results, executer.ExecPresubmitScript(
1449 presubmit_script, filename, project, change))
1450
1451 # Make sets to lists again for later JSON serialization.
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00001452 for builders in results.values():
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001453 for builder in builders:
1454 builders[builder] = list(builders[builder])
1455
1456 if results and verbose:
1457 output_stream.write('%s\n' % str(results))
1458 return results
1459
1460
rmistry@google.com5626a922015-02-26 14:03:30 +00001461def DoPostUploadExecuter(change,
1462 cl,
1463 repository_root,
1464 verbose,
1465 output_stream):
1466 """Execute the post upload hook.
1467
1468 Args:
1469 change: The Change object.
1470 cl: The Changelist object.
1471 repository_root: The repository root.
1472 verbose: Prints debug info.
1473 output_stream: A stream to write debug output to.
1474 """
1475 presubmit_files = ListRelevantPresubmitFiles(
1476 change.LocalPaths(), repository_root)
1477 if not presubmit_files and verbose:
Edward Lemura5799e32020-01-17 19:26:51 +00001478 output_stream.write('Warning, no PRESUBMIT.py found.\n')
rmistry@google.com5626a922015-02-26 14:03:30 +00001479 results = []
1480 executer = GetPostUploadExecuter()
1481 # The root presubmit file should be executed after the ones in subdirectories.
1482 # i.e. the specific post upload hooks should run before the general ones.
1483 # Thus, reverse the order provided by ListRelevantPresubmitFiles.
1484 presubmit_files.reverse()
1485
1486 for filename in presubmit_files:
1487 filename = os.path.abspath(filename)
1488 if verbose:
Edward Lemura5799e32020-01-17 19:26:51 +00001489 output_stream.write('Running %s\n' % filename)
rmistry@google.com5626a922015-02-26 14:03:30 +00001490 # Accept CRLF presubmit script.
1491 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1492 results.extend(executer.ExecPresubmitScript(
1493 presubmit_script, filename, cl, change))
1494 output_stream.write('\n')
1495 if results:
1496 output_stream.write('** Post Upload Hook Messages **\n')
1497 for result in results:
1498 result.handle(output_stream)
1499 output_stream.write('\n')
1500
1501 return results
1502
1503
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001504class PresubmitExecuter(object):
Aaron Gable668c1d82018-04-03 10:19:16 -07001505 def __init__(self, change, committing, verbose,
Edward Lesmes8e282792018-04-03 18:50:29 -04001506 gerrit_obj, dry_run=None, thread_pool=None, parallel=False):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001507 """
1508 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001509 change: The Change object.
agable92bec4f2016-08-24 09:27:27 -07001510 committing: True if 'git cl land' is running, False if 'git cl upload' is.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001511 gerrit_obj: provides basic Gerrit codereview functionality.
1512 dry_run: if true, some Checks will be skipped.
Edward Lesmes8e282792018-04-03 18:50:29 -04001513 parallel: if true, all tests reported via input_api.RunTests for all
1514 PRESUBMIT files will be run in parallel.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001515 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001516 self.change = change
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001517 self.committing = committing
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001518 self.gerrit = gerrit_obj
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001519 self.verbose = verbose
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001520 self.dry_run = dry_run
Daniel Cheng7227d212017-11-17 08:12:37 -08001521 self.more_cc = []
Edward Lesmes8e282792018-04-03 18:50:29 -04001522 self.thread_pool = thread_pool
1523 self.parallel = parallel
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001524
1525 def ExecPresubmitScript(self, script_text, presubmit_path):
1526 """Executes a single presubmit script.
1527
1528 Args:
1529 script_text: The text of the presubmit script.
1530 presubmit_path: The path to the presubmit file (this will be reported via
1531 input_api.PresubmitLocalPath()).
1532
1533 Return:
1534 A list of result objects, empty if no problems.
1535 """
thakis@chromium.orgc6ef53a2014-11-04 00:13:54 +00001536
chase@chromium.org8e416c82009-10-06 04:30:44 +00001537 # Change to the presubmit file's directory to support local imports.
1538 main_path = os.getcwd()
1539 os.chdir(os.path.dirname(presubmit_path))
1540
1541 # Load the presubmit script into context.
dpranke@chromium.org970c5222011-03-12 00:32:24 +00001542 input_api = InputApi(self.change, presubmit_path, self.committing,
Aaron Gable668c1d82018-04-03 10:19:16 -07001543 self.verbose, gerrit_obj=self.gerrit,
Edward Lesmes8e282792018-04-03 18:50:29 -04001544 dry_run=self.dry_run, thread_pool=self.thread_pool,
1545 parallel=self.parallel)
Daniel Cheng7227d212017-11-17 08:12:37 -08001546 output_api = OutputApi(self.committing)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001547 context = {}
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001548 try:
Raul Tambre09e64b42019-05-14 01:57:22 +00001549 exec(compile(script_text, 'PRESUBMIT.py', 'exec', dont_inherit=True),
1550 context)
Raul Tambre7c938462019-05-24 16:35:35 +00001551 except Exception as e:
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001552 raise PresubmitFailure('"%s" had an exception.\n%s' % (presubmit_path, e))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001553
1554 # These function names must change if we make substantial changes to
1555 # the presubmit API that are not backwards compatible.
1556 if self.committing:
1557 function_name = 'CheckChangeOnCommit'
1558 else:
1559 function_name = 'CheckChangeOnUpload'
1560 if function_name in context:
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +01001561 try:
Daniel Cheng7227d212017-11-17 08:12:37 -08001562 context['__args'] = (input_api, output_api)
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +01001563 logging.debug('Running %s in %s', function_name, presubmit_path)
1564 result = eval(function_name + '(*__args)', context)
1565 logging.debug('Running %s done.', function_name)
Daniel Chengd36fce42017-11-21 21:52:52 -08001566 self.more_cc.extend(output_api.more_cc)
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +01001567 finally:
Edward Lemurb9830242019-10-30 22:19:20 +00001568 for f in input_api._named_temporary_files:
1569 os.remove(f)
1570 if not isinstance(result, (tuple, list)):
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001571 raise PresubmitFailure(
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001572 'Presubmit functions must return a tuple or list')
1573 for item in result:
1574 if not isinstance(item, OutputApi.PresubmitResult):
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001575 raise PresubmitFailure(
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001576 'All presubmit results must be of types derived from '
1577 'output_api.PresubmitResult')
1578 else:
1579 result = () # no error since the script doesn't care about current event.
1580
chase@chromium.org8e416c82009-10-06 04:30:44 +00001581 # Return the process to the original working directory.
1582 os.chdir(main_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001583 return result
1584
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001585def DoPresubmitChecks(change,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001586 committing,
1587 verbose,
1588 output_stream,
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +00001589 input_stream,
maruel@chromium.orgb0dfd352009-06-10 14:12:54 +00001590 default_presubmit,
dpranke@chromium.org970c5222011-03-12 00:32:24 +00001591 may_prompt,
Aaron Gable668c1d82018-04-03 10:19:16 -07001592 gerrit_obj,
Edward Lesmes8e282792018-04-03 18:50:29 -04001593 dry_run=None,
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001594 parallel=False,
1595 json_output=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001596 """Runs all presubmit checks that apply to the files in the change.
1597
1598 This finds all PRESUBMIT.py files in directories enclosing the files in the
1599 change (up to the repository root) and calls the relevant entrypoint function
1600 depending on whether the change is being committed or uploaded.
1601
1602 Prints errors, warnings and notifications. Prompts the user for warnings
1603 when needed.
1604
1605 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001606 change: The Change object.
agable92bec4f2016-08-24 09:27:27 -07001607 committing: True if 'git cl land' is running, False if 'git cl upload' is.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001608 verbose: Prints debug info.
1609 output_stream: A stream to write output from presubmit tests to.
1610 input_stream: A stream to read input from the user.
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +00001611 default_presubmit: A default presubmit script to execute in any case.
Quinten Yearsley516fe7f2016-12-14 11:50:18 -08001612 may_prompt: Enable (y/n) questions on warning or error. If False,
1613 any questions are answered with yes by default.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001614 gerrit_obj: provides basic Gerrit codereview functionality.
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001615 dry_run: if true, some Checks will be skipped.
Edward Lesmes8e282792018-04-03 18:50:29 -04001616 parallel: if true, all tests specified by input_api.RunTests in all
1617 PRESUBMIT files will be run in parallel.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001618
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +00001619 Warning:
1620 If may_prompt is true, output_stream SHOULD be sys.stdout and input_stream
1621 SHOULD be sys.stdin.
1622
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001623 Return:
dpranke@chromium.org5ac21012011-03-16 02:58:25 +00001624 A PresubmitOutput object. Use output.should_continue() to figure out
1625 if there were errors or warnings and the caller should abort.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001626 """
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001627 old_environ = os.environ
1628 try:
1629 # Make sure python subprocesses won't generate .pyc files.
1630 os.environ = os.environ.copy()
Edward Lemurb9830242019-10-30 22:19:20 +00001631 os.environ['PYTHONDONTWRITEBYTECODE'] = '1'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001632
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001633 output = PresubmitOutput(input_stream, output_stream)
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001634
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001635 if committing:
Edward Lemura5799e32020-01-17 19:26:51 +00001636 output.write('Running presubmit commit checks ...\n')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001637 else:
Edward Lemura5799e32020-01-17 19:26:51 +00001638 output.write('Running presubmit upload checks ...\n')
Edward Lemurecc27072020-01-06 16:42:34 +00001639 start_time = time_time()
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001640 presubmit_files = ListRelevantPresubmitFiles(
agable0b65e732016-11-22 09:25:46 -08001641 change.AbsoluteLocalPaths(), change.RepositoryRoot())
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001642 if not presubmit_files and verbose:
Edward Lemura5799e32020-01-17 19:26:51 +00001643 output.write('Warning, no PRESUBMIT.py found.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001644 results = []
Edward Lesmes8e282792018-04-03 18:50:29 -04001645 thread_pool = ThreadPool()
Edward Lemur7e3c67f2018-07-20 20:52:49 +00001646 executer = PresubmitExecuter(change, committing, verbose, gerrit_obj,
1647 dry_run, thread_pool, parallel)
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001648 if default_presubmit:
1649 if verbose:
Edward Lemura5799e32020-01-17 19:26:51 +00001650 output.write('Running default presubmit script.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001651 fake_path = os.path.join(change.RepositoryRoot(), 'PRESUBMIT.py')
1652 results += executer.ExecPresubmitScript(default_presubmit, fake_path)
1653 for filename in presubmit_files:
1654 filename = os.path.abspath(filename)
1655 if verbose:
Edward Lemura5799e32020-01-17 19:26:51 +00001656 output.write('Running %s\n' % filename)
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001657 # Accept CRLF presubmit script.
1658 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1659 results += executer.ExecPresubmitScript(presubmit_script, filename)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001660
Edward Lesmes8e282792018-04-03 18:50:29 -04001661 results += thread_pool.RunAsync()
1662
Daniel Cheng7227d212017-11-17 08:12:37 -08001663 output.more_cc.extend(executer.more_cc)
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001664 errors = []
1665 notifications = []
1666 warnings = []
1667 for result in results:
1668 if result.fatal:
1669 errors.append(result)
1670 elif result.should_prompt:
1671 warnings.append(result)
1672 else:
1673 notifications.append(result)
pam@chromium.orged9a0832009-09-09 22:48:55 +00001674
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001675 if json_output:
1676 # Write the presubmit results to json output
1677 presubmit_results = {
1678 'errors': [
1679 error.json_format() for error in errors
1680 ],
1681 'notifications': [
1682 notification.json_format() for notification in notifications
1683 ],
1684 'warnings': [
1685 warning.json_format() for warning in warnings
1686 ]
1687 }
1688
Edward Lemurb9830242019-10-30 22:19:20 +00001689 gclient_utils.FileWrite(
1690 json_output, json.dumps(presubmit_results, sort_keys=True))
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001691
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001692 output.write('\n')
1693 for name, items in (('Messages', notifications),
1694 ('Warnings', warnings),
1695 ('ERRORS', errors)):
1696 if items:
1697 output.write('** Presubmit %s **\n' % name)
1698 for item in items:
1699 item.handle(output)
1700 output.write('\n')
pam@chromium.orged9a0832009-09-09 22:48:55 +00001701
Edward Lemurecc27072020-01-06 16:42:34 +00001702 total_time = time_time() - start_time
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001703 if total_time > 1.0:
Edward Lemura5799e32020-01-17 19:26:51 +00001704 output.write('Presubmit checks took %.1fs to calculate.\n\n' % total_time)
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +00001705
Quinten Yearsley516fe7f2016-12-14 11:50:18 -08001706 if errors:
1707 output.fail()
1708 elif warnings:
1709 output.write('There were presubmit warnings. ')
1710 if may_prompt:
1711 output.prompt_yes_no('Are you sure you wish to continue? (y/N): ')
1712 else:
1713 output.write('Presubmit checks passed.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001714
1715 global _ASKED_FOR_FEEDBACK
1716 # Ask for feedback one time out of 5.
1717 if (len(results) and random.randint(0, 4) == 0 and not _ASKED_FOR_FEEDBACK):
maruel@chromium.org1ce8e662014-01-14 15:23:00 +00001718 output.write(
1719 'Was the presubmit check useful? If not, run "git cl presubmit -v"\n'
1720 'to figure out which PRESUBMIT.py was run, then run git blame\n'
1721 'on the file to figure out who to ask for help.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001722 _ASKED_FOR_FEEDBACK = True
1723 return output
1724 finally:
1725 os.environ = old_environ
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001726
1727
Edward Lemur1c8026d2020-02-04 22:09:08 +00001728def _scan_sub_dirs(mask, recursive):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001729 if not recursive:
pgervais@chromium.orge57b09d2014-05-07 00:58:13 +00001730 return [x for x in glob.glob(mask) if x not in ('.svn', '.git')]
Lei Zhang9611c4c2017-04-04 01:41:56 -07001731
1732 results = []
1733 for root, dirs, files in os.walk('.'):
1734 if '.svn' in dirs:
1735 dirs.remove('.svn')
1736 if '.git' in dirs:
1737 dirs.remove('.git')
1738 for name in files:
1739 if fnmatch.fnmatch(name, mask):
1740 results.append(os.path.join(root, name))
1741 return results
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001742
1743
Edward Lemur1c8026d2020-02-04 22:09:08 +00001744def _parse_files(args, recursive):
tobiasjs2836bcf2016-08-16 04:08:16 -07001745 logging.debug('Searching for %s', args)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001746 files = []
1747 for arg in args:
Edward Lemur1c8026d2020-02-04 22:09:08 +00001748 files.extend([('M', f) for f in _scan_sub_dirs(arg, recursive)])
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001749 return files
1750
1751
Edward Lemur1c8026d2020-02-04 22:09:08 +00001752def _parse_change(parser, options):
1753 """Process change options.
1754
1755 Args:
1756 parser: The parser used to parse the arguments from command line.
1757 options: The arguments parsed from command line.
1758 Returns:
1759 A GitChange if the change root is a git repository, or a Change otherwise.
1760 """
1761 if options.files and options.all_files:
1762 parser.error('<files> cannot be specified when --all-files is set.')
1763
agable0b65e732016-11-22 09:25:46 -08001764 change_scm = scm.determine_scm(options.root)
Edward Lemur1c8026d2020-02-04 22:09:08 +00001765 if change_scm != 'git' and not options.files:
1766 parser.error('<files> is not optional for unversioned directories.')
1767
1768 if options.files:
1769 change_files = _parse_files(options.files, options.recursive)
1770 elif options.all_files:
1771 change_files = [('M', f) for f in scm.GIT.GetAllFiles(options.root)]
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001772 else:
Edward Lemur1c8026d2020-02-04 22:09:08 +00001773 change_files = scm.GIT.CaptureStatus(
1774 [], options.root, options.upstream or None)
1775
1776 logging.info('Found %d file(s).', len(change_files))
1777
1778 change_class = GitChange if change_scm == 'git' else Change
1779 return change_class(
1780 options.name,
1781 options.description,
1782 options.root,
1783 change_files,
1784 options.issue,
1785 options.patchset,
1786 options.author,
1787 upstream=options.upstream)
1788
1789
1790def _parse_gerrit_options(parser, options):
1791 """Process gerrit options.
1792
1793 SIDE EFFECTS: Modifies options.author and options.description from Gerrit if
1794 options.gerrit_fetch is set.
1795
1796 Args:
1797 parser: The parser used to parse the arguments from command line.
1798 options: The arguments parsed from command line.
1799 Returns:
1800 A GerritAccessor object if options.gerrit_url is set, or None otherwise.
1801 """
1802 gerrit_obj = None
1803 if options.gerrit_url:
1804 gerrit_obj = GerritAccessor(urlparse.urlparse(options.gerrit_url).netloc)
1805
1806 if not options.gerrit_fetch:
1807 return gerrit_obj
1808
1809 if not options.gerrit_url or not options.issue or not options.patchset:
1810 parser.error(
1811 '--gerrit_fetch requires --gerrit_url, --issue and --patchset.')
1812
1813 options.author = gerrit_obj.GetChangeOwner(options.issue)
1814 options.description = gerrit_obj.GetChangeDescription(
1815 options.issue, options.patchset)
1816
1817 logging.info('Got author: "%s"', options.author)
1818 logging.info('Got description: """\n%s\n"""', options.description)
1819
1820 return gerrit_obj
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001821
1822
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001823@contextlib.contextmanager
1824def canned_check_filter(method_names):
1825 filtered = {}
1826 try:
1827 for method_name in method_names:
1828 if not hasattr(presubmit_canned_checks, method_name):
Aaron Gableecee74c2018-04-02 15:13:08 -07001829 logging.warn('Skipping unknown "canned" check %s' % method_name)
1830 continue
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001831 filtered[method_name] = getattr(presubmit_canned_checks, method_name)
1832 setattr(presubmit_canned_checks, method_name, lambda *_a, **_kw: [])
1833 yield
1834 finally:
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00001835 for name, method in filtered.items():
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001836 setattr(presubmit_canned_checks, name, method)
1837
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001838
sbc@chromium.org013731e2015-02-26 18:28:43 +00001839def main(argv=None):
Edward Lemura5799e32020-01-17 19:26:51 +00001840 parser = argparse.ArgumentParser(usage='%(prog)s [options] <files...>')
1841 hooks = parser.add_mutually_exclusive_group()
1842 hooks.add_argument('-c', '--commit', action='store_true',
1843 help='Use commit instead of upload checks.')
1844 hooks.add_argument('-u', '--upload', action='store_false', dest='commit',
1845 help='Use upload instead of commit checks.')
1846 parser.add_argument('-r', '--recursive', action='store_true',
1847 help='Act recursively.')
1848 parser.add_argument('-v', '--verbose', action='count', default=0,
1849 help='Use 2 times for more debug info.')
1850 parser.add_argument('--name', default='no name')
1851 parser.add_argument('--author')
1852 parser.add_argument('--description', default='')
1853 parser.add_argument('--issue', type=int, default=0)
1854 parser.add_argument('--patchset', type=int, default=0)
1855 parser.add_argument('--root', default=os.getcwd(),
1856 help='Search for PRESUBMIT.py up to this directory. '
1857 'If inherit-review-settings-ok is present in this '
1858 'directory, parent directories up to the root file '
1859 'system directories will also be searched.')
1860 parser.add_argument('--upstream',
1861 help='Git only: the base ref or upstream branch against '
1862 'which the diff should be computed.')
1863 parser.add_argument('--default_presubmit')
1864 parser.add_argument('--may_prompt', action='store_true', default=False)
1865 parser.add_argument('--skip_canned', action='append', default=[],
1866 help='A list of checks to skip which appear in '
1867 'presubmit_canned_checks. Can be provided multiple times '
1868 'to skip multiple canned checks.')
1869 parser.add_argument('--dry_run', action='store_true', help=argparse.SUPPRESS)
1870 parser.add_argument('--gerrit_url', help=argparse.SUPPRESS)
1871 parser.add_argument('--gerrit_fetch', action='store_true',
1872 help=argparse.SUPPRESS)
1873 parser.add_argument('--parallel', action='store_true',
1874 help='Run all tests specified by input_api.RunTests in '
1875 'all PRESUBMIT files in parallel.')
1876 parser.add_argument('--json_output',
1877 help='Write presubmit errors to json output.')
Edward Lemur1c8026d2020-02-04 22:09:08 +00001878 parser.add_argument('--all-files', action='store_true',
1879 help='Mark all files under source control as modified.')
Edward Lemura5799e32020-01-17 19:26:51 +00001880 parser.add_argument('files', nargs='*',
1881 help='List of files to be marked as modified when '
1882 'executing presubmit or post-upload hooks. fnmatch '
1883 'wildcards can also be used.')
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001884
Edward Lemura5799e32020-01-17 19:26:51 +00001885 options = parser.parse_args(argv)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001886
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001887 if options.verbose >= 2:
maruel@chromium.org7444c502011-02-09 14:02:11 +00001888 logging.basicConfig(level=logging.DEBUG)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001889 elif options.verbose:
1890 logging.basicConfig(level=logging.INFO)
1891 else:
1892 logging.basicConfig(level=logging.ERROR)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001893
Edward Lemur1c8026d2020-02-04 22:09:08 +00001894 change = _parse_change(parser, options)
1895 gerrit_obj = _parse_gerrit_options(parser, options)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001896
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001897 try:
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001898 with canned_check_filter(options.skip_canned):
1899 results = DoPresubmitChecks(
Edward Lemur1c8026d2020-02-04 22:09:08 +00001900 change,
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001901 options.commit,
1902 options.verbose,
1903 sys.stdout,
1904 sys.stdin,
1905 options.default_presubmit,
1906 options.may_prompt,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001907 gerrit_obj,
Edward Lesmes8e282792018-04-03 18:50:29 -04001908 options.dry_run,
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001909 options.parallel,
1910 options.json_output)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001911 return not results.should_continue()
Raul Tambre7c938462019-05-24 16:35:35 +00001912 except PresubmitFailure as e:
Raul Tambre80ee78e2019-05-06 22:41:05 +00001913 print(e, file=sys.stderr)
1914 print('Maybe your depot_tools is out of date?', file=sys.stderr)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001915 return 2
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001916
1917
1918if __name__ == '__main__':
maruel@chromium.org35625c72011-03-23 17:34:02 +00001919 fix_encoding.fix_encoding()
sbc@chromium.org013731e2015-02-26 18:28:43 +00001920 try:
1921 sys.exit(main())
1922 except KeyboardInterrupt:
1923 sys.stderr.write('interrupted\n')
sergiybf8a3b382016-07-05 11:21:30 -07001924 sys.exit(2)