blob: 927525e066aa3126a4b21c70d64290f5e9d9037e [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
Edward Lemur6eb1d322020-02-27 22:20:15 +0000295def prompt_should_continue(prompt_string):
296 sys.stdout.write(prompt_string)
297 response = sys.stdin.readline().strip().lower()
298 return response in ('y', 'yes')
dpranke@chromium.org5ac21012011-03-16 02:58:25 +0000299
300
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000301# Top level object so multiprocessing can pickle
302# Public access through OutputApi object.
303class _PresubmitResult(object):
304 """Base class for result objects."""
305 fatal = False
306 should_prompt = False
307
308 def __init__(self, message, items=None, long_text=''):
309 """
310 message: A short one-line message to indicate errors.
311 items: A list of short strings to indicate where errors occurred.
312 long_text: multi-line text output, e.g. from another tool
313 """
314 self._message = message
315 self._items = items or []
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000316 self._long_text = long_text.rstrip()
317
Edward Lemur6eb1d322020-02-27 22:20:15 +0000318 def handle(self):
319 sys.stdout.write(self._message)
320 sys.stdout.write('\n')
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000321 for index, item in enumerate(self._items):
Edward Lemur6eb1d322020-02-27 22:20:15 +0000322 sys.stdout.write(' ')
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000323 # Write separately in case it's unicode.
Edward Lemur6eb1d322020-02-27 22:20:15 +0000324 sys.stdout.write(str(item))
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000325 if index < len(self._items) - 1:
Edward Lemur6eb1d322020-02-27 22:20:15 +0000326 sys.stdout.write(' \\')
327 sys.stdout.write('\n')
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000328 if self._long_text:
Edward Lemur6eb1d322020-02-27 22:20:15 +0000329 sys.stdout.write('\n***************\n')
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000330 # Write separately in case it's unicode.
Edward Lemur6eb1d322020-02-27 22:20:15 +0000331 sys.stdout.write(self._long_text)
332 sys.stdout.write('\n***************\n')
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000333
Debrian Figueroadd2737e2019-06-21 23:50:13 +0000334 def json_format(self):
335 return {
336 'message': self._message,
Debrian Figueroa6095d402019-06-28 18:47:18 +0000337 'items': [str(item) for item in self._items],
Debrian Figueroadd2737e2019-06-21 23:50:13 +0000338 'long_text': self._long_text,
339 'fatal': self.fatal
340 }
341
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000342
343# Top level object so multiprocessing can pickle
344# Public access through OutputApi object.
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000345class _PresubmitError(_PresubmitResult):
346 """A hard presubmit error."""
347 fatal = True
348
349
350# Top level object so multiprocessing can pickle
351# Public access through OutputApi object.
352class _PresubmitPromptWarning(_PresubmitResult):
353 """An warning that prompts the user if they want to continue."""
354 should_prompt = True
355
356
357# Top level object so multiprocessing can pickle
358# Public access through OutputApi object.
359class _PresubmitNotifyResult(_PresubmitResult):
360 """Just print something to the screen -- but it's not even a warning."""
361 pass
362
363
364# Top level object so multiprocessing can pickle
365# Public access through OutputApi object.
366class _MailTextResult(_PresubmitResult):
367 """A warning that should be included in the review request email."""
368 def __init__(self, *args, **kwargs):
369 super(_MailTextResult, self).__init__()
370 raise NotImplementedError()
371
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000372class GerritAccessor(object):
373 """Limited Gerrit functionality for canned presubmit checks to work.
374
375 To avoid excessive Gerrit calls, caches the results.
376 """
377
378 def __init__(self, host):
379 self.host = host
380 self.cache = {}
381
382 def _FetchChangeDetail(self, issue):
383 # Separate function to be easily mocked in tests.
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +0100384 try:
385 return gerrit_util.GetChangeDetail(
386 self.host, str(issue),
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700387 ['ALL_REVISIONS', 'DETAILED_LABELS', 'ALL_COMMITS'])
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +0100388 except gerrit_util.GerritError as e:
389 if e.http_status == 404:
390 raise Exception('Either Gerrit issue %s doesn\'t exist, or '
391 'no credentials to fetch issue details' % issue)
392 raise
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000393
394 def GetChangeInfo(self, issue):
395 """Returns labels and all revisions (patchsets) for this issue.
396
397 The result is a dictionary according to Gerrit REST Api.
398 https://gerrit-review.googlesource.com/Documentation/rest-api.html
399
400 However, API isn't very clear what's inside, so see tests for example.
401 """
402 assert issue
403 cache_key = int(issue)
404 if cache_key not in self.cache:
405 self.cache[cache_key] = self._FetchChangeDetail(issue)
406 return self.cache[cache_key]
407
408 def GetChangeDescription(self, issue, patchset=None):
409 """If patchset is none, fetches current patchset."""
410 info = self.GetChangeInfo(issue)
411 # info is a reference to cache. We'll modify it here adding description to
412 # it to the right patchset, if it is not yet there.
413
414 # Find revision info for the patchset we want.
415 if patchset is not None:
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000416 for rev, rev_info in info['revisions'].items():
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000417 if str(rev_info['_number']) == str(patchset):
418 break
419 else:
420 raise Exception('patchset %s doesn\'t exist in issue %s' % (
421 patchset, issue))
422 else:
423 rev = info['current_revision']
424 rev_info = info['revisions'][rev]
425
Andrii Shyshkalov9c3a4642017-01-24 17:41:22 +0100426 return rev_info['commit']['message']
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000427
Mun Yong Jang603d01e2017-12-19 16:38:30 -0800428 def GetDestRef(self, issue):
429 ref = self.GetChangeInfo(issue)['branch']
430 if not ref.startswith('refs/'):
431 # NOTE: it is possible to create 'refs/x' branch,
432 # aka 'refs/heads/refs/x'. However, this is ill-advised.
433 ref = 'refs/heads/%s' % ref
434 return ref
435
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000436 def GetChangeOwner(self, issue):
437 return self.GetChangeInfo(issue)['owner']['email']
438
439 def GetChangeReviewers(self, issue, approving_only=True):
Aaron Gable8b478f02017-07-31 15:33:19 -0700440 changeinfo = self.GetChangeInfo(issue)
441 if approving_only:
442 labelinfo = changeinfo.get('labels', {}).get('Code-Review', {})
443 values = labelinfo.get('values', {}).keys()
444 try:
445 max_value = max(int(v) for v in values)
446 reviewers = [r for r in labelinfo.get('all', [])
447 if r.get('value', 0) == max_value]
448 except ValueError: # values is the empty list
449 reviewers = []
450 else:
451 reviewers = changeinfo.get('reviewers', {}).get('REVIEWER', [])
452 return [r.get('email') for r in reviewers]
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000453
Edward Lemure4d329c2020-02-03 20:41:18 +0000454 def UpdateDescription(self, description, issue):
455 gerrit_util.SetCommitMessage(self.host, issue, description, notify='NONE')
456
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000457
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000458class OutputApi(object):
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000459 """An instance of OutputApi gets passed to presubmit scripts so that they
460 can output various types of results.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000461 """
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000462 PresubmitResult = _PresubmitResult
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000463 PresubmitError = _PresubmitError
464 PresubmitPromptWarning = _PresubmitPromptWarning
465 PresubmitNotifyResult = _PresubmitNotifyResult
466 MailTextResult = _MailTextResult
467
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000468 def __init__(self, is_committing):
469 self.is_committing = is_committing
Daniel Cheng7227d212017-11-17 08:12:37 -0800470 self.more_cc = []
471
472 def AppendCC(self, cc):
473 """Appends a user to cc for this change."""
474 self.more_cc.append(cc)
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000475
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000476 def PresubmitPromptOrNotify(self, *args, **kwargs):
477 """Warn the user when uploading, but only notify if committing."""
478 if self.is_committing:
479 return self.PresubmitNotifyResult(*args, **kwargs)
480 return self.PresubmitPromptWarning(*args, **kwargs)
481
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000482
483class InputApi(object):
484 """An instance of this object is passed to presubmit scripts so they can
485 know stuff about the change they're looking at.
486 """
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000487 # Method could be a function
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800488 # pylint: disable=no-self-use
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000489
maruel@chromium.org3410d912009-06-09 20:56:16 +0000490 # File extensions that are considered source files from a style guide
491 # perspective. Don't modify this list from a presubmit script!
maruel@chromium.orgc33455a2011-06-24 19:14:18 +0000492 #
493 # Files without an extension aren't included in the list. If you want to
Edward Lemura5799e32020-01-17 19:26:51 +0000494 # filter them as source files, add r'(^|.*?[\\\/])[^.]+$' to the white list.
maruel@chromium.orgc33455a2011-06-24 19:14:18 +0000495 # Note that ALL CAPS files are black listed in DEFAULT_BLACK_LIST below.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000496 DEFAULT_WHITE_LIST = (
497 # C++ and friends
Edward Lemura5799e32020-01-17 19:26:51 +0000498 r'.+\.c$', r'.+\.cc$', r'.+\.cpp$', r'.+\.h$', r'.+\.m$', r'.+\.mm$',
499 r'.+\.inl$', r'.+\.asm$', r'.+\.hxx$', r'.+\.hpp$', r'.+\.s$', r'.+\.S$',
maruel@chromium.org3410d912009-06-09 20:56:16 +0000500 # Scripts
Edward Lemura5799e32020-01-17 19:26:51 +0000501 r'.+\.js$', r'.+\.py$', r'.+\.sh$', r'.+\.rb$', r'.+\.pl$', r'.+\.pm$',
maruel@chromium.org3410d912009-06-09 20:56:16 +0000502 # Other
Edward Lemura5799e32020-01-17 19:26:51 +0000503 r'.+\.java$', r'.+\.mk$', r'.+\.am$', r'.+\.css$', r'.+\.mojom$',
504 r'.+\.fidl$'
maruel@chromium.org3410d912009-06-09 20:56:16 +0000505 )
506
507 # Path regexp that should be excluded from being considered containing source
508 # files. Don't modify this list from a presubmit script!
509 DEFAULT_BLACK_LIST = (
Edward Lemura5799e32020-01-17 19:26:51 +0000510 r'testing_support[\\\/]google_appengine[\\\/].*',
511 r'.*\bexperimental[\\\/].*',
Kent Tamura179dd1e2018-04-26 15:07:41 +0900512 # Exclude third_party/.* but NOT third_party/{WebKit,blink}
513 # (crbug.com/539768 and crbug.com/836555).
Edward Lemura5799e32020-01-17 19:26:51 +0000514 r'.*\bthird_party[\\\/](?!(WebKit|blink)[\\\/]).*',
maruel@chromium.org3410d912009-06-09 20:56:16 +0000515 # Output directories (just in case)
Edward Lemura5799e32020-01-17 19:26:51 +0000516 r'.*\bDebug[\\\/].*',
517 r'.*\bRelease[\\\/].*',
518 r'.*\bxcodebuild[\\\/].*',
519 r'.*\bout[\\\/].*',
maruel@chromium.org3410d912009-06-09 20:56:16 +0000520 # All caps files like README and LICENCE.
Edward Lemura5799e32020-01-17 19:26:51 +0000521 r'.*\b[A-Z0-9_]{2,}$',
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000522 # SCM (can happen in dual SCM configuration). (Slightly over aggressive)
Edward Lemura5799e32020-01-17 19:26:51 +0000523 r'(|.*[\\\/])\.git[\\\/].*',
524 r'(|.*[\\\/])\.svn[\\\/].*',
maruel@chromium.org7ccb4bb2011-11-07 20:26:20 +0000525 # There is no point in processing a patch file.
Edward Lemura5799e32020-01-17 19:26:51 +0000526 r'.+\.diff$',
527 r'.+\.patch$',
maruel@chromium.org3410d912009-06-09 20:56:16 +0000528 )
529
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000530 def __init__(self, change, presubmit_path, is_committing,
Edward Lesmes8e282792018-04-03 18:50:29 -0400531 verbose, gerrit_obj, dry_run=None, thread_pool=None, parallel=False):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000532 """Builds an InputApi object.
533
534 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000535 change: A presubmit.Change object.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000536 presubmit_path: The path to the presubmit script being processed.
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000537 is_committing: True if the change is about to be committed.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000538 gerrit_obj: provides basic Gerrit codereview functionality.
539 dry_run: if true, some Checks will be skipped.
Edward Lesmes8e282792018-04-03 18:50:29 -0400540 parallel: if true, all tests reported via input_api.RunTests for all
541 PRESUBMIT files will be run in parallel.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000542 """
maruel@chromium.org9711bba2009-05-22 23:51:39 +0000543 # Version number of the presubmit_support script.
544 self.version = [int(x) for x in __version__.split('.')]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000545 self.change = change
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000546 self.is_committing = is_committing
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000547 self.gerrit = gerrit_obj
tandrii@chromium.org57bafac2016-04-28 05:09:03 +0000548 self.dry_run = dry_run
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000549
Edward Lesmes8e282792018-04-03 18:50:29 -0400550 self.parallel = parallel
551 self.thread_pool = thread_pool or ThreadPool()
552
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000553 # We expose various modules and functions as attributes of the input_api
554 # so that presubmit scripts don't have to import them.
Takeshi Yoshino07a6bea2017-08-02 02:44:06 +0900555 self.ast = ast
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000556 self.basename = os.path.basename
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000557 self.cpplint = cpplint
dcheng091b7db2016-06-16 01:27:51 -0700558 self.fnmatch = fnmatch
Yoshisato Yanagisawa04600b42019-03-15 03:03:41 +0000559 self.gclient_paths = gclient_paths
Yoshisato Yanagisawa57dd17b2019-03-22 09:10:29 +0000560 # TODO(yyanagisawa): stop exposing this when python3 become default.
561 # Since python3's tempfile has TemporaryDirectory, we do not need this.
562 self.temporary_directory = gclient_utils.temporary_directory
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000563 self.glob = glob.glob
maruel@chromium.orgfb11c7b2010-03-18 18:22:14 +0000564 self.json = json
maruel@chromium.org6fba34d2011-06-02 13:45:12 +0000565 self.logging = logging.getLogger('PRESUBMIT')
maruel@chromium.org2b5ce562011-03-31 16:15:44 +0000566 self.os_listdir = os.listdir
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000567 self.os_path = os.path
pgervais@chromium.orgbd0cace2014-10-02 23:23:46 +0000568 self.os_stat = os.stat
Yoshisato Yanagisawa406de132018-06-29 05:43:25 +0000569 self.os_walk = os.walk
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000570 self.re = re
571 self.subprocess = subprocess
Edward Lemurb9830242019-10-30 22:19:20 +0000572 self.sys = sys
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000573 self.tempfile = tempfile
dpranke@chromium.org0d1bdea2011-03-24 22:54:38 +0000574 self.time = time
maruel@chromium.org1487d532009-06-06 00:22:57 +0000575 self.unittest = unittest
Edward Lemurb9830242019-10-30 22:19:20 +0000576 if sys.version_info.major == 2:
577 self.urllib2 = urllib2
Edward Lemur16af3562019-10-17 22:11:33 +0000578 self.urllib_request = urllib_request
579 self.urllib_error = urllib_error
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000580
Robert Iannucci50258932018-03-19 10:30:59 -0700581 self.is_windows = sys.platform == 'win32'
582
Edward Lemurb9646622019-10-25 20:57:35 +0000583 # Set python_executable to 'vpython' in order to allow scripts in other
584 # repos (e.g. src.git) to automatically pick up that repo's .vpython file,
585 # instead of inheriting the one in depot_tools.
586 self.python_executable = 'vpython'
maruel@chromium.orgc0b22972009-06-25 16:19:14 +0000587 self.environ = os.environ
588
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000589 # InputApi.platform is the platform you're currently running on.
590 self.platform = sys.platform
591
iannucci@chromium.org0af3bb32015-06-12 20:44:35 +0000592 self.cpu_count = multiprocessing.cpu_count()
593
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000594 # The local path of the currently-being-processed presubmit script.
maruel@chromium.org3d235242009-05-15 12:40:48 +0000595 self._current_presubmit_path = os.path.dirname(presubmit_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000596
597 # We carry the canned checks so presubmit scripts can easily use them.
598 self.canned_checks = presubmit_canned_checks
599
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +0100600 # Temporary files we must manually remove at the end of a run.
601 self._named_temporary_files = []
Jochen Eisinger72606f82017-04-04 10:44:18 +0200602
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000603 # TODO(dpranke): figure out a list of all approved owners for a repo
604 # in order to be able to handle wildcard OWNERS files?
605 self.owners_db = owners.Database(change.RepositoryRoot(),
Edward Lemurb9830242019-10-30 22:19:20 +0000606 fopen=open, os_path=self.os_path)
Jochen Eisinger76f5fc62017-04-07 16:27:46 +0200607 self.owners_finder = owners_finder.OwnersFinder
maruel@chromium.org899e1c12011-04-07 17:03:18 +0000608 self.verbose = verbose
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000609 self.Command = CommandData
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000610
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000611 # Replace <hash_map> and <hash_set> as headers that need to be included
Edward Lemura5799e32020-01-17 19:26:51 +0000612 # with 'base/containers/hash_tables.h' instead.
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000613 # Access to a protected member _XX of a client class
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800614 # pylint: disable=protected-access
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000615 self.cpplint._re_pattern_templates = [
danakj@chromium.org18278522013-06-11 22:42:32 +0000616 (a, b, 'base/containers/hash_tables.h')
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000617 if header in ('<hash_map>', '<hash_set>') else (a, b, header)
618 for (a, b, header) in cpplint._re_pattern_templates
619 ]
620
Edward Lemurecc27072020-01-06 16:42:34 +0000621 def SetTimeout(self, timeout):
622 self.thread_pool.timeout = timeout
623
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000624 def PresubmitLocalPath(self):
625 """Returns the local path of the presubmit script currently being run.
626
627 This is useful if you don't want to hard-code absolute paths in the
628 presubmit script. For example, It can be used to find another file
629 relative to the PRESUBMIT.py script, so the whole tree can be branched and
630 the presubmit script still works, without editing its content.
631 """
maruel@chromium.org3d235242009-05-15 12:40:48 +0000632 return self._current_presubmit_path
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000633
agable0b65e732016-11-22 09:25:46 -0800634 def AffectedFiles(self, include_deletes=True, file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000635 """Same as input_api.change.AffectedFiles() except only lists files
636 (and optionally directories) in the same directory as the current presubmit
637 script, or subdirectories thereof.
638 """
Edward Lemura5799e32020-01-17 19:26:51 +0000639 dir_with_slash = normpath('%s/' % self.PresubmitLocalPath())
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000640 if len(dir_with_slash) == 1:
641 dir_with_slash = ''
sail@chromium.org5538e022011-05-12 17:53:16 +0000642
Edward Lemurb9830242019-10-30 22:19:20 +0000643 return list(filter(
maruel@chromium.org4661e0c2009-06-04 00:45:26 +0000644 lambda x: normpath(x.AbsoluteLocalPath()).startswith(dir_with_slash),
Edward Lemurb9830242019-10-30 22:19:20 +0000645 self.change.AffectedFiles(include_deletes, file_filter)))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000646
agable0b65e732016-11-22 09:25:46 -0800647 def LocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000648 """Returns local paths of input_api.AffectedFiles()."""
agable0b65e732016-11-22 09:25:46 -0800649 paths = [af.LocalPath() for af in self.AffectedFiles()]
Edward Lemura5799e32020-01-17 19:26:51 +0000650 logging.debug('LocalPaths: %s', paths)
pgervais@chromium.org2f64f782014-04-25 00:12:33 +0000651 return paths
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000652
agable0b65e732016-11-22 09:25:46 -0800653 def AbsoluteLocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000654 """Returns absolute local paths of input_api.AffectedFiles()."""
agable0b65e732016-11-22 09:25:46 -0800655 return [af.AbsoluteLocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000656
John Budorick16162372018-04-18 10:39:53 -0700657 def AffectedTestableFiles(self, include_deletes=None, **kwargs):
agable0b65e732016-11-22 09:25:46 -0800658 """Same as input_api.change.AffectedTestableFiles() except only lists files
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000659 in the same directory as the current presubmit script, or subdirectories
660 thereof.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000661 """
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000662 if include_deletes is not None:
Edward Lemura5799e32020-01-17 19:26:51 +0000663 warn('AffectedTestableFiles(include_deletes=%s)'
664 ' is deprecated and ignored' % str(include_deletes),
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000665 category=DeprecationWarning,
666 stacklevel=2)
Edward Lemurb9830242019-10-30 22:19:20 +0000667 return list(filter(
668 lambda x: x.IsTestableFile(),
669 self.AffectedFiles(include_deletes=False, **kwargs)))
agable0b65e732016-11-22 09:25:46 -0800670
671 def AffectedTextFiles(self, include_deletes=None):
672 """An alias to AffectedTestableFiles for backwards compatibility."""
673 return self.AffectedTestableFiles(include_deletes=include_deletes)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000674
maruel@chromium.org3410d912009-06-09 20:56:16 +0000675 def FilterSourceFile(self, affected_file, white_list=None, black_list=None):
Edward Lemura5799e32020-01-17 19:26:51 +0000676 """Filters out files that aren't considered 'source file'.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000677
678 If white_list or black_list is None, InputApi.DEFAULT_WHITE_LIST
679 and InputApi.DEFAULT_BLACK_LIST is used respectively.
680
681 The lists will be compiled as regular expression and
682 AffectedFile.LocalPath() needs to pass both list.
683
684 Note: Copy-paste this function to suit your needs or use a lambda function.
685 """
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000686 def Find(affected_file, items):
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000687 local_path = affected_file.LocalPath()
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000688 for item in items:
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000689 if self.re.match(item, local_path):
maruel@chromium.org3410d912009-06-09 20:56:16 +0000690 return True
691 return False
692 return (Find(affected_file, white_list or self.DEFAULT_WHITE_LIST) and
693 not Find(affected_file, black_list or self.DEFAULT_BLACK_LIST))
694
695 def AffectedSourceFiles(self, source_file):
agable0b65e732016-11-22 09:25:46 -0800696 """Filter the list of AffectedTestableFiles by the function source_file.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000697
698 If source_file is None, InputApi.FilterSourceFile() is used.
699 """
700 if not source_file:
701 source_file = self.FilterSourceFile
Edward Lemurb9830242019-10-30 22:19:20 +0000702 return list(filter(source_file, self.AffectedTestableFiles()))
maruel@chromium.org3410d912009-06-09 20:56:16 +0000703
704 def RightHandSideLines(self, source_file_filter=None):
Edward Lemura5799e32020-01-17 19:26:51 +0000705 """An iterator over all text lines in 'new' version of changed files.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000706
707 Only lists lines from new or modified text files in the change that are
708 contained by the directory of the currently executing presubmit script.
709
710 This is useful for doing line-by-line regex checks, like checking for
711 trailing whitespace.
712
713 Yields:
714 a 3 tuple:
715 the AffectedFile instance of the current file;
716 integer line number (1-based); and
717 the contents of the line as a string.
maruel@chromium.org1487d532009-06-06 00:22:57 +0000718
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000719 Note: The carriage return (LF or CR) is stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000720 """
maruel@chromium.org3410d912009-06-09 20:56:16 +0000721 files = self.AffectedSourceFiles(source_file_filter)
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000722 return _RightHandSideLinesImpl(files)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000723
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000724 def ReadFile(self, file_item, mode='r'):
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000725 """Reads an arbitrary file.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000726
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000727 Deny reading anything outside the repository.
728 """
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000729 if isinstance(file_item, AffectedFile):
730 file_item = file_item.AbsoluteLocalPath()
731 if not file_item.startswith(self.change.RepositoryRoot()):
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000732 raise IOError('Access outside the repository root is denied.')
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000733 return gclient_utils.FileRead(file_item, mode)
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000734
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +0100735 def CreateTemporaryFile(self, **kwargs):
736 """Returns a named temporary file that must be removed with a call to
737 RemoveTemporaryFiles().
738
739 All keyword arguments are forwarded to tempfile.NamedTemporaryFile(),
740 except for |delete|, which is always set to False.
741
742 Presubmit checks that need to create a temporary file and pass it for
743 reading should use this function instead of NamedTemporaryFile(), as
744 Windows fails to open a file that is already open for writing.
745
746 with input_api.CreateTemporaryFile() as f:
747 f.write('xyz')
748 f.close()
749 input_api.subprocess.check_output(['script-that', '--reads-from',
750 f.name])
751
752
753 Note that callers of CreateTemporaryFile() should not worry about removing
754 any temporary file; this is done transparently by the presubmit handling
755 code.
756 """
757 if 'delete' in kwargs:
758 # Prevent users from passing |delete|; we take care of file deletion
759 # ourselves and this prevents unintuitive error messages when we pass
760 # delete=False and 'delete' is also in kwargs.
761 raise TypeError('CreateTemporaryFile() does not take a "delete" '
762 'argument, file deletion is handled automatically by '
763 'the same presubmit_support code that creates InputApi '
764 'objects.')
765 temp_file = self.tempfile.NamedTemporaryFile(delete=False, **kwargs)
766 self._named_temporary_files.append(temp_file.name)
767 return temp_file
768
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000769 @property
770 def tbr(self):
771 """Returns if a change is TBR'ed."""
Jeremy Romandce22502017-06-20 15:37:29 -0400772 return 'TBR' in self.change.tags or self.change.TBRsFromDescription()
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000773
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +0000774 def RunTests(self, tests_mix, parallel=True):
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000775 tests = []
776 msgs = []
777 for t in tests_mix:
Edward Lesmes8e282792018-04-03 18:50:29 -0400778 if isinstance(t, OutputApi.PresubmitResult) and t:
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000779 msgs.append(t)
780 else:
781 assert issubclass(t.message, _PresubmitResult)
782 tests.append(t)
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +0000783 if self.verbose:
784 t.info = _PresubmitNotifyResult
Edward Lemur1037c742018-05-01 18:56:04 -0400785 if not t.kwargs.get('cwd'):
786 t.kwargs['cwd'] = self.PresubmitLocalPath()
Edward Lesmes8e282792018-04-03 18:50:29 -0400787 self.thread_pool.AddTests(tests, parallel)
Edward Lemur21000eb2019-05-24 23:25:58 +0000788 # When self.parallel is True (i.e. --parallel is passed as an option)
789 # RunTests doesn't actually run tests. It adds them to a ThreadPool that
790 # will run all tests once all PRESUBMIT files are processed.
791 # Otherwise, it will run them and return the results.
792 if not self.parallel:
Edward Lesmes8e282792018-04-03 18:50:29 -0400793 msgs.extend(self.thread_pool.RunAsync())
794 return msgs
scottmg86099d72016-09-01 09:16:51 -0700795
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000796
nick@chromium.orgff526192013-06-10 19:30:26 +0000797class _DiffCache(object):
798 """Caches diffs retrieved from a particular SCM."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000799 def __init__(self, upstream=None):
800 """Stores the upstream revision against which all diffs will be computed."""
801 self._upstream = upstream
nick@chromium.orgff526192013-06-10 19:30:26 +0000802
803 def GetDiff(self, path, local_root):
804 """Get the diff for a particular path."""
805 raise NotImplementedError()
806
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700807 def GetOldContents(self, path, local_root):
808 """Get the old version for a particular path."""
809 raise NotImplementedError()
810
nick@chromium.orgff526192013-06-10 19:30:26 +0000811
nick@chromium.orgff526192013-06-10 19:30:26 +0000812class _GitDiffCache(_DiffCache):
813 """DiffCache implementation for git; gets all file diffs at once."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000814 def __init__(self, upstream):
815 super(_GitDiffCache, self).__init__(upstream=upstream)
nick@chromium.orgff526192013-06-10 19:30:26 +0000816 self._diffs_by_file = None
817
818 def GetDiff(self, path, local_root):
819 if not self._diffs_by_file:
820 # Compute a single diff for all files and parse the output; should
821 # with git this is much faster than computing one diff for each file.
822 diffs = {}
823
824 # Don't specify any filenames below, because there are command line length
825 # limits on some platforms and GenerateDiff would fail.
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000826 unified_diff = scm.GIT.GenerateDiff(local_root, files=[], full_move=True,
827 branch=self._upstream)
nick@chromium.orgff526192013-06-10 19:30:26 +0000828
829 # This regex matches the path twice, separated by a space. Note that
830 # filename itself may contain spaces.
831 file_marker = re.compile('^diff --git (?P<filename>.*) (?P=filename)$')
832 current_diff = []
833 keep_line_endings = True
834 for x in unified_diff.splitlines(keep_line_endings):
835 match = file_marker.match(x)
836 if match:
837 # Marks the start of a new per-file section.
838 diffs[match.group('filename')] = current_diff = [x]
839 elif x.startswith('diff --git'):
840 raise PresubmitFailure('Unexpected diff line: %s' % x)
841 else:
842 current_diff.append(x)
843
844 self._diffs_by_file = dict(
845 (normpath(path), ''.join(diff)) for path, diff in diffs.items())
846
847 if path not in self._diffs_by_file:
848 raise PresubmitFailure(
849 'Unified diff did not contain entry for file %s' % path)
850
851 return self._diffs_by_file[path]
852
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700853 def GetOldContents(self, path, local_root):
854 return scm.GIT.GetOldContents(local_root, path, branch=self._upstream)
855
nick@chromium.orgff526192013-06-10 19:30:26 +0000856
Yannic Bonenberger68409632020-01-23 18:29:01 +0000857def _ParseDiffHeader(line):
858 """Searches |line| for diff headers and returns a tuple
859 (header, old_line, old_size, new_line, new_size), or None if line doesn't
860 contain a diff header.
861
862 This relies on the scm diff output describing each changed code section
863 with a line of the form
864
865 ^@@ <old line num>,<old size> <new line num>,<new size> @@$
866 """
867 m = re.match(r'^@@ \-([0-9]+)\,([0-9]+) \+([0-9]+)\,([0-9]+) @@', line)
868 if m:
869 return (m.group(0), int(m.group(1)), int(m.group(2)), int(m.group(3)),
870 int(m.group(4)))
871
872
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000873class AffectedFile(object):
874 """Representation of a file in a change."""
nick@chromium.orgff526192013-06-10 19:30:26 +0000875
876 DIFF_CACHE = _DiffCache
877
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000878 # Method could be a function
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800879 # pylint: disable=no-self-use
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000880 def __init__(self, path, action, repository_root, diff_cache):
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000881 self._path = path
882 self._action = action
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000883 self._local_root = repository_root
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000884 self._is_directory = None
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000885 self._cached_changed_contents = None
Yannic Bonenberger68409632020-01-23 18:29:01 +0000886 self._cached_change_size_in_bytes = None
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000887 self._cached_new_contents = None
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000888 self._diff_cache = diff_cache
tobiasjs2836bcf2016-08-16 04:08:16 -0700889 logging.debug('%s(%s)', self.__class__.__name__, self._path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000890
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000891 def LocalPath(self):
892 """Returns the path of this file on the local disk relative to client root.
Andrew Grieve92b8b992017-11-02 09:42:24 -0400893
894 This should be used for error messages but not for accessing files,
895 because presubmit checks are run with CWD=PresubmitLocalPath() (which is
896 often != client root).
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000897 """
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000898 return normpath(self._path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000899
900 def AbsoluteLocalPath(self):
901 """Returns the absolute path of this file on the local disk.
902 """
chase@chromium.org8e416c82009-10-06 04:30:44 +0000903 return os.path.abspath(os.path.join(self._local_root, self.LocalPath()))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000904
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000905 def Action(self):
906 """Returns the action on this opened file, e.g. A, M, D, etc."""
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000907 return self._action
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000908
agable0b65e732016-11-22 09:25:46 -0800909 def IsTestableFile(self):
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000910 """Returns True if the file is a text file and not a binary file.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000911
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000912 Deleted files are not text file."""
maruel@chromium.org1e08c002009-05-28 19:09:33 +0000913 raise NotImplementedError() # Implement when needed
914
agable0b65e732016-11-22 09:25:46 -0800915 def IsTextFile(self):
916 """An alias to IsTestableFile for backwards compatibility."""
917 return self.IsTestableFile()
918
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700919 def OldContents(self):
920 """Returns an iterator over the lines in the old version of file.
921
Daniel Cheng2da34fe2017-03-21 20:42:12 -0700922 The old version is the file before any modifications in the user's
Edward Lemura5799e32020-01-17 19:26:51 +0000923 workspace, i.e. the 'left hand side'.
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700924
925 Contents will be empty if the file is a directory or does not exist.
926 Note: The carriage returns (LF or CR) are stripped off.
927 """
928 return self._diff_cache.GetOldContents(self.LocalPath(),
929 self._local_root).splitlines()
930
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000931 def NewContents(self):
932 """Returns an iterator over the lines in the new version of file.
933
Edward Lemura5799e32020-01-17 19:26:51 +0000934 The new version is the file in the user's workspace, i.e. the 'right hand
935 side'.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000936
937 Contents will be empty if the file is a directory or does not exist.
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000938 Note: The carriage returns (LF or CR) are stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000939 """
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000940 if self._cached_new_contents is None:
941 self._cached_new_contents = []
agable0b65e732016-11-22 09:25:46 -0800942 try:
943 self._cached_new_contents = gclient_utils.FileRead(
944 self.AbsoluteLocalPath(), 'rU').splitlines()
945 except IOError:
946 pass # File not found? That's fine; maybe it was deleted.
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000947 return self._cached_new_contents[:]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000948
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000949 def ChangedContents(self):
950 """Returns a list of tuples (line number, line text) of all new lines.
951
952 This relies on the scm diff output describing each changed code section
953 with a line of the form
954
955 ^@@ <old line num>,<old size> <new line num>,<new size> @@$
956 """
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000957 if self._cached_changed_contents is not None:
958 return self._cached_changed_contents[:]
959 self._cached_changed_contents = []
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000960 line_num = 0
961
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000962 for line in self.GenerateScmDiff().splitlines():
Yannic Bonenberger68409632020-01-23 18:29:01 +0000963 h = _ParseDiffHeader(line)
964 if h:
965 line_num = h[3]
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000966 continue
967 if line.startswith('+') and not line.startswith('++'):
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000968 self._cached_changed_contents.append((line_num, line[1:]))
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000969 if not line.startswith('-'):
970 line_num += 1
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000971 return self._cached_changed_contents[:]
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000972
Yannic Bonenberger68409632020-01-23 18:29:01 +0000973 def ChangeSizeInBytes(self):
974 """Returns a list of tuples (deleted bytes, added bytes) of all changes
975 in this file.
976
977 This relies on the scm diff output describing each changed code section
978 with a line of the form
979
980 ^@@ <old line num>,<old size> <new line num>,<new size> @@$
981 """
982 if self._cached_change_size_in_bytes is not None:
983 return self._cached_change_size_in_bytes[:]
984 self._cached_change_size_in_bytes = []
985
986 for line in self.GenerateScmDiff().splitlines():
987 h = _ParseDiffHeader(line)
988 if h:
989 self._cached_change_size_in_bytes.append((h[2], h[4]))
990 return self._cached_change_size_in_bytes[:]
991
maruel@chromium.org5de13972009-06-10 18:16:06 +0000992 def __str__(self):
993 return self.LocalPath()
994
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000995 def GenerateScmDiff(self):
nick@chromium.orgff526192013-06-10 19:30:26 +0000996 return self._diff_cache.GetDiff(self.LocalPath(), self._local_root)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000997
maruel@chromium.org58407af2011-04-12 23:15:57 +0000998
maruel@chromium.orgc70a2202009-06-17 12:55:10 +0000999class GitAffectedFile(AffectedFile):
1000 """Representation of a file in a change out of a git checkout."""
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +00001001 # Method 'NNN' is abstract in class 'NNN' but is not overridden
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -08001002 # pylint: disable=abstract-method
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001003
nick@chromium.orgff526192013-06-10 19:30:26 +00001004 DIFF_CACHE = _GitDiffCache
1005
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001006 def __init__(self, *args, **kwargs):
1007 AffectedFile.__init__(self, *args, **kwargs)
1008 self._server_path = None
agable0b65e732016-11-22 09:25:46 -08001009 self._is_testable_file = None
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001010
agable0b65e732016-11-22 09:25:46 -08001011 def IsTestableFile(self):
1012 if self._is_testable_file is None:
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001013 if self.Action() == 'D':
agable0b65e732016-11-22 09:25:46 -08001014 # A deleted file is not testable.
1015 self._is_testable_file = False
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001016 else:
agable0b65e732016-11-22 09:25:46 -08001017 self._is_testable_file = os.path.isfile(self.AbsoluteLocalPath())
1018 return self._is_testable_file
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001019
maruel@chromium.orgc1938752011-04-12 23:11:13 +00001020
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001021class Change(object):
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001022 """Describe a change.
1023
1024 Used directly by the presubmit scripts to query the current change being
1025 tested.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +00001026
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001027 Instance members:
nick@chromium.orgff526192013-06-10 19:30:26 +00001028 tags: Dictionary of KEY=VALUE pairs found in the change description.
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001029 self.KEY: equivalent to tags['KEY']
1030 """
1031
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001032 _AFFECTED_FILES = AffectedFile
1033
Edward Lemura5799e32020-01-17 19:26:51 +00001034 # Matches key/value (or 'tag') lines in changelist descriptions.
maruel@chromium.org428342a2011-11-10 15:46:33 +00001035 TAG_LINE_RE = re.compile(
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001036 '^[ \t]*(?P<key>[A-Z][A-Z_0-9]*)[ \t]*=[ \t]*(?P<value>.*?)[ \t]*$')
maruel@chromium.orgc1938752011-04-12 23:11:13 +00001037 scm = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001038
maruel@chromium.org58407af2011-04-12 23:15:57 +00001039 def __init__(
agable@chromium.orgea84ef12014-04-30 19:55:12 +00001040 self, name, description, local_root, files, issue, patchset, author,
1041 upstream=None):
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001042 if files is None:
1043 files = []
1044 self._name = name
chase@chromium.org8e416c82009-10-06 04:30:44 +00001045 # Convert root into an absolute path.
1046 self._local_root = os.path.abspath(local_root)
agable@chromium.orgea84ef12014-04-30 19:55:12 +00001047 self._upstream = upstream
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001048 self.issue = issue
1049 self.patchset = patchset
maruel@chromium.org58407af2011-04-12 23:15:57 +00001050 self.author_email = author
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001051
isherman@chromium.orgb5cded62014-03-25 17:47:57 +00001052 self._full_description = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001053 self.tags = {}
isherman@chromium.orgb5cded62014-03-25 17:47:57 +00001054 self._description_without_tags = ''
1055 self.SetDescriptionText(description)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001056
maruel@chromium.orge085d812011-10-10 19:49:15 +00001057 assert all(
1058 (isinstance(f, (list, tuple)) and len(f) == 2) for f in files), files
1059
agable@chromium.orgea84ef12014-04-30 19:55:12 +00001060 diff_cache = self._AFFECTED_FILES.DIFF_CACHE(self._upstream)
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001061 self._affected_files = [
nick@chromium.orgff526192013-06-10 19:30:26 +00001062 self._AFFECTED_FILES(path, action.strip(), self._local_root, diff_cache)
1063 for action, path in files
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +00001064 ]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001065
maruel@chromium.org92022ec2009-06-11 01:59:28 +00001066 def Name(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001067 """Returns the change name."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001068 return self._name
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001069
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001070 def DescriptionText(self):
1071 """Returns the user-entered changelist description, minus tags.
1072
Edward Lemura5799e32020-01-17 19:26:51 +00001073 Any line in the user-provided description starting with e.g. 'FOO='
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001074 (whitespace permitted before and around) is considered a tag line. Such
1075 lines are stripped out of the description this function returns.
1076 """
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001077 return self._description_without_tags
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001078
1079 def FullDescriptionText(self):
1080 """Returns the complete changelist description including tags."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001081 return self._full_description
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001082
isherman@chromium.orgb5cded62014-03-25 17:47:57 +00001083 def SetDescriptionText(self, description):
1084 """Sets the full description text (including tags) to |description|.
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001085
isherman@chromium.orgb5cded62014-03-25 17:47:57 +00001086 Also updates the list of tags."""
1087 self._full_description = description
1088
1089 # From the description text, build up a dictionary of key/value pairs
Edward Lemura5799e32020-01-17 19:26:51 +00001090 # plus the description minus all key/value or 'tag' lines.
isherman@chromium.orgb5cded62014-03-25 17:47:57 +00001091 description_without_tags = []
1092 self.tags = {}
1093 for line in self._full_description.splitlines():
1094 m = self.TAG_LINE_RE.match(line)
1095 if m:
1096 self.tags[m.group('key')] = m.group('value')
1097 else:
1098 description_without_tags.append(line)
1099
1100 # Change back to text and remove whitespace at end.
1101 self._description_without_tags = (
1102 '\n'.join(description_without_tags).rstrip())
1103
Edward Lemur69bb8be2020-02-03 20:37:38 +00001104 def AddDescriptionFooter(self, key, value):
1105 """Adds the given footer to the change description.
1106
1107 Args:
1108 key: A string with the key for the git footer. It must conform to
1109 the git footers format (i.e. 'List-Of-Tokens') and will be case
1110 normalized so that each token is title-cased.
1111 value: A string with the value for the git footer.
1112 """
1113 description = git_footers.add_footer(
1114 self.FullDescriptionText(), git_footers.normalize_name(key), value)
1115 self.SetDescriptionText(description)
1116
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001117 def RepositoryRoot(self):
maruel@chromium.org92022ec2009-06-11 01:59:28 +00001118 """Returns the repository (checkout) root directory for this change,
1119 as an absolute path.
1120 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001121 return self._local_root
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001122
1123 def __getattr__(self, attr):
maruel@chromium.org92022ec2009-06-11 01:59:28 +00001124 """Return tags directly as attributes on the object."""
Edward Lemura5799e32020-01-17 19:26:51 +00001125 if not re.match(r'^[A-Z_]*$', attr):
maruel@chromium.org92022ec2009-06-11 01:59:28 +00001126 raise AttributeError(self, attr)
maruel@chromium.orge1a524f2009-05-27 14:43:46 +00001127 return self.tags.get(attr)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001128
Edward Lemur69bb8be2020-02-03 20:37:38 +00001129 def GitFootersFromDescription(self):
1130 """Return the git footers present in the description.
1131
1132 Returns:
1133 footers: A dict of {footer: [values]} containing a multimap of the footers
1134 in the change description.
1135 """
1136 return git_footers.parse_footers(self.FullDescriptionText())
1137
Aaron Gablefc03e672017-05-15 14:09:42 -07001138 def BugsFromDescription(self):
1139 """Returns all bugs referenced in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -07001140 tags = [b.strip() for b in self.tags.get('BUG', '').split(',') if b.strip()]
Caleb Rouleauc0546b92019-02-22 06:12:57 +00001141 footers = []
Edward Lemur69bb8be2020-02-03 20:37:38 +00001142 parsed = self.GitFootersFromDescription()
Dan Beam62954042019-10-03 21:20:33 +00001143 unsplit_footers = parsed.get('Bug', []) + parsed.get('Fixed', [])
Caleb Rouleauc0546b92019-02-22 06:12:57 +00001144 for unsplit_footer in unsplit_footers:
1145 footers += [b.strip() for b in unsplit_footer.split(',')]
Aaron Gable12ef5012017-05-15 14:29:00 -07001146 return sorted(set(tags + footers))
Aaron Gablefc03e672017-05-15 14:09:42 -07001147
1148 def ReviewersFromDescription(self):
1149 """Returns all reviewers listed in the commit description."""
Edward Lemura5799e32020-01-17 19:26:51 +00001150 # We don't support a 'R:' git-footer for reviewers; that is in metadata.
Aaron Gable12ef5012017-05-15 14:29:00 -07001151 tags = [r.strip() for r in self.tags.get('R', '').split(',') if r.strip()]
1152 return sorted(set(tags))
Aaron Gablefc03e672017-05-15 14:09:42 -07001153
1154 def TBRsFromDescription(self):
1155 """Returns all TBR reviewers listed in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -07001156 tags = [r.strip() for r in self.tags.get('TBR', '').split(',') if r.strip()]
1157 # TODO(agable): Remove support for 'Tbr:' when TBRs are programmatically
1158 # determined by self-CR+1s.
Edward Lemur69bb8be2020-02-03 20:37:38 +00001159 footers = self.GitFootersFromDescription().get('Tbr', [])
Aaron Gable12ef5012017-05-15 14:29:00 -07001160 return sorted(set(tags + footers))
Aaron Gablefc03e672017-05-15 14:09:42 -07001161
1162 # TODO(agable): Delete these once we're sure they're unused.
1163 @property
1164 def BUG(self):
1165 return ','.join(self.BugsFromDescription())
1166 @property
1167 def R(self):
1168 return ','.join(self.ReviewersFromDescription())
1169 @property
1170 def TBR(self):
1171 return ','.join(self.TBRsFromDescription())
1172
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001173 def AllFiles(self, root=None):
1174 """List all files under source control in the repo."""
1175 raise NotImplementedError()
1176
agable0b65e732016-11-22 09:25:46 -08001177 def AffectedFiles(self, include_deletes=True, file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001178 """Returns a list of AffectedFile instances for all files in the change.
1179
1180 Args:
1181 include_deletes: If false, deleted files will be filtered out.
sail@chromium.org5538e022011-05-12 17:53:16 +00001182 file_filter: An additional filter to apply.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001183
1184 Returns:
1185 [AffectedFile(path, action), AffectedFile(path, action)]
1186 """
Edward Lemurb9830242019-10-30 22:19:20 +00001187 affected = list(filter(file_filter, self._affected_files))
sail@chromium.org5538e022011-05-12 17:53:16 +00001188
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001189 if include_deletes:
1190 return affected
Edward Lemurb9830242019-10-30 22:19:20 +00001191 return list(filter(lambda x: x.Action() != 'D', affected))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001192
John Budorick16162372018-04-18 10:39:53 -07001193 def AffectedTestableFiles(self, include_deletes=None, **kwargs):
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +00001194 """Return a list of the existing text files in a change."""
1195 if include_deletes is not None:
Edward Lemura5799e32020-01-17 19:26:51 +00001196 warn('AffectedTeestableFiles(include_deletes=%s)'
1197 ' is deprecated and ignored' % str(include_deletes),
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +00001198 category=DeprecationWarning,
1199 stacklevel=2)
Edward Lemurb9830242019-10-30 22:19:20 +00001200 return list(filter(
1201 lambda x: x.IsTestableFile(),
1202 self.AffectedFiles(include_deletes=False, **kwargs)))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001203
agable0b65e732016-11-22 09:25:46 -08001204 def AffectedTextFiles(self, include_deletes=None):
1205 """An alias to AffectedTestableFiles for backwards compatibility."""
1206 return self.AffectedTestableFiles(include_deletes=include_deletes)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001207
agable0b65e732016-11-22 09:25:46 -08001208 def LocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001209 """Convenience function."""
agable0b65e732016-11-22 09:25:46 -08001210 return [af.LocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001211
agable0b65e732016-11-22 09:25:46 -08001212 def AbsoluteLocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001213 """Convenience function."""
agable0b65e732016-11-22 09:25:46 -08001214 return [af.AbsoluteLocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001215
1216 def RightHandSideLines(self):
Edward Lemura5799e32020-01-17 19:26:51 +00001217 """An iterator over all text lines in 'new' version of changed files.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001218
1219 Lists lines from new or modified text files in the change.
1220
1221 This is useful for doing line-by-line regex checks, like checking for
1222 trailing whitespace.
1223
1224 Yields:
1225 a 3 tuple:
1226 the AffectedFile instance of the current file;
1227 integer line number (1-based); and
1228 the contents of the line as a string.
1229 """
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +00001230 return _RightHandSideLinesImpl(
1231 x for x in self.AffectedFiles(include_deletes=False)
agable0b65e732016-11-22 09:25:46 -08001232 if x.IsTestableFile())
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001233
Jochen Eisingerd0573ec2017-04-13 10:55:06 +02001234 def OriginalOwnersFiles(self):
1235 """A map from path names of affected OWNERS files to their old content."""
1236 def owners_file_filter(f):
1237 return 'OWNERS' in os.path.split(f.LocalPath())[1]
1238 files = self.AffectedFiles(file_filter=owners_file_filter)
1239 return dict([(f.LocalPath(), f.OldContents()) for f in files])
1240
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001241
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001242class GitChange(Change):
1243 _AFFECTED_FILES = GitAffectedFile
maruel@chromium.orgc1938752011-04-12 23:11:13 +00001244 scm = 'git'
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +00001245
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001246 def AllFiles(self, root=None):
1247 """List all files under source control in the repo."""
1248 root = root or self.RepositoryRoot()
1249 return subprocess.check_output(
Aaron Gable7817f022017-12-12 09:43:17 -08001250 ['git', '-c', 'core.quotePath=false', 'ls-files', '--', '.'],
1251 cwd=root).splitlines()
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001252
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001253
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001254def ListRelevantPresubmitFiles(files, root):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001255 """Finds all presubmit files that apply to a given set of source files.
1256
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001257 If inherit-review-settings-ok is present right under root, looks for
1258 PRESUBMIT.py in directories enclosing root.
1259
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001260 Args:
1261 files: An iterable container containing file paths.
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001262 root: Path where to stop searching.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001263
1264 Return:
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001265 List of absolute paths of the existing PRESUBMIT.py scripts.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001266 """
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001267 files = [normpath(os.path.join(root, f)) for f in files]
1268
1269 # List all the individual directories containing files.
1270 directories = set([os.path.dirname(f) for f in files])
1271
1272 # Ignore root if inherit-review-settings-ok is present.
1273 if os.path.isfile(os.path.join(root, 'inherit-review-settings-ok')):
1274 root = None
1275
1276 # Collect all unique directories that may contain PRESUBMIT.py.
1277 candidates = set()
1278 for directory in directories:
1279 while True:
1280 if directory in candidates:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001281 break
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001282 candidates.add(directory)
1283 if directory == root:
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001284 break
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001285 parent_dir = os.path.dirname(directory)
1286 if parent_dir == directory:
1287 # We hit the system root directory.
1288 break
1289 directory = parent_dir
1290
1291 # Look for PRESUBMIT.py in all candidate directories.
1292 results = []
1293 for directory in sorted(list(candidates)):
tobiasjsff061c02016-08-17 03:23:57 -07001294 try:
1295 for f in os.listdir(directory):
1296 p = os.path.join(directory, f)
1297 if os.path.isfile(p) and re.match(
1298 r'PRESUBMIT.*\.py$', f) and not f.startswith('PRESUBMIT_test'):
1299 results.append(p)
1300 except OSError:
1301 pass
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001302
tobiasjs2836bcf2016-08-16 04:08:16 -07001303 logging.debug('Presubmit files: %s', ','.join(results))
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001304 return results
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001305
1306
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001307class GetTryMastersExecuter(object):
1308 @staticmethod
1309 def ExecPresubmitScript(script_text, presubmit_path, project, change):
1310 """Executes GetPreferredTryMasters() from a single presubmit script.
1311
1312 Args:
1313 script_text: The text of the presubmit script.
1314 presubmit_path: Project script to run.
1315 project: Project name to pass to presubmit script for bot selection.
1316
1317 Return:
1318 A map of try masters to map of builders to set of tests.
1319 """
1320 context = {}
1321 try:
Raul Tambre09e64b42019-05-14 01:57:22 +00001322 exec(compile(script_text, 'PRESUBMIT.py', 'exec', dont_inherit=True),
1323 context)
Raul Tambre7c938462019-05-24 16:35:35 +00001324 except Exception as e:
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001325 raise PresubmitFailure('"%s" had an exception.\n%s'
1326 % (presubmit_path, e))
1327
1328 function_name = 'GetPreferredTryMasters'
1329 if function_name not in context:
1330 return {}
1331 get_preferred_try_masters = context[function_name]
1332 if not len(inspect.getargspec(get_preferred_try_masters)[0]) == 2:
1333 raise PresubmitFailure(
1334 'Expected function "GetPreferredTryMasters" to take two arguments.')
1335 return get_preferred_try_masters(project, change)
1336
1337
rmistry@google.com5626a922015-02-26 14:03:30 +00001338class GetPostUploadExecuter(object):
1339 @staticmethod
Edward Lemur016a0872020-02-04 22:13:28 +00001340 def ExecPresubmitScript(script_text, presubmit_path, gerrit_obj, change):
rmistry@google.com5626a922015-02-26 14:03:30 +00001341 """Executes PostUploadHook() from a single presubmit script.
1342
1343 Args:
1344 script_text: The text of the presubmit script.
1345 presubmit_path: Project script to run.
Edward Lemur016a0872020-02-04 22:13:28 +00001346 gerrit_obj: The GerritAccessor object.
rmistry@google.com5626a922015-02-26 14:03:30 +00001347 change: The Change object.
1348
1349 Return:
1350 A list of results objects.
1351 """
1352 context = {}
1353 try:
Raul Tambre09e64b42019-05-14 01:57:22 +00001354 exec(compile(script_text, 'PRESUBMIT.py', 'exec', dont_inherit=True),
1355 context)
Raul Tambre7c938462019-05-24 16:35:35 +00001356 except Exception as e:
rmistry@google.com5626a922015-02-26 14:03:30 +00001357 raise PresubmitFailure('"%s" had an exception.\n%s'
1358 % (presubmit_path, e))
1359
1360 function_name = 'PostUploadHook'
1361 if function_name not in context:
1362 return {}
1363 post_upload_hook = context[function_name]
1364 if not len(inspect.getargspec(post_upload_hook)[0]) == 3:
1365 raise PresubmitFailure(
1366 'Expected function "PostUploadHook" to take three arguments.')
Edward Lemur016a0872020-02-04 22:13:28 +00001367 return post_upload_hook(gerrit_obj, change, OutputApi(False))
rmistry@google.com5626a922015-02-26 14:03:30 +00001368
1369
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001370def _MergeMasters(masters1, masters2):
1371 """Merges two master maps. Merges also the tests of each builder."""
1372 result = {}
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00001373 for (master, builders) in itertools.chain(masters1.items(),
1374 masters2.items()):
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001375 new_builders = result.setdefault(master, {})
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00001376 for (builder, tests) in builders.items():
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001377 new_builders.setdefault(builder, set([])).update(tests)
1378 return result
1379
1380
1381def DoGetTryMasters(change,
1382 changed_files,
1383 repository_root,
1384 default_presubmit,
1385 project,
1386 verbose,
1387 output_stream):
1388 """Get the list of try masters from the presubmit scripts.
1389
1390 Args:
1391 changed_files: List of modified files.
1392 repository_root: The repository root.
1393 default_presubmit: A default presubmit script to execute in any case.
1394 project: Optional name of a project used in selecting trybots.
1395 verbose: Prints debug info.
1396 output_stream: A stream to write debug output to.
1397
1398 Return:
1399 Map of try masters to map of builders to set of tests.
1400 """
1401 presubmit_files = ListRelevantPresubmitFiles(changed_files, repository_root)
1402 if not presubmit_files and verbose:
Edward Lemura5799e32020-01-17 19:26:51 +00001403 output_stream.write('Warning, no PRESUBMIT.py found.\n')
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001404 results = {}
1405 executer = GetTryMastersExecuter()
1406
1407 if default_presubmit:
1408 if verbose:
Edward Lemura5799e32020-01-17 19:26:51 +00001409 output_stream.write('Running default presubmit script.\n')
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001410 fake_path = os.path.join(repository_root, 'PRESUBMIT.py')
1411 results = _MergeMasters(results, executer.ExecPresubmitScript(
1412 default_presubmit, fake_path, project, change))
1413 for filename in presubmit_files:
1414 filename = os.path.abspath(filename)
1415 if verbose:
Edward Lemura5799e32020-01-17 19:26:51 +00001416 output_stream.write('Running %s\n' % filename)
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001417 # Accept CRLF presubmit script.
1418 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1419 results = _MergeMasters(results, executer.ExecPresubmitScript(
1420 presubmit_script, filename, project, change))
1421
1422 # Make sets to lists again for later JSON serialization.
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00001423 for builders in results.values():
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001424 for builder in builders:
1425 builders[builder] = list(builders[builder])
1426
1427 if results and verbose:
1428 output_stream.write('%s\n' % str(results))
1429 return results
1430
1431
rmistry@google.com5626a922015-02-26 14:03:30 +00001432def DoPostUploadExecuter(change,
Edward Lemur016a0872020-02-04 22:13:28 +00001433 gerrit_obj,
Edward Lemur6eb1d322020-02-27 22:20:15 +00001434 verbose):
rmistry@google.com5626a922015-02-26 14:03:30 +00001435 """Execute the post upload hook.
1436
1437 Args:
1438 change: The Change object.
Edward Lemur016a0872020-02-04 22:13:28 +00001439 gerrit_obj: The GerritAccessor object.
rmistry@google.com5626a922015-02-26 14:03:30 +00001440 verbose: Prints debug info.
rmistry@google.com5626a922015-02-26 14:03:30 +00001441 """
1442 presubmit_files = ListRelevantPresubmitFiles(
Edward Lemur6eb1d322020-02-27 22:20:15 +00001443 change.LocalPaths(), change.RepositoryRoot())
rmistry@google.com5626a922015-02-26 14:03:30 +00001444 if not presubmit_files and verbose:
Edward Lemur6eb1d322020-02-27 22:20:15 +00001445 sys.stdout.write('Warning, no PRESUBMIT.py found.\n')
rmistry@google.com5626a922015-02-26 14:03:30 +00001446 results = []
1447 executer = GetPostUploadExecuter()
1448 # The root presubmit file should be executed after the ones in subdirectories.
1449 # i.e. the specific post upload hooks should run before the general ones.
1450 # Thus, reverse the order provided by ListRelevantPresubmitFiles.
1451 presubmit_files.reverse()
1452
1453 for filename in presubmit_files:
1454 filename = os.path.abspath(filename)
1455 if verbose:
Edward Lemur6eb1d322020-02-27 22:20:15 +00001456 sys.stdout.write('Running %s\n' % filename)
rmistry@google.com5626a922015-02-26 14:03:30 +00001457 # Accept CRLF presubmit script.
1458 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1459 results.extend(executer.ExecPresubmitScript(
Edward Lemur016a0872020-02-04 22:13:28 +00001460 presubmit_script, filename, gerrit_obj, change))
rmistry@google.com5626a922015-02-26 14:03:30 +00001461
Edward Lemur6eb1d322020-02-27 22:20:15 +00001462 if not results:
1463 return 0
1464
1465 sys.stdout.write('\n')
1466 sys.stdout.write('** Post Upload Hook Messages **\n')
1467
1468 exit_code = 0
1469 for result in results:
1470 if result.fatal:
1471 exit_code = 1
1472 result.handle()
1473 sys.stdout.write('\n')
1474
1475 return exit_code
rmistry@google.com5626a922015-02-26 14:03:30 +00001476
1477
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001478class PresubmitExecuter(object):
Aaron Gable668c1d82018-04-03 10:19:16 -07001479 def __init__(self, change, committing, verbose,
Edward Lesmes8e282792018-04-03 18:50:29 -04001480 gerrit_obj, dry_run=None, thread_pool=None, parallel=False):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001481 """
1482 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001483 change: The Change object.
agable92bec4f2016-08-24 09:27:27 -07001484 committing: True if 'git cl land' is running, False if 'git cl upload' is.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001485 gerrit_obj: provides basic Gerrit codereview functionality.
1486 dry_run: if true, some Checks will be skipped.
Edward Lesmes8e282792018-04-03 18:50:29 -04001487 parallel: if true, all tests reported via input_api.RunTests for all
1488 PRESUBMIT files will be run in parallel.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001489 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001490 self.change = change
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001491 self.committing = committing
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001492 self.gerrit = gerrit_obj
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001493 self.verbose = verbose
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001494 self.dry_run = dry_run
Daniel Cheng7227d212017-11-17 08:12:37 -08001495 self.more_cc = []
Edward Lesmes8e282792018-04-03 18:50:29 -04001496 self.thread_pool = thread_pool
1497 self.parallel = parallel
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001498
1499 def ExecPresubmitScript(self, script_text, presubmit_path):
1500 """Executes a single presubmit script.
1501
1502 Args:
1503 script_text: The text of the presubmit script.
1504 presubmit_path: The path to the presubmit file (this will be reported via
1505 input_api.PresubmitLocalPath()).
1506
1507 Return:
1508 A list of result objects, empty if no problems.
1509 """
thakis@chromium.orgc6ef53a2014-11-04 00:13:54 +00001510
chase@chromium.org8e416c82009-10-06 04:30:44 +00001511 # Change to the presubmit file's directory to support local imports.
1512 main_path = os.getcwd()
1513 os.chdir(os.path.dirname(presubmit_path))
1514
1515 # Load the presubmit script into context.
dpranke@chromium.org970c5222011-03-12 00:32:24 +00001516 input_api = InputApi(self.change, presubmit_path, self.committing,
Aaron Gable668c1d82018-04-03 10:19:16 -07001517 self.verbose, gerrit_obj=self.gerrit,
Edward Lesmes8e282792018-04-03 18:50:29 -04001518 dry_run=self.dry_run, thread_pool=self.thread_pool,
1519 parallel=self.parallel)
Daniel Cheng7227d212017-11-17 08:12:37 -08001520 output_api = OutputApi(self.committing)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001521 context = {}
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001522 try:
Raul Tambre09e64b42019-05-14 01:57:22 +00001523 exec(compile(script_text, 'PRESUBMIT.py', 'exec', dont_inherit=True),
1524 context)
Raul Tambre7c938462019-05-24 16:35:35 +00001525 except Exception as e:
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001526 raise PresubmitFailure('"%s" had an exception.\n%s' % (presubmit_path, e))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001527
1528 # These function names must change if we make substantial changes to
1529 # the presubmit API that are not backwards compatible.
1530 if self.committing:
1531 function_name = 'CheckChangeOnCommit'
1532 else:
1533 function_name = 'CheckChangeOnUpload'
1534 if function_name in context:
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +01001535 try:
Daniel Cheng7227d212017-11-17 08:12:37 -08001536 context['__args'] = (input_api, output_api)
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +01001537 logging.debug('Running %s in %s', function_name, presubmit_path)
1538 result = eval(function_name + '(*__args)', context)
1539 logging.debug('Running %s done.', function_name)
Daniel Chengd36fce42017-11-21 21:52:52 -08001540 self.more_cc.extend(output_api.more_cc)
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +01001541 finally:
Edward Lemurb9830242019-10-30 22:19:20 +00001542 for f in input_api._named_temporary_files:
1543 os.remove(f)
1544 if not isinstance(result, (tuple, list)):
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001545 raise PresubmitFailure(
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001546 'Presubmit functions must return a tuple or list')
1547 for item in result:
1548 if not isinstance(item, OutputApi.PresubmitResult):
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001549 raise PresubmitFailure(
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001550 'All presubmit results must be of types derived from '
1551 'output_api.PresubmitResult')
1552 else:
1553 result = () # no error since the script doesn't care about current event.
1554
chase@chromium.org8e416c82009-10-06 04:30:44 +00001555 # Return the process to the original working directory.
1556 os.chdir(main_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001557 return result
1558
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001559def DoPresubmitChecks(change,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001560 committing,
1561 verbose,
maruel@chromium.orgb0dfd352009-06-10 14:12:54 +00001562 default_presubmit,
dpranke@chromium.org970c5222011-03-12 00:32:24 +00001563 may_prompt,
Aaron Gable668c1d82018-04-03 10:19:16 -07001564 gerrit_obj,
Edward Lesmes8e282792018-04-03 18:50:29 -04001565 dry_run=None,
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001566 parallel=False,
1567 json_output=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001568 """Runs all presubmit checks that apply to the files in the change.
1569
1570 This finds all PRESUBMIT.py files in directories enclosing the files in the
1571 change (up to the repository root) and calls the relevant entrypoint function
1572 depending on whether the change is being committed or uploaded.
1573
1574 Prints errors, warnings and notifications. Prompts the user for warnings
1575 when needed.
1576
1577 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001578 change: The Change object.
agable92bec4f2016-08-24 09:27:27 -07001579 committing: True if 'git cl land' is running, False if 'git cl upload' is.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001580 verbose: Prints debug info.
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +00001581 default_presubmit: A default presubmit script to execute in any case.
Quinten Yearsley516fe7f2016-12-14 11:50:18 -08001582 may_prompt: Enable (y/n) questions on warning or error. If False,
1583 any questions are answered with yes by default.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001584 gerrit_obj: provides basic Gerrit codereview functionality.
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001585 dry_run: if true, some Checks will be skipped.
Edward Lesmes8e282792018-04-03 18:50:29 -04001586 parallel: if true, all tests specified by input_api.RunTests in all
1587 PRESUBMIT files will be run in parallel.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001588
1589 Return:
Edward Lemur6eb1d322020-02-27 22:20:15 +00001590 1 if presubmit checks failed or 0 otherwise.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001591 """
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001592 old_environ = os.environ
1593 try:
1594 # Make sure python subprocesses won't generate .pyc files.
1595 os.environ = os.environ.copy()
Edward Lemurb9830242019-10-30 22:19:20 +00001596 os.environ['PYTHONDONTWRITEBYTECODE'] = '1'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001597
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001598 if committing:
Edward Lemur6eb1d322020-02-27 22:20:15 +00001599 sys.stdout.write('Running presubmit commit checks ...\n')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001600 else:
Edward Lemur6eb1d322020-02-27 22:20:15 +00001601 sys.stdout.write('Running presubmit upload checks ...\n')
Edward Lemurecc27072020-01-06 16:42:34 +00001602 start_time = time_time()
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001603 presubmit_files = ListRelevantPresubmitFiles(
agable0b65e732016-11-22 09:25:46 -08001604 change.AbsoluteLocalPaths(), change.RepositoryRoot())
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001605 if not presubmit_files and verbose:
Edward Lemur6eb1d322020-02-27 22:20:15 +00001606 sys.stdout.write('Warning, no PRESUBMIT.py found.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001607 results = []
Edward Lesmes8e282792018-04-03 18:50:29 -04001608 thread_pool = ThreadPool()
Edward Lemur7e3c67f2018-07-20 20:52:49 +00001609 executer = PresubmitExecuter(change, committing, verbose, gerrit_obj,
1610 dry_run, thread_pool, parallel)
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001611 if default_presubmit:
1612 if verbose:
Edward Lemur6eb1d322020-02-27 22:20:15 +00001613 sys.stdout.write('Running default presubmit script.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001614 fake_path = os.path.join(change.RepositoryRoot(), 'PRESUBMIT.py')
1615 results += executer.ExecPresubmitScript(default_presubmit, fake_path)
1616 for filename in presubmit_files:
1617 filename = os.path.abspath(filename)
1618 if verbose:
Edward Lemur6eb1d322020-02-27 22:20:15 +00001619 sys.stdout.write('Running %s\n' % filename)
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001620 # Accept CRLF presubmit script.
1621 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1622 results += executer.ExecPresubmitScript(presubmit_script, filename)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001623
Edward Lesmes8e282792018-04-03 18:50:29 -04001624 results += thread_pool.RunAsync()
1625
Edward Lemur6eb1d322020-02-27 22:20:15 +00001626 messages = {}
1627 should_prompt = False
1628 presubmits_failed = False
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001629 for result in results:
1630 if result.fatal:
Edward Lemur6eb1d322020-02-27 22:20:15 +00001631 presubmits_failed = True
1632 messages.setdefault('ERRORS', []).append(result)
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001633 elif result.should_prompt:
Edward Lemur6eb1d322020-02-27 22:20:15 +00001634 should_prompt = True
1635 messages.setdefault('Warnings', []).append(result)
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001636 else:
Edward Lemur6eb1d322020-02-27 22:20:15 +00001637 messages.setdefault('Messages', []).append(result)
pam@chromium.orged9a0832009-09-09 22:48:55 +00001638
Edward Lemur6eb1d322020-02-27 22:20:15 +00001639 sys.stdout.write('\n')
1640 for name, items in messages.items():
1641 sys.stdout.write('** Presubmit %s **\n' % name)
1642 for item in items:
1643 item.handle()
1644 sys.stdout.write('\n')
pam@chromium.orged9a0832009-09-09 22:48:55 +00001645
Edward Lemurecc27072020-01-06 16:42:34 +00001646 total_time = time_time() - start_time
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001647 if total_time > 1.0:
Edward Lemur6eb1d322020-02-27 22:20:15 +00001648 sys.stdout.write(
1649 'Presubmit checks took %.1fs to calculate.\n\n' % total_time)
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +00001650
Edward Lemur6eb1d322020-02-27 22:20:15 +00001651 if not should_prompt and not presubmits_failed:
1652 sys.stdout.write('Presubmit checks passed.\n')
1653 elif should_prompt:
1654 sys.stdout.write('There were presubmit warnings. ')
Quinten Yearsley516fe7f2016-12-14 11:50:18 -08001655 if may_prompt:
Edward Lemur6eb1d322020-02-27 22:20:15 +00001656 presubmits_failed = not prompt_should_continue(
1657 'Are you sure you wish to continue? (y/N): ')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001658
Edward Lemur1dc66e12020-02-21 21:36:34 +00001659 if json_output:
1660 # Write the presubmit results to json output
1661 presubmit_results = {
1662 'errors': [
Edward Lemur6eb1d322020-02-27 22:20:15 +00001663 error.json_format()
1664 for error in messages.get('ERRORS', [])
Edward Lemur1dc66e12020-02-21 21:36:34 +00001665 ],
1666 'notifications': [
Edward Lemur6eb1d322020-02-27 22:20:15 +00001667 notification.json_format()
1668 for notification in messages.get('Messages', [])
Edward Lemur1dc66e12020-02-21 21:36:34 +00001669 ],
1670 'warnings': [
Edward Lemur6eb1d322020-02-27 22:20:15 +00001671 warning.json_format()
1672 for warning in messages.get('Warnings', [])
Edward Lemur1dc66e12020-02-21 21:36:34 +00001673 ],
Edward Lemur6eb1d322020-02-27 22:20:15 +00001674 'more_cc': executer.more_cc,
Edward Lemur1dc66e12020-02-21 21:36:34 +00001675 }
1676
1677 gclient_utils.FileWrite(
1678 json_output, json.dumps(presubmit_results, sort_keys=True))
1679
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001680 global _ASKED_FOR_FEEDBACK
1681 # Ask for feedback one time out of 5.
1682 if (len(results) and random.randint(0, 4) == 0 and not _ASKED_FOR_FEEDBACK):
Edward Lemur6eb1d322020-02-27 22:20:15 +00001683 sys.stdout.write(
maruel@chromium.org1ce8e662014-01-14 15:23:00 +00001684 'Was the presubmit check useful? If not, run "git cl presubmit -v"\n'
1685 'to figure out which PRESUBMIT.py was run, then run git blame\n'
1686 'on the file to figure out who to ask for help.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001687 _ASKED_FOR_FEEDBACK = True
Edward Lemur6eb1d322020-02-27 22:20:15 +00001688
1689 return 1 if presubmits_failed else 0
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001690 finally:
1691 os.environ = old_environ
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001692
1693
Edward Lemur50984a62020-02-06 18:10:18 +00001694def _scan_sub_dirs(mask, recursive):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001695 if not recursive:
pgervais@chromium.orge57b09d2014-05-07 00:58:13 +00001696 return [x for x in glob.glob(mask) if x not in ('.svn', '.git')]
Lei Zhang9611c4c2017-04-04 01:41:56 -07001697
1698 results = []
1699 for root, dirs, files in os.walk('.'):
1700 if '.svn' in dirs:
1701 dirs.remove('.svn')
1702 if '.git' in dirs:
1703 dirs.remove('.git')
1704 for name in files:
1705 if fnmatch.fnmatch(name, mask):
1706 results.append(os.path.join(root, name))
1707 return results
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001708
1709
Edward Lemur50984a62020-02-06 18:10:18 +00001710def _parse_files(args, recursive):
tobiasjs2836bcf2016-08-16 04:08:16 -07001711 logging.debug('Searching for %s', args)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001712 files = []
1713 for arg in args:
Edward Lemur50984a62020-02-06 18:10:18 +00001714 files.extend([('M', f) for f in _scan_sub_dirs(arg, recursive)])
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001715 return files
1716
1717
Edward Lemur50984a62020-02-06 18:10:18 +00001718def _parse_change(parser, options):
1719 """Process change options.
1720
1721 Args:
1722 parser: The parser used to parse the arguments from command line.
1723 options: The arguments parsed from command line.
1724 Returns:
1725 A GitChange if the change root is a git repository, or a Change otherwise.
1726 """
1727 if options.files and options.all_files:
1728 parser.error('<files> cannot be specified when --all-files is set.')
1729
Edward Lesmes44ea3ff2020-02-05 00:14:30 +00001730 change_scm = scm.determine_scm(options.root)
Edward Lemur50984a62020-02-06 18:10:18 +00001731 if change_scm != 'git' and not options.files:
1732 parser.error('<files> is not optional for unversioned directories.')
1733
1734 if options.files:
1735 change_files = _parse_files(options.files, options.recursive)
1736 elif options.all_files:
1737 change_files = [('M', f) for f in scm.GIT.GetAllFiles(options.root)]
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001738 else:
Edward Lemur50984a62020-02-06 18:10:18 +00001739 change_files = scm.GIT.CaptureStatus(
Edward Lemur7f6dec02020-02-06 20:23:58 +00001740 options.root, options.upstream or None)
Edward Lemur50984a62020-02-06 18:10:18 +00001741
1742 logging.info('Found %d file(s).', len(change_files))
1743
1744 change_class = GitChange if change_scm == 'git' else Change
1745 return change_class(
1746 options.name,
1747 options.description,
1748 options.root,
1749 change_files,
1750 options.issue,
1751 options.patchset,
1752 options.author,
1753 upstream=options.upstream)
1754
1755
1756def _parse_gerrit_options(parser, options):
1757 """Process gerrit options.
1758
1759 SIDE EFFECTS: Modifies options.author and options.description from Gerrit if
1760 options.gerrit_fetch is set.
1761
1762 Args:
1763 parser: The parser used to parse the arguments from command line.
1764 options: The arguments parsed from command line.
1765 Returns:
1766 A GerritAccessor object if options.gerrit_url is set, or None otherwise.
1767 """
1768 gerrit_obj = None
1769 if options.gerrit_url:
1770 gerrit_obj = GerritAccessor(urlparse.urlparse(options.gerrit_url).netloc)
1771
1772 if not options.gerrit_fetch:
1773 return gerrit_obj
1774
1775 if not options.gerrit_url or not options.issue or not options.patchset:
1776 parser.error(
1777 '--gerrit_fetch requires --gerrit_url, --issue and --patchset.')
1778
1779 options.author = gerrit_obj.GetChangeOwner(options.issue)
1780 options.description = gerrit_obj.GetChangeDescription(
1781 options.issue, options.patchset)
1782
1783 logging.info('Got author: "%s"', options.author)
1784 logging.info('Got description: """\n%s\n"""', options.description)
1785
1786 return gerrit_obj
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001787
1788
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001789@contextlib.contextmanager
1790def canned_check_filter(method_names):
1791 filtered = {}
1792 try:
1793 for method_name in method_names:
1794 if not hasattr(presubmit_canned_checks, method_name):
Aaron Gableecee74c2018-04-02 15:13:08 -07001795 logging.warn('Skipping unknown "canned" check %s' % method_name)
1796 continue
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001797 filtered[method_name] = getattr(presubmit_canned_checks, method_name)
1798 setattr(presubmit_canned_checks, method_name, lambda *_a, **_kw: [])
1799 yield
1800 finally:
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00001801 for name, method in filtered.items():
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001802 setattr(presubmit_canned_checks, name, method)
1803
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001804
sbc@chromium.org013731e2015-02-26 18:28:43 +00001805def main(argv=None):
Edward Lemura5799e32020-01-17 19:26:51 +00001806 parser = argparse.ArgumentParser(usage='%(prog)s [options] <files...>')
1807 hooks = parser.add_mutually_exclusive_group()
1808 hooks.add_argument('-c', '--commit', action='store_true',
1809 help='Use commit instead of upload checks.')
1810 hooks.add_argument('-u', '--upload', action='store_false', dest='commit',
1811 help='Use upload instead of commit checks.')
1812 parser.add_argument('-r', '--recursive', action='store_true',
1813 help='Act recursively.')
1814 parser.add_argument('-v', '--verbose', action='count', default=0,
1815 help='Use 2 times for more debug info.')
1816 parser.add_argument('--name', default='no name')
1817 parser.add_argument('--author')
Edward Lemur227d5102020-02-25 23:45:35 +00001818 desc = parser.add_mutually_exclusive_group()
1819 desc.add_argument('--description', default='', help='The change description.')
1820 desc.add_argument('--description_file',
1821 help='File to read change description from.')
Edward Lemura5799e32020-01-17 19:26:51 +00001822 parser.add_argument('--issue', type=int, default=0)
1823 parser.add_argument('--patchset', type=int, default=0)
1824 parser.add_argument('--root', default=os.getcwd(),
1825 help='Search for PRESUBMIT.py up to this directory. '
1826 'If inherit-review-settings-ok is present in this '
1827 'directory, parent directories up to the root file '
1828 'system directories will also be searched.')
1829 parser.add_argument('--upstream',
1830 help='Git only: the base ref or upstream branch against '
1831 'which the diff should be computed.')
1832 parser.add_argument('--default_presubmit')
1833 parser.add_argument('--may_prompt', action='store_true', default=False)
1834 parser.add_argument('--skip_canned', action='append', default=[],
1835 help='A list of checks to skip which appear in '
1836 'presubmit_canned_checks. Can be provided multiple times '
1837 'to skip multiple canned checks.')
1838 parser.add_argument('--dry_run', action='store_true', help=argparse.SUPPRESS)
1839 parser.add_argument('--gerrit_url', help=argparse.SUPPRESS)
1840 parser.add_argument('--gerrit_fetch', action='store_true',
1841 help=argparse.SUPPRESS)
1842 parser.add_argument('--parallel', action='store_true',
1843 help='Run all tests specified by input_api.RunTests in '
1844 'all PRESUBMIT files in parallel.')
1845 parser.add_argument('--json_output',
1846 help='Write presubmit errors to json output.')
Edward Lemur1dc66e12020-02-21 21:36:34 +00001847 parser.add_argument('--all_files', action='store_true',
Edward Lemur50984a62020-02-06 18:10:18 +00001848 help='Mark all files under source control as modified.')
Edward Lemura5799e32020-01-17 19:26:51 +00001849 parser.add_argument('files', nargs='*',
1850 help='List of files to be marked as modified when '
1851 'executing presubmit or post-upload hooks. fnmatch '
1852 'wildcards can also be used.')
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001853
Edward Lemura5799e32020-01-17 19:26:51 +00001854 options = parser.parse_args(argv)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001855
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001856 if options.verbose >= 2:
maruel@chromium.org7444c502011-02-09 14:02:11 +00001857 logging.basicConfig(level=logging.DEBUG)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001858 elif options.verbose:
1859 logging.basicConfig(level=logging.INFO)
1860 else:
1861 logging.basicConfig(level=logging.ERROR)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001862
Edward Lemur227d5102020-02-25 23:45:35 +00001863 if options.description_file:
1864 options.description = gclient_utils.FileRead(options.description_file)
Edward Lemur50984a62020-02-06 18:10:18 +00001865 gerrit_obj = _parse_gerrit_options(parser, options)
1866 change = _parse_change(parser, options)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001867
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001868 try:
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001869 with canned_check_filter(options.skip_canned):
Edward Lemur6eb1d322020-02-27 22:20:15 +00001870 return DoPresubmitChecks(
Edward Lemur50984a62020-02-06 18:10:18 +00001871 change,
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001872 options.commit,
1873 options.verbose,
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001874 options.default_presubmit,
1875 options.may_prompt,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001876 gerrit_obj,
Edward Lesmes8e282792018-04-03 18:50:29 -04001877 options.dry_run,
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001878 options.parallel,
1879 options.json_output)
Raul Tambre7c938462019-05-24 16:35:35 +00001880 except PresubmitFailure as e:
Raul Tambre80ee78e2019-05-06 22:41:05 +00001881 print(e, file=sys.stderr)
1882 print('Maybe your depot_tools is out of date?', file=sys.stderr)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001883 return 2
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001884
1885
1886if __name__ == '__main__':
maruel@chromium.org35625c72011-03-23 17:34:02 +00001887 fix_encoding.fix_encoding()
sbc@chromium.org013731e2015-02-26 18:28:43 +00001888 try:
1889 sys.exit(main())
1890 except KeyboardInterrupt:
1891 sys.stderr.write('interrupted\n')
sergiybf8a3b382016-07-05 11:21:30 -07001892 sys.exit(2)