blob: c53ed8fa18c5d77c11455c67d5c278a6419a572a [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
Saagar Sanghavi99816902020-08-11 22:41:25 +000011__version__ = '2.0.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
Edward Lesmes9ce03f82021-01-12 20:13:31 +000046import owners as owners_db
47import owners_client
Jochen Eisinger76f5fc62017-04-07 16:27:46 +020048import owners_finder
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000049import presubmit_canned_checks
Saagar Sanghavi9949ab72020-07-20 20:56:40 +000050import rdb_wrapper
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +000051import scm
maruel@chromium.org84f4fe32011-04-06 13:26:45 +000052import subprocess2 as subprocess # Exposed through the API.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000053
Edward Lemur16af3562019-10-17 22:11:33 +000054if sys.version_info.major == 2:
55 # TODO(1009814): Expose urllib2 only through urllib_request and urllib_error
56 import urllib2 # Exposed through the API.
57 import urlparse
58 import urllib2 as urllib_request
59 import urllib2 as urllib_error
60else:
61 import urllib.parse as urlparse
62 import urllib.request as urllib_request
63 import urllib.error as urllib_error
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000064
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +000065# Ask for feedback only once in program lifetime.
66_ASKED_FOR_FEEDBACK = False
67
Edward Lemurecc27072020-01-06 16:42:34 +000068def time_time():
69 # Use this so that it can be mocked in tests without interfering with python
70 # system machinery.
71 return time.time()
72
73
maruel@chromium.org899e1c12011-04-07 17:03:18 +000074class PresubmitFailure(Exception):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000075 pass
76
77
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +000078class CommandData(object):
Edward Lemur940c2822019-08-23 00:34:25 +000079 def __init__(self, name, cmd, kwargs, message, python3=False):
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +000080 self.name = name
81 self.cmd = cmd
Edward Lesmes8e282792018-04-03 18:50:29 -040082 self.stdin = kwargs.get('stdin', None)
Edward Lemur2d6b67c2019-08-23 22:25:41 +000083 self.kwargs = kwargs.copy()
Edward Lesmes8e282792018-04-03 18:50:29 -040084 self.kwargs['stdout'] = subprocess.PIPE
85 self.kwargs['stderr'] = subprocess.STDOUT
86 self.kwargs['stdin'] = subprocess.PIPE
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +000087 self.message = message
88 self.info = None
Edward Lemur940c2822019-08-23 00:34:25 +000089 self.python3 = python3
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +000090
ilevy@chromium.orgbc117312013-04-20 03:57:56 +000091
Edward Lesmes8e282792018-04-03 18:50:29 -040092# Adapted from
93# https://github.com/google/gtest-parallel/blob/master/gtest_parallel.py#L37
94#
95# An object that catches SIGINT sent to the Python process and notices
96# if processes passed to wait() die by SIGINT (we need to look for
97# both of those cases, because pressing Ctrl+C can result in either
98# the main process or one of the subprocesses getting the signal).
99#
100# Before a SIGINT is seen, wait(p) will simply call p.wait() and
101# return the result. Once a SIGINT has been seen (in the main process
102# or a subprocess, including the one the current call is waiting for),
Edward Lemur9a5bb612019-09-26 02:01:52 +0000103# wait(p) will call p.terminate().
Edward Lesmes8e282792018-04-03 18:50:29 -0400104class SigintHandler(object):
Edward Lesmes8e282792018-04-03 18:50:29 -0400105 sigint_returncodes = {-signal.SIGINT, # Unix
106 -1073741510, # Windows
107 }
108 def __init__(self):
109 self.__lock = threading.Lock()
110 self.__processes = set()
111 self.__got_sigint = False
Edward Lemur9a5bb612019-09-26 02:01:52 +0000112 self.__previous_signal = signal.signal(signal.SIGINT, self.interrupt)
Edward Lesmes8e282792018-04-03 18:50:29 -0400113
114 def __on_sigint(self):
115 self.__got_sigint = True
116 while self.__processes:
117 try:
118 self.__processes.pop().terminate()
119 except OSError:
120 pass
121
Edward Lemur9a5bb612019-09-26 02:01:52 +0000122 def interrupt(self, signal_num, frame):
Edward Lesmes8e282792018-04-03 18:50:29 -0400123 with self.__lock:
124 self.__on_sigint()
Edward Lemur9a5bb612019-09-26 02:01:52 +0000125 self.__previous_signal(signal_num, frame)
Edward Lesmes8e282792018-04-03 18:50:29 -0400126
127 def got_sigint(self):
128 with self.__lock:
129 return self.__got_sigint
130
131 def wait(self, p, stdin):
132 with self.__lock:
133 if self.__got_sigint:
134 p.terminate()
135 self.__processes.add(p)
136 stdout, stderr = p.communicate(stdin)
137 code = p.returncode
138 with self.__lock:
139 self.__processes.discard(p)
140 if code in self.sigint_returncodes:
141 self.__on_sigint()
Edward Lesmes8e282792018-04-03 18:50:29 -0400142 return stdout, stderr
143
144sigint_handler = SigintHandler()
145
146
Edward Lemurecc27072020-01-06 16:42:34 +0000147class Timer(object):
148 def __init__(self, timeout, fn):
149 self.completed = False
150 self._fn = fn
151 self._timer = threading.Timer(timeout, self._onTimer) if timeout else None
152
153 def __enter__(self):
154 if self._timer:
155 self._timer.start()
156 return self
157
158 def __exit__(self, _type, _value, _traceback):
159 if self._timer:
160 self._timer.cancel()
161
162 def _onTimer(self):
163 self._fn()
164 self.completed = True
165
166
Edward Lesmes8e282792018-04-03 18:50:29 -0400167class ThreadPool(object):
Edward Lemurecc27072020-01-06 16:42:34 +0000168 def __init__(self, pool_size=None, timeout=None):
169 self.timeout = timeout
Edward Lesmes8e282792018-04-03 18:50:29 -0400170 self._pool_size = pool_size or multiprocessing.cpu_count()
171 self._messages = []
172 self._messages_lock = threading.Lock()
173 self._tests = []
174 self._tests_lock = threading.Lock()
175 self._nonparallel_tests = []
176
Edward Lemurecc27072020-01-06 16:42:34 +0000177 def _GetCommand(self, test):
Edward Lemur940c2822019-08-23 00:34:25 +0000178 vpython = 'vpython'
179 if test.python3:
180 vpython += '3'
181 if sys.platform == 'win32':
182 vpython += '.bat'
Edward Lesmes8e282792018-04-03 18:50:29 -0400183
184 cmd = test.cmd
185 if cmd[0] == 'python':
186 cmd = list(cmd)
187 cmd[0] = vpython
188 elif cmd[0].endswith('.py'):
189 cmd = [vpython] + cmd
190
Edward Lemur336e51f2019-11-14 21:42:04 +0000191 # On Windows, scripts on the current directory take precedence over PATH, so
192 # that when testing depot_tools on Windows, calling `vpython.bat` will
193 # execute the copy of vpython of the depot_tools under test instead of the
194 # one in the bot.
195 # As a workaround, we run the tests from the parent directory instead.
196 if (cmd[0] == vpython and
197 'cwd' in test.kwargs and
198 os.path.basename(test.kwargs['cwd']) == 'depot_tools'):
199 test.kwargs['cwd'] = os.path.dirname(test.kwargs['cwd'])
200 cmd[1] = os.path.join('depot_tools', cmd[1])
201
Edward Lemurecc27072020-01-06 16:42:34 +0000202 return cmd
203
204 def _RunWithTimeout(self, cmd, stdin, kwargs):
205 p = subprocess.Popen(cmd, **kwargs)
206 with Timer(self.timeout, p.terminate) as timer:
207 stdout, _ = sigint_handler.wait(p, stdin)
208 if timer.completed:
209 stdout = 'Process timed out after %ss\n%s' % (self.timeout, stdout)
210 return p.returncode, stdout
211
212 def CallCommand(self, test):
213 """Runs an external program.
214
Edward Lemura5799e32020-01-17 19:26:51 +0000215 This function converts invocation of .py files and invocations of 'python'
Edward Lemurecc27072020-01-06 16:42:34 +0000216 to vpython invocations.
217 """
218 cmd = self._GetCommand(test)
Edward Lesmes8e282792018-04-03 18:50:29 -0400219 try:
Edward Lemurecc27072020-01-06 16:42:34 +0000220 start = time_time()
221 returncode, stdout = self._RunWithTimeout(cmd, test.stdin, test.kwargs)
222 duration = time_time() - start
Edward Lemur7cf94382019-11-15 22:36:41 +0000223 except Exception:
Edward Lemurecc27072020-01-06 16:42:34 +0000224 duration = time_time() - start
Edward Lesmes8e282792018-04-03 18:50:29 -0400225 return test.message(
Edward Lemur7cf94382019-11-15 22:36:41 +0000226 '%s\n%s exec failure (%4.2fs)\n%s' % (
227 test.name, ' '.join(cmd), duration, traceback.format_exc()))
Edward Lemurde9e3ca2019-10-24 21:13:31 +0000228
Edward Lemurecc27072020-01-06 16:42:34 +0000229 if returncode != 0:
Edward Lesmes8e282792018-04-03 18:50:29 -0400230 return test.message(
Edward Lemur7cf94382019-11-15 22:36:41 +0000231 '%s\n%s (%4.2fs) failed\n%s' % (
232 test.name, ' '.join(cmd), duration, stdout))
Edward Lemurecc27072020-01-06 16:42:34 +0000233
Edward Lesmes8e282792018-04-03 18:50:29 -0400234 if test.info:
Edward Lemur7cf94382019-11-15 22:36:41 +0000235 return test.info('%s\n%s (%4.2fs)' % (test.name, ' '.join(cmd), duration))
Edward Lesmes8e282792018-04-03 18:50:29 -0400236
237 def AddTests(self, tests, parallel=True):
238 if parallel:
239 self._tests.extend(tests)
240 else:
241 self._nonparallel_tests.extend(tests)
242
243 def RunAsync(self):
244 self._messages = []
245
246 def _WorkerFn():
247 while True:
248 test = None
249 with self._tests_lock:
250 if not self._tests:
251 break
252 test = self._tests.pop()
253 result = self.CallCommand(test)
254 if result:
255 with self._messages_lock:
256 self._messages.append(result)
257
258 def _StartDaemon():
259 t = threading.Thread(target=_WorkerFn)
260 t.daemon = True
261 t.start()
262 return t
263
264 while self._nonparallel_tests:
265 test = self._nonparallel_tests.pop()
266 result = self.CallCommand(test)
267 if result:
268 self._messages.append(result)
269
270 if self._tests:
271 threads = [_StartDaemon() for _ in range(self._pool_size)]
272 for worker in threads:
273 worker.join()
274
275 return self._messages
276
277
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000278def normpath(path):
279 '''Version of os.path.normpath that also changes backward slashes to
280 forward slashes when not running on Windows.
281 '''
282 # This is safe to always do because the Windows version of os.path.normpath
283 # will replace forward slashes with backward slashes.
284 path = path.replace(os.sep, '/')
285 return os.path.normpath(path)
286
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000287
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000288def _RightHandSideLinesImpl(affected_files):
289 """Implements RightHandSideLines for InputApi and GclChange."""
290 for af in affected_files:
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000291 lines = af.ChangedContents()
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000292 for line in lines:
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000293 yield (af, line[0], line[1])
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000294
295
Edward Lemur6eb1d322020-02-27 22:20:15 +0000296def prompt_should_continue(prompt_string):
297 sys.stdout.write(prompt_string)
298 response = sys.stdin.readline().strip().lower()
299 return response in ('y', 'yes')
dpranke@chromium.org5ac21012011-03-16 02:58:25 +0000300
301
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000302# Top level object so multiprocessing can pickle
303# Public access through OutputApi object.
304class _PresubmitResult(object):
305 """Base class for result objects."""
306 fatal = False
307 should_prompt = False
308
309 def __init__(self, message, items=None, long_text=''):
310 """
311 message: A short one-line message to indicate errors.
312 items: A list of short strings to indicate where errors occurred.
313 long_text: multi-line text output, e.g. from another tool
314 """
315 self._message = message
316 self._items = items or []
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000317 self._long_text = long_text.rstrip()
318
Edward Lemur6eb1d322020-02-27 22:20:15 +0000319 def handle(self):
320 sys.stdout.write(self._message)
321 sys.stdout.write('\n')
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000322 for index, item in enumerate(self._items):
Edward Lemur6eb1d322020-02-27 22:20:15 +0000323 sys.stdout.write(' ')
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000324 # Write separately in case it's unicode.
Edward Lemur6eb1d322020-02-27 22:20:15 +0000325 sys.stdout.write(str(item))
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000326 if index < len(self._items) - 1:
Edward Lemur6eb1d322020-02-27 22:20:15 +0000327 sys.stdout.write(' \\')
328 sys.stdout.write('\n')
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000329 if self._long_text:
Edward Lemur6eb1d322020-02-27 22:20:15 +0000330 sys.stdout.write('\n***************\n')
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000331 # Write separately in case it's unicode.
Edward Lemur6eb1d322020-02-27 22:20:15 +0000332 sys.stdout.write(self._long_text)
333 sys.stdout.write('\n***************\n')
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000334
Debrian Figueroadd2737e2019-06-21 23:50:13 +0000335 def json_format(self):
336 return {
337 'message': self._message,
Debrian Figueroa6095d402019-06-28 18:47:18 +0000338 'items': [str(item) for item in self._items],
Debrian Figueroadd2737e2019-06-21 23:50:13 +0000339 'long_text': self._long_text,
340 'fatal': self.fatal
341 }
342
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000343
344# Top level object so multiprocessing can pickle
345# Public access through OutputApi object.
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000346class _PresubmitError(_PresubmitResult):
347 """A hard presubmit error."""
348 fatal = True
349
350
351# Top level object so multiprocessing can pickle
352# Public access through OutputApi object.
353class _PresubmitPromptWarning(_PresubmitResult):
354 """An warning that prompts the user if they want to continue."""
355 should_prompt = True
356
357
358# Top level object so multiprocessing can pickle
359# Public access through OutputApi object.
360class _PresubmitNotifyResult(_PresubmitResult):
361 """Just print something to the screen -- but it's not even a warning."""
362 pass
363
364
365# Top level object so multiprocessing can pickle
366# Public access through OutputApi object.
367class _MailTextResult(_PresubmitResult):
368 """A warning that should be included in the review request email."""
369 def __init__(self, *args, **kwargs):
370 super(_MailTextResult, self).__init__()
371 raise NotImplementedError()
372
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000373class GerritAccessor(object):
374 """Limited Gerrit functionality for canned presubmit checks to work.
375
376 To avoid excessive Gerrit calls, caches the results.
377 """
378
Edward Lesmeseb1bd622021-03-01 19:54:07 +0000379 def __init__(self, url=None, project=None, branch=None):
380 self.host = urlparse.urlparse(url).netloc if url else None
381 self.project = project
382 self.branch = branch
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000383 self.cache = {}
384
385 def _FetchChangeDetail(self, issue):
386 # Separate function to be easily mocked in tests.
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +0100387 try:
388 return gerrit_util.GetChangeDetail(
389 self.host, str(issue),
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700390 ['ALL_REVISIONS', 'DETAILED_LABELS', 'ALL_COMMITS'])
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +0100391 except gerrit_util.GerritError as e:
392 if e.http_status == 404:
393 raise Exception('Either Gerrit issue %s doesn\'t exist, or '
394 'no credentials to fetch issue details' % issue)
395 raise
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000396
397 def GetChangeInfo(self, issue):
398 """Returns labels and all revisions (patchsets) for this issue.
399
400 The result is a dictionary according to Gerrit REST Api.
401 https://gerrit-review.googlesource.com/Documentation/rest-api.html
402
403 However, API isn't very clear what's inside, so see tests for example.
404 """
405 assert issue
406 cache_key = int(issue)
407 if cache_key not in self.cache:
408 self.cache[cache_key] = self._FetchChangeDetail(issue)
409 return self.cache[cache_key]
410
411 def GetChangeDescription(self, issue, patchset=None):
412 """If patchset is none, fetches current patchset."""
413 info = self.GetChangeInfo(issue)
414 # info is a reference to cache. We'll modify it here adding description to
415 # it to the right patchset, if it is not yet there.
416
417 # Find revision info for the patchset we want.
418 if patchset is not None:
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000419 for rev, rev_info in info['revisions'].items():
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000420 if str(rev_info['_number']) == str(patchset):
421 break
422 else:
423 raise Exception('patchset %s doesn\'t exist in issue %s' % (
424 patchset, issue))
425 else:
426 rev = info['current_revision']
427 rev_info = info['revisions'][rev]
428
Andrii Shyshkalov9c3a4642017-01-24 17:41:22 +0100429 return rev_info['commit']['message']
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000430
Mun Yong Jang603d01e2017-12-19 16:38:30 -0800431 def GetDestRef(self, issue):
432 ref = self.GetChangeInfo(issue)['branch']
433 if not ref.startswith('refs/'):
434 # NOTE: it is possible to create 'refs/x' branch,
435 # aka 'refs/heads/refs/x'. However, this is ill-advised.
436 ref = 'refs/heads/%s' % ref
437 return ref
438
Edward Lesmes02d4b822020-11-11 00:37:35 +0000439 def _GetApproversForLabel(self, issue, label):
440 change_info = self.GetChangeInfo(issue)
441 label_info = change_info.get('labels', {}).get(label, {})
442 values = label_info.get('values', {}).keys()
443 if not values:
444 return []
445 max_value = max(int(v) for v in values)
446 return [v for v in label_info.get('all', [])
447 if v.get('value', 0) == max_value]
448
Edward Lesmescf49cb82020-11-11 01:08:36 +0000449 def IsOwnersOverrideApproved(self, issue):
450 return bool(self._GetApproversForLabel(issue, 'Owners-Override'))
451
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000452 def GetChangeOwner(self, issue):
453 return self.GetChangeInfo(issue)['owner']['email']
454
455 def GetChangeReviewers(self, issue, approving_only=True):
Aaron Gable8b478f02017-07-31 15:33:19 -0700456 changeinfo = self.GetChangeInfo(issue)
457 if approving_only:
Edward Lesmes02d4b822020-11-11 00:37:35 +0000458 reviewers = self._GetApproversForLabel(issue, 'Code-Review')
Aaron Gable8b478f02017-07-31 15:33:19 -0700459 else:
460 reviewers = changeinfo.get('reviewers', {}).get('REVIEWER', [])
461 return [r.get('email') for r in reviewers]
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000462
Edward Lemure4d329c2020-02-03 20:41:18 +0000463 def UpdateDescription(self, description, issue):
464 gerrit_util.SetCommitMessage(self.host, issue, description, notify='NONE')
465
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000466
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000467class OutputApi(object):
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000468 """An instance of OutputApi gets passed to presubmit scripts so that they
469 can output various types of results.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000470 """
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000471 PresubmitResult = _PresubmitResult
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000472 PresubmitError = _PresubmitError
473 PresubmitPromptWarning = _PresubmitPromptWarning
474 PresubmitNotifyResult = _PresubmitNotifyResult
475 MailTextResult = _MailTextResult
476
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000477 def __init__(self, is_committing):
478 self.is_committing = is_committing
Daniel Cheng7227d212017-11-17 08:12:37 -0800479 self.more_cc = []
480
481 def AppendCC(self, cc):
482 """Appends a user to cc for this change."""
483 self.more_cc.append(cc)
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000484
wez@chromium.orga6d011e2013-03-26 17:31:49 +0000485 def PresubmitPromptOrNotify(self, *args, **kwargs):
486 """Warn the user when uploading, but only notify if committing."""
487 if self.is_committing:
488 return self.PresubmitNotifyResult(*args, **kwargs)
489 return self.PresubmitPromptWarning(*args, **kwargs)
490
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000491
492class InputApi(object):
493 """An instance of this object is passed to presubmit scripts so they can
494 know stuff about the change they're looking at.
495 """
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000496 # Method could be a function
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800497 # pylint: disable=no-self-use
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000498
maruel@chromium.org3410d912009-06-09 20:56:16 +0000499 # File extensions that are considered source files from a style guide
500 # perspective. Don't modify this list from a presubmit script!
maruel@chromium.orgc33455a2011-06-24 19:14:18 +0000501 #
502 # Files without an extension aren't included in the list. If you want to
local_bot30f774e2020-06-25 18:23:34 +0000503 # filter them as source files, add r'(^|.*?[\\\/])[^.]+$' to the allow list.
local_bot64021412020-07-08 21:05:39 +0000504 # Note that ALL CAPS files are skipped in DEFAULT_FILES_TO_SKIP below.
505 DEFAULT_FILES_TO_CHECK = (
maruel@chromium.org3410d912009-06-09 20:56:16 +0000506 # C++ and friends
Edward Lemura5799e32020-01-17 19:26:51 +0000507 r'.+\.c$', r'.+\.cc$', r'.+\.cpp$', r'.+\.h$', r'.+\.m$', r'.+\.mm$',
508 r'.+\.inl$', r'.+\.asm$', r'.+\.hxx$', r'.+\.hpp$', r'.+\.s$', r'.+\.S$',
maruel@chromium.org3410d912009-06-09 20:56:16 +0000509 # Scripts
Edward Lemura5799e32020-01-17 19:26:51 +0000510 r'.+\.js$', r'.+\.py$', r'.+\.sh$', r'.+\.rb$', r'.+\.pl$', r'.+\.pm$',
maruel@chromium.org3410d912009-06-09 20:56:16 +0000511 # Other
Edward Lemura5799e32020-01-17 19:26:51 +0000512 r'.+\.java$', r'.+\.mk$', r'.+\.am$', r'.+\.css$', r'.+\.mojom$',
513 r'.+\.fidl$'
maruel@chromium.org3410d912009-06-09 20:56:16 +0000514 )
515
516 # Path regexp that should be excluded from being considered containing source
517 # files. Don't modify this list from a presubmit script!
local_bot64021412020-07-08 21:05:39 +0000518 DEFAULT_FILES_TO_SKIP = (
Edward Lemura5799e32020-01-17 19:26:51 +0000519 r'testing_support[\\\/]google_appengine[\\\/].*',
520 r'.*\bexperimental[\\\/].*',
Kent Tamura179dd1e2018-04-26 15:07:41 +0900521 # Exclude third_party/.* but NOT third_party/{WebKit,blink}
522 # (crbug.com/539768 and crbug.com/836555).
Edward Lemura5799e32020-01-17 19:26:51 +0000523 r'.*\bthird_party[\\\/](?!(WebKit|blink)[\\\/]).*',
maruel@chromium.org3410d912009-06-09 20:56:16 +0000524 # Output directories (just in case)
Edward Lemura5799e32020-01-17 19:26:51 +0000525 r'.*\bDebug[\\\/].*',
526 r'.*\bRelease[\\\/].*',
527 r'.*\bxcodebuild[\\\/].*',
528 r'.*\bout[\\\/].*',
maruel@chromium.org3410d912009-06-09 20:56:16 +0000529 # All caps files like README and LICENCE.
Edward Lemura5799e32020-01-17 19:26:51 +0000530 r'.*\b[A-Z0-9_]{2,}$',
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000531 # SCM (can happen in dual SCM configuration). (Slightly over aggressive)
Edward Lemura5799e32020-01-17 19:26:51 +0000532 r'(|.*[\\\/])\.git[\\\/].*',
533 r'(|.*[\\\/])\.svn[\\\/].*',
maruel@chromium.org7ccb4bb2011-11-07 20:26:20 +0000534 # There is no point in processing a patch file.
Edward Lemura5799e32020-01-17 19:26:51 +0000535 r'.+\.diff$',
536 r'.+\.patch$',
maruel@chromium.org3410d912009-06-09 20:56:16 +0000537 )
538
local_bot30f774e2020-06-25 18:23:34 +0000539 # TODO(https://crbug.com/1098562): Remove once no longer used
540 @property
541 def DEFAULT_WHITE_LIST(self):
local_bot64021412020-07-08 21:05:39 +0000542 return self.DEFAULT_FILES_TO_CHECK
local_bot30f774e2020-06-25 18:23:34 +0000543
544 # TODO(https://crbug.com/1098562): Remove once no longer used
local_bot37ce2012020-06-26 17:39:24 +0000545 @DEFAULT_WHITE_LIST.setter
546 def DEFAULT_WHITE_LIST(self, value):
local_bot64021412020-07-08 21:05:39 +0000547 self.DEFAULT_FILES_TO_CHECK = value
548
549 # TODO(https://crbug.com/1098562): Remove once no longer used
550 @property
551 def DEFAULT_ALLOW_LIST(self):
552 return self.DEFAULT_FILES_TO_CHECK
553
554 # TODO(https://crbug.com/1098562): Remove once no longer used
555 @DEFAULT_ALLOW_LIST.setter
556 def DEFAULT_ALLOW_LIST(self, value):
557 self.DEFAULT_FILES_TO_CHECK = value
local_bot37ce2012020-06-26 17:39:24 +0000558
559 # TODO(https://crbug.com/1098562): Remove once no longer used
local_bot30f774e2020-06-25 18:23:34 +0000560 @property
561 def DEFAULT_BLACK_LIST(self):
local_bot64021412020-07-08 21:05:39 +0000562 return self.DEFAULT_FILES_TO_SKIP
local_bot30f774e2020-06-25 18:23:34 +0000563
local_bot37ce2012020-06-26 17:39:24 +0000564 # TODO(https://crbug.com/1098562): Remove once no longer used
565 @DEFAULT_BLACK_LIST.setter
566 def DEFAULT_BLACK_LIST(self, value):
local_bot64021412020-07-08 21:05:39 +0000567 self.DEFAULT_FILES_TO_SKIP = value
568
569 # TODO(https://crbug.com/1098562): Remove once no longer used
570 @property
571 def DEFAULT_BLOCK_LIST(self):
572 return self.DEFAULT_FILES_TO_SKIP
573
574 # TODO(https://crbug.com/1098562): Remove once no longer used
575 @DEFAULT_BLOCK_LIST.setter
576 def DEFAULT_BLOCK_LIST(self, value):
577 self.DEFAULT_FILES_TO_SKIP = value
local_bot37ce2012020-06-26 17:39:24 +0000578
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000579 def __init__(self, change, presubmit_path, is_committing,
Edward Lesmes8e282792018-04-03 18:50:29 -0400580 verbose, gerrit_obj, dry_run=None, thread_pool=None, parallel=False):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000581 """Builds an InputApi object.
582
583 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000584 change: A presubmit.Change object.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000585 presubmit_path: The path to the presubmit script being processed.
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000586 is_committing: True if the change is about to be committed.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000587 gerrit_obj: provides basic Gerrit codereview functionality.
588 dry_run: if true, some Checks will be skipped.
Edward Lesmes8e282792018-04-03 18:50:29 -0400589 parallel: if true, all tests reported via input_api.RunTests for all
590 PRESUBMIT files will be run in parallel.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000591 """
maruel@chromium.org9711bba2009-05-22 23:51:39 +0000592 # Version number of the presubmit_support script.
593 self.version = [int(x) for x in __version__.split('.')]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000594 self.change = change
maruel@chromium.orgd7dccf52009-06-06 18:51:58 +0000595 self.is_committing = is_committing
tandrii@chromium.org37b07a72016-04-29 16:42:28 +0000596 self.gerrit = gerrit_obj
tandrii@chromium.org57bafac2016-04-28 05:09:03 +0000597 self.dry_run = dry_run
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000598
Edward Lesmes8e282792018-04-03 18:50:29 -0400599 self.parallel = parallel
600 self.thread_pool = thread_pool or ThreadPool()
601
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000602 # We expose various modules and functions as attributes of the input_api
603 # so that presubmit scripts don't have to import them.
Takeshi Yoshino07a6bea2017-08-02 02:44:06 +0900604 self.ast = ast
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000605 self.basename = os.path.basename
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000606 self.cpplint = cpplint
dcheng091b7db2016-06-16 01:27:51 -0700607 self.fnmatch = fnmatch
Yoshisato Yanagisawa04600b42019-03-15 03:03:41 +0000608 self.gclient_paths = gclient_paths
Yoshisato Yanagisawa57dd17b2019-03-22 09:10:29 +0000609 # TODO(yyanagisawa): stop exposing this when python3 become default.
610 # Since python3's tempfile has TemporaryDirectory, we do not need this.
611 self.temporary_directory = gclient_utils.temporary_directory
dpranke@chromium.org17cc2442012-10-17 21:12:09 +0000612 self.glob = glob.glob
maruel@chromium.orgfb11c7b2010-03-18 18:22:14 +0000613 self.json = json
maruel@chromium.org6fba34d2011-06-02 13:45:12 +0000614 self.logging = logging.getLogger('PRESUBMIT')
maruel@chromium.org2b5ce562011-03-31 16:15:44 +0000615 self.os_listdir = os.listdir
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000616 self.os_path = os.path
pgervais@chromium.orgbd0cace2014-10-02 23:23:46 +0000617 self.os_stat = os.stat
Yoshisato Yanagisawa406de132018-06-29 05:43:25 +0000618 self.os_walk = os.walk
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000619 self.re = re
620 self.subprocess = subprocess
Edward Lemurb9830242019-10-30 22:19:20 +0000621 self.sys = sys
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000622 self.tempfile = tempfile
dpranke@chromium.org0d1bdea2011-03-24 22:54:38 +0000623 self.time = time
maruel@chromium.org1487d532009-06-06 00:22:57 +0000624 self.unittest = unittest
Edward Lemurb9830242019-10-30 22:19:20 +0000625 if sys.version_info.major == 2:
626 self.urllib2 = urllib2
Edward Lemur16af3562019-10-17 22:11:33 +0000627 self.urllib_request = urllib_request
628 self.urllib_error = urllib_error
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000629
Robert Iannucci50258932018-03-19 10:30:59 -0700630 self.is_windows = sys.platform == 'win32'
631
Edward Lemurb9646622019-10-25 20:57:35 +0000632 # Set python_executable to 'vpython' in order to allow scripts in other
633 # repos (e.g. src.git) to automatically pick up that repo's .vpython file,
634 # instead of inheriting the one in depot_tools.
635 self.python_executable = 'vpython'
maruel@chromium.orgc0b22972009-06-25 16:19:14 +0000636 self.environ = os.environ
637
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000638 # InputApi.platform is the platform you're currently running on.
639 self.platform = sys.platform
640
iannucci@chromium.org0af3bb32015-06-12 20:44:35 +0000641 self.cpu_count = multiprocessing.cpu_count()
642
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000643 # The local path of the currently-being-processed presubmit script.
maruel@chromium.org3d235242009-05-15 12:40:48 +0000644 self._current_presubmit_path = os.path.dirname(presubmit_path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000645
646 # We carry the canned checks so presubmit scripts can easily use them.
647 self.canned_checks = presubmit_canned_checks
648
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +0100649 # Temporary files we must manually remove at the end of a run.
650 self._named_temporary_files = []
Jochen Eisinger72606f82017-04-04 10:44:18 +0200651
Edward Lesmes48492322021-03-17 16:47:09 +0000652 # TODO(dpranke): figure out a list of all approved owners for a repo
653 # in order to be able to handle wildcard OWNERS files?
654 self.owners_client = owners_client.DepotToolsClient(
655 change.RepositoryRoot(), change.UpstreamBranch(), os_path=self.os_path)
Edward Lesmes9ce03f82021-01-12 20:13:31 +0000656 self.owners_db = owners_db.Database(
657 change.RepositoryRoot(), fopen=open, os_path=self.os_path)
Jochen Eisinger76f5fc62017-04-07 16:27:46 +0200658 self.owners_finder = owners_finder.OwnersFinder
maruel@chromium.org899e1c12011-04-07 17:03:18 +0000659 self.verbose = verbose
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000660 self.Command = CommandData
dpranke@chromium.org2a009622011-03-01 02:43:31 +0000661
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000662 # Replace <hash_map> and <hash_set> as headers that need to be included
Edward Lemura5799e32020-01-17 19:26:51 +0000663 # with 'base/containers/hash_tables.h' instead.
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000664 # Access to a protected member _XX of a client class
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800665 # pylint: disable=protected-access
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000666 self.cpplint._re_pattern_templates = [
danakj@chromium.org18278522013-06-11 22:42:32 +0000667 (a, b, 'base/containers/hash_tables.h')
enne@chromium.orge72c5f52013-04-16 00:36:40 +0000668 if header in ('<hash_map>', '<hash_set>') else (a, b, header)
669 for (a, b, header) in cpplint._re_pattern_templates
670 ]
671
Edward Lemurecc27072020-01-06 16:42:34 +0000672 def SetTimeout(self, timeout):
673 self.thread_pool.timeout = timeout
674
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000675 def PresubmitLocalPath(self):
676 """Returns the local path of the presubmit script currently being run.
677
678 This is useful if you don't want to hard-code absolute paths in the
679 presubmit script. For example, It can be used to find another file
680 relative to the PRESUBMIT.py script, so the whole tree can be branched and
681 the presubmit script still works, without editing its content.
682 """
maruel@chromium.org3d235242009-05-15 12:40:48 +0000683 return self._current_presubmit_path
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000684
agable0b65e732016-11-22 09:25:46 -0800685 def AffectedFiles(self, include_deletes=True, file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000686 """Same as input_api.change.AffectedFiles() except only lists files
687 (and optionally directories) in the same directory as the current presubmit
Bruce Dawson7a0b07a2020-04-23 17:14:40 +0000688 script, or subdirectories thereof. Note that files are listed using the OS
689 path separator, so backslashes are used as separators on Windows.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000690 """
Edward Lemura5799e32020-01-17 19:26:51 +0000691 dir_with_slash = normpath('%s/' % self.PresubmitLocalPath())
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000692 if len(dir_with_slash) == 1:
693 dir_with_slash = ''
sail@chromium.org5538e022011-05-12 17:53:16 +0000694
Edward Lemurb9830242019-10-30 22:19:20 +0000695 return list(filter(
maruel@chromium.org4661e0c2009-06-04 00:45:26 +0000696 lambda x: normpath(x.AbsoluteLocalPath()).startswith(dir_with_slash),
Edward Lemurb9830242019-10-30 22:19:20 +0000697 self.change.AffectedFiles(include_deletes, file_filter)))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000698
agable0b65e732016-11-22 09:25:46 -0800699 def LocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000700 """Returns local paths of input_api.AffectedFiles()."""
agable0b65e732016-11-22 09:25:46 -0800701 paths = [af.LocalPath() for af in self.AffectedFiles()]
Edward Lemura5799e32020-01-17 19:26:51 +0000702 logging.debug('LocalPaths: %s', paths)
pgervais@chromium.org2f64f782014-04-25 00:12:33 +0000703 return paths
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000704
agable0b65e732016-11-22 09:25:46 -0800705 def AbsoluteLocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000706 """Returns absolute local paths of input_api.AffectedFiles()."""
agable0b65e732016-11-22 09:25:46 -0800707 return [af.AbsoluteLocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000708
John Budorick16162372018-04-18 10:39:53 -0700709 def AffectedTestableFiles(self, include_deletes=None, **kwargs):
agable0b65e732016-11-22 09:25:46 -0800710 """Same as input_api.change.AffectedTestableFiles() except only lists files
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000711 in the same directory as the current presubmit script, or subdirectories
712 thereof.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000713 """
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000714 if include_deletes is not None:
Edward Lemura5799e32020-01-17 19:26:51 +0000715 warn('AffectedTestableFiles(include_deletes=%s)'
716 ' is deprecated and ignored' % str(include_deletes),
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000717 category=DeprecationWarning,
718 stacklevel=2)
Edward Lemurb9830242019-10-30 22:19:20 +0000719 return list(filter(
720 lambda x: x.IsTestableFile(),
721 self.AffectedFiles(include_deletes=False, **kwargs)))
agable0b65e732016-11-22 09:25:46 -0800722
723 def AffectedTextFiles(self, include_deletes=None):
724 """An alias to AffectedTestableFiles for backwards compatibility."""
725 return self.AffectedTestableFiles(include_deletes=include_deletes)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000726
Josip Sokcevic8c955952021-02-01 21:32:57 +0000727 def FilterSourceFile(self,
728 affected_file,
729 files_to_check=None,
730 files_to_skip=None,
731 allow_list=None,
732 block_list=None):
Edward Lemura5799e32020-01-17 19:26:51 +0000733 """Filters out files that aren't considered 'source file'.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000734
local_bot64021412020-07-08 21:05:39 +0000735 If files_to_check or files_to_skip is None, InputApi.DEFAULT_FILES_TO_CHECK
736 and InputApi.DEFAULT_FILES_TO_SKIP is used respectively.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000737
738 The lists will be compiled as regular expression and
739 AffectedFile.LocalPath() needs to pass both list.
740
741 Note: Copy-paste this function to suit your needs or use a lambda function.
742 """
local_bot64021412020-07-08 21:05:39 +0000743 if files_to_check is None:
744 files_to_check = self.DEFAULT_FILES_TO_CHECK
745 if files_to_skip is None:
746 files_to_skip = self.DEFAULT_FILES_TO_SKIP
local_bot30f774e2020-06-25 18:23:34 +0000747
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000748 def Find(affected_file, items):
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000749 local_path = affected_file.LocalPath()
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000750 for item in items:
maruel@chromium.orgdf1595a2009-06-11 02:00:13 +0000751 if self.re.match(item, local_path):
maruel@chromium.org3410d912009-06-09 20:56:16 +0000752 return True
753 return False
local_bot64021412020-07-08 21:05:39 +0000754 return (Find(affected_file, files_to_check) and
755 not Find(affected_file, files_to_skip))
maruel@chromium.org3410d912009-06-09 20:56:16 +0000756
757 def AffectedSourceFiles(self, source_file):
agable0b65e732016-11-22 09:25:46 -0800758 """Filter the list of AffectedTestableFiles by the function source_file.
maruel@chromium.org3410d912009-06-09 20:56:16 +0000759
760 If source_file is None, InputApi.FilterSourceFile() is used.
761 """
762 if not source_file:
763 source_file = self.FilterSourceFile
Edward Lemurb9830242019-10-30 22:19:20 +0000764 return list(filter(source_file, self.AffectedTestableFiles()))
maruel@chromium.org3410d912009-06-09 20:56:16 +0000765
766 def RightHandSideLines(self, source_file_filter=None):
Edward Lemura5799e32020-01-17 19:26:51 +0000767 """An iterator over all text lines in 'new' version of changed files.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000768
769 Only lists lines from new or modified text files in the change that are
770 contained by the directory of the currently executing presubmit script.
771
772 This is useful for doing line-by-line regex checks, like checking for
773 trailing whitespace.
774
775 Yields:
776 a 3 tuple:
777 the AffectedFile instance of the current file;
778 integer line number (1-based); and
779 the contents of the line as a string.
maruel@chromium.org1487d532009-06-06 00:22:57 +0000780
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000781 Note: The carriage return (LF or CR) is stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000782 """
maruel@chromium.org3410d912009-06-09 20:56:16 +0000783 files = self.AffectedSourceFiles(source_file_filter)
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +0000784 return _RightHandSideLinesImpl(files)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000785
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000786 def ReadFile(self, file_item, mode='r'):
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000787 """Reads an arbitrary file.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000788
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000789 Deny reading anything outside the repository.
790 """
maruel@chromium.orge3608df2009-11-10 20:22:57 +0000791 if isinstance(file_item, AffectedFile):
792 file_item = file_item.AbsoluteLocalPath()
793 if not file_item.startswith(self.change.RepositoryRoot()):
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000794 raise IOError('Access outside the repository root is denied.')
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000795 return gclient_utils.FileRead(file_item, mode)
maruel@chromium.org44a17ad2009-06-08 14:14:35 +0000796
Raphael Kubo da Costaf2d16152017-11-10 18:07:58 +0100797 def CreateTemporaryFile(self, **kwargs):
798 """Returns a named temporary file that must be removed with a call to
799 RemoveTemporaryFiles().
800
801 All keyword arguments are forwarded to tempfile.NamedTemporaryFile(),
802 except for |delete|, which is always set to False.
803
804 Presubmit checks that need to create a temporary file and pass it for
805 reading should use this function instead of NamedTemporaryFile(), as
806 Windows fails to open a file that is already open for writing.
807
808 with input_api.CreateTemporaryFile() as f:
809 f.write('xyz')
810 f.close()
811 input_api.subprocess.check_output(['script-that', '--reads-from',
812 f.name])
813
814
815 Note that callers of CreateTemporaryFile() should not worry about removing
816 any temporary file; this is done transparently by the presubmit handling
817 code.
818 """
819 if 'delete' in kwargs:
820 # Prevent users from passing |delete|; we take care of file deletion
821 # ourselves and this prevents unintuitive error messages when we pass
822 # delete=False and 'delete' is also in kwargs.
823 raise TypeError('CreateTemporaryFile() does not take a "delete" '
824 'argument, file deletion is handled automatically by '
825 'the same presubmit_support code that creates InputApi '
826 'objects.')
827 temp_file = self.tempfile.NamedTemporaryFile(delete=False, **kwargs)
828 self._named_temporary_files.append(temp_file.name)
829 return temp_file
830
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000831 @property
832 def tbr(self):
833 """Returns if a change is TBR'ed."""
Jeremy Romandce22502017-06-20 15:37:29 -0400834 return 'TBR' in self.change.tags or self.change.TBRsFromDescription()
maruel@chromium.orgcc73ad62011-07-06 17:39:26 +0000835
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +0000836 def RunTests(self, tests_mix, parallel=True):
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000837 tests = []
838 msgs = []
839 for t in tests_mix:
Edward Lesmes8e282792018-04-03 18:50:29 -0400840 if isinstance(t, OutputApi.PresubmitResult) and t:
ilevy@chromium.orgbc117312013-04-20 03:57:56 +0000841 msgs.append(t)
842 else:
843 assert issubclass(t.message, _PresubmitResult)
844 tests.append(t)
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +0000845 if self.verbose:
846 t.info = _PresubmitNotifyResult
Edward Lemur1037c742018-05-01 18:56:04 -0400847 if not t.kwargs.get('cwd'):
848 t.kwargs['cwd'] = self.PresubmitLocalPath()
Edward Lesmes8e282792018-04-03 18:50:29 -0400849 self.thread_pool.AddTests(tests, parallel)
Edward Lemur21000eb2019-05-24 23:25:58 +0000850 # When self.parallel is True (i.e. --parallel is passed as an option)
851 # RunTests doesn't actually run tests. It adds them to a ThreadPool that
852 # will run all tests once all PRESUBMIT files are processed.
853 # Otherwise, it will run them and return the results.
854 if not self.parallel:
Edward Lesmes8e282792018-04-03 18:50:29 -0400855 msgs.extend(self.thread_pool.RunAsync())
856 return msgs
scottmg86099d72016-09-01 09:16:51 -0700857
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000858
nick@chromium.orgff526192013-06-10 19:30:26 +0000859class _DiffCache(object):
860 """Caches diffs retrieved from a particular SCM."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000861 def __init__(self, upstream=None):
862 """Stores the upstream revision against which all diffs will be computed."""
863 self._upstream = upstream
nick@chromium.orgff526192013-06-10 19:30:26 +0000864
865 def GetDiff(self, path, local_root):
866 """Get the diff for a particular path."""
867 raise NotImplementedError()
868
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700869 def GetOldContents(self, path, local_root):
870 """Get the old version for a particular path."""
871 raise NotImplementedError()
872
nick@chromium.orgff526192013-06-10 19:30:26 +0000873
nick@chromium.orgff526192013-06-10 19:30:26 +0000874class _GitDiffCache(_DiffCache):
875 """DiffCache implementation for git; gets all file diffs at once."""
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000876 def __init__(self, upstream):
877 super(_GitDiffCache, self).__init__(upstream=upstream)
nick@chromium.orgff526192013-06-10 19:30:26 +0000878 self._diffs_by_file = None
879
880 def GetDiff(self, path, local_root):
881 if not self._diffs_by_file:
882 # Compute a single diff for all files and parse the output; should
883 # with git this is much faster than computing one diff for each file.
884 diffs = {}
885
886 # Don't specify any filenames below, because there are command line length
887 # limits on some platforms and GenerateDiff would fail.
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000888 unified_diff = scm.GIT.GenerateDiff(local_root, files=[], full_move=True,
889 branch=self._upstream)
nick@chromium.orgff526192013-06-10 19:30:26 +0000890
891 # This regex matches the path twice, separated by a space. Note that
892 # filename itself may contain spaces.
893 file_marker = re.compile('^diff --git (?P<filename>.*) (?P=filename)$')
894 current_diff = []
895 keep_line_endings = True
896 for x in unified_diff.splitlines(keep_line_endings):
897 match = file_marker.match(x)
898 if match:
899 # Marks the start of a new per-file section.
900 diffs[match.group('filename')] = current_diff = [x]
901 elif x.startswith('diff --git'):
902 raise PresubmitFailure('Unexpected diff line: %s' % x)
903 else:
904 current_diff.append(x)
905
906 self._diffs_by_file = dict(
907 (normpath(path), ''.join(diff)) for path, diff in diffs.items())
908
909 if path not in self._diffs_by_file:
910 raise PresubmitFailure(
911 'Unified diff did not contain entry for file %s' % path)
912
913 return self._diffs_by_file[path]
914
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700915 def GetOldContents(self, path, local_root):
916 return scm.GIT.GetOldContents(local_root, path, branch=self._upstream)
917
nick@chromium.orgff526192013-06-10 19:30:26 +0000918
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000919class AffectedFile(object):
920 """Representation of a file in a change."""
nick@chromium.orgff526192013-06-10 19:30:26 +0000921
922 DIFF_CACHE = _DiffCache
923
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +0000924 # Method could be a function
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800925 # pylint: disable=no-self-use
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000926 def __init__(self, path, action, repository_root, diff_cache):
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000927 self._path = path
928 self._action = action
maruel@chromium.org4ff922a2009-06-12 20:20:19 +0000929 self._local_root = repository_root
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000930 self._is_directory = None
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000931 self._cached_changed_contents = None
932 self._cached_new_contents = None
agable@chromium.orgea84ef12014-04-30 19:55:12 +0000933 self._diff_cache = diff_cache
tobiasjs2836bcf2016-08-16 04:08:16 -0700934 logging.debug('%s(%s)', self.__class__.__name__, self._path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000935
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000936 def LocalPath(self):
937 """Returns the path of this file on the local disk relative to client root.
Andrew Grieve92b8b992017-11-02 09:42:24 -0400938
939 This should be used for error messages but not for accessing files,
940 because presubmit checks are run with CWD=PresubmitLocalPath() (which is
941 often != client root).
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000942 """
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000943 return normpath(self._path)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000944
945 def AbsoluteLocalPath(self):
946 """Returns the absolute path of this file on the local disk.
947 """
chase@chromium.org8e416c82009-10-06 04:30:44 +0000948 return os.path.abspath(os.path.join(self._local_root, self.LocalPath()))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000949
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000950 def Action(self):
951 """Returns the action on this opened file, e.g. A, M, D, etc."""
maruel@chromium.org15bdffa2009-05-29 11:16:29 +0000952 return self._action
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000953
agable0b65e732016-11-22 09:25:46 -0800954 def IsTestableFile(self):
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000955 """Returns True if the file is a text file and not a binary file.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +0000956
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +0000957 Deleted files are not text file."""
maruel@chromium.org1e08c002009-05-28 19:09:33 +0000958 raise NotImplementedError() # Implement when needed
959
agable0b65e732016-11-22 09:25:46 -0800960 def IsTextFile(self):
961 """An alias to IsTestableFile for backwards compatibility."""
962 return self.IsTestableFile()
963
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700964 def OldContents(self):
965 """Returns an iterator over the lines in the old version of file.
966
Daniel Cheng2da34fe2017-03-21 20:42:12 -0700967 The old version is the file before any modifications in the user's
Edward Lemura5799e32020-01-17 19:26:51 +0000968 workspace, i.e. the 'left hand side'.
Daniel Cheng7a1f04d2017-03-21 19:12:31 -0700969
970 Contents will be empty if the file is a directory or does not exist.
971 Note: The carriage returns (LF or CR) are stripped off.
972 """
973 return self._diff_cache.GetOldContents(self.LocalPath(),
974 self._local_root).splitlines()
975
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000976 def NewContents(self):
977 """Returns an iterator over the lines in the new version of file.
978
Edward Lemura5799e32020-01-17 19:26:51 +0000979 The new version is the file in the user's workspace, i.e. the 'right hand
980 side'.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000981
982 Contents will be empty if the file is a directory or does not exist.
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000983 Note: The carriage returns (LF or CR) are stripped off.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000984 """
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000985 if self._cached_new_contents is None:
986 self._cached_new_contents = []
agable0b65e732016-11-22 09:25:46 -0800987 try:
988 self._cached_new_contents = gclient_utils.FileRead(
989 self.AbsoluteLocalPath(), 'rU').splitlines()
990 except IOError:
991 pass # File not found? That's fine; maybe it was deleted.
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +0000992 return self._cached_new_contents[:]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000993
maruel@chromium.orgab05d582011-02-09 23:41:22 +0000994 def ChangedContents(self):
995 """Returns a list of tuples (line number, line text) of all new lines.
996
997 This relies on the scm diff output describing each changed code section
998 with a line of the form
999
1000 ^@@ <old line num>,<old size> <new line num>,<new size> @@$
1001 """
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +00001002 if self._cached_changed_contents is not None:
1003 return self._cached_changed_contents[:]
1004 self._cached_changed_contents = []
maruel@chromium.orgab05d582011-02-09 23:41:22 +00001005 line_num = 0
1006
maruel@chromium.orgab05d582011-02-09 23:41:22 +00001007 for line in self.GenerateScmDiff().splitlines():
Edward Lemurac5c55f2020-02-29 00:17:16 +00001008 m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
1009 if m:
1010 line_num = int(m.groups(1)[0])
maruel@chromium.orgab05d582011-02-09 23:41:22 +00001011 continue
1012 if line.startswith('+') and not line.startswith('++'):
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +00001013 self._cached_changed_contents.append((line_num, line[1:]))
maruel@chromium.orgab05d582011-02-09 23:41:22 +00001014 if not line.startswith('-'):
1015 line_num += 1
nick@chromium.org2a3ab7e2011-04-27 22:06:27 +00001016 return self._cached_changed_contents[:]
maruel@chromium.orgab05d582011-02-09 23:41:22 +00001017
maruel@chromium.org5de13972009-06-10 18:16:06 +00001018 def __str__(self):
1019 return self.LocalPath()
1020
maruel@chromium.orgab05d582011-02-09 23:41:22 +00001021 def GenerateScmDiff(self):
nick@chromium.orgff526192013-06-10 19:30:26 +00001022 return self._diff_cache.GetDiff(self.LocalPath(), self._local_root)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001023
maruel@chromium.org58407af2011-04-12 23:15:57 +00001024
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001025class GitAffectedFile(AffectedFile):
1026 """Representation of a file in a change out of a git checkout."""
maruel@chromium.orgb17b55b2010-11-03 14:42:37 +00001027 # Method 'NNN' is abstract in class 'NNN' but is not overridden
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -08001028 # pylint: disable=abstract-method
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001029
nick@chromium.orgff526192013-06-10 19:30:26 +00001030 DIFF_CACHE = _GitDiffCache
1031
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001032 def __init__(self, *args, **kwargs):
1033 AffectedFile.__init__(self, *args, **kwargs)
1034 self._server_path = None
agable0b65e732016-11-22 09:25:46 -08001035 self._is_testable_file = None
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001036
agable0b65e732016-11-22 09:25:46 -08001037 def IsTestableFile(self):
1038 if self._is_testable_file is None:
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001039 if self.Action() == 'D':
agable0b65e732016-11-22 09:25:46 -08001040 # A deleted file is not testable.
1041 self._is_testable_file = False
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001042 else:
agable0b65e732016-11-22 09:25:46 -08001043 self._is_testable_file = os.path.isfile(self.AbsoluteLocalPath())
1044 return self._is_testable_file
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001045
maruel@chromium.orgc1938752011-04-12 23:11:13 +00001046
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001047class Change(object):
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001048 """Describe a change.
1049
1050 Used directly by the presubmit scripts to query the current change being
1051 tested.
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +00001052
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001053 Instance members:
nick@chromium.orgff526192013-06-10 19:30:26 +00001054 tags: Dictionary of KEY=VALUE pairs found in the change description.
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001055 self.KEY: equivalent to tags['KEY']
1056 """
1057
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001058 _AFFECTED_FILES = AffectedFile
1059
Edward Lemura5799e32020-01-17 19:26:51 +00001060 # Matches key/value (or 'tag') lines in changelist descriptions.
maruel@chromium.org428342a2011-11-10 15:46:33 +00001061 TAG_LINE_RE = re.compile(
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00001062 '^[ \t]*(?P<key>[A-Z][A-Z_0-9]*)[ \t]*=[ \t]*(?P<value>.*?)[ \t]*$')
maruel@chromium.orgc1938752011-04-12 23:11:13 +00001063 scm = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001064
maruel@chromium.org58407af2011-04-12 23:15:57 +00001065 def __init__(
agable@chromium.orgea84ef12014-04-30 19:55:12 +00001066 self, name, description, local_root, files, issue, patchset, author,
1067 upstream=None):
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001068 if files is None:
1069 files = []
1070 self._name = name
chase@chromium.org8e416c82009-10-06 04:30:44 +00001071 # Convert root into an absolute path.
1072 self._local_root = os.path.abspath(local_root)
agable@chromium.orgea84ef12014-04-30 19:55:12 +00001073 self._upstream = upstream
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001074 self.issue = issue
1075 self.patchset = patchset
maruel@chromium.org58407af2011-04-12 23:15:57 +00001076 self.author_email = author
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001077
isherman@chromium.orgb5cded62014-03-25 17:47:57 +00001078 self._full_description = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001079 self.tags = {}
isherman@chromium.orgb5cded62014-03-25 17:47:57 +00001080 self._description_without_tags = ''
1081 self.SetDescriptionText(description)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001082
maruel@chromium.orge085d812011-10-10 19:49:15 +00001083 assert all(
1084 (isinstance(f, (list, tuple)) and len(f) == 2) for f in files), files
1085
agable@chromium.orgea84ef12014-04-30 19:55:12 +00001086 diff_cache = self._AFFECTED_FILES.DIFF_CACHE(self._upstream)
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001087 self._affected_files = [
nick@chromium.orgff526192013-06-10 19:30:26 +00001088 self._AFFECTED_FILES(path, action.strip(), self._local_root, diff_cache)
1089 for action, path in files
maruel@chromium.orgdbbeedc2009-05-22 20:26:17 +00001090 ]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001091
Edward Lesmes9ce03f82021-01-12 20:13:31 +00001092 def UpstreamBranch(self):
1093 """Returns the upstream branch for the change."""
1094 return self._upstream
1095
maruel@chromium.org92022ec2009-06-11 01:59:28 +00001096 def Name(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001097 """Returns the change name."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001098 return self._name
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001099
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001100 def DescriptionText(self):
1101 """Returns the user-entered changelist description, minus tags.
1102
Edward Lemura5799e32020-01-17 19:26:51 +00001103 Any line in the user-provided description starting with e.g. 'FOO='
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001104 (whitespace permitted before and around) is considered a tag line. Such
1105 lines are stripped out of the description this function returns.
1106 """
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001107 return self._description_without_tags
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001108
1109 def FullDescriptionText(self):
1110 """Returns the complete changelist description including tags."""
maruel@chromium.org6ebe68a2009-05-27 23:43:40 +00001111 return self._full_description
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001112
isherman@chromium.orgb5cded62014-03-25 17:47:57 +00001113 def SetDescriptionText(self, description):
1114 """Sets the full description text (including tags) to |description|.
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001115
isherman@chromium.orgb5cded62014-03-25 17:47:57 +00001116 Also updates the list of tags."""
1117 self._full_description = description
1118
1119 # From the description text, build up a dictionary of key/value pairs
Edward Lemura5799e32020-01-17 19:26:51 +00001120 # plus the description minus all key/value or 'tag' lines.
isherman@chromium.orgb5cded62014-03-25 17:47:57 +00001121 description_without_tags = []
1122 self.tags = {}
1123 for line in self._full_description.splitlines():
1124 m = self.TAG_LINE_RE.match(line)
1125 if m:
1126 self.tags[m.group('key')] = m.group('value')
1127 else:
1128 description_without_tags.append(line)
1129
1130 # Change back to text and remove whitespace at end.
1131 self._description_without_tags = (
1132 '\n'.join(description_without_tags).rstrip())
1133
Edward Lemur69bb8be2020-02-03 20:37:38 +00001134 def AddDescriptionFooter(self, key, value):
1135 """Adds the given footer to the change description.
1136
1137 Args:
1138 key: A string with the key for the git footer. It must conform to
1139 the git footers format (i.e. 'List-Of-Tokens') and will be case
1140 normalized so that each token is title-cased.
1141 value: A string with the value for the git footer.
1142 """
1143 description = git_footers.add_footer(
1144 self.FullDescriptionText(), git_footers.normalize_name(key), value)
1145 self.SetDescriptionText(description)
1146
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001147 def RepositoryRoot(self):
maruel@chromium.org92022ec2009-06-11 01:59:28 +00001148 """Returns the repository (checkout) root directory for this change,
1149 as an absolute path.
1150 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001151 return self._local_root
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001152
1153 def __getattr__(self, attr):
maruel@chromium.org92022ec2009-06-11 01:59:28 +00001154 """Return tags directly as attributes on the object."""
Edward Lemura5799e32020-01-17 19:26:51 +00001155 if not re.match(r'^[A-Z_]*$', attr):
maruel@chromium.org92022ec2009-06-11 01:59:28 +00001156 raise AttributeError(self, attr)
maruel@chromium.orge1a524f2009-05-27 14:43:46 +00001157 return self.tags.get(attr)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001158
Edward Lemur69bb8be2020-02-03 20:37:38 +00001159 def GitFootersFromDescription(self):
1160 """Return the git footers present in the description.
1161
1162 Returns:
1163 footers: A dict of {footer: [values]} containing a multimap of the footers
1164 in the change description.
1165 """
1166 return git_footers.parse_footers(self.FullDescriptionText())
1167
Aaron Gablefc03e672017-05-15 14:09:42 -07001168 def BugsFromDescription(self):
1169 """Returns all bugs referenced in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -07001170 tags = [b.strip() for b in self.tags.get('BUG', '').split(',') if b.strip()]
Caleb Rouleauc0546b92019-02-22 06:12:57 +00001171 footers = []
Edward Lemur69bb8be2020-02-03 20:37:38 +00001172 parsed = self.GitFootersFromDescription()
Dan Beam62954042019-10-03 21:20:33 +00001173 unsplit_footers = parsed.get('Bug', []) + parsed.get('Fixed', [])
Caleb Rouleauc0546b92019-02-22 06:12:57 +00001174 for unsplit_footer in unsplit_footers:
1175 footers += [b.strip() for b in unsplit_footer.split(',')]
Aaron Gable12ef5012017-05-15 14:29:00 -07001176 return sorted(set(tags + footers))
Aaron Gablefc03e672017-05-15 14:09:42 -07001177
1178 def ReviewersFromDescription(self):
1179 """Returns all reviewers listed in the commit description."""
Edward Lemura5799e32020-01-17 19:26:51 +00001180 # We don't support a 'R:' git-footer for reviewers; that is in metadata.
Aaron Gable12ef5012017-05-15 14:29:00 -07001181 tags = [r.strip() for r in self.tags.get('R', '').split(',') if r.strip()]
1182 return sorted(set(tags))
Aaron Gablefc03e672017-05-15 14:09:42 -07001183
1184 def TBRsFromDescription(self):
1185 """Returns all TBR reviewers listed in the commit description."""
Aaron Gable12ef5012017-05-15 14:29:00 -07001186 tags = [r.strip() for r in self.tags.get('TBR', '').split(',') if r.strip()]
Aaron Gable6e7ddb62020-05-27 22:23:29 +00001187 # TODO(crbug.com/839208): Remove support for 'Tbr:' when TBRs are
1188 # programmatically determined by self-CR+1s.
Edward Lemur69bb8be2020-02-03 20:37:38 +00001189 footers = self.GitFootersFromDescription().get('Tbr', [])
Aaron Gable12ef5012017-05-15 14:29:00 -07001190 return sorted(set(tags + footers))
Aaron Gablefc03e672017-05-15 14:09:42 -07001191
Aaron Gable6e7ddb62020-05-27 22:23:29 +00001192 # TODO(crbug.com/753425): Delete these once we're sure they're unused.
Aaron Gablefc03e672017-05-15 14:09:42 -07001193 @property
1194 def BUG(self):
1195 return ','.join(self.BugsFromDescription())
1196 @property
1197 def R(self):
1198 return ','.join(self.ReviewersFromDescription())
1199 @property
1200 def TBR(self):
1201 return ','.join(self.TBRsFromDescription())
1202
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001203 def AllFiles(self, root=None):
1204 """List all files under source control in the repo."""
1205 raise NotImplementedError()
1206
agable0b65e732016-11-22 09:25:46 -08001207 def AffectedFiles(self, include_deletes=True, file_filter=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001208 """Returns a list of AffectedFile instances for all files in the change.
1209
1210 Args:
1211 include_deletes: If false, deleted files will be filtered out.
sail@chromium.org5538e022011-05-12 17:53:16 +00001212 file_filter: An additional filter to apply.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001213
1214 Returns:
1215 [AffectedFile(path, action), AffectedFile(path, action)]
1216 """
Edward Lemurb9830242019-10-30 22:19:20 +00001217 affected = list(filter(file_filter, self._affected_files))
sail@chromium.org5538e022011-05-12 17:53:16 +00001218
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001219 if include_deletes:
1220 return affected
Edward Lemurb9830242019-10-30 22:19:20 +00001221 return list(filter(lambda x: x.Action() != 'D', affected))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001222
John Budorick16162372018-04-18 10:39:53 -07001223 def AffectedTestableFiles(self, include_deletes=None, **kwargs):
maruel@chromium.org77c4f0f2009-05-29 18:53:04 +00001224 """Return a list of the existing text files in a change."""
1225 if include_deletes is not None:
Edward Lemura5799e32020-01-17 19:26:51 +00001226 warn('AffectedTeestableFiles(include_deletes=%s)'
1227 ' is deprecated and ignored' % str(include_deletes),
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +00001228 category=DeprecationWarning,
1229 stacklevel=2)
Edward Lemurb9830242019-10-30 22:19:20 +00001230 return list(filter(
1231 lambda x: x.IsTestableFile(),
1232 self.AffectedFiles(include_deletes=False, **kwargs)))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001233
agable0b65e732016-11-22 09:25:46 -08001234 def AffectedTextFiles(self, include_deletes=None):
1235 """An alias to AffectedTestableFiles for backwards compatibility."""
1236 return self.AffectedTestableFiles(include_deletes=include_deletes)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001237
agable0b65e732016-11-22 09:25:46 -08001238 def LocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001239 """Convenience function."""
agable0b65e732016-11-22 09:25:46 -08001240 return [af.LocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001241
agable0b65e732016-11-22 09:25:46 -08001242 def AbsoluteLocalPaths(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001243 """Convenience function."""
agable0b65e732016-11-22 09:25:46 -08001244 return [af.AbsoluteLocalPath() for af in self.AffectedFiles()]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001245
1246 def RightHandSideLines(self):
Edward Lemura5799e32020-01-17 19:26:51 +00001247 """An iterator over all text lines in 'new' version of changed files.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001248
1249 Lists lines from new or modified text files in the change.
1250
1251 This is useful for doing line-by-line regex checks, like checking for
1252 trailing whitespace.
1253
1254 Yields:
1255 a 3 tuple:
1256 the AffectedFile instance of the current file;
1257 integer line number (1-based); and
1258 the contents of the line as a string.
1259 """
maruel@chromium.orgcb2985f2010-11-03 14:08:31 +00001260 return _RightHandSideLinesImpl(
1261 x for x in self.AffectedFiles(include_deletes=False)
agable0b65e732016-11-22 09:25:46 -08001262 if x.IsTestableFile())
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001263
Jochen Eisingerd0573ec2017-04-13 10:55:06 +02001264 def OriginalOwnersFiles(self):
1265 """A map from path names of affected OWNERS files to their old content."""
1266 def owners_file_filter(f):
1267 return 'OWNERS' in os.path.split(f.LocalPath())[1]
1268 files = self.AffectedFiles(file_filter=owners_file_filter)
1269 return dict([(f.LocalPath(), f.OldContents()) for f in files])
1270
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001271
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001272class GitChange(Change):
1273 _AFFECTED_FILES = GitAffectedFile
maruel@chromium.orgc1938752011-04-12 23:11:13 +00001274 scm = 'git'
thestig@chromium.orgda8cddd2009-08-13 00:25:55 +00001275
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001276 def AllFiles(self, root=None):
1277 """List all files under source control in the repo."""
1278 root = root or self.RepositoryRoot()
1279 return subprocess.check_output(
Aaron Gable7817f022017-12-12 09:43:17 -08001280 ['git', '-c', 'core.quotePath=false', 'ls-files', '--', '.'],
1281 cwd=root).splitlines()
agable@chromium.org40a3d0b2014-05-15 01:59:16 +00001282
maruel@chromium.orgc70a2202009-06-17 12:55:10 +00001283
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001284def ListRelevantPresubmitFiles(files, root):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001285 """Finds all presubmit files that apply to a given set of source files.
1286
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001287 If inherit-review-settings-ok is present right under root, looks for
1288 PRESUBMIT.py in directories enclosing root.
1289
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001290 Args:
1291 files: An iterable container containing file paths.
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001292 root: Path where to stop searching.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001293
1294 Return:
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001295 List of absolute paths of the existing PRESUBMIT.py scripts.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001296 """
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001297 files = [normpath(os.path.join(root, f)) for f in files]
1298
1299 # List all the individual directories containing files.
1300 directories = set([os.path.dirname(f) for f in files])
1301
1302 # Ignore root if inherit-review-settings-ok is present.
1303 if os.path.isfile(os.path.join(root, 'inherit-review-settings-ok')):
1304 root = None
1305
1306 # Collect all unique directories that may contain PRESUBMIT.py.
1307 candidates = set()
1308 for directory in directories:
1309 while True:
1310 if directory in candidates:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001311 break
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001312 candidates.add(directory)
1313 if directory == root:
maruel@chromium.org4661e0c2009-06-04 00:45:26 +00001314 break
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001315 parent_dir = os.path.dirname(directory)
1316 if parent_dir == directory:
1317 # We hit the system root directory.
1318 break
1319 directory = parent_dir
1320
1321 # Look for PRESUBMIT.py in all candidate directories.
1322 results = []
1323 for directory in sorted(list(candidates)):
tobiasjsff061c02016-08-17 03:23:57 -07001324 try:
1325 for f in os.listdir(directory):
1326 p = os.path.join(directory, f)
1327 if os.path.isfile(p) and re.match(
1328 r'PRESUBMIT.*\.py$', f) and not f.startswith('PRESUBMIT_test'):
1329 results.append(p)
1330 except OSError:
1331 pass
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001332
tobiasjs2836bcf2016-08-16 04:08:16 -07001333 logging.debug('Presubmit files: %s', ','.join(results))
maruel@chromium.orgb1901a62010-06-16 00:18:47 +00001334 return results
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001335
1336
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001337class GetTryMastersExecuter(object):
1338 @staticmethod
1339 def ExecPresubmitScript(script_text, presubmit_path, project, change):
1340 """Executes GetPreferredTryMasters() from a single presubmit script.
1341
1342 Args:
1343 script_text: The text of the presubmit script.
1344 presubmit_path: Project script to run.
1345 project: Project name to pass to presubmit script for bot selection.
1346
1347 Return:
1348 A map of try masters to map of builders to set of tests.
1349 """
1350 context = {}
1351 try:
Raul Tambre09e64b42019-05-14 01:57:22 +00001352 exec(compile(script_text, 'PRESUBMIT.py', 'exec', dont_inherit=True),
1353 context)
Raul Tambre7c938462019-05-24 16:35:35 +00001354 except Exception as e:
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001355 raise PresubmitFailure('"%s" had an exception.\n%s'
1356 % (presubmit_path, e))
1357
1358 function_name = 'GetPreferredTryMasters'
1359 if function_name not in context:
1360 return {}
1361 get_preferred_try_masters = context[function_name]
1362 if not len(inspect.getargspec(get_preferred_try_masters)[0]) == 2:
1363 raise PresubmitFailure(
1364 'Expected function "GetPreferredTryMasters" to take two arguments.')
1365 return get_preferred_try_masters(project, change)
1366
1367
rmistry@google.com5626a922015-02-26 14:03:30 +00001368class GetPostUploadExecuter(object):
1369 @staticmethod
Edward Lemur016a0872020-02-04 22:13:28 +00001370 def ExecPresubmitScript(script_text, presubmit_path, gerrit_obj, change):
rmistry@google.com5626a922015-02-26 14:03:30 +00001371 """Executes PostUploadHook() from a single presubmit script.
1372
1373 Args:
1374 script_text: The text of the presubmit script.
1375 presubmit_path: Project script to run.
Edward Lemur016a0872020-02-04 22:13:28 +00001376 gerrit_obj: The GerritAccessor object.
rmistry@google.com5626a922015-02-26 14:03:30 +00001377 change: The Change object.
1378
1379 Return:
1380 A list of results objects.
1381 """
1382 context = {}
1383 try:
Raul Tambre09e64b42019-05-14 01:57:22 +00001384 exec(compile(script_text, 'PRESUBMIT.py', 'exec', dont_inherit=True),
1385 context)
Raul Tambre7c938462019-05-24 16:35:35 +00001386 except Exception as e:
rmistry@google.com5626a922015-02-26 14:03:30 +00001387 raise PresubmitFailure('"%s" had an exception.\n%s'
1388 % (presubmit_path, e))
1389
1390 function_name = 'PostUploadHook'
1391 if function_name not in context:
1392 return {}
1393 post_upload_hook = context[function_name]
1394 if not len(inspect.getargspec(post_upload_hook)[0]) == 3:
1395 raise PresubmitFailure(
1396 'Expected function "PostUploadHook" to take three arguments.')
Edward Lemur016a0872020-02-04 22:13:28 +00001397 return post_upload_hook(gerrit_obj, change, OutputApi(False))
rmistry@google.com5626a922015-02-26 14:03:30 +00001398
1399
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001400def _MergeMasters(masters1, masters2):
1401 """Merges two master maps. Merges also the tests of each builder."""
1402 result = {}
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00001403 for (master, builders) in itertools.chain(masters1.items(),
1404 masters2.items()):
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001405 new_builders = result.setdefault(master, {})
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00001406 for (builder, tests) in builders.items():
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001407 new_builders.setdefault(builder, set([])).update(tests)
1408 return result
1409
1410
1411def DoGetTryMasters(change,
1412 changed_files,
1413 repository_root,
1414 default_presubmit,
1415 project,
1416 verbose,
1417 output_stream):
1418 """Get the list of try masters from the presubmit scripts.
1419
1420 Args:
1421 changed_files: List of modified files.
1422 repository_root: The repository root.
1423 default_presubmit: A default presubmit script to execute in any case.
1424 project: Optional name of a project used in selecting trybots.
1425 verbose: Prints debug info.
1426 output_stream: A stream to write debug output to.
1427
1428 Return:
1429 Map of try masters to map of builders to set of tests.
1430 """
1431 presubmit_files = ListRelevantPresubmitFiles(changed_files, repository_root)
1432 if not presubmit_files and verbose:
Edward Lemura5799e32020-01-17 19:26:51 +00001433 output_stream.write('Warning, no PRESUBMIT.py found.\n')
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001434 results = {}
1435 executer = GetTryMastersExecuter()
1436
1437 if default_presubmit:
1438 if verbose:
Edward Lemura5799e32020-01-17 19:26:51 +00001439 output_stream.write('Running default presubmit script.\n')
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001440 fake_path = os.path.join(repository_root, 'PRESUBMIT.py')
1441 results = _MergeMasters(results, executer.ExecPresubmitScript(
1442 default_presubmit, fake_path, project, change))
1443 for filename in presubmit_files:
1444 filename = os.path.abspath(filename)
1445 if verbose:
Edward Lemura5799e32020-01-17 19:26:51 +00001446 output_stream.write('Running %s\n' % filename)
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001447 # Accept CRLF presubmit script.
1448 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1449 results = _MergeMasters(results, executer.ExecPresubmitScript(
1450 presubmit_script, filename, project, change))
1451
1452 # Make sets to lists again for later JSON serialization.
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00001453 for builders in results.values():
machenbach@chromium.org58a69cb2014-03-01 02:08:29 +00001454 for builder in builders:
1455 builders[builder] = list(builders[builder])
1456
1457 if results and verbose:
1458 output_stream.write('%s\n' % str(results))
1459 return results
1460
1461
rmistry@google.com5626a922015-02-26 14:03:30 +00001462def DoPostUploadExecuter(change,
Edward Lemur016a0872020-02-04 22:13:28 +00001463 gerrit_obj,
Edward Lemur6eb1d322020-02-27 22:20:15 +00001464 verbose):
rmistry@google.com5626a922015-02-26 14:03:30 +00001465 """Execute the post upload hook.
1466
1467 Args:
1468 change: The Change object.
Edward Lemur016a0872020-02-04 22:13:28 +00001469 gerrit_obj: The GerritAccessor object.
rmistry@google.com5626a922015-02-26 14:03:30 +00001470 verbose: Prints debug info.
rmistry@google.com5626a922015-02-26 14:03:30 +00001471 """
1472 presubmit_files = ListRelevantPresubmitFiles(
Edward Lemur6eb1d322020-02-27 22:20:15 +00001473 change.LocalPaths(), change.RepositoryRoot())
rmistry@google.com5626a922015-02-26 14:03:30 +00001474 if not presubmit_files and verbose:
Edward Lemur6eb1d322020-02-27 22:20:15 +00001475 sys.stdout.write('Warning, no PRESUBMIT.py found.\n')
rmistry@google.com5626a922015-02-26 14:03:30 +00001476 results = []
1477 executer = GetPostUploadExecuter()
1478 # The root presubmit file should be executed after the ones in subdirectories.
1479 # i.e. the specific post upload hooks should run before the general ones.
1480 # Thus, reverse the order provided by ListRelevantPresubmitFiles.
1481 presubmit_files.reverse()
1482
1483 for filename in presubmit_files:
1484 filename = os.path.abspath(filename)
1485 if verbose:
Edward Lemur6eb1d322020-02-27 22:20:15 +00001486 sys.stdout.write('Running %s\n' % filename)
rmistry@google.com5626a922015-02-26 14:03:30 +00001487 # Accept CRLF presubmit script.
1488 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1489 results.extend(executer.ExecPresubmitScript(
Edward Lemur016a0872020-02-04 22:13:28 +00001490 presubmit_script, filename, gerrit_obj, change))
rmistry@google.com5626a922015-02-26 14:03:30 +00001491
Edward Lemur6eb1d322020-02-27 22:20:15 +00001492 if not results:
1493 return 0
1494
1495 sys.stdout.write('\n')
1496 sys.stdout.write('** Post Upload Hook Messages **\n')
1497
1498 exit_code = 0
1499 for result in results:
1500 if result.fatal:
1501 exit_code = 1
1502 result.handle()
1503 sys.stdout.write('\n')
1504
1505 return exit_code
rmistry@google.com5626a922015-02-26 14:03:30 +00001506
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001507class PresubmitExecuter(object):
Saagar Sanghavi531d9922020-08-10 20:14:01 +00001508 def __init__(self, change, committing, verbose, gerrit_obj, dry_run=None,
Edward Lesmeseb1bd622021-03-01 19:54:07 +00001509 thread_pool=None, parallel=False):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001510 """
1511 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001512 change: The Change object.
agable92bec4f2016-08-24 09:27:27 -07001513 committing: True if 'git cl land' is running, False if 'git cl upload' is.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001514 gerrit_obj: provides basic Gerrit codereview functionality.
1515 dry_run: if true, some Checks will be skipped.
Edward Lesmes8e282792018-04-03 18:50:29 -04001516 parallel: if true, all tests reported via input_api.RunTests for all
1517 PRESUBMIT files will be run in parallel.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001518 """
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001519 self.change = change
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001520 self.committing = committing
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001521 self.gerrit = gerrit_obj
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001522 self.verbose = verbose
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001523 self.dry_run = dry_run
Daniel Cheng7227d212017-11-17 08:12:37 -08001524 self.more_cc = []
Edward Lesmes8e282792018-04-03 18:50:29 -04001525 self.thread_pool = thread_pool
1526 self.parallel = parallel
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001527
1528 def ExecPresubmitScript(self, script_text, presubmit_path):
1529 """Executes a single presubmit script.
1530
1531 Args:
1532 script_text: The text of the presubmit script.
1533 presubmit_path: The path to the presubmit file (this will be reported via
1534 input_api.PresubmitLocalPath()).
1535
1536 Return:
1537 A list of result objects, empty if no problems.
1538 """
Saagar Sanghavi03b15132020-08-10 16:43:41 +00001539
chase@chromium.org8e416c82009-10-06 04:30:44 +00001540 # Change to the presubmit file's directory to support local imports.
1541 main_path = os.getcwd()
Saagar Sanghavi98b332f2020-07-31 17:19:15 +00001542 presubmit_dir = os.path.dirname(presubmit_path)
1543 os.chdir(presubmit_dir)
chase@chromium.org8e416c82009-10-06 04:30:44 +00001544
1545 # Load the presubmit script into context.
dpranke@chromium.org970c5222011-03-12 00:32:24 +00001546 input_api = InputApi(self.change, presubmit_path, self.committing,
Aaron Gable668c1d82018-04-03 10:19:16 -07001547 self.verbose, gerrit_obj=self.gerrit,
Edward Lesmes8e282792018-04-03 18:50:29 -04001548 dry_run=self.dry_run, thread_pool=self.thread_pool,
1549 parallel=self.parallel)
Daniel Cheng7227d212017-11-17 08:12:37 -08001550 output_api = OutputApi(self.committing)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001551 context = {}
Saagar Sanghavi03b15132020-08-10 16:43:41 +00001552
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001553 try:
Raul Tambre09e64b42019-05-14 01:57:22 +00001554 exec(compile(script_text, 'PRESUBMIT.py', 'exec', dont_inherit=True),
1555 context)
Raul Tambre7c938462019-05-24 16:35:35 +00001556 except Exception as e:
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001557 raise PresubmitFailure('"%s" had an exception.\n%s' % (presubmit_path, e))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001558
Saagar Sanghavi03b15132020-08-10 16:43:41 +00001559 context['__args'] = (input_api, output_api)
Ben Pastene8351dc12020-08-06 05:01:35 +00001560
Saagar Sanghavi531d9922020-08-10 20:14:01 +00001561 # Get path of presubmit directory relative to repository root.
Saagar Sanghavi03b15132020-08-10 16:43:41 +00001562 # Always use forward slashes, so that path is same in *nix and Windows
1563 root = input_api.change.RepositoryRoot()
1564 rel_path = os.path.relpath(presubmit_dir, root)
1565 rel_path = rel_path.replace(os.path.sep, '/')
Ben Pastene8351dc12020-08-06 05:01:35 +00001566
Saagar Sanghavi531d9922020-08-10 20:14:01 +00001567 # Get the URL of git remote origin and use it to identify host and project
Edward Lesmeseb1bd622021-03-01 19:54:07 +00001568 host = project = ''
1569 if self.gerrit:
1570 host = self.gerrit.host or ''
1571 project = self.gerrit.project or ''
Saagar Sanghavi531d9922020-08-10 20:14:01 +00001572
1573 # Prefix for test names
1574 prefix = 'presubmit:%s/%s:%s/' % (host, project, rel_path)
1575
Saagar Sanghavi03b15132020-08-10 16:43:41 +00001576 # Perform all the desired presubmit checks.
1577 results = []
Ben Pastene8351dc12020-08-06 05:01:35 +00001578
Saagar Sanghavi03b15132020-08-10 16:43:41 +00001579 try:
Scott Leecc2fe9b2020-11-19 19:38:06 +00001580 version = [
1581 int(x) for x in context.get('PRESUBMIT_VERSION', '0.0.0').split('.')
1582 ]
Saagar Sanghavi03b15132020-08-10 16:43:41 +00001583
Scott Leecc2fe9b2020-11-19 19:38:06 +00001584 with rdb_wrapper.client(prefix) as sink:
1585 if version >= [2, 0, 0]:
1586 for function_name in context:
1587 if not function_name.startswith('Check'):
1588 continue
1589 if function_name.endswith('Commit') and not self.committing:
1590 continue
1591 if function_name.endswith('Upload') and self.committing:
1592 continue
Saagar Sanghavi03b15132020-08-10 16:43:41 +00001593 logging.debug('Running %s in %s', function_name, presubmit_path)
1594 results.extend(
Scott Leecc2fe9b2020-11-19 19:38:06 +00001595 self._run_check_function(function_name, context, sink))
1596 logging.debug('Running %s done.', function_name)
1597 self.more_cc.extend(output_api.more_cc)
1598
1599 else: # Old format
1600 if self.committing:
1601 function_name = 'CheckChangeOnCommit'
1602 else:
1603 function_name = 'CheckChangeOnUpload'
1604 if function_name in context:
1605 logging.debug('Running %s in %s', function_name, presubmit_path)
1606 results.extend(
1607 self._run_check_function(function_name, context, sink))
Saagar Sanghavi03b15132020-08-10 16:43:41 +00001608 logging.debug('Running %s done.', function_name)
1609 self.more_cc.extend(output_api.more_cc)
1610
1611 finally:
1612 for f in input_api._named_temporary_files:
1613 os.remove(f)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001614
chase@chromium.org8e416c82009-10-06 04:30:44 +00001615 # Return the process to the original working directory.
1616 os.chdir(main_path)
Saagar Sanghavi03b15132020-08-10 16:43:41 +00001617 return results
1618
Scott Leecc2fe9b2020-11-19 19:38:06 +00001619 def _run_check_function(self, function_name, context, sink=None):
1620 """Evaluates and returns the result of a given presubmit function.
1621
1622 If sink is given, the result of the presubmit function will be reported
1623 to the ResultSink.
Saagar Sanghavi03b15132020-08-10 16:43:41 +00001624
1625 Args:
Scott Leecc2fe9b2020-11-19 19:38:06 +00001626 function_name: the name of the presubmit function to evaluate
Saagar Sanghavi03b15132020-08-10 16:43:41 +00001627 context: a context dictionary in which the function will be evaluated
Scott Leecc2fe9b2020-11-19 19:38:06 +00001628 sink: an instance of ResultSink. None, by default.
1629 Returns:
1630 the result of the presubmit function call.
1631 """
1632 start_time = time_time()
1633 try:
Saagar Sanghavi03b15132020-08-10 16:43:41 +00001634 result = eval(function_name + '(*__args)', context)
1635 self._check_result_type(result)
Scott Leecc2fe9b2020-11-19 19:38:06 +00001636 except:
1637 if sink:
1638 elapsed_time = time_time() - start_time
1639 sink.report(function_name, rdb_wrapper.STATUS_FAIL, elapsed_time)
1640 raise
1641
1642 if sink:
1643 elapsed_time = time_time() - start_time
1644 status = rdb_wrapper.STATUS_PASS
1645 if any(r.fatal for r in result):
1646 status = rdb_wrapper.STATUS_FAIL
1647 sink.report(function_name, status, elapsed_time)
1648
1649 return result
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001650
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00001651 def _check_result_type(self, result):
1652 """Helper function which ensures result is a list, and all elements are
1653 instances of OutputApi.PresubmitResult"""
1654 if not isinstance(result, (tuple, list)):
1655 raise PresubmitFailure('Presubmit functions must return a tuple or list')
1656 if not all(isinstance(res, OutputApi.PresubmitResult) for res in result):
1657 raise PresubmitFailure(
1658 'All presubmit results must be of types derived from '
1659 'output_api.PresubmitResult')
1660
1661
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001662def DoPresubmitChecks(change,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001663 committing,
1664 verbose,
maruel@chromium.orgb0dfd352009-06-10 14:12:54 +00001665 default_presubmit,
dpranke@chromium.org970c5222011-03-12 00:32:24 +00001666 may_prompt,
Aaron Gable668c1d82018-04-03 10:19:16 -07001667 gerrit_obj,
Edward Lesmes8e282792018-04-03 18:50:29 -04001668 dry_run=None,
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001669 parallel=False,
Edward Lesmeseb1bd622021-03-01 19:54:07 +00001670 json_output=None):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001671 """Runs all presubmit checks that apply to the files in the change.
1672
1673 This finds all PRESUBMIT.py files in directories enclosing the files in the
1674 change (up to the repository root) and calls the relevant entrypoint function
1675 depending on whether the change is being committed or uploaded.
1676
1677 Prints errors, warnings and notifications. Prompts the user for warnings
1678 when needed.
1679
1680 Args:
maruel@chromium.org4ff922a2009-06-12 20:20:19 +00001681 change: The Change object.
agable92bec4f2016-08-24 09:27:27 -07001682 committing: True if 'git cl land' is running, False if 'git cl upload' is.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001683 verbose: Prints debug info.
maruel@chromium.org0ff1fab2009-05-22 13:08:15 +00001684 default_presubmit: A default presubmit script to execute in any case.
Quinten Yearsley516fe7f2016-12-14 11:50:18 -08001685 may_prompt: Enable (y/n) questions on warning or error. If False,
1686 any questions are answered with yes by default.
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001687 gerrit_obj: provides basic Gerrit codereview functionality.
tandrii@chromium.org57bafac2016-04-28 05:09:03 +00001688 dry_run: if true, some Checks will be skipped.
Edward Lesmes8e282792018-04-03 18:50:29 -04001689 parallel: if true, all tests specified by input_api.RunTests in all
1690 PRESUBMIT files will be run in parallel.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001691
1692 Return:
Edward Lemur6eb1d322020-02-27 22:20:15 +00001693 1 if presubmit checks failed or 0 otherwise.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001694 """
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001695 old_environ = os.environ
1696 try:
1697 # Make sure python subprocesses won't generate .pyc files.
1698 os.environ = os.environ.copy()
Edward Lemurb9830242019-10-30 22:19:20 +00001699 os.environ['PYTHONDONTWRITEBYTECODE'] = '1'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001700
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001701 if committing:
Edward Lemur6eb1d322020-02-27 22:20:15 +00001702 sys.stdout.write('Running presubmit commit checks ...\n')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001703 else:
Edward Lemur6eb1d322020-02-27 22:20:15 +00001704 sys.stdout.write('Running presubmit upload checks ...\n')
Edward Lemurecc27072020-01-06 16:42:34 +00001705 start_time = time_time()
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001706 presubmit_files = ListRelevantPresubmitFiles(
agable0b65e732016-11-22 09:25:46 -08001707 change.AbsoluteLocalPaths(), change.RepositoryRoot())
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001708 if not presubmit_files and verbose:
Edward Lemur6eb1d322020-02-27 22:20:15 +00001709 sys.stdout.write('Warning, no PRESUBMIT.py found.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001710 results = []
Edward Lesmes8e282792018-04-03 18:50:29 -04001711 thread_pool = ThreadPool()
Edward Lemur7e3c67f2018-07-20 20:52:49 +00001712 executer = PresubmitExecuter(change, committing, verbose, gerrit_obj,
Edward Lesmeseb1bd622021-03-01 19:54:07 +00001713 dry_run, thread_pool, parallel)
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001714 if default_presubmit:
1715 if verbose:
Edward Lemur6eb1d322020-02-27 22:20:15 +00001716 sys.stdout.write('Running default presubmit script.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001717 fake_path = os.path.join(change.RepositoryRoot(), 'PRESUBMIT.py')
1718 results += executer.ExecPresubmitScript(default_presubmit, fake_path)
1719 for filename in presubmit_files:
1720 filename = os.path.abspath(filename)
1721 if verbose:
Edward Lemur6eb1d322020-02-27 22:20:15 +00001722 sys.stdout.write('Running %s\n' % filename)
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001723 # Accept CRLF presubmit script.
1724 presubmit_script = gclient_utils.FileRead(filename, 'rU')
1725 results += executer.ExecPresubmitScript(presubmit_script, filename)
Edward Lesmes8e282792018-04-03 18:50:29 -04001726 results += thread_pool.RunAsync()
1727
Edward Lemur6eb1d322020-02-27 22:20:15 +00001728 messages = {}
1729 should_prompt = False
1730 presubmits_failed = False
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001731 for result in results:
1732 if result.fatal:
Edward Lemur6eb1d322020-02-27 22:20:15 +00001733 presubmits_failed = True
1734 messages.setdefault('ERRORS', []).append(result)
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001735 elif result.should_prompt:
Edward Lemur6eb1d322020-02-27 22:20:15 +00001736 should_prompt = True
1737 messages.setdefault('Warnings', []).append(result)
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001738 else:
Edward Lemur6eb1d322020-02-27 22:20:15 +00001739 messages.setdefault('Messages', []).append(result)
pam@chromium.orged9a0832009-09-09 22:48:55 +00001740
Edward Lemur6eb1d322020-02-27 22:20:15 +00001741 sys.stdout.write('\n')
1742 for name, items in messages.items():
1743 sys.stdout.write('** Presubmit %s **\n' % name)
1744 for item in items:
1745 item.handle()
1746 sys.stdout.write('\n')
pam@chromium.orged9a0832009-09-09 22:48:55 +00001747
Edward Lemurecc27072020-01-06 16:42:34 +00001748 total_time = time_time() - start_time
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001749 if total_time > 1.0:
Edward Lemur6eb1d322020-02-27 22:20:15 +00001750 sys.stdout.write(
1751 'Presubmit checks took %.1fs to calculate.\n\n' % total_time)
maruel@chromium.orgce8e46b2009-06-26 22:31:51 +00001752
Edward Lemur6eb1d322020-02-27 22:20:15 +00001753 if not should_prompt and not presubmits_failed:
1754 sys.stdout.write('Presubmit checks passed.\n')
1755 elif should_prompt:
1756 sys.stdout.write('There were presubmit warnings. ')
Quinten Yearsley516fe7f2016-12-14 11:50:18 -08001757 if may_prompt:
Edward Lemur6eb1d322020-02-27 22:20:15 +00001758 presubmits_failed = not prompt_should_continue(
1759 'Are you sure you wish to continue? (y/N): ')
Garrett Beatyacb807e2020-08-28 18:17:24 +00001760 else:
1761 sys.stdout.write('\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001762
Edward Lemur1dc66e12020-02-21 21:36:34 +00001763 if json_output:
1764 # Write the presubmit results to json output
1765 presubmit_results = {
1766 'errors': [
Edward Lemur6eb1d322020-02-27 22:20:15 +00001767 error.json_format()
1768 for error in messages.get('ERRORS', [])
Edward Lemur1dc66e12020-02-21 21:36:34 +00001769 ],
1770 'notifications': [
Edward Lemur6eb1d322020-02-27 22:20:15 +00001771 notification.json_format()
1772 for notification in messages.get('Messages', [])
Edward Lemur1dc66e12020-02-21 21:36:34 +00001773 ],
1774 'warnings': [
Edward Lemur6eb1d322020-02-27 22:20:15 +00001775 warning.json_format()
1776 for warning in messages.get('Warnings', [])
Edward Lemur1dc66e12020-02-21 21:36:34 +00001777 ],
Edward Lemur6eb1d322020-02-27 22:20:15 +00001778 'more_cc': executer.more_cc,
Edward Lemur1dc66e12020-02-21 21:36:34 +00001779 }
1780
1781 gclient_utils.FileWrite(
1782 json_output, json.dumps(presubmit_results, sort_keys=True))
1783
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001784 global _ASKED_FOR_FEEDBACK
1785 # Ask for feedback one time out of 5.
1786 if (len(results) and random.randint(0, 4) == 0 and not _ASKED_FOR_FEEDBACK):
Edward Lemur6eb1d322020-02-27 22:20:15 +00001787 sys.stdout.write(
maruel@chromium.org1ce8e662014-01-14 15:23:00 +00001788 'Was the presubmit check useful? If not, run "git cl presubmit -v"\n'
1789 'to figure out which PRESUBMIT.py was run, then run git blame\n'
1790 'on the file to figure out who to ask for help.\n')
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001791 _ASKED_FOR_FEEDBACK = True
Edward Lemur6eb1d322020-02-27 22:20:15 +00001792
1793 return 1 if presubmits_failed else 0
maruel@chromium.orgea7c8552011-04-18 14:12:07 +00001794 finally:
1795 os.environ = old_environ
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001796
1797
Edward Lemur50984a62020-02-06 18:10:18 +00001798def _scan_sub_dirs(mask, recursive):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001799 if not recursive:
pgervais@chromium.orge57b09d2014-05-07 00:58:13 +00001800 return [x for x in glob.glob(mask) if x not in ('.svn', '.git')]
Lei Zhang9611c4c2017-04-04 01:41:56 -07001801
1802 results = []
1803 for root, dirs, files in os.walk('.'):
1804 if '.svn' in dirs:
1805 dirs.remove('.svn')
1806 if '.git' in dirs:
1807 dirs.remove('.git')
1808 for name in files:
1809 if fnmatch.fnmatch(name, mask):
1810 results.append(os.path.join(root, name))
1811 return results
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001812
1813
Edward Lemur50984a62020-02-06 18:10:18 +00001814def _parse_files(args, recursive):
tobiasjs2836bcf2016-08-16 04:08:16 -07001815 logging.debug('Searching for %s', args)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001816 files = []
1817 for arg in args:
Edward Lemur50984a62020-02-06 18:10:18 +00001818 files.extend([('M', f) for f in _scan_sub_dirs(arg, recursive)])
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001819 return files
1820
1821
Edward Lemur50984a62020-02-06 18:10:18 +00001822def _parse_change(parser, options):
1823 """Process change options.
1824
1825 Args:
1826 parser: The parser used to parse the arguments from command line.
1827 options: The arguments parsed from command line.
1828 Returns:
1829 A GitChange if the change root is a git repository, or a Change otherwise.
1830 """
1831 if options.files and options.all_files:
1832 parser.error('<files> cannot be specified when --all-files is set.')
1833
Edward Lesmes44ea3ff2020-02-05 00:14:30 +00001834 change_scm = scm.determine_scm(options.root)
Edward Lemur50984a62020-02-06 18:10:18 +00001835 if change_scm != 'git' and not options.files:
1836 parser.error('<files> is not optional for unversioned directories.')
1837
1838 if options.files:
1839 change_files = _parse_files(options.files, options.recursive)
1840 elif options.all_files:
1841 change_files = [('M', f) for f in scm.GIT.GetAllFiles(options.root)]
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001842 else:
Edward Lemur50984a62020-02-06 18:10:18 +00001843 change_files = scm.GIT.CaptureStatus(
Edward Lemur7f6dec02020-02-06 20:23:58 +00001844 options.root, options.upstream or None)
Edward Lemur50984a62020-02-06 18:10:18 +00001845
1846 logging.info('Found %d file(s).', len(change_files))
1847
1848 change_class = GitChange if change_scm == 'git' else Change
1849 return change_class(
1850 options.name,
1851 options.description,
1852 options.root,
1853 change_files,
1854 options.issue,
1855 options.patchset,
1856 options.author,
1857 upstream=options.upstream)
1858
1859
1860def _parse_gerrit_options(parser, options):
1861 """Process gerrit options.
1862
1863 SIDE EFFECTS: Modifies options.author and options.description from Gerrit if
1864 options.gerrit_fetch is set.
1865
1866 Args:
1867 parser: The parser used to parse the arguments from command line.
1868 options: The arguments parsed from command line.
1869 Returns:
Stephen Martinisfb09de22021-02-25 03:41:13 +00001870 A GerritAccessor object if options.gerrit_url is set, or None otherwise.
Edward Lemur50984a62020-02-06 18:10:18 +00001871 """
1872 gerrit_obj = None
Stephen Martinisfb09de22021-02-25 03:41:13 +00001873 if options.gerrit_url:
Edward Lesmeseb1bd622021-03-01 19:54:07 +00001874 gerrit_obj = GerritAccessor(
1875 url=options.gerrit_url,
1876 project=options.gerrit_project,
1877 branch=options.gerrit_branch)
Edward Lemur50984a62020-02-06 18:10:18 +00001878
1879 if not options.gerrit_fetch:
1880 return gerrit_obj
1881
1882 if not options.gerrit_url or not options.issue or not options.patchset:
1883 parser.error(
1884 '--gerrit_fetch requires --gerrit_url, --issue and --patchset.')
1885
1886 options.author = gerrit_obj.GetChangeOwner(options.issue)
1887 options.description = gerrit_obj.GetChangeDescription(
1888 options.issue, options.patchset)
1889
1890 logging.info('Got author: "%s"', options.author)
1891 logging.info('Got description: """\n%s\n"""', options.description)
1892
1893 return gerrit_obj
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +00001894
1895
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001896@contextlib.contextmanager
1897def canned_check_filter(method_names):
1898 filtered = {}
1899 try:
1900 for method_name in method_names:
1901 if not hasattr(presubmit_canned_checks, method_name):
Gavin Make6a62332020-12-04 21:57:10 +00001902 logging.warning('Skipping unknown "canned" check %s' % method_name)
Aaron Gableecee74c2018-04-02 15:13:08 -07001903 continue
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001904 filtered[method_name] = getattr(presubmit_canned_checks, method_name)
1905 setattr(presubmit_canned_checks, method_name, lambda *_a, **_kw: [])
1906 yield
1907 finally:
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00001908 for name, method in filtered.items():
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001909 setattr(presubmit_canned_checks, name, method)
1910
maruel@chromium.orgffeb2f32013-12-03 13:55:22 +00001911
sbc@chromium.org013731e2015-02-26 18:28:43 +00001912def main(argv=None):
Edward Lemura5799e32020-01-17 19:26:51 +00001913 parser = argparse.ArgumentParser(usage='%(prog)s [options] <files...>')
1914 hooks = parser.add_mutually_exclusive_group()
1915 hooks.add_argument('-c', '--commit', action='store_true',
1916 help='Use commit instead of upload checks.')
1917 hooks.add_argument('-u', '--upload', action='store_false', dest='commit',
1918 help='Use upload instead of commit checks.')
Edward Lemur75526302020-02-27 22:31:05 +00001919 hooks.add_argument('--post_upload', action='store_true',
1920 help='Run post-upload commit hooks.')
Edward Lemura5799e32020-01-17 19:26:51 +00001921 parser.add_argument('-r', '--recursive', action='store_true',
1922 help='Act recursively.')
1923 parser.add_argument('-v', '--verbose', action='count', default=0,
1924 help='Use 2 times for more debug info.')
1925 parser.add_argument('--name', default='no name')
1926 parser.add_argument('--author')
Edward Lemur227d5102020-02-25 23:45:35 +00001927 desc = parser.add_mutually_exclusive_group()
1928 desc.add_argument('--description', default='', help='The change description.')
1929 desc.add_argument('--description_file',
1930 help='File to read change description from.')
Edward Lemura5799e32020-01-17 19:26:51 +00001931 parser.add_argument('--issue', type=int, default=0)
1932 parser.add_argument('--patchset', type=int, default=0)
1933 parser.add_argument('--root', default=os.getcwd(),
1934 help='Search for PRESUBMIT.py up to this directory. '
1935 'If inherit-review-settings-ok is present in this '
1936 'directory, parent directories up to the root file '
1937 'system directories will also be searched.')
1938 parser.add_argument('--upstream',
1939 help='Git only: the base ref or upstream branch against '
1940 'which the diff should be computed.')
1941 parser.add_argument('--default_presubmit')
1942 parser.add_argument('--may_prompt', action='store_true', default=False)
1943 parser.add_argument('--skip_canned', action='append', default=[],
1944 help='A list of checks to skip which appear in '
1945 'presubmit_canned_checks. Can be provided multiple times '
1946 'to skip multiple canned checks.')
1947 parser.add_argument('--dry_run', action='store_true', help=argparse.SUPPRESS)
1948 parser.add_argument('--gerrit_url', help=argparse.SUPPRESS)
Edward Lesmeseb1bd622021-03-01 19:54:07 +00001949 parser.add_argument('--gerrit_project', help=argparse.SUPPRESS)
1950 parser.add_argument('--gerrit_branch', help=argparse.SUPPRESS)
Edward Lemura5799e32020-01-17 19:26:51 +00001951 parser.add_argument('--gerrit_fetch', action='store_true',
1952 help=argparse.SUPPRESS)
1953 parser.add_argument('--parallel', action='store_true',
1954 help='Run all tests specified by input_api.RunTests in '
1955 'all PRESUBMIT files in parallel.')
1956 parser.add_argument('--json_output',
1957 help='Write presubmit errors to json output.')
Edward Lemur1dc66e12020-02-21 21:36:34 +00001958 parser.add_argument('--all_files', action='store_true',
Edward Lemur50984a62020-02-06 18:10:18 +00001959 help='Mark all files under source control as modified.')
Edward Lemura5799e32020-01-17 19:26:51 +00001960 parser.add_argument('files', nargs='*',
1961 help='List of files to be marked as modified when '
1962 'executing presubmit or post-upload hooks. fnmatch '
1963 'wildcards can also be used.')
Edward Lemura5799e32020-01-17 19:26:51 +00001964 options = parser.parse_args(argv)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001965
Erik Staabcca5c492020-04-16 17:40:07 +00001966 log_level = logging.ERROR
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001967 if options.verbose >= 2:
Erik Staabcca5c492020-04-16 17:40:07 +00001968 log_level = logging.DEBUG
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001969 elif options.verbose:
Erik Staabcca5c492020-04-16 17:40:07 +00001970 log_level = logging.INFO
1971 log_format = ('[%(levelname).1s%(asctime)s %(process)d %(thread)d '
1972 '%(filename)s] %(message)s')
1973 logging.basicConfig(format=log_format, level=log_level)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001974
Edward Lemur227d5102020-02-25 23:45:35 +00001975 if options.description_file:
1976 options.description = gclient_utils.FileRead(options.description_file)
Edward Lemur50984a62020-02-06 18:10:18 +00001977 gerrit_obj = _parse_gerrit_options(parser, options)
1978 change = _parse_change(parser, options)
pgervais@chromium.org92c30092014-04-15 00:30:37 +00001979
maruel@chromium.org899e1c12011-04-07 17:03:18 +00001980 try:
Edward Lemur75526302020-02-27 22:31:05 +00001981 if options.post_upload:
1982 return DoPostUploadExecuter(
1983 change,
1984 gerrit_obj,
1985 options.verbose)
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001986 with canned_check_filter(options.skip_canned):
Edward Lemur6eb1d322020-02-27 22:20:15 +00001987 return DoPresubmitChecks(
Edward Lemur50984a62020-02-06 18:10:18 +00001988 change,
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001989 options.commit,
1990 options.verbose,
iannucci@chromium.org8a4a2bc2013-03-08 08:13:20 +00001991 options.default_presubmit,
1992 options.may_prompt,
tandrii@chromium.org37b07a72016-04-29 16:42:28 +00001993 gerrit_obj,
Edward Lesmes8e282792018-04-03 18:50:29 -04001994 options.dry_run,
Debrian Figueroadd2737e2019-06-21 23:50:13 +00001995 options.parallel,
Edward Lesmeseb1bd622021-03-01 19:54:07 +00001996 options.json_output)
Raul Tambre7c938462019-05-24 16:35:35 +00001997 except PresubmitFailure as e:
Raul Tambre80ee78e2019-05-06 22:41:05 +00001998 print(e, file=sys.stderr)
1999 print('Maybe your depot_tools is out of date?', file=sys.stderr)
maruel@chromium.org899e1c12011-04-07 17:03:18 +00002000 return 2
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002001
2002
2003if __name__ == '__main__':
maruel@chromium.org35625c72011-03-23 17:34:02 +00002004 fix_encoding.fix_encoding()
sbc@chromium.org013731e2015-02-26 18:28:43 +00002005 try:
2006 sys.exit(main())
2007 except KeyboardInterrupt:
2008 sys.stderr.write('interrupted\n')
sergiybf8a3b382016-07-05 11:21:30 -07002009 sys.exit(2)